Skip to content
Merged
Changes from 1 commit
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
41 changes: 40 additions & 1 deletion lib/resty/limit/count.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ local mt = {
__index = _M
}

local incr_support_init_ttl
local ngx_config = ngx.config
local ngx_lua_v = ngx.config.ngx_lua_version
if not ngx_config or not ngx_lua_v or (ngx_lua_v < 10012) then
incr_support_init_ttl = false
else
incr_support_init_ttl = true
end


-- the "limit" argument controls number of request allowed in a time window.
-- time "window" argument controls the time window in seconds.
Expand All @@ -35,8 +44,30 @@ function _M.new(dict_name, limit, window)
return setmetatable(self, mt)
end

function _M.incoming_new(self, key, commit)
local dict = self.dict
local limit = self.limit
local window = self.window

function _M.incoming(self, key, commit)
local remaining, ok, err

if commit then
remaining, err = dict:incr(key, -1, limit, window)
if not remaining then
return nil, err
end
else
remaining = (dict:get(key) or limit) - 1
end

if remaining < 0 then
return nil, "rejected"
end

return 0, remaining
end

function _M.incoming_old(self, key, commit)
local dict = self.dict
local limit = self.limit
local window = self.window
Expand Down Expand Up @@ -80,6 +111,14 @@ function _M.incoming(self, key, commit)
return 0, remaining
end

function _M.incoming(self, key, commit)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This way should be better:

local function incoming_new
local function incoming_old
_M.incomming = incr_support_init_ttl and incoming_new or incoming_old

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@doujiang24 fixed, please review again, thanks

if incr_support_init_ttl then
return self:incoming_new(key, commit)
else
return self:incoming_old(key, commit)
end
end


-- uncommit remaining and return remaining value
function _M.uncommit(self, key)
Expand Down