local time = redis.call('TIME')
local now = time[1] * 1000 + math.floor(time[2] / 1000)
if redis.call('EXISTS', KEYS[2]) == 0 then return {'NOT_FOUND'} end
local currentExpireAt = tonumber(redis.call('HGET', KEYS[2], 'expireAt') or '0')
if currentExpireAt <= now then return {'NOT_FOUND'} end
local currentRevision = tonumber(redis.call('HGET', KEYS[2], 'heartbeatRevision') or '0')
local requestId = ARGV[6] or ''
if requestId ~= '' and redis.call('HGET', KEYS[2], 'heartbeatRequestId') == requestId then
return {'OK', tostring(now), tostring(currentExpireAt), tostring(currentRevision)}
end
if ARGV[7] and ARGV[7] ~= '' and currentRevision ~= tonumber(ARGV[7]) then
return {'STALE_AUTHORITY', tostring(currentRevision)}
end
local expireAt = now + tonumber(ARGV[3])
local revision = redis.call('HINCRBY', KEYS[2], 'heartbeatRevision', 1)
local requestedState = ARGV[2]
local requestedReady = ARGV[5]
if redis.call('HGET', KEYS[2], 'state') == 'FANOUT_UNREADY' then
local unreadyUntil = tonumber(redis.call('HGET', KEYS[2], 'fanoutUnreadyUntil') or '0')
if unreadyUntil > now then
requestedState = 'FANOUT_UNREADY'
requestedReady = 'false'
else
redis.call('DEL', KEYS[3])
redis.call('HDEL', KEYS[2], 'fanoutUnreadyUntil')
end
end
redis.call('HSET', KEYS[2], 'heartbeatAt', now, 'expireAt', expireAt,
'state', requestedState, 'inflight', ARGV[4], 'fanoutReady', requestedReady)
if requestId ~= '' then redis.call('HSET', KEYS[2], 'heartbeatRequestId', requestId) end
redis.call('ZADD', KEYS[1], expireAt, ARGV[1])
for index = 4, #KEYS do redis.call('ZADD', KEYS[index], expireAt, ARGV[1]) end
return {'OK', tostring(now), tostring(expireAt), tostring(revision)}