workflow 5.0.0-beta.1 → 5.0.0-beta.11
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 +4 -4
- package/dist/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -2
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.d.ts +17 -0
- package/dist/internal/builtins.d.ts.map +1 -1
- package/dist/internal/builtins.js +65 -1
- package/dist/internal/class-serialization.js +1 -1
- package/dist/internal/errors.js +1 -1
- package/dist/nest.js +1 -1
- package/dist/next.cjs +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2 -2
- package/dist/stdlib.js +1 -1
- package/dist/sveltekit.js +1 -1
- package/dist/typescript-plugin.cjs +1 -1
- package/dist/vite.js +1 -1
- package/dist/workflow.js +1 -1
- package/docs/ai/index.mdx +6 -5
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/vitest/index.mdx +28 -1
- package/docs/api-reference/workflow/create-webhook.mdx +37 -18
- package/docs/api-reference/workflow/experimental-set-attributes.mdx +63 -0
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +34 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +0 -4
- package/docs/api-reference/workflow-ai/index.mdx +0 -5
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +0 -4
- package/docs/api-reference/workflow-api/start.mdx +5 -4
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
- package/docs/api-reference/workflow-next/with-workflow.mdx +34 -2
- package/docs/changelog/attributes-mvp.mdx +368 -0
- package/docs/changelog/eager-processing.mdx +595 -0
- package/docs/changelog/index.mdx +2 -1
- package/docs/cookbook/advanced/child-workflows.mdx +313 -0
- package/docs/cookbook/advanced/meta.json +9 -0
- package/docs/cookbook/advanced/publishing-libraries.mdx +336 -0
- package/docs/cookbook/advanced/serializable-steps.mdx +147 -0
- package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +154 -0
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +255 -0
- package/docs/cookbook/agent-patterns/meta.json +4 -0
- package/docs/cookbook/common-patterns/batching.mdx +105 -0
- package/docs/cookbook/common-patterns/idempotency.mdx +107 -0
- package/docs/cookbook/common-patterns/meta.json +15 -0
- package/docs/cookbook/common-patterns/rate-limiting.mdx +228 -0
- package/docs/cookbook/common-patterns/saga.mdx +247 -0
- package/docs/cookbook/common-patterns/scheduling.mdx +129 -0
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
- package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +111 -0
- package/docs/cookbook/index.mdx +38 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +383 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +307 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +520 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +6 -4
- package/docs/deploying/world/vercel-world.mdx +3 -1
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
- package/docs/errors/hook-conflict.mdx +56 -4
- package/docs/errors/index.mdx +3 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/start-invalid-workflow-function.mdx +1 -1
- package/docs/foundations/cancellation.mdx +460 -0
- package/docs/foundations/errors-and-retries.mdx +7 -3
- package/docs/foundations/index.mdx +3 -3
- package/docs/foundations/meta.json +3 -2
- package/docs/foundations/serialization.mdx +78 -42
- package/docs/foundations/starting-workflows.mdx +6 -2
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +6 -0
- package/docs/getting-started/index.mdx +13 -7
- package/docs/getting-started/meta.json +3 -1
- package/docs/getting-started/nestjs.mdx +8 -0
- package/docs/getting-started/next.mdx +5 -3
- package/docs/getting-started/nitro.mdx +22 -0
- package/docs/getting-started/python.mdx +165 -0
- package/docs/getting-started/sveltekit.mdx +6 -0
- package/docs/getting-started/tanstack-start.mdx +241 -0
- package/docs/how-it-works/cancellation.mdx +287 -0
- package/docs/how-it-works/code-transform.mdx +2 -2
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- package/docs/how-it-works/meta.json +2 -1
- package/docs/internal/index.mdx +19 -0
- package/docs/internal/meta.json +5 -0
- package/docs/internal/serializable-abort-controller.mdx +148 -0
- package/docs/meta.json +1 -0
- package/docs/migration-guides/index.mdx +34 -0
- package/docs/migration-guides/meta.json +9 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +358 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +304 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +313 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +328 -0
- package/docs/observability/attributes.mdx +66 -0
- package/docs/observability/index.mdx +9 -1
- package/docs/observability/meta.json +1 -1
- package/package.json +14 -13
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Sequential & Parallel Execution
|
|
3
|
+
description: Compose steps with familiar async/await patterns — sequential await, Promise.all, and Promise.race.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Workflows are just async functions, so all the standard composition primitives (await, Promise.all, Promise.race) apply unchanged — including racing webhooks against durable sleeps.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
- /cookbook/common-patterns/timeouts
|
|
9
|
+
- /cookbook/common-patterns/scheduling
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Workflows are written in plain async/await — there's no new control-flow API to learn. Sequential awaits chain steps that depend on each other, `Promise.all` runs independent steps in parallel, and `Promise.race` returns whichever finishes first. These compose with workflow primitives like [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) since those are also just promises.
|
|
13
|
+
|
|
14
|
+
## When to use this
|
|
15
|
+
|
|
16
|
+
- **Pipelines** — each step depends on the previous step's output (validate → process → store)
|
|
17
|
+
- **Independent fan-out** — fetch multiple resources or perform multiple actions that don't depend on each other
|
|
18
|
+
- **Race conditions** — return as soon as one of N operations completes (timeout, first-responder, deadline)
|
|
19
|
+
- **Mixing primitives** — running steps, sleeps, and webhooks side-by-side in the same control-flow expression
|
|
20
|
+
|
|
21
|
+
## Pattern
|
|
22
|
+
|
|
23
|
+
### Sequential
|
|
24
|
+
|
|
25
|
+
The simplest way to orchestrate steps is to execute them one after another, where each step depends on the previous step's output.
|
|
26
|
+
|
|
27
|
+
```typescript lineNumbers
|
|
28
|
+
declare function validateData(data: unknown): Promise<string>; // @setup
|
|
29
|
+
declare function processData(data: string): Promise<string>; // @setup
|
|
30
|
+
declare function storeData(data: string): Promise<string>; // @setup
|
|
31
|
+
|
|
32
|
+
export async function dataPipelineWorkflow(data: unknown) {
|
|
33
|
+
"use workflow";
|
|
34
|
+
|
|
35
|
+
const validated = await validateData(data);
|
|
36
|
+
const processed = await processData(validated);
|
|
37
|
+
const stored = await storeData(processed);
|
|
38
|
+
|
|
39
|
+
return stored;
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Parallel with `Promise.all`
|
|
44
|
+
|
|
45
|
+
When steps don't depend on each other, run them concurrently with `Promise.all`. The workflow waits until all of them resolve.
|
|
46
|
+
|
|
47
|
+
```typescript lineNumbers
|
|
48
|
+
declare function fetchUser(userId: string): Promise<{ name: string }>; // @setup
|
|
49
|
+
declare function fetchOrders(userId: string): Promise<{ items: string[] }>; // @setup
|
|
50
|
+
declare function fetchPreferences(userId: string): Promise<{ theme: string }>; // @setup
|
|
51
|
+
|
|
52
|
+
export async function fetchUserData(userId: string) {
|
|
53
|
+
"use workflow";
|
|
54
|
+
|
|
55
|
+
const [user, orders, preferences] = await Promise.all([ // [!code highlight]
|
|
56
|
+
fetchUser(userId), // [!code highlight]
|
|
57
|
+
fetchOrders(userId), // [!code highlight]
|
|
58
|
+
fetchPreferences(userId), // [!code highlight]
|
|
59
|
+
]); // [!code highlight]
|
|
60
|
+
|
|
61
|
+
return { user, orders, preferences };
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Race with `Promise.race`
|
|
66
|
+
|
|
67
|
+
`Promise.race` resolves as soon as the first promise settles. Since [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) return promises, they compose naturally — for example, waiting for a webhook callback with a deadline:
|
|
68
|
+
|
|
69
|
+
```typescript lineNumbers
|
|
70
|
+
import { sleep, createWebhook } from "workflow";
|
|
71
|
+
|
|
72
|
+
declare function executeExternalTask(webhookUrl: string): Promise<void>; // @setup
|
|
73
|
+
|
|
74
|
+
export async function runExternalTask(userId: string) {
|
|
75
|
+
"use workflow";
|
|
76
|
+
|
|
77
|
+
const webhook = createWebhook();
|
|
78
|
+
await executeExternalTask(webhook.url);
|
|
79
|
+
|
|
80
|
+
await Promise.race([ // [!code highlight]
|
|
81
|
+
webhook, // [!code highlight]
|
|
82
|
+
sleep("1 day"), // [!code highlight]
|
|
83
|
+
]); // [!code highlight]
|
|
84
|
+
|
|
85
|
+
console.log("Done");
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
For racing operations against deadlines specifically (timeouts), see the dedicated [Timeouts](/cookbook/common-patterns/timeouts) recipe — it covers result discrimination, `FatalError` semantics, and the "loser keeps running" caveat.
|
|
90
|
+
|
|
91
|
+
### Combining sequential, parallel, and durable primitives
|
|
92
|
+
|
|
93
|
+
Most real workflows combine all three. Here's a simplified version of the [birthday card generator demo](https://github.com/vercel/workflow-examples/tree/main/birthday-card-generator) — sequential card generation, parallel RSVP fan-out, non-blocking webhook collection, and a durable sleep until the birthday:
|
|
94
|
+
|
|
95
|
+
```typescript lineNumbers
|
|
96
|
+
import { createWebhook, sleep, type Webhook } from "workflow";
|
|
97
|
+
|
|
98
|
+
declare function makeCardText(prompt: string): Promise<string>; // @setup
|
|
99
|
+
declare function makeCardImage(text: string): Promise<string>; // @setup
|
|
100
|
+
declare function sendRSVPEmail(friend: string, webhook: Webhook): Promise<void>; // @setup
|
|
101
|
+
declare function sendBirthdayCard(text: string, image: string, rsvps: unknown[], email: string): Promise<void>; // @setup
|
|
102
|
+
|
|
103
|
+
export async function birthdayWorkflow(
|
|
104
|
+
prompt: string,
|
|
105
|
+
email: string,
|
|
106
|
+
friends: string[],
|
|
107
|
+
birthday: Date
|
|
108
|
+
) {
|
|
109
|
+
"use workflow";
|
|
110
|
+
|
|
111
|
+
const text = await makeCardText(prompt); // [!code highlight]
|
|
112
|
+
const image = await makeCardImage(text); // [!code highlight]
|
|
113
|
+
|
|
114
|
+
const webhooks = friends.map(() => createWebhook());
|
|
115
|
+
|
|
116
|
+
await Promise.all( // [!code highlight]
|
|
117
|
+
friends.map((friend, i) => sendRSVPEmail(friend, webhooks[i])) // [!code highlight]
|
|
118
|
+
); // [!code highlight]
|
|
119
|
+
|
|
120
|
+
const rsvps: unknown[] = [];
|
|
121
|
+
webhooks.map((webhook) =>
|
|
122
|
+
webhook.then((req) => req.json()).then(({ rsvp }) => rsvps.push(rsvp))
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
await sleep(birthday); // [!code highlight]
|
|
126
|
+
|
|
127
|
+
await sendBirthdayCard(text, image, rsvps, email);
|
|
128
|
+
|
|
129
|
+
return { text, image, status: "Sent" };
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## How it works
|
|
134
|
+
|
|
135
|
+
1. **`await` is durable.** When the workflow awaits a step, the runtime persists the step's input, suspends the workflow, runs the step, and replays the workflow with the step's result on resume. The same applies to `sleep()` and `createWebhook()`.
|
|
136
|
+
2. **`Promise.all` runs steps concurrently.** Each promise in the array is suspended on its own and the workflow resumes only when all have settled. Failures propagate — if any promise rejects, the whole `Promise.all` rejects.
|
|
137
|
+
3. **`Promise.race` resolves on the first settle.** The losing promises keep running in the background but their results are discarded by the workflow.
|
|
138
|
+
4. **All primitives are promises.** `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` / `Promise.race` exactly like steps do — this is what makes patterns like "race a webhook against a 24-hour deadline" a one-liner.
|
|
139
|
+
|
|
140
|
+
## Adapting to your use case
|
|
141
|
+
|
|
142
|
+
- **Replace `Promise.all` with `Promise.allSettled`** when partial failures should not abort the rest. You'll get an array of `{ status, value | reason }` instead of throwing on the first rejection.
|
|
143
|
+
- **Bound the parallelism** — `Promise.all` over 1000 items will fan out 1000 concurrent steps. If your downstream APIs can't handle that, batch the array into chunks (see [Batching](/cookbook/common-patterns/batching)).
|
|
144
|
+
- **Add a deadline to any race** — pair the operation with `sleep("30s").then(() => "timeout" as const)` and check the discriminated result. See [Timeouts](/cookbook/common-patterns/timeouts).
|
|
145
|
+
- **Mix steps and hooks in a race** — wait for an external signal *or* a deadline *or* a step result, all in the same `Promise.race`. The first one to resolve wins.
|
|
146
|
+
|
|
147
|
+
## Key APIs
|
|
148
|
+
|
|
149
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
150
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
|
|
151
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable sleep that survives restarts
|
|
152
|
+
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — webhook URL the workflow can race against
|
|
153
|
+
- [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) — wait for all promises
|
|
154
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — wait for the first to settle
|
|
155
|
+
- [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) — wait for all, including failures
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Timeouts
|
|
3
|
+
description: Add deadlines to slow operations by racing them against a durable sleep.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Use `Promise.race` with `sleep()` to bound the time any step, hook, or webhook is allowed to take — and recover gracefully when the deadline fires first.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/api-reference/workflow/sleep
|
|
8
|
+
- /docs/foundations/hooks
|
|
9
|
+
- /cookbook/common-patterns/scheduling
|
|
10
|
+
- /cookbook/common-patterns/webhooks
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
A common requirement is bounding how long a workflow waits for something to finish — a slow step, an external webhook, a human approval. Race the operation against a durable `sleep()` with `Promise.race()` — whichever finishes first wins, and the loser keeps running but its result is ignored.
|
|
14
|
+
|
|
15
|
+
## When to use this
|
|
16
|
+
|
|
17
|
+
- **Slow steps** — bound the time spent waiting on third-party APIs, model calls, or expensive computation
|
|
18
|
+
- **External callbacks** — give webhooks a deadline so the workflow doesn't hang forever waiting for an event that may never arrive
|
|
19
|
+
- **Human approvals** — auto-decline or escalate when a hook isn't resumed within a window
|
|
20
|
+
- **Polling loops** — give an outer poll-until-ready loop an overall budget
|
|
21
|
+
|
|
22
|
+
## Pattern
|
|
23
|
+
|
|
24
|
+
### Timeout on a slow step
|
|
25
|
+
|
|
26
|
+
```typescript lineNumbers
|
|
27
|
+
import { sleep } from "workflow";
|
|
28
|
+
|
|
29
|
+
declare function processData(data: string): Promise<string>; // @setup
|
|
30
|
+
|
|
31
|
+
export async function processWithTimeout(data: string) {
|
|
32
|
+
"use workflow";
|
|
33
|
+
|
|
34
|
+
const result = await Promise.race([ // [!code highlight]
|
|
35
|
+
processData(data), // [!code highlight]
|
|
36
|
+
sleep("30s").then(() => "timeout" as const), // [!code highlight]
|
|
37
|
+
]); // [!code highlight]
|
|
38
|
+
|
|
39
|
+
if (result === "timeout") {
|
|
40
|
+
throw new Error("Processing timed out after 30 seconds");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Timeout on a webhook
|
|
48
|
+
|
|
49
|
+
The same pattern works for any promise — including hooks and webhooks. Here a webhook waits for an external service to call back, with a hard deadline of 7 days:
|
|
50
|
+
|
|
51
|
+
```typescript lineNumbers
|
|
52
|
+
import { sleep, createWebhook } from "workflow";
|
|
53
|
+
|
|
54
|
+
declare function sendApprovalRequest(requestId: string, webhookUrl: string): Promise<void>; // @setup
|
|
55
|
+
|
|
56
|
+
export async function waitForApproval(requestId: string) {
|
|
57
|
+
"use workflow";
|
|
58
|
+
|
|
59
|
+
const webhook = createWebhook<{ approved: boolean }>();
|
|
60
|
+
await sendApprovalRequest(requestId, webhook.url);
|
|
61
|
+
|
|
62
|
+
const result = await Promise.race([ // [!code highlight]
|
|
63
|
+
webhook.then((req) => req.json()), // [!code highlight]
|
|
64
|
+
sleep("7 days").then(() => ({ timedOut: true }) as const), // [!code highlight]
|
|
65
|
+
]); // [!code highlight]
|
|
66
|
+
|
|
67
|
+
if ("timedOut" in result) {
|
|
68
|
+
throw new Error("Approval request expired after 7 days");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return result.approved;
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## How it works
|
|
76
|
+
|
|
77
|
+
1. **Durable sleep** — `sleep("30s")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
|
|
78
|
+
2. **Race** — `Promise.race([work, sleep(...)])` returns the value of whichever promise resolves first. The loser keeps running in the background but its result is ignored by the workflow.
|
|
79
|
+
3. **Discriminated result** — tagging the sleep branch with a sentinel value (`"timeout" as const`, `{ timedOut: true }`) lets TypeScript narrow the result and pick the right branch.
|
|
80
|
+
4. **Throw to fail the workflow** — inside a workflow function, throwing an `Error` exits the run with that error. Use `FatalError` inside steps; throw plain errors inside workflows.
|
|
81
|
+
|
|
82
|
+
<Callout type="warn">
|
|
83
|
+
**The losing operation keeps running.** `Promise.race` doesn't cancel — when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money. Pass an `AbortSignal` into the step to cancel it cooperatively — see the [Cancellation Guide](/docs/foundations/cancellation) for patterns.
|
|
84
|
+
</Callout>
|
|
85
|
+
|
|
86
|
+
## Adapting to your use case
|
|
87
|
+
|
|
88
|
+
- **Different durations** — `sleep()` accepts duration strings (`"30s"`, `"5m"`, `"7 days"`), milliseconds, or `Date` objects for absolute deadlines.
|
|
89
|
+
- **Soft timeout (retry)** — instead of throwing, loop and retry with a fresh `Promise.race` and a backoff.
|
|
90
|
+
- **Soft timeout (fallback)** — return a default value when the timer wins instead of throwing: `if (result === "timeout") return cachedFallback`.
|
|
91
|
+
- **Combine with cancellation** — race three promises: the operation, a deadline `sleep()`, and a cancellation hook. See the [Scheduling cookbook](/cookbook/common-patterns/scheduling) for the cancellation half of this pattern.
|
|
92
|
+
- **Per-step deadlines** — wrap each step in its own `Promise.race` for independent budgets, or use a single outer race for an overall workflow deadline.
|
|
93
|
+
|
|
94
|
+
## Key APIs
|
|
95
|
+
|
|
96
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
|
|
97
|
+
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — create a webhook URL the workflow can race against
|
|
98
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — typed hook for in-process cancellation
|
|
99
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — race operations against deadlines
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Webhooks & External Callbacks
|
|
3
|
+
description: Receive HTTP callbacks from external services, process them durably, and respond inline.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Create webhook endpoints that your workflow can await, process incoming requests in steps, and respond to the caller — all within durable workflow context.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Use webhooks when external services push events to your application via HTTP callbacks. The workflow creates a webhook URL, suspends with zero compute cost, and resumes when a request arrives.
|
|
9
|
+
|
|
10
|
+
## When to use this
|
|
11
|
+
|
|
12
|
+
- Accepting callbacks from payment processors (Stripe, PayPal)
|
|
13
|
+
- Waiting for third-party verification or processing results
|
|
14
|
+
- Any integration where an external system calls you back asynchronously
|
|
15
|
+
|
|
16
|
+
## Pattern: Processing webhook events
|
|
17
|
+
|
|
18
|
+
Create a webhook with manual response control, then iterate over incoming requests:
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { createWebhook, type RequestWithResponse } from "workflow";
|
|
22
|
+
|
|
23
|
+
declare function processEvent(request: RequestWithResponse): Promise<{ type: string }>; // @setup
|
|
24
|
+
|
|
25
|
+
export async function paymentWebhook(orderId: string) {
|
|
26
|
+
"use workflow";
|
|
27
|
+
|
|
28
|
+
const webhook = createWebhook({ respondWith: "manual" }); // [!code highlight]
|
|
29
|
+
// webhook.url is the URL to give to the external service
|
|
30
|
+
|
|
31
|
+
const ledger: { type: string }[] = [];
|
|
32
|
+
|
|
33
|
+
for await (const request of webhook) { // [!code highlight]
|
|
34
|
+
const entry = await processEvent(request);
|
|
35
|
+
ledger.push(entry);
|
|
36
|
+
|
|
37
|
+
// Break when we've received a terminal event
|
|
38
|
+
if (entry.type === "payment.succeeded" || entry.type === "refund.created") {
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return { orderId, webhookUrl: webhook.url, ledger, status: "settled" };
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Step function for processing
|
|
48
|
+
|
|
49
|
+
Each webhook request is processed in its own step, giving you full Node.js access for validation, database writes, and responding to the caller:
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { type RequestWithResponse } from "workflow";
|
|
53
|
+
|
|
54
|
+
async function processEvent(
|
|
55
|
+
request: RequestWithResponse
|
|
56
|
+
): Promise<{ type: string }> {
|
|
57
|
+
"use step";
|
|
58
|
+
|
|
59
|
+
const body = await request.json().catch(() => ({}));
|
|
60
|
+
const type = body?.type ?? "unknown";
|
|
61
|
+
|
|
62
|
+
// Validate, process, and respond inline
|
|
63
|
+
if (type === "payment.succeeded") {
|
|
64
|
+
// Record the payment in your database
|
|
65
|
+
await request.respondWith(Response.json({ ack: true, action: "captured" })); // [!code highlight]
|
|
66
|
+
} else if (type === "payment.failed") {
|
|
67
|
+
await request.respondWith(Response.json({ ack: true, action: "flagged" }));
|
|
68
|
+
} else {
|
|
69
|
+
await request.respondWith(Response.json({ ack: true, action: "ignored" }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return { type };
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Pattern: Async request-reply with timeout
|
|
77
|
+
|
|
78
|
+
Submit a request to an external service, pass it your webhook URL, then race the callback against a deadline:
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { createWebhook, sleep, FatalError, type RequestWithResponse } from "workflow";
|
|
82
|
+
|
|
83
|
+
export async function asyncVerification(documentId: string) {
|
|
84
|
+
"use workflow";
|
|
85
|
+
|
|
86
|
+
const webhook = createWebhook({ respondWith: "manual" });
|
|
87
|
+
|
|
88
|
+
// Submit to vendor, passing our webhook URL for the callback
|
|
89
|
+
await submitToVendor(documentId, webhook.url);
|
|
90
|
+
|
|
91
|
+
// Race: wait for callback OR timeout after 30 seconds
|
|
92
|
+
const result = await Promise.race([ // [!code highlight]
|
|
93
|
+
(async () => {
|
|
94
|
+
for await (const request of webhook) {
|
|
95
|
+
const body = await processCallback(request);
|
|
96
|
+
return body;
|
|
97
|
+
}
|
|
98
|
+
throw new FatalError("Webhook closed without callback");
|
|
99
|
+
})(),
|
|
100
|
+
sleep("30s").then(() => ({ status: "timed_out" as const })), // [!code highlight]
|
|
101
|
+
]);
|
|
102
|
+
|
|
103
|
+
return { documentId, ...result };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function submitToVendor(documentId: string, callbackUrl: string): Promise<void> {
|
|
107
|
+
"use step";
|
|
108
|
+
await fetch("https://vendor.example.com/verify", {
|
|
109
|
+
method: "POST",
|
|
110
|
+
body: JSON.stringify({ documentId, callbackUrl }),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function processCallback(
|
|
115
|
+
request: RequestWithResponse
|
|
116
|
+
): Promise<{ status: string; details: string }> {
|
|
117
|
+
"use step";
|
|
118
|
+
const body = await request.json();
|
|
119
|
+
await request.respondWith(Response.json({ ack: true }));
|
|
120
|
+
return {
|
|
121
|
+
status: body.approved ? "verified" : "rejected",
|
|
122
|
+
details: body.details ?? body.reason ?? "",
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Pattern: Large payload by reference
|
|
128
|
+
|
|
129
|
+
When payloads are too large to serialize into the event log, pass a lightweight reference (a "claim check") instead. Use a hook to signal when the data is ready:
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import { defineHook } from "workflow";
|
|
133
|
+
|
|
134
|
+
export const blobReady = defineHook<{ blobToken: string }>(); // [!code highlight]
|
|
135
|
+
|
|
136
|
+
export async function importLargeFile(importId: string) {
|
|
137
|
+
"use workflow";
|
|
138
|
+
|
|
139
|
+
// Suspend until the external system signals the blob is uploaded
|
|
140
|
+
const { blobToken } = await blobReady.create({ token: `upload:${importId}` }); // [!code highlight]
|
|
141
|
+
|
|
142
|
+
// Process by reference -- the full payload never enters the event log
|
|
143
|
+
await processBlob(blobToken);
|
|
144
|
+
|
|
145
|
+
return { importId, blobToken, status: "indexed" };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function processBlob(blobToken: string): Promise<void> {
|
|
149
|
+
"use step";
|
|
150
|
+
// Fetch the blob using the token, process it
|
|
151
|
+
const res = await fetch(`https://storage.example.com/blobs/${blobToken}`);
|
|
152
|
+
const data = await res.arrayBuffer();
|
|
153
|
+
// Index, transform, or store the data
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Resume from an API route when the upload completes:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { resumeHook } from "workflow/api";
|
|
161
|
+
|
|
162
|
+
// POST /api/upload-complete
|
|
163
|
+
export async function POST(request: Request) {
|
|
164
|
+
const { importId, blobToken } = await request.json();
|
|
165
|
+
await resumeHook(`upload:${importId}`, { blobToken }); // [!code highlight]
|
|
166
|
+
return Response.json({ ok: true });
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## Tips
|
|
171
|
+
|
|
172
|
+
- **`respondWith: "manual"`** gives you control over the HTTP response from inside a step. Use this when you need to validate the request before responding.
|
|
173
|
+
- **`for await` on a webhook** lets you process multiple events from the same URL. Use `break` to stop listening after a terminal event.
|
|
174
|
+
- **Webhooks auto-generate URLs** at `/.well-known/workflow/v1/webhook/:token`. Pass this URL to external services.
|
|
175
|
+
- **Race webhooks against `sleep()`** for deadlines. If the callback doesn't arrive in time, the workflow can take a fallback action.
|
|
176
|
+
- **For large payloads**, use a hook + reference token instead of passing the data through the workflow. The event log serializes all step inputs/outputs, so large payloads hurt performance.
|
|
177
|
+
|
|
178
|
+
## Key APIs
|
|
179
|
+
|
|
180
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
|
|
181
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions with full Node.js access
|
|
182
|
+
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) -- creates an HTTP endpoint the workflow can await
|
|
183
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) -- creates a typed hook for signal-based patterns
|
|
184
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) -- durable timer for deadlines
|
|
185
|
+
- [`FatalError`](/docs/api-reference/workflow/fatal-error) -- prevents retry on permanent failures
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Workflow Composition
|
|
3
|
+
description: Call workflows from other workflows by direct await (flatten into the parent) or background spawn via start() (separate run).
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Compose workflows two ways — direct await flattens the child into the parent's event log, while background spawn via start() runs the child as an independent run.
|
|
6
|
+
related:
|
|
7
|
+
- /cookbook/advanced/child-workflows
|
|
8
|
+
- /docs/api-reference/workflow-api/start
|
|
9
|
+
- /docs/api-reference/workflow-api/get-run
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or wants to fire the child off as an independent run (background spawn). For massive fan-out with hook-based waiting and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
|
|
13
|
+
|
|
14
|
+
## When to use this
|
|
15
|
+
|
|
16
|
+
- **Direct await** — the parent needs the child's result before continuing, and you want a single unified event log
|
|
17
|
+
- **Background spawn** — the parent doesn't need to wait, and you want the child to be observable as a separate run with its own `runId`
|
|
18
|
+
|
|
19
|
+
## Pattern
|
|
20
|
+
|
|
21
|
+
### Direct await (flattening)
|
|
22
|
+
|
|
23
|
+
Call a child workflow with `await` and the child's steps execute inline within the parent — they appear in the parent's event log as if you'd called them directly.
|
|
24
|
+
|
|
25
|
+
```typescript lineNumbers
|
|
26
|
+
declare function sendEmail(userId: string): Promise<void>; // @setup
|
|
27
|
+
declare function sendPushNotification(userId: string): Promise<void>; // @setup
|
|
28
|
+
declare function createAccount(userId: string): Promise<void>; // @setup
|
|
29
|
+
declare function setupPreferences(userId: string): Promise<void>; // @setup
|
|
30
|
+
|
|
31
|
+
// Child workflow
|
|
32
|
+
export async function sendNotifications(userId: string) {
|
|
33
|
+
"use workflow";
|
|
34
|
+
|
|
35
|
+
await sendEmail(userId);
|
|
36
|
+
await sendPushNotification(userId);
|
|
37
|
+
return { notified: true };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Parent workflow calls the child directly
|
|
41
|
+
export async function onboardUser(userId: string) {
|
|
42
|
+
"use workflow";
|
|
43
|
+
|
|
44
|
+
await createAccount(userId);
|
|
45
|
+
await sendNotifications(userId); // [!code highlight]
|
|
46
|
+
await setupPreferences(userId);
|
|
47
|
+
|
|
48
|
+
return { userId, status: "onboarded" };
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The parent waits for the child to finish before continuing. Both functions share a single workflow run, a single retry boundary, and a single event log.
|
|
53
|
+
|
|
54
|
+
### Background spawn via `start()`
|
|
55
|
+
|
|
56
|
+
To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from the parent workflow. This launches the child as a separate workflow run with its own `runId`.
|
|
57
|
+
|
|
58
|
+
```typescript lineNumbers
|
|
59
|
+
import { start } from "workflow/api";
|
|
60
|
+
|
|
61
|
+
declare function generateReport(reportId: string): Promise<void>; // @setup
|
|
62
|
+
declare function fulfillOrder(orderId: string): Promise<{ id: string }>; // @setup
|
|
63
|
+
declare function sendConfirmation(orderId: string): Promise<void>; // @setup
|
|
64
|
+
|
|
65
|
+
export async function processOrder(orderId: string) {
|
|
66
|
+
"use workflow";
|
|
67
|
+
|
|
68
|
+
const order = await fulfillOrder(orderId);
|
|
69
|
+
|
|
70
|
+
const reportRun = await start(generateReport, [orderId]); // [!code highlight]
|
|
71
|
+
|
|
72
|
+
await sendConfirmation(orderId);
|
|
73
|
+
|
|
74
|
+
return { orderId, reportRunId: reportRun.runId };
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The parent continues immediately after `start()` returns. The child runs independently and can be monitored separately using the returned `runId` (e.g., via [`getRun()`](/docs/api-reference/workflow-api/get-run)).
|
|
79
|
+
|
|
80
|
+
<Callout type="info">
|
|
81
|
+
If you want the child workflow to run on the latest deployment rather than the current one, pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. See [Versioning](/docs/foundations/versioning) for the full model. This is currently a Vercel-specific feature, and other Worlds may map the concept to their own deployment runtimes. Be aware that the child workflow's function name, file path, argument types, and return type must remain compatible across deployments — renaming the function or changing its location will change the workflow ID, and modifying expected inputs or outputs can cause serialization failures.
|
|
82
|
+
</Callout>
|
|
83
|
+
|
|
84
|
+
## How it works
|
|
85
|
+
|
|
86
|
+
1. **Direct await flattens.** When a workflow function awaits another workflow function, the child's `"use workflow"` directive is treated as inline — the child's steps emit into the parent's event log and share the parent's run ID.
|
|
87
|
+
2. **`start()` mints a new run.** The child gets its own `runId`, its own event log, and its own retry boundary. The parent only sees the `runId` returned by `start()`.
|
|
88
|
+
3. **`start()` can run inside workflows.** In v5, `start()` is step-backed, so it can be called directly from a workflow function and still records a deterministic step boundary in the event log.
|
|
89
|
+
|
|
90
|
+
## Choosing between the two modes
|
|
91
|
+
|
|
92
|
+
| | Direct await | Background spawn (`start()`) |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| Parent waits for child | Yes | No |
|
|
95
|
+
| Has its own `runId` | No (shares parent's) | Yes |
|
|
96
|
+
| Has its own event log | No | Yes |
|
|
97
|
+
| Has its own retry boundary | No | Yes |
|
|
98
|
+
| Best for | Sequential composition, helper workflows | Independent work, fire-and-forget, fan-out |
|
|
99
|
+
|
|
100
|
+
## Adapting to your use case
|
|
101
|
+
|
|
102
|
+
- **Spawn many children at once** — call `start()` in a loop from the workflow. For more advanced fan-out (chunking, hook-based waiting, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
|
|
103
|
+
- **Wait for a background child to finish** — combine `start()` with a completion hook the child resumes when done. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the recommended `startAndWait()` pattern.
|
|
104
|
+
- **Pass results back from background children** — the wrapped child resumes the parent's hook in `finally` with `{ status, value | error }`; the parent awaits the hook instead of polling `getRun().status`.
|
|
105
|
+
|
|
106
|
+
## Key APIs
|
|
107
|
+
|
|
108
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
109
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
|
|
110
|
+
- [`start()`](/docs/api-reference/workflow-api/start) — spawn a child workflow as a separate run
|
|
111
|
+
- [`getRun()`](/docs/api-reference/workflow-api/get-run) — retrieve a workflow run's status and return value
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Cookbook
|
|
3
|
+
description: Best-practice workflow patterns with copy-paste code examples.
|
|
4
|
+
type: overview
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
A curated collection of workflow patterns with clean, copy-paste code examples for real use cases.
|
|
8
|
+
|
|
9
|
+
## Agent Patterns
|
|
10
|
+
|
|
11
|
+
- [**Durable Agent**](/cookbook/agent-patterns/durable-agent) — Replace a stateless AI agent with one that survives crashes and retries tool calls
|
|
12
|
+
- [**Human-in-the-Loop**](/cookbook/agent-patterns/human-in-the-loop) — Pause an agent for human approval, then resume based on the decision
|
|
13
|
+
- [**Agent Cancellation**](/cookbook/agent-patterns/agent-cancellation) — Stop a running agent immediately via `run.cancel()` or gracefully via a hook + `Promise.race`
|
|
14
|
+
|
|
15
|
+
## Common Patterns
|
|
16
|
+
|
|
17
|
+
- [**Sequential & Parallel Execution**](/cookbook/common-patterns/sequential-and-parallel) — Compose steps with `await`, `Promise.all`, and `Promise.race` against durable sleeps and webhooks
|
|
18
|
+
- [**Workflow Composition**](/cookbook/common-patterns/workflow-composition) — Call workflows from other workflows by direct await or background spawn via `start()`
|
|
19
|
+
- [**Saga**](/cookbook/common-patterns/saga) — Coordinate multi-step transactions with automatic rollback when a step fails
|
|
20
|
+
- [**Batching**](/cookbook/common-patterns/batching) — Process large collections in parallel batches with failure isolation
|
|
21
|
+
- [**Rate Limiting**](/cookbook/common-patterns/rate-limiting) — Handle 429 responses and transient failures with RetryableError and backoff
|
|
22
|
+
- [**Scheduling**](/cookbook/common-patterns/scheduling) — Use durable sleep to schedule actions minutes, hours, or weeks ahead
|
|
23
|
+
- [**Timeouts**](/cookbook/common-patterns/timeouts) — Add deadlines to slow steps, hooks, and webhooks by racing them against a durable sleep
|
|
24
|
+
- [**Idempotency**](/cookbook/common-patterns/idempotency) — Ensure side effects happen exactly once, even when steps retry
|
|
25
|
+
- [**Webhooks**](/cookbook/common-patterns/webhooks) — Receive HTTP callbacks from external services and process them durably
|
|
26
|
+
|
|
27
|
+
## Integrations
|
|
28
|
+
|
|
29
|
+
- [**AI SDK**](/cookbook/integrations/ai-sdk) — Use streamText() directly inside a workflow for lower-level control over model calls and tool execution
|
|
30
|
+
- [**Chat SDK**](/cookbook/integrations/chat-sdk) — Build durable chat sessions with workflow persistence and AI SDK chat primitives
|
|
31
|
+
- [**Sandbox**](/cookbook/integrations/sandbox) — Orchestrate Vercel Sandbox lifecycle inside durable workflows
|
|
32
|
+
|
|
33
|
+
## Advanced
|
|
34
|
+
|
|
35
|
+
- [**Child Workflows**](/cookbook/advanced/child-workflows) — Spawn and orchestrate child workflows from a parent
|
|
36
|
+
- [**Upgrading Workflows**](/cookbook/advanced/upgrading-workflows) — Identify a clean upgrade point in a long-running workflow and spawn a fresh run on the latest deployment carrying state forward
|
|
37
|
+
- [**Serializable Steps**](/cookbook/advanced/serializable-steps) — Wrap non-serializable third-party objects so they cross the workflow boundary
|
|
38
|
+
- [**Publishing Libraries**](/cookbook/advanced/publishing-libraries) — Ship npm packages that export reusable workflow functions
|