@workflow/core 5.0.0-beta.15 → 5.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const version = "5.0.0-beta.15";
1
+ export declare const version = "5.0.0-beta.16";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Generated by genversion.
2
- export const version = '5.0.0-beta.15';
3
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmVyc2lvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy92ZXJzaW9uLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDJCQUEyQjtBQUMzQixNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsZUFBZSxDQUFBIiwic291cmNlc0NvbnRlbnQiOlsiLy8gR2VuZXJhdGVkIGJ5IGdlbnZlcnNpb24uXG5leHBvcnQgY29uc3QgdmVyc2lvbiA9ICc1LjAuMC1iZXRhLjE1J1xuIl19
2
+ export const version = '5.0.0-beta.16';
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmVyc2lvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy92ZXJzaW9uLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDJCQUEyQjtBQUMzQixNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsZUFBZSxDQUFBIiwic291cmNlc0NvbnRlbnQiOlsiLy8gR2VuZXJhdGVkIGJ5IGdlbnZlcnNpb24uXG5leHBvcnQgY29uc3QgdmVyc2lvbiA9ICc1LjAuMC1iZXRhLjE2J1xuIl19
@@ -8,6 +8,7 @@ prerequisites:
8
8
  related:
9
9
  - /docs/api-reference/workflow/define-hook
10
10
  - /docs/api-reference/workflow/create-webhook
11
+ - /docs/foundations/idempotency
11
12
  ---
12
13
 
13
14
  Creates a low-level hook primitive that can be used to resume a workflow run with arbitrary payloads.
@@ -142,7 +143,11 @@ async function processOrder(orderId: string) {
142
143
 
143
144
  Because `createHook()` alone does not suspend the workflow, awaiting `hook.getConflict()` is what actually suspends the run and commits the hook registration. It only waits for registration — to receive payload data from a future `resumeHook()` call, await the hook itself or iterate it with `for await...of`.
144
145
 
145
- On a conflict, the resolved value is a `Run` handle for the run that currently owns the token, with durable step-backed accessors. The duplicate run can decide in code how to handle it: return or log `conflict.runId`, inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()` and continue in the current run. See [Idempotency](/docs/foundations/idempotency) for these strategies in context.
146
+ On a conflict, the resolved value is a `Run` handle for the run that currently owns the token, with durable step-backed accessors. The duplicate run can decide in code how to handle it: return or log `conflict.runId`, inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()` and continue in the current run. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies in context.
147
+
148
+ <Callout type="info">
149
+ Custom hook tokens are the recommended way to coordinate active workflow runs. Use a deterministic token from your domain, such as an order ID or conversation ID, create the hook near the beginning of the workflow, and check `await hook.getConflict()` before work that depends on owning the token. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
150
+ </Callout>
146
151
 
147
152
  ### Waiting for Multiple Payloads
148
153
 
@@ -227,3 +232,4 @@ This is equivalent to manually calling `dispose()` but ensures the hook is alway
227
232
  - [`defineHook()`](/docs/api-reference/workflow/define-hook) - Type-safe hook helper
228
233
  - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) - Resume a hook with a payload
229
234
  - [`createWebhook()`](/docs/api-reference/workflow/create-webhook) - Higher-level HTTP webhook abstraction
235
+ - [Idempotency](/docs/foundations/idempotency) - Deduplicate step side effects and workflow starts
@@ -7,12 +7,17 @@ prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
9
9
  - /docs/errors/fetch-in-workflow
10
+ - /docs/foundations/idempotency
10
11
  ---
11
12
 
12
13
  Makes HTTP requests from within a workflow. This is a special step function that wraps the standard `fetch` API, automatically handling serialization and providing retry semantics.
13
14
 
14
15
  This is useful when you need to call external APIs or services from within your workflow.
15
16
 
17
+ <Callout type="warn">
18
+ Because workflow `fetch()` has retry semantics, use idempotency keys when the request mutates an external system, such as creating a charge, sending an email, or enqueueing work. See [Idempotency](/docs/foundations/idempotency).
19
+ </Callout>
20
+
16
21
  <Callout>
17
22
  `fetch` is a *special* type of step function provided and should be called directly inside workflow functions.
