falvaradorodriguez commented on code in PR #12605:
URL: https://github.com/apache/apisix/pull/12605#discussion_r2736070946
##########
apisix/plugins/limit-req/util.lua:
##########
@@ -14,61 +14,97 @@
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-local math = require "math"
-local abs = math.abs
-local max = math.max
local ngx_now = ngx.now
-local ngx_null = ngx.null
local tonumber = tonumber
+local tostring = tostring
+local type = type
+local core = require("apisix.core")
+local resty_string = require("resty.string")
local _M = {version = 0.1}
+local script = core.string.compress_script([=[
+ local state_key = KEYS[1] -- state_key (hash), fields:
"excess", "last"
+ local rate = tonumber(ARGV[1]) -- req/s
+ local now = tonumber(ARGV[2]) -- ms
+ local burst = tonumber(ARGV[3]) -- req/s
+ local commit = tonumber(ARGV[4]) -- 1/0
+
+ local vals = redis.call("HMGET", state_key, "excess", "last")
+ local prev_excess = tonumber(vals[1] or "0")
+ local prev_last = tonumber(vals[2] or "0")
+
+ local new_excess
+ if prev_last > 0 then
+ local elapsed = math.abs(now - prev_last)
+ new_excess = math.max(prev_excess - rate * (elapsed) / 1000 + 1000, 0)
+ else
+ new_excess = 0
+ end
+
+ if new_excess > burst then
+ return {0, new_excess}
+ end
+
+ if commit == 1 then
+ redis.call("HMSET", state_key, "excess", new_excess, "last", now)
+ local ttl = math.ceil(burst / rate) + 1
+ redis.call("EXPIRE", state_key, ttl)
+ end
+
+ return {1, new_excess}
+]=])
+
+-- Pre-calculate SHA1 for EVALSHA optimization
+local script_sha1 = resty_string.to_hex(ngx.sha1_bin(script))
+
+
+local function is_noscript_error(err)
+ if not err then
+ return false
+ end
+
+ local s
+ if type(err) == "table" then
+ s = tostring(err[1] or err.err or err.message or err.msg or err)
Review Comment:
~~Thanks for the note. In resty.redis the error is indeed typically returned
as a plain string.~~
~~However, since this code path is meant to work with both resty.redis and
resty.rediscluster, I added a small defensive handling for the case where
errors may be propagated as a structured table (e.g. containing err/message
fields) instead of a raw string.~~
~~This doesn’t change the behavior for the common case, but makes the
NOSCRIPT detection more robust across Redis standalone and Redis Cluster
setups, especially during redirects/failovers where error formats may differ.~~
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]