@workflow/world-local 5.0.0-beta.4 → 5.0.0-beta.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAa,KAAK,KAAK,EAAkB,MAAM,iBAAiB,CAAC;AAKxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAiD1C,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhE,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG;IAC/B,kDAAkD;IAClD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,+EAA+E;IAC/E,eAAe,CACb,MAAM,EAAE,aAAa,GAAG,iBAAiB,EACzC,OAAO,EAAE,aAAa,GACrB,IAAI,CAAC;CACT,CAAC;AAeF,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,UAAU,CAoP/D"}
1
+ {"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAa,KAAK,KAAK,EAAkB,MAAM,iBAAiB,CAAC;AAKxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAiD1C,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhE,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG;IAC/B,kDAAkD;IAClD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,+EAA+E;IAC/E,eAAe,CACb,MAAM,EAAE,aAAa,GAAG,iBAAiB,EACzC,OAAO,EAAE,aAAa,GACrB,IAAI,CAAC;CACT,CAAC;AAuCF,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,UAAU,CAoQ/D"}
package/dist/queue.js CHANGED
@@ -45,6 +45,22 @@ const MAX_SAFE_TIMEOUT_MS = 2147483647;
45
45
  const DEFAULT_CONCURRENCY_LIMIT = 1000;
46
46
  const WORKFLOW_LOCAL_QUEUE_CONCURRENCY = parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY ?? '0', 10) ||
47
47
  DEFAULT_CONCURRENCY_LIMIT;
