Skip to content

Commit bbc4a85

Browse files
committed
Allow calling with different capacities
2 parents ba91ae5 + d072ec4 commit bbc4a85

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

lib/lightning/webhook_rate_limiter.ex

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,13 @@ 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, capacity \\ nil, refill \\ nil, name \\ __MODULE__) do
4444
name
4545
|> via_tuple()
46-
|> GenServer.call({:check_rate, bucket, cost})
46+
|> GenServer.call({:check_rate, bucket, capacity, refill})
4747
end
4848

4949
def inspect_table(name \\ __MODULE__) do
@@ -53,8 +53,8 @@ defmodule Lightning.WebhookRateLimiter do
5353
end
5454

5555
@impl true
56-
def handle_call({:check_rate, bucket, cost}, _from, state) do
57-
{:reply, do_check_rate(state, bucket, cost), state}
56+
def handle_call({:check_rate, bucket, capacity, refill}, _from, state) do
57+
{:reply, do_check_rate(state, bucket, capacity, refill), state}
5858
end
5959

6060
@impl true
@@ -74,21 +74,19 @@ defmodule Lightning.WebhookRateLimiter do
7474
{:stop, :normal, state}
7575
end
7676

77-
def do_check_rate(
78-
%{table: table, capacity: capacity, refill: refill_per_sec},
79-
bucket,
80-
cost
81-
) do
77+
def do_check_rate( %{table: table} = config, bucket, capacity, refill_per_sec) do
8278
now = System.monotonic_time(:millisecond)
79+
capacity = capacity || config[:capacity]
80+
refill_per_sec = refill_per_sec || config[:refill_per_second]
8381

8482
:ets.insert_new(table, {bucket, {capacity, now}})
8583
[{^bucket, {level, updated}}] = :ets.lookup(table, bucket)
8684

8785
refilled = div(now - updated, 1_000) * refill_per_sec
8886
current = min(capacity, level + refilled)
8987

90-
if current >= cost do
91-
level = current - cost
88+
if current >= 1 do
89+
level = current - 1
9290
:ets.insert(table, {bucket, {level, now}})
9391

9492
{:allow, level}

0 commit comments

Comments
 (0)