-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a98dea4
commit 8b5d0f1
Showing
6 changed files
with
162 additions
and
179 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
local key = KEYS[1] | ||
local now = ARGV[1] | ||
local cost = ARGV[2] | ||
local poolMax = ARGV[3] | ||
local fillRate = ARGV[4] | ||
local expiry = ARGV[5] | ||
local before = redis.call('hget', key, 'ts') | ||
|
||
-- If we don't have a timestamp then we set it to now and fill up the bucket | ||
if before == false then | ||
local ret = poolMax - cost | ||
redis.call('hset', key, 'ts', now) | ||
redis.call('hset', key, 'pool', ret) | ||
-- redis.call('expire', key, expiry) | ||
return ret | ||
end | ||
|
||
-- We update the timestamp if it has changed | ||
local timediff = now - before | ||
|
||
if timediff > 0 then | ||
redis.call('hset', key, 'ts', now) | ||
else | ||
timediff = 0 | ||
end | ||
|
||
-- Calculate how much should be refilled in the bucket and add it | ||
local owedTokens = timediff / fillRate | ||
local currentTokens = redis.call('hget', key, 'pool') | ||
|
||
if currentTokens == false then | ||
currentTokens = poolMax | ||
end | ||
|
||
currentTokens = math.min(currentTokens + owedTokens, poolMax) | ||
|
||
-- Remove the cost and return the new number of tokens | ||
if currentTokens - cost >= 0 then | ||
currentTokens = currentTokens - cost | ||
else | ||
currentTokens = -1 | ||
end | ||
|
||
redis.call('hset', key, 'pool', currentTokens) | ||
redis.call('expire', key, expiry) | ||
|
||
-- Finally return the value - if it's negative then we've hit the limit | ||
return currentTokens |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.