local targetKey = KEYS[1]
local ledgerKey = KEYS[2]
local recordField = ARGV[1]
local opType = ARGV[2]
local member = ARGV[3]
local delta = ARGV[4]
local nonceTtlMs = tonumber(ARGV[5])
if nonceTtlMs == nil or nonceTtlMs <= 0 or #KEYS ~= 2 then
return { 'REJECTED_OPERATION', '', 'invalid idempotent hash field configuration' }
end
local ledgerType = redis.call('TYPE', ledgerKey)['ok']
if ledgerType ~= 'none' and ledgerType ~= 'hash' then
return { 'REJECTED_LEDGER_TYPE', '', '' }
end
local previous = redis.call('HGET', ledgerKey, recordField)
if previous then
return { 'DUPLICATE', previous, '' }
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
redis.call('HSET', ledgerKey, recordField, value)
local ttlResult = redis.pcall('HPEXPIRE', ledgerKey, ARGV[5], 'FIELDS', 1, recordField)
if type(ttlResult) == 'table' and ttlResult.err then
return { 'APPLIED_TTL_MISSING', value, ttlResult.err }
end
if ttlResult[1] ~= 1 then
return { 'APPLIED_TTL_MISSING', value, 'HPEXPIRE did not attach field TTL' }
end
return { 'APPLIED', value, '' }