-
Notifications
You must be signed in to change notification settings - Fork 53
/
count_and_increment_within_threshold.lua
40 lines (35 loc) · 1.3 KB
/
count_and_increment_within_threshold.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
local subject = KEYS[1];
local numKeys = tonumber(ARGV[1]);
local numBurstKeys = tonumber(ARGV[numKeys + 2]);
local totalKeys = numKeys + numBurstKeys;
local bucket = tonumber(ARGV[totalKeys + 2]);
local bucketCount = tonumber(ARGV[totalKeys + 3]);
local bucketExpiry = tonumber(ARGV[totalKeys + 4]);
local threshold = tonumber(ARGV[totalKeys + 5]);
local burstThreshold = tonumber(ARGV[totalKeys + 6]) or 0;
local increment = tonumber(ARGV[totalKeys + 7]);
local success = false;
local withinBurstThreshold = false;
if numBurstKeys > 0 then
local burstCount = 0;
local burstCounts = redis.call("HMGET", subject, unpack(ARGV, numKeys + 3, totalKeys + 3 ));
for key, value in ipairs(burstCounts) do
burstCount = burstCount + (tonumber(value) or 0)
end;
if burstCount < burstThreshold then
withinBurstThreshold = true;
end
end
local count = 0;
local counts = redis.call("HMGET", subject, unpack(ARGV, 2, numKeys + 1));
for key, value in ipairs(counts) do
count = count + (tonumber(value) or 0)
end;
if count < threshold or withinBurstThreshold then
redis.call("HINCRBY", subject, bucket, increment);
redis.call("HDEL", subject, (bucket + 1) % bucketCount);
redis.call("HDEL", subject, (bucket + 2) % bucketCount);
redis.call("EXPIRE", subject, bucketExpiry);
success = true;
end
return success;