@@ -37,13 +37,15 @@ defmodule Lightning.WebhookRateLimiter do
3737 capacity = Keyword . fetch! ( opts , :capacity )
3838 refill = Keyword . fetch! ( opts , :refill_per_second )
3939
40- { :ok , % { table: :ets . new ( :table , [ :set ] ) , capacity: capacity , refill : refill } }
40+ { :ok , % { table: :ets . new ( :table , [ :set ] ) , capacity: capacity , refill_per_second : refill } }
4141 end
4242
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+
4446 name
4547 |> via_tuple ( )
46- |> GenServer . call ( { :check_rate , bucket , cost } )
48+ |> GenServer . call ( { :check_rate , bucket , opts } )
4749 end
4850
4951 def inspect_table ( name \\ __MODULE__ ) do
@@ -53,8 +55,8 @@ defmodule Lightning.WebhookRateLimiter do
5355 end
5456
5557 @ 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 }
5860 end
5961
6062 @ impl true
@@ -74,21 +76,19 @@ defmodule Lightning.WebhookRateLimiter do
7476 { :stop , :normal , state }
7577 end
7678
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
8280 now = System . monotonic_time ( :millisecond )
81+ capacity = opts [ :capacity ] || config [ :capacity ]
82+ refill_per_sec = opts [ :refill_per_second ] || config [ :refill_per_second ]
8383
8484 :ets . insert_new ( table , { bucket , { capacity , now } } )
8585 [ { ^ bucket , { level , updated } } ] = :ets . lookup ( table , bucket )
8686
8787 refilled = div ( now - updated , 1_000 ) * refill_per_sec
8888 current = min ( capacity , level + refilled )
8989
90- if current >= cost do
91- level = current - cost
90+ if current >= 1 do
91+ level = current - 1
9292 :ets . insert ( table , { bucket , { level , now } } )
9393
9494 { :allow , level }
0 commit comments