@brickkit/redis-world 0.11.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.
@@ -0,0 +1,2452 @@
1
+ import { i as resolveConfig, t as keys } from "./keys-CqKp_Amk.js";
2
+ import { createHash } from "node:crypto";
3
+ import { EventSchema, FIRST_EVENT_SLOT, HookSchema, MessageId, StepSchema, WorkflowRunSchema, entityResolveData, eventIdToSlot, isLegacySpecVersion, mintedSpecVersion, parseQueueName, parseQueueRoute, reenqueueActiveRuns, requiresNewerWorld, slotToEventId, stripEventDataRefs, validateAttributeChanges } from "@workflow/world";
4
+ import { createAppRouteUrl, createWorkflowBaseUrl, createWorkflowUrl, globalSingleton } from "@workflow/utils";
5
+ import { encodeTime, monotonicFactory, ulid } from "ulid";
6
+ import { EntityConflictError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError } from "@workflow/errors";
7
+ import { Redis } from "ioredis";
8
+ import { EventEmitter } from "node:events";
9
+ // src/internal/debug.ts
10
+ /**
11
+ * Creates a namespaced debug logger.
12
+ * Logs to stderr to avoid corrupting CLI JSON output on stdout.
13
+ *
14
+ * Control via WORKFLOW_DEBUG environment variable:
15
+ * WORKFLOW_DEBUG=1 // Enable all
16
+ * WORKFLOW_DEBUG=redis-world // Named namespaces, comma-separated
17
+ */
18
+ function createDebugLogger(namespace) {
19
+ return (...args) => {
20
+ const debug = process.env.WORKFLOW_DEBUG;
21
+ if (!debug) return;
22
+ if (!(debug === "1" || debug === "true" || debug === "*" || debug.split(",").some((ns) => ns.trim() === namespace))) return;
23
+ const prefix = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${namespace}]`;
24
+ const message = args.map((arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)).join(" ");
25
+ process.stderr.write(`${prefix} ${message}\n`);
26
+ };
27
+ }
28
+ // src/util.ts
29
+ const debug = createDebugLogger("redis-world");
30
+ // src/internal/serialization.ts
31
+ /** Standard Date fields used across all worlds */
32
+ const DATE_FIELDS = /* @__PURE__ */ new Set([
33
+ "createdAt",
34
+ "updatedAt",
35
+ "startedAt",
36
+ "completedAt",
37
+ "retryAfter"
38
+ ]);
39
+ /**
40
+ * JSON reviver that converts ISO date strings to Date objects.
41
+ * Use with JSON.parse(json, dateReviver).
42
+ */
43
+ function dateReviver(key, value) {
44
+ if (DATE_FIELDS.has(key) && typeof value === "string") {
45
+ const date = new Date(value);
46
+ return Number.isNaN(date.getTime()) ? value : date;
47
+ }
48
+ return value;
49
+ }
50
+ /**
51
+ * JSON replacer that encodes Uint8Array as a tagged object with base64 data.
52
+ */
53
+ function uint8ArrayReplacer(_key, value) {
54
+ if (value instanceof Uint8Array) return {
55
+ __type: "Uint8Array",
56
+ data: Buffer.from(value).toString("base64")
57
+ };
58
+ return value;
59
+ }
60
+ /** The Uint8Array a tagged object (`{ __type: 'Uint8Array', data: '<base64>' }`) encodes. */
61
+ function taggedBinary(value) {
62
+ if (value && typeof value === "object") {
63
+ const obj = value;
64
+ if (obj.__type === "Uint8Array" && typeof obj.data === "string") return new Uint8Array(Buffer.from(obj.data, "base64"));
65
+ }
66
+ }
67
+ /** JSON reviver that decodes tagged Uint8Array objects and ISO date strings. */
68
+ function uint8ArrayReviver(key, value) {
69
+ return taggedBinary(value) ?? dateReviver(key, value);
70
+ }
71
+ /** The tag `uint8ArrayReviver` decodes. Absent, only dates need reviving. */
72
+ const BINARY_TAG = "\"__type\"";
73
+ /** Revive `DATE_FIELDS` in place at any depth — the same reach as
74
+ * `dateReviver` under `JSON.parse`, just without the per-node JSON interop. */
75
+ function reviveDatesDeep(value) {
76
+ if (value === null || typeof value !== "object") return value;
77
+ if (Array.isArray(value)) {
78
+ for (let i = 0; i < value.length; i++) value[i] = reviveDatesDeep(value[i]);
79
+ return value;
80
+ }
81
+ const obj = value;
82
+ for (const key in obj) {
83
+ const child = obj[key];
84
+ if (DATE_FIELDS.has(key) && typeof child === "string") {
85
+ const date = new Date(child);
86
+ if (!Number.isNaN(date.getTime())) {
87
+ obj[key] = date;
88
+ continue;
89
+ }
90
+ }
91
+ obj[key] = reviveDatesDeep(child);
92
+ }
93
+ return obj;
94
+ }
95
+ /**
96
+ * Is there a `Uint8Array` anywhere in the graph?
97
+ *
98
+ * Must stay exact: `JSON.stringify` turns a bare `Uint8Array` into
99
+ * `{"0":1,...}` without complaint, so a miss is data corruption, not a slow
100
+ * path. The walk allocates nothing, which is why it beats the replacer over
101
+ * the same nodes.
102
+ */
103
+ function hasBinary(value) {
104
+ if (value === null || typeof value !== "object") return false;
105
+ if (value instanceof Uint8Array) return true;
106
+ if (Array.isArray(value)) {
107
+ for (let i = 0; i < value.length; i++) if (hasBinary(value[i])) return true;
108
+ return false;
109
+ }
110
+ for (const key in value) if (hasBinary(value[key])) return true;
111
+ return false;
112
+ }
113
+ /** Stringify with Uint8Array support. */
114
+ function stringify(value) {
115
+ return hasBinary(value) ? JSON.stringify(value, uint8ArrayReplacer) : JSON.stringify(value);
116
+ }
117
+ /** Parse with Uint8Array and Date support. */
118
+ function parse(text) {
119
+ if (text.includes(BINARY_TAG)) return JSON.parse(text, uint8ArrayReviver);
120
+ return reviveDatesDeep(JSON.parse(text));
121
+ }
122
+ /**
123
+ * Parse a queue message: tagged Uint8Arrays only. Queue payloads are the
124
+ * runtime's own, so a field that happens to be named like a date stays a string.
125
+ */
126
+ function parseQueueMessage(text) {
127
+ return text.includes(BINARY_TAG) ? JSON.parse(text, (_key, value) => taggedBinary(value) ?? value) : JSON.parse(text);
128
+ }
129
+ // src/run-id.ts
130
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
131
+ const MAX_TIME = 2 ** 48 - 1;
132
+ const MAX_KEY_LENGTH = 1024;
133
+ function keyedRandomness(key) {
134
+ const digest = createHash("sha256").update(key).digest();
135
+ let bits = 0n;
136
+ for (let index = 0; index < 10; index++) bits = bits << 8n | BigInt(digest[index]);
137
+ let out = "";
138
+ for (let group = 15; group >= 0; group--) out += CROCKFORD[Number(bits >> BigInt(group * 5) & 31n)];
139
+ return out;
140
+ }
141
+ /**
142
+ * The run id the SDK asks the world for when a run starts. Without options it is
143
+ * a fresh ULID. With `runKey` and `runKeyTime` it is the same ULID every time, so
144
+ * starting the same run twice creates one run: the second start finds it already
145
+ * there.
146
+ *
147
+ * The id is a real ULID. Its time is `runKeyTime`, not the clock, because the SDK
148
+ * seeds a workflow's clock from the time in its run id. Pass the time the run is
149
+ * for, such as when the event it handles happened, and the same time on every
150
+ * attempt.
151
+ *
152
+ * @param options - The options given to `start()`. `runKey` is a non-empty string
153
+ * that names the run (at most 1024 characters), and `runKeyTime` is milliseconds
154
+ * since the epoch.
155
+ * @returns The id without its `wrun_` prefix, which the SDK adds.
156
+ * @throws When `runKey` is not a usable string, or comes without a valid `runKeyTime`.
157
+ */
158
+ function createRunId(options) {
159
+ const key = options?.runKey;
160
+ if (key === void 0) return ulid();
161
+ if (typeof key !== "string" || !key || key.length > MAX_KEY_LENGTH) throw new TypeError(`runKey must be a non-empty string of at most ${MAX_KEY_LENGTH} characters`);
162
+ const time = options?.runKeyTime;
163
+ if (typeof time !== "number" || !Number.isInteger(time) || time < 0 || time > MAX_TIME) throw new TypeError("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");
164
+ return encodeTime(time, 10) + keyedRandomness(key);
165
+ }
166
+ /**
167
+ * The idempotency key for the message that starts a run, which is the only
168
+ * message that carries the run's input. `start()` sends no key of its own, so a
169
+ * second start of the same run would otherwise queue a second first delivery.
170
+ *
171
+ * The key only covers a first message that is still queued or running. Once the
172
+ * run has started, the queue does not enqueue the message at all (see
173
+ * `runHasStarted` in `createWorldQueue`): the runtime runs a run's first step from the
174
+ * first message, in parallel with `run_created`, so a late second one would run
175
+ * that step's code again.
176
+ *
177
+ * @param message - The queue payload.
178
+ * @returns A key for a run's first message, and `undefined` for every other message.
179
+ */
180
+ function initialMessageKey(message) {
181
+ const { runId, runInput } = message ?? {};
182
+ return typeof runId === "string" && runInput !== void 0 ? `start:${runId}` : void 0;
183
+ }
184
+ // src/world-queue.ts
185
+ /** A response without a valid `{ timeoutSeconds }` acknowledges the message. */
186
+ function parseReschedule(text) {
187
+ try {
188
+ const seconds = JSON.parse(text)?.timeoutSeconds;
189
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0) return seconds;
190
+ } catch {}
191
+ }
192
+ /**
193
+ * The Workflow SDK `Queue` on top of a backend: message ids, the first-message
194
+ * guard, the payload transport, HTTP or in-process delivery with the `x-vqs-*`
195
+ * headers, and the handler that answers those deliveries.
196
+ */
197
+ function createWorldQueue(backend, config, options) {
198
+ const { debug } = options;
199
+ const generateMessageId = monotonicFactory();
200
+ const { httpTimeoutMs } = config;
201
+ const directHandlers = /* @__PURE__ */ new Map();
202
+ const routes = /* @__PURE__ */ new Map();
203
+ let closed = false;
204
+ const queue = async (queueName, message, opts) => {
205
+ if (closed) throw new Error("Queue is closed");
206
+ const { prefix } = parseQueueName(queueName);
207
+ const messageId = MessageId.parse(`msg_${generateMessageId()}`);
208
+ const idempotencyKey = opts?.idempotencyKey ?? initialMessageKey(message);
209
+ if (!opts?.idempotencyKey && idempotencyKey && await options.runHasStarted?.(message.runId)) {
210
+ debug("run already started, not queueing its first message again", { runId: message.runId });
211
+ return { messageId };
212
+ }
213
+ const route = routes.get(prefix);
214
+ return { messageId: await backend.enqueue({
215
+ messageId,
216
+ queueName,
217
+ message: stringify(message),
218
+ ...opts?.headers && { headers: opts.headers },
219
+ ...route && { route }
220
+ }, {
221
+ idempotencyKey,
222
+ delaySeconds: opts?.delaySeconds
223
+ }) };
224
+ };
225
+ const deliver = async (job) => {
226
+ const { prefix } = parseQueueName(job.queueName);
227
+ const headers = new Headers(job.headers);
228
+ headers.set("content-type", "application/json");
229
+ headers.set("x-vqs-queue-name", job.queueName);
230
+ headers.set("x-vqs-message-id", job.messageId);
231
+ headers.set("x-vqs-message-attempt", String(job.attempt));
232
+ headers.set("x-vqs-message-delivery-count", String(job.deliveryCount));
233
+ headers.set("x-vqs-message-created-at", new Date(job.createdAt).toISOString());
234
+ const deliveryRoute = routes.get(prefix) ?? job.route;
235
+ const directHandler = directHandlers.get(prefix);
236
+ let response;
237
+ if (directHandler) {
238
+ const localBase = createWorkflowBaseUrl("http://localhost");
239
+ response = await directHandler(new Request(deliveryRoute ? createAppRouteUrl(localBase, deliveryRoute) : createWorkflowUrl(localBase, { type: "flow" }), {
240
+ method: "POST",
241
+ headers,
242
+ body: job.message
243
+ }));
244
+ } else {
245
+ const baseUrl = config.baseUrl || process.env.WORKFLOW_BASE_URL || `http://localhost:${process.env.PORT ?? "3000"}`;
246
+ response = await fetch(deliveryRoute ? createAppRouteUrl(baseUrl, deliveryRoute) : createWorkflowUrl(baseUrl, { type: "flow" }), {
247
+ method: "POST",
248
+ headers,
249
+ body: job.message,
250
+ signal: AbortSignal.timeout(httpTimeoutMs)
251
+ });
252
+ }
253
+ const text = await response.text();
254
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
255
+ return parseReschedule(text);
256
+ };
257
+ const createQueueHandler = (queueNamePrefix, handler) => {
258
+ return async (req) => {
259
+ const queueName = req.headers.get("x-vqs-queue-name");
260
+ const messageId = req.headers.get("x-vqs-message-id");
261
+ const attemptStr = req.headers.get("x-vqs-message-attempt");
262
+ const deliveryCountStr = req.headers.get("x-vqs-message-delivery-count");
263
+ const createdAtStr = req.headers.get("x-vqs-message-created-at");
264
+ if (!queueName || !messageId || !attemptStr || !req.body) return Response.json({ error: "Missing required headers or body" }, { status: 400 });
265
+ if (!queueName.startsWith(queueNamePrefix)) return Response.json({ error: "Unhandled queue" }, { status: 400 });
266
+ const attempt = Number.parseInt(attemptStr, 10);
267
+ const deliveryCount = deliveryCountStr ? Number.parseInt(deliveryCountStr, 10) : attempt;
268
+ const createdAt = createdAtStr ? new Date(createdAtStr) : void 0;
269
+ try {
270
+ const timeoutSeconds = (await handler(parseQueueMessage(await req.text()), {
271
+ attempt,
272
+ deliveryCount,
273
+ ...createdAt && !Number.isNaN(createdAt.getTime()) && { createdAt },
274
+ queueName,
275
+ messageId
276
+ }))?.timeoutSeconds;
277
+ if (typeof timeoutSeconds === "number" && Number.isFinite(timeoutSeconds)) return Response.json({ timeoutSeconds: Math.max(0, timeoutSeconds) });
278
+ return Response.json({ ok: true });
279
+ } catch (error) {
280
+ debug("queue handler error:", error);
281
+ return Response.json({ error: String(error) }, { status: 500 });
282
+ }
283
+ };
284
+ };
285
+ return {
286
+ queue,
287
+ createQueueHandler,
288
+ getDeploymentId: async () => "redis",
289
+ registerHandler(prefix, handler) {
290
+ directHandlers.set(prefix, handler);
291
+ },
292
+ registerRoute(prefix, path) {
293
+ routes.set(prefix, parseQueueRoute(path));
294
+ },
295
+ getQueueStats: () => backend.getQueueStats(),
296
+ start: () => backend.start(deliver),
297
+ async close() {
298
+ closed = true;
299
+ await backend.close();
300
+ }
301
+ };
302
+ }
303
+ /** The delay before retrying a failed delivery: the configured curve, capped. */
304
+ function retryDelayMs(attempt, config) {
305
+ const delay = config.backoffType === "fixed" ? config.backoffDelayMs : config.backoffDelayMs * 2 ** Math.min(30, Math.max(0, attempt - 1));
306
+ return Math.min(config.maxBackoffMs, delay);
307
+ }
308
+ // src/reaper.ts
309
+ const TERMINAL = [
310
+ "completed",
311
+ "failed",
312
+ "cancelled"
313
+ ];
314
+ const DEFAULT_SWEEP_INTERVAL_MS = 6e4;
315
+ const DEFAULT_BATCH_SIZE = 200;
316
+ const UNLINK_CHUNK = 500;
317
+ function validateRetention(retention) {
318
+ if (!retention) return;
319
+ for (const status of TERMINAL) {
320
+ const keep = retention[status];
321
+ if (!keep) continue;
322
+ for (const field of ["age", "count"]) {
323
+ const value = keep[field];
324
+ if (value !== void 0 && (!Number.isInteger(value) || value < 0)) throw new TypeError(`retention.${status}.${field} must be a non-negative integer, received ${String(value)}`);
325
+ }
326
+ }
327
+ for (const field of ["sweepIntervalMs", "batchSize"]) {
328
+ const value = retention[field];
329
+ if (value !== void 0 && (!Number.isInteger(value) || value < 1)) throw new TypeError(`retention.${field} must be a positive integer, received ${String(value)}`);
330
+ }
331
+ }
332
+ function hasRetention(retention) {
333
+ return !!retention && TERMINAL.some((status) => retention[status] !== void 0);
334
+ }
335
+ /**
336
+ * Deletes finished runs once they pass their retention. Safe to run on every
337
+ * worker: one lock per interval picks a single sweeper, and deleting a run is
338
+ * idempotent anyway. A run's own key and index entries go last, in one
339
+ * transaction, so a crash part-way leaves the run listed and the next sweep
340
+ * finishes the job.
341
+ */
342
+ function createReaper(options) {
343
+ const { redis, keyPrefix, retention } = options;
344
+ const intervalMs = retention.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
345
+ const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;
346
+ const k = keys(keyPrefix);
347
+ const byStatusKey = k.runsByStatusKey;
348
+ let timer;
349
+ let running = Promise.resolve();
350
+ /** Runs past retention, oldest first: too old, or beyond the newest `count`. */
351
+ async function expired(status) {
352
+ const keep = retention[status];
353
+ if (!keep) return [];
354
+ const ids = /* @__PURE__ */ new Set();
355
+ if (keep.age !== void 0) {
356
+ const cutoff = Date.now() - keep.age * 1e3;
357
+ for (const id of await redis.zrangebyscore(byStatusKey(status), "-inf", cutoff, "LIMIT", 0, batchSize)) ids.add(id);
358
+ }
359
+ if (keep.count !== void 0) {
360
+ const stop = -(keep.count + 1);
361
+ for (const id of await redis.zrange(byStatusKey(status), "0", String(stop))) {
362
+ if (ids.size >= batchSize) break;
363
+ ids.add(id);
364
+ }
365
+ }
366
+ return [...ids].slice(0, batchSize);
367
+ }
368
+ async function unlink(keys) {
369
+ for (let i = 0; i < keys.length; i += UNLINK_CHUNK) await redis.unlink(...keys.slice(i, i + UNLINK_CHUNK));
370
+ }
371
+ async function scan(pattern) {
372
+ const found = [];
373
+ let cursor = "0";
374
+ do {
375
+ const [next, batch] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 1e3);
376
+ cursor = next;
377
+ found.push(...batch);
378
+ } while (cursor !== "0");
379
+ return found;
380
+ }
381
+ /** Delete one run if it is still finished. Returns whether it was deleted. */
382
+ async function deleteRun(runId, listedAs) {
383
+ const metaKey = k.runMetaKey(runId);
384
+ const meta = await redis.get(metaKey);
385
+ const status = meta?.split("|")[0];
386
+ if (!status || !TERMINAL.includes(status)) {
387
+ if (!meta) await redis.zrem(byStatusKey(listedAs), runId);
388
+ return false;
389
+ }
390
+ const runKey = k.runKey(runId);
391
+ const runJson = await redis.get(runKey);
392
+ const workflowName = runJson ? JSON.parse(runJson).workflowName : void 0;
393
+ const eventsKey = k.eventsKey(runId);
394
+ const correlationIds = /* @__PURE__ */ new Set();
395
+ let hasResume = false;
396
+ for (const raw of await redis.hvals(eventsKey)) try {
397
+ const event = JSON.parse(raw);
398
+ if (event.correlationId) correlationIds.add(event.correlationId);
399
+ if (event.eventType === "hook_received") hasResume = true;
400
+ } catch {}
401
+ const stepIds = await redis.zrange(k.stepsIndexKey(runId), "0", "-1");
402
+ const hookIds = await redis.zrange(k.hooksIndexKey(runId), "0", "-1");
403
+ const streamNames = await redis.smembers(k.streamsByRunKey(runId));
404
+ const keys = k.ownedByRun(runId, {
405
+ correlationIds,
406
+ stepIds,
407
+ hookIds,
408
+ streamNames
409
+ });
410
+ if (hasResume) keys.push(...await scan(k.resumeClaimKey(runId, "*")));
411
+ await unlink(keys);
412
+ const tx = redis.multi().zrem(k.runsIndexKey(), runId).zrem(byStatusKey(status), runId).unlink(metaKey, runKey);
413
+ if (workflowName) tx.zrem(k.runsByNameKey(workflowName), runId);
414
+ await tx.exec();
415
+ return true;
416
+ }
417
+ async function sweep() {
418
+ if (await redis.set(k.reaperLockKey, "1", "PX", Math.max(1e3, Math.floor(intervalMs / 2)), "NX") !== "OK") return 0;
419
+ let deleted = 0;
420
+ for (const status of TERMINAL) for (const runId of await expired(status)) try {
421
+ if (await deleteRun(runId, status)) deleted++;
422
+ } catch (err) {
423
+ console.warn(`Retention: could not delete run ${runId}:`, err);
424
+ }
425
+ return deleted;
426
+ }
427
+ return {
428
+ sweep,
429
+ start() {
430
+ if (timer) return;
431
+ const tick = () => {
432
+ running = sweep().catch((err) => console.warn("Retention sweep failed:", err));
433
+ };
434
+ timer = setInterval(tick, intervalMs);
435
+ timer.unref();
436
+ },
437
+ async stop() {
438
+ if (timer) clearInterval(timer);
439
+ timer = void 0;
440
+ await running;
441
+ }
442
+ };
443
+ }
444
+ // src/internal/util.ts
445
+ function compact(obj) {
446
+ const value = {};
447
+ for (const key in obj) if (obj[key] !== null) value[key] = obj[key];
448
+ else value[key] = void 0;
449
+ return value;
450
+ }
451
+ // src/storage.ts
452
+ /** Per-run event ceiling reported to core, mirroring the Vercel World. */
453
+ const DEFAULT_MAX_EVENTS_PER_RUN = 25e3;
454
+ /** Resolve the per-run event ceiling surfaced as `EventResult.maxEvents`:
455
+ * explicit config, then `WORKFLOW_MAX_EVENTS`, then the default. A
456
+ * non-positive configured value throws rather than being ignored. */
457
+ function resolveMaxEventsPerRun(configured) {
458
+ if (configured !== void 0) {
459
+ if (!Number.isInteger(configured) || configured <= 0) throw new TypeError(`maxEventsPerRun must be a positive integer, received ${String(configured)}`);
460
+ return configured;
461
+ }
462
+ const raw = process.env.WORKFLOW_MAX_EVENTS;
463
+ const parsed = raw !== void 0 ? Number(raw) : NaN;
464
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_EVENTS_PER_RUN;
465
+ }
466
+ /** Events that mutate the run, so validation needs its full body. Everything
467
+ * else only reads status/specVersion and is served from the run meta key. */
468
+ const RUN_LIFECYCLE_EVENT_TYPES = /* @__PURE__ */ new Set([
469
+ "run_started",
470
+ "run_completed",
471
+ "run_failed",
472
+ "run_cancelled"
473
+ ]);
474
+ /** Sentinel from the event scripts when a creation-dedup check rejects. */
475
+ const LUA_DUPLICATE_CREATION = -8;
476
+ /**
477
+ * Stand-in for the event id inside the event JSON the caller hands to a script.
478
+ * The id is a log position (`evnt_` + the 1-based slot), and a position may only
479
+ * be chosen at the commit (see `LUA_APPEND_EVENT`), so the script writes it into
480
+ * the JSON itself. `serializeEvent` always emits `eventId` as the first key, so
481
+ * the first match is ours whatever the payload holds. A constant, not a random
482
+ * value: two bundled copies of this module can share one connection's scripts.
483
+ */
484
+ const EVENT_ID_PLACEHOLDER = "__brick_event_id__";
485
+ /**
486
+ * Lua helper shared by every script that appends to a run's event log.
487
+ *
488
+ * A run's events live in one hash, `eventId -> JSON`. The log is dense and
489
+ * 1-based, and a script runs atomically, so the next slot is the hash length
490
+ * plus one and no other writer can interleave between reading it and writing the
491
+ * event. That is the whole race story: the slot is chosen at the commit, in the
492
+ * same operation that appends, and a writer that is behind simply lands on the
493
+ * next free slot (the caller reports what it skipped).
494
+ *
495
+ * `appendEvent(eventsKey, correlationKey, json)` returns the new event id.
496
+ * `correlationKey` may be nil. The id is written into `json` in place of the
497
+ * placeholder, so what is stored is exactly what the reader parses.
498
+ */
499
+ const LUA_APPEND_EVENT = `
500
+ local function appendEvent(eventsKey, correlationKey, json)
501
+ local slot = redis.call('HLEN', eventsKey) + 1
502
+ local digits = string.format('%d', slot)
503
+ local eventId = 'evnt_' .. string.rep('0', 26 - #digits) .. digits
504
+ local from, to = string.find(json, '${EVENT_ID_PLACEHOLDER}', 1, true)
505
+ json = string.sub(json, 1, from - 1) .. eventId .. string.sub(json, to + 1)
506
+ redis.call('HSET', eventsKey, eventId, json)
507
+ if correlationKey then
508
+ redis.call('ZADD', correlationKey, slot, eventId)
509
+ end
510
+ return eventId
511
+ end
512
+
513
+ -- A run's status from its meta key ('<status>|<specVersion>'), or false when absent.
514
+ local function runStatus(metaKey)
515
+ local meta = redis.call('GET', metaKey)
516
+ if not meta then
517
+ return false
518
+ end
519
+ return string.match(meta, '^([^|]*)')
520
+ end
521
+
522
+ local function isTerminal(status)
523
+ return status == 'completed' or status == 'failed' or status == 'cancelled'
524
+ end
525
+ `;
526
+ /**
527
+ * Filter hook data based on resolveData parameter
528
+ */
529
+ function filterHookData(hook, resolveData) {
530
+ if (resolveData === "none" && "metadata" in hook) {
531
+ const { metadata: _, ...rest } = hook;
532
+ return {
533
+ metadata: void 0,
534
+ ...rest
535
+ };
536
+ }
537
+ return hook;
538
+ }
539
+ function filterStepData(step, resolveData) {
540
+ if (resolveData === "none") {
541
+ const { input: _, output: __, ...rest } = step;
542
+ return {
543
+ input: void 0,
544
+ output: void 0,
545
+ ...rest
546
+ };
547
+ }
548
+ return step;
549
+ }
550
+ function filterRunData(run, resolveData) {
551
+ if (resolveData === "none") {
552
+ const { input: _, output: __, ...rest } = run;
553
+ return {
554
+ input: void 0,
555
+ output: void 0,
556
+ ...rest
557
+ };
558
+ }
559
+ return run;
560
+ }
561
+ /**
562
+ * Read up to `want` members of one or more sorted-set indexes, in score order,
563
+ * resuming after `cursor`. With several indexes the members are merged into one
564
+ * ordering, which is how a listing across statuses avoids scanning an index of
565
+ * every run there has ever been.
566
+ *
567
+ * A cursor is the last member's `<score>|<id>`, not its rank: a rank means
568
+ * nothing once that member has left the index (a run that changed status, a
569
+ * hook that was disposed), and paging would fail halfway through a listing. A
570
+ * position by score and id stays valid wherever the member went. Members that
571
+ * share a score are ordered by id, as Redis orders them.
572
+ */
573
+ async function pageIndex(redis, indexKeys, cursor, want, order = "desc") {
574
+ let after;
575
+ if (cursor) {
576
+ const sep = cursor.indexOf("|");
577
+ const score = sep > 0 ? Number(cursor.slice(0, sep)) : NaN;
578
+ if (Number.isNaN(score)) throw new WorkflowWorldError(`Invalid pagination cursor "${cursor}"`, { status: 400 });
579
+ after = {
580
+ score,
581
+ id: cursor.slice(sep + 1)
582
+ };
583
+ }
584
+ const bound = after ? String(after.score) : order === "desc" ? "+inf" : "-inf";
585
+ const readOne = async (indexKey) => {
586
+ const out = [];
587
+ const batch = Math.max(want, 50);
588
+ let offset = 0;
589
+ while (out.length < want) {
590
+ const raw = order === "desc" ? await redis.zrevrangebyscore(indexKey, bound, "-inf", "WITHSCORES", "LIMIT", offset, batch) : await redis.zrangebyscore(indexKey, bound, "+inf", "WITHSCORES", "LIMIT", offset, batch);
591
+ for (let i = 0; i < raw.length && out.length < want; i += 2) {
592
+ const id = raw[i];
593
+ const score = Number(raw[i + 1]);
594
+ if (after && score === after.score && (order === "desc" ? id >= after.id : id <= after.id)) continue;
595
+ out.push({
596
+ id,
597
+ score,
598
+ cursor: `${raw[i + 1]}|${id}`
599
+ });
600
+ }
601
+ offset += raw.length / 2;
602
+ if (raw.length / 2 < batch) break;
603
+ }
604
+ return out;
605
+ };
606
+ const keys = Array.isArray(indexKeys) ? indexKeys : [indexKeys];
607
+ if (keys.length === 1) return readOne(keys[0]);
608
+ const merged = (await Promise.all(keys.map(readOne))).flat();
609
+ const direction = order === "desc" ? -1 : 1;
610
+ merged.sort((x, y) => direction * (x.score - y.score || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0)));
611
+ return merged.slice(0, want);
612
+ }
613
+ /**
614
+ * Atomically create a run entity with all its indexes AND its creation
615
+ * event. SETNX arbitrates duplicates: when the run already exists, NO
616
+ * index, meta, or event write happens (a replayed run_created must not
617
+ * reset index scores, re-insert a terminal run into the pending status
618
+ * index, or append a second creation event).
619
+ *
620
+ * KEYS[1] = run key
621
+ * KEYS[2] = runs index key
622
+ * KEYS[3] = runs by name key
623
+ * KEYS[4] = runs by status key (pending)
624
+ * KEYS[5] = run meta key
625
+ * KEYS[6] = events key (the run's log)
626
+ * KEYS[7] = run attributes key
627
+ * ARGV[1] = run JSON
628
+ * ARGV[2] = run ID
629
+ * ARGV[3] = score (timestamp)
630
+ * ARGV[4] = run meta value (`<status>|<specVersion>`)
631
+ * ARGV[5] = event JSON (event id left as the placeholder)
632
+ * ARGV[6..] = attribute key, value pairs to seed
633
+ * Returns: [1, eventId] when created, [0, runJson] on replay.
634
+ */
635
+ const LUA_CREATE_RUN_WITH_EVENT = `${LUA_APPEND_EVENT}
636
+ local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])
637
+ if wasCreated == 0 then
638
+ return {0, redis.call('GET', KEYS[1])}
639
+ end
640
+ local score = tonumber(ARGV[3])
641
+ redis.call('ZADD', KEYS[2], score, ARGV[2])
642
+ redis.call('ZADD', KEYS[3], score, ARGV[2])
643
+ redis.call('ZADD', KEYS[4], score, ARGV[2])
644
+ redis.call('SET', KEYS[5], ARGV[4])
645
+ for i = 6, #ARGV, 2 do
646
+ redis.call('HSET', KEYS[7], ARGV[i], ARGV[i + 1])
647
+ end
648
+ return {1, appendEvent(KEYS[6], nil, ARGV[5])}
649
+ `;
650
+ /**
651
+ * Move a run to a new status, release its hooks when it finishes, and append the
652
+ * lifecycle event, all in one execution. They are one script because a crash
653
+ * between them would leave a terminal run with no terminal event (every retry is
654
+ * then refused as terminal) or a started run with no `run_started` (the redelivery
655
+ * takes the resume path and appends nothing).
656
+ *
657
+ * KEYS[1] = run key
658
+ * KEYS[2] = old status index key
659
+ * KEYS[3] = new status index key
660
+ * KEYS[4] = run meta key
661
+ * KEYS[5] = events key
662
+ * KEYS[6] = hooks index key
663
+ * KEYS[7] = hooks token-map key
664
+ * ARGV[1] = updated run JSON
665
+ * ARGV[2] = run ID
666
+ * ARGV[3] = score (timestamp)
667
+ * ARGV[4] = run meta value (`<status>|<specVersion>`)
668
+ * ARGV[5] = the status the caller read the run in
669
+ * ARGV[6] = event JSON
670
+ * ARGV[7] = "1" to release the run's hooks (a terminal transition)
671
+ * ARGV[8] = hook key prefix
672
+ * ARGV[9] = hooks-by-token key prefix
673
+ * Returns: [1, eventId] on success, [0, ''] if the run is absent, [-2, status] if
674
+ * the run is no longer in the status the caller read (another writer
675
+ * moved it first; nothing is written)
676
+ */
677
+ const LUA_TRANSITION_RUN = `${LUA_APPEND_EVENT}
678
+ if redis.call('EXISTS', KEYS[1]) == 0 then
679
+ return {0, ''}
680
+ end
681
+
682
+ local current = runStatus(KEYS[4])
683
+ if current and current ~= ARGV[5] then
684
+ return {-2, current}
685
+ end
686
+
687
+ redis.call('SET', KEYS[1], ARGV[1])
688
+ redis.call('SET', KEYS[4], ARGV[4])
689
+ redis.call('ZREM', KEYS[2], ARGV[2])
690
+ redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])
691
+
692
+ if ARGV[7] == '1' then
693
+ local pairsFlat = redis.call('HGETALL', KEYS[7])
694
+ for i = 1, #pairsFlat, 2 do
695
+ local hookId = pairsFlat[i]
696
+ local tokenKey = ARGV[9] .. pairsFlat[i + 1]
697
+ redis.call('DEL', ARGV[8] .. hookId)
698
+ -- Only a token this hook still owns: a stale entry must not wipe a claim
699
+ -- another run has taken since.
700
+ if redis.call('GET', tokenKey) == hookId then
701
+ redis.call('DEL', tokenKey)
702
+ end
703
+ end
704
+ redis.call('DEL', KEYS[7])
705
+ redis.call('DEL', KEYS[6])
706
+ end
707
+
708
+ return {1, appendEvent(KEYS[5], nil, ARGV[6])}
709
+ `;
710
+ /**
711
+ * Atomically create a step entity with its index AND its creation event.
712
+ * SETNX arbitrates duplicates: a replayed step_created writes nothing. A step is
713
+ * never created on a finished run.
714
+ *
715
+ * KEYS[1] = step key
716
+ * KEYS[2] = steps index key
717
+ * KEYS[3] = events key
718
+ * KEYS[4] = events by correlation key
719
+ * KEYS[5] = step status key (see `LUA_STORE_EVENT`)
720
+ * KEYS[6] = run meta key
721
+ * ARGV[1] = step JSON
722
+ * ARGV[2] = step ID (correlationId)
723
+ * ARGV[3] = score (timestamp)
724
+ * ARGV[4] = event JSON
725
+ * ARGV[5] = step status value (`<status>|<attempt>`)
726
+ * Returns: [1, eventId] when created, [0, stepJson] on replay, [-6, status] when
727
+ * the run is terminal
728
+ */
729
+ const LUA_CREATE_STEP_WITH_EVENT = `${LUA_APPEND_EVENT}
730
+ local status = runStatus(KEYS[6])
731
+ if status and isTerminal(status) then
732
+ return {-6, status}
733
+ end
734
+ local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])
735
+ if wasCreated == 0 then
736
+ return {0, redis.call('GET', KEYS[1])}
737
+ end
738
+ redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])
739
+ redis.call('SET', KEYS[5], ARGV[5])
740
+ return {1, appendEvent(KEYS[3], KEYS[4], ARGV[4])}
741
+ `;
742
+ /**
743
+ * Lazy step start: a `step_started` that carries the step's input also creates
744
+ * the step. The step entity (already running, attempt 1), the synthetic
745
+ * `step_created` and the `step_started` land together, so replay still sees the
746
+ * creation, and exactly one concurrent caller wins the SETNX and runs the body.
747
+ *
748
+ * KEYS[1] = step key
749
+ * KEYS[2] = steps index key
750
+ * KEYS[3] = events key
751
+ * KEYS[4] = events by correlation key
752
+ * KEYS[5] = step status key (see `LUA_STORE_EVENT`)
753
+ * KEYS[6] = run meta key
754
+ * ARGV[1] = step JSON (running)
755
+ * ARGV[2] = step ID (correlationId)
756
+ * ARGV[3] = score (timestamp)
757
+ * ARGV[4] = step_created event JSON
758
+ * ARGV[5] = step_started event JSON
759
+ * ARGV[6] = step status value (`running|1`)
760
+ * Returns: [1, createdEventId, startedEventId] when created, [0, stepJson] when
761
+ * the step already exists (the caller lost the claim), [-6, status]
762
+ * when the run is terminal
763
+ */
764
+ const LUA_CREATE_STEP_STARTED = `${LUA_APPEND_EVENT}
765
+ local status = runStatus(KEYS[6])
766
+ if status and isTerminal(status) then
767
+ return {-6, status}
768
+ end
769
+ local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])
770
+ if wasCreated == 0 then
771
+ return {0, redis.call('GET', KEYS[1])}
772
+ end
773
+ redis.call('ZADD', KEYS[2], tonumber(ARGV[3]), ARGV[2])
774
+ redis.call('SET', KEYS[5], ARGV[6])
775
+ local createdId = appendEvent(KEYS[3], KEYS[4], ARGV[4])
776
+ local startedId = appendEvent(KEYS[3], KEYS[4], ARGV[5])
777
+ return {1, createdId, startedId}
778
+ `;
779
+ /**
780
+ * Atomically claim a hook token and create the hook entity, its indexes,
781
+ * token-map entry, AND its creation event. The by-token key is the claim
782
+ * arbiter (SETNX):
783
+ * - A DIFFERENT hookId already owning the token -> cross-run conflict; the
784
+ * rightful owner's token mapping is left untouched. If that owner's hook no
785
+ * longer exists (a crash during cleanup left the token behind), the token is
786
+ * free and is taken over here, in the same execution, so a concurrent claim
787
+ * can never be wiped.
788
+ * - The SAME hookId owning the token with the entity present -> duplicate.
789
+ * Entity + event are written in the same atomic script, so a crash can
790
+ * never leave a hook entity without its hook_created event (or vice versa). A
791
+ * hook is never created on a finished run, which would hold its token forever.
792
+ *
793
+ * KEYS[1] = hook key
794
+ * KEYS[2] = hooks by token key
795
+ * KEYS[3] = hooks index key
796
+ * KEYS[4] = hooks token-map key (hash of hookId -> token, per run)
797
+ * KEYS[5] = events key
798
+ * KEYS[6] = events by correlation key
799
+ * KEYS[7] = run meta key
800
+ * ARGV[1] = hook JSON
801
+ * ARGV[2] = hook ID (correlationId)
802
+ * ARGV[3] = score (timestamp)
803
+ * ARGV[4] = the token, recorded in the token map so terminal-run cleanup can
804
+ * drop token lookups without reading every hook body
805
+ * ARGV[5] = event JSON
806
+ * ARGV[6] = hook key prefix
807
+ * Returns: [2, owningHookId] on token conflict,
808
+ * [0, hookJson] when the hook already exists, or has existed (created
809
+ * and since disposed),
810
+ * [1, eventId] on success,
811
+ * [-6, status] when the run is terminal
812
+ */
813
+ const LUA_CREATE_HOOK_WITH_EVENT = `${LUA_APPEND_EVENT}
814
+ local status = runStatus(KEYS[7])
815
+ if status and isTerminal(status) then
816
+ return {-6, status}
817
+ end
818
+ -- Disposal removes the hook and its token, so a stale writer that loaded the log
819
+ -- before the hook existed would otherwise create it again behind its disposal.
820
+ -- The creation event is the record that it already happened.
821
+ if redis.call('ZCARD', KEYS[6]) > 0 then
822
+ return {0, ''}
823
+ end
824
+ local claimed = redis.call('SETNX', KEYS[2], ARGV[2])
825
+ if claimed == 0 then
826
+ local owner = redis.call('GET', KEYS[2])
827
+ if owner ~= ARGV[2] then
828
+ if redis.call('EXISTS', ARGV[6] .. owner) == 1 then
829
+ return {2, owner}
830
+ end
831
+ redis.call('SET', KEYS[2], ARGV[2])
832
+ end
833
+ end
834
+ local wasCreated = redis.call('SETNX', KEYS[1], ARGV[1])
835
+ if wasCreated == 0 then
836
+ return {0, redis.call('GET', KEYS[1])}
837
+ end
838
+ redis.call('ZADD', KEYS[3], tonumber(ARGV[3]), ARGV[2])
839
+ redis.call('HSET', KEYS[4], ARGV[2], ARGV[4])
840
+ return {1, appendEvent(KEYS[5], KEYS[6], ARGV[5])}
841
+ `;
842
+ /**
843
+ * Atomically dispose a hook: delete the hook key, its token lookup (only while
844
+ * it still points at this hook), its index entry and its token-map entry, and
845
+ * append `hook_disposed`. One script, because a crash between the delete and the
846
+ * append would lose the event, and a delete racing a `hook_received` must not
847
+ * leave the received event behind the disposal in the log.
848
+ *
849
+ * KEYS[1] = hook key
850
+ * KEYS[2] = hooks by token key
851
+ * KEYS[3] = hooks index key
852
+ * KEYS[4] = hooks token-map key
853
+ * KEYS[5] = events key
854
+ * KEYS[6] = events by correlation key
855
+ * ARGV[1] = hook ID (correlationId)
856
+ * ARGV[2] = event JSON
857
+ * Returns: [1, eventId] if disposed, [0, ''] if the hook was not found
858
+ */
859
+ const LUA_DISPOSE_HOOK = `${LUA_APPEND_EVENT}
860
+ if redis.call('DEL', KEYS[1]) == 0 then
861
+ return {0, ''}
862
+ end
863
+ if redis.call('GET', KEYS[2]) == ARGV[1] then
864
+ redis.call('DEL', KEYS[2])
865
+ end
866
+ redis.call('ZREM', KEYS[3], ARGV[1])
867
+ redis.call('HDEL', KEYS[4], ARGV[1])
868
+ return {1, appendEvent(KEYS[5], KEYS[6], ARGV[2])}
869
+ `;
870
+ /**
871
+ * Atomically append an event to the run's log and its correlation index,
872
+ * optionally writing an entity first so the mutation and its event commit
873
+ * together.
874
+ *
875
+ * KEYS[1] = events key
876
+ * KEYS[2] = events by correlation key (or unused placeholder)
877
+ * KEYS[3] = entity key (or unused placeholder)
878
+ * KEYS[4] = hook resume claim key (or unused placeholder)
879
+ * KEYS[5] = step status key (or unused placeholder)
880
+ * KEYS[6] = run meta key (or unused placeholder)
881
+ * KEYS[7] = hook key (or unused placeholder)
882
+ * ARGV[1] = event JSON
883
+ * ARGV[2] = has correlation ("1" or "0")
884
+ * ARGV[3] = creation dedup: "1" rejects when the correlation index already holds
885
+ * an event (a wait or hook conflict recorded once), "2" rejects when it
886
+ * already holds two (a wait completed once)
887
+ * ARGV[4] = entity JSON to write to KEYS[3] ('' to write nothing)
888
+ * ARGV[5] = resume claim payload ('' when the event is not a lazy hook resume)
889
+ * ARGV[6] = the step's new status ('' when the event writes no step)
890
+ * ARGV[7] = the attempt the caller read ('' to skip the check)
891
+ * ARGV[8] = the step's new attempt ('' to keep the current one)
892
+ * ARGV[9] = "1" to refuse when the run is terminal
893
+ * ARGV[10] = "1" to refuse when the hook (KEYS[7]) does not exist
894
+ *
895
+ * A lazy hook resume is claimed per (run, resumeId): the first writer appends and
896
+ * records `<eventId>|<claim payload>`, a later one appends nothing and gets the
897
+ * recorded claim back, so both writers converge on one event.
898
+ *
899
+ * A step write is a transition out of the state the caller read, so it is checked
900
+ * where the state lives: a terminal step takes no further write, and a write that
901
+ * read an older attempt than the step now has lost to another writer. Without
902
+ * this two deliveries could both record an outcome, and the log would hold both.
903
+ * The attempt counter is kept here, not taken from the caller's possibly stale
904
+ * copy of the step, so it only moves forward.
905
+ *
906
+ * The run and hook guards live here because the checks the caller makes before
907
+ * calling are stale by the time the event is appended: a `hook_received` must not
908
+ * land behind the hook's disposal or the run's end, which no replay can consume.
909
+ *
910
+ * Returns: [1, eventId] on success, [-8, ''] when creation dedup rejects,
911
+ * [-7, ''] when completion dedup rejects, [3, claim] when a resume claim
912
+ * already exists, [-3, status] when the step is already terminal,
913
+ * [-4, attempt] when the step has moved past the attempt the caller
914
+ * read, [-6, status] when the run is terminal, [-5, ''] when the hook
915
+ * is gone
916
+ */
917
+ const LUA_STORE_EVENT = `${LUA_APPEND_EVENT}
918
+ if ARGV[5] ~= '' then
919
+ local claim = redis.call('GET', KEYS[4])
920
+ if claim then
921
+ return {3, claim}
922
+ end
923
+ end
924
+
925
+ if ARGV[10] == '1' and redis.call('EXISTS', KEYS[7]) == 0 then
926
+ return {-5, ''}
927
+ end
928
+
929
+ if ARGV[9] == '1' then
930
+ local status = runStatus(KEYS[6])
931
+ if status and isTerminal(status) then
932
+ return {-6, status}
933
+ end
934
+ end
935
+
936
+ if ARGV[3] == '1' and redis.call('ZCARD', KEYS[2]) > 0 then
937
+ return {${LUA_DUPLICATE_CREATION}, ''}
938
+ end
939
+ if ARGV[3] == '2' and redis.call('ZCARD', KEYS[2]) > 1 then
940
+ return {-7, ''}
941
+ end
942
+
943
+ if ARGV[6] ~= '' then
944
+ local current = redis.call('GET', KEYS[5])
945
+ -- No key (a step written before it existed): the caller's read is the best
946
+ -- attempt there is. Assuming 0 would make every later start look stale.
947
+ local attempt = '0'
948
+ if ARGV[7] ~= '' then
949
+ attempt = ARGV[7]
950
+ end
951
+ if current then
952
+ local status
953
+ status, attempt = string.match(current, '^([^|]*)|?(.*)$')
954
+ if status == 'completed' or status == 'failed' or status == 'cancelled' then
955
+ return {-3, status}
956
+ end
957
+ if ARGV[7] ~= '' and attempt ~= ARGV[7] then
958
+ return {-4, attempt}
959
+ end
960
+ end
961
+ if ARGV[8] ~= '' then
962
+ attempt = ARGV[8]
963
+ end
964
+ redis.call('SET', KEYS[5], ARGV[6] .. '|' .. attempt)
965
+ end
966
+
967
+ if ARGV[4] ~= '' then
968
+ redis.call('SET', KEYS[3], ARGV[4])
969
+ end
970
+
971
+ local correlationKey = nil
972
+ if ARGV[2] == '1' then
973
+ correlationKey = KEYS[2]
974
+ end
975
+ local eventId = appendEvent(KEYS[1], correlationKey, ARGV[1])
976
+ if ARGV[5] ~= '' then
977
+ redis.call('SET', KEYS[4], eventId .. '|' .. ARGV[5])
978
+ end
979
+ return {1, eventId}
980
+ `;
981
+ /**
982
+ * Atomically apply a batch of attribute changes and append the `attr_set` event.
983
+ * Attributes live in a hash of their own, not in the run JSON, so two writers
984
+ * changing different keys never overwrite each other.
985
+ *
986
+ * KEYS[1] = run attributes key
987
+ * KEYS[2] = events key
988
+ * KEYS[3] = events by correlation key (or unused placeholder)
989
+ * KEYS[4] = run meta key
990
+ * ARGV[1] = event JSON
991
+ * ARGV[2] = has correlation ("1" or "0")
992
+ * ARGV[3] = "1" to refuse a repeat for this correlation id (a replayed write)
993
+ * ARGV[4..] = triples: attribute key, value, op ("set" or "del")
994
+ * Returns: [1, eventId], [-6, status] when the run is terminal, [-8, ''] when
995
+ * this correlation id already set attributes
996
+ */
997
+ const LUA_SET_ATTRIBUTES = `${LUA_APPEND_EVENT}
998
+ local status = runStatus(KEYS[4])
999
+ if status and isTerminal(status) then
1000
+ return {-6, status}
1001
+ end
1002
+ if ARGV[3] == '1' and ARGV[2] == '1' and redis.call('ZCARD', KEYS[3]) > 0 then
1003
+ return {${LUA_DUPLICATE_CREATION}, ''}
1004
+ end
1005
+ for i = 4, #ARGV, 3 do
1006
+ if ARGV[i + 2] == 'del' then
1007
+ redis.call('HDEL', KEYS[1], ARGV[i])
1008
+ else
1009
+ redis.call('HSET', KEYS[1], ARGV[i], ARGV[i + 1])
1010
+ end
1011
+ end
1012
+ local correlationKey = nil
1013
+ if ARGV[2] == '1' then
1014
+ correlationKey = KEYS[3]
1015
+ end
1016
+ return {1, appendEvent(KEYS[2], correlationKey, ARGV[1])}
1017
+ `;
1018
+ /** Registered via `defineCommand` so ioredis dispatches with `EVALSHA` rather
1019
+ * than shipping the script body every call. `LUA_STORE_EVENT` is ~1 KB and
1020
+ * runs once per workflow event. */
1021
+ const SCRIPTS = {
1022
+ wfCreateRunWithEvent: {
1023
+ numberOfKeys: 7,
1024
+ lua: LUA_CREATE_RUN_WITH_EVENT
1025
+ },
1026
+ wfSetAttributes: {
1027
+ numberOfKeys: 4,
1028
+ lua: LUA_SET_ATTRIBUTES
1029
+ },
1030
+ wfTransitionRun: {
1031
+ numberOfKeys: 7,
1032
+ lua: LUA_TRANSITION_RUN
1033
+ },
1034
+ wfCreateStepWithEvent: {
1035
+ numberOfKeys: 6,
1036
+ lua: LUA_CREATE_STEP_WITH_EVENT
1037
+ },
1038
+ wfCreateStepStarted: {
1039
+ numberOfKeys: 6,
1040
+ lua: LUA_CREATE_STEP_STARTED
1041
+ },
1042
+ wfCreateHookWithEvent: {
1043
+ numberOfKeys: 7,
1044
+ lua: LUA_CREATE_HOOK_WITH_EVENT
1045
+ },
1046
+ wfDisposeHook: {
1047
+ numberOfKeys: 6,
1048
+ lua: LUA_DISPOSE_HOOK
1049
+ },
1050
+ wfStoreEvent: {
1051
+ numberOfKeys: 7,
1052
+ lua: LUA_STORE_EVENT
1053
+ }
1054
+ };
1055
+ /** Clients that already have the scripts attached; every storage factory
1056
+ * calls this with the same shared connection, so it must be idempotent. */
1057
+ const scriptState = globalSingleton("@brickkit/redis-world//scripts", 1, () => ({ clients: /* @__PURE__ */ new WeakSet() }));
1058
+ function withScripts(redis) {
1059
+ if (!scriptState.clients.has(redis)) {
1060
+ for (const [name, def] of Object.entries(SCRIPTS)) redis.defineCommand(name, {
1061
+ numberOfKeys: def.numberOfKeys,
1062
+ lua: def.lua
1063
+ });
1064
+ scriptState.clients.add(redis);
1065
+ }
1066
+ return redis;
1067
+ }
1068
+ /** Compact `<status>|<specVersion>` marker beside the run blob, so validation
1069
+ * reads those two fields without transferring the run's input/output. */
1070
+ function runMetaValue(status, specVersion) {
1071
+ return `${status}|${specVersion ?? ""}`;
1072
+ }
1073
+ function parseRunMeta(value) {
1074
+ const sep = value.indexOf("|");
1075
+ if (sep === -1) return { status: value };
1076
+ const version = value.slice(sep + 1);
1077
+ return {
1078
+ status: value.slice(0, sep),
1079
+ specVersion: version === "" ? void 0 : Number(version)
1080
+ };
1081
+ }
1082
+ /**
1083
+ * Create storage for workflow runs using Redis hashes and sorted sets
1084
+ */
1085
+ function createRunsStorage(config) {
1086
+ const { redis, keyPrefix } = config;
1087
+ const { runKey, runAttributesKey, runsIndexKey, runsByNameKey, runsByStatusKey } = keys(keyPrefix);
1088
+ /** The statuses a list filter allows, or undefined for any. `status` takes one
1089
+ * status or an array; an empty array matches nothing, unlike omitting it. */
1090
+ function allowedStatuses(params) {
1091
+ const status = params?.status;
1092
+ if (status === void 0) return void 0;
1093
+ return Array.isArray(status) ? status : [status];
1094
+ }
1095
+ function selectIndexKeys(params) {
1096
+ if (params?.workflowName) return [runsByNameKey(params.workflowName)];
1097
+ const statuses = allowedStatuses(params);
1098
+ if (statuses) return statuses.map(runsByStatusKey);
1099
+ return [runsIndexKey()];
1100
+ }
1101
+ function parseRunsFromPipeline(results, params) {
1102
+ const runs = [];
1103
+ for (let i = 0; i + 1 < (results?.length ?? 0); i += 2) {
1104
+ const result = results[i];
1105
+ if (!result?.[1]) continue;
1106
+ const run = parse(result[1]);
1107
+ run.attributes = results[i + 1]?.[1] ?? {};
1108
+ const statuses = allowedStatuses(params);
1109
+ const statusMatches = !statuses || statuses.includes(run.status);
1110
+ const nameMatches = !params?.workflowName || run.workflowName === params.workflowName;
1111
+ if (statusMatches && nameMatches) {
1112
+ const resolveData = params?.resolveData ?? "all";
1113
+ const parsed = WorkflowRunSchema.parse(compact(run));
1114
+ runs.push(filterRunData(parsed, resolveData));
1115
+ }
1116
+ }
1117
+ return runs;
1118
+ }
1119
+ return {
1120
+ get: (async (id, params) => {
1121
+ const replies = await redis.pipeline().get(runKey(id)).hgetall(runAttributesKey(id)).exec();
1122
+ const data = replies?.[0]?.[1];
1123
+ if (!data) throw new WorkflowRunNotFoundError(id);
1124
+ const run = parse(data);
1125
+ run.attributes = replies?.[1]?.[1] ?? {};
1126
+ return filterRunData(WorkflowRunSchema.parse(compact(run)), params?.resolveData ?? "all");
1127
+ }),
1128
+ list: (async (params) => {
1129
+ const limit = params?.pagination?.limit ?? 20;
1130
+ const fromCursor = params?.pagination?.cursor;
1131
+ if (allowedStatuses(params)?.length === 0) return {
1132
+ data: [],
1133
+ hasMore: false,
1134
+ cursor: null
1135
+ };
1136
+ const indexKeys = selectIndexKeys(params);
1137
+ const order = params?.pagination?.sortOrder ?? "desc";
1138
+ const runs = [];
1139
+ let scanFrom = fromCursor;
1140
+ while (runs.length <= limit) {
1141
+ const entries = await pageIndex(redis, indexKeys, scanFrom, limit + 1, order);
1142
+ if (entries.length === 0) break;
1143
+ const pipeline = redis.pipeline();
1144
+ for (const { id } of entries) {
1145
+ pipeline.get(runKey(id));
1146
+ pipeline.hgetall(runAttributesKey(id));
1147
+ }
1148
+ const results = await pipeline.exec();
1149
+ const cursorOf = new Map(entries.map((entry) => [entry.id, entry.cursor]));
1150
+ for (const run of parseRunsFromPipeline(results, params)) runs.push({
1151
+ run,
1152
+ cursor: cursorOf.get(run.runId)
1153
+ });
1154
+ if (entries.length < limit + 1) break;
1155
+ scanFrom = entries.at(-1).cursor;
1156
+ }
1157
+ const values = runs.slice(0, limit);
1158
+ const hasMore = runs.length > limit;
1159
+ return {
1160
+ data: values.map((entry) => entry.run),
1161
+ hasMore,
1162
+ cursor: values.at(-1)?.cursor ?? null
1163
+ };
1164
+ })
1165
+ };
1166
+ }
1167
+ /**
1168
+ * Create storage for workflow events using Redis hashes and sorted sets.
1169
+ *
1170
+ * A run's log is one hash (`eventId -> JSON`). Event ids are log positions, so
1171
+ * the log is dense and 1-based, and every script that appends to it picks the
1172
+ * next position itself, atomically with the write (see `LUA_APPEND_EVENT`).
1173
+ */
1174
+ function createEventsStorage(config) {
1175
+ const { redis, keyPrefix } = config;
1176
+ const scripts = withScripts(redis);
1177
+ const ulid = monotonicFactory();
1178
+ const maxEventsPerRun = resolveMaxEventsPerRun(config.maxEventsPerRun);
1179
+ const { eventsKey, eventsByCorrelationKey, resumeClaimKey, runKey, runAttributesKey, runMetaKey, runsIndexKey, runsByNameKey, runsByStatusKey, stepKey, stepsIndexKey, stepStatusKey, hookKey, hooksByTokenKey, hooksIndexKey, hooksTokenMapKey } = keys(keyPrefix);
1180
+ /** Events per `HMGET`; keeps a long log from building one huge command. */
1181
+ const READ_CHUNK = 500;
1182
+ /** The most events an inline delta or skipped-slot report carries; the
1183
+ * caller continues from the cursor (or reloads) when `hasMore` is set. */
1184
+ const MAX_INLINE_EVENTS = 200;
1185
+ /** A run with its current attributes, which live apart from the run body. */
1186
+ async function withAttributes(run) {
1187
+ const attributes = await redis.hgetall(runAttributesKey(run.runId));
1188
+ return {
1189
+ ...run,
1190
+ attributes
1191
+ };
1192
+ }
1193
+ /** `[key, value, ...]` for a script, from an attribute record. */
1194
+ const flattenAttributes = (attributes) => Object.entries(attributes ?? {}).flat();
1195
+ /** Serialize an event for a script: `eventId` first, holding the placeholder. */
1196
+ function serializeEvent(event) {
1197
+ const { eventId: _eventId, ...rest } = event;
1198
+ return stringify({
1199
+ eventId: EVENT_ID_PLACEHOLDER,
1200
+ ...rest
1201
+ });
1202
+ }
1203
+ /** Read events by id out of one run's log, skipping any that are absent. */
1204
+ async function readEvents(runId, eventIds) {
1205
+ const events = [];
1206
+ for (let i = 0; i < eventIds.length; i += READ_CHUNK) {
1207
+ const values = await redis.hmget(eventsKey(runId), ...eventIds.slice(i, i + READ_CHUNK));
1208
+ for (const value of values) if (value) events.push(EventSchema.parse(compact(parse(value))));
1209
+ }
1210
+ return events;
1211
+ }
1212
+ /** Events at slots `from..to` inclusive, in slot order. */
1213
+ async function readSlots(runId, from, to) {
1214
+ const ids = [];
1215
+ for (let slot = Math.max(from, FIRST_EVENT_SLOT); slot <= to; slot++) ids.push(slotToEventId(slot));
1216
+ return readEvents(runId, ids);
1217
+ }
1218
+ /**
1219
+ * Move a run from `oldStatus` to `newStatus`, release its hooks when it
1220
+ * finishes, and append the lifecycle event: one script, so a crash or a racing
1221
+ * writer can never leave the status and the log disagreeing. `moved` means the
1222
+ * run was no longer in `oldStatus` by the time the script ran, and nothing was
1223
+ * written.
1224
+ */
1225
+ async function transitionRun(runId, oldStatus, newStatus, updatedRun, at, event, releaseHooks) {
1226
+ const result = await scripts.wfTransitionRun(runKey(runId), runsByStatusKey(oldStatus), runsByStatusKey(newStatus), runMetaKey(runId), eventsKey(runId), hooksIndexKey(runId), hooksTokenMapKey(runId), stringify(updatedRun), runId, at.getTime().toString(), runMetaValue(newStatus, updatedRun.specVersion), oldStatus, serializeEvent(event), releaseHooks ? "1" : "0", hookKey(""), hooksByTokenKey(""));
1227
+ if (result[0] === 1) return {
1228
+ kind: "ok",
1229
+ eventId: result[1]
1230
+ };
1231
+ if (result[0] === -2) return {
1232
+ kind: "moved",
1233
+ status: result[1]
1234
+ };
1235
+ return { kind: "absent" };
1236
+ }
1237
+ /** Append an event whose id the script picks. Returns the stored event. */
1238
+ async function appendEvent(runId, event, options = {}) {
1239
+ const correlationId = event.correlationId;
1240
+ const result = await scripts.wfStoreEvent(eventsKey(runId), correlationId ? eventsByCorrelationKey(runId, correlationId) : "__unused__", options.entityKey ?? "__unused__", options.resume ? resumeClaimKey(runId, options.resume.id) : "__unused__", options.step?.key ?? "__unused__", options.runMustBeLive ? runMetaKey(runId) : "__unused__", options.hookMustExist && correlationId ? hookKey(correlationId) : "__unused__", serializeEvent(event), correlationId ? "1" : "0", options.dedup === "creation" ? "1" : options.dedup === "completion" ? "2" : "0", options.entityJson ?? "", options.resume?.claim ?? "", options.step?.status ?? "", options.step?.expectedAttempt === void 0 ? "" : String(options.step.expectedAttempt), options.step?.newAttempt === void 0 ? "" : String(options.step.newAttempt), options.runMustBeLive ? "1" : "0", options.hookMustExist ? "1" : "0");
1241
+ switch (result[0]) {
1242
+ case LUA_DUPLICATE_CREATION: return { kind: "duplicate" };
1243
+ case -7: return { kind: "alreadyCompleted" };
1244
+ case -3: return {
1245
+ kind: "stepTerminal",
1246
+ status: result[1]
1247
+ };
1248
+ case -4: return {
1249
+ kind: "stepMoved",
1250
+ attempt: result[1]
1251
+ };
1252
+ case -5: return { kind: "hookGone" };
1253
+ case -6: return {
1254
+ kind: "runTerminal",
1255
+ status: result[1]
1256
+ };
1257
+ case 3: return {
1258
+ kind: "claimed",
1259
+ claim: result[1]
1260
+ };
1261
+ default: return {
1262
+ kind: "stored",
1263
+ event: EventSchema.parse({
1264
+ ...event,
1265
+ eventId: result[1]
1266
+ })
1267
+ };
1268
+ }
1269
+ }
1270
+ /** The events a bumped write skipped over: those between the slot the writer
1271
+ * asked for (`eventCount + 1`) and the one it landed on. */
1272
+ async function reportSkippedSlots(result, askedFor, resolveData) {
1273
+ if (!result.event) return result;
1274
+ const committedSlot = eventIdToSlot(result.event.eventId);
1275
+ if (committedSlot === null || askedFor < 0 || committedSlot <= askedFor + 1) return result;
1276
+ const span = committedSlot - askedFor - 1;
1277
+ const upto = Math.min(committedSlot - 1, askedFor + MAX_INLINE_EVENTS);
1278
+ const skipped = await readSlots(result.event.runId, askedFor + 1, upto);
1279
+ return {
1280
+ ...result,
1281
+ events: skipped.map((event) => stripEventDataRefs(event, resolveData)),
1282
+ cursor: null,
1283
+ hasMore: skipped.length < span
1284
+ };
1285
+ }
1286
+ /** The inline delta: everything after `sinceCursor`, as `events.list` would
1287
+ * return it right after the write. */
1288
+ async function deltaSince(result, sinceCursor, resolveData) {
1289
+ if (!result.event) return result;
1290
+ const sinceSlot = eventIdToSlot(sinceCursor);
1291
+ if (sinceSlot === null) return result;
1292
+ const total = await redis.hlen(eventsKey(result.event.runId));
1293
+ const upto = Math.min(total, sinceSlot + MAX_INLINE_EVENTS);
1294
+ const page = await readSlots(result.event.runId, sinceSlot + 1, upto);
1295
+ return {
1296
+ ...result,
1297
+ events: page.map((event) => stripEventDataRefs(event, resolveData)),
1298
+ cursor: page.at(-1)?.eventId ?? sinceCursor,
1299
+ hasMore: upto < total
1300
+ };
1301
+ }
1302
+ const isTerminal = (status) => [
1303
+ "completed",
1304
+ "failed",
1305
+ "cancelled"
1306
+ ].includes(status);
1307
+ /** How many times a step write recomputes after losing a race for the step. */
1308
+ const MAX_STALE_RETRIES = 5;
1309
+ async function createEvent(runId, data, params, staleRetries = 0) {
1310
+ const now = /* @__PURE__ */ new Date();
1311
+ const resolveData = params?.resolveData ?? "all";
1312
+ const entityData = entityResolveData(resolveData);
1313
+ let effectiveRunId;
1314
+ if (data.eventType === "run_created" && (!runId || runId === "")) effectiveRunId = `wrun_${ulid()}`;
1315
+ else if (!runId) throw new Error("runId is required for non-run_created events");
1316
+ else effectiveRunId = runId;
1317
+ const effectiveSpecVersion = data.specVersion ?? mintedSpecVersion();
1318
+ const buildEvent = (overrides = {}) => ({
1319
+ ...data,
1320
+ runId: effectiveRunId,
1321
+ createdAt: /* @__PURE__ */ new Date(),
1322
+ specVersion: effectiveSpecVersion,
1323
+ ...overrides
1324
+ });
1325
+ let run;
1326
+ let step;
1327
+ let hook;
1328
+ let lifecycleEvent;
1329
+ let pendingEntityKey;
1330
+ let pendingEntityJson;
1331
+ let pendingStep;
1332
+ let currentRun = null;
1333
+ let existingRun = null;
1334
+ async function loadRunBody() {
1335
+ const runData = await redis.get(runKey(effectiveRunId));
1336
+ if (runData) {
1337
+ existingRun = parse(runData);
1338
+ currentRun = {
1339
+ status: existingRun.status,
1340
+ specVersion: existingRun.specVersion
1341
+ };
1342
+ }
1343
+ }
1344
+ if (data.eventType !== "run_created" && !["step_completed", "step_retrying"].includes(data.eventType)) {
1345
+ if (RUN_LIFECYCLE_EVENT_TYPES.has(data.eventType)) await loadRunBody();
1346
+ else {
1347
+ const meta = await redis.get(runMetaKey(effectiveRunId));
1348
+ if (meta) currentRun = parseRunMeta(meta);
1349
+ }
1350
+ }
1351
+ if (data.eventType === "run_started" && !currentRun && "eventData" in data && data.eventData) {
1352
+ const runInputData = data.eventData;
1353
+ if (runInputData.deploymentId && runInputData.workflowName && runInputData.input !== void 0) {
1354
+ const seeds = runInputData.attributes ?? {};
1355
+ validateAttributeChanges(Object.entries(seeds).map(([key, value]) => ({
1356
+ key,
1357
+ value
1358
+ })), { allowReservedAttributes: runInputData.allowReservedAttributes === true });
1359
+ const newRun = {
1360
+ runId: effectiveRunId,
1361
+ deploymentId: runInputData.deploymentId,
1362
+ workflowName: runInputData.workflowName,
1363
+ specVersion: effectiveSpecVersion,
1364
+ input: runInputData.input,
1365
+ executionContext: runInputData.executionContext,
1366
+ ...runInputData.encryptionPublicKey && { encryptionPublicKey: runInputData.encryptionPublicKey },
1367
+ ...runInputData.dynamicWorkflowCode !== void 0 && { dynamicWorkflowCode: runInputData.dynamicWorkflowCode },
1368
+ status: "pending",
1369
+ output: void 0,
1370
+ error: void 0,
1371
+ completedAt: void 0,
1372
+ startedAt: void 0,
1373
+ createdAt: now,
1374
+ updatedAt: now
1375
+ };
1376
+ const result = await scripts.wfCreateRunWithEvent(runKey(effectiveRunId), runsIndexKey(), runsByNameKey(runInputData.workflowName), runsByStatusKey("pending"), runMetaKey(effectiveRunId), eventsKey(effectiveRunId), runAttributesKey(effectiveRunId), stringify(newRun), effectiveRunId, now.getTime().toString(), runMetaValue("pending", effectiveSpecVersion), serializeEvent({
1377
+ eventType: "run_created",
1378
+ eventData: {
1379
+ deploymentId: runInputData.deploymentId,
1380
+ workflowName: runInputData.workflowName,
1381
+ input: runInputData.input,
1382
+ executionContext: runInputData.executionContext,
1383
+ ...runInputData.attributes && { attributes: runInputData.attributes },
1384
+ ...runInputData.allowReservedAttributes && { allowReservedAttributes: true },
1385
+ ...runInputData.encryptionPublicKey && { encryptionPublicKey: runInputData.encryptionPublicKey }
1386
+ },
1387
+ runId: effectiveRunId,
1388
+ createdAt: now,
1389
+ specVersion: effectiveSpecVersion
1390
+ }), ...flattenAttributes(seeds));
1391
+ if (result[0] === 1) {
1392
+ currentRun = {
1393
+ status: "pending",
1394
+ specVersion: effectiveSpecVersion
1395
+ };
1396
+ existingRun = newRun;
1397
+ } else {
1398
+ const parsed = parse(result[1]);
1399
+ currentRun = {
1400
+ status: parsed.status,
1401
+ specVersion: parsed.specVersion
1402
+ };
1403
+ existingRun = parsed;
1404
+ }
1405
+ }
1406
+ }
1407
+ if (currentRun) {
1408
+ if (requiresNewerWorld(currentRun.specVersion)) throw new RunNotSupportedError(currentRun.specVersion, mintedSpecVersion());
1409
+ if (isLegacySpecVersion(currentRun.specVersion)) throw new RunNotSupportedError(currentRun.specVersion, mintedSpecVersion());
1410
+ }
1411
+ if (currentRun && isTerminal(currentRun.status)) {
1412
+ const terminalStatus = currentRun.status;
1413
+ const runTerminalEvents = [
1414
+ "run_started",
1415
+ "run_completed",
1416
+ "run_failed"
1417
+ ];
1418
+ if (data.eventType === "run_cancelled" && terminalStatus === "cancelled") {
1419
+ const stored = await appendEvent(effectiveRunId, buildEvent());
1420
+ if (stored.kind !== "stored") throw new EntityConflictError("Duplicate run_cancelled");
1421
+ return {
1422
+ event: stripEventDataRefs(stored.event, entityData),
1423
+ run: existingRun ? await withAttributes(WorkflowRunSchema.parse(compact(existingRun))) : void 0
1424
+ };
1425
+ }
1426
+ if (data.eventType === "run_started") throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in terminal state "${terminalStatus}"`);
1427
+ if (data.eventType === "step_started") throw new RunExpiredError(`Cannot start step on run in terminal state "${terminalStatus}"`);
1428
+ if (runTerminalEvents.includes(data.eventType) || data.eventType === "run_cancelled") throw new EntityConflictError(`Cannot transition run from terminal state "${terminalStatus}"`);
1429
+ if (data.eventType === "step_created" || data.eventType === "hook_created" || data.eventType === "wait_created") throw new EntityConflictError(`Cannot create new entities on run in terminal state "${terminalStatus}"`);
1430
+ }
1431
+ let validatedStep = null;
1432
+ const lazyStepStart = data.eventType === "step_started" && typeof data.eventData?.stepName === "string" && data.eventData?.input !== void 0;
1433
+ if (["step_started", "step_retrying"].includes(data.eventType) && data.correlationId) {
1434
+ const stepData = await redis.get(stepKey(effectiveRunId, data.correlationId));
1435
+ if (stepData) validatedStep = parse(stepData);
1436
+ if (!validatedStep && !lazyStepStart) throw new WorkflowWorldError(`Step "${data.correlationId}" not found`, { status: 404 });
1437
+ if (lazyStepStart && validatedStep) throw new EntityConflictError(`Step "${data.correlationId}" already created`);
1438
+ if (validatedStep) {
1439
+ if (isTerminal(validatedStep.status)) throw new EntityConflictError(`Cannot modify step in terminal state "${validatedStep.status}"`);
1440
+ if (currentRun && isTerminal(currentRun.status)) {
1441
+ if (validatedStep.status !== "running") throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
1442
+ }
1443
+ }
1444
+ }
1445
+ let validatedHook = null;
1446
+ const hookEventsRequiringExistence = ["hook_disposed", "hook_received"];
1447
+ const isResumeRetryCandidate = data.eventType === "hook_received" && params?.resumeId;
1448
+ if (hookEventsRequiringExistence.includes(data.eventType) && data.correlationId && !isResumeRetryCandidate) {
1449
+ const existingHook = await redis.get(hookKey(data.correlationId));
1450
+ if (!existingHook) throw new HookNotFoundError(data.correlationId);
1451
+ validatedHook = parse(existingHook);
1452
+ }
1453
+ if (data.eventType === "run_created") {
1454
+ const eventData = data.eventData;
1455
+ if (eventData.dynamicWorkflowCodeRef !== void 0) throw new WorkflowWorldError("dynamicWorkflowCodeRef is not supported by this world", { status: 501 });
1456
+ const seeds = eventData.attributes ?? {};
1457
+ validateAttributeChanges(Object.entries(seeds).map(([key, value]) => ({
1458
+ key,
1459
+ value
1460
+ })), { allowReservedAttributes: eventData.allowReservedAttributes === true });
1461
+ const newRun = {
1462
+ runId: effectiveRunId,
1463
+ deploymentId: eventData.deploymentId,
1464
+ workflowName: eventData.workflowName,
1465
+ specVersion: effectiveSpecVersion,
1466
+ input: eventData.input,
1467
+ executionContext: eventData.executionContext,
1468
+ ...eventData.encryptionPublicKey && { encryptionPublicKey: eventData.encryptionPublicKey },
1469
+ ...eventData.dynamicWorkflowCode !== void 0 && { dynamicWorkflowCode: eventData.dynamicWorkflowCode },
1470
+ status: "pending",
1471
+ output: void 0,
1472
+ error: void 0,
1473
+ completedAt: void 0,
1474
+ startedAt: void 0,
1475
+ createdAt: now,
1476
+ updatedAt: now
1477
+ };
1478
+ const event = buildEvent({ createdAt: now });
1479
+ const result = await scripts.wfCreateRunWithEvent(runKey(effectiveRunId), runsIndexKey(), runsByNameKey(eventData.workflowName), runsByStatusKey("pending"), runMetaKey(effectiveRunId), eventsKey(effectiveRunId), runAttributesKey(effectiveRunId), stringify(newRun), effectiveRunId, now.getTime().toString(), runMetaValue("pending", effectiveSpecVersion), serializeEvent(event), ...flattenAttributes(seeds));
1480
+ if (result[0] === 0) throw new EntityConflictError(`Workflow run "${effectiveRunId}" already exists`);
1481
+ run = WorkflowRunSchema.parse({
1482
+ ...compact(newRun),
1483
+ attributes: seeds
1484
+ });
1485
+ const parsed = EventSchema.parse({
1486
+ ...event,
1487
+ eventId: result[1]
1488
+ });
1489
+ return {
1490
+ event: stripEventDataRefs(parsed, entityData),
1491
+ run,
1492
+ maxEvents: maxEventsPerRun
1493
+ };
1494
+ }
1495
+ if (data.eventType === "run_started") {
1496
+ const resumeResponse = async (current) => {
1497
+ const resumed = current ? await withAttributes(WorkflowRunSchema.parse(compact(current))) : void 0;
1498
+ return {
1499
+ run: resumed ? filterRunData(resumed, entityData) : void 0,
1500
+ ...resumed ? { maxEvents: maxEventsPerRun } : {}
1501
+ };
1502
+ };
1503
+ if (currentRun?.status === "running") return resumeResponse(existingRun);
1504
+ if (!existingRun) throw new WorkflowRunNotFoundError(effectiveRunId);
1505
+ const existing = existingRun;
1506
+ const updatedRun = {
1507
+ ...existing,
1508
+ status: "running",
1509
+ startedAt: now,
1510
+ updatedAt: now
1511
+ };
1512
+ const { eventData: _startData, ...startEvent } = buildEvent({ createdAt: now });
1513
+ const moved = await transitionRun(effectiveRunId, existing.status, "running", updatedRun, now, startEvent, false);
1514
+ if (moved.kind === "absent") throw new WorkflowRunNotFoundError(effectiveRunId);
1515
+ if (moved.kind === "moved") {
1516
+ if (isTerminal(moved.status)) throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in terminal state "${moved.status}"`);
1517
+ await loadRunBody();
1518
+ return resumeResponse(existingRun);
1519
+ }
1520
+ run = WorkflowRunSchema.parse(compact(updatedRun));
1521
+ lifecycleEvent = EventSchema.parse({
1522
+ ...startEvent,
1523
+ eventId: moved.eventId
1524
+ });
1525
+ }
1526
+ if (data.eventType === "run_completed" || data.eventType === "run_failed" || data.eventType === "run_cancelled") {
1527
+ if (!existingRun) throw new WorkflowRunNotFoundError(effectiveRunId);
1528
+ const existing = existingRun;
1529
+ let updatedRun;
1530
+ let newStatus;
1531
+ if (data.eventType === "run_completed") {
1532
+ const eventData = data.eventData;
1533
+ newStatus = "completed";
1534
+ updatedRun = {
1535
+ ...existing,
1536
+ status: "completed",
1537
+ output: eventData.output,
1538
+ completedAt: now,
1539
+ updatedAt: now
1540
+ };
1541
+ } else if (data.eventType === "run_failed") {
1542
+ const eventData = data.eventData;
1543
+ newStatus = "failed";
1544
+ updatedRun = {
1545
+ ...existing,
1546
+ status: "failed",
1547
+ error: eventData.error,
1548
+ errorCode: eventData.errorCode,
1549
+ completedAt: now,
1550
+ updatedAt: now
1551
+ };
1552
+ } else {
1553
+ newStatus = "cancelled";
1554
+ updatedRun = {
1555
+ ...existing,
1556
+ status: "cancelled",
1557
+ completedAt: now,
1558
+ updatedAt: now
1559
+ };
1560
+ }
1561
+ const terminalEvent = buildEvent({ createdAt: now });
1562
+ const moved = await transitionRun(effectiveRunId, existing.status, newStatus, updatedRun, now, terminalEvent, true);
1563
+ if (moved.kind === "absent") throw new WorkflowRunNotFoundError(effectiveRunId);
1564
+ if (moved.kind === "moved") throw new EntityConflictError(`Cannot transition run "${effectiveRunId}" to "${newStatus}": it already left "${existing.status}" for "${moved.status}"`);
1565
+ run = WorkflowRunSchema.parse(compact(updatedRun));
1566
+ lifecycleEvent = EventSchema.parse({
1567
+ ...terminalEvent,
1568
+ eventId: moved.eventId
1569
+ });
1570
+ }
1571
+ if (data.eventType === "step_created") {
1572
+ const eventData = data.eventData;
1573
+ const newStep = {
1574
+ runId: effectiveRunId,
1575
+ stepId: data.correlationId,
1576
+ stepName: eventData.stepName,
1577
+ input: eventData.input,
1578
+ status: "pending",
1579
+ attempt: 0,
1580
+ specVersion: effectiveSpecVersion,
1581
+ createdAt: now,
1582
+ updatedAt: now
1583
+ };
1584
+ const event = buildEvent({ createdAt: now });
1585
+ const result = await scripts.wfCreateStepWithEvent(stepKey(effectiveRunId, data.correlationId), stepsIndexKey(effectiveRunId), eventsKey(effectiveRunId), eventsByCorrelationKey(effectiveRunId, data.correlationId), stepStatusKey(effectiveRunId, data.correlationId), runMetaKey(effectiveRunId), stringify(newStep), data.correlationId, now.getTime().toString(), serializeEvent(event), "pending|0");
1586
+ if (result[0] === -6) throw new EntityConflictError(`Cannot create new entities on run in terminal state "${result[1]}"`);
1587
+ if (result[0] === 0) throw new EntityConflictError(`Step "${data.correlationId}" already exists`);
1588
+ step = StepSchema.parse(compact(newStep));
1589
+ const parsed = EventSchema.parse({
1590
+ ...event,
1591
+ eventId: result[1]
1592
+ });
1593
+ return {
1594
+ event: stripEventDataRefs(parsed, entityData),
1595
+ step
1596
+ };
1597
+ }
1598
+ const dedup = data.eventType === "wait_created" ? "creation" : data.eventType === "wait_completed" ? "completion" : void 0;
1599
+ if (data.eventType === "step_started") {
1600
+ if (validatedStep?.retryAfter && validatedStep.retryAfter.getTime() > Date.now()) throw new TooEarlyError(`Cannot start step "${data.correlationId}": retryAfter timestamp has not been reached yet`, { retryAfter: Math.ceil((validatedStep.retryAfter.getTime() - Date.now()) / 1e3) });
1601
+ if (lazyStepStart) {
1602
+ const lazyData = data.eventData;
1603
+ const startedStep = {
1604
+ runId: effectiveRunId,
1605
+ stepId: data.correlationId,
1606
+ stepName: lazyData.stepName,
1607
+ input: lazyData.input,
1608
+ status: "running",
1609
+ attempt: 1,
1610
+ startedAt: now,
1611
+ specVersion: effectiveSpecVersion,
1612
+ createdAt: now,
1613
+ updatedAt: now
1614
+ };
1615
+ const { input: _input, ...startedEventData } = lazyData;
1616
+ const createdEvent = {
1617
+ eventType: "step_created",
1618
+ correlationId: data.correlationId,
1619
+ runId: effectiveRunId,
1620
+ createdAt: now,
1621
+ specVersion: effectiveSpecVersion,
1622
+ eventData: {
1623
+ stepName: lazyData.stepName,
1624
+ ...lazyData.workflowName !== void 0 && { workflowName: lazyData.workflowName },
1625
+ input: lazyData.input
1626
+ }
1627
+ };
1628
+ const startedEvent = buildEvent({
1629
+ createdAt: now,
1630
+ eventData: startedEventData
1631
+ });
1632
+ const result = await scripts.wfCreateStepStarted(stepKey(effectiveRunId, data.correlationId), stepsIndexKey(effectiveRunId), eventsKey(effectiveRunId), eventsByCorrelationKey(effectiveRunId, data.correlationId), stepStatusKey(effectiveRunId, data.correlationId), runMetaKey(effectiveRunId), stringify(startedStep), data.correlationId, now.getTime().toString(), serializeEvent(createdEvent), serializeEvent(startedEvent), "running|1");
1633
+ if (result[0] === -6) throw new RunExpiredError(`Cannot start step on run in terminal state "${result[1]}"`);
1634
+ if (result[0] === 0) throw new EntityConflictError(`Step "${data.correlationId}" already created`);
1635
+ step = StepSchema.parse(compact(startedStep));
1636
+ const parsed = EventSchema.parse({
1637
+ ...startedEvent,
1638
+ eventId: result[2]
1639
+ });
1640
+ return {
1641
+ event: stripEventDataRefs(parsed, entityData),
1642
+ step,
1643
+ stepCreated: true
1644
+ };
1645
+ }
1646
+ const isFirstStart = !validatedStep?.startedAt;
1647
+ const existing = validatedStep;
1648
+ if (existing) {
1649
+ const updatedStep = {
1650
+ ...existing,
1651
+ status: "running",
1652
+ attempt: existing.attempt + 1,
1653
+ ...isFirstStart ? { startedAt: now } : {},
1654
+ retryAfter: void 0,
1655
+ updatedAt: now
1656
+ };
1657
+ pendingEntityKey = stepKey(effectiveRunId, data.correlationId);
1658
+ pendingEntityJson = stringify(updatedStep);
1659
+ pendingStep = {
1660
+ key: stepStatusKey(effectiveRunId, data.correlationId),
1661
+ status: "running",
1662
+ expectedAttempt: existing.attempt,
1663
+ newAttempt: updatedStep.attempt
1664
+ };
1665
+ step = StepSchema.parse(compact(updatedStep));
1666
+ }
1667
+ }
1668
+ if (data.eventType === "step_completed") {
1669
+ const eventData = data.eventData;
1670
+ const existingData = await redis.get(stepKey(effectiveRunId, data.correlationId));
1671
+ if (existingData) {
1672
+ const existing = parse(existingData);
1673
+ if (isTerminal(existing.status)) throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
1674
+ const updatedStep = {
1675
+ ...existing,
1676
+ status: "completed",
1677
+ output: eventData.result,
1678
+ completedAt: now,
1679
+ updatedAt: now
1680
+ };
1681
+ pendingEntityKey = stepKey(effectiveRunId, data.correlationId);
1682
+ pendingEntityJson = stringify(updatedStep);
1683
+ pendingStep = {
1684
+ key: stepStatusKey(effectiveRunId, data.correlationId),
1685
+ status: "completed",
1686
+ expectedAttempt: existing.attempt
1687
+ };
1688
+ step = StepSchema.parse(compact(updatedStep));
1689
+ } else throw new WorkflowWorldError(`Step "${data.correlationId}" not found`, { status: 404 });
1690
+ }
1691
+ if (data.eventType === "step_failed") {
1692
+ const eventData = data.eventData;
1693
+ const existingData = await redis.get(stepKey(effectiveRunId, data.correlationId));
1694
+ if (existingData) {
1695
+ const existing = parse(existingData);
1696
+ if (isTerminal(existing.status)) throw new EntityConflictError(`Cannot modify step in terminal state "${existing.status}"`);
1697
+ const updatedStep = {
1698
+ ...existing,
1699
+ status: "failed",
1700
+ error: eventData.error,
1701
+ completedAt: now,
1702
+ updatedAt: now
1703
+ };
1704
+ pendingEntityKey = stepKey(effectiveRunId, data.correlationId);
1705
+ pendingEntityJson = stringify(updatedStep);
1706
+ pendingStep = {
1707
+ key: stepStatusKey(effectiveRunId, data.correlationId),
1708
+ status: "failed",
1709
+ expectedAttempt: existing.attempt
1710
+ };
1711
+ step = StepSchema.parse(compact(updatedStep));
1712
+ } else throw new WorkflowWorldError(`Step "${data.correlationId}" not found`, { status: 404 });
1713
+ }
1714
+ if (data.eventType === "step_retrying") {
1715
+ const eventData = data.eventData;
1716
+ const existing = validatedStep;
1717
+ if (existing) {
1718
+ const updatedStep = {
1719
+ ...existing,
1720
+ status: "pending",
1721
+ error: eventData.error,
1722
+ retryAfter: eventData.retryAfter,
1723
+ updatedAt: now
1724
+ };
1725
+ pendingEntityKey = stepKey(effectiveRunId, data.correlationId);
1726
+ pendingEntityJson = stringify(updatedStep);
1727
+ pendingStep = {
1728
+ key: stepStatusKey(effectiveRunId, data.correlationId),
1729
+ status: "pending",
1730
+ expectedAttempt: existing.attempt
1731
+ };
1732
+ step = StepSchema.parse(compact(updatedStep));
1733
+ }
1734
+ }
1735
+ if (data.eventType === "hook_created") {
1736
+ const eventData = data.eventData;
1737
+ const newHook = {
1738
+ runId: effectiveRunId,
1739
+ hookId: data.correlationId,
1740
+ token: eventData.token,
1741
+ ownerId: "",
1742
+ projectId: "",
1743
+ environment: "",
1744
+ metadata: eventData.metadata,
1745
+ specVersion: effectiveSpecVersion,
1746
+ createdAt: now,
1747
+ ...eventData.isWebhook !== void 0 && { isWebhook: eventData.isWebhook },
1748
+ ...eventData.isSystem !== void 0 && { isSystem: eventData.isSystem }
1749
+ };
1750
+ const event = buildEvent({ createdAt: now });
1751
+ const result = await scripts.wfCreateHookWithEvent(hookKey(data.correlationId), hooksByTokenKey(eventData.token), hooksIndexKey(effectiveRunId), hooksTokenMapKey(effectiveRunId), eventsKey(effectiveRunId), eventsByCorrelationKey(effectiveRunId, data.correlationId), runMetaKey(effectiveRunId), stringify(newHook), data.correlationId, now.getTime().toString(), eventData.token, serializeEvent(event), hookKey(""));
1752
+ if (result[0] === -6) throw new EntityConflictError(`Cannot create new entities on run in terminal state "${result[1]}"`);
1753
+ if (result[0] === 2) {
1754
+ const owningHookId = result[1];
1755
+ let conflictingRunId;
1756
+ const owningHookData = await redis.get(hookKey(owningHookId));
1757
+ if (owningHookData) conflictingRunId = parse(owningHookData).runId;
1758
+ const stored = await appendEvent(effectiveRunId, {
1759
+ eventType: "hook_conflict",
1760
+ correlationId: data.correlationId,
1761
+ eventData: {
1762
+ token: eventData.token,
1763
+ ...conflictingRunId ? { conflictingRunId } : {}
1764
+ },
1765
+ runId: effectiveRunId,
1766
+ createdAt: now,
1767
+ specVersion: effectiveSpecVersion
1768
+ }, {
1769
+ dedup: "creation",
1770
+ runMustBeLive: true
1771
+ });
1772
+ if (stored.kind === "runTerminal") throw new EntityConflictError(`Cannot create new entities on run in terminal state "${stored.status}"`);
1773
+ if (stored.kind !== "stored") throw new EntityConflictError(`Hook "${data.correlationId}" conflict already recorded`);
1774
+ return {
1775
+ event: stripEventDataRefs(stored.event, entityData),
1776
+ run,
1777
+ step,
1778
+ hook: void 0
1779
+ };
1780
+ }
1781
+ if (result[0] === 0) throw new EntityConflictError(`Hook "${data.correlationId}" already created`);
1782
+ hook = HookSchema.parse(compact(newHook));
1783
+ const parsed = EventSchema.parse({
1784
+ ...event,
1785
+ eventId: result[1]
1786
+ });
1787
+ return {
1788
+ event: stripEventDataRefs(parsed, entityData),
1789
+ hook
1790
+ };
1791
+ }
1792
+ if (data.eventType === "hook_disposed" && data.correlationId) {
1793
+ if (!validatedHook) throw new EntityConflictError(`Hook "${data.correlationId}" already disposed`);
1794
+ const event = buildEvent();
1795
+ const result = await scripts.wfDisposeHook(hookKey(data.correlationId), hooksByTokenKey(validatedHook.token), hooksIndexKey(effectiveRunId), hooksTokenMapKey(effectiveRunId), eventsKey(effectiveRunId), eventsByCorrelationKey(effectiveRunId, data.correlationId), data.correlationId, serializeEvent(event));
1796
+ if (result[0] === 0) throw new EntityConflictError(`Hook "${data.correlationId}" already disposed`);
1797
+ const parsed = EventSchema.parse({
1798
+ ...event,
1799
+ eventId: result[1]
1800
+ });
1801
+ return { event: stripEventDataRefs(parsed, entityData) };
1802
+ }
1803
+ if (data.eventType === "attr_set") {
1804
+ if (!currentRun) throw new WorkflowRunNotFoundError(effectiveRunId);
1805
+ const eventData = data.eventData;
1806
+ validateAttributeChanges(eventData.changes, {
1807
+ existingKeys: await redis.hkeys(runAttributesKey(effectiveRunId)),
1808
+ allowReservedAttributes: eventData.allowReservedAttributes === true
1809
+ });
1810
+ const event = buildEvent();
1811
+ const correlationId = data.correlationId;
1812
+ const result = await scripts.wfSetAttributes(runAttributesKey(effectiveRunId), eventsKey(effectiveRunId), correlationId ? eventsByCorrelationKey(effectiveRunId, correlationId) : "__unused__", runMetaKey(effectiveRunId), serializeEvent(event), correlationId ? "1" : "0", data.eventData?.writer?.type === "workflow" ? "1" : "0", ...eventData.changes.flatMap((change) => [
1813
+ change.key,
1814
+ change.value ?? "",
1815
+ change.value === null ? "del" : "set"
1816
+ ]));
1817
+ if (result[0] === -6) throw new EntityConflictError(`Cannot set attributes on run in terminal state "${result[1]}"`);
1818
+ if (result[0] === LUA_DUPLICATE_CREATION) throw new EntityConflictError(`attr_set for correlationId "${correlationId}" already exists in run "${effectiveRunId}"`);
1819
+ await loadRunBody();
1820
+ return {
1821
+ event: stripEventDataRefs(EventSchema.parse({
1822
+ ...event,
1823
+ eventId: result[1]
1824
+ }), entityData),
1825
+ run: existingRun ? await withAttributes(WorkflowRunSchema.parse(compact(existingRun))) : void 0
1826
+ };
1827
+ }
1828
+ const resume = data.eventType === "hook_received" && params?.resumeId ? {
1829
+ id: params.resumeId,
1830
+ claim: `${params.resumePayloadDigest ?? ""}|${data.correlationId}`
1831
+ } : void 0;
1832
+ const stored = lifecycleEvent ? {
1833
+ kind: "stored",
1834
+ event: lifecycleEvent
1835
+ } : await appendEvent(effectiveRunId, buildEvent(), {
1836
+ entityKey: pendingEntityKey,
1837
+ entityJson: pendingEntityJson,
1838
+ dedup,
1839
+ resume,
1840
+ step: pendingStep,
1841
+ runMustBeLive: data.eventType === "hook_received" || data.eventType === "wait_created" || data.eventType === "step_started",
1842
+ hookMustExist: data.eventType === "hook_received"
1843
+ });
1844
+ if (stored.kind === "duplicate") throw new EntityConflictError(`"${data.correlationId}" already exists`);
1845
+ if (stored.kind === "alreadyCompleted") throw new EntityConflictError(`Wait "${data.correlationId}" already completed`);
1846
+ if (stored.kind === "stepTerminal") throw new EntityConflictError(`Cannot modify step in terminal state "${stored.status}"`);
1847
+ if (stored.kind === "stepMoved") {
1848
+ if (data.eventType !== "step_started" && staleRetries < MAX_STALE_RETRIES) return createEvent(runId, data, params, staleRetries + 1);
1849
+ throw new EntityConflictError(`Step "${data.correlationId}" was moved by another delivery (attempt ${stored.attempt})`);
1850
+ }
1851
+ if (stored.kind === "runTerminal") {
1852
+ if (data.eventType === "step_started") throw new RunExpiredError(`Cannot start step on run in terminal state "${stored.status}"`);
1853
+ throw new EntityConflictError(`Cannot add ${data.eventType} to run in terminal state "${stored.status}"`);
1854
+ }
1855
+ if (stored.kind === "hookGone") throw new HookNotFoundError(data.correlationId);
1856
+ if (stored.kind === "claimed") {
1857
+ const [claimedEventId, claimedDigest, claimedHookId] = stored.claim.split("|");
1858
+ if (claimedHookId !== data.correlationId) throw new EntityConflictError(`hook_received resumeId "${params.resumeId}" already recorded for a different hook`);
1859
+ if (params?.resumePayloadDigest && claimedDigest && claimedDigest !== params.resumePayloadDigest) throw new EntityConflictError(`hook_received resumeId "${params.resumeId}" already recorded with a different payload`);
1860
+ const [existingEvent] = await readEvents(effectiveRunId, [claimedEventId]);
1861
+ if (!existingEvent) throw new WorkflowWorldError(`Event not found: ${claimedEventId}`, { status: 404 });
1862
+ return { event: stripEventDataRefs(existingEvent, entityData) };
1863
+ }
1864
+ let preloaded;
1865
+ if (data.eventType === "run_started" && run && params?.skipPreload !== true) {
1866
+ const total = await redis.hlen(eventsKey(effectiveRunId));
1867
+ const all = await readSlots(effectiveRunId, FIRST_EVENT_SLOT, total);
1868
+ preloaded = {
1869
+ events: all.map((e) => stripEventDataRefs(e, resolveData)),
1870
+ cursor: all.at(-1)?.eventId ?? null,
1871
+ hasMore: false
1872
+ };
1873
+ }
1874
+ return {
1875
+ event: stripEventDataRefs(stored.event, entityData),
1876
+ run: run ? await withAttributes(run) : void 0,
1877
+ step,
1878
+ hook,
1879
+ ...preloaded,
1880
+ ...run ? { maxEvents: maxEventsPerRun } : {}
1881
+ };
1882
+ }
1883
+ return {
1884
+ create: (async (runId, data, params) => {
1885
+ const result = await createEvent(runId, data, params);
1886
+ if (!result.event || result.events !== void 0) return result;
1887
+ const resolveData = params?.resolveData ?? "all";
1888
+ if (typeof params?.sinceCursor === "string") return deltaSince(result, params.sinceCursor, resolveData);
1889
+ if (params?.eventCount !== void 0) return reportSkippedSlots(result, params.eventCount, resolveData);
1890
+ return result;
1891
+ }),
1892
+ async get(runId, eventId, params) {
1893
+ const data = await redis.hget(eventsKey(runId), eventId);
1894
+ if (!data) throw new WorkflowWorldError(`Event not found: ${eventId}`, { status: 404 });
1895
+ const event = EventSchema.parse(compact(parse(data)));
1896
+ return stripEventDataRefs(event, params?.resolveData ?? "all");
1897
+ },
1898
+ async list(params) {
1899
+ const sortOrder = params.pagination?.sortOrder || "asc";
1900
+ const fromCursor = params.pagination?.cursor;
1901
+ const total = await redis.hlen(eventsKey(params.runId));
1902
+ const limit = params.pagination?.limit ?? Math.max(total, 1);
1903
+ let cursorSlot = null;
1904
+ if (fromCursor) {
1905
+ cursorSlot = eventIdToSlot(fromCursor);
1906
+ if (cursorSlot === null) throw new WorkflowWorldError(`Invalid pagination cursor "${fromCursor}"`, { status: 400 });
1907
+ }
1908
+ let events;
1909
+ let hasMore;
1910
+ if (sortOrder === "desc") {
1911
+ const last = cursorSlot === null ? total : Math.min(cursorSlot - 1, total);
1912
+ const first = Math.max(FIRST_EVENT_SLOT, last - limit + 1);
1913
+ events = (await readSlots(params.runId, first, last)).reverse();
1914
+ hasMore = first > FIRST_EVENT_SLOT;
1915
+ } else {
1916
+ const first = (cursorSlot ?? 0) + 1;
1917
+ const last = Math.min(total, first + limit - 1);
1918
+ events = await readSlots(params.runId, first, last);
1919
+ hasMore = last < total;
1920
+ }
1921
+ const resolveData = params.resolveData ?? "all";
1922
+ return {
1923
+ data: events.map((event) => stripEventDataRefs(event, resolveData)),
1924
+ cursor: events.at(-1)?.eventId ?? fromCursor ?? null,
1925
+ hasMore
1926
+ };
1927
+ },
1928
+ async listByCorrelationId(params) {
1929
+ const limit = params.pagination?.limit ?? 100;
1930
+ const sortOrder = params.pagination?.sortOrder || "asc";
1931
+ const fromCursor = params.pagination?.cursor;
1932
+ const indexKey = eventsByCorrelationKey(params.runId, params.correlationId);
1933
+ let ids;
1934
+ if (sortOrder === "desc") {
1935
+ const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;
1936
+ const max = cursorSlot === null ? "+inf" : `(${cursorSlot}`;
1937
+ ids = await redis.zrevrangebyscore(indexKey, max, "-inf", "LIMIT", 0, limit + 1);
1938
+ } else {
1939
+ const cursorSlot = fromCursor ? eventIdToSlot(fromCursor) : null;
1940
+ const min = cursorSlot === null ? "-inf" : `(${cursorSlot}`;
1941
+ ids = await redis.zrangebyscore(indexKey, min, "+inf", "LIMIT", 0, limit + 1);
1942
+ }
1943
+ const page = ids.slice(0, limit);
1944
+ const events = await readEvents(params.runId, page);
1945
+ const resolveData = params.resolveData ?? "all";
1946
+ return {
1947
+ data: events.map((event) => stripEventDataRefs(event, resolveData)),
1948
+ cursor: events.at(-1)?.eventId ?? fromCursor ?? null,
1949
+ hasMore: ids.length > limit
1950
+ };
1951
+ }
1952
+ };
1953
+ }
1954
+ /**
1955
+ * Create storage for workflow steps using Redis hashes and sorted sets
1956
+ */
1957
+ function createStepsStorage(config) {
1958
+ const { redis, keyPrefix } = config;
1959
+ const { stepKey, stepsIndexKey } = keys(keyPrefix);
1960
+ async function getStepData(key, stepId, params) {
1961
+ const data = await redis.get(key);
1962
+ if (!data) throw new WorkflowWorldError(`Step not found: ${stepId}`, { status: 404 });
1963
+ const step = parse(data);
1964
+ return filterStepData(StepSchema.parse(compact(step)), params?.resolveData ?? "all");
1965
+ }
1966
+ return {
1967
+ get: (async (runId, stepId, params) => getStepData(stepKey(runId, stepId), stepId, params)),
1968
+ list: (async (params) => {
1969
+ const limit = params?.pagination?.limit ?? 20;
1970
+ const fromCursor = params?.pagination?.cursor;
1971
+ const entries = await pageIndex(redis, stepsIndexKey(params.runId), fromCursor, limit + 1, params?.pagination?.sortOrder ?? "desc");
1972
+ const pipeline = redis.pipeline();
1973
+ for (const { id } of entries) pipeline.get(stepKey(params.runId, id));
1974
+ const results = await pipeline.exec();
1975
+ const resolveData = params?.resolveData ?? "all";
1976
+ const steps = [];
1977
+ for (const [i, result] of (results ?? []).entries()) if (result?.[1]) {
1978
+ const step = parse(result[1]);
1979
+ const parsed = StepSchema.parse(compact(step));
1980
+ steps.push({
1981
+ step: filterStepData(parsed, resolveData),
1982
+ cursor: entries[i].cursor
1983
+ });
1984
+ }
1985
+ const values = steps.slice(0, limit);
1986
+ const hasMore = steps.length > limit;
1987
+ return {
1988
+ data: values.map((entry) => entry.step),
1989
+ hasMore,
1990
+ cursor: values.at(-1)?.cursor ?? null
1991
+ };
1992
+ })
1993
+ };
1994
+ }
1995
+ /**
1996
+ * Create storage for hooks using Redis hashes and sorted sets
1997
+ */
1998
+ function createHooksStorage(config) {
1999
+ const { redis, keyPrefix } = config;
2000
+ const { hookKey: hookKeyFn, hooksByTokenKey, hooksIndexKey, runsByStatusKey } = keys(keyPrefix);
2001
+ async function liveHooksIndexKeys() {
2002
+ return (await Promise.all(["pending", "running"].map((status) => redis.zrange(runsByStatusKey(status), "0", "-1")))).flat().map(hooksIndexKey);
2003
+ }
2004
+ return {
2005
+ async get(hookId, params) {
2006
+ const data = await redis.get(hookKeyFn(hookId));
2007
+ if (!data) throw new HookNotFoundError(hookId);
2008
+ const hook = parse(data);
2009
+ return filterHookData(HookSchema.parse(compact(hook)), params?.resolveData ?? "all");
2010
+ },
2011
+ async getByToken(token, params) {
2012
+ const hookId = await redis.get(hooksByTokenKey(token));
2013
+ if (!hookId) throw new HookNotFoundError(token);
2014
+ return this.get(hookId, params);
2015
+ },
2016
+ async list(params) {
2017
+ const limit = params?.pagination?.limit ?? 100;
2018
+ const fromCursor = params?.pagination?.cursor;
2019
+ const entries = await pageIndex(redis, params.runId ? hooksIndexKey(params.runId) : await liveHooksIndexKeys(), fromCursor, limit + 1, params?.pagination?.sortOrder ?? "asc");
2020
+ const pipeline = redis.pipeline();
2021
+ for (const { id } of entries) pipeline.get(hookKeyFn(id));
2022
+ const results = await pipeline.exec();
2023
+ const hooks = [];
2024
+ for (const [i, result] of (results ?? []).entries()) if (result?.[1]) {
2025
+ const hook = parse(result[1]);
2026
+ const parsed = HookSchema.parse(compact(hook));
2027
+ hooks.push({
2028
+ hook: filterHookData(parsed, params?.resolveData ?? "all"),
2029
+ cursor: entries[i].cursor
2030
+ });
2031
+ }
2032
+ const values = hooks.slice(0, limit);
2033
+ const hasMore = hooks.length > limit;
2034
+ return {
2035
+ data: values.map((entry) => entry.hook),
2036
+ cursor: values.at(-1)?.cursor ?? null,
2037
+ hasMore
2038
+ };
2039
+ }
2040
+ };
2041
+ }
2042
+ // src/streamer.ts
2043
+ function parseStreamPublishMessage(raw) {
2044
+ let parsed;
2045
+ try {
2046
+ parsed = JSON.parse(raw);
2047
+ } catch {
2048
+ return null;
2049
+ }
2050
+ if (!parsed || typeof parsed !== "object") return null;
2051
+ const { runId, streamId, entryId, data, eof, prevId } = parsed;
2052
+ if (typeof runId !== "string" || typeof streamId !== "string") return null;
2053
+ if (typeof entryId !== "string" || typeof prevId !== "string") return null;
2054
+ if (typeof data !== "string" || typeof eof !== "boolean") return null;
2055
+ return {
2056
+ runId,
2057
+ streamId,
2058
+ entryId,
2059
+ data,
2060
+ eof,
2061
+ prevId
2062
+ };
2063
+ }
2064
+ /** A reader also re-reads the stream this often, in case a notification and the
2065
+ * reconnect hook both missed something. Notifications are the fast path. */
2066
+ const CATCH_UP_INTERVAL_MS = 2e3;
2067
+ /**
2068
+ * Compare two Redis stream entry IDs (`<ms>-<seq>`) numerically.
2069
+ *
2070
+ * String comparison is NOT safe here: within one millisecond `...-10` compares
2071
+ * lexicographically smaller than `...-9`, which would drop chunks (and the eof
2072
+ * marker) once the sequence number crosses a digit boundary.
2073
+ */
2074
+ function compareStreamEntryIds(a, b) {
2075
+ const [aMs, aSeq] = a.split("-").map(Number);
2076
+ const [bMs, bSeq] = b.split("-").map(Number);
2077
+ return aMs - bMs || aSeq - bSeq;
2078
+ }
2079
+ /**
2080
+ * Append one or more chunks, index the stream under its run, and notify
2081
+ * subscribers in one round trip. The publish could not be pipelined with the
2082
+ * append because it needs the entry ID `XADD` generates; Lua makes that
2083
+ * dependency server-side. Each chunk rides along in its message so subscribers
2084
+ * do not `XRANGE` per notification.
2085
+ *
2086
+ * A stream that already holds its eof marker is closed: the append is dropped
2087
+ * and nothing is published. Readers stop at the first eof anyway, so this only
2088
+ * keeps the invariant that the eof marker, when present, is the final entry.
2089
+ * `getInfo` relies on it to answer from `XLEN` and the tail entry alone, and a
2090
+ * producer retrying a lost-ACK `close()` would otherwise break it.
2091
+ *
2092
+ * KEYS[1] = stream key
2093
+ * KEYS[2] = streams-by-run key
2094
+ * ARGV[1] = notification channel
2095
+ * ARGV[2] = run ID
2096
+ * ARGV[3] = stream name
2097
+ * ARGV[4] = 'true' | 'false' (eof marker, applied to every chunk below)
2098
+ * ARGV[5..] = base64 chunk data, in write order
2099
+ * Returns: 1 if appended, 0 if the stream was already closed
2100
+ */
2101
+ const LUA_APPEND_AND_PUBLISH = `
2102
+ local streamKey = KEYS[1]
2103
+ local runIndexKey = KEYS[2]
2104
+ local channel = ARGV[1]
2105
+ local runId = ARGV[2]
2106
+ local streamId = ARGV[3]
2107
+ local eof = ARGV[4]
2108
+
2109
+ local tail = redis.call('XREVRANGE', streamKey, '+', '-', 'COUNT', 1)
2110
+ if #tail > 0 and tail[1][2][4] == 'true' then
2111
+ return 0
2112
+ end
2113
+
2114
+ local prevId = ''
2115
+ if #tail > 0 then
2116
+ prevId = tail[1][1]
2117
+ end
2118
+
2119
+ for i = 5, #ARGV do
2120
+ local data = ARGV[i]
2121
+ local entryId = redis.call('XADD', streamKey, '*', 'data', data, 'eof', eof)
2122
+ redis.call('PUBLISH', channel, cjson.encode({
2123
+ runId = runId,
2124
+ streamId = streamId,
2125
+ entryId = entryId,
2126
+ data = data,
2127
+ eof = eof == 'true',
2128
+ prevId = prevId
2129
+ }))
2130
+ prevId = entryId
2131
+ end
2132
+ redis.call('SADD', runIndexKey, streamId)
2133
+ return 1
2134
+ `;
2135
+ /** An XRANGE entry, by the field order `LUA_APPEND_AND_PUBLISH` writes: data, then eof. */
2136
+ function decodeEntry([id, fields]) {
2137
+ return {
2138
+ id,
2139
+ data: Buffer.from(fields[1], "base64"),
2140
+ eof: fields[3] === "true"
2141
+ };
2142
+ }
2143
+ /**
2144
+ * Create a streamer implementation using Redis Streams.
2145
+ *
2146
+ * Uses Redis auto-generated stream entry IDs (timestamp-sequence format)
2147
+ * instead of custom IDs, since Redis Streams require IDs in
2148
+ * `<millisecondsTime>-<sequenceNumber>` format.
2149
+ *
2150
+ * Key layout (every key is scoped to the run that owns the stream, so two runs
2151
+ * can use the same stream name without sharing chunks):
2152
+ * - `<prefix>stream:<runId>:<name>` Redis Stream of the chunks plus the eof marker
2153
+ * - `<prefix>streams:by_run:<runId>` Set of the run's stream names
2154
+ * - `<prefix>stream_notify` pub/sub channel carrying live chunks
2155
+ */
2156
+ function createStreamer(config) {
2157
+ const { redis, keyPrefix } = config;
2158
+ const events = new EventEmitter();
2159
+ const tails = /* @__PURE__ */ new Map();
2160
+ const withStreamMutex = (key, fn) => {
2161
+ const run = (tails.get(key) ?? Promise.resolve()).then(fn, fn);
2162
+ const tail = run.catch(() => {});
2163
+ tails.set(key, tail);
2164
+ tail.then(() => {
2165
+ if (tails.get(key) === tail) tails.delete(key);
2166
+ });
2167
+ return run;
2168
+ };
2169
+ redis.defineCommand("wfStreamAppend", {
2170
+ numberOfKeys: 2,
2171
+ lua: LUA_APPEND_AND_PUBLISH
2172
+ });
2173
+ const scripted = redis;
2174
+ const { streamKey, streamsByRunKey, streamChannel: STREAM_CHANNEL } = keys(keyPrefix);
2175
+ const emitterKey = (runId, name) => `strm:${runId}:${name}`;
2176
+ const subscriber = redis.duplicate();
2177
+ const subscriptionReady = subscriber.subscribe(STREAM_CHANNEL).then(() => {});
2178
+ const resync = new EventEmitter();
2179
+ resync.setMaxListeners(0);
2180
+ let subscriberConnected = false;
2181
+ subscriber.on("ready", () => {
2182
+ if (subscriberConnected) resync.emit("resync");
2183
+ subscriberConnected = true;
2184
+ });
2185
+ subscriber.on("message", async (channel, message) => {
2186
+ if (channel !== STREAM_CHANNEL) return;
2187
+ try {
2188
+ const parsed = parseStreamPublishMessage(message);
2189
+ if (!parsed) return;
2190
+ const key = emitterKey(parsed.runId, parsed.streamId);
2191
+ if (!events.listenerCount(key)) return;
2192
+ await withStreamMutex(key, async () => {
2193
+ events.emit(key, {
2194
+ id: parsed.entryId,
2195
+ data: Buffer.from(parsed.data, "base64"),
2196
+ eof: parsed.eof,
2197
+ prevId: parsed.prevId
2198
+ });
2199
+ });
2200
+ } catch (error) {
2201
+ console.error("Error processing stream notification:", error);
2202
+ }
2203
+ });
2204
+ const toBase64 = (chunk) => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)).toString("base64");
2205
+ const append = async (runId, name, eof, encodedChunks) => {
2206
+ await subscriptionReady;
2207
+ await scripted.wfStreamAppend(streamKey(runId, name), streamsByRunKey(runId), STREAM_CHANNEL, runId, name, eof ? "true" : "false", ...encodedChunks);
2208
+ };
2209
+ return {
2210
+ streams: {
2211
+ async write(_runId, name, chunk) {
2212
+ const runId = await _runId;
2213
+ await append(runId, name, false, [toBase64(chunk)]);
2214
+ },
2215
+ async writeMulti(_runId, name, chunks) {
2216
+ if (chunks.length === 0) return;
2217
+ const runId = await _runId;
2218
+ await append(runId, name, false, chunks.map(toBase64));
2219
+ },
2220
+ async close(_runId, name) {
2221
+ const runId = await _runId;
2222
+ await append(runId, name, true, [""]);
2223
+ },
2224
+ async get(runId, name, startIndex) {
2225
+ const key = emitterKey(runId, name);
2226
+ const cleanups = [];
2227
+ let cleanedUp = false;
2228
+ const cleanup = () => {
2229
+ if (cleanedUp) return;
2230
+ cleanedUp = true;
2231
+ for (const fn of cleanups) fn();
2232
+ };
2233
+ return new ReadableStream({
2234
+ async start(controller) {
2235
+ let lastEntryId = "";
2236
+ let offset = startIndex ?? 0;
2237
+ let buffer = [];
2238
+ function enqueue(msg) {
2239
+ if (cleanedUp) return;
2240
+ if (lastEntryId !== "" && compareStreamEntryIds(lastEntryId, msg.id) >= 0) return;
2241
+ lastEntryId = msg.id;
2242
+ if (offset > 0 && !msg.eof) {
2243
+ offset--;
2244
+ return;
2245
+ }
2246
+ if (msg.data.byteLength) controller.enqueue(new Uint8Array(msg.data));
2247
+ if (msg.eof) {
2248
+ cleanup();
2249
+ controller.close();
2250
+ }
2251
+ }
2252
+ let catchingUp = false;
2253
+ let again = false;
2254
+ async function catchUp() {
2255
+ if (cleanedUp || buffer) return;
2256
+ if (catchingUp) {
2257
+ again = true;
2258
+ return;
2259
+ }
2260
+ catchingUp = true;
2261
+ try {
2262
+ do {
2263
+ again = false;
2264
+ const entries = await redis.xrange(streamKey(runId, name), lastEntryId === "" ? "-" : `(${lastEntryId}`, "+");
2265
+ for (const entry of entries) enqueue(decodeEntry(entry));
2266
+ } while (again && !cleanedUp);
2267
+ } catch (error) {
2268
+ debug("Stream catch-up failed:", error);
2269
+ } finally {
2270
+ catchingUp = false;
2271
+ }
2272
+ }
2273
+ function deliverLive(data) {
2274
+ if (data.prevId !== void 0 && data.prevId !== lastEntryId) {
2275
+ catchUp();
2276
+ return;
2277
+ }
2278
+ enqueue(data);
2279
+ }
2280
+ function onData(data) {
2281
+ if (buffer) {
2282
+ buffer.push(data);
2283
+ return;
2284
+ }
2285
+ deliverLive(data);
2286
+ }
2287
+ events.on(key, onData);
2288
+ cleanups.push(() => {
2289
+ events.off(key, onData);
2290
+ });
2291
+ const parsedChunks = (await redis.xrange(streamKey(runId, name), "-", "+").catch((err) => {
2292
+ cleanup();
2293
+ throw err;
2294
+ })).map(decodeEntry);
2295
+ if (offset < 0) {
2296
+ const firstEof = parsedChunks.findIndex((chunk) => chunk.eof);
2297
+ const dataCount = firstEof === -1 ? parsedChunks.length : firstEof;
2298
+ offset = Math.max(0, dataCount + offset);
2299
+ }
2300
+ const buffered = buffer ?? [];
2301
+ buffer = null;
2302
+ for (const chunk of parsedChunks) enqueue(chunk);
2303
+ for (const chunk of buffered) deliverLive(chunk);
2304
+ resync.on("resync", catchUp);
2305
+ const timer = setInterval(() => void catchUp(), CATCH_UP_INTERVAL_MS);
2306
+ timer.unref();
2307
+ cleanups.push(() => {
2308
+ resync.off("resync", catchUp);
2309
+ clearInterval(timer);
2310
+ });
2311
+ await catchUp();
2312
+ },
2313
+ cancel() {
2314
+ cleanup();
2315
+ }
2316
+ });
2317
+ },
2318
+ async list(runId) {
2319
+ return await redis.smembers(streamsByRunKey(runId)) ?? [];
2320
+ },
2321
+ async getChunks(runId, name, options) {
2322
+ const limit = Math.min(options?.limit ?? 100, 1e3);
2323
+ let dataIndex = 0;
2324
+ let start = "-";
2325
+ if (options?.cursor) try {
2326
+ const decoded = JSON.parse(Buffer.from(options.cursor, "base64").toString("utf-8"));
2327
+ if (typeof decoded.i === "number") dataIndex = decoded.i;
2328
+ if (typeof decoded.id === "string") start = `(${decoded.id}`;
2329
+ } catch {
2330
+ dataIndex = 0;
2331
+ start = "-";
2332
+ }
2333
+ const entries = await redis.xrange(streamKey(runId, name), start, "+", "COUNT", limit + 1);
2334
+ const data = [];
2335
+ let done = false;
2336
+ let hasMore = false;
2337
+ let lastId = null;
2338
+ for (const entry of entries) {
2339
+ const { id, data: bytes, eof } = decodeEntry(entry);
2340
+ if (eof) {
2341
+ done = true;
2342
+ break;
2343
+ }
2344
+ if (data.length >= limit) {
2345
+ hasMore = true;
2346
+ break;
2347
+ }
2348
+ data.push({
2349
+ index: dataIndex,
2350
+ data: new Uint8Array(bytes)
2351
+ });
2352
+ dataIndex++;
2353
+ lastId = id;
2354
+ }
2355
+ return {
2356
+ data,
2357
+ cursor: hasMore && lastId ? Buffer.from(JSON.stringify({
2358
+ i: dataIndex,
2359
+ id: lastId
2360
+ })).toString("base64") : null,
2361
+ hasMore,
2362
+ done
2363
+ };
2364
+ },
2365
+ async getInfo(runId, name) {
2366
+ const key = streamKey(runId, name);
2367
+ const [length, tail] = await Promise.all([redis.xlen(key), redis.xrevrange(key, "+", "-", "COUNT", 1)]);
2368
+ const done = tail.length > 0 && tail[0][1][3] === "true";
2369
+ return {
2370
+ tailIndex: length - (done ? 1 : 0) - 1,
2371
+ done
2372
+ };
2373
+ }
2374
+ },
2375
+ async close() {
2376
+ await subscriber.quit();
2377
+ }
2378
+ };
2379
+ }
2380
+ // src/world.ts
2381
+ /**
2382
+ * A world on Redis: storage, streams and retention are the same for every
2383
+ * queue; `createQueue` supplies the queue. `config` is laid over `env`, so an
2384
+ * option the caller leaves out still comes from the environment.
2385
+ */
2386
+ function createRedisBackedWorld(config, world) {
2387
+ const merged = { ...world.env };
2388
+ for (const [key, value] of Object.entries(config)) if (value !== void 0) merged[key] = value;
2389
+ const cfg = resolveConfig(merged);
2390
+ const autoPipelining = cfg.enableAutoPipelining;
2391
+ validateRetention(cfg.retention);
2392
+ const redis = typeof cfg.redis === "string" ? new Redis(cfg.redis, { enableAutoPipelining: autoPipelining }) : new Redis({
2393
+ enableAutoPipelining: autoPipelining,
2394
+ ...cfg.redis
2395
+ });
2396
+ const { keyPrefix } = cfg;
2397
+ const reaper = hasRetention(cfg.retention) ? createReaper({
2398
+ redis,
2399
+ keyPrefix,
2400
+ retention: cfg.retention
2401
+ }) : void 0;
2402
+ const storageConfig = {
2403
+ redis,
2404
+ keyPrefix,
2405
+ maxEventsPerRun: cfg.maxEventsPerRun
2406
+ };
2407
+ const storage = {
2408
+ runs: createRunsStorage(storageConfig),
2409
+ events: createEventsStorage(storageConfig),
2410
+ hooks: createHooksStorage(storageConfig),
2411
+ steps: createStepsStorage(storageConfig)
2412
+ };
2413
+ const queue = world.createQueue(redis, cfg, { runHasStarted: async (runId) => {
2414
+ try {
2415
+ return (await storage.runs.get(runId, { resolveData: "none" })).status !== "pending";
2416
+ } catch (error) {
2417
+ if (WorkflowRunNotFoundError.is(error)) return false;
2418
+ throw error;
2419
+ }
2420
+ } });
2421
+ const streamer = createStreamer({
2422
+ redis,
2423
+ keyPrefix
2424
+ });
2425
+ return {
2426
+ ...storage,
2427
+ ...streamer,
2428
+ ...queue,
2429
+ specVersion: mintedSpecVersion(),
2430
+ createRunId,
2431
+ async start() {
2432
+ await queue.start();
2433
+ reaper?.start();
2434
+ await reenqueueActiveRuns(storage.runs, (queueName, message, opts) => queue.queue(queueName, message, {
2435
+ ...opts,
2436
+ idempotencyKey: `recover:${message.runId}`
2437
+ }), world.label);
2438
+ },
2439
+ async sweepRetention() {
2440
+ return reaper ? reaper.sweep() : 0;
2441
+ },
2442
+ async close() {
2443
+ await reaper?.stop();
2444
+ await queue.close();
2445
+ await streamer.close();
2446
+ await redis.quit();
2447
+ }
2448
+ };
2449
+ }
2450
+ export { createDebugLogger as a, debug as i, createWorldQueue as n, retryDelayMs as r, createRedisBackedWorld as t };
2451
+
2452
+ //# sourceMappingURL=world-783VJfKL.js.map