@brickkit/redis-world 0.12.0 → 0.13.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/bin/setup.js +0 -2
- package/dist/cli-BEHfAdNK.js +65 -0
- package/dist/cli-BEHfAdNK.js.map +1 -0
- package/dist/cli.d.ts +10 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +1 -49
- package/dist/index.d.ts +5 -119
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +45 -234
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +5 -81
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +4 -3
- package/dist/keys-CqKp_Amk.js +104 -0
- package/dist/keys-CqKp_Amk.js.map +1 -0
- package/dist/{shared-Bhvu4aZA.js → world-783VJfKL.js} +354 -247
- package/dist/world-783VJfKL.js.map +1 -0
- package/dist/world-BDW_evdb.d.ts +242 -0
- package/dist/world-BDW_evdb.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/cli.js.map +0 -1
- package/dist/env-DMwDVTiZ.js +0 -18
- package/dist/env-DMwDVTiZ.js.map +0 -1
- package/dist/reaper-SOJDwnBw.d.ts +0 -45
- package/dist/reaper-SOJDwnBw.d.ts.map +0 -1
- package/dist/shared-Bhvu4aZA.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"shared-Bhvu4aZA.js","names":[],"sources":["../src/run-id.ts","../src/internal/debug.ts","../src/internal/util.ts","../src/internal/serialization.ts","../src/util.ts","../src/reaper.ts","../src/storage.ts","../src/streamer.ts","../src/shared.ts"],"sourcesContent":["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 `createQueue`): 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","/**\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=mysql-world // Specific namespace\n * WORKFLOW_DEBUG=mysql-world,redis-world // Multiple namespaces\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","export class Mutex {\n promise: Promise<unknown> = Promise.resolve();\n andThen<T>(fn: () => Promise<T> | T): Promise<T> {\n this.promise = this.promise.then(\n () => fn(),\n () => fn(),\n );\n return this.promise as Promise<T>;\n }\n}\n\nexport 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\n/**\n * Reference counting helper for managing resource lifecycle\n */\nexport class Rc {\n private count = 0;\n private disposeFn?: () => void | Promise<void>;\n\n constructor(disposeFn?: () => void | Promise<void>) {\n this.disposeFn = disposeFn;\n }\n\n inc(): void {\n this.count++;\n }\n\n async dec(): Promise<void> {\n this.count--;\n if (this.count === 0 && this.disposeFn) {\n await this.disposeFn();\n }\n }\n\n getCount(): number {\n return this.count;\n }\n}\n","/** Standard Date fields used across all worlds */\nexport const 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 */\nexport function 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 */\nexport function 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/**\n * JSON reviver that decodes tagged Uint8Array objects\n * (`{ __type: 'Uint8Array', data: '<base64>' }`) and ISO date strings.\n */\nexport function uint8ArrayReviver(key: string, value: unknown): unknown {\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 as string, \"base64\"));\n }\n }\n return 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 */\nexport function 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","import { createDebugLogger } from \"./internal/debug.js\";\n\nexport { compact, Mutex, Rc } 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.\nexport {\n hasBinary,\n parse,\n stringify,\n uint8ArrayReplacer,\n} from \"./internal/serialization.js\";\nexport const debug = createDebugLogger(\"redis-world\");\n","import type { Redis } from \"ioredis\";\nimport { debug } from \"./util.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 /** Logs sweep failures; each world passes its own debug namespace. */\n log?: (...args: unknown[]) => void;\n}): Reaper {\n const { redis, keyPrefix, retention, log = debug } = options;\n const intervalMs = retention.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;\n const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;\n const lockKey = `${keyPrefix}reaper:lock`;\n\n const byStatusKey = (status: string) =>\n `${keyPrefix}runs:by_status:${status}`;\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 = `${keyPrefix}run:meta:${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 = `${keyPrefix}run:${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 = `${keyPrefix}events:data:${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(\n `${keyPrefix}steps:by_run:${runId}`,\n \"0\",\n \"-1\",\n );\n const hookIds = await redis.zrange(\n `${keyPrefix}hooks:by_run:${runId}`,\n \"0\",\n \"-1\",\n );\n const streamNames = await redis.smembers(\n `${keyPrefix}streams:by_run:${runId}`,\n );\n\n const keys = [\n eventsKey,\n `${keyPrefix}run:attrs:${runId}`,\n `${keyPrefix}steps:by_run:${runId}`,\n `${keyPrefix}hooks:by_run:${runId}`,\n `${keyPrefix}hooks:tokens:${runId}`,\n `${keyPrefix}streams:by_run:${runId}`,\n ...[...correlationIds].map(\n (id) => `${keyPrefix}events:by_correlation:${runId}:${id}`,\n ),\n ...stepIds.flatMap((id) => [\n `${keyPrefix}step:${runId}:${id}`,\n `${keyPrefix}step:status:${runId}:${id}`,\n ]),\n ...hookIds.map((id) => `${keyPrefix}hook:${id}`),\n ...streamNames.map((name) => `${keyPrefix}stream:${runId}:${name}`),\n ];\n // Resume claims are not indexed; only a run that received a hook payload can have one.\n if (hasResume)\n keys.push(...(await scan(`${keyPrefix}events:resume:${runId}:*`)));\n await unlink(keys);\n\n const tx = redis\n .multi()\n .zrem(`${keyPrefix}runs:index`, runId)\n .zrem(byStatusKey(status), runId)\n .unlink(metaKey, runKey);\n if (workflowName)\n tx.zrem(`${keyPrefix}runs:by_name:${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 lockKey,\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 log(\"reaper failed to 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) => log(\"reaper sweep failed\", err));\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","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 { compact, parse, stringify } from \"./util.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/** Stringify an object with Uint8Array support. Delegates to the shared\n * helper, which tags binary as base64; the previous number-array encoding\n * cost ~450x more CPU to re-parse and ~2.7x more storage at 2MB. */\nfunction stringifyWithUint8Array(obj: any): string {\n return stringify(obj);\n}\n\n/** Parse JSON with Uint8Array and Date support. The shared reviver decodes\n * both the base64 tag and the legacy number-array tag, so rows already in\n * Redis keep reading back correctly. */\nfunction parseWithUint8Array<T>(json: string): T {\n return parse<T>(json);\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// ============================================================\n// Lua Scripts for Atomic Multi-Key Writes\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// ============================================================\n// Script registration (EVALSHA)\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 runKey = (id: string) => `${keyPrefix}run:${id}`;\n const runAttributesKey = (id: string) => `${keyPrefix}run:attrs:${id}`;\n const runsIndexKey = () => `${keyPrefix}runs:index`;\n const runsByNameKey = (name: string) => `${keyPrefix}runs:by_name:${name}`;\n const runsByStatusKey = (status: string) =>\n `${keyPrefix}runs:by_status:${status}`;\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 // Helper: Select the index (or indexes) to scan, based on filters\n function selectIndexKeys(params?: ListWorkflowRunsParams): string[] {\n if (params?.workflowName) {\n // Use the workflowName index and filter by status in memory\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 // Helper: Fetch and parse runs from pipeline results\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 = parseWithUint8Array<WorkflowRun>(\n result[1] as string,\n );\n run.attributes =\n (results![i + 1]?.[1] as Record<string, string> | undefined) ?? {};\n\n // Apply filters\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 = parseWithUint8Array<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 // Fetch this batch of runs via pipeline\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 eventsKey = (runId: string) => `${keyPrefix}events:data:${runId}`;\n // A correlation id is only unique within its run.\n const eventsByCorrelationKey = (runId: string, correlationId: string) =>\n `${keyPrefix}events:by_correlation:${runId}:${correlationId}`;\n const resumeClaimKey = (runId: string, resumeId: string) =>\n `${keyPrefix}events:resume:${runId}:${resumeId}`;\n\n // Run key helpers (needed for event-sourced entity mutations)\n const runKey = (id: string) => `${keyPrefix}run:${id}`;\n const runAttributesKey = (id: string) => `${keyPrefix}run:attrs:${id}`;\n const runMetaKey = (id: string) => `${keyPrefix}run:meta:${id}`;\n const runsIndexKey = () => `${keyPrefix}runs:index`;\n const runsByNameKey = (name: string) => `${keyPrefix}runs:by_name:${name}`;\n const runsByStatusKey = (status: string) =>\n `${keyPrefix}runs:by_status:${status}`;\n\n // Step key helpers\n const stepKey = (runId: string, stepId: string) =>\n `${keyPrefix}step:${runId}:${stepId}`;\n const stepsIndexKey = (runId: string) => `${keyPrefix}steps:by_run:${runId}`;\n // `<status>|<attempt>`, kept beside the step so a script can check it atomically.\n const stepStatusKey = (runId: string, stepId: string) =>\n `${keyPrefix}step:status:${runId}:${stepId}`;\n\n // Hook key helpers\n const hookKey = (hookId: string) => `${keyPrefix}hook:${hookId}`;\n const hooksByTokenKey = (token: string) =>\n `${keyPrefix}hooks:by_token:${token}`;\n const hooksIndexKey = (runId: string) => `${keyPrefix}hooks:by_run:${runId}`;\n const hooksTokenMapKey = (runId: string) =>\n `${keyPrefix}hooks:tokens:${runId}`;\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 stringifyWithUint8Array({ 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(\n EventSchema.parse(compact(parseWithUint8Array<Event>(value))),\n );\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 stringifyWithUint8Array(updatedRun),\n runId,\n at.getTime().toString(),\n runMetaValue(newStatus, updatedRun.specVersion),\n oldStatus,\n serializeEvent(event),\n releaseHooks ? \"1\" : \"0\",\n `${keyPrefix}hook:`,\n `${keyPrefix}hooks:by_token:`,\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 // For run_created events, generate runId server-side if null or empty\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 // Track entity created/updated for EventResult\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 // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\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 = parseWithUint8Array<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 // ============================================================\n // RESILIENT START: Bootstrap run from run_started eventData\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 stringifyWithUint8Array(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 = parseWithUint8Array<WorkflowRun>(result[1]);\n currentRun = {\n status: parsed.status,\n specVersion: parsed.specVersion,\n };\n existingRun = parsed;\n }\n }\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\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 // Run terminal state validation\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 // Idempotent operation: run_cancelled on already cancelled run is allowed\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 // Other run state transitions are not allowed on terminal runs\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 // Creating new entities on terminal runs is not allowed\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 // Step-related event validation\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 = parseWithUint8Array<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 = parseWithUint8Array<Hook>(existingHook);\n }\n\n // ============================================================\n // Entity creation/updates based on event type\n // ============================================================\n\n // Handle run_created event: create the run entity atomically\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 stringifyWithUint8Array(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 // Handle run_started event: update run status atomically via Lua\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 // Handle run_completed / run_failed / run_cancelled: update the run status\n // atomically, then clean up the run's hooks.\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 // Handle step_created event: create step entity\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 stringifyWithUint8Array(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 // Handle step_started event: increment attempt, set status to 'running'\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 stringifyWithUint8Array(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 = stringifyWithUint8Array(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 // Handle step_completed event: update step status\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 = parseWithUint8Array<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 = stringifyWithUint8Array(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 // Handle step_failed event: terminal state with error\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 = parseWithUint8Array<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 = stringifyWithUint8Array(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 // Handle step_retrying event: sets status back to 'pending', records error\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 = stringifyWithUint8Array(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 // Handle hook_created event: create hook entity atomically via Lua\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 stringifyWithUint8Array(newHook),\n data.correlationId!,\n now.getTime().toString(),\n eventData.token,\n serializeEvent(event),\n `${keyPrefix}hook:`,\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 = parseWithUint8Array<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(\n compact(parseWithUint8Array<Event>(data)),\n );\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 = (runId: string, stepId: string) =>\n `${keyPrefix}step:${runId}:${stepId}`;\n const stepsIndexKey = (runId: string) => `${keyPrefix}steps:by_run:${runId}`;\n\n // Helper: Get step data from Redis key\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 = parseWithUint8Array<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 // Fetch all steps\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 = parseWithUint8Array<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 hookKeyFn = (hookId: string) => `${keyPrefix}hook:${hookId}`;\n const hooksByTokenKey = (token: string) =>\n `${keyPrefix}hooks:by_token:${token}`;\n const hooksIndexKey = (runId: string) => `${keyPrefix}hooks:by_run:${runId}`;\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(`${keyPrefix}runs:by_status:${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 = parseWithUint8Array<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 // Fetch all hooks\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 = parseWithUint8Array<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 { Mutex, Rc } 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\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 mutexes = new Map<string, { mutex: Mutex; rc: Rc }>();\n\n // Serialize work per stream key through a shared, ref-counted Mutex so\n // concurrent pub/sub notifications for the same stream are processed in\n // order. The entry is dropped once the last holder releases it.\n const withStreamMutex = async <T>(\n key: string,\n fn: () => Promise<T>,\n ): Promise<T> => {\n let entry = mutexes.get(key);\n if (!entry) {\n entry = {\n mutex: new Mutex(),\n rc: new Rc(() => {\n mutexes.delete(key);\n }),\n };\n mutexes.set(key, entry);\n }\n entry.rc.inc();\n try {\n return await entry.mutex.andThen(fn);\n } finally {\n await entry.rc.dec();\n }\n };\n\n redis.defineCommand(\"wfStreamAppend\", {\n numberOfKeys: 2,\n lua: LUA_APPEND_AND_PUBLISH,\n });\n const scripted = redis as RedisWithStreamScript;\n\n // Run IDs (`wrun_<ulid>`) never contain ':', so the first ':' after the run\n // ID always starts the stream name, even if the name contains colons itself.\n const streamKey = (runId: string, name: string) =>\n `${keyPrefix}stream:${runId}:${name}`;\n // Per-run index of stream names, mirroring the `<entity>:by_run:<runId>`\n // convention used by storage. Populated on every write/close so\n // `streams.list` can enumerate a run's streams.\n const streamsByRunKey = (runId: string) =>\n `${keyPrefix}streams:by_run:${runId}`;\n const STREAM_CHANNEL = `${keyPrefix}stream_notify`;\n const emitterKey = (runId: string, name: string) =>\n `strm:${runId}:${name}` as const;\n\n // Set up pub/sub subscriber for stream notifications\n const subscriber = redis.duplicate();\n\n // CRITICAL: Must await subscribe() to avoid race condition where PUBLISH happens before SUBSCRIBE is ready\n // This was causing workflows to hang because completion events were published but never received\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 // Ignore parse errors\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 // CRITICAL: Wait for subscription to be ready before publishing\n // Otherwise the message might be published before anyone is subscribed\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 // Await runId if it's a promise to ensure proper flushing\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 // Await runId if it's a promise to ensure proper flushing\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 // Await runId if it's a promise to ensure proper flushing\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 // Track last entry ID for ordering\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 [id, fields] of entries) {\n enqueue({\n id,\n data: Buffer.from(fields[1] as string, \"base64\"),\n eof: fields[3] === \"true\",\n });\n }\n } while (again && !cleanedUp);\n } catch {\n // Transient (connection loss): the next trigger reads again.\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 // Read all historical chunks from Redis Stream\n // XRANGE reads entries from start to end\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: StreamChunkEvent[] = [];\n for (const [id, fields] of chunks) {\n const data = Buffer.from(fields[1] as string, \"base64\");\n const eof = fields[3] === \"true\";\n parsedChunks.push({\n id,\n data,\n eof,\n });\n }\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 // From now on, process chunks in real-time\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 [id, fields] of entries) {\n if (fields[3] === \"true\") {\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(Buffer.from(fields[1] as string, \"base64\")),\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","// Storage, streams, retention and run ids, shared with @brickkit/bullmq-world\n// through the `@brickkit/redis-world/internal` export. Not a public API: it\n// changes with the package versions, which ship in lockstep.\nimport type { Storage } from \"@workflow/world\";\nimport type { Redis } from \"ioredis\";\nimport {\n createEventsStorage,\n createHooksStorage,\n createRunsStorage,\n createStepsStorage,\n} from \"./storage.js\";\n\nexport function createStorage(\n redis: Redis,\n keyPrefix: string,\n maxEventsPerRun?: number,\n): Storage {\n const config = { redis, keyPrefix, maxEventsPerRun };\n return {\n runs: createRunsStorage(config),\n events: createEventsStorage(config),\n hooks: createHooksStorage(config),\n steps: createStepsStorage(config),\n };\n}\n\nexport {\n createReaper,\n hasRetention,\n validateRetention,\n type KeepRuns,\n type RunRetention,\n} from \"./reaper.js\";\nexport { createRunId, initialMessageKey } from \"./run-id.js\";\nexport { createStreamer } from \"./streamer.js\";\nexport { createDebugLogger } from \"./internal/debug.js\";\nexport { loadOptionalEnvFile } from \"./internal/env.js\";\nexport { hasBinary, uint8ArrayReplacer } from \"./util.js\";\n"],"mappings":";;;;;;;AAGA,MAAM,YAAY;AAClB,MAAM,WAAW,KAAK,KAAK;AAC3B,MAAM,iBAAiB;AAEvB,SAAS,gBAAgB,KAAqB;CAC5C,MAAM,SAAS,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO;CACvD,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,IAAI,SAC9B,OAAQ,QAAQ,KAAM,OAAO,OAAO,MAAM;CAC5C,IAAI,MAAM;CACV,KAAK,IAAI,QAAQ,IAAI,SAAS,GAAG,SAC/B,OAAO,UAAU,OAAQ,QAAQ,OAAO,QAAQ,CAAC,IAAK,GAAG;CAC3D,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YACd,SACQ;CACR,MAAM,MAAM,SAAS;CACrB,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAK;CACnC,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,IAAI,SAAS,gBAClD,MAAM,IAAI,UACR,gDAAgD,eAAe,YACjE;CACF,MAAM,OAAO,SAAS;C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