@@ -18,13 +18,28 @@ function MT:get_updates(channel, offset)
18
18
local prefix = self .opts .data_prefix
19
19
local redis = self :getcon ()
20
20
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])
23
27
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 )
26
40
redis :quit ()
27
- return updates , total
41
+
42
+ return result [1 ], result [2 ]
28
43
end
29
44
30
45
function MT :add_update (channel , data )
0 commit comments