Skip to content

Commit cced971

Browse files
committed
Fix rare race condition
1 parent 1799f2f commit cced971

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

lua/long-polling/dataproviders/redis.lua

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,28 @@ function MT:get_updates(channel, offset)
1818
local prefix = self.opts.data_prefix
1919
local redis = self:getcon()
2020

21-
local total = tonumber(redis:get(prefix .. "total:" .. channel)) or 0
22-
if offset >= total then return {}, total end -- redis can't return empty list when need_elements == 0
21+
-- The reason why there is script instead of just commands:
22+
-- https://chatgpt.com/share/67686def-c558-8004-893a-c372405c2a8f
23+
local script = [[
24+
local total_key = KEYS[1]
25+
local updates_key = KEYS[2]
26+
local offset = tonumber(ARGV[1])
2327
24-
local need_elements = total - offset
25-
local updates = redis:lrange(prefix .. "updates:" .. channel, -need_elements, -1)
28+
local total = tonumber(redis.call('get', total_key)) or 0
29+
if offset >= total then return {{}, total} end
30+
31+
local need_elements = total - offset
32+
local updates = redis.call('lrange', updates_key, -need_elements, -1)
33+
34+
return {updates, total}
35+
]]
36+
37+
local total_key = prefix .. "total:" .. channel
38+
local updates_key = prefix .. "updates:" .. channel
39+
local result = redis:eval(script, 2, total_key, updates_key, offset)
2640
redis:quit()
27-
return updates, total
41+
42+
return result[1], result[2]
2843
end
2944

3045
function MT:add_update(channel, data)

0 commit comments

Comments
 (0)