Skip to content

req: add exptime argument for key-value pairs #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/resty/limit/req.lua
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ local mt = {
}


function _M.new(dict_name, rate, burst)
function _M.new(dict_name, rate, burst, exptime)
local dict = ngx_shared[dict_name]
if not dict then
return nil, "shared dict not found"
Expand All @@ -59,6 +59,7 @@ function _M.new(dict_name, rate, burst)
dict = dict,
rate = rate * 1000,
burst = burst * 1000,
exptime = exptime or 0,
}

return setmetatable(self, mt)
Expand All @@ -73,6 +74,7 @@ end
function _M.incoming(self, key, commit)
local dict = self.dict
local rate = self.rate
local exptime = self.exptime
local now = ngx_now() * 1000

local excess
Expand Down Expand Up @@ -108,7 +110,7 @@ function _M.incoming(self, key, commit)
if commit then
rec_cdata.excess = excess
rec_cdata.last = now
dict:set(key, ffi_str(rec_cdata, rec_size))
dict:set(key, ffi_str(rec_cdata, rec_size), exptime)
end

-- return the delay in seconds, as well as excess
Expand All @@ -119,6 +121,7 @@ end
function _M.uncommit(self, key)
assert(key)
local dict = self.dict
local exptime = self.exptime

local v = dict:get(key)
if not v then
Expand All @@ -135,7 +138,7 @@ function _M.uncommit(self, key)

rec_cdata.excess = excess
rec_cdata.last = rec.last
dict:set(key, ffi_str(rec_cdata, rec_size))
dict:set(key, ffi_str(rec_cdata, rec_size), exptime)
return true
end

Expand Down
5 changes: 4 additions & 1 deletion lib/resty/limit/req.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Methods

new
---
**syntax:** `obj, err = class.new(shdict_name, rate, burst)`
**syntax:** `obj, err = class.new(shdict_name, rate, burst, exptime)`

Instantiates an object of this class. The `class` value is returned by the call `require "resty.limit.req"`.

Expand All @@ -124,6 +124,9 @@ This method takes the following arguments:

Requests exceeding this hard limit
will get rejected immediately.
* `exptime` is the expiration time (in seconds) for the inserted limiter key.

Optional argument. Default is 0 (never expire key-value pair).

On failure, this method returns `nil` and a string describing the error (like a bad `lua_shared_dict` name).

Expand Down