limit req - add burst and delay parameters

This commit is contained in:
bunkerity 2021-10-13 20:53:10 +02:00
parent 4c77a14825
commit bfb5319c16
No known key found for this signature in database
GPG Key ID: 3D80806F12602A7C
2 changed files with 37 additions and 26 deletions

View File

@ -33,10 +33,9 @@ function M.incr (key)
return true return true
end end
function M.check (url, rate) function M.check (rate, burst, sleep)
if url == "/" or url == ngx.var.request_uri then local key = ngx.var.remote_addr .. ngx.var.uri
local key = ngx.var.remote_addr .. url local rate_split = rate:gmatch("([^r/]+)")
local rate_split = rate:gmatch("([^/]+)")
local max = rate_split[1] local max = rate_split[1]
local unit = rate_split[2] local unit = rate_split[2]
local delay = 0 local delay = 0
@ -52,15 +51,18 @@ function M.check (url, rate)
if M.incr(key) then if M.incr(key) then
local current, flags = ngx.shared.limit_req:get(key) local current, flags = ngx.shared.limit_req:get(key)
if M.decr(key, delay) then if M.decr(key, delay) then
if current > max then if current > max + burst then
logger.log(ngx.WARN, "REQ LIMIT", "ip " .. ngx.var.remote_addr .. " has reached the limit : " .. current .. "/" .. unit .. " (max = " .. rate .. ")") logger.log(ngx.WARN, "REQ LIMIT", "ip " .. ngx.var.remote_addr .. " has reached the limit for uri " .. ngx.var.uri .. " : " .. current .. "r/" .. unit .. " (max = " .. rate .. ")")
return true return true
elseif current > max then
if sleep > 0 then
ngx.sleep(sleep)
end
end end
else else
ngx.shared.limit_req:set(key, current-1, 0) ngx.shared.limit_req:set(key, current-1, 0)
end end
end end
end
return false return false
end end

View File

@ -877,18 +877,27 @@
"env": "LIMIT_REQ_RATE", "env": "LIMIT_REQ_RATE",
"id": "limit-req-rate", "id": "limit-req-rate",
"label": "Limit req rate", "label": "Limit req rate",
"regex": "^\\d+r/(ms|s|m|h|d)$", "regex": "^\\d+r/(s|m|h|d)$",
"type": "text" "type": "text"
}, },
{ {
"context": "multisite", "context": "multisite",
"default": "2", "default": "5",
"env": "LIMIT_REQ_BURST", "env": "LIMIT_REQ_BURST",
"id": "limit-req-burst", "id": "limit-req-burst",
"label": "Limit req burst", "label": "Limit req burst",
"regex": "^\\d+$", "regex": "^\\d+$",
"type": "text" "type": "text"
}, },
{
"context": "multisite",
"default": "1",
"env": "LIMIT_REQ_DELAY",
"id": "limit-req-delay",
"label": "Limit req delay",
"regex": "^\\d+(\\.\\d+)?$",
"type": "text"
},
{ {
"context": "global", "context": "global",
"default": "10m", "default": "10m",