@yolk-sdk/vercel-workflows 0.1.0-canary.130 → 0.1.0-canary.132
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/dist/testing/index.d.mts +8 -0
- package/dist/testing/index.d.mts.map +1 -1
- package/dist/testing/index.mjs +97 -4
- package/dist/testing/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/testing/index.ts +230 -4
package/README.md
CHANGED
|
@@ -69,9 +69,17 @@ queues, hooks, or stream storage.
|
|
|
69
69
|
`@yolk-sdk/vercel-workflows/testing` provides `TestWorkflowWorld`, a behavioral emulator for host
|
|
70
70
|
tests. It covers run lifecycle, append-only streams with close-once conflicts, step retries and
|
|
71
71
|
attempt metadata, hooks/resume, cancellation, and the SDK seam used by
|
|
72
|
-
`VercelWorkflows.layerFromSdk`.
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
`VercelWorkflows.layerFromSdk`. Step errors cross the platform boundary as in a deployment: each is
|
|
73
|
+
stored with the installed `workflow` runtime's step-error serializer and the workflow body sees only
|
|
74
|
+
the value read back (error tags, prototypes and custom fields are lost; `cause` survives). A
|
|
75
|
+
FatalError (named `FatalError`, or with `fatal: true`; an `AbortError` is promoted to one) is never
|
|
76
|
+
retried, an exhausted step fails with the platform's FatalError wrapping the last error, and a
|
|
77
|
+
thrown value the platform cannot store (a class instance anywhere in its `cause` chain) is
|
|
78
|
+
redelivered like the platform does until the step exceeds its retries;
|
|
79
|
+
`world.inspect(runId).unstorableStepErrors` lists those values. Executing a step loads the workflow
|
|
80
|
+
runtime, so it needs the Node test environment. Ambient module mocks do not apply retry policy by
|
|
81
|
+
themselves: wrap host step callbacks with `world.step(...)` or call `world.runStep(...)` explicitly
|
|
82
|
+
when the test must exercise platform retry attempts and `getStepMetadata().attempt`.
|
|
75
83
|
|
|
76
84
|
Mock the ambient `workflow` module so production orchestration runs against the active test world:
|
|
77
85
|
|
package/dist/testing/index.d.mts
CHANGED
|
@@ -34,6 +34,12 @@ export type TestWorkflowStepMetadata = {
|
|
|
34
34
|
readonly stepId: string;
|
|
35
35
|
readonly stepName: string;
|
|
36
36
|
};
|
|
37
|
+
/** A thrown step value the platform could not store; the step was redelivered instead. */
|
|
38
|
+
export type TestWorkflowUnstorableStepError = {
|
|
39
|
+
readonly stepName: string;
|
|
40
|
+
readonly attempt: number;
|
|
41
|
+
readonly error: unknown;
|
|
42
|
+
};
|
|
37
43
|
export type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((...args: TArgs) => Promise<TResult>) & {
|
|
38
44
|
readonly maxRetries?: number;
|
|
39
45
|
};
|
|
@@ -47,6 +53,8 @@ export type TestWorkflowRunInspection = {
|
|
|
47
53
|
readonly writeAfterCloseAttempts: number;
|
|
48
54
|
readonly stepAttempts: ReadonlyMap<string, number>;
|
|
49
55
|
readonly runError: unknown;
|
|
56
|
+
/** Every thrown step value the platform could not store, in order. */
|
|
57
|
+
readonly unstorableStepErrors: ReadonlyArray<TestWorkflowUnstorableStepError>;
|
|
50
58
|
};
|
|
51
59
|
export type TestWorkflowHook<T> = Promise<T> & {
|
|
52
60
|
readonly [Symbol.dispose]: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/testing/index.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/testing/index.ts"],"mappings":";YAkCY,wBAAwB;qBAKvB,wCAAwC;WACjC;WACT;EAET,YAAY;;qBAKD,qCAAqC;WAC9B;WACT;EAET,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;qBAKD,qCAAqC;WAC9B;EAElB,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;YAKF;WAAkC;;YAElC;WACD;WACA;WACA;;;YAIC;WACD;WACA;WACA;;YAGC,yBAAyB,cAAc,wBAAwB,gBACtE,MAAM,UACN,QAAQ;WAAuB;;qBAGvB;YA+LD;WACD;WACA,QAAQ;WACR,QAAQ;WACR;WACA;WACA;WACA,cAAc;WACd;;WAEA,sBAAsB,cAAc;;YAGnC,iBAAiB,KAAK,QAAQ;YAAiB,OAAO;;KAE7D;WAA0C;;qBAElC;mBACM;UACT;EAER,MAAM,cAAc,wBAAwB,SAC1C,gBAAgB,MAAM,UAAU,QAAQ,UACxC,MAAM,QACL;EAoDG,QAAQ,gBAAgB;EAI9B,QAAQ,gBAAgB;EAgBxB,OAAO,gBAAgB;EAIjB,OAAO,gBAAgB;EAmBvB,WAAW,eAAe,mBAAmB;EAoBnD,eAAe;EAiBT,QAAQ,cAAc,wBAAwB,SAClD,QAAQ,yBAAyB,OAAO,UACxC,MAAM,OACN,oBACC,QAAQ;EA6EX,KAAK,cAAc,wBAAwB,SACzC,QAAQ,yBAAyB,OAAO,UACxC,wBACK,MAAM,UAAU,QAAQ;SAMxB,uBAAuB;SAIvB,mBAAmB;SAUnB,YAAY,MAAM,eAAe;SAMjC,WAAW,GAAG;aAAkB;MAAkB,iBAAiB;UAQlE;UAwBA;EAqBR,YAAY,GACV,eACA,UAAU,gCACT,6BAA6B;UAiCxB;UAIA;UAOA;UAMA;UAUA;WA2BC,KAAK;;qBAcH;EACX,2BAAmB;EACnB,uBAAe;EACf,cAAc,QAAC,eAAA;EACf,aAAa,GAAC;aAAoB;QAAe,iBAAA"}
|
package/dist/testing/index.mjs
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { Predicate } from "effect";
|
|
1
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import { types } from "node:util";
|
|
6
|
+
import path from "node:path";
|
|
2
7
|
// src/testing/index.ts
|
|
3
8
|
var TestWorkflowStreamConflictError = class extends Error {
|
|
4
9
|
name = "EntityConflictError";
|
|
@@ -45,6 +50,68 @@ const requireAmbient = () => {
|
|
|
45
50
|
if (ambient === void 0) throw new Error("Workflow ambient API called outside a TestWorkflowWorld run context");
|
|
46
51
|
return ambient;
|
|
47
52
|
};
|
|
53
|
+
let stepErrorSerializer;
|
|
54
|
+
const workflowPackageDir = (require) => {
|
|
55
|
+
let dir = path.dirname(require.resolve("workflow"));
|
|
56
|
+
while (!fs.existsSync(path.join(dir, "package.json"))) {
|
|
57
|
+
const parent = path.dirname(dir);
|
|
58
|
+
if (parent === dir) throw new Error("Cannot locate the installed workflow package");
|
|
59
|
+
dir = parent;
|
|
60
|
+
}
|
|
61
|
+
return dir;
|
|
62
|
+
};
|
|
63
|
+
const loadStepErrorSerializer = () => stepErrorSerializer ??= (async () => {
|
|
64
|
+
const require = createRequire(import.meta.url);
|
|
65
|
+
const serialization = await import(require.resolve("@workflow/core/serialization", { paths: [workflowPackageDir(require)] })).catch((cause) => {
|
|
66
|
+
throw new Error("TestWorkflowWorld cannot load the workflow step-error serializer (under jsdom: step execution needs the Node test environment)", { cause });
|
|
67
|
+
});
|
|
68
|
+
if (!Predicate.hasProperty(serialization, "dehydrateStepError") || !Predicate.hasProperty(serialization, "hydrateStepError") || !Predicate.isFunction(serialization.dehydrateStepError) || !Predicate.isFunction(serialization.hydrateStepError)) throw new Error("The installed workflow runtime has no step-error serializer");
|
|
69
|
+
const { dehydrateStepError, hydrateStepError } = serialization;
|
|
70
|
+
return {
|
|
71
|
+
dehydrate: async (error, runId) => {
|
|
72
|
+
let bytes;
|
|
73
|
+
try {
|
|
74
|
+
bytes = await dehydrateStepError(error, runId, void 0);
|
|
75
|
+
} catch (failure) {
|
|
76
|
+
if (Predicate.hasProperty(failure, "name") && failure.name === "SerializationError") return;
|
|
77
|
+
throw failure;
|
|
78
|
+
}
|
|
79
|
+
if (!(bytes instanceof Uint8Array)) throw new Error("The workflow step-error serializer returned no bytes");
|
|
80
|
+
return bytes;
|
|
81
|
+
},
|
|
82
|
+
hydrate: async (bytes, runId) => {
|
|
83
|
+
return await hydrateStepError(bytes, runId, void 0);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
})();
|
|
87
|
+
const isPlatformError = (value) => Predicate.hasProperty(value, "name") && Predicate.hasProperty(value, "message");
|
|
88
|
+
const isFatalStepError = (value) => isPlatformError(value) && (Predicate.hasProperty(value, "name") && value.name === "FatalError" || Predicate.hasProperty(value, "fatal") && value.fatal === true);
|
|
89
|
+
const promoteAbortError = (value) => {
|
|
90
|
+
if (!Predicate.hasProperty(value, "name") || value.name !== "AbortError" || !Predicate.hasProperty(value, "message") || !Predicate.isString(value.message) || Predicate.hasProperty(value, "stack") && value.stack !== void 0 && !Predicate.isString(value.stack) || isFatalStepError(value)) return value;
|
|
91
|
+
const fatal = platformFatalError(`Aborted: ${value.message}`, void 0);
|
|
92
|
+
if (Predicate.hasProperty(value, "stack") && Predicate.isString(value.stack)) fatal.stack = value.stack;
|
|
93
|
+
return fatal;
|
|
94
|
+
};
|
|
95
|
+
const platformFatalError = (message, cause) => {
|
|
96
|
+
const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
|
|
97
|
+
error.name = "FatalError";
|
|
98
|
+
return error;
|
|
99
|
+
};
|
|
100
|
+
const platformErrorMessage = async (value) => {
|
|
101
|
+
if (Predicate.hasProperty(value, "then") && Predicate.isFunction(value.then)) try {
|
|
102
|
+
return `Promise rejection: ${await platformErrorMessage(await value)}`;
|
|
103
|
+
} catch (rejection) {
|
|
104
|
+
return `Promise rejection: ${await platformErrorMessage(rejection)}`;
|
|
105
|
+
}
|
|
106
|
+
if (types.isNativeError(value)) return value.message;
|
|
107
|
+
if (Predicate.isString(value)) return value;
|
|
108
|
+
try {
|
|
109
|
+
return String(JSON.stringify(value));
|
|
110
|
+
} catch {
|
|
111
|
+
return String(value);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const retriesLabel = (count) => count === 1 ? "retry" : "retries";
|
|
48
115
|
var TestWorkflowWorld = class {
|
|
49
116
|
runs = /* @__PURE__ */ new Map();
|
|
50
117
|
runSequence = 0;
|
|
@@ -65,7 +132,8 @@ var TestWorkflowWorld = class {
|
|
|
65
132
|
hooks: /* @__PURE__ */ new Map(),
|
|
66
133
|
resumedHookTokens: /* @__PURE__ */ new Set(),
|
|
67
134
|
stepSequence: 0,
|
|
68
|
-
stepAttempts: /* @__PURE__ */ new Map()
|
|
135
|
+
stepAttempts: /* @__PURE__ */ new Map(),
|
|
136
|
+
unstorableStepErrors: []
|
|
69
137
|
};
|
|
70
138
|
this.runs.set(runId, run);
|
|
71
139
|
run.settled = ambientStorage.run({
|
|
@@ -101,7 +169,8 @@ var TestWorkflowWorld = class {
|
|
|
101
169
|
streamCloseCount: run.streamCloseCount,
|
|
102
170
|
writeAfterCloseAttempts: run.writeAfterCloseAttempts,
|
|
103
171
|
stepAttempts: new Map(run.stepAttempts),
|
|
104
|
-
runError: run.runError
|
|
172
|
+
runError: run.runError,
|
|
173
|
+
unstorableStepErrors: [...run.unstorableStepErrors]
|
|
105
174
|
};
|
|
106
175
|
}
|
|
107
176
|
status(runId) {
|
|
@@ -138,10 +207,13 @@ var TestWorkflowWorld = class {
|
|
|
138
207
|
const run = requireAmbient().run;
|
|
139
208
|
run.stepSequence += 1;
|
|
140
209
|
const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`;
|
|
141
|
-
const
|
|
210
|
+
const maxRetries = stepFn.maxRetries ?? 3;
|
|
211
|
+
const maxAttempts = maxRetries + 1;
|
|
212
|
+
const serializer = await loadStepErrorSerializer();
|
|
142
213
|
let attempt = 1;
|
|
143
214
|
for (;;) {
|
|
144
215
|
run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1);
|
|
216
|
+
let thrown;
|
|
145
217
|
try {
|
|
146
218
|
return await ambientStorage.run({
|
|
147
219
|
world: this,
|
|
@@ -153,9 +225,30 @@ var TestWorkflowWorld = class {
|
|
|
153
225
|
}
|
|
154
226
|
}, () => stepFn(...args));
|
|
155
227
|
} catch (error) {
|
|
156
|
-
|
|
228
|
+
thrown = error;
|
|
229
|
+
}
|
|
230
|
+
const effective = promoteAbortError(thrown);
|
|
231
|
+
const message = await platformErrorMessage(effective);
|
|
232
|
+
const fatal = isFatalStepError(effective);
|
|
233
|
+
const exhausted = !fatal && attempt >= maxAttempts;
|
|
234
|
+
const recorded = fatal ? effective : exhausted ? platformFatalError(`Step "${stepName}" failed after ${maxRetries} ${retriesLabel(maxRetries)}: ${message}`, thrown) : thrown;
|
|
235
|
+
const bytes = await serializer.dehydrate(recorded, run.runId);
|
|
236
|
+
if (bytes === void 0) {
|
|
237
|
+
run.unstorableStepErrors.push({
|
|
238
|
+
stepName,
|
|
239
|
+
attempt,
|
|
240
|
+
error: thrown
|
|
241
|
+
});
|
|
242
|
+
if (attempt >= maxAttempts) {
|
|
243
|
+
const exceeded = await serializer.dehydrate(platformFatalError(`Step "${stepName}" exceeded max retries (${maxRetries} ${retriesLabel(maxRetries)})`, void 0), run.runId);
|
|
244
|
+
if (exceeded === void 0) throw new Error("The workflow runtime cannot store a FatalError");
|
|
245
|
+
throw await serializer.hydrate(exceeded, run.runId);
|
|
246
|
+
}
|
|
157
247
|
attempt += 1;
|
|
248
|
+
continue;
|
|
158
249
|
}
|
|
250
|
+
if (fatal || exhausted) throw await serializer.hydrate(bytes, run.runId);
|
|
251
|
+
attempt += 1;
|
|
159
252
|
}
|
|
160
253
|
}
|
|
161
254
|
step(stepFn, stepName) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type {\n VercelWorkflowsSdkClient,\n VercelWorkflowsSdkRun,\n VercelWorkflowReadableOptions,\n VercelWorkflowReadableStream,\n VercelWorkflowRunStatus\n} from '../effect.ts'\n\n// Behavioral emulator of the Vercel Workflow platform for tests: run lifecycle,\n// append-only durable streams with close-once -> 409 write conflicts, a step\n// executor honoring `fn.maxRetries` + `getStepMetadata().attempt`, hooks/resume,\n// and cancellation. Host code under test runs unmodified against it; tests mock\n// only the `workflow` module's ambient APIs, delegating to the active world\n// (see `testWorkflowModule`).\n//\n// The single most important semantic: writing to (or re-closing) a closed\n// durable stream fails with the platform's HTTP 409 \"already completed\"\n// conflict shape. Any code path that performs a terminal stream effect from a\n// retryable step attempt poisons every subsequent platform retry — exactly the\n// #252 production bug. The emulator enforces that invariant permanently.\n\nexport type TestWorkflowRunStatus = VercelWorkflowRunStatus\n\n// Matches the platform's conflict contract: `EntityConflictError.is(value)`\n// checks `value.name === 'EntityConflictError'`, and the Vercel world maps\n// HTTP 409 responses to that class.\nexport class TestWorkflowStreamConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" stream already completed`)\n }\n}\n\nexport class TestWorkflowRunConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(message: string) {\n super(message)\n }\n}\n\nexport class TestWorkflowHookNotFoundError extends Error {\n override readonly name = 'HookNotFoundError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was not found`)\n }\n}\n\nexport class TestWorkflowHookConflictError extends Error {\n override readonly name = 'HookConflictError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was already resumed`)\n }\n}\n\nexport class TestWorkflowRunNotFoundError extends Error {\n override readonly name = 'WorkflowRunNotFoundError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was not found`)\n }\n}\n\nexport class TestWorkflowRunCancelledError extends Error {\n override readonly name = 'WorkflowRunCancelledError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was cancelled`)\n }\n}\n\nexport type TestWorkflowMetadata = { readonly workflowRunId: string }\n\nexport type TestWorkflowStepMetadata = {\n readonly attempt: number\n readonly stepId: string\n readonly stepName: string\n}\n\nexport type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((\n ...args: TArgs\n) => Promise<TResult>) & { readonly maxRetries?: number }\n\n// The platform default: retries after the first attempt; total attempts = maxRetries + 1.\nexport const defaultTestWorkflowStepMaxRetries = 3\n\ntype HookRecord = {\n readonly resolve: (payload: unknown) => void\n readonly reject: (error: TestWorkflowRunCancelledError) => void\n}\n\ntype TestWorkflowRunRecord = {\n readonly runId: string\n status: TestWorkflowRunStatus\n returnValue: unknown\n runError: unknown\n settled: Promise<void>\n readonly chunks: Array<unknown>\n streamClosed: boolean\n streamCloseCount: number\n writeAfterCloseAttempts: number\n readonly changeListeners: Set<() => void>\n readonly hooks: Map<string, HookRecord>\n readonly resumedHookTokens: Set<string>\n stepSequence: number\n readonly stepAttempts: Map<string, number>\n}\n\ntype AmbientContext = {\n readonly world: TestWorkflowWorld\n readonly run: TestWorkflowRunRecord\n readonly stepMetadata: TestWorkflowStepMetadata | undefined\n}\n\nconst ambientStorage = new AsyncLocalStorage<AmbientContext>()\n\nconst requireAmbient = (): AmbientContext => {\n const ambient = ambientStorage.getStore()\n\n if (ambient === undefined) {\n throw new Error('Workflow ambient API called outside a TestWorkflowWorld run context')\n }\n\n return ambient\n}\n\nexport type TestWorkflowRunInspection = {\n readonly runId: string\n readonly status: TestWorkflowRunStatus\n readonly chunks: ReadonlyArray<unknown>\n readonly streamClosed: boolean\n readonly streamCloseCount: number\n readonly writeAfterCloseAttempts: number\n readonly stepAttempts: ReadonlyMap<string, number>\n readonly runError: unknown\n}\n\nexport type TestWorkflowHook<T> = Promise<T> & { readonly [Symbol.dispose]: () => void }\n\ntype TestWorkflowWorldStartResult = { readonly runId: string }\n\nexport class TestWorkflowWorld {\n private readonly runs = new Map<string, TestWorkflowRunRecord>()\n private runSequence = 0\n\n start<TArgs extends ReadonlyArray<unknown>, TResult>(\n workflowFn: (...args: TArgs) => Promise<TResult>,\n args: TArgs\n ): TestWorkflowWorldStartResult {\n this.runSequence += 1\n const runId = `twr_${this.runSequence}`\n\n const run: TestWorkflowRunRecord = {\n runId,\n status: 'pending',\n returnValue: undefined,\n runError: undefined,\n settled: Promise.resolve(),\n chunks: [],\n streamClosed: false,\n streamCloseCount: 0,\n writeAfterCloseAttempts: 0,\n changeListeners: new Set(),\n hooks: new Map(),\n resumedHookTokens: new Set(),\n stepSequence: 0,\n stepAttempts: new Map()\n }\n\n this.runs.set(runId, run)\n\n run.settled = ambientStorage.run(\n { world: this, run, stepMetadata: undefined },\n async (): Promise<void> => {\n // Yield once so callers observe `pending` before execution begins,\n // mirroring the platform's enqueue-then-run lifecycle.\n await Promise.resolve()\n\n if (run.status === 'cancelled') return\n\n run.status = 'running'\n\n try {\n run.returnValue = await workflowFn(...args)\n\n if (run.status === 'running') run.status = 'completed'\n } catch (error) {\n run.runError = error\n\n if (run.status === 'running') run.status = 'failed'\n } finally {\n this.notifyChange(run)\n }\n }\n )\n\n return { runId }\n }\n\n async settled(runId: string): Promise<void> {\n await this.requireRun(runId).settled\n }\n\n inspect(runId: string): TestWorkflowRunInspection {\n const run = this.requireRun(runId)\n\n return {\n runId: run.runId,\n status: run.status,\n chunks: [...run.chunks],\n streamClosed: run.streamClosed,\n streamCloseCount: run.streamCloseCount,\n writeAfterCloseAttempts: run.writeAfterCloseAttempts,\n stepAttempts: new Map(run.stepAttempts),\n runError: run.runError\n }\n }\n\n status(runId: string): TestWorkflowRunStatus {\n return this.requireRun(runId).status\n }\n\n async cancel(runId: string): Promise<void> {\n const run = this.requireRun(runId)\n\n if (run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled') {\n throw new TestWorkflowRunConflictError(\n `Workflow run \"${runId}\" is already ${run.status} and cannot be cancelled`\n )\n }\n\n run.status = 'cancelled'\n\n for (const [token, hook] of run.hooks) {\n run.hooks.delete(token)\n hook.reject(new TestWorkflowRunCancelledError(runId))\n }\n\n this.notifyChange(run)\n }\n\n async resumeHook(token: string, payload: unknown): Promise<void> {\n for (const run of this.runs.values()) {\n const hook = run.hooks.get(token)\n\n if (hook !== undefined) {\n run.hooks.delete(token)\n run.resumedHookTokens.add(token)\n hook.resolve(payload)\n\n return\n }\n\n if (run.resumedHookTokens.has(token)) {\n throw new TestWorkflowHookConflictError(token)\n }\n }\n\n throw new TestWorkflowHookNotFoundError(token)\n }\n\n hasResumedHook(token: string): boolean {\n for (const run of this.runs.values()) {\n if (run.resumedHookTokens.has(token)) return true\n }\n\n return false\n }\n\n // --- Step executor (platform retry semantics) ---\n\n // Runs a step body with the platform's retry contract: `fn.maxRetries`\n // retries after the first attempt (total attempts = maxRetries + 1) and\n // 1-based `getStepMetadata().attempt` visible to the body.\n async runStep<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n args: TArgs,\n stepName = stepFn.name === '' ? 'step' : stepFn.name\n ): Promise<TResult> {\n const ambient = requireAmbient()\n const run = ambient.run\n run.stepSequence += 1\n const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`\n const maxRetries = stepFn.maxRetries ?? defaultTestWorkflowStepMaxRetries\n const maxAttempts = maxRetries + 1\n\n let attempt = 1\n\n for (;;) {\n run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1)\n\n try {\n return await ambientStorage.run(\n { world: this, run, stepMetadata: { attempt, stepId, stepName } },\n () => stepFn(...args)\n )\n } catch (error) {\n if (attempt >= maxAttempts) throw error\n attempt += 1\n }\n }\n }\n\n // Wraps a step function so orchestration code can invoke it exactly the way\n // the platform invokes `use step` functions: through the retry executor.\n step<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n stepName?: string\n ): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs) => this.runStep(stepFn, args, stepName)\n }\n\n // --- Ambient platform APIs (exposed through `testWorkflowModule`) ---\n\n static getWorkflowMetadata(): TestWorkflowMetadata {\n return { workflowRunId: requireAmbient().run.runId }\n }\n\n static getStepMetadata(): TestWorkflowStepMetadata {\n const ambient = requireAmbient()\n\n if (ambient.stepMetadata === undefined) {\n throw new Error('getStepMetadata called outside a step context')\n }\n\n return ambient.stepMetadata\n }\n\n static getWritable<T>(): WritableStream<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeWritable(ambient.run)\n }\n\n static createHook<T>(input: { readonly token: string }): TestWorkflowHook<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeHook<T>(ambient.run, input.token)\n }\n\n // --- Durable streams ---\n\n private makeWritable<T>(run: TestWorkflowRunRecord): WritableStream<T> {\n return new WritableStream<T>({\n write: chunk => {\n if (run.streamClosed || run.status === 'cancelled') {\n run.writeAfterCloseAttempts += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.chunks.push(chunk)\n this.notifyChange(run)\n },\n close: () => {\n if (run.streamClosed) {\n run.streamCloseCount += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.streamClosed = true\n run.streamCloseCount += 1\n this.notifyChange(run)\n }\n })\n }\n\n private makeHook<T>(run: TestWorkflowRunRecord, token: string): TestWorkflowHook<T> {\n let resolveHook: (payload: unknown) => void = () => {}\n\n let rejectHook: (error: TestWorkflowRunCancelledError) => void = () => {}\n\n const promise = new Promise<T>((resolve, reject) => {\n // SAFETY: Hook payloads are caller-typed on the platform (`createHook<T>`).\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n resolveHook = payload => resolve(payload as T)\n rejectHook = reject\n })\n\n run.hooks.set(token, { resolve: resolveHook, reject: rejectHook })\n\n return Object.assign(promise, {\n [Symbol.dispose]: () => {\n run.hooks.delete(token)\n }\n })\n }\n\n getReadable<T>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): VercelWorkflowReadableStream<T> {\n const run = this.requireRun(runId)\n const requestedStart = options?.startIndex ?? 0\n\n let index =\n requestedStart < 0 ? Math.max(0, run.chunks.length + requestedStart) : requestedStart\n\n const stream = new ReadableStream<T>({\n pull: async controller => {\n while (index >= run.chunks.length && !this.streamEnded(run)) {\n await this.nextChange(run)\n }\n\n if (index < run.chunks.length) {\n // SAFETY: The platform readable is caller-typed (`WorkflowReadableStream<R = any>`);\n // the durable log stores opaque chunks, so this coercion mirrors the\n // platform contract exactly.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n controller.enqueue(run.chunks[index] as T)\n index += 1\n\n return\n }\n\n controller.close()\n }\n })\n\n return Object.assign(stream, {\n getTailIndex: () => Promise.resolve(run.chunks.length - 1)\n })\n }\n\n private streamEnded(run: TestWorkflowRunRecord): boolean {\n return run.streamClosed || run.status === 'cancelled'\n }\n\n private notifyChange(run: TestWorkflowRunRecord): void {\n const listeners = [...run.changeListeners]\n run.changeListeners.clear()\n\n for (const listener of listeners) listener()\n }\n\n private nextChange(run: TestWorkflowRunRecord): Promise<void> {\n return new Promise(resolve => {\n run.changeListeners.add(resolve)\n })\n }\n\n private requireRun(runId: string): TestWorkflowRunRecord {\n const run = this.runs.get(runId)\n\n if (run === undefined) throw new TestWorkflowRunNotFoundError(runId)\n\n return run\n }\n\n // --- SDK adapter for `VercelWorkflows.layerFromSdk` ---\n\n private sdkRun<TResult>(run: TestWorkflowRunRecord): VercelWorkflowsSdkRun<TResult> {\n const getReadable = <Chunk>(options?: VercelWorkflowReadableOptions) =>\n this.getReadable<Chunk>(run.runId, options)\n\n const cancel = () => this.cancel(run.runId)\n\n return {\n runId: run.runId,\n getReadable,\n cancel,\n get status() {\n return Promise.resolve(run.status)\n },\n get returnValue() {\n return run.settled.then(() => {\n if (run.status === 'completed') {\n // SAFETY: Return values are caller-typed on the platform SDK as well.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return run.returnValue as TResult\n }\n\n throw run.runError ?? new TestWorkflowRunCancelledError(run.runId)\n })\n }\n }\n }\n\n readonly sdk: VercelWorkflowsSdkClient = {\n start: async (workflowFn, args) => {\n const { runId } = this.start(workflowFn, args)\n\n return this.sdkRun(this.requireRun(runId))\n },\n getRun: <TResult>(runId: string) => this.sdkRun<TResult>(this.requireRun(runId)),\n resumeHook: (token, payload) => this.resumeHook(token, payload)\n }\n}\n\n// Factory for `vi.mock('workflow', () => testWorkflowModule)`: the mocked\n// module surface delegates every ambient platform API to the active world's\n// AsyncLocalStorage context, so production code under test runs unmodified.\nexport const testWorkflowModule = {\n getWorkflowMetadata: () => TestWorkflowWorld.getWorkflowMetadata(),\n getStepMetadata: () => TestWorkflowWorld.getStepMetadata(),\n getWritable: <T>() => TestWorkflowWorld.getWritable<T>(),\n createHook: <T>(input: { readonly token: string }) => TestWorkflowWorld.createHook<T>(input)\n}\n"],"mappings":";;AA2BA,IAAa,kCAAb,cAAqD,MAAM;CACzD,OAAyB;CACzB,SAAkB;CAElB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,2BAA2B;CAC1D;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CACzB,SAAkB;CAElB,YAAY,SAAiB;EAC3B,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,kBAAkB,MAAM,gBAAgB;CAChD;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,kBAAkB,MAAM,sBAAsB;CACtD;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,gBAAgB;CAC/C;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,gBAAgB;CAC/C;AACF;AAeA,MAAa,oCAAoC;AA8BjD,MAAM,iBAAiB,IAAI,kBAAkC;AAE7D,MAAM,uBAAuC;CAC3C,MAAM,UAAU,eAAe,SAAS;CAExC,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,qEAAqE;CAGvF,OAAO;AACT;AAiBA,IAAa,oBAAb,MAA+B;CAC7B,uBAAwB,IAAI,IAAmC;CAC/D,cAAsB;CAEtB,MACE,YACA,MAC8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,KAAK,YAAmB,IAAI,OAAO,OAAO;EAE5C,MAAM,eAAe,KAAK,OAAO,IAAI,KAAK;EAE1C,OAAO;GACL,OAAO,IAAI;GACX;GACA;GACA,IAAI,SAAS;IACX,OAAO,QAAQ,QAAQ,IAAI,MAAM;GACnC;GACA,IAAI,cAAc;IAChB,OAAO,IAAI,QAAQ,WAAW;KAC5B,IAAI,IAAI,WAAW,aAGjB,OAAO,IAAI;KAGb,MAAM,IAAI,YAAY,IAAI,8BAA8B,IAAI,KAAK;IACnE,CAAC;GACH;EACF;CACF;CAEA,MAAyC;EACvC,OAAO,OAAO,YAAY,SAAS;GACjC,MAAM,EAAE,UAAU,KAAK,MAAM,YAAY,IAAI;GAE7C,OAAO,KAAK,OAAO,KAAK,WAAW,KAAK,CAAC;EAC3C;EACA,SAAkB,UAAkB,KAAK,OAAgB,KAAK,WAAW,KAAK,CAAC;EAC/E,aAAa,OAAO,YAAY,KAAK,WAAW,OAAO,OAAO;CAChE;AACF;AAKA,MAAa,qBAAqB;CAChC,2BAA2B,kBAAkB,oBAAoB;CACjE,uBAAuB,kBAAkB,gBAAgB;CACzD,mBAAsB,kBAAkB,YAAe;CACvD,aAAgB,UAAsC,kBAAkB,WAAc,KAAK;AAC7F"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { types } from 'node:util'\nimport path from 'node:path'\nimport { Predicate } from 'effect'\nimport type {\n VercelWorkflowsSdkClient,\n VercelWorkflowsSdkRun,\n VercelWorkflowReadableOptions,\n VercelWorkflowReadableStream,\n VercelWorkflowRunStatus\n} from '../effect.ts'\n\n// Behavioral emulator of the Vercel Workflow platform for tests: run lifecycle,\n// append-only durable streams with close-once -> 409 write conflicts, a step\n// executor honoring `fn.maxRetries` + `getStepMetadata().attempt`, hooks/resume,\n// and cancellation. Host code under test runs unmodified against it; tests mock\n// only the `workflow` module's ambient APIs, delegating to the active world\n// (see `testWorkflowModule`).\n//\n// Step errors cross the platform boundary the way they do in a deployment: each one is stored with\n// the installed `workflow` runtime's own step-error serializer, and the workflow body sees only the\n// value read back (error tags, prototypes and custom fields are gone; a `cause` survives). A thrown\n// value the serializer cannot store (a class instance anywhere in its `cause` chain) never reaches\n// the body: the platform's queue handler fails and redelivers the step, which runs again until its\n// retries run out and it fails with \"exceeded max retries\" (see `unstorableStepErrors`).\n//\n// The single most important semantic: writing to (or re-closing) a closed\n// durable stream fails with the platform's HTTP 409 \"already completed\"\n// conflict shape. Any code path that performs a terminal stream effect from a\n// retryable step attempt poisons every subsequent platform retry — exactly the\n// #252 production bug. The emulator enforces that invariant permanently.\n\nexport type TestWorkflowRunStatus = VercelWorkflowRunStatus\n\n// Matches the platform's conflict contract: `EntityConflictError.is(value)`\n// checks `value.name === 'EntityConflictError'`, and the Vercel world maps\n// HTTP 409 responses to that class.\nexport class TestWorkflowStreamConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" stream already completed`)\n }\n}\n\nexport class TestWorkflowRunConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(message: string) {\n super(message)\n }\n}\n\nexport class TestWorkflowHookNotFoundError extends Error {\n override readonly name = 'HookNotFoundError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was not found`)\n }\n}\n\nexport class TestWorkflowHookConflictError extends Error {\n override readonly name = 'HookConflictError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was already resumed`)\n }\n}\n\nexport class TestWorkflowRunNotFoundError extends Error {\n override readonly name = 'WorkflowRunNotFoundError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was not found`)\n }\n}\n\nexport class TestWorkflowRunCancelledError extends Error {\n override readonly name = 'WorkflowRunCancelledError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was cancelled`)\n }\n}\n\nexport type TestWorkflowMetadata = { readonly workflowRunId: string }\n\nexport type TestWorkflowStepMetadata = {\n readonly attempt: number\n readonly stepId: string\n readonly stepName: string\n}\n\n/** A thrown step value the platform could not store; the step was redelivered instead. */\nexport type TestWorkflowUnstorableStepError = {\n readonly stepName: string\n readonly attempt: number\n readonly error: unknown\n}\n\nexport type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((\n ...args: TArgs\n) => Promise<TResult>) & { readonly maxRetries?: number }\n\n// The platform default: retries after the first attempt; total attempts = maxRetries + 1.\nexport const defaultTestWorkflowStepMaxRetries = 3\n\ntype HookRecord = {\n readonly resolve: (payload: unknown) => void\n readonly reject: (error: TestWorkflowRunCancelledError) => void\n}\n\ntype TestWorkflowRunRecord = {\n readonly runId: string\n status: TestWorkflowRunStatus\n returnValue: unknown\n runError: unknown\n settled: Promise<void>\n readonly chunks: Array<unknown>\n streamClosed: boolean\n streamCloseCount: number\n writeAfterCloseAttempts: number\n readonly changeListeners: Set<() => void>\n readonly hooks: Map<string, HookRecord>\n readonly resumedHookTokens: Set<string>\n stepSequence: number\n readonly stepAttempts: Map<string, number>\n readonly unstorableStepErrors: Array<TestWorkflowUnstorableStepError>\n}\n\ntype AmbientContext = {\n readonly world: TestWorkflowWorld\n readonly run: TestWorkflowRunRecord\n readonly stepMetadata: TestWorkflowStepMetadata | undefined\n}\n\nconst ambientStorage = new AsyncLocalStorage<AmbientContext>()\n\nconst requireAmbient = (): AmbientContext => {\n const ambient = ambientStorage.getStore()\n\n if (ambient === undefined) {\n throw new Error('Workflow ambient API called outside a TestWorkflowWorld run context')\n }\n\n return ambient\n}\n\ntype StepErrorSerializer = {\n /** Undefined when the platform cannot store the value (its `SerializationError`). */\n readonly dehydrate: (error: unknown, runId: string) => Promise<Uint8Array | undefined>\n readonly hydrate: (bytes: Uint8Array, runId: string) => Promise<unknown>\n}\n\nlet stepErrorSerializer: Promise<StepErrorSerializer> | undefined\n\nconst workflowPackageDir = (require: NodeJS.Require) => {\n let dir = path.dirname(require.resolve('workflow'))\n\n while (!fs.existsSync(path.join(dir, 'package.json'))) {\n const parent = path.dirname(dir)\n\n if (parent === dir) throw new Error('Cannot locate the installed workflow package')\n\n dir = parent\n }\n\n return dir\n}\n\n// The installed `workflow` runtime's own step-error serializer (`@workflow/core`, resolved\n// through `workflow`'s package so its version matches the host's), loaded natively: a\n// `vi.mock('workflow')` of the ambient module never replaces it.\nconst loadStepErrorSerializer = (): Promise<StepErrorSerializer> =>\n (stepErrorSerializer ??= (async () => {\n const require = createRequire(import.meta.url)\n\n const serialization: unknown = await import(\n require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] })\n ).catch((cause: unknown) => {\n // Workflow 5 captures Node `URL` intrinsics when its serializer loads; jsdom's fail.\n throw new Error(\n 'TestWorkflowWorld cannot load the workflow step-error serializer (under jsdom: step execution needs the Node test environment)',\n { cause }\n )\n })\n\n if (\n !Predicate.hasProperty(serialization, 'dehydrateStepError') ||\n !Predicate.hasProperty(serialization, 'hydrateStepError') ||\n !Predicate.isFunction(serialization.dehydrateStepError) ||\n !Predicate.isFunction(serialization.hydrateStepError)\n ) {\n throw new Error('The installed workflow runtime has no step-error serializer')\n }\n\n const { dehydrateStepError, hydrateStepError } = serialization\n\n return {\n dehydrate: async (error, runId) => {\n let bytes: unknown\n\n try {\n bytes = await dehydrateStepError(error, runId, undefined)\n } catch (failure) {\n // The platform reframes every failure to store a value as `SerializationError`; any\n // other failure is this emulator's integration breaking, never the host's error.\n if (Predicate.hasProperty(failure, 'name') && failure.name === 'SerializationError') {\n return undefined\n }\n\n throw failure\n }\n\n if (!(bytes instanceof Uint8Array)) {\n throw new Error('The workflow step-error serializer returned no bytes')\n }\n\n return bytes\n },\n hydrate: async (bytes, runId) => {\n const error: unknown = await hydrateStepError(bytes, runId, undefined)\n\n return error\n }\n }\n })())\n\n// The platform's error shape check (`@workflow/errors`): duck-typed, so it holds across realms.\nconst isPlatformError = (value: unknown) =>\n Predicate.hasProperty(value, 'name') && Predicate.hasProperty(value, 'message')\n\n// `FatalError.is`: named `FatalError`, or carrying `fatal: true`.\nconst isFatalStepError = (value: unknown) =>\n isPlatformError(value) &&\n ((Predicate.hasProperty(value, 'name') && value.name === 'FatalError') ||\n (Predicate.hasProperty(value, 'fatal') && value.fatal === true))\n\n// The platform turns an abort into a FatalError before classifying a step error\n// (`promoteAbortErrorToFatal`), so an aborted step is never retried.\nconst promoteAbortError = (value: unknown) => {\n if (\n !Predicate.hasProperty(value, 'name') ||\n value.name !== 'AbortError' ||\n !Predicate.hasProperty(value, 'message') ||\n !Predicate.isString(value.message) ||\n (Predicate.hasProperty(value, 'stack') &&\n value.stack !== undefined &&\n !Predicate.isString(value.stack)) ||\n isFatalStepError(value)\n ) {\n return value\n }\n\n const fatal = platformFatalError(`Aborted: ${value.message}`, undefined)\n\n if (Predicate.hasProperty(value, 'stack') && Predicate.isString(value.stack)) {\n fatal.stack = value.stack\n }\n\n return fatal\n}\n\n// Stored and read back, an error named `FatalError` is the platform's FatalError.\nconst platformFatalError = (message: string, cause: unknown) => {\n const error = cause === undefined ? new Error(message) : new Error(message, { cause })\n\n error.name = 'FatalError'\n\n return error\n}\n\n// The platform's `normalizeUnknownError` message: an error's message, a string as is, anything\n// else as JSON (else `String`), and an awaited thenable prefixed `Promise rejection: `.\nconst platformErrorMessage = async (value: unknown): Promise<string> => {\n if (Predicate.hasProperty(value, 'then') && Predicate.isFunction(value.then)) {\n try {\n return `Promise rejection: ${await platformErrorMessage(await value)}`\n } catch (rejection) {\n return `Promise rejection: ${await platformErrorMessage(rejection)}`\n }\n }\n\n if (types.isNativeError(value)) return value.message\n\n if (Predicate.isString(value)) return value\n\n try {\n return String(JSON.stringify(value))\n } catch {\n return String(value)\n }\n}\n\nconst retriesLabel = (count: number) => (count === 1 ? 'retry' : 'retries')\n\nexport type TestWorkflowRunInspection = {\n readonly runId: string\n readonly status: TestWorkflowRunStatus\n readonly chunks: ReadonlyArray<unknown>\n readonly streamClosed: boolean\n readonly streamCloseCount: number\n readonly writeAfterCloseAttempts: number\n readonly stepAttempts: ReadonlyMap<string, number>\n readonly runError: unknown\n /** Every thrown step value the platform could not store, in order. */\n readonly unstorableStepErrors: ReadonlyArray<TestWorkflowUnstorableStepError>\n}\n\nexport type TestWorkflowHook<T> = Promise<T> & { readonly [Symbol.dispose]: () => void }\n\ntype TestWorkflowWorldStartResult = { readonly runId: string }\n\nexport class TestWorkflowWorld {\n private readonly runs = new Map<string, TestWorkflowRunRecord>()\n private runSequence = 0\n\n start<TArgs extends ReadonlyArray<unknown>, TResult>(\n workflowFn: (...args: TArgs) => Promise<TResult>,\n args: TArgs\n ): TestWorkflowWorldStartResult {\n this.runSequence += 1\n const runId = `twr_${this.runSequence}`\n\n const run: TestWorkflowRunRecord = {\n runId,\n status: 'pending',\n returnValue: undefined,\n runError: undefined,\n settled: Promise.resolve(),\n chunks: [],\n streamClosed: false,\n streamCloseCount: 0,\n writeAfterCloseAttempts: 0,\n changeListeners: new Set(),\n hooks: new Map(),\n resumedHookTokens: new Set(),\n stepSequence: 0,\n stepAttempts: new Map(),\n unstorableStepErrors: []\n }\n\n this.runs.set(runId, run)\n\n run.settled = ambientStorage.run(\n { world: this, run, stepMetadata: undefined },\n async (): Promise<void> => {\n // Yield once so callers observe `pending` before execution begins,\n // mirroring the platform's enqueue-then-run lifecycle.\n await Promise.resolve()\n\n if (run.status === 'cancelled') return\n\n run.status = 'running'\n\n try {\n run.returnValue = await workflowFn(...args)\n\n if (run.status === 'running') run.status = 'completed'\n } catch (error) {\n run.runError = error\n\n if (run.status === 'running') run.status = 'failed'\n } finally {\n this.notifyChange(run)\n }\n }\n )\n\n return { runId }\n }\n\n async settled(runId: string): Promise<void> {\n await this.requireRun(runId).settled\n }\n\n inspect(runId: string): TestWorkflowRunInspection {\n const run = this.requireRun(runId)\n\n return {\n runId: run.runId,\n status: run.status,\n chunks: [...run.chunks],\n streamClosed: run.streamClosed,\n streamCloseCount: run.streamCloseCount,\n writeAfterCloseAttempts: run.writeAfterCloseAttempts,\n stepAttempts: new Map(run.stepAttempts),\n runError: run.runError,\n unstorableStepErrors: [...run.unstorableStepErrors]\n }\n }\n\n status(runId: string): TestWorkflowRunStatus {\n return this.requireRun(runId).status\n }\n\n async cancel(runId: string): Promise<void> {\n const run = this.requireRun(runId)\n\n if (run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled') {\n throw new TestWorkflowRunConflictError(\n `Workflow run \"${runId}\" is already ${run.status} and cannot be cancelled`\n )\n }\n\n run.status = 'cancelled'\n\n for (const [token, hook] of run.hooks) {\n run.hooks.delete(token)\n hook.reject(new TestWorkflowRunCancelledError(runId))\n }\n\n this.notifyChange(run)\n }\n\n async resumeHook(token: string, payload: unknown): Promise<void> {\n for (const run of this.runs.values()) {\n const hook = run.hooks.get(token)\n\n if (hook !== undefined) {\n run.hooks.delete(token)\n run.resumedHookTokens.add(token)\n hook.resolve(payload)\n\n return\n }\n\n if (run.resumedHookTokens.has(token)) {\n throw new TestWorkflowHookConflictError(token)\n }\n }\n\n throw new TestWorkflowHookNotFoundError(token)\n }\n\n hasResumedHook(token: string): boolean {\n for (const run of this.runs.values()) {\n if (run.resumedHookTokens.has(token)) return true\n }\n\n return false\n }\n\n // --- Step executor (platform retry semantics) ---\n\n // Runs a step body with the platform's retry contract: `fn.maxRetries`\n // retries after the first attempt (total attempts = maxRetries + 1) and\n // 1-based `getStepMetadata().attempt` visible to the body. A FatalError\n // (by `name`, or `fatal: true`; an AbortError is promoted to one) is never\n // retried; an exhausted step fails with the platform's FatalError whose\n // `cause` is the last thrown value. The caller sees errors only as the\n // platform stores and reads them back.\n async runStep<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n args: TArgs,\n stepName = stepFn.name === '' ? 'step' : stepFn.name\n ): Promise<TResult> {\n const ambient = requireAmbient()\n const run = ambient.run\n run.stepSequence += 1\n const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`\n const maxRetries = stepFn.maxRetries ?? defaultTestWorkflowStepMaxRetries\n const maxAttempts = maxRetries + 1\n const serializer = await loadStepErrorSerializer()\n\n let attempt = 1\n\n for (;;) {\n run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1)\n\n let thrown: unknown\n\n try {\n return await ambientStorage.run(\n { world: this, run, stepMetadata: { attempt, stepId, stepName } },\n () => stepFn(...args)\n )\n } catch (error) {\n thrown = error\n }\n\n const effective = promoteAbortError(thrown)\n // Normalized on every attempt, as the platform does: a thrown thenable is awaited here.\n const message = await platformErrorMessage(effective)\n const fatal = isFatalStepError(effective)\n const exhausted = !fatal && attempt >= maxAttempts\n\n // A fatal error is stored as is (abort promoted); an exhausted step's error becomes the\n // cause of the platform's FatalError; a retried attempt stores the thrown value.\n const recorded = fatal\n ? effective\n : exhausted\n ? platformFatalError(\n `Step \"${stepName}\" failed after ${maxRetries} ${retriesLabel(maxRetries)}: ${message}`,\n thrown\n )\n : thrown\n\n const bytes = await serializer.dehydrate(recorded, run.runId)\n\n if (bytes === undefined) {\n // The platform cannot record this attempt: its queue handler fails and the\n // redelivered message runs the step again as the next attempt.\n run.unstorableStepErrors.push({ stepName, attempt, error: thrown })\n\n if (attempt >= maxAttempts) {\n // The redelivery past the budget fails the step before running it again.\n const exceeded = await serializer.dehydrate(\n platformFatalError(\n `Step \"${stepName}\" exceeded max retries (${maxRetries} ${retriesLabel(maxRetries)})`,\n undefined\n ),\n run.runId\n )\n\n if (exceeded === undefined)\n throw new Error('The workflow runtime cannot store a FatalError')\n\n throw await serializer.hydrate(exceeded, run.runId)\n }\n\n attempt += 1\n continue\n }\n\n if (fatal || exhausted) throw await serializer.hydrate(bytes, run.runId)\n\n attempt += 1\n }\n }\n\n // Wraps a step function so orchestration code can invoke it exactly the way\n // the platform invokes `use step` functions: through the retry executor.\n step<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n stepName?: string\n ): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs) => this.runStep(stepFn, args, stepName)\n }\n\n // --- Ambient platform APIs (exposed through `testWorkflowModule`) ---\n\n static getWorkflowMetadata(): TestWorkflowMetadata {\n return { workflowRunId: requireAmbient().run.runId }\n }\n\n static getStepMetadata(): TestWorkflowStepMetadata {\n const ambient = requireAmbient()\n\n if (ambient.stepMetadata === undefined) {\n throw new Error('getStepMetadata called outside a step context')\n }\n\n return ambient.stepMetadata\n }\n\n static getWritable<T>(): WritableStream<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeWritable(ambient.run)\n }\n\n static createHook<T>(input: { readonly token: string }): TestWorkflowHook<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeHook<T>(ambient.run, input.token)\n }\n\n // --- Durable streams ---\n\n private makeWritable<T>(run: TestWorkflowRunRecord): WritableStream<T> {\n return new WritableStream<T>({\n write: chunk => {\n if (run.streamClosed || run.status === 'cancelled') {\n run.writeAfterCloseAttempts += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.chunks.push(chunk)\n this.notifyChange(run)\n },\n close: () => {\n if (run.streamClosed) {\n run.streamCloseCount += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.streamClosed = true\n run.streamCloseCount += 1\n this.notifyChange(run)\n }\n })\n }\n\n private makeHook<T>(run: TestWorkflowRunRecord, token: string): TestWorkflowHook<T> {\n let resolveHook: (payload: unknown) => void = () => {}\n\n let rejectHook: (error: TestWorkflowRunCancelledError) => void = () => {}\n\n const promise = new Promise<T>((resolve, reject) => {\n // SAFETY: Hook payloads are caller-typed on the platform (`createHook<T>`).\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n resolveHook = payload => resolve(payload as T)\n rejectHook = reject\n })\n\n run.hooks.set(token, { resolve: resolveHook, reject: rejectHook })\n\n return Object.assign(promise, {\n [Symbol.dispose]: () => {\n run.hooks.delete(token)\n }\n })\n }\n\n getReadable<T>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): VercelWorkflowReadableStream<T> {\n const run = this.requireRun(runId)\n const requestedStart = options?.startIndex ?? 0\n\n let index =\n requestedStart < 0 ? Math.max(0, run.chunks.length + requestedStart) : requestedStart\n\n const stream = new ReadableStream<T>({\n pull: async controller => {\n while (index >= run.chunks.length && !this.streamEnded(run)) {\n await this.nextChange(run)\n }\n\n if (index < run.chunks.length) {\n // SAFETY: The platform readable is caller-typed (`WorkflowReadableStream<R = any>`);\n // the durable log stores opaque chunks, so this coercion mirrors the\n // platform contract exactly.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n controller.enqueue(run.chunks[index] as T)\n index += 1\n\n return\n }\n\n controller.close()\n }\n })\n\n return Object.assign(stream, {\n getTailIndex: () => Promise.resolve(run.chunks.length - 1)\n })\n }\n\n private streamEnded(run: TestWorkflowRunRecord): boolean {\n return run.streamClosed || run.status === 'cancelled'\n }\n\n private notifyChange(run: TestWorkflowRunRecord): void {\n const listeners = [...run.changeListeners]\n run.changeListeners.clear()\n\n for (const listener of listeners) listener()\n }\n\n private nextChange(run: TestWorkflowRunRecord): Promise<void> {\n return new Promise(resolve => {\n run.changeListeners.add(resolve)\n })\n }\n\n private requireRun(runId: string): TestWorkflowRunRecord {\n const run = this.runs.get(runId)\n\n if (run === undefined) throw new TestWorkflowRunNotFoundError(runId)\n\n return run\n }\n\n // --- SDK adapter for `VercelWorkflows.layerFromSdk` ---\n\n private sdkRun<TResult>(run: TestWorkflowRunRecord): VercelWorkflowsSdkRun<TResult> {\n const getReadable = <Chunk>(options?: VercelWorkflowReadableOptions) =>\n this.getReadable<Chunk>(run.runId, options)\n\n const cancel = () => this.cancel(run.runId)\n\n return {\n runId: run.runId,\n getReadable,\n cancel,\n get status() {\n return Promise.resolve(run.status)\n },\n get returnValue() {\n return run.settled.then(() => {\n if (run.status === 'completed') {\n // SAFETY: Return values are caller-typed on the platform SDK as well.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return run.returnValue as TResult\n }\n\n throw run.runError ?? new TestWorkflowRunCancelledError(run.runId)\n })\n }\n }\n }\n\n readonly sdk: VercelWorkflowsSdkClient = {\n start: async (workflowFn, args) => {\n const { runId } = this.start(workflowFn, args)\n\n return this.sdkRun(this.requireRun(runId))\n },\n getRun: <TResult>(runId: string) => this.sdkRun<TResult>(this.requireRun(runId)),\n resumeHook: (token, payload) => this.resumeHook(token, payload)\n }\n}\n\n// Factory for `vi.mock('workflow', () => testWorkflowModule)`: the mocked\n// module surface delegates every ambient platform API to the active world's\n// AsyncLocalStorage context, so production code under test runs unmodified.\nexport const testWorkflowModule = {\n getWorkflowMetadata: () => TestWorkflowWorld.getWorkflowMetadata(),\n getStepMetadata: () => TestWorkflowWorld.getStepMetadata(),\n getWritable: <T>() => TestWorkflowWorld.getWritable<T>(),\n createHook: <T>(input: { readonly token: string }) => TestWorkflowWorld.createHook<T>(input)\n}\n"],"mappings":";;;;;;;AAuCA,IAAa,kCAAb,cAAqD,MAAM;CACzD,OAAyB;CACzB,SAAkB;CAElB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,2BAA2B;CAC1D;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CACzB,SAAkB;CAElB,YAAY,SAAiB;EAC3B,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,kBAAkB,MAAM,gBAAgB;CAChD;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,kBAAkB,MAAM,sBAAsB;CACtD;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,gBAAgB;CAC/C;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,gBAA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,KAAK,OAAO,IAAI,KAAK;EAE1C,OAAO;GACL,OAAO,IAAI;GACX;GACA;GACA,IAAI,SAAS;IACX,OAAO,QAAQ,QAAQ,IAAI,MAAM;GACnC;GACA,IAAI,cAAc;IAChB,OAAO,IAAI,QAAQ,WAAW;KAC5B,IAAI,IAAI,WAAW,aAGjB,OAAO,IAAI;KAGb,MAAM,IAAI,YAAY,IAAI,8BAA8B,IAAI,KAAK;IACnE,CAAC;GACH;EACF;CACF;CAEA,MAAyC;EACvC,OAAO,OAAO,YAAY,SAAS;GACjC,MAAM,EAAE,UAAU,KAAK,MAAM,YAAY,IAAI;GAE7C,OAAO,KAAK,OAAO,KAAK,WAAW,KAAK,CAAC;EAC3C;EACA,SAAkB,UAAkB,KAAK,OAAgB,KAAK,WAAW,KAAK,CAAC;EAC/E,aAAa,OAAO,YAAY,KAAK,WAAW,OAAO,OAAO;CAChE;AACF;AAKA,MAAa,qBAAqB;CAChC,2BAA2B,kBAAkB,oBAAoB;CACjE,uBAAuB,kBAAkB,gBAAgB;CACzD,mBAAsB,kBAAkB,YAAe;CACvD,aAAgB,UAAsC,kBAAkB,WAAc,KAAK;AAC7F"}
|
package/package.json
CHANGED
package/src/testing/index.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { types } from 'node:util'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { Predicate } from 'effect'
|
|
2
7
|
import type {
|
|
3
8
|
VercelWorkflowsSdkClient,
|
|
4
9
|
VercelWorkflowsSdkRun,
|
|
@@ -14,6 +19,13 @@ import type {
|
|
|
14
19
|
// only the `workflow` module's ambient APIs, delegating to the active world
|
|
15
20
|
// (see `testWorkflowModule`).
|
|
16
21
|
//
|
|
22
|
+
// Step errors cross the platform boundary the way they do in a deployment: each one is stored with
|
|
23
|
+
// the installed `workflow` runtime's own step-error serializer, and the workflow body sees only the
|
|
24
|
+
// value read back (error tags, prototypes and custom fields are gone; a `cause` survives). A thrown
|
|
25
|
+
// value the serializer cannot store (a class instance anywhere in its `cause` chain) never reaches
|
|
26
|
+
// the body: the platform's queue handler fails and redelivers the step, which runs again until its
|
|
27
|
+
// retries run out and it fails with "exceeded max retries" (see `unstorableStepErrors`).
|
|
28
|
+
//
|
|
17
29
|
// The single most important semantic: writing to (or re-closing) a closed
|
|
18
30
|
// durable stream fails with the platform's HTTP 409 "already completed"
|
|
19
31
|
// conflict shape. Any code path that performs a terminal stream effect from a
|
|
@@ -83,6 +95,13 @@ export type TestWorkflowStepMetadata = {
|
|
|
83
95
|
readonly stepName: string
|
|
84
96
|
}
|
|
85
97
|
|
|
98
|
+
/** A thrown step value the platform could not store; the step was redelivered instead. */
|
|
99
|
+
export type TestWorkflowUnstorableStepError = {
|
|
100
|
+
readonly stepName: string
|
|
101
|
+
readonly attempt: number
|
|
102
|
+
readonly error: unknown
|
|
103
|
+
}
|
|
104
|
+
|
|
86
105
|
export type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((
|
|
87
106
|
...args: TArgs
|
|
88
107
|
) => Promise<TResult>) & { readonly maxRetries?: number }
|
|
@@ -110,6 +129,7 @@ type TestWorkflowRunRecord = {
|
|
|
110
129
|
readonly resumedHookTokens: Set<string>
|
|
111
130
|
stepSequence: number
|
|
112
131
|
readonly stepAttempts: Map<string, number>
|
|
132
|
+
readonly unstorableStepErrors: Array<TestWorkflowUnstorableStepError>
|
|
113
133
|
}
|
|
114
134
|
|
|
115
135
|
type AmbientContext = {
|
|
@@ -130,6 +150,154 @@ const requireAmbient = (): AmbientContext => {
|
|
|
130
150
|
return ambient
|
|
131
151
|
}
|
|
132
152
|
|
|
153
|
+
type StepErrorSerializer = {
|
|
154
|
+
/** Undefined when the platform cannot store the value (its `SerializationError`). */
|
|
155
|
+
readonly dehydrate: (error: unknown, runId: string) => Promise<Uint8Array | undefined>
|
|
156
|
+
readonly hydrate: (bytes: Uint8Array, runId: string) => Promise<unknown>
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
let stepErrorSerializer: Promise<StepErrorSerializer> | undefined
|
|
160
|
+
|
|
161
|
+
const workflowPackageDir = (require: NodeJS.Require) => {
|
|
162
|
+
let dir = path.dirname(require.resolve('workflow'))
|
|
163
|
+
|
|
164
|
+
while (!fs.existsSync(path.join(dir, 'package.json'))) {
|
|
165
|
+
const parent = path.dirname(dir)
|
|
166
|
+
|
|
167
|
+
if (parent === dir) throw new Error('Cannot locate the installed workflow package')
|
|
168
|
+
|
|
169
|
+
dir = parent
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return dir
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The installed `workflow` runtime's own step-error serializer (`@workflow/core`, resolved
|
|
176
|
+
// through `workflow`'s package so its version matches the host's), loaded natively: a
|
|
177
|
+
// `vi.mock('workflow')` of the ambient module never replaces it.
|
|
178
|
+
const loadStepErrorSerializer = (): Promise<StepErrorSerializer> =>
|
|
179
|
+
(stepErrorSerializer ??= (async () => {
|
|
180
|
+
const require = createRequire(import.meta.url)
|
|
181
|
+
|
|
182
|
+
const serialization: unknown = await import(
|
|
183
|
+
require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] })
|
|
184
|
+
).catch((cause: unknown) => {
|
|
185
|
+
// Workflow 5 captures Node `URL` intrinsics when its serializer loads; jsdom's fail.
|
|
186
|
+
throw new Error(
|
|
187
|
+
'TestWorkflowWorld cannot load the workflow step-error serializer (under jsdom: step execution needs the Node test environment)',
|
|
188
|
+
{ cause }
|
|
189
|
+
)
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
if (
|
|
193
|
+
!Predicate.hasProperty(serialization, 'dehydrateStepError') ||
|
|
194
|
+
!Predicate.hasProperty(serialization, 'hydrateStepError') ||
|
|
195
|
+
!Predicate.isFunction(serialization.dehydrateStepError) ||
|
|
196
|
+
!Predicate.isFunction(serialization.hydrateStepError)
|
|
197
|
+
) {
|
|
198
|
+
throw new Error('The installed workflow runtime has no step-error serializer')
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const { dehydrateStepError, hydrateStepError } = serialization
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
dehydrate: async (error, runId) => {
|
|
205
|
+
let bytes: unknown
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
bytes = await dehydrateStepError(error, runId, undefined)
|
|
209
|
+
} catch (failure) {
|
|
210
|
+
// The platform reframes every failure to store a value as `SerializationError`; any
|
|
211
|
+
// other failure is this emulator's integration breaking, never the host's error.
|
|
212
|
+
if (Predicate.hasProperty(failure, 'name') && failure.name === 'SerializationError') {
|
|
213
|
+
return undefined
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
throw failure
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
220
|
+
throw new Error('The workflow step-error serializer returned no bytes')
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return bytes
|
|
224
|
+
},
|
|
225
|
+
hydrate: async (bytes, runId) => {
|
|
226
|
+
const error: unknown = await hydrateStepError(bytes, runId, undefined)
|
|
227
|
+
|
|
228
|
+
return error
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
})())
|
|
232
|
+
|
|
233
|
+
// The platform's error shape check (`@workflow/errors`): duck-typed, so it holds across realms.
|
|
234
|
+
const isPlatformError = (value: unknown) =>
|
|
235
|
+
Predicate.hasProperty(value, 'name') && Predicate.hasProperty(value, 'message')
|
|
236
|
+
|
|
237
|
+
// `FatalError.is`: named `FatalError`, or carrying `fatal: true`.
|
|
238
|
+
const isFatalStepError = (value: unknown) =>
|
|
239
|
+
isPlatformError(value) &&
|
|
240
|
+
((Predicate.hasProperty(value, 'name') && value.name === 'FatalError') ||
|
|
241
|
+
(Predicate.hasProperty(value, 'fatal') && value.fatal === true))
|
|
242
|
+
|
|
243
|
+
// The platform turns an abort into a FatalError before classifying a step error
|
|
244
|
+
// (`promoteAbortErrorToFatal`), so an aborted step is never retried.
|
|
245
|
+
const promoteAbortError = (value: unknown) => {
|
|
246
|
+
if (
|
|
247
|
+
!Predicate.hasProperty(value, 'name') ||
|
|
248
|
+
value.name !== 'AbortError' ||
|
|
249
|
+
!Predicate.hasProperty(value, 'message') ||
|
|
250
|
+
!Predicate.isString(value.message) ||
|
|
251
|
+
(Predicate.hasProperty(value, 'stack') &&
|
|
252
|
+
value.stack !== undefined &&
|
|
253
|
+
!Predicate.isString(value.stack)) ||
|
|
254
|
+
isFatalStepError(value)
|
|
255
|
+
) {
|
|
256
|
+
return value
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const fatal = platformFatalError(`Aborted: ${value.message}`, undefined)
|
|
260
|
+
|
|
261
|
+
if (Predicate.hasProperty(value, 'stack') && Predicate.isString(value.stack)) {
|
|
262
|
+
fatal.stack = value.stack
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return fatal
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Stored and read back, an error named `FatalError` is the platform's FatalError.
|
|
269
|
+
const platformFatalError = (message: string, cause: unknown) => {
|
|
270
|
+
const error = cause === undefined ? new Error(message) : new Error(message, { cause })
|
|
271
|
+
|
|
272
|
+
error.name = 'FatalError'
|
|
273
|
+
|
|
274
|
+
return error
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The platform's `normalizeUnknownError` message: an error's message, a string as is, anything
|
|
278
|
+
// else as JSON (else `String`), and an awaited thenable prefixed `Promise rejection: `.
|
|
279
|
+
const platformErrorMessage = async (value: unknown): Promise<string> => {
|
|
280
|
+
if (Predicate.hasProperty(value, 'then') && Predicate.isFunction(value.then)) {
|
|
281
|
+
try {
|
|
282
|
+
return `Promise rejection: ${await platformErrorMessage(await value)}`
|
|
283
|
+
} catch (rejection) {
|
|
284
|
+
return `Promise rejection: ${await platformErrorMessage(rejection)}`
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (types.isNativeError(value)) return value.message
|
|
289
|
+
|
|
290
|
+
if (Predicate.isString(value)) return value
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
return String(JSON.stringify(value))
|
|
294
|
+
} catch {
|
|
295
|
+
return String(value)
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const retriesLabel = (count: number) => (count === 1 ? 'retry' : 'retries')
|
|
300
|
+
|
|
133
301
|
export type TestWorkflowRunInspection = {
|
|
134
302
|
readonly runId: string
|
|
135
303
|
readonly status: TestWorkflowRunStatus
|
|
@@ -139,6 +307,8 @@ export type TestWorkflowRunInspection = {
|
|
|
139
307
|
readonly writeAfterCloseAttempts: number
|
|
140
308
|
readonly stepAttempts: ReadonlyMap<string, number>
|
|
141
309
|
readonly runError: unknown
|
|
310
|
+
/** Every thrown step value the platform could not store, in order. */
|
|
311
|
+
readonly unstorableStepErrors: ReadonlyArray<TestWorkflowUnstorableStepError>
|
|
142
312
|
}
|
|
143
313
|
|
|
144
314
|
export type TestWorkflowHook<T> = Promise<T> & { readonly [Symbol.dispose]: () => void }
|
|
@@ -170,7 +340,8 @@ export class TestWorkflowWorld {
|
|
|
170
340
|
hooks: new Map(),
|
|
171
341
|
resumedHookTokens: new Set(),
|
|
172
342
|
stepSequence: 0,
|
|
173
|
-
stepAttempts: new Map()
|
|
343
|
+
stepAttempts: new Map(),
|
|
344
|
+
unstorableStepErrors: []
|
|
174
345
|
}
|
|
175
346
|
|
|
176
347
|
this.runs.set(runId, run)
|
|
@@ -218,7 +389,8 @@ export class TestWorkflowWorld {
|
|
|
218
389
|
streamCloseCount: run.streamCloseCount,
|
|
219
390
|
writeAfterCloseAttempts: run.writeAfterCloseAttempts,
|
|
220
391
|
stepAttempts: new Map(run.stepAttempts),
|
|
221
|
-
runError: run.runError
|
|
392
|
+
runError: run.runError,
|
|
393
|
+
unstorableStepErrors: [...run.unstorableStepErrors]
|
|
222
394
|
}
|
|
223
395
|
}
|
|
224
396
|
|
|
@@ -277,7 +449,11 @@ export class TestWorkflowWorld {
|
|
|
277
449
|
|
|
278
450
|
// Runs a step body with the platform's retry contract: `fn.maxRetries`
|
|
279
451
|
// retries after the first attempt (total attempts = maxRetries + 1) and
|
|
280
|
-
// 1-based `getStepMetadata().attempt` visible to the body.
|
|
452
|
+
// 1-based `getStepMetadata().attempt` visible to the body. A FatalError
|
|
453
|
+
// (by `name`, or `fatal: true`; an AbortError is promoted to one) is never
|
|
454
|
+
// retried; an exhausted step fails with the platform's FatalError whose
|
|
455
|
+
// `cause` is the last thrown value. The caller sees errors only as the
|
|
456
|
+
// platform stores and reads them back.
|
|
281
457
|
async runStep<TArgs extends ReadonlyArray<unknown>, TResult>(
|
|
282
458
|
stepFn: TestWorkflowStepFunction<TArgs, TResult>,
|
|
283
459
|
args: TArgs,
|
|
@@ -289,21 +465,71 @@ export class TestWorkflowWorld {
|
|
|
289
465
|
const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`
|
|
290
466
|
const maxRetries = stepFn.maxRetries ?? defaultTestWorkflowStepMaxRetries
|
|
291
467
|
const maxAttempts = maxRetries + 1
|
|
468
|
+
const serializer = await loadStepErrorSerializer()
|
|
292
469
|
|
|
293
470
|
let attempt = 1
|
|
294
471
|
|
|
295
472
|
for (;;) {
|
|
296
473
|
run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1)
|
|
297
474
|
|
|
475
|
+
let thrown: unknown
|
|
476
|
+
|
|
298
477
|
try {
|
|
299
478
|
return await ambientStorage.run(
|
|
300
479
|
{ world: this, run, stepMetadata: { attempt, stepId, stepName } },
|
|
301
480
|
() => stepFn(...args)
|
|
302
481
|
)
|
|
303
482
|
} catch (error) {
|
|
304
|
-
|
|
483
|
+
thrown = error
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const effective = promoteAbortError(thrown)
|
|
487
|
+
// Normalized on every attempt, as the platform does: a thrown thenable is awaited here.
|
|
488
|
+
const message = await platformErrorMessage(effective)
|
|
489
|
+
const fatal = isFatalStepError(effective)
|
|
490
|
+
const exhausted = !fatal && attempt >= maxAttempts
|
|
491
|
+
|
|
492
|
+
// A fatal error is stored as is (abort promoted); an exhausted step's error becomes the
|
|
493
|
+
// cause of the platform's FatalError; a retried attempt stores the thrown value.
|
|
494
|
+
const recorded = fatal
|
|
495
|
+
? effective
|
|
496
|
+
: exhausted
|
|
497
|
+
? platformFatalError(
|
|
498
|
+
`Step "${stepName}" failed after ${maxRetries} ${retriesLabel(maxRetries)}: ${message}`,
|
|
499
|
+
thrown
|
|
500
|
+
)
|
|
501
|
+
: thrown
|
|
502
|
+
|
|
503
|
+
const bytes = await serializer.dehydrate(recorded, run.runId)
|
|
504
|
+
|
|
505
|
+
if (bytes === undefined) {
|
|
506
|
+
// The platform cannot record this attempt: its queue handler fails and the
|
|
507
|
+
// redelivered message runs the step again as the next attempt.
|
|
508
|
+
run.unstorableStepErrors.push({ stepName, attempt, error: thrown })
|
|
509
|
+
|
|
510
|
+
if (attempt >= maxAttempts) {
|
|
511
|
+
// The redelivery past the budget fails the step before running it again.
|
|
512
|
+
const exceeded = await serializer.dehydrate(
|
|
513
|
+
platformFatalError(
|
|
514
|
+
`Step "${stepName}" exceeded max retries (${maxRetries} ${retriesLabel(maxRetries)})`,
|
|
515
|
+
undefined
|
|
516
|
+
),
|
|
517
|
+
run.runId
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
if (exceeded === undefined)
|
|
521
|
+
throw new Error('The workflow runtime cannot store a FatalError')
|
|
522
|
+
|
|
523
|
+
throw await serializer.hydrate(exceeded, run.runId)
|
|
524
|
+
}
|
|
525
|
+
|
|
305
526
|
attempt += 1
|
|
527
|
+
continue
|
|
306
528
|
}
|
|
529
|
+
|
|
530
|
+
if (fatal || exhausted) throw await serializer.hydrate(bytes, run.runId)
|
|
531
|
+
|
|
532
|
+
attempt += 1
|
|
307
533
|
}
|
|
308
534
|
}
|
|
309
535
|
|