From bfb5319c16d9897f8ce06589d4e5f645cbe4e1fc Mon Sep 17 00:00:00 2001 From: bunkerity Date: Wed, 13 Oct 2021 20:53:10 +0200 Subject: [PATCH] limit req - add burst and delay parameters --- lua/limitreq.lua | 50 +++++++++++++++++++++++++----------------------- settings.json | 13 +++++++++++-- 2 files changed, 37 insertions(+), 26 deletions(-) diff --git a/lua/limitreq.lua b/lua/limitreq.lua index bcdbae8..2ec3aa4 100644 --- a/lua/limitreq.lua +++ b/lua/limitreq.lua @@ -33,32 +33,34 @@ function M.incr (key) return true end -function M.check (url, rate) - if url == "/" or url == ngx.var.request_uri then - local key = ngx.var.remote_addr .. url - local rate_split = rate:gmatch("([^/]+)") - local max = rate_split[1] - local unit = rate_split[2] - local delay = 0 - if unit == "s" then - delay = 1 - elseif unit == "m" then - delay = 60 - elseif unit == "h" then - delay = 3600 - elseif unit == "d" then - delay = 86400 - end - if M.incr(key) then - local current, flags = ngx.shared.limit_req:get(key) - if M.decr(key, delay) then - if current > max then - logger.log(ngx.WARN, "REQ LIMIT", "ip " .. ngx.var.remote_addr .. " has reached the limit : " .. current .. "/" .. unit .. " (max = " .. rate .. ")") - return true +function M.check (rate, burst, sleep) + local key = ngx.var.remote_addr .. ngx.var.uri + local rate_split = rate:gmatch("([^r/]+)") + local max = rate_split[1] + local unit = rate_split[2] + local delay = 0 + if unit == "s" then + delay = 1 + elseif unit == "m" then + delay = 60 + elseif unit == "h" then + delay = 3600 + elseif unit == "d" then + delay = 86400 + end + if M.incr(key) then + local current, flags = ngx.shared.limit_req:get(key) + if M.decr(key, delay) then + if current > max + burst then + 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 + elseif current > max then + if sleep > 0 then + ngx.sleep(sleep) end - else - ngx.shared.limit_req:set(key, current-1, 0) end + else + ngx.shared.limit_req:set(key, current-1, 0) end end return false diff --git a/settings.json b/settings.json index 14536aa..0da273e 100644 --- a/settings.json +++ b/settings.json @@ -877,18 +877,27 @@ "env": "LIMIT_REQ_RATE", "id": "limit-req-rate", "label": "Limit req rate", - "regex": "^\\d+r/(ms|s|m|h|d)$", + "regex": "^\\d+r/(s|m|h|d)$", "type": "text" }, { "context": "multisite", - "default": "2", + "default": "5", "env": "LIMIT_REQ_BURST", "id": "limit-req-burst", "label": "Limit req burst", "regex": "^\\d+$", "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", "default": "10m",