@@ -73,27 +73,36 @@ local cost = tonumber(ARGV[3])
7373local now = tonumber (ARGV [4 ]) -- Current unix time in seconds
7474
7575local fields = redis .call (" HGETALL" , key )
76+
7677if # fields == 0 then
77- redis .call (" HSET" , key , " count" , max - cost , " refilled_at" , now )
78- return {1 }
78+ local expiresInSeconds = cost * refillIntervalSeconds
79+ redis .call (" HSET" , key , " count" , max - cost , " refilled_at" , now )
80+ redis .call (" EXPIRE" , key , expiresInSeconds )
81+ return {1 }
7982end
83+
8084local count = 0
8185local refilledAt = 0
8286for i = 1 , # fields , 2 do
8387 if fields [i ] == " count" then
84- count = tonumber (fields [i + 1 ])
85- elseif fields [i ] == " refilled_at" then
86- refilledAt = tonumber (fields [i + 1 ])
87- end
88+ count = tonumber (fields [i + 1 ])
89+ elseif fields [i ] == " refilled_at" then
90+ refilledAt = tonumber (fields [i + 1 ])
91+ end
8892end
93+
8994local refill = math.floor ((now - refilledAt ) / refillIntervalSeconds )
9095count = math.min (count + refill , max )
9196refilledAt = refilledAt + refill * refillIntervalSeconds
97+
9298if count < cost then
93- return {0 }
99+ return {0 }
94100end
101+
95102count = count - cost
103+ local expiresInSeconds = (max - count ) * refillIntervalSeconds
96104redis .call (" HSET" , key , " count" , count , " refilled_at" , now )
105+ redis .call (" EXPIRE" , key , expiresInSeconds )
97106return {1 }
98107```
99108
0 commit comments