local state = redis.call('HGET', KEYS[1], 'state')
if state ~= 'COMMITTED' and state ~= 'WAITING_CHILDREN' then return {'NOT_COMMITTED'} end
local time = redis.call('TIME')
local now = time[1] * 1000 + math.floor(time[2] / 1000)
local count = tonumber(ARGV[1])
local delivered = 0
local cursor = 5
for index = 1, count do
local shardKey = KEYS[3 + (index - 1) * 3]
local inboxKey = KEYS[4 + (index - 1) * 3]
local notifyChannel = KEYS[5 + (index - 1) * 3]
local shardState = redis.call('HGET', shardKey, 'state')
local epoch = redis.call('HGET', shardKey, 'assignmentEpoch')
local inboxMessageId = redis.call('HGET', shardKey, 'inboxMessageId')
if shardState == 'AWAITING_RECEIPT' and epoch == ARGV[cursor + 1]
and (not inboxMessageId or inboxMessageId == '') then
local messageId = redis.call('XADD', inboxKey, '*', 'fanoutId', ARGV[2],
'seq', ARGV[cursor], 'assignmentEpoch', epoch, 'shardRunId', ARGV[cursor + 2],
'schedulerQualifier', redis.call('HGET', shardKey, 'schedulerQualifier') or '')
local deadline = now + tonumber(ARGV[cursor + 3])
redis.call('HSET', shardKey, 'inboxMessageId', messageId, 'receiptDeadlineAt', deadline)
redis.call('ZADD', KEYS[2], deadline, ARGV[2] .. ':' .. ARGV[cursor])
redis.call(ARGV[3], notifyChannel, ARGV[2] .. '|' .. ARGV[cursor]
.. '|' .. epoch .. '|' .. messageId)
delivered = delivered + 1
end
cursor = cursor + 4
end
if ARGV[4] == '1' then redis.call('HINCRBY', KEYS[1], 'deliveryCursor', count) end
return {'OK', tostring(delivered), redis.call('HGET', KEYS[1], 'deliveryCursor')}