@@ -37,13 +37,15 @@ defmodule Lightning.WebhookRateLimiter do
37
37
capacity = Keyword . fetch! ( opts , :capacity )
38
38
refill = Keyword . fetch! ( opts , :refill_per_second )
39
39
40
- { :ok , % { table: :ets . new ( :table , [ :set ] ) , capacity: capacity , refill : refill } }
40
+ { :ok , % { table: :ets . new ( :table , [ :set ] ) , capacity: capacity , refill_per_second : refill } }
41
41
end
42
42
43
- def check_rate ( bucket , cost \\ 1 , name \\ __MODULE__ ) do
43
+ def check_rate ( bucket , opts \\ [ ] ) do
44
+ name = Keyword . get ( opts , :name , __MODULE__ )
45
+
44
46
name
45
47
|> via_tuple ( )
46
- |> GenServer . call ( { :check_rate , bucket , cost } )
48
+ |> GenServer . call ( { :check_rate , bucket , opts } )
47
49
end
48
50
49
51
def inspect_table ( name \\ __MODULE__ ) do
@@ -53,8 +55,8 @@ defmodule Lightning.WebhookRateLimiter do
53
55
end
54
56
55
57
@ impl true
56
- def handle_call ( { :check_rate , bucket , cost } , _from , state ) do
57
- { :reply , do_check_rate ( state , bucket , cost ) , state }
58
+ def handle_call ( { :check_rate , bucket , opts } , _from , state ) do
59
+ { :reply , do_check_rate ( state , bucket , opts ) , state }
58
60
end
59
61
60
62
@ impl true
@@ -74,21 +76,19 @@ defmodule Lightning.WebhookRateLimiter do
74
76
{ :stop , :normal , state }
75
77
end
76
78
77
- def do_check_rate (
78
- % { table: table , capacity: capacity , refill: refill_per_sec } ,
79
- bucket ,
80
- cost
81
- ) do
79
+ def do_check_rate ( % { table: table } = config , bucket , opts ) do
82
80
now = System . monotonic_time ( :millisecond )
81
+ capacity = opts [ :capacity ] || config [ :capacity ]
82
+ refill_per_sec = opts [ :refill_per_second ] || config [ :refill_per_second ]
83
83
84
84
:ets . insert_new ( table , { bucket , { capacity , now } } )
85
85
[ { ^ bucket , { level , updated } } ] = :ets . lookup ( table , bucket )
86
86
87
87
refilled = div ( now - updated , 1_000 ) * refill_per_sec
88
88
current = min ( capacity , level + refilled )
89
89
90
- if current >= cost do
91
- level = current - cost
90
+ if current >= 1 do
91
+ level = current - 1
92
92
:ets . insert ( table , { bucket , { level , now } } )
93
93
94
94
{ :allow , level }
0 commit comments