18
23
  </Callout>
@@ -6,7 +6,6 @@ summary: Cancel in-flight work with AbortSignal or stop entire workflow runs.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
9
- - /docs/foundations/common-patterns
10
9
  - /docs/foundations/hooks
11
10
  - /docs/how-it-works/cancellation
12
11
  ---
@@ -455,6 +454,6 @@ This is safe even if both steps have already completed — aborting a finished o
455
454
 
456
455
  - [How Cancellation Works](/docs/how-it-works/cancellation) — Hook and stream backing, serialization internals
457
456
  - [Serialization](/docs/foundations/serialization) — Understanding serializable types
458
- - [Common Patterns](/docs/foundations/common-patterns) — Timeout and race patterns
457
+ - [Cookbook](/v5/cookbook) — Timeout, race, and other reliability patterns
459
458
  - [Hooks](/docs/foundations/hooks) — Pausing workflows for external events
460
459
  - [Errors and Retries](/docs/foundations/errors-and-retries) — Handling step failures
@@ -112,7 +112,7 @@ export async function orderWorkflow(orderId: string) {
112
112
  }
113
113
  ```
114
114
 
115
- Calling `createHook()` on its own does not register the hook — registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token if another active hook already claimed it (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()` — see [Idempotency](/docs/foundations/idempotency) for these strategies.
115
+ Calling `createHook()` on its own does not register the hook — registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token if another active hook already claimed it (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()` — see [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies.
116
116
 
117
117
  ### Custom Tokens for Deterministic Hooks
118
118
 
@@ -1,23 +1,27 @@
1
1
  ---
2
2
  title: Idempotency
3
- description: Ensure operations can be safely retried without producing duplicate side effects.
3
+ description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
4
4
  type: conceptual
5
- summary: Prevent duplicate side effects when retrying operations in steps.
5
+ summary: Use step IDs for retry-safe external calls, and route duplicate workflow-start requests through deterministic hook tokens.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
9
9
  - /docs/foundations/errors-and-retries
10
+ - /docs/foundations/starting-workflows
11
+ - /docs/foundations/hooks
10
12
  ---
11
13
 
12
- Idempotency is a property of an operation that ensures it can be safely retried without producing duplicate side effects.
14
+ Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
15
+
16
+ In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency coordinates duplicate requests that try to start the same workflow.
17
+
18
+ ## Step Idempotency
13
19
 
14
20
  In distributed systems (calling external APIs), it is not always possible to ensure an operation has only been performed once just by seeing if it succeeds.
15
21
  Consider a payment API that charges the user $10, but due to network failures, the confirmation response is lost. When the step retries (because the previous attempt was considered a failure), it will charge the user again.
16
22
 
17
23
  To prevent this, many external APIs support idempotency keys. An idempotency key is a unique identifier for an operation that can be used to deduplicate requests.
18
24
 
19
- ## The core pattern: use the step ID as your idempotency key
20
-
21
25
  Every step invocation has a stable `stepId` that stays the same across retries.
22
26
  Use it as the idempotency key when calling third-party APIs.
23
27
 
@@ -27,7 +31,7 @@ import { getStepMetadata } from "workflow";
27
31
  async function chargeUser(userId: string, amount: number) {
28
32
  "use step";
29
33
 
30
- const { stepId } = getStepMetadata();
34
+ const { stepId } = getStepMetadata(); // [!code highlight]
31
35
 
32
36
  // Example: Stripe-style idempotency key
33
37
  // This guarantees only one charge is created even if the step retries
@@ -49,14 +53,235 @@ Why this works:
49
53
  - **Stable across retries**: `stepId` does not change between attempts.
50
54
  - **Globally unique per step**: Fulfills the uniqueness requirement for an idempotency key.
51
55
 
52
- ## Best practices
56
+ ## Run idempotency
57
+
58
+ Step idempotency protects side effects **inside** a workflow run. Run idempotency answers a different question: if the same API request is sent twice, should it create one workflow run or two?
59
+
60
+ Because [hooks](/docs/foundations/hooks) already ensure globally unique active tokens, Workflow can use the same mechanism to coordinate duplicate requests while a run is active.
61
+
62
+ Use a hook token as the idempotency key for an active workflow run. Hook tokens are globally unique while they are active: if another run tries to create a hook with the same token, the runtime records a conflict, `hook.getConflict()` resolves with a `Run` handle for the run that owns the token, and the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict) when the workflow awaits or iterates its payload.
63
+
64
+ The token should come from your domain, such as an order ID, invoice ID, import ID, or request ID. Create the hook near the beginning of the workflow and check `await hook.getConflict()` before doing duplicate-sensitive work that depends on owning the active token. Calling `createHook()` alone does not register the hook — awaiting `getConflict()` suspends the workflow to commit the registration.
65
+
66
+ ```typescript lineNumbers
67
+ import { createHook } from "workflow";
68
+
69
+ type OrderRequest = { confirmed: boolean };
70
+ type OrderResult =
71
+ | { status: "processed" | "cancelled" }
72
+ | { status: "duplicate"; runId: string };
73
+ declare function chargeOrder(orderId: string): Promise<void>; // @setup
74
+
75
+ export async function processOrder(orderId: string): Promise<OrderResult> {
76
+ "use workflow";
77
+
78
+ using request = createHook<OrderRequest>({ // [!code highlight]
79
+ token: `order:${orderId}`, // [!code highlight]
80
+ }); // [!code highlight]
81
+
82
+ const conflict = await request.getConflict(); // [!code highlight]
83
+ if (conflict) { // [!code highlight]
84
+ // Another active run already owns this order's token. // [!code highlight]
85
+ return { status: "duplicate" as const, runId: conflict.runId }; // [!code highlight]
86
+ } // [!code highlight]
87
+
88
+ const { confirmed } = await request;
89
+
90
+ if (!confirmed) {
91
+ return { status: "cancelled" as const };
92
+ }
93
+
94
+ await chargeOrder(orderId);
95
+ return { status: "processed" as const };
96
+ }
97
+ ```
98
+
99
+ The runtime creates the hook atomically. At most one active hook can own `order:${orderId}`, so duplicate workflow runs converge on one active owner. A duplicate run observes `getConflict()` resolving with the owner's `Run` and returns before it reaches `chargeOrder()`. The conflicting run's accessors (`status`, `returnValue`, `cancel()`, …) are durable steps, so the duplicate run can do more than report the owner — see [conflict-handling strategies](#conflict-handling-strategies) below.
100
+
101
+ Outside the workflow, try to resume the hook first. If the hook is not registered yet, start the workflow and retry the resume until the new run creates the hook:
102
+
103
+ ```typescript lineNumbers
104
+ import { resumeHook, start } from "workflow/api";
105
+ import { HookNotFoundError } from "workflow/errors";
106
+ import { processOrder } from "./workflows/process-order";
107
+
108
+ type OrderRequest = { confirmed: boolean };
109
+
110
+ async function resumeOrder(token: string, payload: OrderRequest) {
111
+ for (let attempt = 0; attempt < 5; attempt++) {
112
+ try {
113
+ return await resumeHook(token, payload); // [!code highlight]
114
+ } catch (error) {
115
+ if (!HookNotFoundError.is(error)) throw error;
116
+ await new Promise((resolve) => setTimeout(resolve, 100));
117
+ }
118
+ }
119
+
120
+ throw new Error("Order workflow did not register its hook in time");
121
+ }
122
+
123
+ export async function POST(request: Request) {
124
+ const { orderId, confirmed } = await request.json();
125
+ const token = `order:${orderId}`;
126
+ const payload = { confirmed };
127
+
128
+ try {
129
+ const hook = await resumeHook(token, payload); // [!code highlight]
130
+ return Response.json({ runId: hook.runId, reused: true });
131
+ } catch (error) {
132
+ if (!HookNotFoundError.is(error)) throw error;
133
+ }
134
+
135
+ const run = await start(processOrder, [orderId]); // [!code highlight]
136
+ const resumed = await resumeOrder(token, payload);
137
+
138
+ // A concurrent request's run may have won the race between `start()` // [!code highlight]
139
+ // and hook registration. The resume always reaches the actual active // [!code highlight]
140
+ // owner, so compare run IDs instead of waiting for this run to finish. // [!code highlight]
141
+ return Response.json({ // [!code highlight]
142
+ runId: resumed.runId, // [!code highlight]
143
+ reused: resumed.runId !== run.runId, // [!code highlight]
144
+ }); // [!code highlight]
145
+ }
146
+ ```
147
+
148
+ <Callout type="warn">
149
+ This avoids creating a new run only after the first run has registered its hook. Because `start()` returns before the run body executes and calls `createHook()`, two concurrent requests can both observe "no hook yet" and each call `start()`. The race is resolved inside the workflow body, where the losing run observes `getConflict()` resolving with the active owner and returns without doing duplicate-sensitive work — and the route detects it by comparing the resumed hook's `runId` against the run it just started, without waiting for either run to finish. A native API for atomically starting a run and registering a hook is in the works. Until then, model recovery inside the workflow by checking `hook.getConflict()`.
150
+ </Callout>
151
+
152
+ This is active-run coordination. When the workflow completes and disposes the hook, the token can be used again. If a duplicate request after completion must return the original result instead of starting fresh work, persist that completed result under the same domain key.
153
+
154
+ ### Conflict-handling strategies
155
+
156
+ Some workflow systems resolve duplicate IDs with a fixed, pre-declared policy — typically a static choice between rejecting the new execution, deferring to the existing one, or terminating it. Workflow has no policy enum. `hook.getConflict()` hands the duplicate run the conflicting `Run` itself, and the policy is ordinary code — including policies that inspect state before deciding, which static configuration can't express.
157
+
158
+ The example above implements **reject the duplicate**: return the owner's `runId` and let the caller decide. Other common strategies:
159
+
160
+ **Adopt the owner's result.** Wait for the active run to finish and return its result, so callers cannot tell which run did the work:
161
+
162
+ ```typescript lineNumbers
163
+ import { createHook } from "workflow";
164
+
165
+ type OrderRequest = { confirmed: boolean };
166
+ declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
167
+
168
+ export async function processOrder(orderId: string) {
169
+ "use workflow";
170
+
171
+ using request = createHook<OrderRequest>({
172
+ token: `order:${orderId}`,
173
+ });
174
+
175
+ const conflict = await request.getConflict();
176
+ if (conflict) {
177
+ // Callers get the same result regardless of which run did the work.
178
+ return await conflict.returnValue; // [!code highlight]
179
+ }
180
+
181
+ return await processOwnedOrder(orderId);
182
+ }
183
+ ```
184
+
185
+ **Inspect the owner before deciding.** Branch on the owner's live state:
186
+
187
+ ```typescript lineNumbers
188
+ import { createHook } from "workflow";
189
+
190
+ type OrderRequest = { confirmed: boolean };
191
+ declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
192
+
193
+ export async function processOrder(orderId: string) {
194
+ "use workflow";
195
+
196
+ using request = createHook<OrderRequest>({
197
+ token: `order:${orderId}`,
198
+ });
199
+
200
+ const conflict = await request.getConflict();
201
+ if (conflict) {
202
+ const status = await conflict.status; // [!code highlight]
203
+ if (status === "running") {
204
+ return { status: "duplicate" as const, runId: conflict.runId };
205
+ }
206
+ // Owner already reached a terminal state; its hook will be released.
207
+ }
208
+
209
+ return await processOwnedOrder(orderId);
210
+ }
211
+ ```
212
+
213
+ **Signal the owner instead of doing the work.** The duplicate run knows the token, so it can deliver this run's input to the owner's hook from a step:
214
+
215
+ ```typescript lineNumbers
216
+ import { createHook } from "workflow";
217
+ import { resumeHook } from "workflow/api";
218
+
219
+ type OrderRequest = { confirmed: boolean };
220
+
221
+ async function forwardToOwner(token: string, payload: OrderRequest) {
222
+ "use step";
223
+ await resumeHook(token, payload); // [!code highlight]
224
+ }
225
+
226
+ export async function processOrder(orderId: string, confirmed: boolean) {
227
+ "use workflow";
228
+
229
+ const token = `order:${orderId}`;
230
+ using request = createHook<OrderRequest>({ token });
231
+
232
+ const conflict = await request.getConflict();
233
+ if (conflict) {
234
+ await forwardToOwner(token, { confirmed }); // [!code highlight]
235
+ return { status: "forwarded" as const, runId: conflict.runId };
236
+ }
237
+
238
+ // ... own the token and do the work
239
+ }
240
+ ```
241
+
242
+ **Supersede the owner.** Newest-wins: cancel the active run, then claim the released token. Cancellation disposes the owner's hooks; the retry loop covers the window where that disposal has not propagated yet:
243
+
244
+ ```typescript lineNumbers
245
+ import { createHook } from "workflow";
246
+
247
+ type OrderRequest = { confirmed: boolean };
248
+ declare function chargeOrder(orderId: string): Promise<void>; // @setup
249
+
250
+ export async function processOrderNewestWins(orderId: string) {
251
+ "use workflow";
252
+
253
+ const token = `order:${orderId}`;
254
+
255
+ for (let attempt = 0; attempt < 3; attempt++) {
256
+ using request = createHook<OrderRequest>({ token });
257
+
258
+ const conflict = await request.getConflict();
259
+ if (!conflict) {
260
+ // Token claimed — this run is now the owner.
261
+ const { confirmed } = await request;
262
+ if (confirmed) {
263
+ await chargeOrder(orderId);
264
+ }
265
+ return { status: "processed" as const };
266
+ }
267
+
268
+ await conflict.cancel(); // [!code highlight]
269
+ }
270
+
271
+ throw new Error(`Could not claim ${token} after cancelling the owner`);
272
+ }
273
+ ```
274
+
275
+ If duplicate requests should only reuse the active run without sending data, use [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) as an advisory pre-check before calling `start()`. The workflow should still check `hook.getConflict()`, because the lookup and `start()` are not atomic.
53
276
 
54
- - **Always provide idempotency keys to external side effects that are not idempotent** inside steps (payments, emails, SMS, queues).
55
- - **Prefer `stepId` as your key**; it is stable across retries and unique per step.
56
- - **Keep keys deterministic**; avoid including timestamps or attempt counters.
57
- - **Handle 409/conflict responses** gracefully; treat them as success if the prior attempt completed.
277
+ Because this pattern uses hooks for idempotency, duplicate requests can also inject additional data and steer the existing run. The route example above uses `resumeHook()` for that: if the hook already exists, the duplicate request resumes the active workflow; if the hook is not registered yet, the route starts the workflow and retries `resumeHook()` so the payload is not dropped.
58
278
 
59
279
  ## Related docs
60
280
 
61
281
  - Learn about retries in [Errors & Retrying](/docs/foundations/errors-and-retries)
62
282
  - API reference: [`getStepMetadata`](/docs/api-reference/workflow/get-step-metadata)
283
+ - API reference: [`createHook()`](/docs/api-reference/workflow/create-hook)
284
+ - API reference: [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token)
285
+ - API reference: [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook)
286
+ - API reference: [`start()`](/docs/api-reference/workflow-api/start)
287
+ - Learn about deterministic hook tokens in [Hooks](/docs/foundations/hooks)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/core",
3
- "version": "5.0.0-beta.15",
3
+ "version": "5.0.0-beta.16",
4
4
  "description": "Core runtime and engine for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -92,9 +92,9 @@
92
92
  "@workflow/errors": "5.0.0-beta.7",
93
93
  "@workflow/serde": "5.0.0-beta.2",
94
94
  "@workflow/utils": "5.0.0-beta.3",
95
- "@workflow/world": "5.0.0-beta.9",
96
- "@workflow/world-local": "5.0.0-beta.16",
97
- "@workflow/world-vercel": "5.0.0-beta.14"
95
+ "@workflow/world": "5.0.0-beta.10",
96
+ "@workflow/world-local": "5.0.0-beta.17",
97
+ "@workflow/world-vercel": "5.0.0-beta.15"
98
98
  },
99
99
  "devDependencies": {
100
100
  "@opentelemetry/api": "1.9.0",