@@ -37,13 +37,20 @@ 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 ,
41+ % {
42+ table: :ets . new ( :table , [ :set ] ) ,
43+ capacity: capacity ,
44+ refill_per_second: refill
45+ } }
4146 end
4247
43- def check_rate ( bucket , cost \\ 1 , name \\ __MODULE__ ) do
48+ def check_rate ( bucket , opts \\ [ ] ) do
49+ name = Keyword . get ( opts , :name , __MODULE__ )
50+
4451 name
4552 |> via_tuple ( )
46- |> GenServer . call ( { :check_rate , bucket , cost } )
53+ |> GenServer . call ( { :check_rate , bucket , opts } )
4754 end
4855
4956 def inspect_table ( name \\ __MODULE__ ) do
@@ -53,8 +60,8 @@ defmodule Lightning.WebhookRateLimiter do
5360 end
5461
5562 @ impl true
56- def handle_call ( { :check_rate , bucket , cost } , _from , state ) do
57- { :reply , do_check_rate ( state , bucket , cost ) , state }
63+ def handle_call ( { :check_rate , bucket , opts } , _from , state ) do
64+ { :reply , do_check_rate ( state , bucket , opts ) , state }
5865 end
5966
6067 @ impl true
@@ -74,21 +81,19 @@ defmodule Lightning.WebhookRateLimiter do
7481 { :stop , :normal , state }
7582 end
7683
77- def do_check_rate (
78- % { table: table , capacity: capacity , refill: refill_per_sec } ,
79- bucket ,
80- cost
81- ) do
84+ def do_check_rate ( % { table: table } = config , bucket , opts ) do
8285 now = System . monotonic_time ( :millisecond )
86+ capacity = opts [ :capacity ] || config [ :capacity ]
87+ refill_per_sec = opts [ :refill_per_second ] || config [ :refill_per_second ]
8388
8489 :ets . insert_new ( table , { bucket , { capacity , now } } )
8590 [ { ^ bucket , { level , updated } } ] = :ets . lookup ( table , bucket )
8691
8792 refilled = div ( now - updated , 1_000 ) * refill_per_sec
8893 current = min ( capacity , level + refilled )
8994
90- if current >= cost do
91- level = current - cost
95+ if current >= 1 do
96+ level = current - 1
9297 :ets . insert ( table , { bucket , { level , now } } )
9398
9499 { :allow , level }
0 commit comments