Skip to content

Commit

Permalink
fix(globalpatches): imeplement SharedDict:get_stale API (#12233)
Browse files Browse the repository at this point in the history
1. It implements the `get_stale` API.
2. It completes the `set` API with support for the `flags` parameter.
3. It abstracts the `is_stale` function for reuse.
4. It does not delete expired data during referring operations.

KAG-3398
  • Loading branch information
chobits authored Dec 22, 2023
1 parent e7f9023 commit 28fcbcb
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions kong/globalpatches.lua
Original file line number Diff line number Diff line change
Expand Up @@ -246,17 +246,19 @@ return function(options)
-- See https://github.com/openresty/resty-cli/pull/12
-- for a definitive solution of using shms in CLI
local SharedDict = {}
local function set(data, key, value, expire_at)
local function set(data, key, value, expire_at, flags)
data[key] = {
value = value,
info = {expire_at = expire_at}
info = {expire_at = expire_at, flags=flags}
}
return data[key]
end
local function is_stale(item)
return item.info.expire_at and item.info.expire_at <= ngx.now()
end
local function get(data, key)
local item = data[key]
if item and item.info.expire_at and item.info.expire_at <= ngx.now() then
data[key] = nil
if item and is_stale(item) then
item = nil
end
return item
Expand All @@ -272,9 +274,18 @@ return function(options)
end
function SharedDict:get(key)
local item = get(self.data, key)
return item and item.value, nil
if item then
return item.value, item.info.flags
end
return nil
end
function SharedDict:get_stale(key)
local item = self.data[key]
if item then
return item.value, item.info.flags, is_stale(item)
end
return nil
end
SharedDict.get_stale = SharedDict.get
function SharedDict:set(key, value, exptime)
local expire_at = (exptime and exptime ~= 0) and (ngx.now() + exptime)
set(self.data, key, value, expire_at)
Expand Down Expand Up @@ -325,7 +336,7 @@ return function(options)
local flushed = 0

for key, item in pairs(self.data) do
if item.info.expire_at and item.info.expire_at <= ngx.now() then
if is_stale(item) then
data[key] = nil
flushed = flushed + 1
if n and flushed == n then
Expand All @@ -341,9 +352,7 @@ return function(options)
local i = 0
local keys = {}
for k, item in pairs(self.data) do
if item.info.expire_at and item.info.expire_at <= ngx.now() then
self.data[k] = nil
else
if not is_stale(item) then
keys[#keys+1] = k
i = i + 1
if n ~= 0 and i == n then
Expand Down

0 comments on commit 28fcbcb

Please sign in to comment.