| 1 | -- A sliding window over one user's transfers. KEYS[1] is a sorted set: each |
| 2 | -- member is a transfer, "id:amount", scored by when we first saw it. ARGV is |
| 3 | -- the member, then the count window and the amount window, in milliseconds. |
| 4 | -- Redis runs a script all at once: nobody else reads or writes in between. |
| 5 | local t = redis.call('TIME') |
| 6 | local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000) |
| 7 | local count_window = tonumber(ARGV[2]) |
| 8 | local amount_window = tonumber(ARGV[3]) |
| 9 | |
| 10 | -- Forget what's older than the longer window. Then add this transfer. NX: a |
| 11 | -- retry of the same transfer keeps its first time, and counts once. |
| 12 | redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - amount_window) |
| 13 | redis.call('ZADD', KEYS[1], 'NX', now, ARGV[1]) |
| 14 | redis.call('PEXPIRE', KEYS[1], amount_window) |
| 15 | |
| 16 | -- How many in the count window, and how much in the amount window. |
| 17 | local count = redis.call('ZCOUNT', KEYS[1], now - count_window, '+inf') |
| 18 | local amount = 0 |
| 19 | for _, member in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do |
| 20 | amount = amount + tonumber(string.match(member, ':(%d+)$')) |
| 21 | end |
| 22 | return {count, amount} |