48
+ const DETACHED_ARRAYBUFFER_ERROR = 'Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer';
49
+ const PROXY_HANDLER_DOCS_URL = 'https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler';
50
+ function isDetachedArrayBufferQueueError(error) {
51
+ let current = error;
52
+ const visited = new Set();
53
+ while (current && typeof current === 'object' && !visited.has(current)) {
54
+ visited.add(current);
55
+ if ('message' in current &&
56
+ typeof current.message === 'string' &&
57
+ current.message.includes(DETACHED_ARRAYBUFFER_ERROR)) {
58
+ return true;
59
+ }
60
+ current = 'cause' in current ? current.cause : undefined;
61
+ }
62
+ return false;
63
+ }
48
64
  function getQueueRoute(queueName) {
49
65
  if (queueName.startsWith('__wkf_step_')) {
50
66
  return { pathname: 'step', prefix: '__wkf_step_' };
@@ -185,7 +201,21 @@ export function createQueue(config) {
185
201
  // These are expected and should not cause unhandled rejection warnings
186
202
  const isAbortError = err?.name === 'AbortError' || err?.name === 'ResponseAborted';
187
203
  if (!isAbortError) {
188
- console.error('[local world] Queue operation failed:', err);
204
+ if (isDetachedArrayBufferQueueError(err)) {
205
+ console.error(`[local world] Queue operation failed: detected "${DETACHED_ARRAYBUFFER_ERROR}". ` +
206
+ "This usually means a Next.js proxy/middleware consumed Workflow's internal " +
207
+ 'request before the executor could read it. Exclude `/.well-known/workflow/*` ' +
208
+ `from your matcher. See ${PROXY_HANDLER_DOCS_URL}`, {
209
+ queueName,
210
+ messageId,
211
+ ...(runId && { runId }),
212
+ ...(stepId && { stepId }),
213
+ originalError: err,
214
+ });
215
+ }
216
+ else {
217
+ console.error('[local world] Queue operation failed:', err);
218
+ }
189
219
  }
190
220
  })
191
221
  .finally(() => {
package/dist/queue.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"queue.js","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAc,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAE3B,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C;;;;GAIG;AACH,MAAM,kBAAkB;IACb,WAAW,GAAG,kBAAkB,CAAC;IAE1C,SAAS,CAAC,KAAc;QACtB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,MAAkC;QAClD,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;QAClC,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,IAAI,KAAK;gBAAE,MAAM,CAAC,IAAI,CA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gBAC3C,CAAC;gBAED,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;YACrC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;YACvD,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,eAAe,GAA6B,KAAK,IAAI,EAAE;QAC3D,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;QAC3C,OAAO,aAAa,WAAW,CAAC,OAAO,EAAE,CAAC;IAC5C,CAAC,CAAC;IAEF,OAAO;QACL,KAAK;QACL,kBAAkB;QAClB,eAAe;QACf,eAAe,CACb,MAAyC,EACzC,OAAsB;YAEtB,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;QAC1B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { setTimeout } from 'node:timers/promises';\nimport type { Transport } from '@vercel/queue';\nimport { MessageId, type Queue, ValidQueueName } from '@workflow/world';\nimport { Sema } from 'async-sema';\nimport { monotonicFactory } from 'ulid';\nimport { Agent } from 'undici';\nimport { z } from 'zod/v4';\nimport type { Config } from './config.js';\nimport { resolveBaseUrl } from './config.js';\nimport { jsonReplacer, jsonReviver } from './fs.js';\nimport { getPackageInfo } from './init.js';\n\n/**\n * JSON transport that preserves Uint8Array values using the same\n * replacer/reviver that world-local uses for filesystem storage.\n * Uint8Array → { __type: 'Uint8Array', data: '<base64>' } in JSON.\n */\nclass TypedJsonTransport implements Transport<unknown> {\n readonly contentType = 'application/json';\n\n serialize(value: unknown): Buffer {\n return Buffer.from(JSON.stringify(value, jsonReplacer));\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const chunks: Uint8Array[] = [];\n const reader = stream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n const text = Buffer.concat(chunks).toString();\n return JSON.parse(text, jsonReviver);\n }\n}\n\n// For local queue, there is no technical limit on the message visibility lifespan,\n// but the environment variable can be used for testing purposes to set a max visibility limit.\nconst LOCAL_QUEUE_MAX_VISIBILITY =\n parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY ?? '0', 10) ||\n Infinity;\n\n// Maximum safe delay for setTimeout in Node.js (2^31 - 1 milliseconds ≈ 24.85 days)\n// Larger values cause \"TimeoutOverflowWarning: X does not fit into a 32-bit signed integer\"\n// When the clamped timeout fires, the handler will recalculate remaining time from\n// persistent state and return another timeoutSeconds if needed.\nconst MAX_SAFE_TIMEOUT_MS = 2147483647;\n\n// The local workers share the same Node.js process and event loop,\n// so we need to limit concurrency to avoid overwhelming the system.\nconst DEFAULT_CONCURRENCY_LIMIT = 1000;\nconst WORKFLOW_LOCAL_QUEUE_CONCURRENCY =\n parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY ?? '0', 10) ||\n DEFAULT_CONCURRENCY_LIMIT;\n\nexport type DirectHandler = (req: Request) => Promise<Response>;\n\nexport type LocalQueue = Queue & {\n /** Close the HTTP agent and release resources. */\n close(): Promise<void>;\n /** Register a direct in-process handler for a queue prefix, bypassing HTTP. */\n registerHandler(\n prefix: '__wkf_step_' | '__wkf_workflow_',\n handler: DirectHandler\n ): void;\n};\n\nfunction getQueueRoute(queueName: ValidQueueName): {\n pathname: 'flow' | 'step';\n prefix: '__wkf_step_' | '__wkf_workflow_';\n} {\n if (queueName.startsWith('__wkf_step_')) {\n return { pathname: 'step', prefix: '__wkf_step_' };\n }\n if (queueName.startsWith('__wkf_workflow_')) {\n return { pathname: 'flow', prefix: '__wkf_workflow_' };\n }\n throw new Error('Unknown queue name prefix');\n}\n\nexport function createQueue(config: Partial<Config>): LocalQueue {\n // Create a custom agent optimized for high-concurrency local workflows:\n // - headersTimeout: 0 allows long-running steps\n // - connections: 1000 allows many parallel connections to the same host\n // - pipelining: 1 (default) for HTTP/1.1 compatibility\n // - keepAliveTimeout: 30s keeps connections warm for rapid step execution\n const httpAgent = new Agent({\n headersTimeout: 0,\n connections: 1000,\n keepAliveTimeout: 30_000,\n });\n const transport = new TypedJsonTransport();\n const generateId = monotonicFactory();\n const semaphore = new Sema(WORKFLOW_LOCAL_QUEUE_CONCURRENCY);\n\n /**\n * holds inflight messages by idempotency key to ensure\n * that we don't queue the same message multiple times\n */\n const inflightMessages = new Map<string, MessageId>();\n /** Direct in-process handlers by queue prefix, bypassing HTTP when set. */\n const directHandlers = new Map<string, DirectHandler>();\n\n const queue: Queue['queue'] = async (queueName, message, opts) => {\n const cleanup = [] as (() => void)[];\n\n if (opts?.idempotencyKey) {\n const existing = inflightMessages.get(opts.idempotencyKey);\n if (existing) {\n return { messageId: existing };\n }\n }\n\n const body = transport.serialize(message);\n const { pathname, prefix } = getQueueRoute(queueName);\n const messageId = MessageId.parse(`msg_${generateId()}`);\n\n // Extract identifiers from the message for structured logging.\n // Workflow messages have `runId`, step messages have `workflowRunId` + `stepId`.\n const msg = message as Record<string, unknown>;\n const runId = (msg.runId ?? msg.workflowRunId ?? undefined) as\n | string\n | undefined;\n const stepId = (msg.stepId ?? undefined) as string | undefined;\n\n if (opts?.idempotencyKey) {\n const key = opts.idempotencyKey;\n inflightMessages.set(key, messageId);\n cleanup.push(() => {\n inflightMessages.delete(key);\n });\n }\n\n (async () => {\n const token = semaphore.tryAcquire();\n if (!token) {\n console.warn(\n `[world-local]: concurrency limit (${WORKFLOW_LOCAL_QUEUE_CONCURRENCY}) reached, waiting for queue to free up`\n );\n await semaphore.acquire();\n }\n // Safety limit to prevent infinite loops in the local queue.\n // The actual max delivery enforcement happens in the workflow/step handlers\n // (at MAX_QUEUE_DELIVERIES = 48), so this just needs to be comfortably higher.\n const MAX_LOCAL_SAFETY_LIMIT = 256;\n try {\n for (let attempt = 0; attempt < MAX_LOCAL_SAFETY_LIMIT; attempt++) {\n const headers: Record<string, string> = {\n ...opts?.headers,\n 'content-type': 'application/json',\n 'x-vqs-queue-name': queueName,\n 'x-vqs-message-id': messageId,\n 'x-vqs-message-attempt': String(attempt + 1),\n };\n const directHandler = directHandlers.get(prefix);\n let response: Response;\n\n if (directHandler) {\n const req = new Request(\n `http://localhost/.well-known/workflow/v1/${pathname}`,\n {\n method: 'POST',\n headers,\n body,\n }\n );\n response = await directHandler(req);\n } else {\n const baseUrl = await resolveBaseUrl(config);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici v7 dispatcher types don't match @types/node's RequestInit\n response = await fetch(\n `${baseUrl}/.well-known/workflow/v1/${pathname}`,\n {\n method: 'POST',\n duplex: 'half',\n dispatcher: httpAgent,\n headers,\n body,\n } as any\n );\n }\n\n const text = await response.text();\n\n if (response.ok) {\n try {\n const timeoutSeconds = Number(JSON.parse(text).timeoutSeconds);\n if (Number.isFinite(timeoutSeconds) && timeoutSeconds >= 0) {\n // Clamp to MAX_SAFE_TIMEOUT_MS to avoid Node.js setTimeout overflow warning.\n // When this fires early, the handler recalculates remaining time from\n // persistent state and returns another timeoutSeconds if needed.\n if (timeoutSeconds > 0) {\n const timeoutMs = Math.min(\n timeoutSeconds * 1000,\n MAX_SAFE_TIMEOUT_MS\n );\n await setTimeout(timeoutMs);\n }\n continue;\n }\n } catch {}\n return;\n }\n\n console.error(\n `[world-local] Queue message failed (attempt ${attempt + 1}, HTTP ${response.status})`,\n {\n queueName,\n messageId,\n ...(runId && { runId }),\n ...(stepId && { stepId }),\n handlerError: text,\n }\n );\n\n // 5s linear backoff to approximate VQS retry timing in local dev.\n // VQS uses 5s linear for attempts 1–32, then exponential, but for\n // local dev linear 5s is sufficient — the handler enforces the real\n // cap at MAX_QUEUE_DELIVERIES (48) which keeps total time under ~4min.\n await setTimeout(5000);\n }\n\n console.error(\n `[world-local] Queue message exhausted safety limit (${MAX_LOCAL_SAFETY_LIMIT} attempts)`,\n {\n queueName,\n messageId,\n ...(runId && { runId }),\n ...(stepId && { stepId }),\n }\n );\n } finally {\n semaphore.release();\n }\n })()\n .catch((err) => {\n // Silently ignore client disconnect errors (e.g., browser refresh during streaming)\n // These are expected and should not cause unhandled rejection warnings\n const isAbortError =\n err?.name === 'AbortError' || err?.name === 'ResponseAborted';\n if (!isAbortError) {\n console.error('[local world] Queue operation failed:', err);\n }\n })\n .finally(() => {\n for (const fn of cleanup) {\n fn();\n }\n });\n\n return { messageId };\n };\n\n const HeaderParser = z.object({\n 'x-vqs-queue-name': ValidQueueName,\n 'x-vqs-message-id': MessageId,\n 'x-vqs-message-attempt': z.coerce.number(),\n });\n\n const createQueueHandler: Queue['createQueueHandler'] = (prefix, handler) => {\n return async (req) => {\n const headers = HeaderParser.safeParse(Object.fromEntries(req.headers));\n\n if (!headers.success || !req.body) {\n return Response.json(\n {\n error: !req.body\n ? 'Missing request body'\n : 'Missing required headers',\n },\n { status: 400 }\n );\n }\n\n const queueName = headers.data['x-vqs-queue-name'];\n const messageId = headers.data['x-vqs-message-id'];\n const attempt = headers.data['x-vqs-message-attempt'];\n\n if (!queueName.startsWith(prefix)) {\n return Response.json({ error: 'Unhandled queue' }, { status: 400 });\n }\n\n const body = await new TypedJsonTransport().deserialize(req.body);\n try {\n const result = await handler(body, { attempt, queueName, messageId });\n\n let timeoutSeconds: number | null = null;\n if (typeof result?.timeoutSeconds === 'number') {\n timeoutSeconds = Math.min(\n result.timeoutSeconds,\n LOCAL_QUEUE_MAX_VISIBILITY\n );\n }\n\n if (timeoutSeconds != null) {\n return Response.json({ timeoutSeconds });\n }\n\n return Response.json({ ok: true });\n } catch (error) {\n return Response.json(String(error), { status: 500 });\n }\n };\n };\n\n const getDeploymentId: Queue['getDeploymentId'] = async () => {\n const packageInfo = await getPackageInfo();\n return `dpl_local@${packageInfo.version}`;\n };\n\n return {\n queue,\n createQueueHandler,\n getDeploymentId,\n registerHandler(\n prefix: '__wkf_step_' | '__wkf_workflow_',\n handler: DirectHandler\n ) {\n directHandlers.set(prefix, handler);\n },\n async close() {\n await httpAgent.close();\n },\n };\n}\n"]}
1
+ {"version":3,"file":"queue.js","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAc,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAE3B,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C;;;;GAIG;AACH,MAAM,kBAAkB;IACb,WAAW,GAAG,kBAAkB,CAAC;IAE1C,SAAS,CAAC,KAAc;QACtB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,MAAkC;QAClD,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;QAClC,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,IAAI,KAAK;gBAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;QACD,MAAM,IAAI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MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;YACvD,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,eAAe,GAA6B,KAAK,IAAI,EAAE;QAC3D,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;QAC3C,OAAO,aAAa,WAAW,CAAC,OAAO,EAAE,CAAC;IAC5C,CAAC,CAAC;IAEF,OAAO;QACL,KAAK;QACL,kBAAkB;QAClB,eAAe;QACf,eAAe,CACb,MAAyC,EACzC,OAAsB;YAEtB,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;QAC1B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { setTimeout } from 'node:timers/promises';\nimport type { Transport } from '@vercel/queue';\nimport { MessageId, type Queue, ValidQueueName } from '@workflow/world';\nimport { Sema } from 'async-sema';\nimport { monotonicFactory } from 'ulid';\nimport { Agent } from 'undici';\nimport { z } from 'zod/v4';\nimport type { Config } from './config.js';\nimport { resolveBaseUrl } from './config.js';\nimport { jsonReplacer, jsonReviver } from './fs.js';\nimport { getPackageInfo } from './init.js';\n\n/**\n * JSON transport that preserves Uint8Array values using the same\n * replacer/reviver that world-local uses for filesystem storage.\n * Uint8Array → { __type: 'Uint8Array', data: '<base64>' } in JSON.\n */\nclass TypedJsonTransport implements Transport<unknown> {\n readonly contentType = 'application/json';\n\n serialize(value: unknown): Buffer {\n return Buffer.from(JSON.stringify(value, jsonReplacer));\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const chunks: Uint8Array[] = [];\n const reader = stream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n const text = Buffer.concat(chunks).toString();\n return JSON.parse(text, jsonReviver);\n }\n}\n\n// For local queue, there is no technical limit on the message visibility lifespan,\n// but the environment variable can be used for testing purposes to set a max visibility limit.\nconst LOCAL_QUEUE_MAX_VISIBILITY =\n parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY ?? '0', 10) ||\n Infinity;\n\n// Maximum safe delay for setTimeout in Node.js (2^31 - 1 milliseconds ≈ 24.85 days)\n// Larger values cause \"TimeoutOverflowWarning: X does not fit into a 32-bit signed integer\"\n// When the clamped timeout fires, the handler will recalculate remaining time from\n// persistent state and return another timeoutSeconds if needed.\nconst MAX_SAFE_TIMEOUT_MS = 2147483647;\n\n// The local workers share the same Node.js process and event loop,\n// so we need to limit concurrency to avoid overwhelming the system.\nconst DEFAULT_CONCURRENCY_LIMIT = 1000;\nconst WORKFLOW_LOCAL_QUEUE_CONCURRENCY =\n parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY ?? '0', 10) ||\n DEFAULT_CONCURRENCY_LIMIT;\n\nexport type DirectHandler = (req: Request) => Promise<Response>;\n\nexport type LocalQueue = Queue & {\n /** Close the HTTP agent and release resources. */\n close(): Promise<void>;\n /** Register a direct in-process handler for a queue prefix, bypassing HTTP. */\n registerHandler(\n prefix: '__wkf_step_' | '__wkf_workflow_',\n handler: DirectHandler\n ): void;\n};\n\nconst DETACHED_ARRAYBUFFER_ERROR =\n 'Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer';\nconst PROXY_HANDLER_DOCS_URL =\n 'https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler';\n\nfunction isDetachedArrayBufferQueueError(error: unknown): boolean {\n let current = error;\n const visited = new Set<unknown>();\n\n while (current && typeof current === 'object' && !visited.has(current)) {\n visited.add(current);\n if (\n 'message' in current &&\n typeof current.message === 'string' &&\n current.message.includes(DETACHED_ARRAYBUFFER_ERROR)\n ) {\n return true;\n }\n current = 'cause' in current ? current.cause : undefined;\n }\n\n return false;\n}\n\nfunction getQueueRoute(queueName: ValidQueueName): {\n pathname: 'flow' | 'step';\n prefix: '__wkf_step_' | '__wkf_workflow_';\n} {\n if (queueName.startsWith('__wkf_step_')) {\n return { pathname: 'step', prefix: '__wkf_step_' };\n }\n if (queueName.startsWith('__wkf_workflow_')) {\n return { pathname: 'flow', prefix: '__wkf_workflow_' };\n }\n throw new Error('Unknown queue name prefix');\n}\n\nexport function createQueue(config: Partial<Config>): LocalQueue {\n // Create a custom agent optimized for high-concurrency local workflows:\n // - headersTimeout: 0 allows long-running steps\n // - connections: 1000 allows many parallel connections to the same host\n // - pipelining: 1 (default) for HTTP/1.1 compatibility\n // - keepAliveTimeout: 30s keeps connections warm for rapid step execution\n const httpAgent = new Agent({\n headersTimeout: 0,\n connections: 1000,\n keepAliveTimeout: 30_000,\n });\n const transport = new TypedJsonTransport();\n const generateId = monotonicFactory();\n const semaphore = new Sema(WORKFLOW_LOCAL_QUEUE_CONCURRENCY);\n\n /**\n * holds inflight messages by idempotency key to ensure\n * that we don't queue the same message multiple times\n */\n const inflightMessages = new Map<string, MessageId>();\n /** Direct in-process handlers by queue prefix, bypassing HTTP when set. */\n const directHandlers = new Map<string, DirectHandler>();\n\n const queue: Queue['queue'] = async (queueName, message, opts) => {\n const cleanup = [] as (() => void)[];\n\n if (opts?.idempotencyKey) {\n const existing = inflightMessages.get(opts.idempotencyKey);\n if (existing) {\n return { messageId: existing };\n }\n }\n\n const body = transport.serialize(message);\n const { pathname, prefix } = getQueueRoute(queueName);\n const messageId = MessageId.parse(`msg_${generateId()}`);\n\n // Extract identifiers from the message for structured logging.\n // Workflow messages have `runId`, step messages have `workflowRunId` + `stepId`.\n const msg = message as Record<string, unknown>;\n const runId = (msg.runId ?? msg.workflowRunId ?? undefined) as\n | string\n | undefined;\n const stepId = (msg.stepId ?? undefined) as string | undefined;\n\n if (opts?.idempotencyKey) {\n const key = opts.idempotencyKey;\n inflightMessages.set(key, messageId);\n cleanup.push(() => {\n inflightMessages.delete(key);\n });\n }\n\n (async () => {\n const token = semaphore.tryAcquire();\n if (!token) {\n console.warn(\n `[world-local]: concurrency limit (${WORKFLOW_LOCAL_QUEUE_CONCURRENCY}) reached, waiting for queue to free up`\n );\n await semaphore.acquire();\n }\n // Safety limit to prevent infinite loops in the local queue.\n // The actual max delivery enforcement happens in the workflow/step handlers\n // (at MAX_QUEUE_DELIVERIES = 48), so this just needs to be comfortably higher.\n const MAX_LOCAL_SAFETY_LIMIT = 256;\n try {\n for (let attempt = 0; attempt < MAX_LOCAL_SAFETY_LIMIT; attempt++) {\n const headers: Record<string, string> = {\n ...opts?.headers,\n 'content-type': 'application/json',\n 'x-vqs-queue-name': queueName,\n 'x-vqs-message-id': messageId,\n 'x-vqs-message-attempt': String(attempt + 1),\n };\n const directHandler = directHandlers.get(prefix);\n let response: Response;\n\n if (directHandler) {\n const req = new Request(\n `http://localhost/.well-known/workflow/v1/${pathname}`,\n {\n method: 'POST',\n headers,\n body,\n }\n );\n response = await directHandler(req);\n } else {\n const baseUrl = await resolveBaseUrl(config);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici v7 dispatcher types don't match @types/node's RequestInit\n response = await fetch(\n `${baseUrl}/.well-known/workflow/v1/${pathname}`,\n {\n method: 'POST',\n duplex: 'half',\n dispatcher: httpAgent,\n headers,\n body,\n } as any\n );\n }\n\n const text = await response.text();\n\n if (response.ok) {\n try {\n const timeoutSeconds = Number(JSON.parse(text).timeoutSeconds);\n if (Number.isFinite(timeoutSeconds) && timeoutSeconds >= 0) {\n // Clamp to MAX_SAFE_TIMEOUT_MS to avoid Node.js setTimeout overflow warning.\n // When this fires early, the handler recalculates remaining time from\n // persistent state and returns another timeoutSeconds if needed.\n if (timeoutSeconds > 0) {\n const timeoutMs = Math.min(\n timeoutSeconds * 1000,\n MAX_SAFE_TIMEOUT_MS\n );\n await setTimeout(timeoutMs);\n }\n continue;\n }\n } catch {}\n return;\n }\n\n console.error(\n `[world-local] Queue message failed (attempt ${attempt + 1}, HTTP ${response.status})`,\n {\n queueName,\n messageId,\n ...(runId && { runId }),\n ...(stepId && { stepId }),\n handlerError: text,\n }\n );\n\n // 5s linear backoff to approximate VQS retry timing in local dev.\n // VQS uses 5s linear for attempts 1–32, then exponential, but for\n // local dev linear 5s is sufficient — the handler enforces the real\n // cap at MAX_QUEUE_DELIVERIES (48) which keeps total time under ~4min.\n await setTimeout(5000);\n }\n\n console.error(\n `[world-local] Queue message exhausted safety limit (${MAX_LOCAL_SAFETY_LIMIT} attempts)`,\n {\n queueName,\n messageId,\n ...(runId && { runId }),\n ...(stepId && { stepId }),\n }\n );\n } finally {\n semaphore.release();\n }\n })()\n .catch((err) => {\n // Silently ignore client disconnect errors (e.g., browser refresh during streaming)\n // These are expected and should not cause unhandled rejection warnings\n const isAbortError =\n err?.name === 'AbortError' || err?.name === 'ResponseAborted';\n if (!isAbortError) {\n if (isDetachedArrayBufferQueueError(err)) {\n console.error(\n `[local world] Queue operation failed: detected \"${DETACHED_ARRAYBUFFER_ERROR}\". ` +\n \"This usually means a Next.js proxy/middleware consumed Workflow's internal \" +\n 'request before the executor could read it. Exclude `/.well-known/workflow/*` ' +\n `from your matcher. See ${PROXY_HANDLER_DOCS_URL}`,\n {\n queueName,\n messageId,\n ...(runId && { runId }),\n ...(stepId && { stepId }),\n originalError: err,\n }\n );\n } else {\n console.error('[local world] Queue operation failed:', err);\n }\n }\n })\n .finally(() => {\n for (const fn of cleanup) {\n fn();\n }\n });\n\n return { messageId };\n };\n\n const HeaderParser = z.object({\n 'x-vqs-queue-name': ValidQueueName,\n 'x-vqs-message-id': MessageId,\n 'x-vqs-message-attempt': z.coerce.number(),\n });\n\n const createQueueHandler: Queue['createQueueHandler'] = (prefix, handler) => {\n return async (req) => {\n const headers = HeaderParser.safeParse(Object.fromEntries(req.headers));\n\n if (!headers.success || !req.body) {\n return Response.json(\n {\n error: !req.body\n ? 'Missing request body'\n : 'Missing required headers',\n },\n { status: 400 }\n );\n }\n\n const queueName = headers.data['x-vqs-queue-name'];\n const messageId = headers.data['x-vqs-message-id'];\n const attempt = headers.data['x-vqs-message-attempt'];\n\n if (!queueName.startsWith(prefix)) {\n return Response.json({ error: 'Unhandled queue' }, { status: 400 });\n }\n\n const body = await new TypedJsonTransport().deserialize(req.body);\n try {\n const result = await handler(body, { attempt, queueName, messageId });\n\n let timeoutSeconds: number | null = null;\n if (typeof result?.timeoutSeconds === 'number') {\n timeoutSeconds = Math.min(\n result.timeoutSeconds,\n LOCAL_QUEUE_MAX_VISIBILITY\n );\n }\n\n if (timeoutSeconds != null) {\n return Response.json({ timeoutSeconds });\n }\n\n return Response.json({ ok: true });\n } catch (error) {\n return Response.json(String(error), { status: 500 });\n }\n };\n };\n\n const getDeploymentId: Queue['getDeploymentId'] = async () => {\n const packageInfo = await getPackageInfo();\n return `dpl_local@${packageInfo.version}`;\n };\n\n return {\n queue,\n createQueueHandler,\n getDeploymentId,\n registerHandler(\n prefix: '__wkf_step_' | '__wkf_workflow_',\n handler: DirectHandler\n ) {\n directHandlers.set(prefix, handler);\n },\n async close() {\n await httpAgent.close();\n },\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"events-storage.d.ts","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAMV,OAAO,EAGR,MAAM,iBAAiB,CAAC;AAsFzB;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CAmjCnB"}
1
+ {"version":3,"file":"events-storage.d.ts","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAMV,OAAO,EAGR,MAAM,iBAAiB,CAAC;AAyGzB;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CAwjCnB"}
@@ -2,8 +2,9 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { EntityConflictError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError, } from '@workflow/errors';
4
4
  import { EventSchema, HookSchema, isLegacySpecVersion, requiresNewerWorld, SPEC_VERSION_CURRENT, StepSchema, validateUlidTimestamp, WaitSchema, WorkflowRunSchema, } from '@workflow/world';
5
+ import { z } from 'zod';
5
6
  import { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';
6
- import { assertSafeEntityId, deleteJSON, jsonReplacer, listJSONFiles, paginatedFileSystemQuery, readJSONWithFallback, resolveWithinBase, taggedPath, writeExclusive, writeJSON, } from '../fs.js';
7
+ import { assertSafeEntityId, deleteJSON, jsonReplacer, listJSONFiles, paginatedFileSystemQuery, readJSON, readJSONWithFallback, resolveWithinBase, taggedPath, writeExclusive, writeJSON, } from '../fs.js';
7
8
  import { stripEventDataRefs } from './filters.js';
8
9
  import { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';
9
10
  import { deleteAllHooksForRun } from './hooks-storage.js';
@@ -21,6 +22,20 @@ import { handleLegacyEvent } from './legacy.js';
21
22
  * step are rejected.
22
23
  */
23
24
  const stepLocks = new Map();
25
+ const HookTokenClaimSchema = z.object({
26
+ runId: z.string(),
27
+ });
28
+ async function readHookTokenClaim(constraintPath) {
29
+ try {
30
+ return await readJSON(constraintPath, HookTokenClaimSchema);
31
+ }
32
+ catch (error) {
33
+ if (error instanceof SyntaxError || error instanceof z.ZodError) {
34
+ return null;
35
+ }
36
+ throw error;
37
+ }
38
+ }
24
39
  function withStepLock(key, fn) {
25
40
  const prev = stepLocks.get(key);
26
41
  const taskBox = {};
@@ -618,6 +633,7 @@ export function createEventsStorage(basedir, tag) {
618
633
  runId: effectiveRunId,
619
634
  }));
620
635
  if (!tokenClaimed) {
636
+ const existingClaim = await readHookTokenClaim(constraintPath);
621
637
  // Create hook_conflict event instead of hook_created
622
638
  // This allows the workflow to continue and fail gracefully when the hook is awaited
623
639
  const conflictEvent = {
@@ -625,6 +641,9 @@ export function createEventsStorage(basedir, tag) {
625
641
  correlationId: data.correlationId,
626
642
  eventData: {
627
643
  token: hookData.token,
644
+ ...(existingClaim
645
+ ? { conflictingRunId: existingClaim.runId }
646
+ : {}),
628
647
  },
629
648
  runId: effectiveRunId,
630
649
  eventId,
@@ -1 +1 @@
1
- {"version":3,"file":"events-storage.js","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EACL,WAAW,EACX,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,oBAAoB,EACpB,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,SAAS,GACV,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;GAWG;AACH,MAAM,SAAS,GAAG,IAAI,GAAG,EAA4B,CAAC;AAEtD,SAAS,YAAY,CAAI,GAAW,EAAE,EAAoB;IACxD,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,GAAG,C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AAa,GAAG,MAAM,CAAC,aAAa,CAAC;YAC3C,kBAAkB,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;YACnD,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,2BAA2B,CAAC;YACtE,MAAM,MAAM,GAAG,MAAM,wBAAwB,CAAC;gBAC5C,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC;gBACvC,MAAM,EAAE,WAAW;gBACnB,oCAAoC;gBACpC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,KAAK,aAAa;gBACxD,2DAA2D;gBAC3D,mDAAmD;gBACnD,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,IAAI,KAAK;gBAChD,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK;gBAC/B,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM;gBACjC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;aAChC,CAAC,CAAC;YAEH,yDAAyD;YACzD,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC9B,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,CACvC;iBACF,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from '@workflow/errors';\nimport type {\n Event,\n EventResult,\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport {\n EventSchema,\n HookSchema,\n isLegacySpecVersion,\n requiresNewerWorld,\n SPEC_VERSION_CURRENT,\n StepSchema,\n validateUlidTimestamp,\n WaitSchema,\n WorkflowRunSchema,\n} from '@workflow/world';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n jsonReplacer,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSONWithFallback,\n resolveWithinBase,\n taggedPath,\n writeExclusive,\n writeJSON,\n} from '../fs.js';\nimport { stripEventDataRefs } from './filters.js';\nimport { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\nimport { handleLegacyEvent } from './legacy.js';\n\n/**\n * Per-step in-process async mutex. Serializes concurrent `events.create` calls\n * that target the same step, so that the \"check terminal state, then write step\n * entity + event\" sequence is atomic. Without this, two concurrent step_started\n * calls can both pass the not-terminal check and both write step_started events\n * — or a step_started can land in the log after step_completed has already\n * written, producing unconsumed events on replay.\n *\n * Duplicate step_started events for a non-terminal step are still allowed\n * (retries legitimately re-start a step), only writes to an already-terminal\n * step are rejected.\n */\nconst stepLocks = new Map<string, Promise<unknown>>();\n\nfunction withStepLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = stepLocks.get(key);\n const taskBox: { task?: Promise<T> } = {};\n const task = (async () => {\n if (prev) {\n // Wait for the previous task to settle; don't inherit its errors.\n await prev.catch(() => undefined);\n }\n try {\n return await fn();\n } finally {\n if (stepLocks.get(key) === taskBox.task) {\n stepLocks.delete(key);\n }\n }\n })();\n taskBox.task = task;\n stepLocks.set(key, task);\n return task;\n}\n\n/**\n * Helper function to delete all waits associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nasync function deleteAllWaitsForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const waitsDir = path.join(basedir, 'waits');\n const files = await listJSONFiles(waitsDir);\n\n for (const file of files) {\n // fileIds may contain tag suffixes (e.g., \"wrun_ABC-corrId.vitest-0\")\n // but startsWith still matches correctly since the tag is a suffix.\n if (file.startsWith(`${runId}-`)) {\n const waitPath = path.join(waitsDir, `${file}.json`);\n await deleteJSON(waitPath);\n }\n }\n}\n\n/**\n * Creates the events storage implementation using the filesystem.\n * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.\n */\nexport function createEventsStorage(\n basedir: string,\n tag?: string\n): Storage['events'] {\n return {\n async create(runId, data, params): Promise<EventResult> {\n // Validate request-supplied IDs before they're concatenated into\n // filesystem paths. This is the primary defense against path traversal\n // attacks where a client supplies runId / correlationId values like\n // \"../../../package\" to read or write files outside the storage root.\n // Run before taking the per-step mutex so malformed inputs fail fast.\n if (runId != null && runId !== '') {\n assertSafeEntityId('runId', runId);\n }\n if (\n 'correlationId' in data &&\n typeof data.correlationId === 'string' &&\n data.correlationId.length > 0\n ) {\n assertSafeEntityId('correlationId', data.correlationId);\n }\n\n // Step lifecycle events are serialized per-step via an in-process mutex\n // so that the \"check state, then write\" sequence in step_started /\n // step_completed / step_failed / step_retrying is atomic. step_created\n // is also serialized so duplicate-create races don't leave extra\n // step_created events in the log.\n const isStepEvent =\n data.eventType === 'step_created' ||\n data.eventType === 'step_started' ||\n data.eventType === 'step_completed' ||\n data.eventType === 'step_failed' ||\n data.eventType === 'step_retrying';\n if (isStepEvent && runId && data.correlationId) {\n const lockKey = tag\n ? `${runId}-${data.correlationId}.${tag}`\n : `${runId}-${data.correlationId}`;\n return withStepLock(lockKey, () => createImpl());\n }\n return createImpl();\n\n async function createImpl(): Promise<EventResult> {\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n\n // For run_created events, use client-provided runId or generate one server-side\n let effectiveRunId: string;\n if (data.eventType === 'run_created' && (!runId || runId === '')) {\n effectiveRunId = `wrun_${monotonicUlid()}`;\n } else if (!runId) {\n throw new Error('runId is required for non-run_created events');\n } else {\n effectiveRunId = runId;\n }\n\n // Validate client-provided runId timestamp is within acceptable threshold\n if (data.eventType === 'run_created' && runId && runId !== '') {\n const validationError = validateUlidTimestamp(\n effectiveRunId,\n 'wrun_'\n );\n if (validationError) {\n throw new WorkflowWorldError(validationError);\n }\n }\n\n // specVersion is always sent by the runtime, but we provide a fallback for safety\n const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;\n\n // Helper to check if run is in terminal state\n const isRunTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Helper to check if step is in terminal state\n const isStepTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Get current run state for validation (if not creating a new run)\n // Skip run validation for step_completed and step_retrying - they only operate\n // on running steps, and running steps are always allowed to modify regardless\n // of run state. This optimization saves filesystem reads per step event.\n let currentRun: WorkflowRun | null = null;\n const skipRunValidationEvents = ['step_completed', 'step_retrying'];\n if (\n data.eventType !== 'run_created' &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n\n // Resilient start: run_started on non-existent run with eventData\n // creates the run first, so the queue can bootstrap a run that\n // failed to create during start().\n if (\n data.eventType === 'run_started' &&\n !currentRun &&\n 'eventData' in data &&\n data.eventData\n ) {\n const runInputData = data.eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: Record<string, any>;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n // Atomically try to create the run entity. writeExclusive\n // uses O_CREAT|O_EXCL so only the first writer wins,\n // preventing a TOCTOU race where a concurrent run_created\n // from start() could overwrite a run that was already\n // transitioned to 'running'.\n const createdRun: WorkflowRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n status: 'pending',\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n executionContext: runInputData.executionContext,\n input: runInputData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(createdRun, jsonReplacer)\n );\n\n if (created) {\n // We created the run — also write the run_created event.\n const runCreatedEventId = `evnt_${monotonicUlid()}`;\n const runCreatedEvent: Event = {\n eventType: 'run_created',\n runId: effectiveRunId,\n eventId: runCreatedEventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n },\n };\n const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', createdCompositeKey, tag),\n runCreatedEvent\n );\n currentRun = createdRun;\n } else {\n // Run already exists (concurrent run_created won the\n // race). Re-read it so downstream logic sees the real state.\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n }\n }\n }\n }\n\n // run_failed on a non-existent run is rejected to match the\n // postgres and vercel worlds, which both surface this as a\n // WorkflowRunNotFoundError rather than silently persisting an\n // event for a run that was never created.\n if (data.eventType === 'run_failed' && !currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\n // ============================================================\n // For events that have fetched the run, check version compatibility.\n // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).\n if (currentRun) {\n // Check if run requires a newer world version\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n SPEC_VERSION_CURRENT\n );\n }\n\n // Route to legacy handler for pre-event-sourcing runs\n if (isLegacySpecVersion(currentRun.specVersion)) {\n return handleLegacyEvent(\n basedir,\n effectiveRunId,\n data,\n currentRun,\n params\n );\n }\n }\n\n // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\n\n // Run terminal state validation\n if (currentRun && isRunTerminal(currentRun.status)) {\n const runTerminalEvents = [\n 'run_started',\n 'run_completed',\n 'run_failed',\n ];\n\n // Idempotent operation: run_cancelled on already cancelled run is allowed\n if (\n data.eventType === 'run_cancelled' &&\n currentRun.status === 'cancelled'\n ) {\n // Return existing state (idempotent)\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return {\n event: stripEventDataRefs(event, resolveData),\n run: currentRun,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === 'run_started') {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${currentRun.status}\"`\n );\n }\n\n // Other run state transitions are not allowed on terminal runs\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === 'run_cancelled'\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${currentRun.status}\"`\n );\n }\n\n // Creating new entities on terminal runs is not allowed\n if (\n data.eventType === 'step_created' ||\n data.eventType === 'hook_created' ||\n data.eventType === 'wait_created'\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n\n // Step-related event validation (ordering and terminal state)\n // Store existingStep so we can reuse it later (avoid double read)\n let validatedStep: Step | null = null;\n const stepEvents = [\n 'step_started',\n 'step_completed',\n 'step_failed',\n 'step_retrying',\n ];\n if (stepEvents.includes(data.eventType) && data.correlationId) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n validatedStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n\n // Event ordering: step must exist before these events\n if (!validatedStep) {\n throw new WorkflowWorldError(\n `Step \"${data.correlationId}\" not found`\n );\n }\n\n // Step terminal state validation\n if (isStepTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`\n );\n }\n\n // On terminal runs: only allow completing/failing in-progress steps\n if (currentRun && isRunTerminal(currentRun.status)) {\n if (validatedStep.status !== 'running') {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n }\n\n // Hook-related event validation (ordering)\n const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId\n ) {\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n }\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n // Strip eventData from run_started — it belongs on run_created only.\n if (data.eventType === 'run_started' && 'eventData' in event) {\n delete (event as any).eventData;\n }\n\n // Track entity created/updated for EventResult\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n let wait: Wait | undefined;\n\n // Create/update entity based on event type (event-sourced architecture)\n // Run lifecycle events\n if (data.eventType === 'run_created' && 'eventData' in data) {\n const runData = data.eventData as {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, any>;\n };\n run = {\n runId: effectiveRunId,\n deploymentId: runData.deploymentId,\n status: 'pending',\n workflowName: runData.workflowName,\n // Propagate specVersion from the event to the run entity\n specVersion: effectiveSpecVersion,\n executionContext: runData.executionContext,\n input: runData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the\n // run entity file. This prevents a TOCTOU race with the resilient\n // start path (run_started on non-existent run) that could result\n // in duplicate run_created events in the event log.\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(run, jsonReplacer, 2)\n );\n if (!created) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`\n );\n }\n } else if (data.eventType === 'run_started') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // If already running, return the run without inserting a\n // duplicate event. This makes run_started idempotent for\n // concurrent invocations. We omit preloaded events here\n // because this is a rare race-condition path — the runtime\n // falls back to loadWorkflowRunEvents().\n if (currentRun.status === 'running') {\n return { run: currentRun };\n }\n\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n status: 'running',\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: currentRun.startedAt ?? now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'run_completed' && 'eventData' in data) {\n const completedData = data.eventData as { output?: any };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'completed',\n output: completedData.output,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_failed' && 'eventData' in data) {\n const failedData = data.eventData as {\n error: unknown;\n errorCode?: string;\n };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateRunError. We store it verbatim — consumers hydrate it\n // via hydrateRunError to reconstruct the original thrown value.\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'failed',\n output: undefined,\n error: failedData.error as Uint8Array,\n errorCode: failedData.errorCode,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_cancelled') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (\n // Step lifecycle events\n data.eventType === 'step_created' &&\n 'eventData' in data\n ) {\n // step_created: Creates step entity with status 'pending', attempt=0, createdAt set.\n // Two concurrent invocations with identical correlationIds (e.g. the\n // snapshot runtime's deterministic correlationIds across replays)\n // must be deduped — otherwise both writes succeed and the event log\n // ends up with duplicate step_created entries. The outer\n // withStepLock mutex serializes within a single process; this\n // O_CREAT|O_EXCL constraint file additionally protects against\n // cross-process races (two pnpm workers, redelivered queue\n // messages, etc.). The loser throws EntityConflictError so the\n // runtime's existing catch path can swallow it and avoid\n // double-queuing the step.\n const stepCreatedLockName = tag\n ? `${effectiveRunId}-${data.correlationId}.created.${tag}`\n : `${effectiveRunId}-${data.correlationId}.created`;\n const stepCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n stepCreatedLockName\n );\n const stepCreatedClaimed = await writeExclusive(\n stepCreatedLockPath,\n ''\n );\n if (!stepCreatedClaimed) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`\n );\n }\n const stepData = data.eventData as {\n stepName: string;\n input: any;\n };\n step = {\n runId: effectiveRunId,\n stepId: data.correlationId,\n stepName: stepData.stepName,\n status: 'pending',\n input: stepData.input,\n output: undefined,\n error: undefined,\n attempt: 0,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n // Propagate specVersion from the event to the step entity\n specVersion: effectiveSpecVersion,\n };\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step\n );\n } else if (data.eventType === 'step_started') {\n // step_started: Increments attempt, sets status to 'running'\n // Sets startedAt only on the first start (not updated on retries)\n // Reuse validatedStep from validation (already read above)\n if (validatedStep) {\n // Check if retryAfter timestamp hasn't been reached yet\n if (\n validatedStep.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000\n ),\n }\n );\n }\n\n // Best-effort guard: re-read the step entity to check if it\n // reached terminal state between the validation read and now.\n // This narrows the TOCTOU window but does not fully eliminate it\n // (the local world is single-process / dev-only; the postgres\n // world uses SQL-level atomic guards for production).\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const freshStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n if (freshStep && isStepTerminal(freshStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${freshStep.status}\"`\n );\n }\n\n step = {\n ...validatedStep,\n status: 'running',\n // Only set startedAt on the first start\n startedAt: validatedStep.startedAt ?? now,\n // Increment attempt counter on every start\n attempt: validatedStep.attempt + 1,\n // Clear retryAfter now that the step has started\n retryAfter: undefined,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_completed' && 'eventData' in data) {\n // step_completed: Terminal state with output\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same step (TOCTOU race).\n const completedData = data.eventData as { result: any };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n step = {\n ...validatedStep,\n status: 'completed',\n output: completedData.result,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_failed' && 'eventData' in data) {\n // step_failed: Terminal state with error\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both failing the same step (TOCTOU race).\n const failedData = data.eventData as {\n error: unknown;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateStepError. We store it verbatim — consumers hydrate it\n // via hydrateStepError to reconstruct the original thrown value.\n step = {\n ...validatedStep,\n status: 'failed',\n error: failedData.error as Uint8Array,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_retrying' && 'eventData' in data) {\n // step_retrying: Sets status back to 'pending', records error\n // Reuse validatedStep from validation (already read above)\n const retryData = data.eventData as {\n error: unknown;\n retryAfter?: Date;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n step = {\n ...validatedStep,\n status: 'pending',\n error: retryData.error as Uint8Array,\n retryAfter: retryData.retryAfter,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (\n // Hook lifecycle events\n data.eventType === 'hook_created' &&\n 'eventData' in data\n ) {\n const hookData = data.eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n // Atomically claim the token using an exclusive-create constraint file.\n // This avoids the TOCTOU race of the previous read-all-then-check approach.\n const constraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(hookData.token)}.json`\n );\n const tokenClaimed = await writeExclusive(\n constraintPath,\n JSON.stringify({\n token: hookData.token,\n hookId: data.correlationId,\n runId: effectiveRunId,\n })\n );\n\n if (!tokenClaimed) {\n // Create hook_conflict event instead of hook_created\n // This allows the workflow to continue and fail gracefully when the hook is awaited\n const conflictEvent: Event = {\n eventType: 'hook_conflict',\n correlationId: data.correlationId,\n eventData: {\n token: hookData.token,\n },\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n\n // Store the conflict event\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n conflictEvent\n );\n\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(\n conflictEvent,\n resolveData\n );\n\n // Return EventResult with conflict event (no hook entity created)\n return {\n event: filteredEvent,\n run,\n step,\n hook: undefined,\n };\n }\n\n hook = {\n runId: effectiveRunId,\n hookId: data.correlationId,\n token: hookData.token,\n metadata: hookData.metadata,\n ownerId: 'local-owner',\n projectId: 'local-project',\n environment: 'local',\n createdAt: now,\n // Propagate specVersion from the event to the hook entity\n specVersion: effectiveSpecVersion,\n isWebhook: hookData.isWebhook ?? false,\n isSystem: hookData.isSystem ?? false,\n };\n await writeJSON(\n taggedPath(basedir, 'hooks', data.correlationId, tag),\n hook\n );\n } else if (data.eventType === 'hook_disposed') {\n // hook_disposed: Deletes hook entity, rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both disposing the same hook (TOCTOU race).\n const hookLockName = tag\n ? `${data.correlationId}.disposed.${tag}`\n : `${data.correlationId}.disposed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'hooks',\n hookLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`\n );\n }\n // Read the hook to get its token before deleting\n const hookPath = taggedPath(\n basedir,\n 'hooks',\n data.correlationId,\n tag\n );\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n if (existingHook) {\n // Delete the token constraint file to free up the token for reuse\n const disposedConstraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(existingHook.token)}.json`\n );\n await deleteJSON(disposedConstraintPath);\n }\n await deleteJSON(hookPath);\n } else if (data.eventType === 'wait_created' && 'eventData' in data) {\n // wait_created: Creates wait entity with status 'waiting'.\n // Atomic claim on a per-(runId, correlationId) constraint file\n // ensures duplicate wait_created from concurrent invocations\n // surfaces as EntityConflictError (replaces a prior TOCTOU\n // read-then-check that could let both writers through).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitCreatedLockName = tag\n ? `${waitCompositeKey}.created.${tag}`\n : `${waitCompositeKey}.created`;\n const waitCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitCreatedLockName\n );\n const waitCreatedClaimed = await writeExclusive(\n waitCreatedLockPath,\n ''\n );\n if (!waitCreatedClaimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already exists`\n );\n }\n const waitData = data.eventData as {\n resumeAt?: Date;\n };\n wait = {\n waitId: waitCompositeKey,\n runId: effectiveRunId,\n status: 'waiting',\n resumeAt: waitData.resumeAt,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n specVersion: effectiveSpecVersion,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait\n );\n } else if (data.eventType === 'wait_completed') {\n // wait_completed: Transitions wait to 'completed', rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same wait (TOCTOU race).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitLockName = tag\n ? `${waitCompositeKey}.completed.${tag}`\n : `${waitCompositeKey}.completed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`\n );\n }\n const existingWait = await readJSONWithFallback(\n basedir,\n 'waits',\n waitCompositeKey,\n WaitSchema,\n tag\n );\n if (!existingWait) {\n // Clean up the lock file we just claimed — the wait doesn't exist\n await fs.unlink(lockPath).catch(() => {});\n throw new WorkflowWorldError(\n `Wait \"${data.correlationId}\" not found`\n );\n }\n // The lock file (writeExclusive above) already prevents concurrent\n // completions — no additional status check needed.\n wait = {\n ...existingWait,\n status: 'completed',\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait,\n { overwrite: true }\n );\n }\n // Note: hook_received events are stored in the event log but don't\n // modify the Hook entity (which doesn't have a payload field)\n\n // Store event using composite key {runId}-{eventId}\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(event, resolveData);\n\n // For run_started: include all events so the runtime can skip\n // the initial events.list call and reduce TTFB.\n let events: Event[] | undefined;\n if (data.eventType === 'run_started' && run) {\n const allEvents = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${effectiveRunId}-`,\n sortOrder: 'asc',\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (e) => e.eventId,\n });\n events = allEvents.data;\n }\n\n // Return EventResult with event and any created/updated entity\n return {\n event: filteredEvent,\n run,\n step,\n hook,\n wait,\n events,\n };\n } // end createImpl\n },\n\n async get(runId, eventId, params) {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('eventId', eventId);\n const compositeKey = `${runId}-${eventId}`;\n const event = await readJSONWithFallback(\n basedir,\n 'events',\n compositeKey,\n EventSchema,\n tag\n );\n if (!event) {\n throw new Error(`Event ${eventId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return stripEventDataRefs(event, resolveData);\n },\n\n async list(params) {\n const { runId } = params;\n assertSafeEntityId('runId', runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${runId}-`,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n\n async listByCorrelationId(params) {\n const correlationId = params.correlationId;\n assertSafeEntityId('correlationId', correlationId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n // No filePrefix - search all events\n filter: (event) => event.correlationId === correlationId,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n };\n}\n"]}
1
+ {"version":3,"file":"events-storage.js","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EACL,WAAW,EACX,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,CAA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AC,mBAAmB,CAAC,MAAM;YAC9B,MAAM,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;YAC3C,kBAAkB,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;YACnD,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,2BAA2B,CAAC;YACtE,MAAM,MAAM,GAAG,MAAM,wBAAwB,CAAC;gBAC5C,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC;gBACvC,MAAM,EAAE,WAAW;gBACnB,oCAAoC;gBACpC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,KAAK,aAAa;gBACxD,2DAA2D;gBAC3D,mDAAmD;gBACnD,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,IAAI,KAAK;gBAChD,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK;gBAC/B,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM;gBACjC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;aAChC,CAAC,CAAC;YAEH,yDAAyD;YACzD,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC9B,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,CACvC;iBACF,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from '@workflow/errors';\nimport type {\n Event,\n EventResult,\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport {\n EventSchema,\n HookSchema,\n isLegacySpecVersion,\n requiresNewerWorld,\n SPEC_VERSION_CURRENT,\n StepSchema,\n validateUlidTimestamp,\n WaitSchema,\n WorkflowRunSchema,\n} from '@workflow/world';\nimport { z } from 'zod';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n jsonReplacer,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSON,\n readJSONWithFallback,\n resolveWithinBase,\n taggedPath,\n writeExclusive,\n writeJSON,\n} from '../fs.js';\nimport { stripEventDataRefs } from './filters.js';\nimport { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\nimport { handleLegacyEvent } from './legacy.js';\n\n/**\n * Per-step in-process async mutex. Serializes concurrent `events.create` calls\n * that target the same step, so that the \"check terminal state, then write step\n * entity + event\" sequence is atomic. Without this, two concurrent step_started\n * calls can both pass the not-terminal check and both write step_started events\n * — or a step_started can land in the log after step_completed has already\n * written, producing unconsumed events on replay.\n *\n * Duplicate step_started events for a non-terminal step are still allowed\n * (retries legitimately re-start a step), only writes to an already-terminal\n * step are rejected.\n */\nconst stepLocks = new Map<string, Promise<unknown>>();\n\nconst HookTokenClaimSchema = z.object({\n runId: z.string(),\n});\n\nasync function readHookTokenClaim(\n constraintPath: string\n): Promise<z.infer<typeof HookTokenClaimSchema> | null> {\n try {\n return await readJSON(constraintPath, HookTokenClaimSchema);\n } catch (error) {\n if (error instanceof SyntaxError || error instanceof z.ZodError) {\n return null;\n }\n throw error;\n }\n}\n\nfunction withStepLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = stepLocks.get(key);\n const taskBox: { task?: Promise<T> } = {};\n const task = (async () => {\n if (prev) {\n // Wait for the previous task to settle; don't inherit its errors.\n await prev.catch(() => undefined);\n }\n try {\n return await fn();\n } finally {\n if (stepLocks.get(key) === taskBox.task) {\n stepLocks.delete(key);\n }\n }\n })();\n taskBox.task = task;\n stepLocks.set(key, task);\n return task;\n}\n\n/**\n * Helper function to delete all waits associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nasync function deleteAllWaitsForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const waitsDir = path.join(basedir, 'waits');\n const files = await listJSONFiles(waitsDir);\n\n for (const file of files) {\n // fileIds may contain tag suffixes (e.g., \"wrun_ABC-corrId.vitest-0\")\n // but startsWith still matches correctly since the tag is a suffix.\n if (file.startsWith(`${runId}-`)) {\n const waitPath = path.join(waitsDir, `${file}.json`);\n await deleteJSON(waitPath);\n }\n }\n}\n\n/**\n * Creates the events storage implementation using the filesystem.\n * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.\n */\nexport function createEventsStorage(\n basedir: string,\n tag?: string\n): Storage['events'] {\n return {\n async create(runId, data, params): Promise<EventResult> {\n // Validate request-supplied IDs before they're concatenated into\n // filesystem paths. This is the primary defense against path traversal\n // attacks where a client supplies runId / correlationId values like\n // \"../../../package\" to read or write files outside the storage root.\n // Run before taking the per-step mutex so malformed inputs fail fast.\n if (runId != null && runId !== '') {\n assertSafeEntityId('runId', runId);\n }\n if (\n 'correlationId' in data &&\n typeof data.correlationId === 'string' &&\n data.correlationId.length > 0\n ) {\n assertSafeEntityId('correlationId', data.correlationId);\n }\n\n // Step lifecycle events are serialized per-step via an in-process mutex\n // so that the \"check state, then write\" sequence in step_started /\n // step_completed / step_failed / step_retrying is atomic. step_created\n // is also serialized so duplicate-create races don't leave extra\n // step_created events in the log.\n const isStepEvent =\n data.eventType === 'step_created' ||\n data.eventType === 'step_started' ||\n data.eventType === 'step_completed' ||\n data.eventType === 'step_failed' ||\n data.eventType === 'step_retrying';\n if (isStepEvent && runId && data.correlationId) {\n const lockKey = tag\n ? `${runId}-${data.correlationId}.${tag}`\n : `${runId}-${data.correlationId}`;\n return withStepLock(lockKey, () => createImpl());\n }\n return createImpl();\n\n async function createImpl(): Promise<EventResult> {\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n\n // For run_created events, use client-provided runId or generate one server-side\n let effectiveRunId: string;\n if (data.eventType === 'run_created' && (!runId || runId === '')) {\n effectiveRunId = `wrun_${monotonicUlid()}`;\n } else if (!runId) {\n throw new Error('runId is required for non-run_created events');\n } else {\n effectiveRunId = runId;\n }\n\n // Validate client-provided runId timestamp is within acceptable threshold\n if (data.eventType === 'run_created' && runId && runId !== '') {\n const validationError = validateUlidTimestamp(\n effectiveRunId,\n 'wrun_'\n );\n if (validationError) {\n throw new WorkflowWorldError(validationError);\n }\n }\n\n // specVersion is always sent by the runtime, but we provide a fallback for safety\n const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;\n\n // Helper to check if run is in terminal state\n const isRunTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Helper to check if step is in terminal state\n const isStepTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Get current run state for validation (if not creating a new run)\n // Skip run validation for step_completed and step_retrying - they only operate\n // on running steps, and running steps are always allowed to modify regardless\n // of run state. This optimization saves filesystem reads per step event.\n let currentRun: WorkflowRun | null = null;\n const skipRunValidationEvents = ['step_completed', 'step_retrying'];\n if (\n data.eventType !== 'run_created' &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n\n // Resilient start: run_started on non-existent run with eventData\n // creates the run first, so the queue can bootstrap a run that\n // failed to create during start().\n if (\n data.eventType === 'run_started' &&\n !currentRun &&\n 'eventData' in data &&\n data.eventData\n ) {\n const runInputData = data.eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: Record<string, any>;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n // Atomically try to create the run entity. writeExclusive\n // uses O_CREAT|O_EXCL so only the first writer wins,\n // preventing a TOCTOU race where a concurrent run_created\n // from start() could overwrite a run that was already\n // transitioned to 'running'.\n const createdRun: WorkflowRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n status: 'pending',\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n executionContext: runInputData.executionContext,\n input: runInputData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(createdRun, jsonReplacer)\n );\n\n if (created) {\n // We created the run — also write the run_created event.\n const runCreatedEventId = `evnt_${monotonicUlid()}`;\n const runCreatedEvent: Event = {\n eventType: 'run_created',\n runId: effectiveRunId,\n eventId: runCreatedEventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n },\n };\n const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', createdCompositeKey, tag),\n runCreatedEvent\n );\n currentRun = createdRun;\n } else {\n // Run already exists (concurrent run_created won the\n // race). Re-read it so downstream logic sees the real state.\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n }\n }\n }\n }\n\n // run_failed on a non-existent run is rejected to match the\n // postgres and vercel worlds, which both surface this as a\n // WorkflowRunNotFoundError rather than silently persisting an\n // event for a run that was never created.\n if (data.eventType === 'run_failed' && !currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\n // ============================================================\n // For events that have fetched the run, check version compatibility.\n // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).\n if (currentRun) {\n // Check if run requires a newer world version\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n SPEC_VERSION_CURRENT\n );\n }\n\n // Route to legacy handler for pre-event-sourcing runs\n if (isLegacySpecVersion(currentRun.specVersion)) {\n return handleLegacyEvent(\n basedir,\n effectiveRunId,\n data,\n currentRun,\n params\n );\n }\n }\n\n // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\n\n // Run terminal state validation\n if (currentRun && isRunTerminal(currentRun.status)) {\n const runTerminalEvents = [\n 'run_started',\n 'run_completed',\n 'run_failed',\n ];\n\n // Idempotent operation: run_cancelled on already cancelled run is allowed\n if (\n data.eventType === 'run_cancelled' &&\n currentRun.status === 'cancelled'\n ) {\n // Return existing state (idempotent)\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return {\n event: stripEventDataRefs(event, resolveData),\n run: currentRun,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === 'run_started') {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${currentRun.status}\"`\n );\n }\n\n // Other run state transitions are not allowed on terminal runs\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === 'run_cancelled'\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${currentRun.status}\"`\n );\n }\n\n // Creating new entities on terminal runs is not allowed\n if (\n data.eventType === 'step_created' ||\n data.eventType === 'hook_created' ||\n data.eventType === 'wait_created'\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n\n // Step-related event validation (ordering and terminal state)\n // Store existingStep so we can reuse it later (avoid double read)\n let validatedStep: Step | null = null;\n const stepEvents = [\n 'step_started',\n 'step_completed',\n 'step_failed',\n 'step_retrying',\n ];\n if (stepEvents.includes(data.eventType) && data.correlationId) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n validatedStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n\n // Event ordering: step must exist before these events\n if (!validatedStep) {\n throw new WorkflowWorldError(\n `Step \"${data.correlationId}\" not found`\n );\n }\n\n // Step terminal state validation\n if (isStepTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`\n );\n }\n\n // On terminal runs: only allow completing/failing in-progress steps\n if (currentRun && isRunTerminal(currentRun.status)) {\n if (validatedStep.status !== 'running') {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n }\n\n // Hook-related event validation (ordering)\n const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId\n ) {\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n }\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n // Strip eventData from run_started — it belongs on run_created only.\n if (data.eventType === 'run_started' && 'eventData' in event) {\n delete (event as any).eventData;\n }\n\n // Track entity created/updated for EventResult\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n let wait: Wait | undefined;\n\n // Create/update entity based on event type (event-sourced architecture)\n // Run lifecycle events\n if (data.eventType === 'run_created' && 'eventData' in data) {\n const runData = data.eventData as {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, any>;\n };\n run = {\n runId: effectiveRunId,\n deploymentId: runData.deploymentId,\n status: 'pending',\n workflowName: runData.workflowName,\n // Propagate specVersion from the event to the run entity\n specVersion: effectiveSpecVersion,\n executionContext: runData.executionContext,\n input: runData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the\n // run entity file. This prevents a TOCTOU race with the resilient\n // start path (run_started on non-existent run) that could result\n // in duplicate run_created events in the event log.\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(run, jsonReplacer, 2)\n );\n if (!created) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`\n );\n }\n } else if (data.eventType === 'run_started') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // If already running, return the run without inserting a\n // duplicate event. This makes run_started idempotent for\n // concurrent invocations. We omit preloaded events here\n // because this is a rare race-condition path — the runtime\n // falls back to loadWorkflowRunEvents().\n if (currentRun.status === 'running') {\n return { run: currentRun };\n }\n\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n status: 'running',\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: currentRun.startedAt ?? now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'run_completed' && 'eventData' in data) {\n const completedData = data.eventData as { output?: any };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'completed',\n output: completedData.output,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_failed' && 'eventData' in data) {\n const failedData = data.eventData as {\n error: unknown;\n errorCode?: string;\n };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateRunError. We store it verbatim — consumers hydrate it\n // via hydrateRunError to reconstruct the original thrown value.\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'failed',\n output: undefined,\n error: failedData.error as Uint8Array,\n errorCode: failedData.errorCode,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_cancelled') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (\n // Step lifecycle events\n data.eventType === 'step_created' &&\n 'eventData' in data\n ) {\n // step_created: Creates step entity with status 'pending', attempt=0, createdAt set.\n // Two concurrent invocations with identical correlationIds (e.g. the\n // snapshot runtime's deterministic correlationIds across replays)\n // must be deduped — otherwise both writes succeed and the event log\n // ends up with duplicate step_created entries. The outer\n // withStepLock mutex serializes within a single process; this\n // O_CREAT|O_EXCL constraint file additionally protects against\n // cross-process races (two pnpm workers, redelivered queue\n // messages, etc.). The loser throws EntityConflictError so the\n // runtime's existing catch path can swallow it and avoid\n // double-queuing the step.\n const stepCreatedLockName = tag\n ? `${effectiveRunId}-${data.correlationId}.created.${tag}`\n : `${effectiveRunId}-${data.correlationId}.created`;\n const stepCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n stepCreatedLockName\n );\n const stepCreatedClaimed = await writeExclusive(\n stepCreatedLockPath,\n ''\n );\n if (!stepCreatedClaimed) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`\n );\n }\n const stepData = data.eventData as {\n stepName: string;\n input: any;\n };\n step = {\n runId: effectiveRunId,\n stepId: data.correlationId,\n stepName: stepData.stepName,\n status: 'pending',\n input: stepData.input,\n output: undefined,\n error: undefined,\n attempt: 0,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n // Propagate specVersion from the event to the step entity\n specVersion: effectiveSpecVersion,\n };\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step\n );\n } else if (data.eventType === 'step_started') {\n // step_started: Increments attempt, sets status to 'running'\n // Sets startedAt only on the first start (not updated on retries)\n // Reuse validatedStep from validation (already read above)\n if (validatedStep) {\n // Check if retryAfter timestamp hasn't been reached yet\n if (\n validatedStep.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000\n ),\n }\n );\n }\n\n // Best-effort guard: re-read the step entity to check if it\n // reached terminal state between the validation read and now.\n // This narrows the TOCTOU window but does not fully eliminate it\n // (the local world is single-process / dev-only; the postgres\n // world uses SQL-level atomic guards for production).\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const freshStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n if (freshStep && isStepTerminal(freshStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${freshStep.status}\"`\n );\n }\n\n step = {\n ...validatedStep,\n status: 'running',\n // Only set startedAt on the first start\n startedAt: validatedStep.startedAt ?? now,\n // Increment attempt counter on every start\n attempt: validatedStep.attempt + 1,\n // Clear retryAfter now that the step has started\n retryAfter: undefined,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_completed' && 'eventData' in data) {\n // step_completed: Terminal state with output\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same step (TOCTOU race).\n const completedData = data.eventData as { result: any };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n step = {\n ...validatedStep,\n status: 'completed',\n output: completedData.result,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_failed' && 'eventData' in data) {\n // step_failed: Terminal state with error\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both failing the same step (TOCTOU race).\n const failedData = data.eventData as {\n error: unknown;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateStepError. We store it verbatim — consumers hydrate it\n // via hydrateStepError to reconstruct the original thrown value.\n step = {\n ...validatedStep,\n status: 'failed',\n error: failedData.error as Uint8Array,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_retrying' && 'eventData' in data) {\n // step_retrying: Sets status back to 'pending', records error\n // Reuse validatedStep from validation (already read above)\n const retryData = data.eventData as {\n error: unknown;\n retryAfter?: Date;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n step = {\n ...validatedStep,\n status: 'pending',\n error: retryData.error as Uint8Array,\n retryAfter: retryData.retryAfter,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (\n // Hook lifecycle events\n data.eventType === 'hook_created' &&\n 'eventData' in data\n ) {\n const hookData = data.eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n // Atomically claim the token using an exclusive-create constraint file.\n // This avoids the TOCTOU race of the previous read-all-then-check approach.\n const constraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(hookData.token)}.json`\n );\n const tokenClaimed = await writeExclusive(\n constraintPath,\n JSON.stringify({\n token: hookData.token,\n hookId: data.correlationId,\n runId: effectiveRunId,\n })\n );\n\n if (!tokenClaimed) {\n const existingClaim = await readHookTokenClaim(constraintPath);\n\n // Create hook_conflict event instead of hook_created\n // This allows the workflow to continue and fail gracefully when the hook is awaited\n const conflictEvent: Event = {\n eventType: 'hook_conflict',\n correlationId: data.correlationId,\n eventData: {\n token: hookData.token,\n ...(existingClaim\n ? { conflictingRunId: existingClaim.runId }\n : {}),\n },\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n\n // Store the conflict event\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n conflictEvent\n );\n\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(\n conflictEvent,\n resolveData\n );\n\n // Return EventResult with conflict event (no hook entity created)\n return {\n event: filteredEvent,\n run,\n step,\n hook: undefined,\n };\n }\n\n hook = {\n runId: effectiveRunId,\n hookId: data.correlationId,\n token: hookData.token,\n metadata: hookData.metadata,\n ownerId: 'local-owner',\n projectId: 'local-project',\n environment: 'local',\n createdAt: now,\n // Propagate specVersion from the event to the hook entity\n specVersion: effectiveSpecVersion,\n isWebhook: hookData.isWebhook ?? false,\n isSystem: hookData.isSystem ?? false,\n };\n await writeJSON(\n taggedPath(basedir, 'hooks', data.correlationId, tag),\n hook\n );\n } else if (data.eventType === 'hook_disposed') {\n // hook_disposed: Deletes hook entity, rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both disposing the same hook (TOCTOU race).\n const hookLockName = tag\n ? `${data.correlationId}.disposed.${tag}`\n : `${data.correlationId}.disposed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'hooks',\n hookLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`\n );\n }\n // Read the hook to get its token before deleting\n const hookPath = taggedPath(\n basedir,\n 'hooks',\n data.correlationId,\n tag\n );\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n if (existingHook) {\n // Delete the token constraint file to free up the token for reuse\n const disposedConstraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(existingHook.token)}.json`\n );\n await deleteJSON(disposedConstraintPath);\n }\n await deleteJSON(hookPath);\n } else if (data.eventType === 'wait_created' && 'eventData' in data) {\n // wait_created: Creates wait entity with status 'waiting'.\n // Atomic claim on a per-(runId, correlationId) constraint file\n // ensures duplicate wait_created from concurrent invocations\n // surfaces as EntityConflictError (replaces a prior TOCTOU\n // read-then-check that could let both writers through).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitCreatedLockName = tag\n ? `${waitCompositeKey}.created.${tag}`\n : `${waitCompositeKey}.created`;\n const waitCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitCreatedLockName\n );\n const waitCreatedClaimed = await writeExclusive(\n waitCreatedLockPath,\n ''\n );\n if (!waitCreatedClaimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already exists`\n );\n }\n const waitData = data.eventData as {\n resumeAt?: Date;\n };\n wait = {\n waitId: waitCompositeKey,\n runId: effectiveRunId,\n status: 'waiting',\n resumeAt: waitData.resumeAt,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n specVersion: effectiveSpecVersion,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait\n );\n } else if (data.eventType === 'wait_completed') {\n // wait_completed: Transitions wait to 'completed', rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same wait (TOCTOU race).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitLockName = tag\n ? `${waitCompositeKey}.completed.${tag}`\n : `${waitCompositeKey}.completed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`\n );\n }\n const existingWait = await readJSONWithFallback(\n basedir,\n 'waits',\n waitCompositeKey,\n WaitSchema,\n tag\n );\n if (!existingWait) {\n // Clean up the lock file we just claimed — the wait doesn't exist\n await fs.unlink(lockPath).catch(() => {});\n throw new WorkflowWorldError(\n `Wait \"${data.correlationId}\" not found`\n );\n }\n // The lock file (writeExclusive above) already prevents concurrent\n // completions — no additional status check needed.\n wait = {\n ...existingWait,\n status: 'completed',\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait,\n { overwrite: true }\n );\n }\n // Note: hook_received events are stored in the event log but don't\n // modify the Hook entity (which doesn't have a payload field)\n\n // Store event using composite key {runId}-{eventId}\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(event, resolveData);\n\n // For run_started: include all events so the runtime can skip\n // the initial events.list call and reduce TTFB.\n let events: Event[] | undefined;\n if (data.eventType === 'run_started' && run) {\n const allEvents = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${effectiveRunId}-`,\n sortOrder: 'asc',\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (e) => e.eventId,\n });\n events = allEvents.data;\n }\n\n // Return EventResult with event and any created/updated entity\n return {\n event: filteredEvent,\n run,\n step,\n hook,\n wait,\n events,\n };\n } // end createImpl\n },\n\n async get(runId, eventId, params) {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('eventId', eventId);\n const compositeKey = `${runId}-${eventId}`;\n const event = await readJSONWithFallback(\n basedir,\n 'events',\n compositeKey,\n EventSchema,\n tag\n );\n if (!event) {\n throw new Error(`Event ${eventId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return stripEventDataRefs(event, resolveData);\n },\n\n async list(params) {\n const { runId } = params;\n assertSafeEntityId('runId', runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${runId}-`,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n\n async listByCorrelationId(params) {\n const correlationId = params.correlationId;\n assertSafeEntityId('correlationId', correlationId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n // No filePrefix - search all events\n filter: (event) => event.correlationId === correlationId,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/world-local",
3
- "version": "5.0.0-beta.4",
3
+ "version": "5.0.0-beta.5",
4
4
  "description": "Local development World implementation for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -23,14 +23,14 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@vercel/queue": "0.1.4",
26
+ "@vercel/queue": "0.1.7",
27
27
  "async-sema": "3.1.1",
28
28
  "ulid": "~3.0.1",
29
29
  "undici": "7.22.0",
30
30
  "zod": "4.3.6",
31
- "@workflow/errors": "5.0.0-beta.2",
32
- "@workflow/world": "5.0.0-beta.2",
33
- "@workflow/utils": "5.0.0-beta.2"
31
+ "@workflow/utils": "5.0.0-beta.2",
32
+ "@workflow/errors": "5.0.0-beta.3",
33
+ "@workflow/world": "5.0.0-beta.3"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@opentelemetry/api": "1.9.0",