@brickkit/redis-world 0.15.0 → 0.16.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/world-783VJfKL.js.map +1 -1
- package/package.json +10 -10
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as RunRetention, a as QueueStats, f as RedisWorldConfig, g as KeepRuns, t as RedisBackedWorld } from "./world-BDW_evdb.js";
|
|
2
|
-
import
|
|
2
|
+
import "ioredis";
|
|
3
3
|
/** `config` is laid over `configFromEnv()`: an option left out comes from the
|
|
4
4
|
* `WORKFLOW_REDIS_*` variables, then the defaults. */
|
|
5
5
|
export declare function createWorld(config?: Partial<RedisWorldConfig>): RedisBackedWorld;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["delay"],"sources":["../src/queue.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { MessageId, ValidQueueName } from \"@workflow/world\";\nimport type { Redis } from \"ioredis\";\nimport {\n checkInteger,\n type RedisWorldConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nimport { keys } from \"./keys.js\";\nimport { debug } from \"./util.js\";\nimport {\n createWorldQueue,\n retryDelayMs,\n type Deliver,\n type Delivery,\n type QueueBackend,\n type WorldQueue,\n type WorldQueueOptions,\n} from \"./world-queue.js\";\n\nexport type { QueueStats } from \"./world-queue.js\";\n\ninterface Envelope extends Delivery {\n dedupKey: string;\n headers: Record<string, string>;\n}\n\n// Derived from the upstream reliable Redis list queue. Every transition is a\n// single script: a process crash cannot leave a message between structures.\nconst ENQUEUE = `\n if ARGV[1] ~= '' then\n local existing = redis.call('GET', KEYS[1])\n if existing then return existing end\n redis.call('SET', KEYS[1], ARGV[2])\n if tonumber(ARGV[3]) > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[3]) end\n end\n if tonumber(ARGV[5]) > 0 then\n redis.call('ZADD', KEYS[3], ARGV[5], ARGV[4])\n else\n redis.call('LPUSH', KEYS[2], ARGV[4])\n end\n return ARGV[2]\n`;\nconst RESERVE = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return nil end\n local raw = redis.call('LINDEX', KEYS[1], -1)\n if not raw then return nil end\n local job = cjson.decode(raw)\n job.attempt = job.attempt + 1\n job.deliveryCount = job.deliveryCount + 1\n local claim = cjson.encode(job)\n redis.call('RPOP', KEYS[1])\n redis.call('LPUSH', KEYS[2], claim)\n return claim\n`;\nconst ACK = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return 0 end\n if redis.call('LREM', KEYS[1], 1, ARGV[1]) == 0 then return 0 end\n if ARGV[2] ~= '' and redis.call('GET', KEYS[2]) == ARGV[3] then\n redis.call('DEL', KEYS[2])\n end\n return 1\n`;\nconst DEFER = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return 0 end\n if redis.call('LREM', KEYS[1], 1, ARGV[1]) == 0 then return 0 end\n redis.call('ZADD', KEYS[2], ARGV[3], ARGV[2])\n return 1\n`;\nconst PROMOTE = `\n local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 100)\n for _, raw in ipairs(due) do\n redis.call('LPUSH', KEYS[2], raw)\n redis.call('ZREM', KEYS[1], raw)\n end\n return #due\n`;\nconst RECLAIM = `\n if redis.call('EXISTS', KEYS[3]) == 1 then return 0 end\n local moved = 0\n for i = 1, 100 do\n local raw = redis.call('RPOPLPUSH', KEYS[1], KEYS[2])\n if not raw then break end\n moved = moved + 1\n end\n if redis.call('LLEN', KEYS[1]) == 0 then redis.call('SREM', KEYS[4], ARGV[1]) end\n return moved\n`;\nconst RENEW = `\n if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\n return 1\n`;\nconst REGISTER = `\n redis.call('SET', KEYS[1], '1', 'PX', ARGV[2])\n redis.call('SADD', KEYS[2], ARGV[1])\n`;\n// ARGV[1] .. owner is the owner's processing list: `keys().queue.processing(\"\")`.\nconst STATS = `\n local active = 0\n for _, owner in ipairs(redis.call('SMEMBERS', KEYS[3])) do\n active = active + redis.call('LLEN', ARGV[1] .. owner)\n end\n return {redis.call('LLEN', KEYS[1]), active, redis.call('ZCARD', KEYS[2])}\n`;\n\nfunction parseEnvelope(raw: string): Envelope {\n const value: unknown = JSON.parse(raw);\n if (\n value === null ||\n typeof value !== \"object\" ||\n !(\"messageId\" in value) ||\n !(\"queueName\" in value) ||\n !(\"message\" in value) ||\n typeof value.message !== \"string\" ||\n !(\"attempt\" in value) ||\n typeof value.attempt !== \"number\" ||\n !(\"deliveryCount\" in value) ||\n typeof value.deliveryCount !== \"number\" ||\n !(\"createdAt\" in value) ||\n typeof value.createdAt !== \"number\" ||\n !(\"dedupKey\" in value) ||\n typeof value.dedupKey !== \"string\" ||\n !(\"headers\" in value) ||\n value.headers === null ||\n typeof value.headers !== \"object\"\n ) {\n throw new TypeError(\"Invalid Redis queue envelope\");\n }\n const headers: Record<string, string> = {};\n for (const [key, header] of Object.entries(value.headers)) {\n if (typeof header !== \"string\") throw new TypeError(\"Invalid queue header\");\n headers[key] = header;\n }\n return {\n messageId: MessageId.parse(value.messageId),\n queueName: ValidQueueName.parse(value.queueName),\n message: value.message,\n attempt: value.attempt,\n deliveryCount: value.deliveryCount,\n createdAt: value.createdAt,\n dedupKey: value.dedupKey,\n headers,\n ...(\"route\" in value &&\n typeof value.route === \"string\" && { route: value.route }),\n };\n}\n\nexport function createQueue(\n redis: Redis,\n config: ResolvedConfig<RedisWorldConfig>,\n options: WorldQueueOptions = {},\n): WorldQueue {\n const queueKeys = keys(config.keyPrefix).queue;\n const { ready, delayed, workers: owners, processing, heartbeat } = queueKeys;\n const heartbeatTtlMs = config.heartbeatTtlMs ?? 90_000;\n checkInteger(\"heartbeatTtlMs\", heartbeatTtlMs, 300);\n const { queueConcurrency: concurrency, maxAttempts, maxBackoffMs } = config;\n let closed = false;\n let startPromise: Promise<void> | undefined;\n let loop: Promise<void> | undefined;\n let owner: string | undefined;\n const inflight = new Set<Promise<void>>();\n const lostOwners = new Set<string>();\n const abort = new AbortController();\n const sleep = () =>\n delay(50, undefined, { signal: abort.signal }).catch(() => {});\n\n async function enqueue(\n message: Parameters<QueueBackend[\"enqueue\"]>[0],\n opts: Parameters<QueueBackend[\"enqueue\"]>[1],\n ): Promise<MessageId> {\n const dedupKey = opts.idempotencyKey\n ? queueKeys.idempotent(opts.idempotencyKey)\n : \"\";\n const envelope: Envelope = {\n messageId: message.messageId,\n queueName: message.queueName,\n message: message.message,\n attempt: 0,\n deliveryCount: 0,\n createdAt: Date.now(),\n dedupKey,\n headers: message.headers ?? {},\n ...(message.route && { route: message.route }),\n };\n const delayMs = Math.max(0, (opts.delaySeconds ?? 0) * 1000);\n if (!Number.isFinite(delayMs))\n throw new RangeError(\"delaySeconds must be finite\");\n const result = await redis.eval(\n ENQUEUE,\n 3,\n dedupKey || ready,\n ready,\n delayed,\n dedupKey,\n message.messageId,\n config.idempotencyTtlMs ?? 0,\n JSON.stringify(envelope),\n delayMs > 0 ? Date.now() + delayMs : 0,\n );\n return MessageId.parse(result);\n }\n\n async function settle(\n raw: string,\n claimOwner: string,\n deliver: Deliver,\n ): Promise<void> {\n try {\n const job = parseEnvelope(raw);\n let seconds: number | undefined;\n let failed = false;\n try {\n // Reservation persists the attempt before delivery, so a crash\n // redelivery reports one more.\n seconds = await deliver(job);\n } catch (error) {\n failed = true;\n debug(\n `Delivery ${job.messageId} attempt ${job.attempt} failed:`,\n error,\n );\n seconds =\n (job.attempt >= maxAttempts\n ? maxBackoffMs\n : retryDelayMs(job.attempt, config)) / 1000;\n if (job.attempt === maxAttempts)\n console.error(\n `Queue message ${job.messageId} exhausted maxAttempts; retaining it for capped retries`,\n );\n }\n if (seconds === undefined) {\n await redis.eval(\n ACK,\n 3,\n processing(claimOwner),\n job.dedupKey || ready,\n heartbeat(claimOwner),\n raw,\n job.dedupKey,\n job.messageId,\n );\n } else {\n // Only successful reschedules preserve the attempt. A crash always\n // leaves the reserved attempt in Redis, so reclaim counts as failure.\n const next = failed ? job : { ...job, attempt: job.attempt - 1 };\n await redis.eval(\n DEFER,\n 3,\n processing(claimOwner),\n delayed,\n heartbeat(claimOwner),\n raw,\n JSON.stringify(next),\n Date.now() + seconds * 1000,\n );\n }\n } catch (error) {\n // Keep the claim for reclaim on connection loss or malformed data.\n lostOwners.add(claimOwner);\n console.error(\"Queue settlement error:\", error);\n }\n }\n\n async function register(): Promise<string> {\n const next = randomUUID();\n await redis.eval(\n REGISTER,\n 2,\n heartbeat(next),\n owners,\n next,\n heartbeatTtlMs,\n );\n return next;\n }\n\n async function run(deliver: Deliver): Promise<void> {\n let renewedAt = Date.now();\n let maintainedAt = 0;\n let failing = false;\n while (!closed) {\n try {\n for (const lost of lostOwners) {\n await redis.del(heartbeat(lost));\n lostOwners.delete(lost);\n if (owner === lost) owner = undefined;\n }\n if (!owner || Date.now() - renewedAt >= heartbeatTtlMs / 3) {\n // Never resurrect an expired lease: its processing list may already\n // belong to the reclaimer. A fresh UUID fences all old settlements.\n if (\n !owner ||\n (await redis.eval(RENEW, 1, heartbeat(owner), heartbeatTtlMs)) !== 1\n )\n owner = await register();\n renewedAt = Date.now();\n }\n if (Date.now() - maintainedAt >= 100) {\n await redis.eval(PROMOTE, 2, delayed, ready, Date.now());\n for (const stale of await redis.smembers(owners)) {\n if (stale !== owner)\n await redis.eval(\n RECLAIM,\n 4,\n processing(stale),\n ready,\n heartbeat(stale),\n owners,\n stale,\n );\n }\n maintainedAt = Date.now();\n }\n for (\n let reserved = 0;\n reserved < concurrency &&\n !closed &&\n owner &&\n inflight.size < concurrency;\n reserved++\n ) {\n const claimOwner = owner;\n const raw = await redis.eval(\n RESERVE,\n 3,\n ready,\n processing(claimOwner),\n heartbeat(claimOwner),\n );\n if (typeof raw !== \"string\") break;\n const task = settle(raw, claimOwner, deliver);\n inflight.add(task);\n void task.finally(() => inflight.delete(task));\n }\n failing = false;\n } catch (error) {\n // Warn once per outage: a queue that lost Redis otherwise looks idle.\n if (!closed && !failing) console.warn(\"Queue polling failed:\", error);\n else if (!closed) debug(\"Queue polling error:\", error);\n failing = true;\n }\n await sleep();\n }\n }\n\n const backend: QueueBackend = {\n enqueue,\n async getQueueStats() {\n const counts = await redis.eval(\n STATS,\n 3,\n ready,\n delayed,\n owners,\n processing(\"\"),\n );\n if (\n !Array.isArray(counts) ||\n counts.length !== 3 ||\n counts.some((c) => typeof c !== \"number\")\n )\n throw new TypeError(\"Invalid queue statistics\");\n return {\n waiting: Number(counts[0]),\n active: Number(counts[1]),\n delayed: Number(counts[2]),\n completed: 0,\n failed: 0,\n };\n },\n start(deliver) {\n if (closed) return Promise.reject(new Error(\"Queue is closed\"));\n startPromise ??= (async () => {\n owner = await register();\n loop = run(deliver);\n })().catch((error) => {\n startPromise = undefined;\n throw error;\n });\n return startPromise;\n },\n async close() {\n if (closed) return;\n closed = true;\n abort.abort();\n await startPromise;\n await loop;\n // While handlers drain, keep the lease alive. close() must not permit a\n // live long-running handler to be reclaimed merely because shutdown began.\n const timer = setInterval(\n () => {\n if (owner)\n void redis\n .eval(RENEW, 1, heartbeat(owner), heartbeatTtlMs)\n .catch((error) => debug(\"Queue close heartbeat:\", error));\n },\n Math.floor(heartbeatTtlMs / 3),\n );\n try {\n await Promise.all(inflight);\n } finally {\n clearInterval(timer);\n }\n if (owner) {\n await redis.del(heartbeat(owner));\n await redis.eval(\n RECLAIM,\n 4,\n processing(owner),\n ready,\n heartbeat(owner),\n owners,\n owner,\n );\n }\n },\n };\n return createWorldQueue(backend, config, { ...options, debug });\n}\n","import { configFromEnv, type RedisWorldConfig } from \"./config.js\";\nimport { createQueue } from \"./queue.js\";\nimport { debug } from \"./util.js\";\nimport { createRedisBackedWorld, type RedisBackedWorld } from \"./world.js\";\n\n/** `config` is laid over `configFromEnv()`: an option left out comes from the\n * `WORKFLOW_REDIS_*` variables, then the defaults. */\nexport function createWorld(\n config: Partial<RedisWorldConfig> = {},\n): RedisBackedWorld {\n return createRedisBackedWorld(config, {\n env: configFromEnv(),\n createQueue,\n label: \"world-redis\",\n debug,\n });\n}\n\nexport type { RedisWorldConfig } from \"./config.js\";\nexport type { QueueStats } from \"./queue.js\";\nexport type { KeepRuns, RunRetention } from \"./reaper.js\";\n"],"mappings":";;;;;;AA8BA,MAAM,UAAU;;;;;;;;;;;;;;AAchB,MAAM,UAAU;;;;;;;;;;;;AAYhB,MAAM,MAAM;;;;;;;;AAQZ,MAAM,QAAQ;;;;;;AAMd,MAAM,UAAU;;;;;;;;AAQhB,MAAM,UAAU;;;;;;;;;;;AAWhB,MAAM,QAAQ;;;;;AAKd,MAAM,WAAW;;;;AAKjB,MAAM,QAAQ;;;;;;;AAQd,SAAS,cAAc,KAAuB;CAC5C,MAAM,QAAiB,KAAK,MAAM,GAAG;CACrC,IACE,UAAU,QACV,OAAO,UAAU,YACjB,EAAE,eAAe,UACjB,EAAE,eAAe,UACjB,EAAE,aAAa,UACf,OAAO,MAAM,YAAY,YACzB,EAAE,aAAa,UACf,OAAO,MAAM,YAAY,YACzB,EAAE,mBAAmB,UACrB,OAAO,MAAM,kBAAkB,YAC/B,EAAE,eAAe,UACjB,OAAO,MAAM,cAAc,YAC3B,EAAE,cAAc,UAChB,OAAO,MAAM,aAAa,YAC1B,EAAE,aAAa,UACf,MAAM,YAAY,QAClB,OAAO,MAAM,YAAY,UAEzB,MAAM,IAAI,UAAU,8BAA8B;CAEpD,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAM,OAAO,GAAG;EACzD,IAAI,OAAO,WAAW,UAAU,MAAM,IAAI,UAAU,sBAAsB;EAC1E,QAAQ,OAAO;CACjB;CACA,OAAO;EACL,WAAW,UAAU,MAAM,MAAM,SAAS;EAC1C,WAAW,eAAe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","names":["delay"],"sources":["../src/queue.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { MessageId, ValidQueueName } from \"@workflow/world\";\nimport type { Redis } from \"ioredis\";\nimport {\n checkInteger,\n type RedisWorldConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nimport { keys } from \"./keys.js\";\nimport { debug } from \"./util.js\";\nimport {\n createWorldQueue,\n retryDelayMs,\n type Deliver,\n type Delivery,\n type QueueBackend,\n type WorldQueue,\n type WorldQueueOptions,\n} from \"./world-queue.js\";\n\nexport type { QueueStats } from \"./world-queue.js\";\n\ninterface Envelope extends Delivery {\n dedupKey: string;\n headers: Record<string, string>;\n}\n\n// Derived from the upstream reliable Redis list queue. Every transition is a\n// single script: a process crash cannot leave a message between structures.\nconst ENQUEUE = `\n if ARGV[1] ~= '' then\n local existing = redis.call('GET', KEYS[1])\n if existing then return existing end\n redis.call('SET', KEYS[1], ARGV[2])\n if tonumber(ARGV[3]) > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[3]) end\n end\n if tonumber(ARGV[5]) > 0 then\n redis.call('ZADD', KEYS[3], ARGV[5], ARGV[4])\n else\n redis.call('LPUSH', KEYS[2], ARGV[4])\n end\n return ARGV[2]\n`;\nconst RESERVE = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return nil end\n local raw = redis.call('LINDEX', KEYS[1], -1)\n if not raw then return nil end\n local job = cjson.decode(raw)\n job.attempt = job.attempt + 1\n job.deliveryCount = job.deliveryCount + 1\n local claim = cjson.encode(job)\n redis.call('RPOP', KEYS[1])\n redis.call('LPUSH', KEYS[2], claim)\n return claim\n`;\nconst ACK = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return 0 end\n if redis.call('LREM', KEYS[1], 1, ARGV[1]) == 0 then return 0 end\n if ARGV[2] ~= '' and redis.call('GET', KEYS[2]) == ARGV[3] then\n redis.call('DEL', KEYS[2])\n end\n return 1\n`;\nconst DEFER = `\n if redis.call('EXISTS', KEYS[3]) == 0 then return 0 end\n if redis.call('LREM', KEYS[1], 1, ARGV[1]) == 0 then return 0 end\n redis.call('ZADD', KEYS[2], ARGV[3], ARGV[2])\n return 1\n`;\nconst PROMOTE = `\n local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 100)\n for _, raw in ipairs(due) do\n redis.call('LPUSH', KEYS[2], raw)\n redis.call('ZREM', KEYS[1], raw)\n end\n return #due\n`;\nconst RECLAIM = `\n if redis.call('EXISTS', KEYS[3]) == 1 then return 0 end\n local moved = 0\n for i = 1, 100 do\n local raw = redis.call('RPOPLPUSH', KEYS[1], KEYS[2])\n if not raw then break end\n moved = moved + 1\n end\n if redis.call('LLEN', KEYS[1]) == 0 then redis.call('SREM', KEYS[4], ARGV[1]) end\n return moved\n`;\nconst RENEW = `\n if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\n return 1\n`;\nconst REGISTER = `\n redis.call('SET', KEYS[1], '1', 'PX', ARGV[2])\n redis.call('SADD', KEYS[2], ARGV[1])\n`;\n// ARGV[1] .. owner is the owner's processing list: `keys().queue.processing(\"\")`.\nconst STATS = `\n local active = 0\n for _, owner in ipairs(redis.call('SMEMBERS', KEYS[3])) do\n active = active + redis.call('LLEN', ARGV[1] .. owner)\n end\n return {redis.call('LLEN', KEYS[1]), active, redis.call('ZCARD', KEYS[2])}\n`;\n\nfunction parseEnvelope(raw: string): Envelope {\n const value: unknown = JSON.parse(raw);\n if (\n value === null ||\n typeof value !== \"object\" ||\n !(\"messageId\" in value) ||\n !(\"queueName\" in value) ||\n !(\"message\" in value) ||\n typeof value.message !== \"string\" ||\n !(\"attempt\" in value) ||\n typeof value.attempt !== \"number\" ||\n !(\"deliveryCount\" in value) ||\n typeof value.deliveryCount !== \"number\" ||\n !(\"createdAt\" in value) ||\n typeof value.createdAt !== \"number\" ||\n !(\"dedupKey\" in value) ||\n typeof value.dedupKey !== \"string\" ||\n !(\"headers\" in value) ||\n value.headers === null ||\n typeof value.headers !== \"object\"\n ) {\n throw new TypeError(\"Invalid Redis queue envelope\");\n }\n const headers: Record<string, string> = {};\n for (const [key, header] of Object.entries(value.headers)) {\n if (typeof header !== \"string\") throw new TypeError(\"Invalid queue header\");\n headers[key] = header;\n }\n return {\n messageId: MessageId.parse(value.messageId),\n queueName: ValidQueueName.parse(value.queueName),\n message: value.message,\n attempt: value.attempt,\n deliveryCount: value.deliveryCount,\n createdAt: value.createdAt,\n dedupKey: value.dedupKey,\n headers,\n ...(\"route\" in value &&\n typeof value.route === \"string\" && { route: value.route }),\n };\n}\n\nexport function createQueue(\n redis: Redis,\n config: ResolvedConfig<RedisWorldConfig>,\n options: WorldQueueOptions = {},\n): WorldQueue {\n const queueKeys = keys(config.keyPrefix).queue;\n const { ready, delayed, workers: owners, processing, heartbeat } = queueKeys;\n const heartbeatTtlMs = config.heartbeatTtlMs ?? 90_000;\n checkInteger(\"heartbeatTtlMs\", heartbeatTtlMs, 300);\n const { queueConcurrency: concurrency, maxAttempts, maxBackoffMs } = config;\n let closed = false;\n let startPromise: Promise<void> | undefined;\n let loop: Promise<void> | undefined;\n let owner: string | undefined;\n const inflight = new Set<Promise<void>>();\n const lostOwners = new Set<string>();\n const abort = new AbortController();\n const sleep = () =>\n delay(50, undefined, { signal: abort.signal }).catch(() => {});\n\n async function enqueue(\n message: Parameters<QueueBackend[\"enqueue\"]>[0],\n opts: Parameters<QueueBackend[\"enqueue\"]>[1],\n ): Promise<MessageId> {\n const dedupKey = opts.idempotencyKey\n ? queueKeys.idempotent(opts.idempotencyKey)\n : \"\";\n const envelope: Envelope = {\n messageId: message.messageId,\n queueName: message.queueName,\n message: message.message,\n attempt: 0,\n deliveryCount: 0,\n createdAt: Date.now(),\n dedupKey,\n headers: message.headers ?? {},\n ...(message.route && { route: message.route }),\n };\n const delayMs = Math.max(0, (opts.delaySeconds ?? 0) * 1000);\n if (!Number.isFinite(delayMs))\n throw new RangeError(\"delaySeconds must be finite\");\n const result = await redis.eval(\n ENQUEUE,\n 3,\n dedupKey || ready,\n ready,\n delayed,\n dedupKey,\n message.messageId,\n config.idempotencyTtlMs ?? 0,\n JSON.stringify(envelope),\n delayMs > 0 ? Date.now() + delayMs : 0,\n );\n return MessageId.parse(result);\n }\n\n async function settle(\n raw: string,\n claimOwner: string,\n deliver: Deliver,\n ): Promise<void> {\n try {\n const job = parseEnvelope(raw);\n let seconds: number | undefined;\n let failed = false;\n try {\n // Reservation persists the attempt before delivery, so a crash\n // redelivery reports one more.\n seconds = await deliver(job);\n } catch (error) {\n failed = true;\n debug(\n `Delivery ${job.messageId} attempt ${job.attempt} failed:`,\n error,\n );\n seconds =\n (job.attempt >= maxAttempts\n ? maxBackoffMs\n : retryDelayMs(job.attempt, config)) / 1000;\n if (job.attempt === maxAttempts)\n console.error(\n `Queue message ${job.messageId} exhausted maxAttempts; retaining it for capped retries`,\n );\n }\n if (seconds === undefined) {\n await redis.eval(\n ACK,\n 3,\n processing(claimOwner),\n job.dedupKey || ready,\n heartbeat(claimOwner),\n raw,\n job.dedupKey,\n job.messageId,\n );\n } else {\n // Only successful reschedules preserve the attempt. A crash always\n // leaves the reserved attempt in Redis, so reclaim counts as failure.\n const next = failed ? job : { ...job, attempt: job.attempt - 1 };\n await redis.eval(\n DEFER,\n 3,\n processing(claimOwner),\n delayed,\n heartbeat(claimOwner),\n raw,\n JSON.stringify(next),\n Date.now() + seconds * 1000,\n );\n }\n } catch (error) {\n // Keep the claim for reclaim on connection loss or malformed data.\n lostOwners.add(claimOwner);\n console.error(\"Queue settlement error:\", error);\n }\n }\n\n async function register(): Promise<string> {\n const next = randomUUID();\n await redis.eval(\n REGISTER,\n 2,\n heartbeat(next),\n owners,\n next,\n heartbeatTtlMs,\n );\n return next;\n }\n\n async function run(deliver: Deliver): Promise<void> {\n let renewedAt = Date.now();\n let maintainedAt = 0;\n let failing = false;\n while (!closed) {\n try {\n for (const lost of lostOwners) {\n await redis.del(heartbeat(lost));\n lostOwners.delete(lost);\n if (owner === lost) owner = undefined;\n }\n if (!owner || Date.now() - renewedAt >= heartbeatTtlMs / 3) {\n // Never resurrect an expired lease: its processing list may already\n // belong to the reclaimer. A fresh UUID fences all old settlements.\n if (\n !owner ||\n (await redis.eval(RENEW, 1, heartbeat(owner), heartbeatTtlMs)) !== 1\n )\n owner = await register();\n renewedAt = Date.now();\n }\n if (Date.now() - maintainedAt >= 100) {\n await redis.eval(PROMOTE, 2, delayed, ready, Date.now());\n for (const stale of await redis.smembers(owners)) {\n if (stale !== owner)\n await redis.eval(\n RECLAIM,\n 4,\n processing(stale),\n ready,\n heartbeat(stale),\n owners,\n stale,\n );\n }\n maintainedAt = Date.now();\n }\n for (\n let reserved = 0;\n reserved < concurrency &&\n !closed &&\n owner &&\n inflight.size < concurrency;\n reserved++\n ) {\n const claimOwner = owner;\n const raw = await redis.eval(\n RESERVE,\n 3,\n ready,\n processing(claimOwner),\n heartbeat(claimOwner),\n );\n if (typeof raw !== \"string\") break;\n const task = settle(raw, claimOwner, deliver);\n inflight.add(task);\n void task.finally(() => inflight.delete(task));\n }\n failing = false;\n } catch (error) {\n // Warn once per outage: a queue that lost Redis otherwise looks idle.\n if (!closed && !failing) console.warn(\"Queue polling failed:\", error);\n else if (!closed) debug(\"Queue polling error:\", error);\n failing = true;\n }\n await sleep();\n }\n }\n\n const backend: QueueBackend = {\n enqueue,\n async getQueueStats() {\n const counts = await redis.eval(\n STATS,\n 3,\n ready,\n delayed,\n owners,\n processing(\"\"),\n );\n if (\n !Array.isArray(counts) ||\n counts.length !== 3 ||\n counts.some((c) => typeof c !== \"number\")\n )\n throw new TypeError(\"Invalid queue statistics\");\n return {\n waiting: Number(counts[0]),\n active: Number(counts[1]),\n delayed: Number(counts[2]),\n completed: 0,\n failed: 0,\n };\n },\n start(deliver) {\n if (closed) return Promise.reject(new Error(\"Queue is closed\"));\n startPromise ??= (async () => {\n owner = await register();\n loop = run(deliver);\n })().catch((error) => {\n startPromise = undefined;\n throw error;\n });\n return startPromise;\n },\n async close() {\n if (closed) return;\n closed = true;\n abort.abort();\n await startPromise;\n await loop;\n // While handlers drain, keep the lease alive. close() must not permit a\n // live long-running handler to be reclaimed merely because shutdown began.\n const timer = setInterval(\n () => {\n if (owner)\n void redis\n .eval(RENEW, 1, heartbeat(owner), heartbeatTtlMs)\n .catch((error) => debug(\"Queue close heartbeat:\", error));\n },\n Math.floor(heartbeatTtlMs / 3),\n );\n try {\n await Promise.all(inflight);\n } finally {\n clearInterval(timer);\n }\n if (owner) {\n await redis.del(heartbeat(owner));\n await redis.eval(\n RECLAIM,\n 4,\n processing(owner),\n ready,\n heartbeat(owner),\n owners,\n owner,\n );\n }\n },\n };\n return createWorldQueue(backend, config, { ...options, debug });\n}\n","import { configFromEnv, type RedisWorldConfig } from \"./config.js\";\nimport { createQueue } from \"./queue.js\";\nimport { debug } from \"./util.js\";\nimport { createRedisBackedWorld, type RedisBackedWorld } from \"./world.js\";\n\n/** `config` is laid over `configFromEnv()`: an option left out comes from the\n * `WORKFLOW_REDIS_*` variables, then the defaults. */\nexport function createWorld(\n config: Partial<RedisWorldConfig> = {},\n): RedisBackedWorld {\n return createRedisBackedWorld(config, {\n env: configFromEnv(),\n createQueue,\n label: \"world-redis\",\n debug,\n });\n}\n\nexport type { RedisWorldConfig } from \"./config.js\";\nexport type { QueueStats } from \"./queue.js\";\nexport type { KeepRuns, RunRetention } from \"./reaper.js\";\n"],"mappings":";;;;;;AA8BA,MAAM,UAAU;;;;;;;;;;;;;;AAchB,MAAM,UAAU;;;;;;;;;;;;AAYhB,MAAM,MAAM;;;;;;;;AAQZ,MAAM,QAAQ;;;;;;AAMd,MAAM,UAAU;;;;;;;;AAQhB,MAAM,UAAU;;;;;;;;;;;AAWhB,MAAM,QAAQ;;;;;AAKd,MAAM,WAAW;;;;AAKjB,MAAM,QAAQ;;;;;;;AAQd,SAAS,cAAc,KAAuB;CAC5C,MAAM,QAAiB,KAAK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,MAAM;GAGN,MAAM,QAAQ,kBACN;IACJ,IAAI,OACG,MACF,KAAK,OAAO,GAAG,UAAU,KAAK,GAAG,cAAc,CAAC,CAChD,OAAO,UAAU,MAAM,0BAA0B,KAAK,CAAC;GAC9D,GACA,KAAK,MAAM,iBAAiB,CAAC,CAC/B;GACA,IAAI;IACF,MAAM,QAAQ,IAAI,QAAQ;GAC5B,UAAU;IACR,cAAc,KAAK;GACrB;GACA,IAAI,OAAO;IACT,MAAM,MAAM,IAAI,UAAU,KAAK,CAAC;IAChC,MAAM,MAAM,KACV,SACA,GACA,WAAW,KAAK,GAChB,OACA,UAAU,KAAK,GACf,QACA,KACF;GACF;EACF;CAE4B,GAAG,QAAQ;EAAE,GAAG;EAAS;CAAM,CAAC;AAChE;;;;AC9ZA,SAAgB,YACd,SAAoC,CAAC,GACnB;CAClB,OAAO,uBAAuB,QAAQ;EACpC,KAAK,cAAc;EACnB;EACA,OAAO;EACP;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"world-783VJfKL.js","names":["redisKeys"],"sources":["../src/internal/debug.ts","../src/util.ts","../src/internal/serialization.ts","../src/run-id.ts","../src/world-queue.ts","../src/reaper.ts","../src/internal/util.ts","../src/storage.ts","../src/streamer.ts","../src/world.ts"],"sourcesContent":["/**\n * Creates a namespaced debug logger.\n * Logs to stderr to avoid corrupting CLI JSON output on stdout.\n *\n * Control via WORKFLOW_DEBUG environment variable:\n * WORKFLOW_DEBUG=1 // Enable all\n * WORKFLOW_DEBUG=redis-world // Named namespaces, comma-separated\n */\nexport function createDebugLogger(namespace: string) {\n return (...args: unknown[]) => {\n const debug = process.env.WORKFLOW_DEBUG;\n if (!debug) return;\n\n const enabled =\n debug === \"1\" ||\n debug === \"true\" ||\n debug === \"*\" ||\n debug.split(\",\").some((ns) => ns.trim() === namespace);\n\n if (!enabled) return;\n\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${namespace}]`;\n const message = args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg, null, 2) : String(arg),\n )\n .join(\" \");\n\n process.stderr.write(`${prefix} ${message}\\n`);\n };\n}\n","import { createDebugLogger } from \"./internal/debug.js\";\n\nexport const debug = createDebugLogger(\"redis-world\");\n","/** Standard Date fields used across all worlds */\nconst DATE_FIELDS = new Set([\n \"createdAt\",\n \"updatedAt\",\n \"startedAt\",\n \"completedAt\",\n \"retryAfter\",\n] as const);\n\n/**\n * JSON reviver that converts ISO date strings to Date objects.\n * Use with JSON.parse(json, dateReviver).\n */\nfunction dateReviver(key: string, value: unknown): unknown {\n if (\n DATE_FIELDS.has(\n key as typeof DATE_FIELDS extends Set<infer T> ? T : never,\n ) &&\n typeof value === \"string\"\n ) {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? value : date;\n }\n return value;\n}\n\n/**\n * JSON replacer that encodes Uint8Array as a tagged object with base64 data.\n */\nfunction uint8ArrayReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return {\n __type: \"Uint8Array\",\n data: Buffer.from(value).toString(\"base64\"),\n };\n }\n return value;\n}\n\n/** The Uint8Array a tagged object (`{ __type: 'Uint8Array', data: '<base64>' }`) encodes. */\nfunction taggedBinary(value: unknown): Uint8Array | undefined {\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (obj.__type === \"Uint8Array\" && typeof obj.data === \"string\") {\n return new Uint8Array(Buffer.from(obj.data, \"base64\"));\n }\n }\n return undefined;\n}\n\n/** JSON reviver that decodes tagged Uint8Array objects and ISO date strings. */\nfunction uint8ArrayReviver(key: string, value: unknown): unknown {\n return taggedBinary(value) ?? dateReviver(key, value);\n}\n\n// Handing JSON a reviver/replacer forces V8 off its fast path and calls into\n// JS for every node. The paths below keep identical semantics while avoiding\n// that: measured ~5x on parse and ~2x on stringify, holding from 6 KB to\n// 700 KB payloads. Wire format is unchanged.\n\n/** The tag `uint8ArrayReviver` decodes. Absent, only dates need reviving. */\nconst BINARY_TAG = '\"__type\"';\n\n/** Revive `DATE_FIELDS` in place at any depth — the same reach as\n * `dateReviver` under `JSON.parse`, just without the per-node JSON interop. */\nfunction reviveDatesDeep(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = reviveDatesDeep(value[i]);\n }\n return value;\n }\n const obj = value as Record<string, unknown>;\n for (const key in obj) {\n const child = obj[key];\n if (DATE_FIELDS.has(key as never) && typeof child === \"string\") {\n const date = new Date(child);\n if (!Number.isNaN(date.getTime())) {\n obj[key] = date;\n continue;\n }\n }\n obj[key] = reviveDatesDeep(child);\n }\n return obj;\n}\n\n/**\n * Is there a `Uint8Array` anywhere in the graph?\n *\n * Must stay exact: `JSON.stringify` turns a bare `Uint8Array` into\n * `{\"0\":1,...}` without complaint, so a miss is data corruption, not a slow\n * path. The walk allocates nothing, which is why it beats the replacer over\n * the same nodes.\n */\nfunction hasBinary(value: unknown): boolean {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n if (value instanceof Uint8Array) {\n return true;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (hasBinary(value[i])) {\n return true;\n }\n }\n return false;\n }\n for (const key in value as Record<string, unknown>) {\n if (hasBinary((value as Record<string, unknown>)[key])) {\n return true;\n }\n }\n return false;\n}\n\n/** Stringify with Uint8Array support. */\nexport function stringify(value: unknown): string {\n return hasBinary(value)\n ? JSON.stringify(value, uint8ArrayReplacer)\n : JSON.stringify(value);\n}\n\n/** Parse with Uint8Array and Date support. */\nexport function parse<T>(text: string): T {\n if (text.includes(BINARY_TAG)) {\n return JSON.parse(text, uint8ArrayReviver) as T;\n }\n return reviveDatesDeep(JSON.parse(text)) as T;\n}\n\n/**\n * Parse a queue message: tagged Uint8Arrays only. Queue payloads are the\n * runtime's own, so a field that happens to be named like a date stays a string.\n */\nexport function parseQueueMessage(text: string): unknown {\n return text.includes(BINARY_TAG)\n ? JSON.parse(text, (_key, value) => taggedBinary(value) ?? value)\n : JSON.parse(text);\n}\n","import { createHash } from \"node:crypto\";\nimport { encodeTime, ulid } from \"ulid\";\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst MAX_TIME = 2 ** 48 - 1;\nconst MAX_KEY_LENGTH = 1024;\n\nfunction keyedRandomness(key: string): string {\n const digest = createHash(\"sha256\").update(key).digest();\n let bits = 0n;\n for (let index = 0; index < 10; index++)\n bits = (bits << 8n) | BigInt(digest[index]);\n let out = \"\";\n for (let group = 15; group >= 0; group--)\n out += CROCKFORD[Number((bits >> BigInt(group * 5)) & 31n)];\n return out;\n}\n\n/**\n * The run id the SDK asks the world for when a run starts. Without options it is\n * a fresh ULID. With `runKey` and `runKeyTime` it is the same ULID every time, so\n * starting the same run twice creates one run: the second start finds it already\n * there.\n *\n * The id is a real ULID. Its time is `runKeyTime`, not the clock, because the SDK\n * seeds a workflow's clock from the time in its run id. Pass the time the run is\n * for, such as when the event it handles happened, and the same time on every\n * attempt.\n *\n * @param options - The options given to `start()`. `runKey` is a non-empty string\n * that names the run (at most 1024 characters), and `runKeyTime` is milliseconds\n * since the epoch.\n * @returns The id without its `wrun_` prefix, which the SDK adds.\n * @throws When `runKey` is not a usable string, or comes without a valid `runKeyTime`.\n */\nexport function createRunId(\n options?: Readonly<Record<string, unknown>>,\n): string {\n const key = options?.runKey;\n if (key === undefined) return ulid();\n if (typeof key !== \"string\" || !key || key.length > MAX_KEY_LENGTH)\n throw new TypeError(\n `runKey must be a non-empty string of at most ${MAX_KEY_LENGTH} characters`,\n );\n const time = options?.runKeyTime;\n if (\n typeof time !== \"number\" ||\n !Number.isInteger(time) ||\n time < 0 ||\n time > MAX_TIME\n )\n throw new TypeError(\n \"runKey needs runKeyTime, the time the run is for in milliseconds since the epoch, so the run id stays a valid ULID with a true time\",\n );\n return encodeTime(time, 10) + keyedRandomness(key);\n}\n\n/**\n * The idempotency key for the message that starts a run, which is the only\n * message that carries the run's input. `start()` sends no key of its own, so a\n * second start of the same run would otherwise queue a second first delivery.\n *\n * The key only covers a first message that is still queued or running. Once the\n * run has started, the queue does not enqueue the message at all (see\n * `runHasStarted` in `createWorldQueue`): the runtime runs a run's first step from the\n * first message, in parallel with `run_created`, so a late second one would run\n * that step's code again.\n *\n * @param message - The queue payload.\n * @returns A key for a run's first message, and `undefined` for every other message.\n */\nexport function initialMessageKey(message: unknown): string | undefined {\n const { runId, runInput } = (message ?? {}) as {\n runId?: unknown;\n runInput?: unknown;\n };\n return typeof runId === \"string\" && runInput !== undefined\n ? `start:${runId}`\n : undefined;\n}\n","import {\n MessageId,\n parseQueueName,\n parseQueueRoute,\n type Queue,\n type QueuePrefix,\n type ValidQueueName,\n} from \"@workflow/world\";\nimport {\n createAppRouteUrl,\n createWorkflowBaseUrl,\n createWorkflowUrl,\n} from \"@workflow/utils\";\nimport { monotonicFactory } from \"ulid\";\nimport type { RedisBackedWorldConfig, ResolvedConfig } from \"./config.js\";\nimport { parseQueueMessage, stringify } from \"./internal/serialization.js\";\nimport { initialMessageKey } from \"./run-id.js\";\n\nexport interface QueueStats {\n waiting: number;\n active: number;\n delayed: number;\n /** Finished delivery records the queue still holds; redis-world keeps none. */\n completed: number;\n failed: number;\n}\n\n/** A message as a queue backend stores it. */\nexport interface QueuedMessage {\n messageId: MessageId;\n queueName: ValidQueueName;\n /** The payload, already serialized; forwarded verbatim as the request body. */\n message: string;\n /** Extra headers the producer asked to forward; the `x-vqs-*` ones override them. */\n headers?: Record<string, string>;\n /** The route registered for this prefix when it was queued (`registerRoute`). */\n route?: string;\n}\n\n/** One delivery of a stored message, with the counters the backend keeps. */\nexport interface Delivery extends QueuedMessage {\n /** Failed deliveries plus this one, crashes included; reschedules don't count. */\n attempt: number;\n /** Every delivery that reached a handler, reschedules included. */\n deliveryCount: number;\n /** When the message was first queued (epoch ms). */\n createdAt: number;\n}\n\n/**\n * Delivers a message to its handler. Resolves to the seconds after which the\n * same message is to be delivered again without consuming an attempt, or\n * `undefined` to acknowledge it. Throws when the delivery failed and must be\n * retried.\n */\nexport type Deliver = (delivery: Delivery) => Promise<number | undefined>;\n\n/** The part of a world's queue that differs between Redis queue implementations. */\nexport interface QueueBackend {\n /** Store a message. Resolves to the id of the queued message: on an\n * `idempotencyKey` hit, the one already queued. */\n enqueue(\n message: QueuedMessage,\n opts: { idempotencyKey?: string; delaySeconds?: number },\n ): Promise<MessageId>;\n /** Start delivering stored messages through `deliver`. */\n start(deliver: Deliver): Promise<void>;\n close(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n}\n\nexport type WorldQueue = Queue & {\n start(): Promise<void>;\n close(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n};\n\nexport interface WorldQueueOptions {\n /**\n * Whether a run has moved past `pending`. The first message of a run is not\n * queued again once it has, see `initialMessageKey`.\n */\n runHasStarted?: (runId: string) => Promise<boolean>;\n}\n\n/** A response without a valid `{ timeoutSeconds }` acknowledges the message. */\nfunction parseReschedule(text: string): number | undefined {\n try {\n const seconds: unknown = JSON.parse(text)?.timeoutSeconds;\n if (typeof seconds === \"number\" && Number.isFinite(seconds) && seconds >= 0)\n return seconds;\n } catch {\n /* not a reschedule */\n }\n return undefined;\n}\n\n/**\n * The Workflow SDK `Queue` on top of a backend: message ids, the first-message\n * guard, the payload transport, HTTP or in-process delivery with the `x-vqs-*`\n * headers, and the handler that answers those deliveries.\n */\nexport function createWorldQueue(\n backend: QueueBackend,\n config: Pick<\n ResolvedConfig<RedisBackedWorldConfig>,\n \"baseUrl\" | \"httpTimeoutMs\"\n >,\n options: WorldQueueOptions & { debug: (...args: unknown[]) => void },\n): WorldQueue {\n const { debug } = options;\n const generateMessageId = monotonicFactory();\n const { httpTimeoutMs } = config;\n const directHandlers = new Map<\n QueuePrefix,\n (req: Request) => Promise<Response>\n >();\n const routes = new Map<QueuePrefix, string>();\n let closed = false;\n\n const queue: Queue[\"queue\"] = async (queueName, message, opts) => {\n if (closed) throw new Error(\"Queue is closed\");\n const { prefix } = parseQueueName(queueName);\n const messageId = MessageId.parse(`msg_${generateMessageId()}`);\n const idempotencyKey = opts?.idempotencyKey ?? initialMessageKey(message);\n if (\n !opts?.idempotencyKey &&\n idempotencyKey &&\n (await options.runHasStarted?.((message as { runId: string }).runId))\n ) {\n debug(\"run already started, not queueing its first message again\", {\n runId: (message as { runId: string }).runId,\n });\n return { messageId };\n }\n const route = routes.get(prefix);\n return {\n messageId: await backend.enqueue(\n {\n messageId,\n queueName,\n // Tagged JSON keeps Uint8Array values (e.g. the resilient-start\n // runInput.input) intact through the backend's own JSON.\n message: stringify(message),\n ...(opts?.headers && { headers: opts.headers }),\n ...(route && { route }),\n },\n { idempotencyKey, delaySeconds: opts?.delaySeconds },\n ),\n };\n };\n\n const deliver: Deliver = async (job) => {\n const { prefix } = parseQueueName(job.queueName);\n const headers = new Headers(job.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(\"x-vqs-queue-name\", job.queueName);\n headers.set(\"x-vqs-message-id\", job.messageId);\n headers.set(\"x-vqs-message-attempt\", String(job.attempt));\n headers.set(\"x-vqs-message-delivery-count\", String(job.deliveryCount));\n headers.set(\n \"x-vqs-message-created-at\",\n new Date(job.createdAt).toISOString(),\n );\n\n const deliveryRoute = routes.get(prefix) ?? job.route;\n const directHandler = directHandlers.get(prefix);\n\n let response: Response;\n if (directHandler) {\n // In process: the request a route serving `createQueueHandler(prefix, ...)`\n // would receive, without the network hop.\n const localBase = createWorkflowBaseUrl(\"http://localhost\");\n response = await directHandler(\n new Request(\n deliveryRoute\n ? createAppRouteUrl(localBase, deliveryRoute)\n : createWorkflowUrl(localBase, { type: \"flow\" }),\n { method: \"POST\", headers, body: job.message },\n ),\n );\n } else {\n const baseUrl =\n config.baseUrl ||\n process.env.WORKFLOW_BASE_URL ||\n `http://localhost:${process.env.PORT ?? \"3000\"}`;\n response = await fetch(\n deliveryRoute\n ? createAppRouteUrl(baseUrl, deliveryRoute)\n : createWorkflowUrl(baseUrl, { type: \"flow\" }),\n {\n method: \"POST\",\n headers,\n body: job.message,\n signal: AbortSignal.timeout(httpTimeoutMs),\n },\n );\n }\n\n const text = await response.text();\n if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);\n return parseReschedule(text);\n };\n\n const createQueueHandler: Queue[\"createQueueHandler\"] = (\n queueNamePrefix,\n handler,\n ) => {\n return async (req) => {\n const queueName = req.headers.get(\n \"x-vqs-queue-name\",\n ) as ValidQueueName | null;\n const messageId = req.headers.get(\"x-vqs-message-id\") as MessageId | null;\n const attemptStr = req.headers.get(\"x-vqs-message-attempt\");\n const deliveryCountStr = req.headers.get(\"x-vqs-message-delivery-count\");\n const createdAtStr = req.headers.get(\"x-vqs-message-created-at\");\n\n if (!queueName || !messageId || !attemptStr || !req.body) {\n return Response.json(\n { error: \"Missing required headers or body\" },\n { status: 400 },\n );\n }\n if (!queueName.startsWith(queueNamePrefix)) {\n return Response.json({ error: \"Unhandled queue\" }, { status: 400 });\n }\n\n const attempt = Number.parseInt(attemptStr, 10);\n const deliveryCount = deliveryCountStr\n ? Number.parseInt(deliveryCountStr, 10)\n : attempt;\n const createdAt = createdAtStr ? new Date(createdAtStr) : undefined;\n\n try {\n const body = parseQueueMessage(await req.text());\n const result = await handler(body, {\n attempt,\n deliveryCount,\n ...(createdAt && !Number.isNaN(createdAt.getTime()) && { createdAt }),\n queueName,\n messageId,\n });\n\n const timeoutSeconds = (\n result as { timeoutSeconds?: unknown } | null | undefined\n )?.timeoutSeconds;\n if (\n typeof timeoutSeconds === \"number\" &&\n Number.isFinite(timeoutSeconds)\n ) {\n return Response.json({ timeoutSeconds: Math.max(0, timeoutSeconds) });\n }\n return Response.json({ ok: true });\n } catch (error) {\n debug(\"queue handler error:\", error);\n return Response.json({ error: String(error) }, { status: 500 });\n }\n };\n };\n\n return {\n queue,\n createQueueHandler,\n getDeploymentId: async () => \"redis\",\n registerHandler(prefix, handler) {\n directHandlers.set(prefix, handler);\n },\n registerRoute(prefix, path) {\n routes.set(prefix, parseQueueRoute(path));\n },\n getQueueStats: () => backend.getQueueStats(),\n start: () => backend.start(deliver),\n async close() {\n closed = true;\n await backend.close();\n },\n };\n}\n\n/** The delay before retrying a failed delivery: the configured curve, capped. */\nexport function retryDelayMs(\n attempt: number,\n config: Pick<\n ResolvedConfig<RedisBackedWorldConfig>,\n \"backoffType\" | \"backoffDelayMs\" | \"maxBackoffMs\"\n >,\n): number {\n const delay =\n config.backoffType === \"fixed\"\n ? config.backoffDelayMs\n : config.backoffDelayMs * 2 ** Math.min(30, Math.max(0, attempt - 1));\n return Math.min(config.maxBackoffMs, delay);\n}\n","import type { Redis } from \"ioredis\";\nimport { keys as redisKeys } from \"./keys.js\";\n\n/** How long finished runs are kept, using `age` and `count` limits. */\nexport interface KeepRuns {\n /** Delete runs that finished more than this many seconds ago. */\n age?: number;\n /** Keep at most this many of the newest runs; delete the rest. */\n count?: number;\n}\n\n/**\n * Retention for run data (the run, its event log, steps, hooks, and streams),\n * per terminal status. A status without a policy is kept forever.\n */\nexport interface RunRetention {\n completed?: KeepRuns;\n failed?: KeepRuns;\n cancelled?: KeepRuns;\n /** How often each worker looks for expired runs (ms). Default: 60000 */\n sweepIntervalMs?: number;\n /** Runs deleted per status per sweep. Default: 200 */\n batchSize?: number;\n}\n\nconst TERMINAL = [\"completed\", \"failed\", \"cancelled\"] as const;\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\nconst DEFAULT_BATCH_SIZE = 200;\nconst UNLINK_CHUNK = 500;\n\nexport interface Reaper {\n start(): void;\n stop(): Promise<void>;\n /** One pass over every status; returns the number of runs deleted. */\n sweep(): Promise<number>;\n}\n\nexport function validateRetention(retention: RunRetention | undefined): void {\n if (!retention) return;\n for (const status of TERMINAL) {\n const keep = retention[status];\n if (!keep) continue;\n for (const field of [\"age\", \"count\"] as const) {\n const value = keep[field];\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new TypeError(\n `retention.${status}.${field} must be a non-negative integer, received ${String(value)}`,\n );\n }\n }\n }\n for (const field of [\"sweepIntervalMs\", \"batchSize\"] as const) {\n const value = retention[field];\n if (value !== undefined && (!Number.isInteger(value) || value < 1)) {\n throw new TypeError(\n `retention.${field} must be a positive integer, received ${String(value)}`,\n );\n }\n }\n}\n\nexport function hasRetention(\n retention: RunRetention | undefined,\n): retention is RunRetention {\n return (\n !!retention && TERMINAL.some((status) => retention[status] !== undefined)\n );\n}\n\n/**\n * Deletes finished runs once they pass their retention. Safe to run on every\n * worker: one lock per interval picks a single sweeper, and deleting a run is\n * idempotent anyway. A run's own key and index entries go last, in one\n * transaction, so a crash part-way leaves the run listed and the next sweep\n * finishes the job.\n */\nexport function createReaper(options: {\n redis: Redis;\n keyPrefix: string;\n retention: RunRetention;\n}): Reaper {\n const { redis, keyPrefix, retention } = options;\n const intervalMs = retention.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;\n const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;\n const k = redisKeys(keyPrefix);\n const byStatusKey = k.runsByStatusKey;\n let timer: NodeJS.Timeout | undefined;\n let running: Promise<unknown> = Promise.resolve();\n\n /** Runs past retention, oldest first: too old, or beyond the newest `count`. */\n async function expired(status: (typeof TERMINAL)[number]): Promise<string[]> {\n const keep = retention[status];\n if (!keep) return [];\n const ids = new Set<string>();\n if (keep.age !== undefined) {\n const cutoff = Date.now() - keep.age * 1000;\n for (const id of await redis.zrangebyscore(\n byStatusKey(status),\n \"-inf\",\n cutoff,\n \"LIMIT\",\n 0,\n batchSize,\n )) {\n ids.add(id);\n }\n }\n if (keep.count !== undefined) {\n // Everything below the newest `count`, oldest first.\n const stop = -(keep.count + 1);\n for (const id of await redis.zrange(\n byStatusKey(status),\n \"0\",\n String(stop),\n )) {\n if (ids.size >= batchSize) break;\n ids.add(id);\n }\n }\n return [...ids].slice(0, batchSize);\n }\n\n async function unlink(keys: string[]): Promise<void> {\n for (let i = 0; i < keys.length; i += UNLINK_CHUNK) {\n await redis.unlink(...keys.slice(i, i + UNLINK_CHUNK));\n }\n }\n\n async function scan(pattern: string): Promise<string[]> {\n const found: string[] = [];\n let cursor = \"0\";\n do {\n const [next, batch] = await redis.scan(\n cursor,\n \"MATCH\",\n pattern,\n \"COUNT\",\n 1000,\n );\n cursor = next;\n found.push(...batch);\n } while (cursor !== \"0\");\n return found;\n }\n\n /** Delete one run if it is still finished. Returns whether it was deleted. */\n async function deleteRun(runId: string, listedAs: string): Promise<boolean> {\n const metaKey = k.runMetaKey(runId);\n const meta = await redis.get(metaKey);\n const status = meta?.split(\"|\")[0];\n if (!status || !(TERMINAL as readonly string[]).includes(status)) {\n // Gone: drop the stale index entry. Moved on to a live status: leave it alone.\n if (!meta) await redis.zrem(byStatusKey(listedAs), runId);\n return false;\n }\n\n const runKey = k.runKey(runId);\n const runJson = await redis.get(runKey);\n const workflowName = runJson\n ? (JSON.parse(runJson) as { workflowName?: string }).workflowName\n : undefined;\n\n const eventsKey = k.eventsKey(runId);\n const correlationIds = new Set<string>();\n let hasResume = false;\n for (const raw of await redis.hvals(eventsKey)) {\n try {\n const event = JSON.parse(raw) as {\n correlationId?: string;\n eventType?: string;\n };\n if (event.correlationId) correlationIds.add(event.correlationId);\n if (event.eventType === \"hook_received\") hasResume = true;\n } catch {\n // An unreadable event still goes with the log key.\n }\n }\n\n const stepIds = await redis.zrange(k.stepsIndexKey(runId), \"0\", \"-1\");\n const hookIds = await redis.zrange(k.hooksIndexKey(runId), \"0\", \"-1\");\n const streamNames = await redis.smembers(k.streamsByRunKey(runId));\n\n const keys = k.ownedByRun(runId, {\n correlationIds,\n stepIds,\n hookIds,\n streamNames,\n });\n // Resume claims are not indexed; only a run that received a hook payload can have one.\n if (hasResume) keys.push(...(await scan(k.resumeClaimKey(runId, \"*\"))));\n await unlink(keys);\n\n const tx = redis\n .multi()\n .zrem(k.runsIndexKey(), runId)\n .zrem(byStatusKey(status), runId)\n .unlink(metaKey, runKey);\n if (workflowName) tx.zrem(k.runsByNameKey(workflowName), runId);\n await tx.exec();\n return true;\n }\n\n async function sweep(): Promise<number> {\n // One sweeper per interval; the lock simply expires.\n const locked = await redis.set(\n k.reaperLockKey,\n \"1\",\n \"PX\",\n Math.max(1000, Math.floor(intervalMs / 2)),\n \"NX\",\n );\n if (locked !== \"OK\") return 0;\n let deleted = 0;\n for (const status of TERMINAL) {\n for (const runId of await expired(status)) {\n try {\n if (await deleteRun(runId, status)) deleted++;\n } catch (err) {\n console.warn(`Retention: could not delete run ${runId}:`, err);\n }\n }\n }\n return deleted;\n }\n\n return {\n sweep,\n start() {\n if (timer) return;\n const tick = () => {\n running = sweep().catch((err) =>\n console.warn(\"Retention sweep failed:\", err),\n );\n };\n timer = setInterval(tick, intervalMs);\n timer.unref();\n },\n async stop() {\n if (timer) clearInterval(timer);\n timer = undefined;\n await running;\n },\n };\n}\n","export function compact<T extends object>(obj: T) {\n const value = {} as {\n [key in keyof T]: null extends T[key]\n ? undefined | NonNullable<T[key]>\n : T[key];\n };\n for (const key in obj) {\n if (obj[key] !== null) {\n value[key] = obj[key] as any;\n } else {\n value[key] = undefined as any;\n }\n }\n return value;\n}\n","import {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from \"@workflow/errors\";\nimport type {\n AttributeChange,\n CreateEventParams,\n CreateEventRequest,\n Event,\n EventListResponse,\n EventResult,\n EventsResolveData,\n GetEventParams,\n GetHookParams,\n GetStepParams,\n GetWorkflowRunParams,\n Hook,\n ListEventsByCorrelationIdParams,\n ListEventsParams,\n ListHooksParams,\n ListWorkflowRunStepsParams,\n ListWorkflowRunsParams,\n PaginatedResponse,\n ResolveData,\n RunCreatedEventRequest,\n Step,\n StepWithoutData,\n Storage,\n WorkflowRun,\n WorkflowRunWithoutData,\n} from \"@workflow/world\";\nimport {\n entityResolveData,\n EventSchema,\n eventIdToSlot,\n FIRST_EVENT_SLOT,\n HookSchema,\n isLegacySpecVersion,\n mintedSpecVersion,\n requiresNewerWorld,\n slotToEventId,\n StepSchema,\n stripEventDataRefs,\n validateAttributeChanges,\n WorkflowRunSchema,\n} from \"@workflow/world\";\nimport { globalSingleton } from \"@workflow/utils\";\nimport type { Redis } from \"ioredis\";\nimport { monotonicFactory } from \"ulid\";\nimport { keys } from \"./keys.js\";\nimport { compact } from \"./internal/util.js\";\n// `parse`/`stringify` take a fast path that skips JSON's reviver/replacer when\n// the payload holds no binary (~5x on parse, ~2x on stringify) with identical\n// semantics.\nimport { parse, stringify } from \"./internal/serialization.js\";\n\ninterface RedisStorageConfig {\n redis: Redis;\n keyPrefix: string;\n /** See `RedisWorldConfig.maxEventsPerRun`. */\n maxEventsPerRun?: number;\n}\n\n/** Per-run event ceiling reported to core, mirroring the Vercel World. */\nconst DEFAULT_MAX_EVENTS_PER_RUN = 25_000;\n\n/** Resolve the per-run event ceiling surfaced as `EventResult.maxEvents`:\n * explicit config, then `WORKFLOW_MAX_EVENTS`, then the default. A\n * non-positive configured value throws rather than being ignored. */\nfunction resolveMaxEventsPerRun(configured: number | undefined): number {\n if (configured !== undefined) {\n if (!Number.isInteger(configured) || configured <= 0) {\n throw new TypeError(\n `maxEventsPerRun must be a positive integer, received ${String(configured)}`,\n );\n }\n return configured;\n }\n const raw = process.env.WORKFLOW_MAX_EVENTS;\n const parsed = raw !== undefined ? Number(raw) : Number.NaN;\n return Number.isInteger(parsed) && parsed > 0\n ? parsed\n : DEFAULT_MAX_EVENTS_PER_RUN;\n}\n\n/** Events that mutate the run, so validation needs its full body. Everything\n * else only reads status/specVersion and is served from the run meta key. */\nconst RUN_LIFECYCLE_EVENT_TYPES = new Set([\n \"run_started\",\n \"run_completed\",\n \"run_failed\",\n \"run_cancelled\",\n]);\n\n/** Sentinel from the event scripts when a creation-dedup check rejects. */\nconst LUA_DUPLICATE_CREATION = -8;\n\n/**\n * Stand-in for the event id inside the event JSON the caller hands to a script.\n * The id is a log position (`evnt_` + the 1-based slot), and a position may only\n * be chosen at the commit (see `LUA_APPEND_EVENT`), so the script writes it into\n * the JSON itself. `serializeEvent` always emits `eventId` as the first key, so\n * the first match is ours whatever the payload holds. A constant, not a random\n * value: two bundled copies of this module can share one connection's scripts.\n */\nconst EVENT_ID_PLACEHOLDER = \"__brick_event_id__\";\n\n/**\n * Lua helper shared by every script that appends to a run's event log.\n *\n * A run's events live in one hash, `eventId -> JSON`. The log is dense and\n * 1-based, and a script runs atomically, so the next slot is the hash length\n * plus one and no other writer can interleave between reading it and writing the\n * event. That is the whole race story: the slot is chosen at the commit, in the\n * same operation that appends, and a writer that is behind simply lands on the\n * next free slot (the caller reports what it skipped).\n *\n * `appendEvent(eventsKey, correlationKey, json)` returns the new event id.\n * `correlationKey` may be nil. The id is written into `json` in place of the\n * placeholder, so what is stored is exactly what the reader parses.\n */\nconst LUA_APPEND_EVENT = `\nlocal function appendEvent(eventsKey, correlationKey, json)\n local slot = redis.call('HLEN', eventsKey) + 1\n local digits = string.format('%d', slot)\n local eventId = 'evnt_' .. string.rep('0', 26 - #digits) .. digits\n local from, to = string.find(json, '${EVENT_ID_PLACEHOLDER}', 1, true)\n json = string.sub(json, 1, from - 1) .. eventId .. string.sub(json, to + 1)\n redis.call('HSET', eventsKey, eventId, json)\n if correlationKey then\n redis.call('ZADD', correlationKey, slot, eventId)\n end\n return eventId\nend\n\n-- A run's status from its meta key ('<status>|<specVersion>'), or false when absent.\nlocal function runStatus(metaKey)\n local meta = redis.call('GET', metaKey)\n if not meta then\n return false\n end\n return string.match(meta, '^([^|]*)')\nend\n\nlocal function isTerminal(status)\n return status == 'completed' or status == 'failed' or status == 'cancelled'\nend\n`;\n\n/**\n * Filter hook data based on resolveData parameter\n */\nfunction filterHookData(hook: Hook, resolveData: ResolveData): Hook {\n if (resolveData === \"none\" && \"metadata\" in hook) {\n const { metadata: _, ...rest } = hook;\n return { metadata: undefined, ...rest };\n }\n return hook;\n}\n\nfunction filterStepData(step: Step, resolveData: \"none\"): StepWithoutData;\nfunction filterStepData(step: Step, resolveData: \"all\"): Step;\nfunction filterStepData(\n step: Step,\n resolveData: ResolveData,\n): Step | StepWithoutData;\nfunction filterStepData(\n step: Step,\n resolveData: ResolveData,\n): Step | StepWithoutData {\n if (resolveData === \"none\") {\n const { input: _, output: __, ...rest } = step;\n return { input: undefined, output: undefined, ...rest };\n }\n return step;\n}\n\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: \"none\",\n): WorkflowRunWithoutData;\nfunction filterRunData(run: WorkflowRun, resolveData: \"all\"): WorkflowRun;\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: ResolveData,\n): WorkflowRun | WorkflowRunWithoutData;\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: ResolveData,\n): WorkflowRun | WorkflowRunWithoutData {\n if (resolveData === \"none\") {\n const { input: _, output: __, ...rest } = run;\n return { input: undefined, output: undefined, ...rest };\n }\n return run;\n}\n\n// Each script encapsulates a multi-key write operation to ensure\n// atomicity. Lua scripts execute as a single atomic operation in\n// Redis, preventing partial writes on connection failures AND\n// check-then-write races between concurrent replays: every\n// entity-creating event writes its entity and its creation event in ONE\n// script, so no probe-then-append window exists (same design as\n// world-redis).\n\n/** One member of an index page, with the cursor that resumes after it. */\ninterface IndexEntry {\n id: string;\n score: number;\n cursor: string;\n}\n\n/**\n * Read up to `want` members of one or more sorted-set indexes, in score order,\n * resuming after `cursor`. With several indexes the members are merged into one\n * ordering, which is how a listing across statuses avoids scanning an index of\n * every run there has ever been.\n *\n * A cursor is the last member's `<score>|<id>`, not its rank: a rank means\n * nothing once that member has left the index (a run that changed status, a\n * hook that was disposed), and paging would fail halfway through a listing. A\n * position by score and id stays valid wherever the member went. Members that\n * share a score are ordered by id, as Redis orders them.\n */\nasync function pageIndex(\n redis: Redis,\n indexKeys: string | string[],\n cursor: string | undefined,\n want: number,\n order: \"asc\" | \"desc\" = \"desc\",\n): Promise<IndexEntry[]> {\n let after: { score: number; id: string } | undefined;\n if (cursor) {\n const sep = cursor.indexOf(\"|\");\n const score = sep > 0 ? Number(cursor.slice(0, sep)) : Number.NaN;\n if (Number.isNaN(score)) {\n throw new WorkflowWorldError(`Invalid pagination cursor \"${cursor}\"`, {\n status: 400,\n });\n }\n after = { score, id: cursor.slice(sep + 1) };\n }\n const bound = after\n ? String(after.score)\n : order === \"desc\"\n ? \"+inf\"\n : \"-inf\";\n\n const readOne = async (indexKey: string): Promise<IndexEntry[]> => {\n const out: IndexEntry[] = [];\n const batch = Math.max(want, 50);\n let offset = 0;\n while (out.length < want) {\n const raw =\n order === \"desc\"\n ? await redis.zrevrangebyscore(\n indexKey,\n bound,\n \"-inf\",\n \"WITHSCORES\",\n \"LIMIT\",\n offset,\n batch,\n )\n : await redis.zrangebyscore(\n indexKey,\n bound,\n \"+inf\",\n \"WITHSCORES\",\n \"LIMIT\",\n offset,\n batch,\n );\n for (let i = 0; i < raw.length && out.length < want; i += 2) {\n const id = raw[i];\n const score = Number(raw[i + 1]);\n // Entries that share the cursor's score and come at or before its id were\n // on an earlier page.\n if (\n after &&\n score === after.score &&\n (order === \"desc\" ? id >= after.id : id <= after.id)\n ) {\n continue;\n }\n out.push({ id, score, cursor: `${raw[i + 1]}|${id}` });\n }\n offset += raw.length / 2;\n if (raw.length / 2 < batch) break;\n }\n return out;\n };\n\n const keys = Array.isArray(indexKeys) ? indexKeys : [indexKeys];\n if (keys.length === 1) return readOne(keys[0]);\n\n const merged = (await Promise.all(keys.map(readOne))).flat();\n const direction = order === \"desc\" ? -1 : 1;\n merged.sort(\n (x, y) =>\n direction *\n (x.score - y.score || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0)),\n );\n return merged.slice(0, want);\n}\n\n/**\n * Atomically create a run entity with all its indexes AND its creation\n * event. SETNX arbitrates duplicates: when the run already exists, NO\n * index, meta, or event write happens (a replayed run_created must not\n * reset index scores, re-insert a terminal run into the pending status\n * index, or append a second creation event).\n *\n * KEYS[1] = run key\n * KEYS[2] = runs index key\n * KEYS[3] = runs by name key\n * KEYS[4] = runs by status key (pending)\n * KEYS[5] = run meta key\n * KEYS[6] = events key (the run's log)\n * KEYS[7] = run attributes key\n * ARGV[1] = run JSON\n * ARGV[2] = run ID\n * ARGV[3] = score (timestamp)\n * ARGV[4] = run meta value (`<status>|<specVersion>`)\n * ARGV[5] = event JSON (event id left as the placeholder)\n * ARGV[6..] = attribute key, value pairs to seed\n * Returns: [1, eventId] when created, [0, runJson] on replay.\n */\nconst LUA_CREATE_RUN_WITH_EVENT = `${LUA_APPEND_EVENT}\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n local score = tonumber(ARGV[3])\n redis.call('ZADD', KEYS[2], score, ARGV[2])\n redis.call('ZADD', KEYS[3], score, ARGV[2])\n redis.call('ZADD', KEYS[4], score, ARGV[2])\n redis.call('SET', KEYS[5], ARGV[4])\n for i = 6, #ARGV, 2 do\n redis.call('HSET', KEYS[7], ARGV[i], ARGV[i + 1])\n end\n return {1, appendEvent(KEYS[6], nil, ARGV[5])}\n`;\n\n/**\n * Move a run to a new status, release its hooks when it finishes, and append the\n * lifecycle event, all in one execution. They are one script because a crash\n * between them would leave a terminal run with no terminal event (every retry is\n * then refused as terminal) or a started run with no `run_started` (the redelivery\n * takes the resume path and appends nothing).\n *\n * KEYS[1] = run key\n * KEYS[2] = old status index key\n * KEYS[3] = new status index key\n * KEYS[4] = run meta key\n * KEYS[5] = events key\n * KEYS[6] = hooks index key\n * KEYS[7] = hooks token-map key\n * ARGV[1] = updated run JSON\n * ARGV[2] = run ID\n * ARGV[3] = score (timestamp)\n * ARGV[4] = run meta value (`<status>|<specVersion>`)\n * ARGV[5] = the status the caller read the run in\n * ARGV[6] = event JSON\n * ARGV[7] = \"1\" to release the run's hooks (a terminal transition)\n * ARGV[8] = hook key prefix\n * ARGV[9] = hooks-by-token key prefix\n * Returns: [1, eventId] on success, [0, ''] if the run is absent, [-2, status] if\n * the run is no longer in the status the caller read (another writer\n * moved it first; nothing is written)\n */\nconst LUA_TRANSITION_RUN = `${LUA_APPEND_EVENT}\n if redis.call('EXISTS', KEYS[1]) == 0 then\n return {0, ''}\n end\n\n local current = runStatus(KEYS[4])\n if current and current ~= ARGV[5] then\n return {-2, current}\n end\n\n redis.call('SET', KEYS[1], ARGV[1])\n redis.call('SET', KEYS[4], ARGV[4])\n redis.call('ZREM', KEYS[2], ARGV[2])\n redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])\n\n if ARGV[7] == '1' then\n local pairsFlat = redis.call('HGETALL', KEYS[7])\n for i = 1, #pairsFlat, 2 do\n local hookId = pairsFlat[i]\n local tokenKey = ARGV[9] .. pairsFlat[i + 1]\n redis.call('DEL', ARGV[8] .. hookId)\n -- Only a token this hook still owns: a stale entry must not wipe a claim\n -- another run has taken since.\n if redis.call('GET', tokenKey) == hookId then\n redis.call('DEL', tokenKey)\n end\n end\n redis.call('DEL', KEYS[7])\n redis.call('DEL', KEYS[6])\n end\n\n return {1, appendEvent(KEYS[5], nil, ARGV[6])}\n`;\n\n/**\n * Atomically create a step entity with its index AND its creation event.\n * SETNX arbitrates duplicates: a replayed step_created writes nothing. A step is\n * never created on a finished run.\n *\n * KEYS[1] = step key\n * KEYS[2] = steps index key\n * KEYS[3] = events key\n * KEYS[4] = events by correlation key\n * KEYS[5] = step status key (see `LUA_STORE_EVENT`)\n * KEYS[6] = run meta key\n * ARGV[1] = step JSON\n * ARGV[2] = step ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = event JSON\n * ARGV[5] = step status value (`<status>|<attempt>`)\n * Returns: [1, eventId] when created, [0, stepJson] on replay, [-6, status] when\n * the run is terminal\n */\nconst LUA_CREATE_STEP_WITH_EVENT = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])\n redis.call('SET', KEYS[5], ARGV[5])\n return {1, appendEvent(KEYS[3], KEYS[4], ARGV[4])}\n`;\n\n/**\n * Lazy step start: a `step_started` that carries the step's input also creates\n * the step. The step entity (already running, attempt 1), the synthetic\n * `step_created` and the `step_started` land together, so replay still sees the\n * creation, and exactly one concurrent caller wins the SETNX and runs the body.\n *\n * KEYS[1] = step key\n * KEYS[2] = steps index key\n * KEYS[3] = events key\n * KEYS[4] = events by correlation key\n * KEYS[5] = step status key (see `LUA_STORE_EVENT`)\n * KEYS[6] = run meta key\n * ARGV[1] = step JSON (running)\n * ARGV[2] = step ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = step_created event JSON\n * ARGV[5] = step_started event JSON\n * ARGV[6] = step status value (`running|1`)\n * Returns: [1, createdEventId, startedEventId] when created, [0, stepJson] when\n * the step already exists (the caller lost the claim), [-6, status]\n * when the run is terminal\n */\nconst LUA_CREATE_STEP_STARTED = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])\n redis.call('SET', KEYS[5], ARGV[6])\n local createdId = appendEvent(KEYS[3], KEYS[4], ARGV[4])\n local startedId = appendEvent(KEYS[3], KEYS[4], ARGV[5])\n return {1, createdId, startedId}\n`;\n\n/**\n * Atomically claim a hook token and create the hook entity, its indexes,\n * token-map entry, AND its creation event. The by-token key is the claim\n * arbiter (SETNX):\n * - A DIFFERENT hookId already owning the token -> cross-run conflict; the\n * rightful owner's token mapping is left untouched. If that owner's hook no\n * longer exists (a crash during cleanup left the token behind), the token is\n * free and is taken over here, in the same execution, so a concurrent claim\n * can never be wiped.\n * - The SAME hookId owning the token with the entity present -> duplicate.\n * Entity + event are written in the same atomic script, so a crash can\n * never leave a hook entity without its hook_created event (or vice versa). A\n * hook is never created on a finished run, which would hold its token forever.\n *\n * KEYS[1] = hook key\n * KEYS[2] = hooks by token key\n * KEYS[3] = hooks index key\n * KEYS[4] = hooks token-map key (hash of hookId -> token, per run)\n * KEYS[5] = events key\n * KEYS[6] = events by correlation key\n * KEYS[7] = run meta key\n * ARGV[1] = hook JSON\n * ARGV[2] = hook ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = the token, recorded in the token map so terminal-run cleanup can\n * drop token lookups without reading every hook body\n * ARGV[5] = event JSON\n * ARGV[6] = hook key prefix\n * Returns: [2, owningHookId] on token conflict,\n * [0, hookJson] when the hook already exists, or has existed (created\n * and since disposed),\n * [1, eventId] on success,\n * [-6, status] when the run is terminal\n */\nconst LUA_CREATE_HOOK_WITH_EVENT = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[7])\n if status and isTerminal(status) then\n return {-6, status}\n end\n -- Disposal removes the hook and its token, so a stale writer that loaded the log\n -- before the hook existed would otherwise create it again behind its disposal.\n -- The creation event is the record that it already happened.\n if redis.call('ZCARD', KEYS[6]) > 0 then\n return {0, ''}\n end\n local claimed = redis.call('SETNX', KEYS[2], ARGV[2])\n if claimed == 0 then\n local owner = redis.call('GET', KEYS[2])\n if owner ~= ARGV[2] then\n if redis.call('EXISTS', ARGV[6] .. owner) == 1 then\n return {2, owner}\n end\n redis.call('SET', KEYS[2], ARGV[2])\n end\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])\n redis.call('HSET', KEYS[4], ARGV[2], ARGV[4])\n return {1, appendEvent(KEYS[5], KEYS[6], ARGV[5])}\n`;\n\n/**\n * Atomically dispose a hook: delete the hook key, its token lookup (only while\n * it still points at this hook), its index entry and its token-map entry, and\n * append `hook_disposed`. One script, because a crash between the delete and the\n * append would lose the event, and a delete racing a `hook_received` must not\n * leave the received event behind the disposal in the log.\n *\n * KEYS[1] = hook key\n * KEYS[2] = hooks by token key\n * KEYS[3] = hooks index key\n * KEYS[4] = hooks token-map key\n * KEYS[5] = events key\n * KEYS[6] = events by correlation key\n * ARGV[1] = hook ID (correlationId)\n * ARGV[2] = event JSON\n * Returns: [1, eventId] if disposed, [0, ''] if the hook was not found\n */\nconst LUA_DISPOSE_HOOK = `${LUA_APPEND_EVENT}\n if redis.call('DEL', KEYS[1]) == 0 then\n return {0, ''}\n end\n if redis.call('GET', KEYS[2]) == ARGV[1] then\n redis.call('DEL', KEYS[2])\n end\n redis.call('ZREM', KEYS[3], ARGV[1])\n redis.call('HDEL', KEYS[4], ARGV[1])\n return {1, appendEvent(KEYS[5], KEYS[6], ARGV[2])}\n`;\n\n/**\n * Atomically append an event to the run's log and its correlation index,\n * optionally writing an entity first so the mutation and its event commit\n * together.\n *\n * KEYS[1] = events key\n * KEYS[2] = events by correlation key (or unused placeholder)\n * KEYS[3] = entity key (or unused placeholder)\n * KEYS[4] = hook resume claim key (or unused placeholder)\n * KEYS[5] = step status key (or unused placeholder)\n * KEYS[6] = run meta key (or unused placeholder)\n * KEYS[7] = hook key (or unused placeholder)\n * ARGV[1] = event JSON\n * ARGV[2] = has correlation (\"1\" or \"0\")\n * ARGV[3] = creation dedup: \"1\" rejects when the correlation index already holds\n * an event (a wait or hook conflict recorded once), \"2\" rejects when it\n * already holds two (a wait completed once)\n * ARGV[4] = entity JSON to write to KEYS[3] ('' to write nothing)\n * ARGV[5] = resume claim payload ('' when the event is not a lazy hook resume)\n * ARGV[6] = the step's new status ('' when the event writes no step)\n * ARGV[7] = the attempt the caller read ('' to skip the check)\n * ARGV[8] = the step's new attempt ('' to keep the current one)\n * ARGV[9] = \"1\" to refuse when the run is terminal\n * ARGV[10] = \"1\" to refuse when the hook (KEYS[7]) does not exist\n *\n * A lazy hook resume is claimed per (run, resumeId): the first writer appends and\n * records `<eventId>|<claim payload>`, a later one appends nothing and gets the\n * recorded claim back, so both writers converge on one event.\n *\n * A step write is a transition out of the state the caller read, so it is checked\n * where the state lives: a terminal step takes no further write, and a write that\n * read an older attempt than the step now has lost to another writer. Without\n * this two deliveries could both record an outcome, and the log would hold both.\n * The attempt counter is kept here, not taken from the caller's possibly stale\n * copy of the step, so it only moves forward.\n *\n * The run and hook guards live here because the checks the caller makes before\n * calling are stale by the time the event is appended: a `hook_received` must not\n * land behind the hook's disposal or the run's end, which no replay can consume.\n *\n * Returns: [1, eventId] on success, [-8, ''] when creation dedup rejects,\n * [-7, ''] when completion dedup rejects, [3, claim] when a resume claim\n * already exists, [-3, status] when the step is already terminal,\n * [-4, attempt] when the step has moved past the attempt the caller\n * read, [-6, status] when the run is terminal, [-5, ''] when the hook\n * is gone\n */\nconst LUA_STORE_EVENT = `${LUA_APPEND_EVENT}\n if ARGV[5] ~= '' then\n local claim = redis.call('GET', KEYS[4])\n if claim then\n return {3, claim}\n end\n end\n\n if ARGV[10] == '1' and redis.call('EXISTS', KEYS[7]) == 0 then\n return {-5, ''}\n end\n\n if ARGV[9] == '1' then\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n end\n\n if ARGV[3] == '1' and redis.call('ZCARD', KEYS[2]) > 0 then\n return {${LUA_DUPLICATE_CREATION}, ''}\n end\n if ARGV[3] == '2' and redis.call('ZCARD', KEYS[2]) > 1 then\n return {-7, ''}\n end\n\n if ARGV[6] ~= '' then\n local current = redis.call('GET', KEYS[5])\n -- No key (a step written before it existed): the caller's read is the best\n -- attempt there is. Assuming 0 would make every later start look stale.\n local attempt = '0'\n if ARGV[7] ~= '' then\n attempt = ARGV[7]\n end\n if current then\n local status\n status, attempt = string.match(current, '^([^|]*)|?(.*)$')\n if status == 'completed' or status == 'failed' or status == 'cancelled' then\n return {-3, status}\n end\n if ARGV[7] ~= '' and attempt ~= ARGV[7] then\n return {-4, attempt}\n end\n end\n if ARGV[8] ~= '' then\n attempt = ARGV[8]\n end\n redis.call('SET', KEYS[5], ARGV[6] .. '|' .. attempt)\n end\n\n if ARGV[4] ~= '' then\n redis.call('SET', KEYS[3], ARGV[4])\n end\n\n local correlationKey = nil\n if ARGV[2] == '1' then\n correlationKey = KEYS[2]\n end\n local eventId = appendEvent(KEYS[1], correlationKey, ARGV[1])\n if ARGV[5] ~= '' then\n redis.call('SET', KEYS[4], eventId .. '|' .. ARGV[5])\n end\n return {1, eventId}\n`;\n\n/**\n * Atomically apply a batch of attribute changes and append the `attr_set` event.\n * Attributes live in a hash of their own, not in the run JSON, so two writers\n * changing different keys never overwrite each other.\n *\n * KEYS[1] = run attributes key\n * KEYS[2] = events key\n * KEYS[3] = events by correlation key (or unused placeholder)\n * KEYS[4] = run meta key\n * ARGV[1] = event JSON\n * ARGV[2] = has correlation (\"1\" or \"0\")\n * ARGV[3] = \"1\" to refuse a repeat for this correlation id (a replayed write)\n * ARGV[4..] = triples: attribute key, value, op (\"set\" or \"del\")\n * Returns: [1, eventId], [-6, status] when the run is terminal, [-8, ''] when\n * this correlation id already set attributes\n */\nconst LUA_SET_ATTRIBUTES = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[4])\n if status and isTerminal(status) then\n return {-6, status}\n end\n if ARGV[3] == '1' and ARGV[2] == '1' and redis.call('ZCARD', KEYS[3]) > 0 then\n return {${LUA_DUPLICATE_CREATION}, ''}\n end\n for i = 4, #ARGV, 3 do\n if ARGV[i + 2] == 'del' then\n redis.call('HDEL', KEYS[1], ARGV[i])\n else\n redis.call('HSET', KEYS[1], ARGV[i], ARGV[i + 1])\n end\n end\n local correlationKey = nil\n if ARGV[2] == '1' then\n correlationKey = KEYS[3]\n end\n return {1, appendEvent(KEYS[2], correlationKey, ARGV[1])}\n`;\n\n/** Registered via `defineCommand` so ioredis dispatches with `EVALSHA` rather\n * than shipping the script body every call. `LUA_STORE_EVENT` is ~1 KB and\n * runs once per workflow event. */\nconst SCRIPTS = {\n wfCreateRunWithEvent: { numberOfKeys: 7, lua: LUA_CREATE_RUN_WITH_EVENT },\n wfSetAttributes: { numberOfKeys: 4, lua: LUA_SET_ATTRIBUTES },\n wfTransitionRun: { numberOfKeys: 7, lua: LUA_TRANSITION_RUN },\n wfCreateStepWithEvent: { numberOfKeys: 6, lua: LUA_CREATE_STEP_WITH_EVENT },\n wfCreateStepStarted: { numberOfKeys: 6, lua: LUA_CREATE_STEP_STARTED },\n wfCreateHookWithEvent: { numberOfKeys: 7, lua: LUA_CREATE_HOOK_WITH_EVENT },\n wfDisposeHook: { numberOfKeys: 6, lua: LUA_DISPOSE_HOOK },\n wfStoreEvent: { numberOfKeys: 7, lua: LUA_STORE_EVENT },\n} as const;\n\ntype ScriptName = keyof typeof SCRIPTS;\ntype ScriptFn = (...args: string[]) => Promise<unknown>;\ntype RedisWithScripts = Redis & Record<ScriptName, ScriptFn>;\n\n/** Clients that already have the scripts attached; every storage factory\n * calls this with the same shared connection, so it must be idempotent. */\n// Process-wide, not module-scoped: a bundled copy of this module must see the\n// connections another copy already attached the scripts to.\nconst scriptState = globalSingleton(\n \"@brickkit/redis-world//scripts\",\n 1,\n () => ({\n clients: new WeakSet<Redis>(),\n }),\n);\n\nfunction withScripts(redis: Redis): RedisWithScripts {\n if (!scriptState.clients.has(redis)) {\n for (const [name, def] of Object.entries(SCRIPTS)) {\n redis.defineCommand(name, {\n numberOfKeys: def.numberOfKeys,\n lua: def.lua,\n });\n }\n scriptState.clients.add(redis);\n }\n return redis as RedisWithScripts;\n}\n\n/** Compact `<status>|<specVersion>` marker beside the run blob, so validation\n * reads those two fields without transferring the run's input/output. */\nfunction runMetaValue(status: string, specVersion: number | undefined): string {\n return `${status}|${specVersion ?? \"\"}`;\n}\n\nfunction parseRunMeta(value: string): { status: string; specVersion?: number } {\n const sep = value.indexOf(\"|\");\n if (sep === -1) {\n return { status: value };\n }\n const version = value.slice(sep + 1);\n return {\n status: value.slice(0, sep),\n specVersion: version === \"\" ? undefined : Number(version),\n };\n}\n\n/**\n * Create storage for workflow runs using Redis hashes and sorted sets\n */\nexport function createRunsStorage(config: RedisStorageConfig): Storage[\"runs\"] {\n const { redis, keyPrefix } = config;\n\n const {\n runKey,\n runAttributesKey,\n runsIndexKey,\n runsByNameKey,\n runsByStatusKey,\n } = keys(keyPrefix);\n\n /** The statuses a list filter allows, or undefined for any. `status` takes one\n * status or an array; an empty array matches nothing, unlike omitting it. */\n function allowedStatuses(\n params?: ListWorkflowRunsParams,\n ): string[] | undefined {\n const status = params?.status;\n if (status === undefined) return undefined;\n return Array.isArray(status) ? status : [status];\n }\n\n function selectIndexKeys(params?: ListWorkflowRunsParams): string[] {\n if (params?.workflowName) {\n return [runsByNameKey(params.workflowName)];\n }\n const statuses = allowedStatuses(params);\n if (statuses) {\n // One index per status, merged: never the index of every run there is.\n return statuses.map(runsByStatusKey);\n }\n return [runsIndexKey()];\n }\n\n function parseRunsFromPipeline(\n results: any[] | null,\n params?: ListWorkflowRunsParams,\n ): (WorkflowRun | WorkflowRunWithoutData)[] {\n const runs: (WorkflowRun | WorkflowRunWithoutData)[] = [];\n\n // Each run contributed two replies: its body, then its attributes.\n for (let i = 0; i + 1 < (results?.length ?? 0); i += 2) {\n const result = results![i];\n if (!result?.[1]) {\n continue;\n }\n\n const run: WorkflowRun = parse<WorkflowRun>(result[1] as string);\n run.attributes =\n (results![i + 1]?.[1] as Record<string, string> | undefined) ?? {};\n\n const statuses = allowedStatuses(params);\n const statusMatches = !statuses || statuses.includes(run.status);\n const nameMatches =\n !params?.workflowName || run.workflowName === params.workflowName;\n\n if (statusMatches && nameMatches) {\n const resolveData = params?.resolveData ?? \"all\";\n const parsed = WorkflowRunSchema.parse(compact(run));\n runs.push(filterRunData(parsed, resolveData));\n }\n }\n\n return runs;\n }\n\n return {\n get: (async (id: string, params?: GetWorkflowRunParams) => {\n const replies = await redis\n .pipeline()\n .get(runKey(id))\n .hgetall(runAttributesKey(id))\n .exec();\n const data = replies?.[0]?.[1] as string | null | undefined;\n if (!data) {\n throw new WorkflowRunNotFoundError(id);\n }\n const run = parse<WorkflowRun>(data);\n run.attributes =\n (replies?.[1]?.[1] as Record<string, string> | undefined) ?? {};\n const parsed = WorkflowRunSchema.parse(compact(run));\n const resolveData = params?.resolveData ?? \"all\";\n return filterRunData(parsed, resolveData);\n }) as Storage[\"runs\"][\"get\"],\n\n list: (async (params?: ListWorkflowRunsParams) => {\n const limit = params?.pagination?.limit ?? 20;\n const fromCursor = params?.pagination?.cursor;\n\n // `status: []` matches nothing, like SQL `IN ()`.\n if (allowedStatuses(params)?.length === 0) {\n return { data: [], hasMore: false, cursor: null };\n }\n\n const indexKeys = selectIndexKeys(params);\n const order = params?.pagination?.sortOrder ?? \"desc\";\n\n // Keep scanning the index until limit+1 matches are collected (needed\n // to compute hasMore) or the index is exhausted. A single fetch is not\n // enough when combined workflowName+status filtering happens in memory\n // after the index scan; it would produce premature empty pages and\n // hasMore=false while matches remain further down the index.\n const runs: {\n run: WorkflowRun | WorkflowRunWithoutData;\n cursor: string;\n }[] = [];\n let scanFrom = fromCursor;\n while (runs.length <= limit) {\n const entries = await pageIndex(\n redis,\n indexKeys,\n scanFrom,\n limit + 1,\n order,\n );\n if (entries.length === 0) {\n break;\n }\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(runKey(id));\n pipeline.hgetall(runAttributesKey(id));\n }\n const results = await pipeline.exec();\n const cursorOf = new Map(\n entries.map((entry) => [entry.id, entry.cursor]),\n );\n for (const run of parseRunsFromPipeline(results, params)) {\n runs.push({ run, cursor: cursorOf.get(run.runId)! });\n }\n\n if (entries.length < limit + 1) {\n break;\n }\n scanFrom = entries.at(-1)!.cursor;\n }\n\n const values = runs.slice(0, limit);\n const hasMore = runs.length > limit;\n\n return {\n data: values.map((entry) => entry.run),\n hasMore,\n cursor: values.at(-1)?.cursor ?? null,\n };\n }) as Storage[\"runs\"][\"list\"],\n };\n}\n\n/**\n * Create storage for workflow events using Redis hashes and sorted sets.\n *\n * A run's log is one hash (`eventId -> JSON`). Event ids are log positions, so\n * the log is dense and 1-based, and every script that appends to it picks the\n * next position itself, atomically with the write (see `LUA_APPEND_EVENT`).\n */\nexport function createEventsStorage(\n config: RedisStorageConfig,\n): Storage[\"events\"] {\n const { redis, keyPrefix } = config;\n const scripts = withScripts(redis);\n const ulid = monotonicFactory();\n const maxEventsPerRun = resolveMaxEventsPerRun(config.maxEventsPerRun);\n\n const {\n eventsKey,\n eventsByCorrelationKey,\n resumeClaimKey,\n runKey,\n runAttributesKey,\n runMetaKey,\n runsIndexKey,\n runsByNameKey,\n runsByStatusKey,\n stepKey,\n stepsIndexKey,\n stepStatusKey,\n hookKey,\n hooksByTokenKey,\n hooksIndexKey,\n hooksTokenMapKey,\n } = keys(keyPrefix);\n\n /** Events per `HMGET`; keeps a long log from building one huge command. */\n const READ_CHUNK = 500;\n /** The most events an inline delta or skipped-slot report carries; the\n * caller continues from the cursor (or reloads) when `hasMore` is set. */\n const MAX_INLINE_EVENTS = 200;\n\n /** A run with its current attributes, which live apart from the run body. */\n async function withAttributes<T extends WorkflowRun | WorkflowRunWithoutData>(\n run: T,\n ): Promise<T> {\n const attributes = await redis.hgetall(runAttributesKey(run.runId));\n return { ...run, attributes };\n }\n\n /** `[key, value, ...]` for a script, from an attribute record. */\n const flattenAttributes = (\n attributes: Record<string, string> | undefined,\n ): string[] => Object.entries(attributes ?? {}).flat();\n\n /** Serialize an event for a script: `eventId` first, holding the placeholder. */\n function serializeEvent(event: Record<string, unknown>): string {\n const { eventId: _eventId, ...rest } = event;\n return stringify({ eventId: EVENT_ID_PLACEHOLDER, ...rest });\n }\n\n /** Read events by id out of one run's log, skipping any that are absent. */\n async function readEvents(\n runId: string,\n eventIds: string[],\n ): Promise<Event[]> {\n const events: Event[] = [];\n for (let i = 0; i < eventIds.length; i += READ_CHUNK) {\n const values = await redis.hmget(\n eventsKey(runId),\n ...eventIds.slice(i, i + READ_CHUNK),\n );\n for (const value of values) {\n if (value) {\n events.push(EventSchema.parse(compact(parse<Event>(value))));\n }\n }\n }\n return events;\n }\n\n /** Events at slots `from..to` inclusive, in slot order. */\n async function readSlots(\n runId: string,\n from: number,\n to: number,\n ): Promise<Event[]> {\n const ids: string[] = [];\n for (let slot = Math.max(from, FIRST_EVENT_SLOT); slot <= to; slot++) {\n ids.push(slotToEventId(slot));\n }\n return readEvents(runId, ids);\n }\n\n type TransitionResult =\n | { kind: \"ok\"; eventId: string }\n | { kind: \"absent\" }\n | { kind: \"moved\"; status: string };\n\n /**\n * Move a run from `oldStatus` to `newStatus`, release its hooks when it\n * finishes, and append the lifecycle event: one script, so a crash or a racing\n * writer can never leave the status and the log disagreeing. `moved` means the\n * run was no longer in `oldStatus` by the time the script ran, and nothing was\n * written.\n */\n async function transitionRun(\n runId: string,\n oldStatus: string,\n newStatus: string,\n updatedRun: { specVersion?: number },\n at: Date,\n event: Record<string, unknown>,\n releaseHooks: boolean,\n ): Promise<TransitionResult> {\n const result = (await scripts.wfTransitionRun(\n runKey(runId),\n runsByStatusKey(oldStatus),\n runsByStatusKey(newStatus),\n runMetaKey(runId),\n eventsKey(runId),\n hooksIndexKey(runId),\n hooksTokenMapKey(runId),\n stringify(updatedRun),\n runId,\n at.getTime().toString(),\n runMetaValue(newStatus, updatedRun.specVersion),\n oldStatus,\n serializeEvent(event),\n releaseHooks ? \"1\" : \"0\",\n hookKey(\"\"),\n hooksByTokenKey(\"\"),\n )) as [number, string];\n if (result[0] === 1) return { kind: \"ok\", eventId: result[1] };\n if (result[0] === -2) return { kind: \"moved\", status: result[1] };\n return { kind: \"absent\" };\n }\n\n /** What an append can come back as besides the stored event. */\n type AppendOutcome =\n | { kind: \"stored\"; event: Event }\n | { kind: \"duplicate\" }\n | { kind: \"alreadyCompleted\" }\n | { kind: \"claimed\"; claim: string }\n | { kind: \"stepTerminal\"; status: string }\n | { kind: \"stepMoved\"; attempt: string }\n | { kind: \"runTerminal\"; status: string }\n | { kind: \"hookGone\" };\n\n /** Append an event whose id the script picks. Returns the stored event. */\n async function appendEvent(\n runId: string,\n event: Record<string, unknown>,\n options: {\n entityKey?: string;\n entityJson?: string;\n /** `creation`: refuse when the correlation id already has an event.\n * `completion`: refuse when it already has two (created, then completed). */\n dedup?: \"creation\" | \"completion\";\n resume?: { id: string; claim: string };\n /**\n * The step this write moves. `expectedAttempt` makes the write lose to any\n * other writer that moved the step past the attempt the caller read.\n * `newAttempt` sets the attempt (a start); otherwise it is kept.\n */\n step?: {\n key: string;\n status: string;\n expectedAttempt?: number;\n newAttempt?: number;\n };\n /** Refuse when the run is terminal. */\n runMustBeLive?: boolean;\n /** Refuse when the hook the event is about no longer exists. */\n hookMustExist?: boolean;\n } = {},\n ): Promise<AppendOutcome> {\n const correlationId = event.correlationId as string | undefined;\n const result = (await scripts.wfStoreEvent(\n eventsKey(runId),\n correlationId\n ? eventsByCorrelationKey(runId, correlationId)\n : \"__unused__\",\n options.entityKey ?? \"__unused__\",\n options.resume ? resumeClaimKey(runId, options.resume.id) : \"__unused__\",\n options.step?.key ?? \"__unused__\",\n options.runMustBeLive ? runMetaKey(runId) : \"__unused__\",\n options.hookMustExist && correlationId\n ? hookKey(correlationId)\n : \"__unused__\",\n serializeEvent(event),\n correlationId ? \"1\" : \"0\",\n options.dedup === \"creation\"\n ? \"1\"\n : options.dedup === \"completion\"\n ? \"2\"\n : \"0\",\n options.entityJson ?? \"\",\n options.resume?.claim ?? \"\",\n options.step?.status ?? \"\",\n options.step?.expectedAttempt === undefined\n ? \"\"\n : String(options.step.expectedAttempt),\n options.step?.newAttempt === undefined\n ? \"\"\n : String(options.step.newAttempt),\n options.runMustBeLive ? \"1\" : \"0\",\n options.hookMustExist ? \"1\" : \"0\",\n )) as [number, string];\n switch (result[0]) {\n case LUA_DUPLICATE_CREATION:\n return { kind: \"duplicate\" };\n case -7:\n return { kind: \"alreadyCompleted\" };\n case -3:\n return { kind: \"stepTerminal\", status: result[1] };\n case -4:\n return { kind: \"stepMoved\", attempt: result[1] };\n case -5:\n return { kind: \"hookGone\" };\n case -6:\n return { kind: \"runTerminal\", status: result[1] };\n case 3:\n return { kind: \"claimed\", claim: result[1] };\n default:\n return {\n kind: \"stored\",\n event: EventSchema.parse({ ...event, eventId: result[1] }),\n };\n }\n }\n\n /** The events a bumped write skipped over: those between the slot the writer\n * asked for (`eventCount + 1`) and the one it landed on. */\n async function reportSkippedSlots(\n result: EventResult,\n askedFor: number,\n resolveData: EventsResolveData,\n ): Promise<EventResult> {\n if (!result.event) return result;\n const committedSlot = eventIdToSlot(result.event.eventId);\n if (\n committedSlot === null ||\n askedFor < 0 ||\n committedSlot <= askedFor + 1\n ) {\n return result;\n }\n const span = committedSlot - askedFor - 1;\n const upto = Math.min(committedSlot - 1, askedFor + MAX_INLINE_EVENTS);\n const skipped = await readSlots(result.event.runId, askedFor + 1, upto);\n return {\n ...result,\n events: skipped.map((event) => stripEventDataRefs(event, resolveData)),\n // The report is a lower bound on what the write skipped, not a page the\n // caller has now read to the end of, so it must not move its read position.\n cursor: null,\n hasMore: skipped.length < span,\n };\n }\n\n /** The inline delta: everything after `sinceCursor`, as `events.list` would\n * return it right after the write. */\n async function deltaSince(\n result: EventResult,\n sinceCursor: string,\n resolveData: EventsResolveData,\n ): Promise<EventResult> {\n if (!result.event) return result;\n const sinceSlot = eventIdToSlot(sinceCursor);\n if (sinceSlot === null) return result;\n const total = await redis.hlen(eventsKey(result.event.runId));\n const upto = Math.min(total, sinceSlot + MAX_INLINE_EVENTS);\n const page = await readSlots(result.event.runId, sinceSlot + 1, upto);\n return {\n ...result,\n events: page.map((event) => stripEventDataRefs(event, resolveData)),\n cursor: page.at(-1)?.eventId ?? sinceCursor,\n hasMore: upto < total,\n };\n }\n\n const isTerminal = (status: string) =>\n [\"completed\", \"failed\", \"cancelled\"].includes(status);\n\n /** How many times a step write recomputes after losing a race for the step. */\n const MAX_STALE_RETRIES = 5;\n\n async function createEvent(\n runId: string | null,\n data: CreateEventRequest | RunCreatedEventRequest,\n params?: CreateEventParams,\n staleRetries = 0,\n ): Promise<EventResult> {\n const now = new Date();\n const resolveData = params?.resolveData ?? \"all\";\n // The created event and the entities are never trimmed to the page option.\n const entityData = entityResolveData(resolveData);\n\n let effectiveRunId: string;\n if (data.eventType === \"run_created\" && (!runId || runId === \"\")) {\n effectiveRunId = `wrun_${ulid()}`;\n } else if (!runId) {\n throw new Error(\"runId is required for non-run_created events\");\n } else {\n effectiveRunId = runId;\n }\n\n const effectiveSpecVersion = data.specVersion ?? mintedSpecVersion();\n\n // Build the event this call appends; the script fills in `eventId`.\n const buildEvent = (\n overrides: Record<string, unknown> = {},\n ): Record<string, unknown> => ({\n ...data,\n runId: effectiveRunId,\n createdAt: new Date(),\n specVersion: effectiveSpecVersion,\n ...overrides,\n });\n\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n\n // Set when a lifecycle transition already committed its own event.\n let lifecycleEvent: Event | undefined;\n\n // Written alongside the event append below instead of in its own round\n // trip, which also makes the mutation and its event atomic.\n let pendingEntityKey: string | undefined;\n let pendingEntityJson: string | undefined;\n let pendingStep:\n | {\n key: string;\n status: string;\n expectedAttempt?: number;\n newAttempt?: number;\n }\n | undefined;\n\n let currentRun: { status: string; specVersion?: number } | null = null;\n // Read at most once per call; every mutation branch below reuses it\n // rather than re-fetching and re-parsing the whole payload.\n let existingRun: WorkflowRun | null = null;\n\n async function loadRunBody(): Promise<void> {\n const runData = await redis.get(runKey(effectiveRunId));\n if (runData) {\n existingRun = parse<WorkflowRun>(runData);\n currentRun = {\n status: existingRun.status,\n specVersion: existingRun.specVersion,\n };\n }\n }\n\n const skipRunValidationEvents = [\"step_completed\", \"step_retrying\"];\n if (\n data.eventType !== \"run_created\" &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n if (RUN_LIFECYCLE_EVENT_TYPES.has(data.eventType)) {\n // These mutate the run, so its body is needed either way.\n await loadRunBody();\n } else {\n // Only status/specVersion are consulted, and the meta key holds\n // both in ~20 bytes. No meta means no such run.\n const meta = await redis.get(runMetaKey(effectiveRunId));\n if (meta) {\n currentRun = parseRunMeta(meta);\n }\n }\n }\n\n if (\n data.eventType === \"run_started\" &&\n !currentRun &&\n \"eventData\" in data &&\n data.eventData\n ) {\n const runInputData = (data as any).eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: any;\n attributes?: Record<string, string>;\n allowReservedAttributes?: true;\n encryptionPublicKey?: string;\n dynamicWorkflowCode?: any;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n const seeds = runInputData.attributes ?? {};\n validateAttributeChanges(\n Object.entries(seeds).map(([key, value]) => ({ key, value })),\n {\n allowReservedAttributes:\n runInputData.allowReservedAttributes === true,\n },\n );\n const newRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n ...(runInputData.encryptionPublicKey && {\n encryptionPublicKey: runInputData.encryptionPublicKey,\n }),\n ...(runInputData.dynamicWorkflowCode !== undefined && {\n dynamicWorkflowCode: runInputData.dynamicWorkflowCode,\n }),\n status: \"pending\" as const,\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Fused script: run entity + synthetic run_created event in one\n // atomic execution, so a crash cannot leave one without the other\n // and concurrent bootstraps cannot double-append the event.\n const result = (await scripts.wfCreateRunWithEvent(\n runKey(effectiveRunId),\n runsIndexKey(),\n runsByNameKey(runInputData.workflowName),\n runsByStatusKey(\"pending\"),\n runMetaKey(effectiveRunId),\n eventsKey(effectiveRunId),\n runAttributesKey(effectiveRunId),\n stringify(newRun),\n effectiveRunId,\n now.getTime().toString(),\n runMetaValue(\"pending\", effectiveSpecVersion),\n serializeEvent({\n eventType: \"run_created\",\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n ...(runInputData.attributes && {\n attributes: runInputData.attributes,\n }),\n ...(runInputData.allowReservedAttributes && {\n allowReservedAttributes: true,\n }),\n ...(runInputData.encryptionPublicKey && {\n encryptionPublicKey: runInputData.encryptionPublicKey,\n }),\n },\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n }),\n ...flattenAttributes(seeds),\n )) as [number, string];\n if (result[0] === 1) {\n currentRun = { status: \"pending\", specVersion: effectiveSpecVersion };\n existingRun = newRun as WorkflowRun;\n } else {\n // Run already exists (the resilient re-start path, which must\n // tolerate losing the race): read the state the other writer left.\n const parsed = parse<WorkflowRun>(result[1]);\n currentRun = {\n status: parsed.status,\n specVersion: parsed.specVersion,\n };\n existingRun = parsed;\n }\n }\n }\n\n if (currentRun) {\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n mintedSpecVersion(),\n );\n }\n if (isLegacySpecVersion(currentRun.specVersion)) {\n // Event ids are log positions; a run from before the event-sourced spec\n // has none.\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n mintedSpecVersion(),\n );\n }\n }\n\n if (currentRun && isTerminal((currentRun as { status: string }).status)) {\n const terminalStatus = (currentRun as { status: string }).status;\n const runTerminalEvents = [\"run_started\", \"run_completed\", \"run_failed\"];\n\n if (\n data.eventType === \"run_cancelled\" &&\n terminalStatus === \"cancelled\"\n ) {\n const stored = await appendEvent(effectiveRunId, buildEvent());\n if (stored.kind !== \"stored\") {\n throw new EntityConflictError(\"Duplicate run_cancelled\");\n }\n return {\n event: stripEventDataRefs(stored.event, entityData),\n // Lifecycle event: validation already loaded the body.\n run: existingRun\n ? await withAttributes(\n WorkflowRunSchema.parse(compact(existingRun)),\n )\n : undefined,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === \"run_started\") {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${terminalStatus}\"`,\n );\n }\n\n // No work begins on a finished run. A step_started is rejected even when\n // the step still reads `running`: that is a redelivery of a start an\n // earlier delivery already claimed, and accepting it would execute a\n // body whose outcome nothing will read. step_completed and step_failed\n // stay accepted so a step already in flight can record its outcome.\n if (data.eventType === \"step_started\") {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${terminalStatus}\"`,\n );\n }\n\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === \"run_cancelled\"\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${terminalStatus}\"`,\n );\n }\n\n if (\n data.eventType === \"step_created\" ||\n data.eventType === \"hook_created\" ||\n data.eventType === \"wait_created\"\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${terminalStatus}\"`,\n );\n }\n }\n\n // Held whole so `step_started`/`step_retrying` can mutate it below\n // without re-fetching and re-parsing the step (including its input).\n let validatedStep: Step | null = null;\n // A step_started that carries the step's name and input also creates it.\n const lazyStepStart =\n data.eventType === \"step_started\" &&\n typeof (data as any).eventData?.stepName === \"string\" &&\n (data as any).eventData?.input !== undefined;\n const stepEventsNeedingValidation = [\"step_started\", \"step_retrying\"];\n if (\n stepEventsNeedingValidation.includes(data.eventType) &&\n data.correlationId\n ) {\n const stepData = await redis.get(\n stepKey(effectiveRunId, data.correlationId),\n );\n if (stepData) {\n validatedStep = parse<Step>(stepData);\n }\n\n if (!validatedStep && !lazyStepStart) {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n\n // The lazy start exactly-once gate: a lazy step_started always CREATES the\n // step, so an existing one means a concurrent handler won the claim.\n // EntityConflictError makes the runtime skip it; without this a loser\n // would re-start a running step and run the body a second time.\n if (lazyStepStart && validatedStep) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`,\n );\n }\n\n if (validatedStep) {\n // EntityConflictError so core's step handler skips the duplicate\n // delivery and re-enqueues the workflow (crash-recovery nudge).\n if (isTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`,\n );\n }\n\n if (\n currentRun &&\n isTerminal((currentRun as { status: string }).status)\n ) {\n if (validatedStep.status !== \"running\") {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${(currentRun as { status: string }).status}\"`,\n );\n }\n }\n }\n }\n\n // Hook validation; the body is kept so `hook_disposed` below need not\n // re-read it just to recover the token.\n let validatedHook: Hook | null = null;\n // A hook_received that carries a resume id may be a retry of one already\n // recorded: the script checks the claim first, then the hook, so the retry\n // gets its event back rather than \"not found\".\n const hookEventsRequiringExistence = [\"hook_disposed\", \"hook_received\"];\n const isResumeRetryCandidate =\n data.eventType === \"hook_received\" && params?.resumeId;\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId &&\n !isResumeRetryCandidate\n ) {\n const existingHook = await redis.get(hookKey(data.correlationId));\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n validatedHook = parse<Hook>(existingHook);\n }\n\n if (data.eventType === \"run_created\") {\n const eventData = (data as any).eventData as {\n deploymentId: string;\n workflowName: string;\n input: any[];\n executionContext?: Record<string, any>;\n attributes?: Record<string, string>;\n allowReservedAttributes?: true;\n encryptionPublicKey?: string;\n dynamicWorkflowCode?: any;\n dynamicWorkflowCodeRef?: string;\n };\n\n if (eventData.dynamicWorkflowCodeRef !== undefined) {\n throw new WorkflowWorldError(\n \"dynamicWorkflowCodeRef is not supported by this world\",\n {\n status: 501,\n },\n );\n }\n const seeds = eventData.attributes ?? {};\n validateAttributeChanges(\n Object.entries(seeds).map(([key, value]) => ({ key, value })),\n { allowReservedAttributes: eventData.allowReservedAttributes === true },\n );\n\n const newRun = {\n runId: effectiveRunId,\n deploymentId: eventData.deploymentId,\n workflowName: eventData.workflowName,\n specVersion: effectiveSpecVersion,\n input: eventData.input,\n executionContext: eventData.executionContext,\n ...(eventData.encryptionPublicKey && {\n encryptionPublicKey: eventData.encryptionPublicKey,\n }),\n ...(eventData.dynamicWorkflowCode !== undefined && {\n dynamicWorkflowCode: eventData.dynamicWorkflowCode,\n }),\n status: \"pending\" as const,\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n\n // Fused script: run entity + run_created event in one atomic\n // execution. A duplicate rejects with EntityConflictError (which the\n // runtime treats as benign) instead of returning the existing run\n // AND appending a second creation event that would poison replay.\n const event = buildEvent({ createdAt: now });\n const result = (await scripts.wfCreateRunWithEvent(\n runKey(effectiveRunId),\n runsIndexKey(),\n runsByNameKey(eventData.workflowName),\n runsByStatusKey(\"pending\"),\n runMetaKey(effectiveRunId),\n eventsKey(effectiveRunId),\n runAttributesKey(effectiveRunId),\n stringify(newRun),\n effectiveRunId,\n now.getTime().toString(),\n runMetaValue(\"pending\", effectiveSpecVersion),\n serializeEvent(event),\n ...flattenAttributes(seeds),\n )) as [number, string];\n\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`,\n );\n }\n\n run = WorkflowRunSchema.parse({ ...compact(newRun), attributes: seeds });\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return {\n event: stripEventDataRefs(parsed, entityData),\n run,\n maxEvents: maxEventsPerRun,\n };\n }\n\n if (data.eventType === \"run_started\") {\n // Core reads the per-run event ceiling only from the run_started response, so\n // omitting it here would drop the limit on every replay after the first.\n const resumeResponse = async (\n current: WorkflowRun | null,\n ): Promise<EventResult> => {\n const resumed = current\n ? await withAttributes(WorkflowRunSchema.parse(compact(current)))\n : undefined;\n return {\n run: resumed\n ? (filterRunData(resumed, entityData) as WorkflowRun)\n : undefined,\n ...(resumed ? { maxEvents: maxEventsPerRun } : {}),\n };\n };\n\n if ((currentRun as { status: string } | null)?.status === \"running\") {\n // Resume path, hit on every re-invocation of a running workflow.\n return resumeResponse(existingRun);\n }\n\n if (!existingRun) {\n // No run and no resilient-start bootstrap data; logging a\n // run_started event against a nonexistent run would corrupt the\n // event log, so fail loudly instead.\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const existing = existingRun as WorkflowRun;\n const updatedRun = {\n ...existing,\n status: \"running\" as const,\n startedAt: now,\n updatedAt: now,\n };\n\n // The event carries no data: the run's input was the creation event's.\n const { eventData: _startData, ...startEvent } = buildEvent({\n createdAt: now,\n });\n const moved = await transitionRun(\n effectiveRunId,\n existing.status,\n \"running\",\n updatedRun,\n now,\n startEvent,\n false,\n );\n if (moved.kind === \"absent\") {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n if (moved.kind === \"moved\") {\n // Another invocation got there first. If it started the run, this one is\n // a resume and must not append a second run_started; if the run ended in\n // the meantime, there is nothing left to start.\n if (isTerminal(moved.status)) {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${moved.status}\"`,\n );\n }\n await loadRunBody();\n return resumeResponse(existingRun);\n }\n\n run = WorkflowRunSchema.parse(compact(updatedRun));\n lifecycleEvent = EventSchema.parse({\n ...startEvent,\n eventId: moved.eventId,\n });\n }\n\n if (\n data.eventType === \"run_completed\" ||\n data.eventType === \"run_failed\" ||\n data.eventType === \"run_cancelled\"\n ) {\n if (!existingRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const existing = existingRun as WorkflowRun;\n let updatedRun: WorkflowRun;\n let newStatus: \"completed\" | \"failed\" | \"cancelled\";\n\n if (data.eventType === \"run_completed\") {\n const eventData = (data as any).eventData as { output?: any };\n newStatus = \"completed\";\n updatedRun = {\n ...existing,\n status: \"completed\",\n output: eventData.output,\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n } else if (data.eventType === \"run_failed\") {\n const eventData = (data as any).eventData as {\n error: any;\n errorCode?: string;\n };\n newStatus = \"failed\";\n updatedRun = {\n ...existing,\n status: \"failed\",\n // Kept as the serialized thrown value; consumers hydrate it.\n error: eventData.error,\n errorCode: eventData.errorCode,\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n } else {\n newStatus = \"cancelled\";\n updatedRun = {\n ...existing,\n status: \"cancelled\",\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n }\n\n // Status, hook release and event commit together (see `transitionRun`).\n const terminalEvent = buildEvent({ createdAt: now });\n const moved = await transitionRun(\n effectiveRunId,\n existing.status,\n newStatus,\n updatedRun,\n now,\n terminalEvent,\n true,\n );\n if (moved.kind === \"absent\") {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n if (moved.kind === \"moved\") {\n throw new EntityConflictError(\n `Cannot transition run \"${effectiveRunId}\" to \"${newStatus}\": it already left \"${existing.status}\" for \"${moved.status}\"`,\n );\n }\n\n run = WorkflowRunSchema.parse(compact(updatedRun));\n lifecycleEvent = EventSchema.parse({\n ...terminalEvent,\n eventId: moved.eventId,\n });\n }\n\n if (data.eventType === \"step_created\") {\n const eventData = (data as any).eventData as {\n stepName: string;\n input: any;\n };\n\n const newStep = {\n runId: effectiveRunId,\n stepId: data.correlationId!,\n stepName: eventData.stepName,\n input: eventData.input,\n status: \"pending\" as const,\n attempt: 0,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n updatedAt: now,\n };\n\n // Fused script: step entity + step_created event in one atomic\n // execution, closing the check-then-write race between concurrent\n // redeliveries. An existing entity means the creation event is\n // already in the log (they are written together), so a duplicate\n // rejects with EntityConflictError, the runtime's dedup signal;\n // returning success would append a second step_created row and\n // poison replay with ReplayDivergenceError.\n const event = buildEvent({ createdAt: now });\n const result = (await scripts.wfCreateStepWithEvent(\n stepKey(effectiveRunId, data.correlationId!),\n stepsIndexKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n stepStatusKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(newStep),\n data.correlationId!,\n now.getTime().toString(),\n serializeEvent(event),\n \"pending|0\",\n )) as [number, string];\n\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already exists`,\n );\n }\n\n step = StepSchema.parse(compact(newStep));\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData), step };\n }\n\n // wait_created has no entity in this world; the event log is the only\n // dedup surface. Throw on a duplicate so the contract matches the\n // runtime's dedup catch path.\n //\n // Checked inside the event-store script: a wait's correlation index only\n // holds wait_created and the wait_completed that follows it, so a\n // non-empty index means \"already recorded\". O(1) and atomic with the\n // write, vs scanning every event on every wait.\n const dedup: \"creation\" | \"completion\" | undefined =\n data.eventType === \"wait_created\"\n ? \"creation\"\n : data.eventType === \"wait_completed\"\n ? \"completion\"\n : undefined;\n\n if (data.eventType === \"step_started\") {\n // Retried steps may be scheduled for later. TooEarlyError tells core\n // to re-deliver after the remaining backoff instead of starting the\n // step before its retryAfter timestamp.\n if (\n validatedStep?.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000,\n ),\n },\n );\n }\n\n if (lazyStepStart) {\n // Lazy start: create the step (already running), a synthetic\n // step_created so replay still observes the creation, and the\n // step_started, in one script. The SETNX is the exactly-once claim.\n const lazyData = (data as any).eventData as {\n stepName: string;\n input: any;\n [key: string]: unknown;\n };\n const startedStep = {\n runId: effectiveRunId,\n stepId: data.correlationId!,\n stepName: lazyData.stepName,\n input: lazyData.input,\n status: \"running\" as const,\n attempt: 1,\n startedAt: now,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n updatedAt: now,\n };\n // The input belongs on the synthetic step_created; the step_started row\n // keeps the rest (stepName is read by the replay's name-divergence check).\n const { input: _input, ...startedEventData } = lazyData;\n const createdEvent = {\n eventType: \"step_created\" as const,\n correlationId: data.correlationId,\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n stepName: lazyData.stepName,\n ...(lazyData.workflowName !== undefined && {\n workflowName: lazyData.workflowName,\n }),\n input: lazyData.input,\n },\n };\n const startedEvent = buildEvent({\n createdAt: now,\n eventData: startedEventData,\n });\n const result = (await scripts.wfCreateStepStarted(\n stepKey(effectiveRunId, data.correlationId!),\n stepsIndexKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n stepStatusKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(startedStep),\n data.correlationId!,\n now.getTime().toString(),\n serializeEvent(createdEvent),\n serializeEvent(startedEvent),\n \"running|1\",\n )) as [number, string, string];\n if (result[0] === -6) {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`,\n );\n }\n step = StepSchema.parse(compact(startedStep));\n const parsed = EventSchema.parse({\n ...startedEvent,\n eventId: result[2],\n });\n return {\n event: stripEventDataRefs(parsed, entityData),\n step,\n stepCreated: true,\n };\n }\n\n const isFirstStart = !validatedStep?.startedAt;\n // Reuses the step loaded during validation above.\n const existing = validatedStep;\n if (existing) {\n const updatedStep = {\n ...existing,\n status: \"running\" as const,\n attempt: existing.attempt + 1,\n ...(isFirstStart ? { startedAt: now } : {}),\n // The step has left the backoff window; always clear retryAfter.\n retryAfter: undefined,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"running\",\n // Two starts that both read this attempt cannot both win.\n expectedAttempt: existing.attempt,\n newAttempt: updatedStep.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n }\n }\n\n if (data.eventType === \"step_completed\") {\n const eventData = (data as any).eventData as { result?: any };\n const existingData = await redis.get(\n stepKey(effectiveRunId, data.correlationId!),\n );\n if (existingData) {\n const existing = parse<Step>(existingData);\n if (isTerminal(existing.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${existing.status}\"`,\n );\n }\n const updatedStep = {\n ...existing,\n status: \"completed\" as const,\n output: eventData.result,\n completedAt: now,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"completed\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n } else {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n }\n\n if (data.eventType === \"step_failed\") {\n const eventData = (data as any).eventData as { error?: any };\n\n const existingData = await redis.get(\n stepKey(effectiveRunId, data.correlationId!),\n );\n if (existingData) {\n const existing = parse<Step>(existingData);\n if (isTerminal(existing.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${existing.status}\"`,\n );\n }\n const updatedStep = {\n ...existing,\n status: \"failed\" as const,\n // Kept as the serialized thrown value; consumers hydrate it.\n error: eventData.error,\n completedAt: now,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"failed\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n } else {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n }\n\n if (data.eventType === \"step_retrying\") {\n const eventData = (data as any).eventData as {\n error?: any;\n retryAfter?: Date;\n };\n\n // Reuses the step loaded during validation above.\n const existing = validatedStep;\n if (existing) {\n const updatedStep = {\n ...existing,\n status: \"pending\" as const,\n error: eventData.error,\n retryAfter: eventData.retryAfter,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"pending\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n }\n }\n\n if (data.eventType === \"hook_created\") {\n const eventData = (data as any).eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n const newHook: Hook = {\n runId: effectiveRunId,\n hookId: data.correlationId!,\n token: eventData.token,\n ownerId: \"\",\n projectId: \"\",\n environment: \"\",\n metadata: eventData.metadata,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n ...(eventData.isWebhook !== undefined && {\n isWebhook: eventData.isWebhook,\n }),\n ...(eventData.isSystem !== undefined && {\n isSystem: eventData.isSystem,\n }),\n };\n const event = buildEvent({ createdAt: now });\n\n // Fused script: token claim + hook entity + hook_created event in\n // one atomic execution. The SETNX on the by-token key arbitrates\n // ownership, closing the check-then-write race between concurrent\n // deliveries. A token whose owner is gone (a crash during cleanup left it\n // behind) is taken over inside the script, and a hook is never created on\n // a finished run, which would hold its token forever.\n const result = (await scripts.wfCreateHookWithEvent(\n hookKey(data.correlationId!),\n hooksByTokenKey(eventData.token),\n hooksIndexKey(effectiveRunId),\n hooksTokenMapKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(newHook),\n data.correlationId!,\n now.getTime().toString(),\n eventData.token,\n serializeEvent(event),\n hookKey(\"\"),\n )) as [number, string];\n\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${result[1]}\"`,\n );\n }\n\n if (result[0] === 2) {\n // A different (runId, hookId) holds this token. Create a\n // hook_conflict event instead of throwing 409; this lets the\n // workflow continue and fail gracefully when the hook is awaited.\n // The rightful owner's token mapping is left untouched.\n const owningHookId = result[1];\n let conflictingRunId: string | undefined;\n const owningHookData = await redis.get(hookKey(owningHookId));\n if (owningHookData) {\n conflictingRunId = parse<Hook>(owningHookData).runId;\n }\n\n // Recorded once: a redelivered hook_created must not journal a second\n // conflict, which replay would read as a second event for one hook.\n const stored = await appendEvent(\n effectiveRunId,\n {\n eventType: \"hook_conflict\" as const,\n correlationId: data.correlationId,\n eventData: {\n token: eventData.token,\n ...(conflictingRunId ? { conflictingRunId } : {}),\n },\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n },\n { dedup: \"creation\", runMustBeLive: true },\n );\n if (stored.kind === \"runTerminal\") {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind !== \"stored\") {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" conflict already recorded`,\n );\n }\n return {\n event: stripEventDataRefs(stored.event, entityData),\n run,\n step,\n hook: undefined,\n };\n }\n\n if (result[0] === 0) {\n // Same (runId, hookId, token) already fully created: entity and\n // event are written atomically, so the event is guaranteed to be\n // in the log. EntityConflictError is the runtime's dedup signal\n // (a self hook_conflict would later replay as HookConflictError).\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already created`,\n );\n }\n\n hook = HookSchema.parse(compact(newHook));\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData), hook };\n }\n\n // Handle hook_disposed: delete the hook and append the event in one script, so\n // a racing hook_received cannot land behind the disposal and a crash cannot\n // lose the event.\n if (data.eventType === \"hook_disposed\" && data.correlationId) {\n if (!validatedHook) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`,\n );\n }\n const event = buildEvent();\n const result = (await scripts.wfDisposeHook(\n hookKey(data.correlationId),\n hooksByTokenKey(validatedHook.token),\n hooksIndexKey(effectiveRunId),\n hooksTokenMapKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId),\n data.correlationId,\n serializeEvent(event),\n )) as [number, string];\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`,\n );\n }\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData) };\n }\n\n // Handle attr_set: merge the changes into the run's attributes and append the\n // event in one script.\n if (data.eventType === \"attr_set\") {\n if (!currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const eventData = (data as any).eventData as {\n changes: AttributeChange[];\n allowReservedAttributes?: true;\n };\n validateAttributeChanges(eventData.changes, {\n existingKeys: await redis.hkeys(runAttributesKey(effectiveRunId)),\n allowReservedAttributes: eventData.allowReservedAttributes === true,\n });\n const event = buildEvent();\n const correlationId = data.correlationId;\n const result = (await scripts.wfSetAttributes(\n runAttributesKey(effectiveRunId),\n eventsKey(effectiveRunId),\n correlationId\n ? eventsByCorrelationKey(effectiveRunId, correlationId)\n : \"__unused__\",\n runMetaKey(effectiveRunId),\n serializeEvent(event),\n correlationId ? \"1\" : \"0\",\n // A workflow replays its writes, so one correlation id sets attributes once.\n (data as { eventData?: { writer?: { type?: string } } }).eventData\n ?.writer?.type === \"workflow\"\n ? \"1\"\n : \"0\",\n ...eventData.changes.flatMap((change) => [\n change.key,\n change.value ?? \"\",\n change.value === null ? \"del\" : \"set\",\n ]),\n )) as [number, string];\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot set attributes on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === LUA_DUPLICATE_CREATION) {\n throw new EntityConflictError(\n `attr_set for correlationId \"${correlationId}\" already exists in run \"${effectiveRunId}\"`,\n );\n }\n await loadRunBody();\n return {\n event: stripEventDataRefs(\n EventSchema.parse({ ...event, eventId: result[1] }),\n entityData,\n ),\n run: existingRun\n ? await withAttributes(WorkflowRunSchema.parse(compact(existingRun)))\n : undefined,\n };\n }\n\n // A lazy hook resume is deduplicated per (run, resumeId): the queue consumer\n // re-ensures the same hook_received the producer may already have written.\n const resume =\n data.eventType === \"hook_received\" && params?.resumeId\n ? {\n id: params.resumeId,\n claim: `${params.resumePayloadDigest ?? \"\"}|${data.correlationId}`,\n }\n : undefined;\n\n // A lifecycle transition committed its own event with the status change.\n // Everything else is appended here, and guards the run and hook it is about\n // inside the script that appends: a check made before the call is stale by the\n // time the event lands.\n const stored: AppendOutcome = lifecycleEvent\n ? { kind: \"stored\", event: lifecycleEvent }\n : await appendEvent(effectiveRunId, buildEvent(), {\n entityKey: pendingEntityKey,\n entityJson: pendingEntityJson,\n dedup,\n resume,\n step: pendingStep,\n runMustBeLive:\n data.eventType === \"hook_received\" ||\n data.eventType === \"wait_created\" ||\n data.eventType === \"step_started\",\n hookMustExist: data.eventType === \"hook_received\",\n });\n if (stored.kind === \"duplicate\") {\n throw new EntityConflictError(`\"${data.correlationId}\" already exists`);\n }\n if (stored.kind === \"alreadyCompleted\") {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`,\n );\n }\n if (stored.kind === \"stepTerminal\") {\n // EntityConflictError so core's step handler skips the duplicate delivery.\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind === \"stepMoved\") {\n // A start that lost to another start is the claim working. Any other write\n // was computed from a stale copy of the step: redo it from a fresh read.\n if (\n data.eventType !== \"step_started\" &&\n staleRetries < MAX_STALE_RETRIES\n ) {\n return createEvent(runId, data, params, staleRetries + 1);\n }\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" was moved by another delivery (attempt ${stored.attempt})`,\n );\n }\n if (stored.kind === \"runTerminal\") {\n if (data.eventType === \"step_started\") {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${stored.status}\"`,\n );\n }\n throw new EntityConflictError(\n `Cannot add ${data.eventType} to run in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind === \"hookGone\") {\n throw new HookNotFoundError(data.correlationId!);\n }\n if (stored.kind === \"claimed\") {\n // Another writer already recorded this resume; converge on its event.\n const [claimedEventId, claimedDigest, claimedHookId] =\n stored.claim.split(\"|\");\n if (claimedHookId !== data.correlationId) {\n throw new EntityConflictError(\n `hook_received resumeId \"${params!.resumeId}\" already recorded for a different hook`,\n );\n }\n if (\n params?.resumePayloadDigest &&\n claimedDigest &&\n claimedDigest !== params.resumePayloadDigest\n ) {\n throw new EntityConflictError(\n `hook_received resumeId \"${params!.resumeId}\" already recorded with a different payload`,\n );\n }\n const [existingEvent] = await readEvents(effectiveRunId, [\n claimedEventId,\n ]);\n if (!existingEvent) {\n throw new WorkflowWorldError(`Event not found: ${claimedEventId}`, {\n status: 404,\n });\n }\n return { event: stripEventDataRefs(existingEvent, entityData) };\n }\n\n // Preload the run's log on run_started to save the caller a list.\n let preloaded:\n | { events: Event[]; cursor: string | null; hasMore: boolean }\n | undefined;\n if (\n data.eventType === \"run_started\" &&\n run &&\n params?.skipPreload !== true\n ) {\n const total = await redis.hlen(eventsKey(effectiveRunId));\n const all = await readSlots(effectiveRunId, FIRST_EVENT_SLOT, total);\n preloaded = {\n events: all.map((e) => stripEventDataRefs(e, resolveData)),\n cursor: all.at(-1)?.eventId ?? null,\n hasMore: false,\n };\n }\n\n return {\n event: stripEventDataRefs(stored.event, entityData),\n run: run ? await withAttributes(run) : undefined,\n step,\n hook,\n ...preloaded,\n // Server-owned per-run event ceiling; the runtime enforces it. Only\n // meaningful when a run entity is attached (run-lifecycle responses).\n ...(run ? { maxEvents: maxEventsPerRun } : {}),\n } as EventResult;\n }\n\n return {\n // Wrapped rather than folded into `createEvent`, which has a dozen commit\n // points: the delta and the skipped-slot report are the same at every one\n // of them (read the committed id, read back what is around it).\n create: (async (\n runId: string | null,\n data: CreateEventRequest | RunCreatedEventRequest,\n params?: CreateEventParams,\n ): Promise<EventResult> => {\n const result = await createEvent(runId, data, params);\n // A preload (run_started) already owns events/cursor/hasMore.\n if (!result.event || result.events !== undefined) return result;\n const resolveData = params?.resolveData ?? \"all\";\n // The delta wins when both were asked for: the skipped slots all sit above\n // the cursor, so it is a strict superset, and it is the only one of the two\n // that advances `cursor`.\n if (typeof params?.sinceCursor === \"string\") {\n return deltaSince(result, params.sinceCursor, resolveData);\n }\n if (params?.eventCount !== undefined) {\n return reportSkippedSlots(result, params.eventCount, resolveData);\n }\n return result;\n }) as Storage[\"events\"][\"create\"],\n\n async get(\n runId: string,\n eventId: string,\n params?: GetEventParams,\n ): Promise<Event> {\n const data = await redis.hget(eventsKey(runId), eventId);\n if (!data) {\n throw new WorkflowWorldError(`Event not found: ${eventId}`, {\n status: 404,\n });\n }\n const event = EventSchema.parse(compact(parse<Event>(data)));\n return stripEventDataRefs(event, params?.resolveData ?? \"all\");\n },\n\n async list(params: ListEventsParams): Promise<EventListResponse> {\n const sortOrder = params.pagination?.sortOrder || \"asc\";\n const fromCursor = params.pagination?.cursor;\n const total = await redis.hlen(eventsKey(params.runId));\n // The log is dense, so a page is a run of consecutive slots.\n const limit = params.pagination?.limit ?? Math.max(total, 1);\n\n let cursorSlot: number | null = null;\n if (fromCursor) {\n cursorSlot = eventIdToSlot(fromCursor);\n if (cursorSlot === null) {\n throw new WorkflowWorldError(\n `Invalid pagination cursor \"${fromCursor}\"`,\n {\n status: 400,\n },\n );\n }\n }\n\n let events: Event[];\n let hasMore: boolean;\n if (sortOrder === \"desc\") {\n const last =\n cursorSlot === null ? total : Math.min(cursorSlot - 1, total);\n const first = Math.max(FIRST_EVENT_SLOT, last - limit + 1);\n events = (await readSlots(params.runId, first, last)).reverse();\n hasMore = first > FIRST_EVENT_SLOT;\n } else {\n const first = (cursorSlot ?? 0) + 1;\n const last = Math.min(total, first + limit - 1);\n events = await readSlots(params.runId, first, last);\n hasMore = last < total;\n }\n\n const resolveData = params.resolveData ?? \"all\";\n return {\n data: events.map((event) => stripEventDataRefs(event, resolveData)),\n // Echo the cursor back on an empty page so a poller keeps its place.\n cursor: events.at(-1)?.eventId ?? fromCursor ?? null,\n hasMore,\n };\n },\n\n async listByCorrelationId(\n params: ListEventsByCorrelationIdParams,\n ): Promise<PaginatedResponse<Event>> {\n const limit = params.pagination?.limit ?? 100;\n const sortOrder = params.pagination?.sortOrder || \"asc\";\n const fromCursor = params.pagination?.cursor;\n const indexKey = eventsByCorrelationKey(\n params.runId,\n params.correlationId,\n );\n\n // Members are event ids scored by slot, so a cursor is a score bound.\n let ids: string[];\n if (sortOrder === \"desc\") {\n const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;\n const max = cursorSlot === null ? \"+inf\" : `(${cursorSlot}`;\n ids = await redis.zrevrangebyscore(\n indexKey,\n max,\n \"-inf\",\n \"LIMIT\",\n 0,\n limit + 1,\n );\n } else {\n const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;\n const min = cursorSlot === null ? \"-inf\" : `(${cursorSlot}`;\n ids = await redis.zrangebyscore(\n indexKey,\n min,\n \"+inf\",\n \"LIMIT\",\n 0,\n limit + 1,\n );\n }\n\n const page = ids.slice(0, limit);\n const events = await readEvents(params.runId, page);\n const resolveData = params.resolveData ?? \"all\";\n return {\n data: events.map((event) => stripEventDataRefs(event, resolveData)),\n cursor: events.at(-1)?.eventId ?? fromCursor ?? null,\n hasMore: ids.length > limit,\n };\n },\n };\n}\n\n/**\n * Create storage for workflow steps using Redis hashes and sorted sets\n */\nexport function createStepsStorage(\n config: RedisStorageConfig,\n): Storage[\"steps\"] {\n const { redis, keyPrefix } = config;\n\n const { stepKey, stepsIndexKey } = keys(keyPrefix);\n\n async function getStepData(\n key: string,\n stepId: string,\n params?: GetStepParams,\n ): Promise<Step | StepWithoutData> {\n const data = await redis.get(key);\n\n if (!data) {\n throw new WorkflowWorldError(`Step not found: ${stepId}`, {\n status: 404,\n });\n }\n\n const step = parse<Step>(data);\n const parsed = StepSchema.parse(compact(step));\n const resolveData = params?.resolveData ?? \"all\";\n return filterStepData(parsed, resolveData);\n }\n\n return {\n // A step id only identifies a step within its run, so the run is part of the key.\n get: (async (runId: string, stepId: string, params?: GetStepParams) =>\n getStepData(\n stepKey(runId, stepId),\n stepId,\n params,\n )) as Storage[\"steps\"][\"get\"],\n\n list: (async (params: ListWorkflowRunStepsParams) => {\n const limit = params?.pagination?.limit ?? 20;\n const fromCursor = params?.pagination?.cursor;\n\n const entries = await pageIndex(\n redis,\n stepsIndexKey(params.runId),\n fromCursor,\n limit + 1,\n params?.pagination?.sortOrder ?? \"desc\",\n );\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(stepKey(params.runId, id));\n }\n const results = await pipeline.exec();\n\n const resolveData = params?.resolveData ?? \"all\";\n const steps: { step: Step | StepWithoutData; cursor: string }[] = [];\n for (const [i, result] of (results ?? []).entries()) {\n if (result?.[1]) {\n const step = parse<Step>(result[1] as string);\n const parsed = StepSchema.parse(compact(step));\n steps.push({\n step: filterStepData(parsed, resolveData),\n cursor: entries[i].cursor,\n });\n }\n }\n\n const values = steps.slice(0, limit);\n const hasMore = steps.length > limit;\n\n return {\n data: values.map((entry) => entry.step),\n hasMore,\n cursor: values.at(-1)?.cursor ?? null,\n };\n }) as Storage[\"steps\"][\"list\"],\n };\n}\n\n/**\n * Create storage for hooks using Redis hashes and sorted sets\n */\nexport function createHooksStorage(\n config: RedisStorageConfig,\n): Storage[\"hooks\"] {\n const { redis, keyPrefix } = config;\n\n const {\n hookKey: hookKeyFn,\n hooksByTokenKey,\n hooksIndexKey,\n runsByStatusKey,\n } = keys(keyPrefix);\n\n // A finished run holds no hooks, so every hook is in the index of a live run.\n // shortcut: one index read per live run on each page, upgrade to a global hooks\n // index (kept in the create/dispose/finish scripts) if that count gets large.\n async function liveHooksIndexKeys(): Promise<string[]> {\n const live = await Promise.all(\n [\"pending\", \"running\"].map((status) =>\n redis.zrange(runsByStatusKey(status), \"0\", \"-1\"),\n ),\n );\n return live.flat().map(hooksIndexKey);\n }\n\n return {\n async get(hookId: string, params?: GetHookParams): Promise<Hook> {\n const data = await redis.get(hookKeyFn(hookId));\n if (!data) {\n throw new HookNotFoundError(hookId);\n }\n const hook = parse<Hook>(data);\n const parsed = HookSchema.parse(compact(hook));\n const resolveData = params?.resolveData ?? \"all\";\n return filterHookData(parsed, resolveData);\n },\n\n async getByToken(token: string, params?: GetHookParams): Promise<Hook> {\n const hookId = await redis.get(hooksByTokenKey(token));\n if (!hookId) {\n throw new HookNotFoundError(token);\n }\n return this.get(hookId, params);\n },\n\n async list(params: ListHooksParams): Promise<PaginatedResponse<Hook>> {\n const limit = params?.pagination?.limit ?? 100;\n const fromCursor = params?.pagination?.cursor;\n\n const entries = await pageIndex(\n redis,\n params.runId ? hooksIndexKey(params.runId) : await liveHooksIndexKeys(),\n fromCursor,\n limit + 1,\n params?.pagination?.sortOrder ?? \"asc\",\n );\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(hookKeyFn(id));\n }\n const results = await pipeline.exec();\n\n const hooks: { hook: Hook; cursor: string }[] = [];\n for (const [i, result] of (results ?? []).entries()) {\n if (result?.[1]) {\n const hook = parse<Hook>(result[1] as string);\n const parsed = HookSchema.parse(compact(hook));\n hooks.push({\n hook: filterHookData(parsed, params?.resolveData ?? \"all\"),\n cursor: entries[i].cursor,\n });\n }\n }\n\n const values = hooks.slice(0, limit);\n const hasMore = hooks.length > limit;\n\n return {\n data: values.map((entry) => entry.hook),\n cursor: values.at(-1)?.cursor ?? null,\n hasMore,\n };\n },\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport type {\n GetChunksOptions,\n StreamChunk,\n StreamChunksResponse,\n StreamInfoResponse,\n Streamer,\n} from \"@workflow/world\";\nimport type { Redis } from \"ioredis\";\nimport { keys } from \"./keys.js\";\nimport { debug } from \"./util.js\";\n\ninterface StreamPublishMessage {\n runId: string;\n streamId: string;\n entryId: string;\n /** Base64 chunk, inline so subscribers need no XRANGE per notification. */\n data: string;\n eof: boolean;\n /**\n * The entry that came before this one in the stream ('' for the first).\n * Pub/sub does not guarantee delivery, so a reader that sees an entry whose\n * predecessor is not the last one it delivered knows a message was lost and\n * reads the stream instead of skipping it.\n */\n prevId: string;\n}\n\nfunction parseStreamPublishMessage(raw: string): StreamPublishMessage | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const { runId, streamId, entryId, data, eof, prevId } = parsed as Record<\n string,\n unknown\n >;\n if (typeof runId !== \"string\" || typeof streamId !== \"string\") return null;\n if (typeof entryId !== \"string\" || typeof prevId !== \"string\") return null;\n if (typeof data !== \"string\" || typeof eof !== \"boolean\") return null;\n return { runId, streamId, entryId, data, eof, prevId };\n}\n\ninterface StreamChunkEvent {\n id: string;\n data: Uint8Array;\n eof: boolean;\n /** Set on live notifications: see `StreamPublishMessage.prevId`. */\n prevId?: string;\n}\n\n/** A reader also re-reads the stream this often, in case a notification and the\n * reconnect hook both missed something. Notifications are the fast path. */\nconst CATCH_UP_INTERVAL_MS = 2_000;\n\n/**\n * Compare two Redis stream entry IDs (`<ms>-<seq>`) numerically.\n *\n * String comparison is NOT safe here: within one millisecond `...-10` compares\n * lexicographically smaller than `...-9`, which would drop chunks (and the eof\n * marker) once the sequence number crosses a digit boundary.\n */\nfunction compareStreamEntryIds(a: string, b: string): number {\n const [aMs, aSeq] = a.split(\"-\").map(Number);\n const [bMs, bSeq] = b.split(\"-\").map(Number);\n return aMs - bMs || aSeq - bSeq;\n}\n\ninterface StreamerConfig {\n redis: Redis;\n keyPrefix: string;\n}\n\n/**\n * Append one or more chunks, index the stream under its run, and notify\n * subscribers in one round trip. The publish could not be pipelined with the\n * append because it needs the entry ID `XADD` generates; Lua makes that\n * dependency server-side. Each chunk rides along in its message so subscribers\n * do not `XRANGE` per notification.\n *\n * A stream that already holds its eof marker is closed: the append is dropped\n * and nothing is published. Readers stop at the first eof anyway, so this only\n * keeps the invariant that the eof marker, when present, is the final entry.\n * `getInfo` relies on it to answer from `XLEN` and the tail entry alone, and a\n * producer retrying a lost-ACK `close()` would otherwise break it.\n *\n * KEYS[1] = stream key\n * KEYS[2] = streams-by-run key\n * ARGV[1] = notification channel\n * ARGV[2] = run ID\n * ARGV[3] = stream name\n * ARGV[4] = 'true' | 'false' (eof marker, applied to every chunk below)\n * ARGV[5..] = base64 chunk data, in write order\n * Returns: 1 if appended, 0 if the stream was already closed\n */\nconst LUA_APPEND_AND_PUBLISH = `\n local streamKey = KEYS[1]\n local runIndexKey = KEYS[2]\n local channel = ARGV[1]\n local runId = ARGV[2]\n local streamId = ARGV[3]\n local eof = ARGV[4]\n\n local tail = redis.call('XREVRANGE', streamKey, '+', '-', 'COUNT', 1)\n if #tail > 0 and tail[1][2][4] == 'true' then\n return 0\n end\n\n local prevId = ''\n if #tail > 0 then\n prevId = tail[1][1]\n end\n\n for i = 5, #ARGV do\n local data = ARGV[i]\n local entryId = redis.call('XADD', streamKey, '*', 'data', data, 'eof', eof)\n redis.call('PUBLISH', channel, cjson.encode({\n runId = runId,\n streamId = streamId,\n entryId = entryId,\n data = data,\n eof = eof == 'true',\n prevId = prevId\n }))\n prevId = entryId\n end\n redis.call('SADD', runIndexKey, streamId)\n return 1\n`;\n\n/** An XRANGE entry, by the field order `LUA_APPEND_AND_PUBLISH` writes: data, then eof. */\nfunction decodeEntry([id, fields]: [string, string[]]): StreamChunkEvent {\n return {\n id,\n data: Buffer.from(fields[1]!, \"base64\"),\n eof: fields[3] === \"true\",\n };\n}\n\ntype RedisWithStreamScript = Redis & {\n wfStreamAppend(...args: string[]): Promise<number>;\n};\n\n/**\n * Create a streamer implementation using Redis Streams.\n *\n * Uses Redis auto-generated stream entry IDs (timestamp-sequence format)\n * instead of custom IDs, since Redis Streams require IDs in\n * `<millisecondsTime>-<sequenceNumber>` format.\n *\n * Key layout (every key is scoped to the run that owns the stream, so two runs\n * can use the same stream name without sharing chunks):\n * - `<prefix>stream:<runId>:<name>` Redis Stream of the chunks plus the eof marker\n * - `<prefix>streams:by_run:<runId>` Set of the run's stream names\n * - `<prefix>stream_notify` pub/sub channel carrying live chunks\n */\nexport function createStreamer(\n config: StreamerConfig,\n): Streamer & { close(): Promise<void> } {\n const { redis, keyPrefix } = config;\n const events = new EventEmitter<{\n [key: `strm:${string}`]: [StreamChunkEvent];\n }>();\n const tails = new Map<string, Promise<unknown>>();\n\n // Serialize work per stream key, so concurrent pub/sub notifications for the\n // same stream are processed in order. A key's tail is dropped once it settles last.\n const withStreamMutex = <T>(\n key: string,\n fn: () => Promise<T>,\n ): Promise<T> => {\n const run = (tails.get(key) ?? Promise.resolve()).then(fn, fn);\n const tail = run.catch(() => {});\n tails.set(key, tail);\n void tail.then(() => {\n if (tails.get(key) === tail) tails.delete(key);\n });\n return run;\n };\n\n redis.defineCommand(\"wfStreamAppend\", {\n numberOfKeys: 2,\n lua: LUA_APPEND_AND_PUBLISH,\n });\n const scripted = redis as RedisWithStreamScript;\n\n // `streamsByRunKey` indexes a run's stream names, populated on every\n // write/close so `streams.list` can enumerate them.\n const {\n streamKey,\n streamsByRunKey,\n streamChannel: STREAM_CHANNEL,\n } = keys(keyPrefix);\n const emitterKey = (runId: string, name: string) =>\n `strm:${runId}:${name}` as const;\n\n const subscriber = redis.duplicate();\n\n // A PUBLISH sent before SUBSCRIBE is ready is lost, and a reader waiting on it\n // hangs, so every append awaits this first.\n const subscriptionReady: Promise<void> = subscriber\n .subscribe(STREAM_CHANNEL)\n .then(() => {});\n\n // Anything published while the subscriber connection was down is gone, so on\n // every reconnect the live readers re-read their streams.\n const resync = new EventEmitter();\n resync.setMaxListeners(0);\n let subscriberConnected = false;\n subscriber.on(\"ready\", () => {\n if (subscriberConnected) resync.emit(\"resync\");\n subscriberConnected = true;\n });\n\n subscriber.on(\"message\", async (channel, message) => {\n if (channel !== STREAM_CHANNEL) return;\n\n try {\n const parsed = parseStreamPublishMessage(message);\n if (!parsed) return;\n\n const key = emitterKey(parsed.runId, parsed.streamId);\n if (!events.listenerCount(key)) {\n return;\n }\n\n await withStreamMutex(key, async () => {\n // The chunk travels with the notification, so no XRANGE per message.\n events.emit(key, {\n id: parsed.entryId,\n data: Buffer.from(parsed.data, \"base64\"),\n eof: parsed.eof,\n prevId: parsed.prevId,\n });\n });\n } catch (error) {\n console.error(\"Error processing stream notification:\", error);\n }\n });\n\n const toBase64 = (chunk: string | Uint8Array): string =>\n (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)).toString(\"base64\");\n\n const append = async (\n runId: string,\n name: string,\n eof: boolean,\n encodedChunks: string[],\n ): Promise<void> => {\n await subscriptionReady;\n\n await scripted.wfStreamAppend(\n streamKey(runId, name),\n streamsByRunKey(runId),\n STREAM_CHANNEL,\n runId,\n name,\n eof ? \"true\" : \"false\",\n ...encodedChunks,\n );\n };\n\n return {\n streams: {\n async write(\n _runId: string | Promise<string>,\n name: string,\n chunk: string | Uint8Array,\n ): Promise<void> {\n const runId = await _runId;\n await append(runId, name, false, [toBase64(chunk)]);\n },\n\n async writeMulti(\n _runId: string | Promise<string>,\n name: string,\n chunks: (string | Uint8Array)[],\n ): Promise<void> {\n if (chunks.length === 0) return;\n\n const runId = await _runId;\n\n // One script call appends every chunk, so they land contiguously and\n // in array order.\n await append(runId, name, false, chunks.map(toBase64));\n },\n\n async close(\n _runId: string | Promise<string>,\n name: string,\n ): Promise<void> {\n const runId = await _runId;\n\n // Final chunk carries eof=true. Same single-round-trip append as\n // above, which also keeps the stream indexed when it closes without\n // any data.\n await append(runId, name, true, [\"\"]);\n },\n\n async get(\n runId: string,\n name: string,\n startIndex?: number,\n ): Promise<ReadableStream<Uint8Array>> {\n const key = emitterKey(runId, name);\n const cleanups: (() => void)[] = [];\n let cleanedUp = false;\n // Idempotent: reachable from eof, cancel() and a failed initial read,\n // and more than one of them can fire for the same reader (for example\n // cancel() while the initial XRANGE is in flight).\n const cleanup = () => {\n if (cleanedUp) return;\n cleanedUp = true;\n for (const fn of cleanups) fn();\n };\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n let lastEntryId = \"\";\n let offset = startIndex ?? 0;\n let buffer = [] as StreamChunkEvent[] | null;\n\n function enqueue(msg: StreamChunkEvent) {\n // The reader was cancelled while the initial read was in flight,\n // or the eof marker was already delivered. Nothing may be\n // enqueued on the controller any more.\n if (cleanedUp) return;\n\n // Already delivered, or out of order.\n if (\n lastEntryId !== \"\" &&\n compareStreamEntryIds(lastEntryId, msg.id) >= 0\n )\n return;\n // Record the entry before the offset check: an entry skipped by\n // the offset must not be skipped (and counted) a second time when\n // it shows up again as a buffered live message.\n lastEntryId = msg.id;\n\n // The eof marker is not a data chunk (`getInfo`'s tailIndex\n // excludes it), so it never counts toward the offset: a start\n // index at or past the data count must still close the stream\n // rather than consume the marker and then hang.\n if (offset > 0 && !msg.eof) {\n offset--;\n return;\n }\n\n if (msg.data.byteLength) {\n controller.enqueue(new Uint8Array(msg.data));\n }\n if (msg.eof) {\n cleanup();\n controller.close();\n }\n }\n\n // Read what the stream holds beyond the last delivered entry. Notifications\n // are fire-and-forget, so this is how a lost one is recovered. Runs one\n // at a time; a request that arrives meanwhile triggers one more pass.\n let catchingUp = false;\n let again = false;\n async function catchUp() {\n if (cleanedUp || buffer) return;\n if (catchingUp) {\n again = true;\n return;\n }\n catchingUp = true;\n try {\n do {\n again = false;\n const entries = await redis.xrange(\n streamKey(runId, name),\n lastEntryId === \"\" ? \"-\" : `(${lastEntryId}`,\n \"+\",\n );\n for (const entry of entries) enqueue(decodeEntry(entry));\n } while (again && !cleanedUp);\n } catch (error) {\n // Transient (connection loss): the next trigger reads again.\n debug(\"Stream catch-up failed:\", error);\n } finally {\n catchingUp = false;\n }\n }\n\n // A live notification. One whose predecessor we never delivered means an\n // earlier one was lost: read the stream rather than skip past it.\n function deliverLive(data: StreamChunkEvent) {\n if (data.prevId !== undefined && data.prevId !== lastEntryId) {\n void catchUp();\n return;\n }\n enqueue(data);\n }\n\n function onData(data: StreamChunkEvent) {\n if (buffer) {\n buffer.push(data);\n return;\n }\n deliverLive(data);\n }\n\n // Subscribe before reading history so nothing published in between\n // is missed; `buffer` holds those until the history is replayed.\n events.on(key, onData);\n cleanups.push(() => {\n events.off(key, onData);\n });\n\n const chunks = await redis\n .xrange(streamKey(runId, name), \"-\", \"+\")\n .catch((err) => {\n // A failed read fails the stream; detach the listener so a\n // failing stream does not leak one per attempt.\n cleanup();\n throw err;\n });\n\n const parsedChunks = chunks.map(decodeEntry);\n\n // Resolve a negative start index against the data chunks stored\n // right now (everything before the eof marker): -3 on a stream\n // with 10 chunks starts at chunk 7. Clamped to 0.\n if (offset < 0) {\n const firstEof = parsedChunks.findIndex((chunk) => chunk.eof);\n const dataCount =\n firstEof === -1 ? parsedChunks.length : firstEof;\n offset = Math.max(0, dataCount + offset);\n }\n\n const buffered = buffer ?? [];\n buffer = null;\n\n // The history is the stream as it was read, so it goes in as is. What was\n // buffered while it was read is live traffic, and a message lost there\n // would leave a hole, so it goes through the same gap check.\n for (const chunk of parsedChunks) {\n enqueue(chunk);\n }\n for (const chunk of buffered) {\n deliverLive(chunk);\n }\n\n // Cover a notification lost while the history was being read, after a\n // reconnect, and by a timer in case both miss.\n resync.on(\"resync\", catchUp);\n const timer = setInterval(\n () => void catchUp(),\n CATCH_UP_INTERVAL_MS,\n );\n timer.unref();\n cleanups.push(() => {\n resync.off(\"resync\", catchUp);\n clearInterval(timer);\n });\n await catchUp();\n },\n cancel() {\n cleanup();\n },\n });\n },\n\n async list(runId: string): Promise<string[]> {\n return (await redis.smembers(streamsByRunKey(runId))) ?? [];\n },\n\n async getChunks(\n runId: string,\n name: string,\n options?: GetChunksOptions,\n ): Promise<StreamChunksResponse> {\n const limit = Math.min(options?.limit ?? 100, 1000);\n\n // Cursor carries the running 0-based data-chunk index plus the last\n // returned entry ID, letting us resume with a bounded XRANGE instead of\n // rescanning the whole stream on every page.\n let dataIndex = 0;\n let start = \"-\";\n if (options?.cursor) {\n try {\n const decoded = JSON.parse(\n Buffer.from(options.cursor, \"base64\").toString(\"utf-8\"),\n ) as {\n i?: number;\n id?: string;\n };\n if (typeof decoded.i === \"number\") dataIndex = decoded.i;\n // '(' makes the range start exclusive of the last returned entry.\n if (typeof decoded.id === \"string\") start = `(${decoded.id}`;\n } catch {\n // Malformed cursor -> restart from the beginning of the stream.\n dataIndex = 0;\n start = \"-\";\n }\n }\n\n // Fetch one extra entry to detect whether more data pages follow.\n const entries = await redis.xrange(\n streamKey(runId, name),\n start,\n \"+\",\n \"COUNT\",\n limit + 1,\n );\n\n const data: StreamChunk[] = [];\n let done = false;\n let hasMore = false;\n let lastId: string | null = null;\n\n for (const entry of entries) {\n const { id, data: bytes, eof } = decodeEntry(entry);\n if (eof) {\n // The eof marker is always the terminal entry, so reaching it means\n // the stream is complete and no further data pages exist.\n done = true;\n break;\n }\n if (data.length >= limit) {\n // A data entry beyond the requested page: more pages remain.\n hasMore = true;\n break;\n }\n data.push({\n index: dataIndex,\n data: new Uint8Array(bytes),\n });\n dataIndex++;\n lastId = id;\n }\n\n const cursor =\n hasMore && lastId\n ? Buffer.from(\n JSON.stringify({ i: dataIndex, id: lastId }),\n ).toString(\"base64\")\n : null;\n\n return { data, cursor, hasMore, done };\n },\n\n async getInfo(runId: string, name: string): Promise<StreamInfoResponse> {\n const key = streamKey(runId, name);\n const [length, tail] = await Promise.all([\n redis.xlen(key),\n redis.xrevrange(key, \"+\", \"-\", \"COUNT\", 1),\n ]);\n // The eof marker is always the final entry (the append script drops\n // anything written after it, and auto-generated IDs are monotonic), so\n // the last entry alone tells us whether the stream is done. Data chunks\n // are the non-eof entries; an empty stream yields tailIndex -1.\n const done = tail.length > 0 && tail[0][1][3] === \"true\";\n const dataCount = length - (done ? 1 : 0);\n return { tailIndex: dataCount - 1, done };\n },\n },\n\n async close(): Promise<void> {\n // Tear down the duplicated pub/sub connection so short-lived processes\n // do not leak it.\n await subscriber.quit();\n },\n };\n}\n","import {\n mintedSpecVersion,\n reenqueueActiveRuns,\n type World,\n} from \"@workflow/world\";\nimport { WorkflowRunNotFoundError } from \"@workflow/errors\";\nimport { Redis } from \"ioredis\";\nimport {\n resolveConfig,\n type RedisBackedWorldConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nimport { createReaper, hasRetention, validateRetention } from \"./reaper.js\";\nimport { createRunId } from \"./run-id.js\";\nimport {\n createEventsStorage,\n createHooksStorage,\n createRunsStorage,\n createStepsStorage,\n} from \"./storage.js\";\nimport { createStreamer } from \"./streamer.js\";\nimport type {\n QueueStats,\n WorldQueue,\n WorldQueueOptions,\n} from \"./world-queue.js\";\n\nexport type RedisBackedWorld = World & {\n start(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n /** Run one retention sweep now; returns the runs deleted. 0 without `retention`. */\n sweepRetention(): Promise<number>;\n};\n\n/**\n * A world on Redis: storage, streams and retention are the same for every\n * queue; `createQueue` supplies the queue. `config` is laid over `env`, so an\n * option the caller leaves out still comes from the environment.\n */\nexport function createRedisBackedWorld<C extends RedisBackedWorldConfig>(\n config: Partial<C>,\n world: {\n env: C;\n createQueue(\n redis: Redis,\n config: ResolvedConfig<C>,\n options: WorldQueueOptions,\n ): WorldQueue;\n /** Log prefix for run recovery on start. */\n label: string;\n debug: (...args: unknown[]) => void;\n },\n): RedisBackedWorld {\n const merged: C = { ...world.env };\n for (const [key, value] of Object.entries(config)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n const cfg = resolveConfig(merged);\n // Batches commands issued in the same event-loop tick into one write. Does\n // nothing for a single serial run, but collapses syscalls under concurrency:\n // measured 1.75x at 256 concurrent invocations, 1.15x at 32, a slight loss\n // at 1. Workers default to 10 and go higher under load, so default on.\n const autoPipelining = cfg.enableAutoPipelining;\n validateRetention(cfg.retention);\n const redis =\n typeof cfg.redis === \"string\"\n ? new Redis(cfg.redis, { enableAutoPipelining: autoPipelining })\n : new Redis({ enableAutoPipelining: autoPipelining, ...cfg.redis });\n\n const { keyPrefix } = cfg;\n const reaper = hasRetention(cfg.retention)\n ? createReaper({\n redis,\n keyPrefix,\n retention: cfg.retention,\n })\n : undefined;\n\n const storageConfig = {\n redis,\n keyPrefix,\n maxEventsPerRun: cfg.maxEventsPerRun,\n };\n const storage = {\n runs: createRunsStorage(storageConfig),\n events: createEventsStorage(storageConfig),\n hooks: createHooksStorage(storageConfig),\n steps: createStepsStorage(storageConfig),\n };\n const queue = world.createQueue(redis, cfg, {\n runHasStarted: async (runId) => {\n try {\n const run = await storage.runs.get(runId, { resolveData: \"none\" });\n return run.status !== \"pending\";\n } catch (error) {\n if (WorkflowRunNotFoundError.is(error)) return false;\n throw error;\n }\n },\n });\n const streamer = createStreamer({ redis, keyPrefix });\n\n return {\n ...storage,\n ...streamer,\n ...queue,\n // Declares support for the CBOR/binary-safe queue transport so core\n // attaches runInput to workflow messages (resilient start). The queue\n // serializes payloads with a tagged-JSON transport that round-trips\n // Uint8Array values. A function, not a constant: the version this world\n // stamps follows `WORKFLOW_SEALED_LOG`.\n specVersion: mintedSpecVersion(),\n createRunId,\n async start() {\n await queue.start();\n reaper?.start();\n // Put runs that were in flight back on the queue, in case the queue lost\n // them (a Redis restart without persistence, a failover). Replay is\n // idempotent, so a duplicate is harmless; the dedup key makes several\n // workers restarting together enqueue one message per run, not one each.\n await reenqueueActiveRuns(\n storage.runs,\n (queueName, message, opts) =>\n queue.queue(queueName, message, {\n ...opts,\n idempotencyKey: `recover:${(message as { runId: string }).runId}`,\n }),\n world.label,\n );\n },\n async sweepRetention() {\n return reaper ? reaper.sweep() : 0;\n },\n async close() {\n await reaper?.stop();\n await queue.close();\n await streamer.close();\n await redis.quit();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAgB,kBAAkB,WAAmB;CACnD,QAAQ,GAAG,SAAoB;EAC7B,MAAM,QAAQ,QAAQ,IAAI;EAC1B,IAAI,CAAC,OAAO;EAQZ,IAAI,EALF,UAAU,OACV,UAAU,UACV,UAAU,OACV,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,OAAO,GAAG,KAAK,MAAM,SAAS,IAEzC;EAGd,MAAM,SAAS,qBADG,IAAI,KAAK,EAAA,CAAE,YACF,EAAE,KAAK,UAAU;EAC5C,MAAM,UAAU,KACb,KAAK,QACJ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,MAAM,WAAW,eAAe;EAAE;EAAO;CAAU,CAAC;CAEpD,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;EAMH,aAAa,kBAAkB;EAC/B;EACA,MAAM,QAAQ;GACZ,MAAM,MAAM,MAAM;GAClB,QAAQ,MAAM;GAKd,MAAM,oBACJ,QAAQ,OACP,WAAW,SAAS,SACnB,MAAM,MAAM,WAAW,SAAS;IAC9B,GAAG;IACH,gBAAgB,WAAY,QAA8B;GAC5D,CAAC,GACH,MAAM,KACR;EACF;EACA,MAAM,iBAAiB;GACrB,OAAO,SAAS,OAAO,MAAM,IAAI;EACnC;EACA,MAAM,QAAQ;GACZ,MAAM,QAAQ,KAAK;GACnB,MAAM,MAAM,MAAM;GAClB,MAAM,SAAS,MAAM;GACrB,MAAM,MAAM,KAAK;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"world-783VJfKL.js","names":["redisKeys"],"sources":["../src/internal/debug.ts","../src/util.ts","../src/internal/serialization.ts","../src/run-id.ts","../src/world-queue.ts","../src/reaper.ts","../src/internal/util.ts","../src/storage.ts","../src/streamer.ts","../src/world.ts"],"sourcesContent":["/**\n * Creates a namespaced debug logger.\n * Logs to stderr to avoid corrupting CLI JSON output on stdout.\n *\n * Control via WORKFLOW_DEBUG environment variable:\n * WORKFLOW_DEBUG=1 // Enable all\n * WORKFLOW_DEBUG=redis-world // Named namespaces, comma-separated\n */\nexport function createDebugLogger(namespace: string) {\n return (...args: unknown[]) => {\n const debug = process.env.WORKFLOW_DEBUG;\n if (!debug) return;\n\n const enabled =\n debug === \"1\" ||\n debug === \"true\" ||\n debug === \"*\" ||\n debug.split(\",\").some((ns) => ns.trim() === namespace);\n\n if (!enabled) return;\n\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${namespace}]`;\n const message = args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg, null, 2) : String(arg),\n )\n .join(\" \");\n\n process.stderr.write(`${prefix} ${message}\\n`);\n };\n}\n","import { createDebugLogger } from \"./internal/debug.js\";\n\nexport const debug = createDebugLogger(\"redis-world\");\n","/** Standard Date fields used across all worlds */\nconst DATE_FIELDS = new Set([\n \"createdAt\",\n \"updatedAt\",\n \"startedAt\",\n \"completedAt\",\n \"retryAfter\",\n] as const);\n\n/**\n * JSON reviver that converts ISO date strings to Date objects.\n * Use with JSON.parse(json, dateReviver).\n */\nfunction dateReviver(key: string, value: unknown): unknown {\n if (\n DATE_FIELDS.has(\n key as typeof DATE_FIELDS extends Set<infer T> ? T : never,\n ) &&\n typeof value === \"string\"\n ) {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? value : date;\n }\n return value;\n}\n\n/**\n * JSON replacer that encodes Uint8Array as a tagged object with base64 data.\n */\nfunction uint8ArrayReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return {\n __type: \"Uint8Array\",\n data: Buffer.from(value).toString(\"base64\"),\n };\n }\n return value;\n}\n\n/** The Uint8Array a tagged object (`{ __type: 'Uint8Array', data: '<base64>' }`) encodes. */\nfunction taggedBinary(value: unknown): Uint8Array | undefined {\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (obj.__type === \"Uint8Array\" && typeof obj.data === \"string\") {\n return new Uint8Array(Buffer.from(obj.data, \"base64\"));\n }\n }\n return undefined;\n}\n\n/** JSON reviver that decodes tagged Uint8Array objects and ISO date strings. */\nfunction uint8ArrayReviver(key: string, value: unknown): unknown {\n return taggedBinary(value) ?? dateReviver(key, value);\n}\n\n// Handing JSON a reviver/replacer forces V8 off its fast path and calls into\n// JS for every node. The paths below keep identical semantics while avoiding\n// that: measured ~5x on parse and ~2x on stringify, holding from 6 KB to\n// 700 KB payloads. Wire format is unchanged.\n\n/** The tag `uint8ArrayReviver` decodes. Absent, only dates need reviving. */\nconst BINARY_TAG = '\"__type\"';\n\n/** Revive `DATE_FIELDS` in place at any depth — the same reach as\n * `dateReviver` under `JSON.parse`, just without the per-node JSON interop. */\nfunction reviveDatesDeep(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = reviveDatesDeep(value[i]);\n }\n return value;\n }\n const obj = value as Record<string, unknown>;\n for (const key in obj) {\n const child = obj[key];\n if (DATE_FIELDS.has(key as never) && typeof child === \"string\") {\n const date = new Date(child);\n if (!Number.isNaN(date.getTime())) {\n obj[key] = date;\n continue;\n }\n }\n obj[key] = reviveDatesDeep(child);\n }\n return obj;\n}\n\n/**\n * Is there a `Uint8Array` anywhere in the graph?\n *\n * Must stay exact: `JSON.stringify` turns a bare `Uint8Array` into\n * `{\"0\":1,...}` without complaint, so a miss is data corruption, not a slow\n * path. The walk allocates nothing, which is why it beats the replacer over\n * the same nodes.\n */\nfunction hasBinary(value: unknown): boolean {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n if (value instanceof Uint8Array) {\n return true;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (hasBinary(value[i])) {\n return true;\n }\n }\n return false;\n }\n for (const key in value as Record<string, unknown>) {\n if (hasBinary((value as Record<string, unknown>)[key])) {\n return true;\n }\n }\n return false;\n}\n\n/** Stringify with Uint8Array support. */\nexport function stringify(value: unknown): string {\n return hasBinary(value)\n ? JSON.stringify(value, uint8ArrayReplacer)\n : JSON.stringify(value);\n}\n\n/** Parse with Uint8Array and Date support. */\nexport function parse<T>(text: string): T {\n if (text.includes(BINARY_TAG)) {\n return JSON.parse(text, uint8ArrayReviver) as T;\n }\n return reviveDatesDeep(JSON.parse(text)) as T;\n}\n\n/**\n * Parse a queue message: tagged Uint8Arrays only. Queue payloads are the\n * runtime's own, so a field that happens to be named like a date stays a string.\n */\nexport function parseQueueMessage(text: string): unknown {\n return text.includes(BINARY_TAG)\n ? JSON.parse(text, (_key, value) => taggedBinary(value) ?? value)\n : JSON.parse(text);\n}\n","import { createHash } from \"node:crypto\";\nimport { encodeTime, ulid } from \"ulid\";\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst MAX_TIME = 2 ** 48 - 1;\nconst MAX_KEY_LENGTH = 1024;\n\nfunction keyedRandomness(key: string): string {\n const digest = createHash(\"sha256\").update(key).digest();\n let bits = 0n;\n for (let index = 0; index < 10; index++)\n bits = (bits << 8n) | BigInt(digest[index]);\n let out = \"\";\n for (let group = 15; group >= 0; group--)\n out += CROCKFORD[Number((bits >> BigInt(group * 5)) & 31n)];\n return out;\n}\n\n/**\n * The run id the SDK asks the world for when a run starts. Without options it is\n * a fresh ULID. With `runKey` and `runKeyTime` it is the same ULID every time, so\n * starting the same run twice creates one run: the second start finds it already\n * there.\n *\n * The id is a real ULID. Its time is `runKeyTime`, not the clock, because the SDK\n * seeds a workflow's clock from the time in its run id. Pass the time the run is\n * for, such as when the event it handles happened, and the same time on every\n * attempt.\n *\n * @param options - The options given to `start()`. `runKey` is a non-empty string\n * that names the run (at most 1024 characters), and `runKeyTime` is milliseconds\n * since the epoch.\n * @returns The id without its `wrun_` prefix, which the SDK adds.\n * @throws When `runKey` is not a usable string, or comes without a valid `runKeyTime`.\n */\nexport function createRunId(\n options?: Readonly<Record<string, unknown>>,\n): string {\n const key = options?.runKey;\n if (key === undefined) return ulid();\n if (typeof key !== \"string\" || !key || key.length > MAX_KEY_LENGTH)\n throw new TypeError(\n `runKey must be a non-empty string of at most ${MAX_KEY_LENGTH} characters`,\n );\n const time = options?.runKeyTime;\n if (\n typeof time !== \"number\" ||\n !Number.isInteger(time) ||\n time < 0 ||\n time > MAX_TIME\n )\n throw new TypeError(\n \"runKey needs runKeyTime, the time the run is for in milliseconds since the epoch, so the run id stays a valid ULID with a true time\",\n );\n return encodeTime(time, 10) + keyedRandomness(key);\n}\n\n/**\n * The idempotency key for the message that starts a run, which is the only\n * message that carries the run's input. `start()` sends no key of its own, so a\n * second start of the same run would otherwise queue a second first delivery.\n *\n * The key only covers a first message that is still queued or running. Once the\n * run has started, the queue does not enqueue the message at all (see\n * `runHasStarted` in `createWorldQueue`): the runtime runs a run's first step from the\n * first message, in parallel with `run_created`, so a late second one would run\n * that step's code again.\n *\n * @param message - The queue payload.\n * @returns A key for a run's first message, and `undefined` for every other message.\n */\nexport function initialMessageKey(message: unknown): string | undefined {\n const { runId, runInput } = (message ?? {}) as {\n runId?: unknown;\n runInput?: unknown;\n };\n return typeof runId === \"string\" && runInput !== undefined\n ? `start:${runId}`\n : undefined;\n}\n","import {\n MessageId,\n parseQueueName,\n parseQueueRoute,\n type Queue,\n type QueuePrefix,\n type ValidQueueName,\n} from \"@workflow/world\";\nimport {\n createAppRouteUrl,\n createWorkflowBaseUrl,\n createWorkflowUrl,\n} from \"@workflow/utils\";\nimport { monotonicFactory } from \"ulid\";\nimport type { RedisBackedWorldConfig, ResolvedConfig } from \"./config.js\";\nimport { parseQueueMessage, stringify } from \"./internal/serialization.js\";\nimport { initialMessageKey } from \"./run-id.js\";\n\nexport interface QueueStats {\n waiting: number;\n active: number;\n delayed: number;\n /** Finished delivery records the queue still holds; redis-world keeps none. */\n completed: number;\n failed: number;\n}\n\n/** A message as a queue backend stores it. */\nexport interface QueuedMessage {\n messageId: MessageId;\n queueName: ValidQueueName;\n /** The payload, already serialized; forwarded verbatim as the request body. */\n message: string;\n /** Extra headers the producer asked to forward; the `x-vqs-*` ones override them. */\n headers?: Record<string, string>;\n /** The route registered for this prefix when it was queued (`registerRoute`). */\n route?: string;\n}\n\n/** One delivery of a stored message, with the counters the backend keeps. */\nexport interface Delivery extends QueuedMessage {\n /** Failed deliveries plus this one, crashes included; reschedules don't count. */\n attempt: number;\n /** Every delivery that reached a handler, reschedules included. */\n deliveryCount: number;\n /** When the message was first queued (epoch ms). */\n createdAt: number;\n}\n\n/**\n * Delivers a message to its handler. Resolves to the seconds after which the\n * same message is to be delivered again without consuming an attempt, or\n * `undefined` to acknowledge it. Throws when the delivery failed and must be\n * retried.\n */\nexport type Deliver = (delivery: Delivery) => Promise<number | undefined>;\n\n/** The part of a world's queue that differs between Redis queue implementations. */\nexport interface QueueBackend {\n /** Store a message. Resolves to the id of the queued message: on an\n * `idempotencyKey` hit, the one already queued. */\n enqueue(\n message: QueuedMessage,\n opts: { idempotencyKey?: string; delaySeconds?: number },\n ): Promise<MessageId>;\n /** Start delivering stored messages through `deliver`. */\n start(deliver: Deliver): Promise<void>;\n close(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n}\n\nexport type WorldQueue = Queue & {\n start(): Promise<void>;\n close(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n};\n\nexport interface WorldQueueOptions {\n /**\n * Whether a run has moved past `pending`. The first message of a run is not\n * queued again once it has, see `initialMessageKey`.\n */\n runHasStarted?: (runId: string) => Promise<boolean>;\n}\n\n/** A response without a valid `{ timeoutSeconds }` acknowledges the message. */\nfunction parseReschedule(text: string): number | undefined {\n try {\n const seconds: unknown = JSON.parse(text)?.timeoutSeconds;\n if (typeof seconds === \"number\" && Number.isFinite(seconds) && seconds >= 0)\n return seconds;\n } catch {\n /* not a reschedule */\n }\n return undefined;\n}\n\n/**\n * The Workflow SDK `Queue` on top of a backend: message ids, the first-message\n * guard, the payload transport, HTTP or in-process delivery with the `x-vqs-*`\n * headers, and the handler that answers those deliveries.\n */\nexport function createWorldQueue(\n backend: QueueBackend,\n config: Pick<\n ResolvedConfig<RedisBackedWorldConfig>,\n \"baseUrl\" | \"httpTimeoutMs\"\n >,\n options: WorldQueueOptions & { debug: (...args: unknown[]) => void },\n): WorldQueue {\n const { debug } = options;\n const generateMessageId = monotonicFactory();\n const { httpTimeoutMs } = config;\n const directHandlers = new Map<\n QueuePrefix,\n (req: Request) => Promise<Response>\n >();\n const routes = new Map<QueuePrefix, string>();\n let closed = false;\n\n const queue: Queue[\"queue\"] = async (queueName, message, opts) => {\n if (closed) throw new Error(\"Queue is closed\");\n const { prefix } = parseQueueName(queueName);\n const messageId = MessageId.parse(`msg_${generateMessageId()}`);\n const idempotencyKey = opts?.idempotencyKey ?? initialMessageKey(message);\n if (\n !opts?.idempotencyKey &&\n idempotencyKey &&\n (await options.runHasStarted?.((message as { runId: string }).runId))\n ) {\n debug(\"run already started, not queueing its first message again\", {\n runId: (message as { runId: string }).runId,\n });\n return { messageId };\n }\n const route = routes.get(prefix);\n return {\n messageId: await backend.enqueue(\n {\n messageId,\n queueName,\n // Tagged JSON keeps Uint8Array values (e.g. the resilient-start\n // runInput.input) intact through the backend's own JSON.\n message: stringify(message),\n ...(opts?.headers && { headers: opts.headers }),\n ...(route && { route }),\n },\n { idempotencyKey, delaySeconds: opts?.delaySeconds },\n ),\n };\n };\n\n const deliver: Deliver = async (job) => {\n const { prefix } = parseQueueName(job.queueName);\n const headers = new Headers(job.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(\"x-vqs-queue-name\", job.queueName);\n headers.set(\"x-vqs-message-id\", job.messageId);\n headers.set(\"x-vqs-message-attempt\", String(job.attempt));\n headers.set(\"x-vqs-message-delivery-count\", String(job.deliveryCount));\n headers.set(\n \"x-vqs-message-created-at\",\n new Date(job.createdAt).toISOString(),\n );\n\n const deliveryRoute = routes.get(prefix) ?? job.route;\n const directHandler = directHandlers.get(prefix);\n\n let response: Response;\n if (directHandler) {\n // In process: the request a route serving `createQueueHandler(prefix, ...)`\n // would receive, without the network hop.\n const localBase = createWorkflowBaseUrl(\"http://localhost\");\n response = await directHandler(\n new Request(\n deliveryRoute\n ? createAppRouteUrl(localBase, deliveryRoute)\n : createWorkflowUrl(localBase, { type: \"flow\" }),\n { method: \"POST\", headers, body: job.message },\n ),\n );\n } else {\n const baseUrl =\n config.baseUrl ||\n process.env.WORKFLOW_BASE_URL ||\n `http://localhost:${process.env.PORT ?? \"3000\"}`;\n response = await fetch(\n deliveryRoute\n ? createAppRouteUrl(baseUrl, deliveryRoute)\n : createWorkflowUrl(baseUrl, { type: \"flow\" }),\n {\n method: \"POST\",\n headers,\n body: job.message,\n signal: AbortSignal.timeout(httpTimeoutMs),\n },\n );\n }\n\n const text = await response.text();\n if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);\n return parseReschedule(text);\n };\n\n const createQueueHandler: Queue[\"createQueueHandler\"] = (\n queueNamePrefix,\n handler,\n ) => {\n return async (req) => {\n const queueName = req.headers.get(\n \"x-vqs-queue-name\",\n ) as ValidQueueName | null;\n const messageId = req.headers.get(\"x-vqs-message-id\") as MessageId | null;\n const attemptStr = req.headers.get(\"x-vqs-message-attempt\");\n const deliveryCountStr = req.headers.get(\"x-vqs-message-delivery-count\");\n const createdAtStr = req.headers.get(\"x-vqs-message-created-at\");\n\n if (!queueName || !messageId || !attemptStr || !req.body) {\n return Response.json(\n { error: \"Missing required headers or body\" },\n { status: 400 },\n );\n }\n if (!queueName.startsWith(queueNamePrefix)) {\n return Response.json({ error: \"Unhandled queue\" }, { status: 400 });\n }\n\n const attempt = Number.parseInt(attemptStr, 10);\n const deliveryCount = deliveryCountStr\n ? Number.parseInt(deliveryCountStr, 10)\n : attempt;\n const createdAt = createdAtStr ? new Date(createdAtStr) : undefined;\n\n try {\n const body = parseQueueMessage(await req.text());\n const result = await handler(body, {\n attempt,\n deliveryCount,\n ...(createdAt && !Number.isNaN(createdAt.getTime()) && { createdAt }),\n queueName,\n messageId,\n });\n\n const timeoutSeconds = (\n result as { timeoutSeconds?: unknown } | null | undefined\n )?.timeoutSeconds;\n if (\n typeof timeoutSeconds === \"number\" &&\n Number.isFinite(timeoutSeconds)\n ) {\n return Response.json({ timeoutSeconds: Math.max(0, timeoutSeconds) });\n }\n return Response.json({ ok: true });\n } catch (error) {\n debug(\"queue handler error:\", error);\n return Response.json({ error: String(error) }, { status: 500 });\n }\n };\n };\n\n return {\n queue,\n createQueueHandler,\n getDeploymentId: async () => \"redis\",\n registerHandler(prefix, handler) {\n directHandlers.set(prefix, handler);\n },\n registerRoute(prefix, path) {\n routes.set(prefix, parseQueueRoute(path));\n },\n getQueueStats: () => backend.getQueueStats(),\n start: () => backend.start(deliver),\n async close() {\n closed = true;\n await backend.close();\n },\n };\n}\n\n/** The delay before retrying a failed delivery: the configured curve, capped. */\nexport function retryDelayMs(\n attempt: number,\n config: Pick<\n ResolvedConfig<RedisBackedWorldConfig>,\n \"backoffType\" | \"backoffDelayMs\" | \"maxBackoffMs\"\n >,\n): number {\n const delay =\n config.backoffType === \"fixed\"\n ? config.backoffDelayMs\n : config.backoffDelayMs * 2 ** Math.min(30, Math.max(0, attempt - 1));\n return Math.min(config.maxBackoffMs, delay);\n}\n","import type { Redis } from \"ioredis\";\nimport { keys as redisKeys } from \"./keys.js\";\n\n/** How long finished runs are kept, using `age` and `count` limits. */\nexport interface KeepRuns {\n /** Delete runs that finished more than this many seconds ago. */\n age?: number;\n /** Keep at most this many of the newest runs; delete the rest. */\n count?: number;\n}\n\n/**\n * Retention for run data (the run, its event log, steps, hooks, and streams),\n * per terminal status. A status without a policy is kept forever.\n */\nexport interface RunRetention {\n completed?: KeepRuns;\n failed?: KeepRuns;\n cancelled?: KeepRuns;\n /** How often each worker looks for expired runs (ms). Default: 60000 */\n sweepIntervalMs?: number;\n /** Runs deleted per status per sweep. Default: 200 */\n batchSize?: number;\n}\n\nconst TERMINAL = [\"completed\", \"failed\", \"cancelled\"] as const;\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\nconst DEFAULT_BATCH_SIZE = 200;\nconst UNLINK_CHUNK = 500;\n\nexport interface Reaper {\n start(): void;\n stop(): Promise<void>;\n /** One pass over every status; returns the number of runs deleted. */\n sweep(): Promise<number>;\n}\n\nexport function validateRetention(retention: RunRetention | undefined): void {\n if (!retention) return;\n for (const status of TERMINAL) {\n const keep = retention[status];\n if (!keep) continue;\n for (const field of [\"age\", \"count\"] as const) {\n const value = keep[field];\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new TypeError(\n `retention.${status}.${field} must be a non-negative integer, received ${String(value)}`,\n );\n }\n }\n }\n for (const field of [\"sweepIntervalMs\", \"batchSize\"] as const) {\n const value = retention[field];\n if (value !== undefined && (!Number.isInteger(value) || value < 1)) {\n throw new TypeError(\n `retention.${field} must be a positive integer, received ${String(value)}`,\n );\n }\n }\n}\n\nexport function hasRetention(\n retention: RunRetention | undefined,\n): retention is RunRetention {\n return (\n !!retention && TERMINAL.some((status) => retention[status] !== undefined)\n );\n}\n\n/**\n * Deletes finished runs once they pass their retention. Safe to run on every\n * worker: one lock per interval picks a single sweeper, and deleting a run is\n * idempotent anyway. A run's own key and index entries go last, in one\n * transaction, so a crash part-way leaves the run listed and the next sweep\n * finishes the job.\n */\nexport function createReaper(options: {\n redis: Redis;\n keyPrefix: string;\n retention: RunRetention;\n}): Reaper {\n const { redis, keyPrefix, retention } = options;\n const intervalMs = retention.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;\n const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;\n const k = redisKeys(keyPrefix);\n const byStatusKey = k.runsByStatusKey;\n let timer: NodeJS.Timeout | undefined;\n let running: Promise<unknown> = Promise.resolve();\n\n /** Runs past retention, oldest first: too old, or beyond the newest `count`. */\n async function expired(status: (typeof TERMINAL)[number]): Promise<string[]> {\n const keep = retention[status];\n if (!keep) return [];\n const ids = new Set<string>();\n if (keep.age !== undefined) {\n const cutoff = Date.now() - keep.age * 1000;\n for (const id of await redis.zrangebyscore(\n byStatusKey(status),\n \"-inf\",\n cutoff,\n \"LIMIT\",\n 0,\n batchSize,\n )) {\n ids.add(id);\n }\n }\n if (keep.count !== undefined) {\n // Everything below the newest `count`, oldest first.\n const stop = -(keep.count + 1);\n for (const id of await redis.zrange(\n byStatusKey(status),\n \"0\",\n String(stop),\n )) {\n if (ids.size >= batchSize) break;\n ids.add(id);\n }\n }\n return [...ids].slice(0, batchSize);\n }\n\n async function unlink(keys: string[]): Promise<void> {\n for (let i = 0; i < keys.length; i += UNLINK_CHUNK) {\n await redis.unlink(...keys.slice(i, i + UNLINK_CHUNK));\n }\n }\n\n async function scan(pattern: string): Promise<string[]> {\n const found: string[] = [];\n let cursor = \"0\";\n do {\n const [next, batch] = await redis.scan(\n cursor,\n \"MATCH\",\n pattern,\n \"COUNT\",\n 1000,\n );\n cursor = next;\n found.push(...batch);\n } while (cursor !== \"0\");\n return found;\n }\n\n /** Delete one run if it is still finished. Returns whether it was deleted. */\n async function deleteRun(runId: string, listedAs: string): Promise<boolean> {\n const metaKey = k.runMetaKey(runId);\n const meta = await redis.get(metaKey);\n const status = meta?.split(\"|\")[0];\n if (!status || !(TERMINAL as readonly string[]).includes(status)) {\n // Gone: drop the stale index entry. Moved on to a live status: leave it alone.\n if (!meta) await redis.zrem(byStatusKey(listedAs), runId);\n return false;\n }\n\n const runKey = k.runKey(runId);\n const runJson = await redis.get(runKey);\n const workflowName = runJson\n ? (JSON.parse(runJson) as { workflowName?: string }).workflowName\n : undefined;\n\n const eventsKey = k.eventsKey(runId);\n const correlationIds = new Set<string>();\n let hasResume = false;\n for (const raw of await redis.hvals(eventsKey)) {\n try {\n const event = JSON.parse(raw) as {\n correlationId?: string;\n eventType?: string;\n };\n if (event.correlationId) correlationIds.add(event.correlationId);\n if (event.eventType === \"hook_received\") hasResume = true;\n } catch {\n // An unreadable event still goes with the log key.\n }\n }\n\n const stepIds = await redis.zrange(k.stepsIndexKey(runId), \"0\", \"-1\");\n const hookIds = await redis.zrange(k.hooksIndexKey(runId), \"0\", \"-1\");\n const streamNames = await redis.smembers(k.streamsByRunKey(runId));\n\n const keys = k.ownedByRun(runId, {\n correlationIds,\n stepIds,\n hookIds,\n streamNames,\n });\n // Resume claims are not indexed; only a run that received a hook payload can have one.\n if (hasResume) keys.push(...(await scan(k.resumeClaimKey(runId, \"*\"))));\n await unlink(keys);\n\n const tx = redis\n .multi()\n .zrem(k.runsIndexKey(), runId)\n .zrem(byStatusKey(status), runId)\n .unlink(metaKey, runKey);\n if (workflowName) tx.zrem(k.runsByNameKey(workflowName), runId);\n await tx.exec();\n return true;\n }\n\n async function sweep(): Promise<number> {\n // One sweeper per interval; the lock simply expires.\n const locked = await redis.set(\n k.reaperLockKey,\n \"1\",\n \"PX\",\n Math.max(1000, Math.floor(intervalMs / 2)),\n \"NX\",\n );\n if (locked !== \"OK\") return 0;\n let deleted = 0;\n for (const status of TERMINAL) {\n for (const runId of await expired(status)) {\n try {\n if (await deleteRun(runId, status)) deleted++;\n } catch (err) {\n console.warn(`Retention: could not delete run ${runId}:`, err);\n }\n }\n }\n return deleted;\n }\n\n return {\n sweep,\n start() {\n if (timer) return;\n const tick = () => {\n running = sweep().catch((err) =>\n console.warn(\"Retention sweep failed:\", err),\n );\n };\n timer = setInterval(tick, intervalMs);\n timer.unref();\n },\n async stop() {\n if (timer) clearInterval(timer);\n timer = undefined;\n await running;\n },\n };\n}\n","export function compact<T extends object>(obj: T) {\n const value = {} as {\n [key in keyof T]: null extends T[key]\n ? undefined | NonNullable<T[key]>\n : T[key];\n };\n for (const key in obj) {\n if (obj[key] !== null) {\n value[key] = obj[key] as any;\n } else {\n value[key] = undefined as any;\n }\n }\n return value;\n}\n","import {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from \"@workflow/errors\";\nimport type {\n AttributeChange,\n CreateEventParams,\n CreateEventRequest,\n Event,\n EventListResponse,\n EventResult,\n EventsResolveData,\n GetEventParams,\n GetHookParams,\n GetStepParams,\n GetWorkflowRunParams,\n Hook,\n ListEventsByCorrelationIdParams,\n ListEventsParams,\n ListHooksParams,\n ListWorkflowRunStepsParams,\n ListWorkflowRunsParams,\n PaginatedResponse,\n ResolveData,\n RunCreatedEventRequest,\n Step,\n StepWithoutData,\n Storage,\n WorkflowRun,\n WorkflowRunWithoutData,\n} from \"@workflow/world\";\nimport {\n entityResolveData,\n EventSchema,\n eventIdToSlot,\n FIRST_EVENT_SLOT,\n HookSchema,\n isLegacySpecVersion,\n mintedSpecVersion,\n requiresNewerWorld,\n slotToEventId,\n StepSchema,\n stripEventDataRefs,\n validateAttributeChanges,\n WorkflowRunSchema,\n} from \"@workflow/world\";\nimport { globalSingleton } from \"@workflow/utils\";\nimport type { Redis } from \"ioredis\";\nimport { monotonicFactory } from \"ulid\";\nimport { keys } from \"./keys.js\";\nimport { compact } from \"./internal/util.js\";\n// `parse`/`stringify` take a fast path that skips JSON's reviver/replacer when\n// the payload holds no binary (~5x on parse, ~2x on stringify) with identical\n// semantics.\nimport { parse, stringify } from \"./internal/serialization.js\";\n\ninterface RedisStorageConfig {\n redis: Redis;\n keyPrefix: string;\n /** See `RedisWorldConfig.maxEventsPerRun`. */\n maxEventsPerRun?: number;\n}\n\n/** Per-run event ceiling reported to core, mirroring the Vercel World. */\nconst DEFAULT_MAX_EVENTS_PER_RUN = 25_000;\n\n/** Resolve the per-run event ceiling surfaced as `EventResult.maxEvents`:\n * explicit config, then `WORKFLOW_MAX_EVENTS`, then the default. A\n * non-positive configured value throws rather than being ignored. */\nfunction resolveMaxEventsPerRun(configured: number | undefined): number {\n if (configured !== undefined) {\n if (!Number.isInteger(configured) || configured <= 0) {\n throw new TypeError(\n `maxEventsPerRun must be a positive integer, received ${String(configured)}`,\n );\n }\n return configured;\n }\n const raw = process.env.WORKFLOW_MAX_EVENTS;\n const parsed = raw !== undefined ? Number(raw) : Number.NaN;\n return Number.isInteger(parsed) && parsed > 0\n ? parsed\n : DEFAULT_MAX_EVENTS_PER_RUN;\n}\n\n/** Events that mutate the run, so validation needs its full body. Everything\n * else only reads status/specVersion and is served from the run meta key. */\nconst RUN_LIFECYCLE_EVENT_TYPES = new Set([\n \"run_started\",\n \"run_completed\",\n \"run_failed\",\n \"run_cancelled\",\n]);\n\n/** Sentinel from the event scripts when a creation-dedup check rejects. */\nconst LUA_DUPLICATE_CREATION = -8;\n\n/**\n * Stand-in for the event id inside the event JSON the caller hands to a script.\n * The id is a log position (`evnt_` + the 1-based slot), and a position may only\n * be chosen at the commit (see `LUA_APPEND_EVENT`), so the script writes it into\n * the JSON itself. `serializeEvent` always emits `eventId` as the first key, so\n * the first match is ours whatever the payload holds. A constant, not a random\n * value: two bundled copies of this module can share one connection's scripts.\n */\nconst EVENT_ID_PLACEHOLDER = \"__brick_event_id__\";\n\n/**\n * Lua helper shared by every script that appends to a run's event log.\n *\n * A run's events live in one hash, `eventId -> JSON`. The log is dense and\n * 1-based, and a script runs atomically, so the next slot is the hash length\n * plus one and no other writer can interleave between reading it and writing the\n * event. That is the whole race story: the slot is chosen at the commit, in the\n * same operation that appends, and a writer that is behind simply lands on the\n * next free slot (the caller reports what it skipped).\n *\n * `appendEvent(eventsKey, correlationKey, json)` returns the new event id.\n * `correlationKey` may be nil. The id is written into `json` in place of the\n * placeholder, so what is stored is exactly what the reader parses.\n */\nconst LUA_APPEND_EVENT = `\nlocal function appendEvent(eventsKey, correlationKey, json)\n local slot = redis.call('HLEN', eventsKey) + 1\n local digits = string.format('%d', slot)\n local eventId = 'evnt_' .. string.rep('0', 26 - #digits) .. digits\n local from, to = string.find(json, '${EVENT_ID_PLACEHOLDER}', 1, true)\n json = string.sub(json, 1, from - 1) .. eventId .. string.sub(json, to + 1)\n redis.call('HSET', eventsKey, eventId, json)\n if correlationKey then\n redis.call('ZADD', correlationKey, slot, eventId)\n end\n return eventId\nend\n\n-- A run's status from its meta key ('<status>|<specVersion>'), or false when absent.\nlocal function runStatus(metaKey)\n local meta = redis.call('GET', metaKey)\n if not meta then\n return false\n end\n return string.match(meta, '^([^|]*)')\nend\n\nlocal function isTerminal(status)\n return status == 'completed' or status == 'failed' or status == 'cancelled'\nend\n`;\n\n/**\n * Filter hook data based on resolveData parameter\n */\nfunction filterHookData(hook: Hook, resolveData: ResolveData): Hook {\n if (resolveData === \"none\" && \"metadata\" in hook) {\n const { metadata: _, ...rest } = hook;\n return { metadata: undefined, ...rest };\n }\n return hook;\n}\n\nfunction filterStepData(step: Step, resolveData: \"none\"): StepWithoutData;\nfunction filterStepData(step: Step, resolveData: \"all\"): Step;\nfunction filterStepData(\n step: Step,\n resolveData: ResolveData,\n): Step | StepWithoutData;\nfunction filterStepData(\n step: Step,\n resolveData: ResolveData,\n): Step | StepWithoutData {\n if (resolveData === \"none\") {\n const { input: _, output: __, ...rest } = step;\n return { input: undefined, output: undefined, ...rest };\n }\n return step;\n}\n\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: \"none\",\n): WorkflowRunWithoutData;\nfunction filterRunData(run: WorkflowRun, resolveData: \"all\"): WorkflowRun;\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: ResolveData,\n): WorkflowRun | WorkflowRunWithoutData;\nfunction filterRunData(\n run: WorkflowRun,\n resolveData: ResolveData,\n): WorkflowRun | WorkflowRunWithoutData {\n if (resolveData === \"none\") {\n const { input: _, output: __, ...rest } = run;\n return { input: undefined, output: undefined, ...rest };\n }\n return run;\n}\n\n// Each script encapsulates a multi-key write operation to ensure\n// atomicity. Lua scripts execute as a single atomic operation in\n// Redis, preventing partial writes on connection failures AND\n// check-then-write races between concurrent replays: every\n// entity-creating event writes its entity and its creation event in ONE\n// script, so no probe-then-append window exists (same design as\n// world-redis).\n\n/** One member of an index page, with the cursor that resumes after it. */\ninterface IndexEntry {\n id: string;\n score: number;\n cursor: string;\n}\n\n/**\n * Read up to `want` members of one or more sorted-set indexes, in score order,\n * resuming after `cursor`. With several indexes the members are merged into one\n * ordering, which is how a listing across statuses avoids scanning an index of\n * every run there has ever been.\n *\n * A cursor is the last member's `<score>|<id>`, not its rank: a rank means\n * nothing once that member has left the index (a run that changed status, a\n * hook that was disposed), and paging would fail halfway through a listing. A\n * position by score and id stays valid wherever the member went. Members that\n * share a score are ordered by id, as Redis orders them.\n */\nasync function pageIndex(\n redis: Redis,\n indexKeys: string | string[],\n cursor: string | undefined,\n want: number,\n order: \"asc\" | \"desc\" = \"desc\",\n): Promise<IndexEntry[]> {\n let after: { score: number; id: string } | undefined;\n if (cursor) {\n const sep = cursor.indexOf(\"|\");\n const score = sep > 0 ? Number(cursor.slice(0, sep)) : Number.NaN;\n if (Number.isNaN(score)) {\n throw new WorkflowWorldError(`Invalid pagination cursor \"${cursor}\"`, {\n status: 400,\n });\n }\n after = { score, id: cursor.slice(sep + 1) };\n }\n const bound = after\n ? String(after.score)\n : order === \"desc\"\n ? \"+inf\"\n : \"-inf\";\n\n const readOne = async (indexKey: string): Promise<IndexEntry[]> => {\n const out: IndexEntry[] = [];\n const batch = Math.max(want, 50);\n let offset = 0;\n while (out.length < want) {\n const raw =\n order === \"desc\"\n ? await redis.zrevrangebyscore(\n indexKey,\n bound,\n \"-inf\",\n \"WITHSCORES\",\n \"LIMIT\",\n offset,\n batch,\n )\n : await redis.zrangebyscore(\n indexKey,\n bound,\n \"+inf\",\n \"WITHSCORES\",\n \"LIMIT\",\n offset,\n batch,\n );\n for (let i = 0; i < raw.length && out.length < want; i += 2) {\n const id = raw[i];\n const score = Number(raw[i + 1]);\n // Entries that share the cursor's score and come at or before its id were\n // on an earlier page.\n if (\n after &&\n score === after.score &&\n (order === \"desc\" ? id >= after.id : id <= after.id)\n ) {\n continue;\n }\n out.push({ id, score, cursor: `${raw[i + 1]}|${id}` });\n }\n offset += raw.length / 2;\n if (raw.length / 2 < batch) break;\n }\n return out;\n };\n\n const keys = Array.isArray(indexKeys) ? indexKeys : [indexKeys];\n if (keys.length === 1) return readOne(keys[0]);\n\n const merged = (await Promise.all(keys.map(readOne))).flat();\n const direction = order === \"desc\" ? -1 : 1;\n merged.sort(\n (x, y) =>\n direction *\n (x.score - y.score || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0)),\n );\n return merged.slice(0, want);\n}\n\n/**\n * Atomically create a run entity with all its indexes AND its creation\n * event. SETNX arbitrates duplicates: when the run already exists, NO\n * index, meta, or event write happens (a replayed run_created must not\n * reset index scores, re-insert a terminal run into the pending status\n * index, or append a second creation event).\n *\n * KEYS[1] = run key\n * KEYS[2] = runs index key\n * KEYS[3] = runs by name key\n * KEYS[4] = runs by status key (pending)\n * KEYS[5] = run meta key\n * KEYS[6] = events key (the run's log)\n * KEYS[7] = run attributes key\n * ARGV[1] = run JSON\n * ARGV[2] = run ID\n * ARGV[3] = score (timestamp)\n * ARGV[4] = run meta value (`<status>|<specVersion>`)\n * ARGV[5] = event JSON (event id left as the placeholder)\n * ARGV[6..] = attribute key, value pairs to seed\n * Returns: [1, eventId] when created, [0, runJson] on replay.\n */\nconst LUA_CREATE_RUN_WITH_EVENT = `${LUA_APPEND_EVENT}\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n local score = tonumber(ARGV[3])\n redis.call('ZADD', KEYS[2], score, ARGV[2])\n redis.call('ZADD', KEYS[3], score, ARGV[2])\n redis.call('ZADD', KEYS[4], score, ARGV[2])\n redis.call('SET', KEYS[5], ARGV[4])\n for i = 6, #ARGV, 2 do\n redis.call('HSET', KEYS[7], ARGV[i], ARGV[i + 1])\n end\n return {1, appendEvent(KEYS[6], nil, ARGV[5])}\n`;\n\n/**\n * Move a run to a new status, release its hooks when it finishes, and append the\n * lifecycle event, all in one execution. They are one script because a crash\n * between them would leave a terminal run with no terminal event (every retry is\n * then refused as terminal) or a started run with no `run_started` (the redelivery\n * takes the resume path and appends nothing).\n *\n * KEYS[1] = run key\n * KEYS[2] = old status index key\n * KEYS[3] = new status index key\n * KEYS[4] = run meta key\n * KEYS[5] = events key\n * KEYS[6] = hooks index key\n * KEYS[7] = hooks token-map key\n * ARGV[1] = updated run JSON\n * ARGV[2] = run ID\n * ARGV[3] = score (timestamp)\n * ARGV[4] = run meta value (`<status>|<specVersion>`)\n * ARGV[5] = the status the caller read the run in\n * ARGV[6] = event JSON\n * ARGV[7] = \"1\" to release the run's hooks (a terminal transition)\n * ARGV[8] = hook key prefix\n * ARGV[9] = hooks-by-token key prefix\n * Returns: [1, eventId] on success, [0, ''] if the run is absent, [-2, status] if\n * the run is no longer in the status the caller read (another writer\n * moved it first; nothing is written)\n */\nconst LUA_TRANSITION_RUN = `${LUA_APPEND_EVENT}\n if redis.call('EXISTS', KEYS[1]) == 0 then\n return {0, ''}\n end\n\n local current = runStatus(KEYS[4])\n if current and current ~= ARGV[5] then\n return {-2, current}\n end\n\n redis.call('SET', KEYS[1], ARGV[1])\n redis.call('SET', KEYS[4], ARGV[4])\n redis.call('ZREM', KEYS[2], ARGV[2])\n redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])\n\n if ARGV[7] == '1' then\n local pairsFlat = redis.call('HGETALL', KEYS[7])\n for i = 1, #pairsFlat, 2 do\n local hookId = pairsFlat[i]\n local tokenKey = ARGV[9] .. pairsFlat[i + 1]\n redis.call('DEL', ARGV[8] .. hookId)\n -- Only a token this hook still owns: a stale entry must not wipe a claim\n -- another run has taken since.\n if redis.call('GET', tokenKey) == hookId then\n redis.call('DEL', tokenKey)\n end\n end\n redis.call('DEL', KEYS[7])\n redis.call('DEL', KEYS[6])\n end\n\n return {1, appendEvent(KEYS[5], nil, ARGV[6])}\n`;\n\n/**\n * Atomically create a step entity with its index AND its creation event.\n * SETNX arbitrates duplicates: a replayed step_created writes nothing. A step is\n * never created on a finished run.\n *\n * KEYS[1] = step key\n * KEYS[2] = steps index key\n * KEYS[3] = events key\n * KEYS[4] = events by correlation key\n * KEYS[5] = step status key (see `LUA_STORE_EVENT`)\n * KEYS[6] = run meta key\n * ARGV[1] = step JSON\n * ARGV[2] = step ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = event JSON\n * ARGV[5] = step status value (`<status>|<attempt>`)\n * Returns: [1, eventId] when created, [0, stepJson] on replay, [-6, status] when\n * the run is terminal\n */\nconst LUA_CREATE_STEP_WITH_EVENT = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])\n redis.call('SET', KEYS[5], ARGV[5])\n return {1, appendEvent(KEYS[3], KEYS[4], ARGV[4])}\n`;\n\n/**\n * Lazy step start: a `step_started` that carries the step's input also creates\n * the step. The step entity (already running, attempt 1), the synthetic\n * `step_created` and the `step_started` land together, so replay still sees the\n * creation, and exactly one concurrent caller wins the SETNX and runs the body.\n *\n * KEYS[1] = step key\n * KEYS[2] = steps index key\n * KEYS[3] = events key\n * KEYS[4] = events by correlation key\n * KEYS[5] = step status key (see `LUA_STORE_EVENT`)\n * KEYS[6] = run meta key\n * ARGV[1] = step JSON (running)\n * ARGV[2] = step ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = step_created event JSON\n * ARGV[5] = step_started event JSON\n * ARGV[6] = step status value (`running|1`)\n * Returns: [1, createdEventId, startedEventId] when created, [0, stepJson] when\n * the step already exists (the caller lost the claim), [-6, status]\n * when the run is terminal\n */\nconst LUA_CREATE_STEP_STARTED = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])\n redis.call('SET', KEYS[5], ARGV[6])\n local createdId = appendEvent(KEYS[3], KEYS[4], ARGV[4])\n local startedId = appendEvent(KEYS[3], KEYS[4], ARGV[5])\n return {1, createdId, startedId}\n`;\n\n/**\n * Atomically claim a hook token and create the hook entity, its indexes,\n * token-map entry, AND its creation event. The by-token key is the claim\n * arbiter (SETNX):\n * - A DIFFERENT hookId already owning the token -> cross-run conflict; the\n * rightful owner's token mapping is left untouched. If that owner's hook no\n * longer exists (a crash during cleanup left the token behind), the token is\n * free and is taken over here, in the same execution, so a concurrent claim\n * can never be wiped.\n * - The SAME hookId owning the token with the entity present -> duplicate.\n * Entity + event are written in the same atomic script, so a crash can\n * never leave a hook entity without its hook_created event (or vice versa). A\n * hook is never created on a finished run, which would hold its token forever.\n *\n * KEYS[1] = hook key\n * KEYS[2] = hooks by token key\n * KEYS[3] = hooks index key\n * KEYS[4] = hooks token-map key (hash of hookId -> token, per run)\n * KEYS[5] = events key\n * KEYS[6] = events by correlation key\n * KEYS[7] = run meta key\n * ARGV[1] = hook JSON\n * ARGV[2] = hook ID (correlationId)\n * ARGV[3] = score (timestamp)\n * ARGV[4] = the token, recorded in the token map so terminal-run cleanup can\n * drop token lookups without reading every hook body\n * ARGV[5] = event JSON\n * ARGV[6] = hook key prefix\n * Returns: [2, owningHookId] on token conflict,\n * [0, hookJson] when the hook already exists, or has existed (created\n * and since disposed),\n * [1, eventId] on success,\n * [-6, status] when the run is terminal\n */\nconst LUA_CREATE_HOOK_WITH_EVENT = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[7])\n if status and isTerminal(status) then\n return {-6, status}\n end\n -- Disposal removes the hook and its token, so a stale writer that loaded the log\n -- before the hook existed would otherwise create it again behind its disposal.\n -- The creation event is the record that it already happened.\n if redis.call('ZCARD', KEYS[6]) > 0 then\n return {0, ''}\n end\n local claimed = redis.call('SETNX', KEYS[2], ARGV[2])\n if claimed == 0 then\n local owner = redis.call('GET', KEYS[2])\n if owner ~= ARGV[2] then\n if redis.call('EXISTS', ARGV[6] .. owner) == 1 then\n return {2, owner}\n end\n redis.call('SET', KEYS[2], ARGV[2])\n end\n end\n local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])\n if wasCreated == 0 then\n return {0, redis.call('GET', KEYS[1])}\n end\n redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])\n redis.call('HSET', KEYS[4], ARGV[2], ARGV[4])\n return {1, appendEvent(KEYS[5], KEYS[6], ARGV[5])}\n`;\n\n/**\n * Atomically dispose a hook: delete the hook key, its token lookup (only while\n * it still points at this hook), its index entry and its token-map entry, and\n * append `hook_disposed`. One script, because a crash between the delete and the\n * append would lose the event, and a delete racing a `hook_received` must not\n * leave the received event behind the disposal in the log.\n *\n * KEYS[1] = hook key\n * KEYS[2] = hooks by token key\n * KEYS[3] = hooks index key\n * KEYS[4] = hooks token-map key\n * KEYS[5] = events key\n * KEYS[6] = events by correlation key\n * ARGV[1] = hook ID (correlationId)\n * ARGV[2] = event JSON\n * Returns: [1, eventId] if disposed, [0, ''] if the hook was not found\n */\nconst LUA_DISPOSE_HOOK = `${LUA_APPEND_EVENT}\n if redis.call('DEL', KEYS[1]) == 0 then\n return {0, ''}\n end\n if redis.call('GET', KEYS[2]) == ARGV[1] then\n redis.call('DEL', KEYS[2])\n end\n redis.call('ZREM', KEYS[3], ARGV[1])\n redis.call('HDEL', KEYS[4], ARGV[1])\n return {1, appendEvent(KEYS[5], KEYS[6], ARGV[2])}\n`;\n\n/**\n * Atomically append an event to the run's log and its correlation index,\n * optionally writing an entity first so the mutation and its event commit\n * together.\n *\n * KEYS[1] = events key\n * KEYS[2] = events by correlation key (or unused placeholder)\n * KEYS[3] = entity key (or unused placeholder)\n * KEYS[4] = hook resume claim key (or unused placeholder)\n * KEYS[5] = step status key (or unused placeholder)\n * KEYS[6] = run meta key (or unused placeholder)\n * KEYS[7] = hook key (or unused placeholder)\n * ARGV[1] = event JSON\n * ARGV[2] = has correlation (\"1\" or \"0\")\n * ARGV[3] = creation dedup: \"1\" rejects when the correlation index already holds\n * an event (a wait or hook conflict recorded once), \"2\" rejects when it\n * already holds two (a wait completed once)\n * ARGV[4] = entity JSON to write to KEYS[3] ('' to write nothing)\n * ARGV[5] = resume claim payload ('' when the event is not a lazy hook resume)\n * ARGV[6] = the step's new status ('' when the event writes no step)\n * ARGV[7] = the attempt the caller read ('' to skip the check)\n * ARGV[8] = the step's new attempt ('' to keep the current one)\n * ARGV[9] = \"1\" to refuse when the run is terminal\n * ARGV[10] = \"1\" to refuse when the hook (KEYS[7]) does not exist\n *\n * A lazy hook resume is claimed per (run, resumeId): the first writer appends and\n * records `<eventId>|<claim payload>`, a later one appends nothing and gets the\n * recorded claim back, so both writers converge on one event.\n *\n * A step write is a transition out of the state the caller read, so it is checked\n * where the state lives: a terminal step takes no further write, and a write that\n * read an older attempt than the step now has lost to another writer. Without\n * this two deliveries could both record an outcome, and the log would hold both.\n * The attempt counter is kept here, not taken from the caller's possibly stale\n * copy of the step, so it only moves forward.\n *\n * The run and hook guards live here because the checks the caller makes before\n * calling are stale by the time the event is appended: a `hook_received` must not\n * land behind the hook's disposal or the run's end, which no replay can consume.\n *\n * Returns: [1, eventId] on success, [-8, ''] when creation dedup rejects,\n * [-7, ''] when completion dedup rejects, [3, claim] when a resume claim\n * already exists, [-3, status] when the step is already terminal,\n * [-4, attempt] when the step has moved past the attempt the caller\n * read, [-6, status] when the run is terminal, [-5, ''] when the hook\n * is gone\n */\nconst LUA_STORE_EVENT = `${LUA_APPEND_EVENT}\n if ARGV[5] ~= '' then\n local claim = redis.call('GET', KEYS[4])\n if claim then\n return {3, claim}\n end\n end\n\n if ARGV[10] == '1' and redis.call('EXISTS', KEYS[7]) == 0 then\n return {-5, ''}\n end\n\n if ARGV[9] == '1' then\n local status = runStatus(KEYS[6])\n if status and isTerminal(status) then\n return {-6, status}\n end\n end\n\n if ARGV[3] == '1' and redis.call('ZCARD', KEYS[2]) > 0 then\n return {${LUA_DUPLICATE_CREATION}, ''}\n end\n if ARGV[3] == '2' and redis.call('ZCARD', KEYS[2]) > 1 then\n return {-7, ''}\n end\n\n if ARGV[6] ~= '' then\n local current = redis.call('GET', KEYS[5])\n -- No key (a step written before it existed): the caller's read is the best\n -- attempt there is. Assuming 0 would make every later start look stale.\n local attempt = '0'\n if ARGV[7] ~= '' then\n attempt = ARGV[7]\n end\n if current then\n local status\n status, attempt = string.match(current, '^([^|]*)|?(.*)$')\n if status == 'completed' or status == 'failed' or status == 'cancelled' then\n return {-3, status}\n end\n if ARGV[7] ~= '' and attempt ~= ARGV[7] then\n return {-4, attempt}\n end\n end\n if ARGV[8] ~= '' then\n attempt = ARGV[8]\n end\n redis.call('SET', KEYS[5], ARGV[6] .. '|' .. attempt)\n end\n\n if ARGV[4] ~= '' then\n redis.call('SET', KEYS[3], ARGV[4])\n end\n\n local correlationKey = nil\n if ARGV[2] == '1' then\n correlationKey = KEYS[2]\n end\n local eventId = appendEvent(KEYS[1], correlationKey, ARGV[1])\n if ARGV[5] ~= '' then\n redis.call('SET', KEYS[4], eventId .. '|' .. ARGV[5])\n end\n return {1, eventId}\n`;\n\n/**\n * Atomically apply a batch of attribute changes and append the `attr_set` event.\n * Attributes live in a hash of their own, not in the run JSON, so two writers\n * changing different keys never overwrite each other.\n *\n * KEYS[1] = run attributes key\n * KEYS[2] = events key\n * KEYS[3] = events by correlation key (or unused placeholder)\n * KEYS[4] = run meta key\n * ARGV[1] = event JSON\n * ARGV[2] = has correlation (\"1\" or \"0\")\n * ARGV[3] = \"1\" to refuse a repeat for this correlation id (a replayed write)\n * ARGV[4..] = triples: attribute key, value, op (\"set\" or \"del\")\n * Returns: [1, eventId], [-6, status] when the run is terminal, [-8, ''] when\n * this correlation id already set attributes\n */\nconst LUA_SET_ATTRIBUTES = `${LUA_APPEND_EVENT}\n local status = runStatus(KEYS[4])\n if status and isTerminal(status) then\n return {-6, status}\n end\n if ARGV[3] == '1' and ARGV[2] == '1' and redis.call('ZCARD', KEYS[3]) > 0 then\n return {${LUA_DUPLICATE_CREATION}, ''}\n end\n for i = 4, #ARGV, 3 do\n if ARGV[i + 2] == 'del' then\n redis.call('HDEL', KEYS[1], ARGV[i])\n else\n redis.call('HSET', KEYS[1], ARGV[i], ARGV[i + 1])\n end\n end\n local correlationKey = nil\n if ARGV[2] == '1' then\n correlationKey = KEYS[3]\n end\n return {1, appendEvent(KEYS[2], correlationKey, ARGV[1])}\n`;\n\n/** Registered via `defineCommand` so ioredis dispatches with `EVALSHA` rather\n * than shipping the script body every call. `LUA_STORE_EVENT` is ~1 KB and\n * runs once per workflow event. */\nconst SCRIPTS = {\n wfCreateRunWithEvent: { numberOfKeys: 7, lua: LUA_CREATE_RUN_WITH_EVENT },\n wfSetAttributes: { numberOfKeys: 4, lua: LUA_SET_ATTRIBUTES },\n wfTransitionRun: { numberOfKeys: 7, lua: LUA_TRANSITION_RUN },\n wfCreateStepWithEvent: { numberOfKeys: 6, lua: LUA_CREATE_STEP_WITH_EVENT },\n wfCreateStepStarted: { numberOfKeys: 6, lua: LUA_CREATE_STEP_STARTED },\n wfCreateHookWithEvent: { numberOfKeys: 7, lua: LUA_CREATE_HOOK_WITH_EVENT },\n wfDisposeHook: { numberOfKeys: 6, lua: LUA_DISPOSE_HOOK },\n wfStoreEvent: { numberOfKeys: 7, lua: LUA_STORE_EVENT },\n} as const;\n\ntype ScriptName = keyof typeof SCRIPTS;\ntype ScriptFn = (...args: string[]) => Promise<unknown>;\ntype RedisWithScripts = Redis & Record<ScriptName, ScriptFn>;\n\n/** Clients that already have the scripts attached; every storage factory\n * calls this with the same shared connection, so it must be idempotent. */\n// Process-wide, not module-scoped: a bundled copy of this module must see the\n// connections another copy already attached the scripts to.\nconst scriptState = globalSingleton(\n \"@brickkit/redis-world//scripts\",\n 1,\n () => ({\n clients: new WeakSet<Redis>(),\n }),\n);\n\nfunction withScripts(redis: Redis): RedisWithScripts {\n if (!scriptState.clients.has(redis)) {\n for (const [name, def] of Object.entries(SCRIPTS)) {\n redis.defineCommand(name, {\n numberOfKeys: def.numberOfKeys,\n lua: def.lua,\n });\n }\n scriptState.clients.add(redis);\n }\n return redis as RedisWithScripts;\n}\n\n/** Compact `<status>|<specVersion>` marker beside the run blob, so validation\n * reads those two fields without transferring the run's input/output. */\nfunction runMetaValue(status: string, specVersion: number | undefined): string {\n return `${status}|${specVersion ?? \"\"}`;\n}\n\nfunction parseRunMeta(value: string): { status: string; specVersion?: number } {\n const sep = value.indexOf(\"|\");\n if (sep === -1) {\n return { status: value };\n }\n const version = value.slice(sep + 1);\n return {\n status: value.slice(0, sep),\n specVersion: version === \"\" ? undefined : Number(version),\n };\n}\n\n/**\n * Create storage for workflow runs using Redis hashes and sorted sets\n */\nexport function createRunsStorage(config: RedisStorageConfig): Storage[\"runs\"] {\n const { redis, keyPrefix } = config;\n\n const {\n runKey,\n runAttributesKey,\n runsIndexKey,\n runsByNameKey,\n runsByStatusKey,\n } = keys(keyPrefix);\n\n /** The statuses a list filter allows, or undefined for any. `status` takes one\n * status or an array; an empty array matches nothing, unlike omitting it. */\n function allowedStatuses(\n params?: ListWorkflowRunsParams,\n ): string[] | undefined {\n const status = params?.status;\n if (status === undefined) return undefined;\n return Array.isArray(status) ? status : [status];\n }\n\n function selectIndexKeys(params?: ListWorkflowRunsParams): string[] {\n if (params?.workflowName) {\n return [runsByNameKey(params.workflowName)];\n }\n const statuses = allowedStatuses(params);\n if (statuses) {\n // One index per status, merged: never the index of every run there is.\n return statuses.map(runsByStatusKey);\n }\n return [runsIndexKey()];\n }\n\n function parseRunsFromPipeline(\n results: any[] | null,\n params?: ListWorkflowRunsParams,\n ): (WorkflowRun | WorkflowRunWithoutData)[] {\n const runs: (WorkflowRun | WorkflowRunWithoutData)[] = [];\n\n // Each run contributed two replies: its body, then its attributes.\n for (let i = 0; i + 1 < (results?.length ?? 0); i += 2) {\n const result = results![i];\n if (!result?.[1]) {\n continue;\n }\n\n const run: WorkflowRun = parse<WorkflowRun>(result[1] as string);\n run.attributes =\n (results![i + 1]?.[1] as Record<string, string> | undefined) ?? {};\n\n const statuses = allowedStatuses(params);\n const statusMatches = !statuses || statuses.includes(run.status);\n const nameMatches =\n !params?.workflowName || run.workflowName === params.workflowName;\n\n if (statusMatches && nameMatches) {\n const resolveData = params?.resolveData ?? \"all\";\n const parsed = WorkflowRunSchema.parse(compact(run));\n runs.push(filterRunData(parsed, resolveData));\n }\n }\n\n return runs;\n }\n\n return {\n get: (async (id: string, params?: GetWorkflowRunParams) => {\n const replies = await redis\n .pipeline()\n .get(runKey(id))\n .hgetall(runAttributesKey(id))\n .exec();\n const data = replies?.[0]?.[1] as string | null | undefined;\n if (!data) {\n throw new WorkflowRunNotFoundError(id);\n }\n const run = parse<WorkflowRun>(data);\n run.attributes =\n (replies?.[1]?.[1] as Record<string, string> | undefined) ?? {};\n const parsed = WorkflowRunSchema.parse(compact(run));\n const resolveData = params?.resolveData ?? \"all\";\n return filterRunData(parsed, resolveData);\n }) as Storage[\"runs\"][\"get\"],\n\n list: (async (params?: ListWorkflowRunsParams) => {\n const limit = params?.pagination?.limit ?? 20;\n const fromCursor = params?.pagination?.cursor;\n\n // `status: []` matches nothing, like SQL `IN ()`.\n if (allowedStatuses(params)?.length === 0) {\n return { data: [], hasMore: false, cursor: null };\n }\n\n const indexKeys = selectIndexKeys(params);\n const order = params?.pagination?.sortOrder ?? \"desc\";\n\n // Keep scanning the index until limit+1 matches are collected (needed\n // to compute hasMore) or the index is exhausted. A single fetch is not\n // enough when combined workflowName+status filtering happens in memory\n // after the index scan; it would produce premature empty pages and\n // hasMore=false while matches remain further down the index.\n const runs: {\n run: WorkflowRun | WorkflowRunWithoutData;\n cursor: string;\n }[] = [];\n let scanFrom = fromCursor;\n while (runs.length <= limit) {\n const entries = await pageIndex(\n redis,\n indexKeys,\n scanFrom,\n limit + 1,\n order,\n );\n if (entries.length === 0) {\n break;\n }\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(runKey(id));\n pipeline.hgetall(runAttributesKey(id));\n }\n const results = await pipeline.exec();\n const cursorOf = new Map(\n entries.map((entry) => [entry.id, entry.cursor]),\n );\n for (const run of parseRunsFromPipeline(results, params)) {\n runs.push({ run, cursor: cursorOf.get(run.runId)! });\n }\n\n if (entries.length < limit + 1) {\n break;\n }\n scanFrom = entries.at(-1)!.cursor;\n }\n\n const values = runs.slice(0, limit);\n const hasMore = runs.length > limit;\n\n return {\n data: values.map((entry) => entry.run),\n hasMore,\n cursor: values.at(-1)?.cursor ?? null,\n };\n }) as Storage[\"runs\"][\"list\"],\n };\n}\n\n/**\n * Create storage for workflow events using Redis hashes and sorted sets.\n *\n * A run's log is one hash (`eventId -> JSON`). Event ids are log positions, so\n * the log is dense and 1-based, and every script that appends to it picks the\n * next position itself, atomically with the write (see `LUA_APPEND_EVENT`).\n */\nexport function createEventsStorage(\n config: RedisStorageConfig,\n): Storage[\"events\"] {\n const { redis, keyPrefix } = config;\n const scripts = withScripts(redis);\n const ulid = monotonicFactory();\n const maxEventsPerRun = resolveMaxEventsPerRun(config.maxEventsPerRun);\n\n const {\n eventsKey,\n eventsByCorrelationKey,\n resumeClaimKey,\n runKey,\n runAttributesKey,\n runMetaKey,\n runsIndexKey,\n runsByNameKey,\n runsByStatusKey,\n stepKey,\n stepsIndexKey,\n stepStatusKey,\n hookKey,\n hooksByTokenKey,\n hooksIndexKey,\n hooksTokenMapKey,\n } = keys(keyPrefix);\n\n /** Events per `HMGET`; keeps a long log from building one huge command. */\n const READ_CHUNK = 500;\n /** The most events an inline delta or skipped-slot report carries; the\n * caller continues from the cursor (or reloads) when `hasMore` is set. */\n const MAX_INLINE_EVENTS = 200;\n\n /** A run with its current attributes, which live apart from the run body. */\n async function withAttributes<T extends WorkflowRun | WorkflowRunWithoutData>(\n run: T,\n ): Promise<T> {\n const attributes = await redis.hgetall(runAttributesKey(run.runId));\n return { ...run, attributes };\n }\n\n /** `[key, value, ...]` for a script, from an attribute record. */\n const flattenAttributes = (\n attributes: Record<string, string> | undefined,\n ): string[] => Object.entries(attributes ?? {}).flat();\n\n /** Serialize an event for a script: `eventId` first, holding the placeholder. */\n function serializeEvent(event: Record<string, unknown>): string {\n const { eventId: _eventId, ...rest } = event;\n return stringify({ eventId: EVENT_ID_PLACEHOLDER, ...rest });\n }\n\n /** Read events by id out of one run's log, skipping any that are absent. */\n async function readEvents(\n runId: string,\n eventIds: string[],\n ): Promise<Event[]> {\n const events: Event[] = [];\n for (let i = 0; i < eventIds.length; i += READ_CHUNK) {\n const values = await redis.hmget(\n eventsKey(runId),\n ...eventIds.slice(i, i + READ_CHUNK),\n );\n for (const value of values) {\n if (value) {\n events.push(EventSchema.parse(compact(parse<Event>(value))));\n }\n }\n }\n return events;\n }\n\n /** Events at slots `from..to` inclusive, in slot order. */\n async function readSlots(\n runId: string,\n from: number,\n to: number,\n ): Promise<Event[]> {\n const ids: string[] = [];\n for (let slot = Math.max(from, FIRST_EVENT_SLOT); slot <= to; slot++) {\n ids.push(slotToEventId(slot));\n }\n return readEvents(runId, ids);\n }\n\n type TransitionResult =\n | { kind: \"ok\"; eventId: string }\n | { kind: \"absent\" }\n | { kind: \"moved\"; status: string };\n\n /**\n * Move a run from `oldStatus` to `newStatus`, release its hooks when it\n * finishes, and append the lifecycle event: one script, so a crash or a racing\n * writer can never leave the status and the log disagreeing. `moved` means the\n * run was no longer in `oldStatus` by the time the script ran, and nothing was\n * written.\n */\n async function transitionRun(\n runId: string,\n oldStatus: string,\n newStatus: string,\n updatedRun: { specVersion?: number },\n at: Date,\n event: Record<string, unknown>,\n releaseHooks: boolean,\n ): Promise<TransitionResult> {\n const result = (await scripts.wfTransitionRun(\n runKey(runId),\n runsByStatusKey(oldStatus),\n runsByStatusKey(newStatus),\n runMetaKey(runId),\n eventsKey(runId),\n hooksIndexKey(runId),\n hooksTokenMapKey(runId),\n stringify(updatedRun),\n runId,\n at.getTime().toString(),\n runMetaValue(newStatus, updatedRun.specVersion),\n oldStatus,\n serializeEvent(event),\n releaseHooks ? \"1\" : \"0\",\n hookKey(\"\"),\n hooksByTokenKey(\"\"),\n )) as [number, string];\n if (result[0] === 1) return { kind: \"ok\", eventId: result[1] };\n if (result[0] === -2) return { kind: \"moved\", status: result[1] };\n return { kind: \"absent\" };\n }\n\n /** What an append can come back as besides the stored event. */\n type AppendOutcome =\n | { kind: \"stored\"; event: Event }\n | { kind: \"duplicate\" }\n | { kind: \"alreadyCompleted\" }\n | { kind: \"claimed\"; claim: string }\n | { kind: \"stepTerminal\"; status: string }\n | { kind: \"stepMoved\"; attempt: string }\n | { kind: \"runTerminal\"; status: string }\n | { kind: \"hookGone\" };\n\n /** Append an event whose id the script picks. Returns the stored event. */\n async function appendEvent(\n runId: string,\n event: Record<string, unknown>,\n options: {\n entityKey?: string;\n entityJson?: string;\n /** `creation`: refuse when the correlation id already has an event.\n * `completion`: refuse when it already has two (created, then completed). */\n dedup?: \"creation\" | \"completion\";\n resume?: { id: string; claim: string };\n /**\n * The step this write moves. `expectedAttempt` makes the write lose to any\n * other writer that moved the step past the attempt the caller read.\n * `newAttempt` sets the attempt (a start); otherwise it is kept.\n */\n step?: {\n key: string;\n status: string;\n expectedAttempt?: number;\n newAttempt?: number;\n };\n /** Refuse when the run is terminal. */\n runMustBeLive?: boolean;\n /** Refuse when the hook the event is about no longer exists. */\n hookMustExist?: boolean;\n } = {},\n ): Promise<AppendOutcome> {\n const correlationId = event.correlationId as string | undefined;\n const result = (await scripts.wfStoreEvent(\n eventsKey(runId),\n correlationId\n ? eventsByCorrelationKey(runId, correlationId)\n : \"__unused__\",\n options.entityKey ?? \"__unused__\",\n options.resume ? resumeClaimKey(runId, options.resume.id) : \"__unused__\",\n options.step?.key ?? \"__unused__\",\n options.runMustBeLive ? runMetaKey(runId) : \"__unused__\",\n options.hookMustExist && correlationId\n ? hookKey(correlationId)\n : \"__unused__\",\n serializeEvent(event),\n correlationId ? \"1\" : \"0\",\n options.dedup === \"creation\"\n ? \"1\"\n : options.dedup === \"completion\"\n ? \"2\"\n : \"0\",\n options.entityJson ?? \"\",\n options.resume?.claim ?? \"\",\n options.step?.status ?? \"\",\n options.step?.expectedAttempt === undefined\n ? \"\"\n : String(options.step.expectedAttempt),\n options.step?.newAttempt === undefined\n ? \"\"\n : String(options.step.newAttempt),\n options.runMustBeLive ? \"1\" : \"0\",\n options.hookMustExist ? \"1\" : \"0\",\n )) as [number, string];\n switch (result[0]) {\n case LUA_DUPLICATE_CREATION:\n return { kind: \"duplicate\" };\n case -7:\n return { kind: \"alreadyCompleted\" };\n case -3:\n return { kind: \"stepTerminal\", status: result[1] };\n case -4:\n return { kind: \"stepMoved\", attempt: result[1] };\n case -5:\n return { kind: \"hookGone\" };\n case -6:\n return { kind: \"runTerminal\", status: result[1] };\n case 3:\n return { kind: \"claimed\", claim: result[1] };\n default:\n return {\n kind: \"stored\",\n event: EventSchema.parse({ ...event, eventId: result[1] }),\n };\n }\n }\n\n /** The events a bumped write skipped over: those between the slot the writer\n * asked for (`eventCount + 1`) and the one it landed on. */\n async function reportSkippedSlots(\n result: EventResult,\n askedFor: number,\n resolveData: EventsResolveData,\n ): Promise<EventResult> {\n if (!result.event) return result;\n const committedSlot = eventIdToSlot(result.event.eventId);\n if (\n committedSlot === null ||\n askedFor < 0 ||\n committedSlot <= askedFor + 1\n ) {\n return result;\n }\n const span = committedSlot - askedFor - 1;\n const upto = Math.min(committedSlot - 1, askedFor + MAX_INLINE_EVENTS);\n const skipped = await readSlots(result.event.runId, askedFor + 1, upto);\n return {\n ...result,\n events: skipped.map((event) => stripEventDataRefs(event, resolveData)),\n // The report is a lower bound on what the write skipped, not a page the\n // caller has now read to the end of, so it must not move its read position.\n cursor: null,\n hasMore: skipped.length < span,\n };\n }\n\n /** The inline delta: everything after `sinceCursor`, as `events.list` would\n * return it right after the write. */\n async function deltaSince(\n result: EventResult,\n sinceCursor: string,\n resolveData: EventsResolveData,\n ): Promise<EventResult> {\n if (!result.event) return result;\n const sinceSlot = eventIdToSlot(sinceCursor);\n if (sinceSlot === null) return result;\n const total = await redis.hlen(eventsKey(result.event.runId));\n const upto = Math.min(total, sinceSlot + MAX_INLINE_EVENTS);\n const page = await readSlots(result.event.runId, sinceSlot + 1, upto);\n return {\n ...result,\n events: page.map((event) => stripEventDataRefs(event, resolveData)),\n cursor: page.at(-1)?.eventId ?? sinceCursor,\n hasMore: upto < total,\n };\n }\n\n const isTerminal = (status: string) =>\n [\"completed\", \"failed\", \"cancelled\"].includes(status);\n\n /** How many times a step write recomputes after losing a race for the step. */\n const MAX_STALE_RETRIES = 5;\n\n async function createEvent(\n runId: string | null,\n data: CreateEventRequest | RunCreatedEventRequest,\n params?: CreateEventParams,\n staleRetries = 0,\n ): Promise<EventResult> {\n const now = new Date();\n const resolveData = params?.resolveData ?? \"all\";\n // The created event and the entities are never trimmed to the page option.\n const entityData = entityResolveData(resolveData);\n\n let effectiveRunId: string;\n if (data.eventType === \"run_created\" && (!runId || runId === \"\")) {\n effectiveRunId = `wrun_${ulid()}`;\n } else if (!runId) {\n throw new Error(\"runId is required for non-run_created events\");\n } else {\n effectiveRunId = runId;\n }\n\n const effectiveSpecVersion = data.specVersion ?? mintedSpecVersion();\n\n // Build the event this call appends; the script fills in `eventId`.\n const buildEvent = (\n overrides: Record<string, unknown> = {},\n ): Record<string, unknown> => ({\n ...data,\n runId: effectiveRunId,\n createdAt: new Date(),\n specVersion: effectiveSpecVersion,\n ...overrides,\n });\n\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n\n // Set when a lifecycle transition already committed its own event.\n let lifecycleEvent: Event | undefined;\n\n // Written alongside the event append below instead of in its own round\n // trip, which also makes the mutation and its event atomic.\n let pendingEntityKey: string | undefined;\n let pendingEntityJson: string | undefined;\n let pendingStep:\n | {\n key: string;\n status: string;\n expectedAttempt?: number;\n newAttempt?: number;\n }\n | undefined;\n\n let currentRun: { status: string; specVersion?: number } | null = null;\n // Read at most once per call; every mutation branch below reuses it\n // rather than re-fetching and re-parsing the whole payload.\n let existingRun: WorkflowRun | null = null;\n\n async function loadRunBody(): Promise<void> {\n const runData = await redis.get(runKey(effectiveRunId));\n if (runData) {\n existingRun = parse<WorkflowRun>(runData);\n currentRun = {\n status: existingRun.status,\n specVersion: existingRun.specVersion,\n };\n }\n }\n\n const skipRunValidationEvents = [\"step_completed\", \"step_retrying\"];\n if (\n data.eventType !== \"run_created\" &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n if (RUN_LIFECYCLE_EVENT_TYPES.has(data.eventType)) {\n // These mutate the run, so its body is needed either way.\n await loadRunBody();\n } else {\n // Only status/specVersion are consulted, and the meta key holds\n // both in ~20 bytes. No meta means no such run.\n const meta = await redis.get(runMetaKey(effectiveRunId));\n if (meta) {\n currentRun = parseRunMeta(meta);\n }\n }\n }\n\n if (\n data.eventType === \"run_started\" &&\n !currentRun &&\n \"eventData\" in data &&\n data.eventData\n ) {\n const runInputData = (data as any).eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: any;\n attributes?: Record<string, string>;\n allowReservedAttributes?: true;\n encryptionPublicKey?: string;\n dynamicWorkflowCode?: any;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n const seeds = runInputData.attributes ?? {};\n validateAttributeChanges(\n Object.entries(seeds).map(([key, value]) => ({ key, value })),\n {\n allowReservedAttributes:\n runInputData.allowReservedAttributes === true,\n },\n );\n const newRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n ...(runInputData.encryptionPublicKey && {\n encryptionPublicKey: runInputData.encryptionPublicKey,\n }),\n ...(runInputData.dynamicWorkflowCode !== undefined && {\n dynamicWorkflowCode: runInputData.dynamicWorkflowCode,\n }),\n status: \"pending\" as const,\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Fused script: run entity + synthetic run_created event in one\n // atomic execution, so a crash cannot leave one without the other\n // and concurrent bootstraps cannot double-append the event.\n const result = (await scripts.wfCreateRunWithEvent(\n runKey(effectiveRunId),\n runsIndexKey(),\n runsByNameKey(runInputData.workflowName),\n runsByStatusKey(\"pending\"),\n runMetaKey(effectiveRunId),\n eventsKey(effectiveRunId),\n runAttributesKey(effectiveRunId),\n stringify(newRun),\n effectiveRunId,\n now.getTime().toString(),\n runMetaValue(\"pending\", effectiveSpecVersion),\n serializeEvent({\n eventType: \"run_created\",\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n ...(runInputData.attributes && {\n attributes: runInputData.attributes,\n }),\n ...(runInputData.allowReservedAttributes && {\n allowReservedAttributes: true,\n }),\n ...(runInputData.encryptionPublicKey && {\n encryptionPublicKey: runInputData.encryptionPublicKey,\n }),\n },\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n }),\n ...flattenAttributes(seeds),\n )) as [number, string];\n if (result[0] === 1) {\n currentRun = { status: \"pending\", specVersion: effectiveSpecVersion };\n existingRun = newRun as WorkflowRun;\n } else {\n // Run already exists (the resilient re-start path, which must\n // tolerate losing the race): read the state the other writer left.\n const parsed = parse<WorkflowRun>(result[1]);\n currentRun = {\n status: parsed.status,\n specVersion: parsed.specVersion,\n };\n existingRun = parsed;\n }\n }\n }\n\n if (currentRun) {\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n mintedSpecVersion(),\n );\n }\n if (isLegacySpecVersion(currentRun.specVersion)) {\n // Event ids are log positions; a run from before the event-sourced spec\n // has none.\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n mintedSpecVersion(),\n );\n }\n }\n\n if (currentRun && isTerminal((currentRun as { status: string }).status)) {\n const terminalStatus = (currentRun as { status: string }).status;\n const runTerminalEvents = [\"run_started\", \"run_completed\", \"run_failed\"];\n\n if (\n data.eventType === \"run_cancelled\" &&\n terminalStatus === \"cancelled\"\n ) {\n const stored = await appendEvent(effectiveRunId, buildEvent());\n if (stored.kind !== \"stored\") {\n throw new EntityConflictError(\"Duplicate run_cancelled\");\n }\n return {\n event: stripEventDataRefs(stored.event, entityData),\n // Lifecycle event: validation already loaded the body.\n run: existingRun\n ? await withAttributes(\n WorkflowRunSchema.parse(compact(existingRun)),\n )\n : undefined,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === \"run_started\") {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${terminalStatus}\"`,\n );\n }\n\n // No work begins on a finished run. A step_started is rejected even when\n // the step still reads `running`: that is a redelivery of a start an\n // earlier delivery already claimed, and accepting it would execute a\n // body whose outcome nothing will read. step_completed and step_failed\n // stay accepted so a step already in flight can record its outcome.\n if (data.eventType === \"step_started\") {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${terminalStatus}\"`,\n );\n }\n\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === \"run_cancelled\"\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${terminalStatus}\"`,\n );\n }\n\n if (\n data.eventType === \"step_created\" ||\n data.eventType === \"hook_created\" ||\n data.eventType === \"wait_created\"\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${terminalStatus}\"`,\n );\n }\n }\n\n // Held whole so `step_started`/`step_retrying` can mutate it below\n // without re-fetching and re-parsing the step (including its input).\n let validatedStep: Step | null = null;\n // A step_started that carries the step's name and input also creates it.\n const lazyStepStart =\n data.eventType === \"step_started\" &&\n typeof (data as any).eventData?.stepName === \"string\" &&\n (data as any).eventData?.input !== undefined;\n const stepEventsNeedingValidation = [\"step_started\", \"step_retrying\"];\n if (\n stepEventsNeedingValidation.includes(data.eventType) &&\n data.correlationId\n ) {\n const stepData = await redis.get(\n stepKey(effectiveRunId, data.correlationId),\n );\n if (stepData) {\n validatedStep = parse<Step>(stepData);\n }\n\n if (!validatedStep && !lazyStepStart) {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n\n // The lazy start exactly-once gate: a lazy step_started always CREATES the\n // step, so an existing one means a concurrent handler won the claim.\n // EntityConflictError makes the runtime skip it; without this a loser\n // would re-start a running step and run the body a second time.\n if (lazyStepStart && validatedStep) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`,\n );\n }\n\n if (validatedStep) {\n // EntityConflictError so core's step handler skips the duplicate\n // delivery and re-enqueues the workflow (crash-recovery nudge).\n if (isTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`,\n );\n }\n\n if (\n currentRun &&\n isTerminal((currentRun as { status: string }).status)\n ) {\n if (validatedStep.status !== \"running\") {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${(currentRun as { status: string }).status}\"`,\n );\n }\n }\n }\n }\n\n // Hook validation; the body is kept so `hook_disposed` below need not\n // re-read it just to recover the token.\n let validatedHook: Hook | null = null;\n // A hook_received that carries a resume id may be a retry of one already\n // recorded: the script checks the claim first, then the hook, so the retry\n // gets its event back rather than \"not found\".\n const hookEventsRequiringExistence = [\"hook_disposed\", \"hook_received\"];\n const isResumeRetryCandidate =\n data.eventType === \"hook_received\" && params?.resumeId;\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId &&\n !isResumeRetryCandidate\n ) {\n const existingHook = await redis.get(hookKey(data.correlationId));\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n validatedHook = parse<Hook>(existingHook);\n }\n\n if (data.eventType === \"run_created\") {\n const eventData = (data as any).eventData as {\n deploymentId: string;\n workflowName: string;\n input: any[];\n executionContext?: Record<string, any>;\n attributes?: Record<string, string>;\n allowReservedAttributes?: true;\n encryptionPublicKey?: string;\n dynamicWorkflowCode?: any;\n dynamicWorkflowCodeRef?: string;\n };\n\n if (eventData.dynamicWorkflowCodeRef !== undefined) {\n throw new WorkflowWorldError(\n \"dynamicWorkflowCodeRef is not supported by this world\",\n {\n status: 501,\n },\n );\n }\n const seeds = eventData.attributes ?? {};\n validateAttributeChanges(\n Object.entries(seeds).map(([key, value]) => ({ key, value })),\n { allowReservedAttributes: eventData.allowReservedAttributes === true },\n );\n\n const newRun = {\n runId: effectiveRunId,\n deploymentId: eventData.deploymentId,\n workflowName: eventData.workflowName,\n specVersion: effectiveSpecVersion,\n input: eventData.input,\n executionContext: eventData.executionContext,\n ...(eventData.encryptionPublicKey && {\n encryptionPublicKey: eventData.encryptionPublicKey,\n }),\n ...(eventData.dynamicWorkflowCode !== undefined && {\n dynamicWorkflowCode: eventData.dynamicWorkflowCode,\n }),\n status: \"pending\" as const,\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n\n // Fused script: run entity + run_created event in one atomic\n // execution. A duplicate rejects with EntityConflictError (which the\n // runtime treats as benign) instead of returning the existing run\n // AND appending a second creation event that would poison replay.\n const event = buildEvent({ createdAt: now });\n const result = (await scripts.wfCreateRunWithEvent(\n runKey(effectiveRunId),\n runsIndexKey(),\n runsByNameKey(eventData.workflowName),\n runsByStatusKey(\"pending\"),\n runMetaKey(effectiveRunId),\n eventsKey(effectiveRunId),\n runAttributesKey(effectiveRunId),\n stringify(newRun),\n effectiveRunId,\n now.getTime().toString(),\n runMetaValue(\"pending\", effectiveSpecVersion),\n serializeEvent(event),\n ...flattenAttributes(seeds),\n )) as [number, string];\n\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`,\n );\n }\n\n run = WorkflowRunSchema.parse({ ...compact(newRun), attributes: seeds });\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return {\n event: stripEventDataRefs(parsed, entityData),\n run,\n maxEvents: maxEventsPerRun,\n };\n }\n\n if (data.eventType === \"run_started\") {\n // Core reads the per-run event ceiling only from the run_started response, so\n // omitting it here would drop the limit on every replay after the first.\n const resumeResponse = async (\n current: WorkflowRun | null,\n ): Promise<EventResult> => {\n const resumed = current\n ? await withAttributes(WorkflowRunSchema.parse(compact(current)))\n : undefined;\n return {\n run: resumed\n ? (filterRunData(resumed, entityData) as WorkflowRun)\n : undefined,\n ...(resumed ? { maxEvents: maxEventsPerRun } : {}),\n };\n };\n\n if ((currentRun as { status: string } | null)?.status === \"running\") {\n // Resume path, hit on every re-invocation of a running workflow.\n return resumeResponse(existingRun);\n }\n\n if (!existingRun) {\n // No run and no resilient-start bootstrap data; logging a\n // run_started event against a nonexistent run would corrupt the\n // event log, so fail loudly instead.\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const existing = existingRun as WorkflowRun;\n const updatedRun = {\n ...existing,\n status: \"running\" as const,\n startedAt: now,\n updatedAt: now,\n };\n\n // The event carries no data: the run's input was the creation event's.\n const { eventData: _startData, ...startEvent } = buildEvent({\n createdAt: now,\n });\n const moved = await transitionRun(\n effectiveRunId,\n existing.status,\n \"running\",\n updatedRun,\n now,\n startEvent,\n false,\n );\n if (moved.kind === \"absent\") {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n if (moved.kind === \"moved\") {\n // Another invocation got there first. If it started the run, this one is\n // a resume and must not append a second run_started; if the run ended in\n // the meantime, there is nothing left to start.\n if (isTerminal(moved.status)) {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${moved.status}\"`,\n );\n }\n await loadRunBody();\n return resumeResponse(existingRun);\n }\n\n run = WorkflowRunSchema.parse(compact(updatedRun));\n lifecycleEvent = EventSchema.parse({\n ...startEvent,\n eventId: moved.eventId,\n });\n }\n\n if (\n data.eventType === \"run_completed\" ||\n data.eventType === \"run_failed\" ||\n data.eventType === \"run_cancelled\"\n ) {\n if (!existingRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const existing = existingRun as WorkflowRun;\n let updatedRun: WorkflowRun;\n let newStatus: \"completed\" | \"failed\" | \"cancelled\";\n\n if (data.eventType === \"run_completed\") {\n const eventData = (data as any).eventData as { output?: any };\n newStatus = \"completed\";\n updatedRun = {\n ...existing,\n status: \"completed\",\n output: eventData.output,\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n } else if (data.eventType === \"run_failed\") {\n const eventData = (data as any).eventData as {\n error: any;\n errorCode?: string;\n };\n newStatus = \"failed\";\n updatedRun = {\n ...existing,\n status: \"failed\",\n // Kept as the serialized thrown value; consumers hydrate it.\n error: eventData.error,\n errorCode: eventData.errorCode,\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n } else {\n newStatus = \"cancelled\";\n updatedRun = {\n ...existing,\n status: \"cancelled\",\n completedAt: now,\n updatedAt: now,\n } as WorkflowRun;\n }\n\n // Status, hook release and event commit together (see `transitionRun`).\n const terminalEvent = buildEvent({ createdAt: now });\n const moved = await transitionRun(\n effectiveRunId,\n existing.status,\n newStatus,\n updatedRun,\n now,\n terminalEvent,\n true,\n );\n if (moved.kind === \"absent\") {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n if (moved.kind === \"moved\") {\n throw new EntityConflictError(\n `Cannot transition run \"${effectiveRunId}\" to \"${newStatus}\": it already left \"${existing.status}\" for \"${moved.status}\"`,\n );\n }\n\n run = WorkflowRunSchema.parse(compact(updatedRun));\n lifecycleEvent = EventSchema.parse({\n ...terminalEvent,\n eventId: moved.eventId,\n });\n }\n\n if (data.eventType === \"step_created\") {\n const eventData = (data as any).eventData as {\n stepName: string;\n input: any;\n };\n\n const newStep = {\n runId: effectiveRunId,\n stepId: data.correlationId!,\n stepName: eventData.stepName,\n input: eventData.input,\n status: \"pending\" as const,\n attempt: 0,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n updatedAt: now,\n };\n\n // Fused script: step entity + step_created event in one atomic\n // execution, closing the check-then-write race between concurrent\n // redeliveries. An existing entity means the creation event is\n // already in the log (they are written together), so a duplicate\n // rejects with EntityConflictError, the runtime's dedup signal;\n // returning success would append a second step_created row and\n // poison replay with ReplayDivergenceError.\n const event = buildEvent({ createdAt: now });\n const result = (await scripts.wfCreateStepWithEvent(\n stepKey(effectiveRunId, data.correlationId!),\n stepsIndexKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n stepStatusKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(newStep),\n data.correlationId!,\n now.getTime().toString(),\n serializeEvent(event),\n \"pending|0\",\n )) as [number, string];\n\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already exists`,\n );\n }\n\n step = StepSchema.parse(compact(newStep));\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData), step };\n }\n\n // wait_created has no entity in this world; the event log is the only\n // dedup surface. Throw on a duplicate so the contract matches the\n // runtime's dedup catch path.\n //\n // Checked inside the event-store script: a wait's correlation index only\n // holds wait_created and the wait_completed that follows it, so a\n // non-empty index means \"already recorded\". O(1) and atomic with the\n // write, vs scanning every event on every wait.\n const dedup: \"creation\" | \"completion\" | undefined =\n data.eventType === \"wait_created\"\n ? \"creation\"\n : data.eventType === \"wait_completed\"\n ? \"completion\"\n : undefined;\n\n if (data.eventType === \"step_started\") {\n // Retried steps may be scheduled for later. TooEarlyError tells core\n // to re-deliver after the remaining backoff instead of starting the\n // step before its retryAfter timestamp.\n if (\n validatedStep?.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000,\n ),\n },\n );\n }\n\n if (lazyStepStart) {\n // Lazy start: create the step (already running), a synthetic\n // step_created so replay still observes the creation, and the\n // step_started, in one script. The SETNX is the exactly-once claim.\n const lazyData = (data as any).eventData as {\n stepName: string;\n input: any;\n [key: string]: unknown;\n };\n const startedStep = {\n runId: effectiveRunId,\n stepId: data.correlationId!,\n stepName: lazyData.stepName,\n input: lazyData.input,\n status: \"running\" as const,\n attempt: 1,\n startedAt: now,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n updatedAt: now,\n };\n // The input belongs on the synthetic step_created; the step_started row\n // keeps the rest (stepName is read by the replay's name-divergence check).\n const { input: _input, ...startedEventData } = lazyData;\n const createdEvent = {\n eventType: \"step_created\" as const,\n correlationId: data.correlationId,\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n stepName: lazyData.stepName,\n ...(lazyData.workflowName !== undefined && {\n workflowName: lazyData.workflowName,\n }),\n input: lazyData.input,\n },\n };\n const startedEvent = buildEvent({\n createdAt: now,\n eventData: startedEventData,\n });\n const result = (await scripts.wfCreateStepStarted(\n stepKey(effectiveRunId, data.correlationId!),\n stepsIndexKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n stepStatusKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(startedStep),\n data.correlationId!,\n now.getTime().toString(),\n serializeEvent(createdEvent),\n serializeEvent(startedEvent),\n \"running|1\",\n )) as [number, string, string];\n if (result[0] === -6) {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`,\n );\n }\n step = StepSchema.parse(compact(startedStep));\n const parsed = EventSchema.parse({\n ...startedEvent,\n eventId: result[2],\n });\n return {\n event: stripEventDataRefs(parsed, entityData),\n step,\n stepCreated: true,\n };\n }\n\n const isFirstStart = !validatedStep?.startedAt;\n // Reuses the step loaded during validation above.\n const existing = validatedStep;\n if (existing) {\n const updatedStep = {\n ...existing,\n status: \"running\" as const,\n attempt: existing.attempt + 1,\n ...(isFirstStart ? { startedAt: now } : {}),\n // The step has left the backoff window; always clear retryAfter.\n retryAfter: undefined,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"running\",\n // Two starts that both read this attempt cannot both win.\n expectedAttempt: existing.attempt,\n newAttempt: updatedStep.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n }\n }\n\n if (data.eventType === \"step_completed\") {\n const eventData = (data as any).eventData as { result?: any };\n const existingData = await redis.get(\n stepKey(effectiveRunId, data.correlationId!),\n );\n if (existingData) {\n const existing = parse<Step>(existingData);\n if (isTerminal(existing.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${existing.status}\"`,\n );\n }\n const updatedStep = {\n ...existing,\n status: \"completed\" as const,\n output: eventData.result,\n completedAt: now,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"completed\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n } else {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n }\n\n if (data.eventType === \"step_failed\") {\n const eventData = (data as any).eventData as { error?: any };\n\n const existingData = await redis.get(\n stepKey(effectiveRunId, data.correlationId!),\n );\n if (existingData) {\n const existing = parse<Step>(existingData);\n if (isTerminal(existing.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${existing.status}\"`,\n );\n }\n const updatedStep = {\n ...existing,\n status: \"failed\" as const,\n // Kept as the serialized thrown value; consumers hydrate it.\n error: eventData.error,\n completedAt: now,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"failed\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n } else {\n throw new WorkflowWorldError(`Step \"${data.correlationId}\" not found`, {\n status: 404,\n });\n }\n }\n\n if (data.eventType === \"step_retrying\") {\n const eventData = (data as any).eventData as {\n error?: any;\n retryAfter?: Date;\n };\n\n // Reuses the step loaded during validation above.\n const existing = validatedStep;\n if (existing) {\n const updatedStep = {\n ...existing,\n status: \"pending\" as const,\n error: eventData.error,\n retryAfter: eventData.retryAfter,\n updatedAt: now,\n };\n pendingEntityKey = stepKey(effectiveRunId, data.correlationId!);\n pendingEntityJson = stringify(updatedStep);\n pendingStep = {\n key: stepStatusKey(effectiveRunId, data.correlationId!),\n status: \"pending\",\n // Lost the race for the step: the caller recomputes from a fresh read.\n expectedAttempt: existing.attempt,\n };\n step = StepSchema.parse(compact(updatedStep));\n }\n }\n\n if (data.eventType === \"hook_created\") {\n const eventData = (data as any).eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n const newHook: Hook = {\n runId: effectiveRunId,\n hookId: data.correlationId!,\n token: eventData.token,\n ownerId: \"\",\n projectId: \"\",\n environment: \"\",\n metadata: eventData.metadata,\n specVersion: effectiveSpecVersion,\n createdAt: now,\n ...(eventData.isWebhook !== undefined && {\n isWebhook: eventData.isWebhook,\n }),\n ...(eventData.isSystem !== undefined && {\n isSystem: eventData.isSystem,\n }),\n };\n const event = buildEvent({ createdAt: now });\n\n // Fused script: token claim + hook entity + hook_created event in\n // one atomic execution. The SETNX on the by-token key arbitrates\n // ownership, closing the check-then-write race between concurrent\n // deliveries. A token whose owner is gone (a crash during cleanup left it\n // behind) is taken over inside the script, and a hook is never created on\n // a finished run, which would hold its token forever.\n const result = (await scripts.wfCreateHookWithEvent(\n hookKey(data.correlationId!),\n hooksByTokenKey(eventData.token),\n hooksIndexKey(effectiveRunId),\n hooksTokenMapKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId!),\n runMetaKey(effectiveRunId),\n stringify(newHook),\n data.correlationId!,\n now.getTime().toString(),\n eventData.token,\n serializeEvent(event),\n hookKey(\"\"),\n )) as [number, string];\n\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${result[1]}\"`,\n );\n }\n\n if (result[0] === 2) {\n // A different (runId, hookId) holds this token. Create a\n // hook_conflict event instead of throwing 409; this lets the\n // workflow continue and fail gracefully when the hook is awaited.\n // The rightful owner's token mapping is left untouched.\n const owningHookId = result[1];\n let conflictingRunId: string | undefined;\n const owningHookData = await redis.get(hookKey(owningHookId));\n if (owningHookData) {\n conflictingRunId = parse<Hook>(owningHookData).runId;\n }\n\n // Recorded once: a redelivered hook_created must not journal a second\n // conflict, which replay would read as a second event for one hook.\n const stored = await appendEvent(\n effectiveRunId,\n {\n eventType: \"hook_conflict\" as const,\n correlationId: data.correlationId,\n eventData: {\n token: eventData.token,\n ...(conflictingRunId ? { conflictingRunId } : {}),\n },\n runId: effectiveRunId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n },\n { dedup: \"creation\", runMustBeLive: true },\n );\n if (stored.kind === \"runTerminal\") {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind !== \"stored\") {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" conflict already recorded`,\n );\n }\n return {\n event: stripEventDataRefs(stored.event, entityData),\n run,\n step,\n hook: undefined,\n };\n }\n\n if (result[0] === 0) {\n // Same (runId, hookId, token) already fully created: entity and\n // event are written atomically, so the event is guaranteed to be\n // in the log. EntityConflictError is the runtime's dedup signal\n // (a self hook_conflict would later replay as HookConflictError).\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already created`,\n );\n }\n\n hook = HookSchema.parse(compact(newHook));\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData), hook };\n }\n\n // Handle hook_disposed: delete the hook and append the event in one script, so\n // a racing hook_received cannot land behind the disposal and a crash cannot\n // lose the event.\n if (data.eventType === \"hook_disposed\" && data.correlationId) {\n if (!validatedHook) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`,\n );\n }\n const event = buildEvent();\n const result = (await scripts.wfDisposeHook(\n hookKey(data.correlationId),\n hooksByTokenKey(validatedHook.token),\n hooksIndexKey(effectiveRunId),\n hooksTokenMapKey(effectiveRunId),\n eventsKey(effectiveRunId),\n eventsByCorrelationKey(effectiveRunId, data.correlationId),\n data.correlationId,\n serializeEvent(event),\n )) as [number, string];\n if (result[0] === 0) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`,\n );\n }\n const parsed = EventSchema.parse({ ...event, eventId: result[1] });\n return { event: stripEventDataRefs(parsed, entityData) };\n }\n\n // Handle attr_set: merge the changes into the run's attributes and append the\n // event in one script.\n if (data.eventType === \"attr_set\") {\n if (!currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n const eventData = (data as any).eventData as {\n changes: AttributeChange[];\n allowReservedAttributes?: true;\n };\n validateAttributeChanges(eventData.changes, {\n existingKeys: await redis.hkeys(runAttributesKey(effectiveRunId)),\n allowReservedAttributes: eventData.allowReservedAttributes === true,\n });\n const event = buildEvent();\n const correlationId = data.correlationId;\n const result = (await scripts.wfSetAttributes(\n runAttributesKey(effectiveRunId),\n eventsKey(effectiveRunId),\n correlationId\n ? eventsByCorrelationKey(effectiveRunId, correlationId)\n : \"__unused__\",\n runMetaKey(effectiveRunId),\n serializeEvent(event),\n correlationId ? \"1\" : \"0\",\n // A workflow replays its writes, so one correlation id sets attributes once.\n (data as { eventData?: { writer?: { type?: string } } }).eventData\n ?.writer?.type === \"workflow\"\n ? \"1\"\n : \"0\",\n ...eventData.changes.flatMap((change) => [\n change.key,\n change.value ?? \"\",\n change.value === null ? \"del\" : \"set\",\n ]),\n )) as [number, string];\n if (result[0] === -6) {\n throw new EntityConflictError(\n `Cannot set attributes on run in terminal state \"${result[1]}\"`,\n );\n }\n if (result[0] === LUA_DUPLICATE_CREATION) {\n throw new EntityConflictError(\n `attr_set for correlationId \"${correlationId}\" already exists in run \"${effectiveRunId}\"`,\n );\n }\n await loadRunBody();\n return {\n event: stripEventDataRefs(\n EventSchema.parse({ ...event, eventId: result[1] }),\n entityData,\n ),\n run: existingRun\n ? await withAttributes(WorkflowRunSchema.parse(compact(existingRun)))\n : undefined,\n };\n }\n\n // A lazy hook resume is deduplicated per (run, resumeId): the queue consumer\n // re-ensures the same hook_received the producer may already have written.\n const resume =\n data.eventType === \"hook_received\" && params?.resumeId\n ? {\n id: params.resumeId,\n claim: `${params.resumePayloadDigest ?? \"\"}|${data.correlationId}`,\n }\n : undefined;\n\n // A lifecycle transition committed its own event with the status change.\n // Everything else is appended here, and guards the run and hook it is about\n // inside the script that appends: a check made before the call is stale by the\n // time the event lands.\n const stored: AppendOutcome = lifecycleEvent\n ? { kind: \"stored\", event: lifecycleEvent }\n : await appendEvent(effectiveRunId, buildEvent(), {\n entityKey: pendingEntityKey,\n entityJson: pendingEntityJson,\n dedup,\n resume,\n step: pendingStep,\n runMustBeLive:\n data.eventType === \"hook_received\" ||\n data.eventType === \"wait_created\" ||\n data.eventType === \"step_started\",\n hookMustExist: data.eventType === \"hook_received\",\n });\n if (stored.kind === \"duplicate\") {\n throw new EntityConflictError(`\"${data.correlationId}\" already exists`);\n }\n if (stored.kind === \"alreadyCompleted\") {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`,\n );\n }\n if (stored.kind === \"stepTerminal\") {\n // EntityConflictError so core's step handler skips the duplicate delivery.\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind === \"stepMoved\") {\n // A start that lost to another start is the claim working. Any other write\n // was computed from a stale copy of the step: redo it from a fresh read.\n if (\n data.eventType !== \"step_started\" &&\n staleRetries < MAX_STALE_RETRIES\n ) {\n return createEvent(runId, data, params, staleRetries + 1);\n }\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" was moved by another delivery (attempt ${stored.attempt})`,\n );\n }\n if (stored.kind === \"runTerminal\") {\n if (data.eventType === \"step_started\") {\n throw new RunExpiredError(\n `Cannot start step on run in terminal state \"${stored.status}\"`,\n );\n }\n throw new EntityConflictError(\n `Cannot add ${data.eventType} to run in terminal state \"${stored.status}\"`,\n );\n }\n if (stored.kind === \"hookGone\") {\n throw new HookNotFoundError(data.correlationId!);\n }\n if (stored.kind === \"claimed\") {\n // Another writer already recorded this resume; converge on its event.\n const [claimedEventId, claimedDigest, claimedHookId] =\n stored.claim.split(\"|\");\n if (claimedHookId !== data.correlationId) {\n throw new EntityConflictError(\n `hook_received resumeId \"${params!.resumeId}\" already recorded for a different hook`,\n );\n }\n if (\n params?.resumePayloadDigest &&\n claimedDigest &&\n claimedDigest !== params.resumePayloadDigest\n ) {\n throw new EntityConflictError(\n `hook_received resumeId \"${params!.resumeId}\" already recorded with a different payload`,\n );\n }\n const [existingEvent] = await readEvents(effectiveRunId, [\n claimedEventId,\n ]);\n if (!existingEvent) {\n throw new WorkflowWorldError(`Event not found: ${claimedEventId}`, {\n status: 404,\n });\n }\n return { event: stripEventDataRefs(existingEvent, entityData) };\n }\n\n // Preload the run's log on run_started to save the caller a list.\n let preloaded:\n | { events: Event[]; cursor: string | null; hasMore: boolean }\n | undefined;\n if (\n data.eventType === \"run_started\" &&\n run &&\n params?.skipPreload !== true\n ) {\n const total = await redis.hlen(eventsKey(effectiveRunId));\n const all = await readSlots(effectiveRunId, FIRST_EVENT_SLOT, total);\n preloaded = {\n events: all.map((e) => stripEventDataRefs(e, resolveData)),\n cursor: all.at(-1)?.eventId ?? null,\n hasMore: false,\n };\n }\n\n return {\n event: stripEventDataRefs(stored.event, entityData),\n run: run ? await withAttributes(run) : undefined,\n step,\n hook,\n ...preloaded,\n // Server-owned per-run event ceiling; the runtime enforces it. Only\n // meaningful when a run entity is attached (run-lifecycle responses).\n ...(run ? { maxEvents: maxEventsPerRun } : {}),\n } as EventResult;\n }\n\n return {\n // Wrapped rather than folded into `createEvent`, which has a dozen commit\n // points: the delta and the skipped-slot report are the same at every one\n // of them (read the committed id, read back what is around it).\n create: (async (\n runId: string | null,\n data: CreateEventRequest | RunCreatedEventRequest,\n params?: CreateEventParams,\n ): Promise<EventResult> => {\n const result = await createEvent(runId, data, params);\n // A preload (run_started) already owns events/cursor/hasMore.\n if (!result.event || result.events !== undefined) return result;\n const resolveData = params?.resolveData ?? \"all\";\n // The delta wins when both were asked for: the skipped slots all sit above\n // the cursor, so it is a strict superset, and it is the only one of the two\n // that advances `cursor`.\n if (typeof params?.sinceCursor === \"string\") {\n return deltaSince(result, params.sinceCursor, resolveData);\n }\n if (params?.eventCount !== undefined) {\n return reportSkippedSlots(result, params.eventCount, resolveData);\n }\n return result;\n }) as Storage[\"events\"][\"create\"],\n\n async get(\n runId: string,\n eventId: string,\n params?: GetEventParams,\n ): Promise<Event> {\n const data = await redis.hget(eventsKey(runId), eventId);\n if (!data) {\n throw new WorkflowWorldError(`Event not found: ${eventId}`, {\n status: 404,\n });\n }\n const event = EventSchema.parse(compact(parse<Event>(data)));\n return stripEventDataRefs(event, params?.resolveData ?? \"all\");\n },\n\n async list(params: ListEventsParams): Promise<EventListResponse> {\n const sortOrder = params.pagination?.sortOrder || \"asc\";\n const fromCursor = params.pagination?.cursor;\n const total = await redis.hlen(eventsKey(params.runId));\n // The log is dense, so a page is a run of consecutive slots.\n const limit = params.pagination?.limit ?? Math.max(total, 1);\n\n let cursorSlot: number | null = null;\n if (fromCursor) {\n cursorSlot = eventIdToSlot(fromCursor);\n if (cursorSlot === null) {\n throw new WorkflowWorldError(\n `Invalid pagination cursor \"${fromCursor}\"`,\n {\n status: 400,\n },\n );\n }\n }\n\n let events: Event[];\n let hasMore: boolean;\n if (sortOrder === \"desc\") {\n const last =\n cursorSlot === null ? total : Math.min(cursorSlot - 1, total);\n const first = Math.max(FIRST_EVENT_SLOT, last - limit + 1);\n events = (await readSlots(params.runId, first, last)).reverse();\n hasMore = first > FIRST_EVENT_SLOT;\n } else {\n const first = (cursorSlot ?? 0) + 1;\n const last = Math.min(total, first + limit - 1);\n events = await readSlots(params.runId, first, last);\n hasMore = last < total;\n }\n\n const resolveData = params.resolveData ?? \"all\";\n return {\n data: events.map((event) => stripEventDataRefs(event, resolveData)),\n // Echo the cursor back on an empty page so a poller keeps its place.\n cursor: events.at(-1)?.eventId ?? fromCursor ?? null,\n hasMore,\n };\n },\n\n async listByCorrelationId(\n params: ListEventsByCorrelationIdParams,\n ): Promise<PaginatedResponse<Event>> {\n const limit = params.pagination?.limit ?? 100;\n const sortOrder = params.pagination?.sortOrder || \"asc\";\n const fromCursor = params.pagination?.cursor;\n const indexKey = eventsByCorrelationKey(\n params.runId,\n params.correlationId,\n );\n\n // Members are event ids scored by slot, so a cursor is a score bound.\n let ids: string[];\n if (sortOrder === \"desc\") {\n const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;\n const max = cursorSlot === null ? \"+inf\" : `(${cursorSlot}`;\n ids = await redis.zrevrangebyscore(\n indexKey,\n max,\n \"-inf\",\n \"LIMIT\",\n 0,\n limit + 1,\n );\n } else {\n const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;\n const min = cursorSlot === null ? \"-inf\" : `(${cursorSlot}`;\n ids = await redis.zrangebyscore(\n indexKey,\n min,\n \"+inf\",\n \"LIMIT\",\n 0,\n limit + 1,\n );\n }\n\n const page = ids.slice(0, limit);\n const events = await readEvents(params.runId, page);\n const resolveData = params.resolveData ?? \"all\";\n return {\n data: events.map((event) => stripEventDataRefs(event, resolveData)),\n cursor: events.at(-1)?.eventId ?? fromCursor ?? null,\n hasMore: ids.length > limit,\n };\n },\n };\n}\n\n/**\n * Create storage for workflow steps using Redis hashes and sorted sets\n */\nexport function createStepsStorage(\n config: RedisStorageConfig,\n): Storage[\"steps\"] {\n const { redis, keyPrefix } = config;\n\n const { stepKey, stepsIndexKey } = keys(keyPrefix);\n\n async function getStepData(\n key: string,\n stepId: string,\n params?: GetStepParams,\n ): Promise<Step | StepWithoutData> {\n const data = await redis.get(key);\n\n if (!data) {\n throw new WorkflowWorldError(`Step not found: ${stepId}`, {\n status: 404,\n });\n }\n\n const step = parse<Step>(data);\n const parsed = StepSchema.parse(compact(step));\n const resolveData = params?.resolveData ?? \"all\";\n return filterStepData(parsed, resolveData);\n }\n\n return {\n // A step id only identifies a step within its run, so the run is part of the key.\n get: (async (runId: string, stepId: string, params?: GetStepParams) =>\n getStepData(\n stepKey(runId, stepId),\n stepId,\n params,\n )) as Storage[\"steps\"][\"get\"],\n\n list: (async (params: ListWorkflowRunStepsParams) => {\n const limit = params?.pagination?.limit ?? 20;\n const fromCursor = params?.pagination?.cursor;\n\n const entries = await pageIndex(\n redis,\n stepsIndexKey(params.runId),\n fromCursor,\n limit + 1,\n params?.pagination?.sortOrder ?? \"desc\",\n );\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(stepKey(params.runId, id));\n }\n const results = await pipeline.exec();\n\n const resolveData = params?.resolveData ?? \"all\";\n const steps: { step: Step | StepWithoutData; cursor: string }[] = [];\n for (const [i, result] of (results ?? []).entries()) {\n if (result?.[1]) {\n const step = parse<Step>(result[1] as string);\n const parsed = StepSchema.parse(compact(step));\n steps.push({\n step: filterStepData(parsed, resolveData),\n cursor: entries[i].cursor,\n });\n }\n }\n\n const values = steps.slice(0, limit);\n const hasMore = steps.length > limit;\n\n return {\n data: values.map((entry) => entry.step),\n hasMore,\n cursor: values.at(-1)?.cursor ?? null,\n };\n }) as Storage[\"steps\"][\"list\"],\n };\n}\n\n/**\n * Create storage for hooks using Redis hashes and sorted sets\n */\nexport function createHooksStorage(\n config: RedisStorageConfig,\n): Storage[\"hooks\"] {\n const { redis, keyPrefix } = config;\n\n const {\n hookKey: hookKeyFn,\n hooksByTokenKey,\n hooksIndexKey,\n runsByStatusKey,\n } = keys(keyPrefix);\n\n // A finished run holds no hooks, so every hook is in the index of a live run.\n // shortcut: one index read per live run on each page, upgrade to a global hooks\n // index (kept in the create/dispose/finish scripts) if that count gets large.\n async function liveHooksIndexKeys(): Promise<string[]> {\n const live = await Promise.all(\n [\"pending\", \"running\"].map((status) =>\n redis.zrange(runsByStatusKey(status), \"0\", \"-1\"),\n ),\n );\n return live.flat().map(hooksIndexKey);\n }\n\n return {\n async get(hookId: string, params?: GetHookParams): Promise<Hook> {\n const data = await redis.get(hookKeyFn(hookId));\n if (!data) {\n throw new HookNotFoundError(hookId);\n }\n const hook = parse<Hook>(data);\n const parsed = HookSchema.parse(compact(hook));\n const resolveData = params?.resolveData ?? \"all\";\n return filterHookData(parsed, resolveData);\n },\n\n async getByToken(token: string, params?: GetHookParams): Promise<Hook> {\n const hookId = await redis.get(hooksByTokenKey(token));\n if (!hookId) {\n throw new HookNotFoundError(token);\n }\n return this.get(hookId, params);\n },\n\n async list(params: ListHooksParams): Promise<PaginatedResponse<Hook>> {\n const limit = params?.pagination?.limit ?? 100;\n const fromCursor = params?.pagination?.cursor;\n\n const entries = await pageIndex(\n redis,\n params.runId ? hooksIndexKey(params.runId) : await liveHooksIndexKeys(),\n fromCursor,\n limit + 1,\n params?.pagination?.sortOrder ?? \"asc\",\n );\n\n const pipeline = redis.pipeline();\n for (const { id } of entries) {\n pipeline.get(hookKeyFn(id));\n }\n const results = await pipeline.exec();\n\n const hooks: { hook: Hook; cursor: string }[] = [];\n for (const [i, result] of (results ?? []).entries()) {\n if (result?.[1]) {\n const hook = parse<Hook>(result[1] as string);\n const parsed = HookSchema.parse(compact(hook));\n hooks.push({\n hook: filterHookData(parsed, params?.resolveData ?? \"all\"),\n cursor: entries[i].cursor,\n });\n }\n }\n\n const values = hooks.slice(0, limit);\n const hasMore = hooks.length > limit;\n\n return {\n data: values.map((entry) => entry.hook),\n cursor: values.at(-1)?.cursor ?? null,\n hasMore,\n };\n },\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport type {\n GetChunksOptions,\n StreamChunk,\n StreamChunksResponse,\n StreamInfoResponse,\n Streamer,\n} from \"@workflow/world\";\nimport type { Redis } from \"ioredis\";\nimport { keys } from \"./keys.js\";\nimport { debug } from \"./util.js\";\n\ninterface StreamPublishMessage {\n runId: string;\n streamId: string;\n entryId: string;\n /** Base64 chunk, inline so subscribers need no XRANGE per notification. */\n data: string;\n eof: boolean;\n /**\n * The entry that came before this one in the stream ('' for the first).\n * Pub/sub does not guarantee delivery, so a reader that sees an entry whose\n * predecessor is not the last one it delivered knows a message was lost and\n * reads the stream instead of skipping it.\n */\n prevId: string;\n}\n\nfunction parseStreamPublishMessage(raw: string): StreamPublishMessage | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const { runId, streamId, entryId, data, eof, prevId } = parsed as Record<\n string,\n unknown\n >;\n if (typeof runId !== \"string\" || typeof streamId !== \"string\") return null;\n if (typeof entryId !== \"string\" || typeof prevId !== \"string\") return null;\n if (typeof data !== \"string\" || typeof eof !== \"boolean\") return null;\n return { runId, streamId, entryId, data, eof, prevId };\n}\n\ninterface StreamChunkEvent {\n id: string;\n data: Uint8Array;\n eof: boolean;\n /** Set on live notifications: see `StreamPublishMessage.prevId`. */\n prevId?: string;\n}\n\n/** A reader also re-reads the stream this often, in case a notification and the\n * reconnect hook both missed something. Notifications are the fast path. */\nconst CATCH_UP_INTERVAL_MS = 2_000;\n\n/**\n * Compare two Redis stream entry IDs (`<ms>-<seq>`) numerically.\n *\n * String comparison is NOT safe here: within one millisecond `...-10` compares\n * lexicographically smaller than `...-9`, which would drop chunks (and the eof\n * marker) once the sequence number crosses a digit boundary.\n */\nfunction compareStreamEntryIds(a: string, b: string): number {\n const [aMs, aSeq] = a.split(\"-\").map(Number);\n const [bMs, bSeq] = b.split(\"-\").map(Number);\n return aMs - bMs || aSeq - bSeq;\n}\n\ninterface StreamerConfig {\n redis: Redis;\n keyPrefix: string;\n}\n\n/**\n * Append one or more chunks, index the stream under its run, and notify\n * subscribers in one round trip. The publish could not be pipelined with the\n * append because it needs the entry ID `XADD` generates; Lua makes that\n * dependency server-side. Each chunk rides along in its message so subscribers\n * do not `XRANGE` per notification.\n *\n * A stream that already holds its eof marker is closed: the append is dropped\n * and nothing is published. Readers stop at the first eof anyway, so this only\n * keeps the invariant that the eof marker, when present, is the final entry.\n * `getInfo` relies on it to answer from `XLEN` and the tail entry alone, and a\n * producer retrying a lost-ACK `close()` would otherwise break it.\n *\n * KEYS[1] = stream key\n * KEYS[2] = streams-by-run key\n * ARGV[1] = notification channel\n * ARGV[2] = run ID\n * ARGV[3] = stream name\n * ARGV[4] = 'true' | 'false' (eof marker, applied to every chunk below)\n * ARGV[5..] = base64 chunk data, in write order\n * Returns: 1 if appended, 0 if the stream was already closed\n */\nconst LUA_APPEND_AND_PUBLISH = `\n local streamKey = KEYS[1]\n local runIndexKey = KEYS[2]\n local channel = ARGV[1]\n local runId = ARGV[2]\n local streamId = ARGV[3]\n local eof = ARGV[4]\n\n local tail = redis.call('XREVRANGE', streamKey, '+', '-', 'COUNT', 1)\n if #tail > 0 and tail[1][2][4] == 'true' then\n return 0\n end\n\n local prevId = ''\n if #tail > 0 then\n prevId = tail[1][1]\n end\n\n for i = 5, #ARGV do\n local data = ARGV[i]\n local entryId = redis.call('XADD', streamKey, '*', 'data', data, 'eof', eof)\n redis.call('PUBLISH', channel, cjson.encode({\n runId = runId,\n streamId = streamId,\n entryId = entryId,\n data = data,\n eof = eof == 'true',\n prevId = prevId\n }))\n prevId = entryId\n end\n redis.call('SADD', runIndexKey, streamId)\n return 1\n`;\n\n/** An XRANGE entry, by the field order `LUA_APPEND_AND_PUBLISH` writes: data, then eof. */\nfunction decodeEntry([id, fields]: [string, string[]]): StreamChunkEvent {\n return {\n id,\n data: Buffer.from(fields[1]!, \"base64\"),\n eof: fields[3] === \"true\",\n };\n}\n\ntype RedisWithStreamScript = Redis & {\n wfStreamAppend(...args: string[]): Promise<number>;\n};\n\n/**\n * Create a streamer implementation using Redis Streams.\n *\n * Uses Redis auto-generated stream entry IDs (timestamp-sequence format)\n * instead of custom IDs, since Redis Streams require IDs in\n * `<millisecondsTime>-<sequenceNumber>` format.\n *\n * Key layout (every key is scoped to the run that owns the stream, so two runs\n * can use the same stream name without sharing chunks):\n * - `<prefix>stream:<runId>:<name>` Redis Stream of the chunks plus the eof marker\n * - `<prefix>streams:by_run:<runId>` Set of the run's stream names\n * - `<prefix>stream_notify` pub/sub channel carrying live chunks\n */\nexport function createStreamer(\n config: StreamerConfig,\n): Streamer & { close(): Promise<void> } {\n const { redis, keyPrefix } = config;\n const events = new EventEmitter<{\n [key: `strm:${string}`]: [StreamChunkEvent];\n }>();\n const tails = new Map<string, Promise<unknown>>();\n\n // Serialize work per stream key, so concurrent pub/sub notifications for the\n // same stream are processed in order. A key's tail is dropped once it settles last.\n const withStreamMutex = <T>(\n key: string,\n fn: () => Promise<T>,\n ): Promise<T> => {\n const run = (tails.get(key) ?? Promise.resolve()).then(fn, fn);\n const tail = run.catch(() => {});\n tails.set(key, tail);\n void tail.then(() => {\n if (tails.get(key) === tail) tails.delete(key);\n });\n return run;\n };\n\n redis.defineCommand(\"wfStreamAppend\", {\n numberOfKeys: 2,\n lua: LUA_APPEND_AND_PUBLISH,\n });\n const scripted = redis as RedisWithStreamScript;\n\n // `streamsByRunKey` indexes a run's stream names, populated on every\n // write/close so `streams.list` can enumerate them.\n const {\n streamKey,\n streamsByRunKey,\n streamChannel: STREAM_CHANNEL,\n } = keys(keyPrefix);\n const emitterKey = (runId: string, name: string) =>\n `strm:${runId}:${name}` as const;\n\n const subscriber = redis.duplicate();\n\n // A PUBLISH sent before SUBSCRIBE is ready is lost, and a reader waiting on it\n // hangs, so every append awaits this first.\n const subscriptionReady: Promise<void> = subscriber\n .subscribe(STREAM_CHANNEL)\n .then(() => {});\n\n // Anything published while the subscriber connection was down is gone, so on\n // every reconnect the live readers re-read their streams.\n const resync = new EventEmitter();\n resync.setMaxListeners(0);\n let subscriberConnected = false;\n subscriber.on(\"ready\", () => {\n if (subscriberConnected) resync.emit(\"resync\");\n subscriberConnected = true;\n });\n\n subscriber.on(\"message\", async (channel, message) => {\n if (channel !== STREAM_CHANNEL) return;\n\n try {\n const parsed = parseStreamPublishMessage(message);\n if (!parsed) return;\n\n const key = emitterKey(parsed.runId, parsed.streamId);\n if (!events.listenerCount(key)) {\n return;\n }\n\n await withStreamMutex(key, async () => {\n // The chunk travels with the notification, so no XRANGE per message.\n events.emit(key, {\n id: parsed.entryId,\n data: Buffer.from(parsed.data, \"base64\"),\n eof: parsed.eof,\n prevId: parsed.prevId,\n });\n });\n } catch (error) {\n console.error(\"Error processing stream notification:\", error);\n }\n });\n\n const toBase64 = (chunk: string | Uint8Array): string =>\n (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)).toString(\"base64\");\n\n const append = async (\n runId: string,\n name: string,\n eof: boolean,\n encodedChunks: string[],\n ): Promise<void> => {\n await subscriptionReady;\n\n await scripted.wfStreamAppend(\n streamKey(runId, name),\n streamsByRunKey(runId),\n STREAM_CHANNEL,\n runId,\n name,\n eof ? \"true\" : \"false\",\n ...encodedChunks,\n );\n };\n\n return {\n streams: {\n async write(\n _runId: string | Promise<string>,\n name: string,\n chunk: string | Uint8Array,\n ): Promise<void> {\n const runId = await _runId;\n await append(runId, name, false, [toBase64(chunk)]);\n },\n\n async writeMulti(\n _runId: string | Promise<string>,\n name: string,\n chunks: (string | Uint8Array)[],\n ): Promise<void> {\n if (chunks.length === 0) return;\n\n const runId = await _runId;\n\n // One script call appends every chunk, so they land contiguously and\n // in array order.\n await append(runId, name, false, chunks.map(toBase64));\n },\n\n async close(\n _runId: string | Promise<string>,\n name: string,\n ): Promise<void> {\n const runId = await _runId;\n\n // Final chunk carries eof=true. Same single-round-trip append as\n // above, which also keeps the stream indexed when it closes without\n // any data.\n await append(runId, name, true, [\"\"]);\n },\n\n async get(\n runId: string,\n name: string,\n startIndex?: number,\n ): Promise<ReadableStream<Uint8Array>> {\n const key = emitterKey(runId, name);\n const cleanups: (() => void)[] = [];\n let cleanedUp = false;\n // Idempotent: reachable from eof, cancel() and a failed initial read,\n // and more than one of them can fire for the same reader (for example\n // cancel() while the initial XRANGE is in flight).\n const cleanup = () => {\n if (cleanedUp) return;\n cleanedUp = true;\n for (const fn of cleanups) fn();\n };\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n let lastEntryId = \"\";\n let offset = startIndex ?? 0;\n let buffer = [] as StreamChunkEvent[] | null;\n\n function enqueue(msg: StreamChunkEvent) {\n // The reader was cancelled while the initial read was in flight,\n // or the eof marker was already delivered. Nothing may be\n // enqueued on the controller any more.\n if (cleanedUp) return;\n\n // Already delivered, or out of order.\n if (\n lastEntryId !== \"\" &&\n compareStreamEntryIds(lastEntryId, msg.id) >= 0\n )\n return;\n // Record the entry before the offset check: an entry skipped by\n // the offset must not be skipped (and counted) a second time when\n // it shows up again as a buffered live message.\n lastEntryId = msg.id;\n\n // The eof marker is not a data chunk (`getInfo`'s tailIndex\n // excludes it), so it never counts toward the offset: a start\n // index at or past the data count must still close the stream\n // rather than consume the marker and then hang.\n if (offset > 0 && !msg.eof) {\n offset--;\n return;\n }\n\n if (msg.data.byteLength) {\n controller.enqueue(new Uint8Array(msg.data));\n }\n if (msg.eof) {\n cleanup();\n controller.close();\n }\n }\n\n // Read what the stream holds beyond the last delivered entry. Notifications\n // are fire-and-forget, so this is how a lost one is recovered. Runs one\n // at a time; a request that arrives meanwhile triggers one more pass.\n let catchingUp = false;\n let again = false;\n async function catchUp() {\n if (cleanedUp || buffer) return;\n if (catchingUp) {\n again = true;\n return;\n }\n catchingUp = true;\n try {\n do {\n again = false;\n const entries = await redis.xrange(\n streamKey(runId, name),\n lastEntryId === \"\" ? \"-\" : `(${lastEntryId}`,\n \"+\",\n );\n for (const entry of entries) enqueue(decodeEntry(entry));\n } while (again && !cleanedUp);\n } catch (error) {\n // Transient (connection loss): the next trigger reads again.\n debug(\"Stream catch-up failed:\", error);\n } finally {\n catchingUp = false;\n }\n }\n\n // A live notification. One whose predecessor we never delivered means an\n // earlier one was lost: read the stream rather than skip past it.\n function deliverLive(data: StreamChunkEvent) {\n if (data.prevId !== undefined && data.prevId !== lastEntryId) {\n void catchUp();\n return;\n }\n enqueue(data);\n }\n\n function onData(data: StreamChunkEvent) {\n if (buffer) {\n buffer.push(data);\n return;\n }\n deliverLive(data);\n }\n\n // Subscribe before reading history so nothing published in between\n // is missed; `buffer` holds those until the history is replayed.\n events.on(key, onData);\n cleanups.push(() => {\n events.off(key, onData);\n });\n\n const chunks = await redis\n .xrange(streamKey(runId, name), \"-\", \"+\")\n .catch((err) => {\n // A failed read fails the stream; detach the listener so a\n // failing stream does not leak one per attempt.\n cleanup();\n throw err;\n });\n\n const parsedChunks = chunks.map(decodeEntry);\n\n // Resolve a negative start index against the data chunks stored\n // right now (everything before the eof marker): -3 on a stream\n // with 10 chunks starts at chunk 7. Clamped to 0.\n if (offset < 0) {\n const firstEof = parsedChunks.findIndex((chunk) => chunk.eof);\n const dataCount =\n firstEof === -1 ? parsedChunks.length : firstEof;\n offset = Math.max(0, dataCount + offset);\n }\n\n const buffered = buffer ?? [];\n buffer = null;\n\n // The history is the stream as it was read, so it goes in as is. What was\n // buffered while it was read is live traffic, and a message lost there\n // would leave a hole, so it goes through the same gap check.\n for (const chunk of parsedChunks) {\n enqueue(chunk);\n }\n for (const chunk of buffered) {\n deliverLive(chunk);\n }\n\n // Cover a notification lost while the history was being read, after a\n // reconnect, and by a timer in case both miss.\n resync.on(\"resync\", catchUp);\n const timer = setInterval(\n () => void catchUp(),\n CATCH_UP_INTERVAL_MS,\n );\n timer.unref();\n cleanups.push(() => {\n resync.off(\"resync\", catchUp);\n clearInterval(timer);\n });\n await catchUp();\n },\n cancel() {\n cleanup();\n },\n });\n },\n\n async list(runId: string): Promise<string[]> {\n return (await redis.smembers(streamsByRunKey(runId))) ?? [];\n },\n\n async getChunks(\n runId: string,\n name: string,\n options?: GetChunksOptions,\n ): Promise<StreamChunksResponse> {\n const limit = Math.min(options?.limit ?? 100, 1000);\n\n // Cursor carries the running 0-based data-chunk index plus the last\n // returned entry ID, letting us resume with a bounded XRANGE instead of\n // rescanning the whole stream on every page.\n let dataIndex = 0;\n let start = \"-\";\n if (options?.cursor) {\n try {\n const decoded = JSON.parse(\n Buffer.from(options.cursor, \"base64\").toString(\"utf-8\"),\n ) as {\n i?: number;\n id?: string;\n };\n if (typeof decoded.i === \"number\") dataIndex = decoded.i;\n // '(' makes the range start exclusive of the last returned entry.\n if (typeof decoded.id === \"string\") start = `(${decoded.id}`;\n } catch {\n // Malformed cursor -> restart from the beginning of the stream.\n dataIndex = 0;\n start = \"-\";\n }\n }\n\n // Fetch one extra entry to detect whether more data pages follow.\n const entries = await redis.xrange(\n streamKey(runId, name),\n start,\n \"+\",\n \"COUNT\",\n limit + 1,\n );\n\n const data: StreamChunk[] = [];\n let done = false;\n let hasMore = false;\n let lastId: string | null = null;\n\n for (const entry of entries) {\n const { id, data: bytes, eof } = decodeEntry(entry);\n if (eof) {\n // The eof marker is always the terminal entry, so reaching it means\n // the stream is complete and no further data pages exist.\n done = true;\n break;\n }\n if (data.length >= limit) {\n // A data entry beyond the requested page: more pages remain.\n hasMore = true;\n break;\n }\n data.push({\n index: dataIndex,\n data: new Uint8Array(bytes),\n });\n dataIndex++;\n lastId = id;\n }\n\n const cursor =\n hasMore && lastId\n ? Buffer.from(\n JSON.stringify({ i: dataIndex, id: lastId }),\n ).toString(\"base64\")\n : null;\n\n return { data, cursor, hasMore, done };\n },\n\n async getInfo(runId: string, name: string): Promise<StreamInfoResponse> {\n const key = streamKey(runId, name);\n const [length, tail] = await Promise.all([\n redis.xlen(key),\n redis.xrevrange(key, \"+\", \"-\", \"COUNT\", 1),\n ]);\n // The eof marker is always the final entry (the append script drops\n // anything written after it, and auto-generated IDs are monotonic), so\n // the last entry alone tells us whether the stream is done. Data chunks\n // are the non-eof entries; an empty stream yields tailIndex -1.\n const done = tail.length > 0 && tail[0][1][3] === \"true\";\n const dataCount = length - (done ? 1 : 0);\n return { tailIndex: dataCount - 1, done };\n },\n },\n\n async close(): Promise<void> {\n // Tear down the duplicated pub/sub connection so short-lived processes\n // do not leak it.\n await subscriber.quit();\n },\n };\n}\n","import {\n mintedSpecVersion,\n reenqueueActiveRuns,\n type World,\n} from \"@workflow/world\";\nimport { WorkflowRunNotFoundError } from \"@workflow/errors\";\nimport { Redis } from \"ioredis\";\nimport {\n resolveConfig,\n type RedisBackedWorldConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nimport { createReaper, hasRetention, validateRetention } from \"./reaper.js\";\nimport { createRunId } from \"./run-id.js\";\nimport {\n createEventsStorage,\n createHooksStorage,\n createRunsStorage,\n createStepsStorage,\n} from \"./storage.js\";\nimport { createStreamer } from \"./streamer.js\";\nimport type {\n QueueStats,\n WorldQueue,\n WorldQueueOptions,\n} from \"./world-queue.js\";\n\nexport type RedisBackedWorld = World & {\n start(): Promise<void>;\n getQueueStats(): Promise<QueueStats>;\n /** Run one retention sweep now; returns the runs deleted. 0 without `retention`. */\n sweepRetention(): Promise<number>;\n};\n\n/**\n * A world on Redis: storage, streams and retention are the same for every\n * queue; `createQueue` supplies the queue. `config` is laid over `env`, so an\n * option the caller leaves out still comes from the environment.\n */\nexport function createRedisBackedWorld<C extends RedisBackedWorldConfig>(\n config: Partial<C>,\n world: {\n env: C;\n createQueue(\n redis: Redis,\n config: ResolvedConfig<C>,\n options: WorldQueueOptions,\n ): WorldQueue;\n /** Log prefix for run recovery on start. */\n label: string;\n debug: (...args: unknown[]) => void;\n },\n): RedisBackedWorld {\n const merged: C = { ...world.env };\n for (const [key, value] of Object.entries(config)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n const cfg = resolveConfig(merged);\n // Batches commands issued in the same event-loop tick into one write. Does\n // nothing for a single serial run, but collapses syscalls under concurrency:\n // measured 1.75x at 256 concurrent invocations, 1.15x at 32, a slight loss\n // at 1. Workers default to 10 and go higher under load, so default on.\n const autoPipelining = cfg.enableAutoPipelining;\n validateRetention(cfg.retention);\n const redis =\n typeof cfg.redis === \"string\"\n ? new Redis(cfg.redis, { enableAutoPipelining: autoPipelining })\n : new Redis({ enableAutoPipelining: autoPipelining, ...cfg.redis });\n\n const { keyPrefix } = cfg;\n const reaper = hasRetention(cfg.retention)\n ? createReaper({\n redis,\n keyPrefix,\n retention: cfg.retention,\n })\n : undefined;\n\n const storageConfig = {\n redis,\n keyPrefix,\n maxEventsPerRun: cfg.maxEventsPerRun,\n };\n const storage = {\n runs: createRunsStorage(storageConfig),\n events: createEventsStorage(storageConfig),\n hooks: createHooksStorage(storageConfig),\n steps: createStepsStorage(storageConfig),\n };\n const queue = world.createQueue(redis, cfg, {\n runHasStarted: async (runId) => {\n try {\n const run = await storage.runs.get(runId, { resolveData: \"none\" });\n return run.status !== \"pending\";\n } catch (error) {\n if (WorkflowRunNotFoundError.is(error)) return false;\n throw error;\n }\n },\n });\n const streamer = createStreamer({ redis, keyPrefix });\n\n return {\n ...storage,\n ...streamer,\n ...queue,\n // Declares support for the CBOR/binary-safe queue transport so core\n // attaches runInput to workflow messages (resilient start). The queue\n // serializes payloads with a tagged-JSON transport that round-trips\n // Uint8Array values. A function, not a constant: the version this world\n // stamps follows `WORKFLOW_SEALED_LOG`.\n specVersion: mintedSpecVersion(),\n createRunId,\n async start() {\n await queue.start();\n reaper?.start();\n // Put runs that were in flight back on the queue, in case the queue lost\n // them (a Redis restart without persistence, a failover). Replay is\n // idempotent, so a duplicate is harmless; the dedup key makes several\n // workers restarting together enqueue one message per run, not one each.\n await reenqueueActiveRuns(\n storage.runs,\n (queueName, message, opts) =>\n queue.queue(queueName, message, {\n ...opts,\n idempotencyKey: `recover:${(message as { runId: string }).runId}`,\n }),\n world.label,\n );\n },\n async sweepRetention() {\n return reaper ? reaper.sweep() : 0;\n },\n async close() {\n await reaper?.stop();\n await queue.close();\n await streamer.close();\n await redis.quit();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAgB,kBAAkB,WAAmB;CACnD,QAAQ,GAAG,SAAoB;EAC7B,MAAM,QAAQ,QAAQ,IAAI;EAC1B,IAAI,CAAC,OAAO;EAQZ,IAAI,EALF,UAAU,OACV,UAAU,UACV,UAAU,OACV,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,OAAO,GAAG,KAAK,MAAM,SAAS,IAEzC;EAGd,MAAM,SAAS,qBADG,IAAI,KAAK,EAAA,CAAE,YACF,EAAE,KAAK,UAAU;EAC5C,MAAM,UAAU,KACb,KAAK,QACJ,OAAO,QAAQ,WAAW,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,OAAO,GAAG,CACrE,CAAC,CACA,KAAK,GAAG;EAEX,QAA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;EAC/B;EACA,MAAM,QAAQ;GACZ,MAAM,MAAM,MAAM;GAClB,QAAQ,MAAM;GAKd,MAAM,oBACJ,QAAQ,OACP,WAAW,SAAS,SACnB,MAAM,MAAM,WAAW,SAAS;IAC9B,GAAG;IACH,gBAAgB,WAAY,QAA8B;GAC5D,CAAC,GACH,MAAM,KACR;EACF;EACA,MAAM,iBAAiB;GACrB,OAAO,SAAS,OAAO,MAAM,IAAI;EACnC;EACA,MAAM,QAAQ;GACZ,MAAM,QAAQ,KAAK;GACnB,MAAM,MAAM,MAAM;GAClB,MAAM,SAAS,MAAM;GACrB,MAAM,MAAM,KAAK;EACnB;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brickkit/redis-world",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0-beta.0",
|
|
4
4
|
"description": "Plain Redis World for Workflow SDK v5 with a reliable list queue and durable storage",
|
|
5
5
|
"homepage": "https://brickkit.dev",
|
|
6
6
|
"keywords": [
|
|
@@ -51,9 +51,9 @@
|
|
|
51
51
|
"test:e2e": "bun run build && vitest run --config vitest.e2e.config.ts"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@workflow/errors": "5.1.
|
|
55
|
-
"@workflow/utils": "5.0
|
|
56
|
-
"@workflow/world": "5.
|
|
54
|
+
"@workflow/errors": "5.1.1",
|
|
55
|
+
"@workflow/utils": "5.1.0",
|
|
56
|
+
"@workflow/world": "5.2.0",
|
|
57
57
|
"ioredis": "^6.0.0",
|
|
58
58
|
"ulid": "^3.0.2"
|
|
59
59
|
},
|
|
@@ -61,13 +61,13 @@
|
|
|
61
61
|
"@hono/node-server": "^2.1.6",
|
|
62
62
|
"@testcontainers/redis": "^12.2.1",
|
|
63
63
|
"@types/node": "^26.6.6",
|
|
64
|
-
"@workflow/cli": "5.0
|
|
65
|
-
"@workflow/core": "5.
|
|
66
|
-
"@workflow/world-testing": "5.0
|
|
64
|
+
"@workflow/cli": "5.1.0",
|
|
65
|
+
"@workflow/core": "5.5.0",
|
|
66
|
+
"@workflow/world-testing": "5.1.0",
|
|
67
67
|
"hono": "^4.13.16",
|
|
68
|
-
"tsdown": "^0.23.
|
|
68
|
+
"tsdown": "^0.23.7",
|
|
69
69
|
"typescript": "^7.0.2",
|
|
70
|
-
"vitest": "^
|
|
71
|
-
"workflow": "5.
|
|
70
|
+
"vitest": "^5.1.0",
|
|
71
|
+
"workflow": "5.5.0"
|
|
72
72
|
}
|
|
73
73
|
}
|