local time = redis.call('TIME')
local now = time[1] * 1000 + math.floor(time[2] / 1000)
local result = {tostring(now)}
local count = tonumber(ARGV[1])
for index = 1, count do
local keyOffset = (index - 1) * 3
local argOffset = 2 + (index - 1) * 4
local recordKey = KEYS[keyOffset + 1]
local leaseKey = KEYS[keyOffset + 2]
local waitingKey = KEYS[keyOffset + 3]
local member = ARGV[argOffset]
local owner = ARGV[argOffset + 1]
local token = ARGV[argOffset + 2]
local duration = tonumber(ARGV[argOffset + 3])
local state = redis.call('HGET', recordKey, 'state')
local code = 'STATE_MISMATCH'
local deadline = 0
local cancellation = ''
if (state == 'RUNNING' or state == 'FANOUT_CREATING')
and redis.call('HGET', recordKey, 'owner') == owner
and redis.call('HGET', recordKey, 'attemptToken') == token then
code = 'OK'
deadline = now + duration
cancellation = redis.call('HGET', recordKey, 'cancelRequestedAt') or ''
if state == 'RUNNING' then
redis.call('HSET', recordKey, 'leaseUntil', deadline)
redis.call('ZADD', leaseKey, deadline, member)
else
redis.call('HSET', recordKey, 'createDeadlineAt', deadline)
redis.call('ZADD', waitingKey, deadline, member)
end
elseif state == 'RUNNING' or state == 'FANOUT_CREATING' then
code = 'STALE_OWNER'
end
result[#result + 1] = code
result[#result + 1] = tostring(deadline)
result[#result + 1] = cancellation
end
return result