local time = redis.call('TIME')
local now = time[1] * 1000 + math.floor(time[2] / 1000)
local runIds = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'LIMIT', 0, tonumber(ARGV[1]))
local prefix = ARGV[5]
local namespaceState = redis.call('HGET', KEYS[2], 'namespaceState') or 'ENABLED'
local promoted = 0
for _, runId in ipairs(runIds) do
local runKey = prefix .. 'run:' .. runId
local state = redis.call('HGET', runKey, 'state')
local storedScore = tonumber(redis.call('HGET', runKey, 'nextVisibleAt') or '0')
local indexScore = tonumber(redis.call('ZSCORE', KEYS[1], runId) or '0')
if (state == 'QUEUED' or state == 'RETRY_WAIT') and storedScore == indexScore then
local jobName = redis.call('HGET', runKey, 'jobName')
local jobKey = prefix .. 'job:' .. jobName
local jobState = redis.call('HGET', jobKey, 'state')
local deletedRevision = tonumber(redis.call('HGET', jobKey, 'deletedRevision') or '-1')
local runRevision = tonumber(redis.call('HGET', runKey, 'definitionRevision') or '0')
if jobState == 'DELETED' or runRevision <= deletedRevision then
redis.call('HSET', runKey, 'state', 'CANCELLED', 'finishedAt', now, 'resultCode', 'JOB_DELETED')
redis.call('ZREM', KEYS[1], runId)
redis.call('XADD', prefix .. 'completion', 'MAXLEN', '~', 100000, '*',
'runId', runId, 'state', 'CANCELLED', 'resultCode', 'JOB_DELETED')
redis.call('PEXPIRE', runKey, tonumber(ARGV[6]))
elseif jobState ~= 'ENABLED' or namespaceState ~= 'ENABLED' then
local nextVisibleAt = now + tonumber(ARGV[4])
redis.call('HSET', runKey, 'nextVisibleAt', nextVisibleAt)
redis.call('ZADD', KEYS[1], nextVisibleAt, runId)
else
local maxAttempts = tonumber(ARGV[3])
local previousAttempts = tonumber(redis.call('HGET', runKey, 'dispatchAttempts') or '0')
local attempts = math.min(previousAttempts + 1, maxAttempts + 1)
local throttled = attempts > maxAttempts
local nextVisibleAt = now + (throttled and tonumber(ARGV[4]) or tonumber(ARGV[2]))
local workerName = redis.call('HGET', runKey, 'workerName')
local workerKey = redis.call('HGET', runKey, 'workerKey')
redis.call('HSET', runKey, 'state', 'QUEUED', 'nextVisibleAt', nextVisibleAt,
'dispatchAttempts', attempts)
redis.call('XADD', prefix .. 'dispatch:' .. workerKey, 'MAXLEN', '~', 100000, '*',
'runId', runId, 'jobName', jobName,
'workerName', workerName, 'protocolVersion', redis.call('HGET', runKey, 'protocolVersion'),
'definitionRevision', redis.call('HGET', runKey, 'definitionRevision'),
'schedulerQualifier', redis.call('HGET', runKey, 'schedulerQualifier') or '')
if throttled then
redis.call('HSET', runKey, 'errorType', 'NO_CAPABLE_EXECUTOR')
end
redis.call('ZADD', KEYS[1], nextVisibleAt, runId)
promoted = promoted + 1
end
else
redis.call('ZREM', KEYS[1], runId)
end
end
local nextEntry = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
return {tostring(promoted), nextEntry[2] or '', tostring(now)}