Skip to content

Commit

Permalink
tests(rate-limiting): flush expired rate limiting counters from share…
Browse files Browse the repository at this point in the history
…d dict

If we do not flush, the `ttl` value may be negative.

```bash
~ $ resty --http-conf 'lua_shared_dict jim 1m;' -e 'local shm = ngx.shared.jim; shm:set("age", 17, 1); local v = shm:get("age"); print(v); ngx.sleep(1.001); print(shm:ttl("age"))'
17
-0.032
```
  • Loading branch information
outsinre authored and windmgc committed Jan 5, 2024
1 parent c3abb6a commit 428ff45
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions spec/03-plugins/23-rate-limiting/02-policies_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ local timestamp = require "kong.tools.timestamp"
local SYNC_RATE_REALTIME = -1

--[[
basically a copy of `get_local_key()`
basically a copy of `get_local_key()`
in `kong/plugins/rate-limiting/policies/init.lua`
--]]
local EMPTY_UUID = "00000000-0000-0000-0000-000000000000"
Expand Down Expand Up @@ -41,7 +41,7 @@ describe("Plugin: rate-limiting (policies)", function()
lazy_setup(function()
package.loaded["kong.plugins.rate-limiting.policies"] = nil
policies = require "kong.plugins.rate-limiting.policies"

if not _G.kong then
_G.kong.db = {}
end
Expand Down Expand Up @@ -80,18 +80,24 @@ describe("Plugin: rate-limiting (policies)", function()
end)

it("expires after due time", function ()
local timestamp = 569000048000
local key = get_local_key(conf, identifier, 'second', timestamp)
local current_timestamp = 1553263548
local periods = timestamp.get_timestamps(current_timestamp)

assert(policies['local'].increment(conf, {second=100}, identifier, timestamp+20, 1))
local v = assert(shm:ttl(key))
local limits = {
second = 100,
}
local cache_key = get_local_key(conf, identifier, 'second', periods.second)

assert(policies['local'].increment(conf, limits, identifier, current_timestamp, 1))
local v = assert(shm:ttl(cache_key))
assert(v > 0, "wrong value")
ngx.sleep(1.020)

v = shm:ttl(key)
assert(v < 0, "expected ttl to be negative")
local val = shm:get(key)
assert.is_nil(val)
shm:flush_expired()
local err
v, err = shm:ttl(cache_key)
assert(v == nil, "still there")
assert.matches("not found", err)
end)
end)

Expand Down

0 comments on commit 428ff45

Please sign in to comment.