-- schedule.lua -- -- atomically schedule a task. either: -- - XADD to the stream (immediate execution), or -- - park the message data in a hash + ZADD to the queue (future execution) -- -- updates the runs hash with state metadata in either case. -- -- KEYS: -- [1] stream_key — {prefix}:stream -- [2] parked_key — {prefix}:parked:{task_key} -- [3] queue_key — {prefix}:queue (sorted set, score = when_micros) -- [4] runs_key — {prefix}:runs:{task_key} -- -- ARGV: -- [1] task_key — caller-provided or uuid7 -- [2] when_micros — unix-epoch microseconds (sort key for the queue) -- [3] is_immediate — '1' if when <= now (after the caller's clock read) -- [4] replacing — the stream id of the message rescheduling itself -- under its own key (a perpetual), or '' -- [5..] — message fields, alternating name/value pairs -- ('function', name, 'params', json, 'attempt', n, ...) -- -- A key that is already scheduled, queued or delivered and not yet acked is -- left alone: the key is an idempotency key. The one exception is the -- delivered message the runs hash points at rescheduling itself. -- -- returns: 'SCHEDULED', or 'ALREADY_SCHEDULED' when the key was live local stream_key = KEYS[1] local parked_key = KEYS[2] local queue_key = KEYS[3] local runs_key = KEYS[4] local task_key = ARGV[1] local when_micros = ARGV[2] local is_immediate = ARGV[3] == '1' local replacing = ARGV[4] local state = redis.call('HGET', runs_key, 'state') if state == 'queued' or state == 'scheduled' then if replacing == '' or redis.call('HGET', runs_key, 'stream_id') ~= replacing then return 'ALREADY_SCHEDULED' end elseif state then -- a terminal tombstone: drop it, and its ttl with it redis.call('DEL', runs_key) end -- collect message fields (ARGV[5..]) local message = {} local function_name = '' for i = 5, #ARGV, 2 do local k = ARGV[i] local v = ARGV[i + 1] message[#message + 1] = k message[#message + 1] = v if k == 'function' then function_name = v end end if is_immediate then -- enqueue on the stream for immediate consumption. local msg_id = redis.call('XADD', stream_key, '*', unpack(message)) redis.call('HSET', runs_key, 'state', 'queued', 'when', when_micros, 'function', function_name, 'stream_id', msg_id ) else -- park the message body in a hash; ZADD by timestamp for the scheduler to promote later. redis.call('HSET', parked_key, unpack(message)) redis.call('ZADD', queue_key, when_micros, task_key) redis.call('HDEL', runs_key, 'stream_id') redis.call('HSET', runs_key, 'state', 'scheduled', 'when', when_micros, 'function', function_name ) end return 'SCHEDULED'