local targetKey = KEYS[1]
local recordField = ARGV[1]
local opType = ARGV[2]
local member = ARGV[3]
local delta = ARGV[4]
local nonceTtlMs = tonumber(ARGV[5])
local bucketSpanMs = tonumber(ARGV[6])
local bucketCount = #KEYS - 1
if nonceTtlMs == nil or nonceTtlMs <= 0
or bucketSpanMs == nil or bucketSpanMs <= 0 or bucketCount <= 0 then
return { 'REJECTED_OPERATION', '', 'invalid idempotent bucket configuration' }
end
local time = redis.call('TIME')
local nowMs = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local currentEpoch = math.floor(nowMs / bucketSpanMs)
for index = 2, #KEYS do
local ledgerType = redis.call('TYPE', KEYS[index])['ok']
if ledgerType ~= 'none' and ledgerType ~= 'hash' then
return { 'REJECTED_LEDGER_TYPE', '', '' }
end
if ledgerType == 'hash' then
local storedEpoch = tonumber(redis.call('HGET', KEYS[index], '__epoch'))
if storedEpoch ~= nil then
local age = currentEpoch - storedEpoch
if age < bucketCount then
local previous = redis.call('HGET', KEYS[index], recordField)
if previous then
return { 'DUPLICATE', previous, '' }
end
end
end
end
end
if opType == 'HASH_DECR' then
if delta == '-9223372036854775808' then
return { 'REJECTED_COMMAND', '', 'hash decrement delta is outside HINCRBY range' }
end
if string.sub(delta, 1, 1) == '-' then
delta = string.sub(delta, 2)
else
delta = '-' .. delta
end
end
local result
if opType == 'STR_INCR' then
result = redis.pcall('INCRBY', targetKey, delta)
elseif opType == 'STR_DECR' then
result = redis.pcall('DECRBY', targetKey, delta)
elseif opType == 'HASH_INCR' or opType == 'HASH_DECR' then
result = redis.pcall('HINCRBY', targetKey, member, delta)
elseif opType == 'ZSET_INCR' then
result = redis.pcall('ZINCRBY', targetKey, delta, member)
else
return { 'REJECTED_OPERATION', '', '' }
end
if type(result) == 'table' and result.err then
return { 'REJECTED_COMMAND', '', result.err }
end
local value
if opType == 'ZSET_INCR' then
value = result
elseif opType == 'HASH_INCR' or opType == 'HASH_DECR' then
value = redis.call('HGET', targetKey, member)
else
value = redis.call('GET', targetKey)
end
local currentIndex = currentEpoch % bucketCount
local currentLedgerKey = KEYS[currentIndex + 2]
local storedEpoch = tonumber(redis.call('HGET', currentLedgerKey, '__epoch'))
if storedEpoch == nil or storedEpoch < currentEpoch then
redis.call('DEL', currentLedgerKey)
redis.call('HSET', currentLedgerKey, '__epoch', string.format('%d', currentEpoch))
end
redis.call('HSET', currentLedgerKey, recordField, value)
local ttlResult = redis.pcall('PEXPIRE', currentLedgerKey, nonceTtlMs)
if type(ttlResult) == 'table' and ttlResult.err then
return { 'APPLIED_TTL_MISSING', value, ttlResult.err }
end
if ttlResult ~= 1 then
return { 'APPLIED_TTL_MISSING', value, 'PEXPIRE did not attach bucket TTL' }
end
return { 'APPLIED', value, '' }