workflow 5.0.0-beta.2 → 5.0.0-beta.4
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/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- package/docs/cookbook/{common-patterns → advanced}/child-workflows.mdx +1 -1
- package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
- package/docs/cookbook/advanced/meta.json +2 -3
- package/docs/cookbook/advanced/publishing-libraries.mdx +83 -26
- package/docs/cookbook/advanced/serializable-steps.mdx +15 -3
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +50 -91
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +148 -171
- package/docs/cookbook/agent-patterns/meta.json +1 -7
- package/docs/cookbook/common-patterns/batching.mdx +44 -118
- package/docs/cookbook/common-patterns/meta.json +4 -4
- package/docs/cookbook/common-patterns/saga.mdx +126 -31
- package/docs/cookbook/common-patterns/scheduling.mdx +70 -194
- 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/workflow-composition.mdx +118 -0
- package/docs/cookbook/index.mdx +13 -16
- package/docs/cookbook/integrations/ai-sdk.mdx +296 -140
- package/docs/cookbook/integrations/chat-sdk.mdx +251 -151
- package/docs/cookbook/integrations/sandbox.mdx +469 -81
- package/docs/cookbook/meta.json +1 -1
- package/docs/foundations/index.mdx +0 -3
- package/docs/foundations/meta.json +0 -1
- package/docs/foundations/serialization.mdx +1 -1
- package/docs/foundations/starting-workflows.mdx +1 -1
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +60 -8
- package/docs/migration-guides/migrating-from-inngest.mdx +38 -6
- package/docs/migration-guides/migrating-from-temporal.mdx +38 -4
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +52 -11
- package/package.json +11 -11
- package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
- package/docs/cookbook/advanced/durable-objects.mdx +0 -148
- package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
- package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
- package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
- package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
- package/docs/cookbook/common-patterns/content-router.mdx +0 -207
- package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Fan-Out & Parallel Delivery
|
|
3
|
-
description: Send a message to multiple channels or recipients in parallel with independent failure handling.
|
|
4
|
-
type: guide
|
|
5
|
-
summary: Fan out an incident alert to Slack, email, SMS, and PagerDuty simultaneously using Promise.allSettled, so a failure in one channel does not block the others.
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
Use fan-out when one event needs to trigger multiple independent actions in parallel. Each action runs as its own step, so failures are isolated -- a Slack outage doesn't prevent the email from sending.
|
|
9
|
-
|
|
10
|
-
## When to use this
|
|
11
|
-
|
|
12
|
-
- Incident alerting across multiple channels (Slack, email, SMS, PagerDuty)
|
|
13
|
-
- Notifying a list of recipients determined at runtime
|
|
14
|
-
- Any "broadcast" where each delivery is independent
|
|
15
|
-
|
|
16
|
-
## Pattern: Static fan-out
|
|
17
|
-
|
|
18
|
-
Define one step per channel and launch them all with `Promise.allSettled()`:
|
|
19
|
-
|
|
20
|
-
```typescript
|
|
21
|
-
declare function sendSlackAlert(incidentId: string, message: string): Promise<any>; // @setup
|
|
22
|
-
declare function sendEmailAlert(incidentId: string, message: string): Promise<any>; // @setup
|
|
23
|
-
declare function sendSmsAlert(incidentId: string, message: string): Promise<any>; // @setup
|
|
24
|
-
declare function sendPagerDutyAlert(incidentId: string, message: string): Promise<any>; // @setup
|
|
25
|
-
|
|
26
|
-
export async function incidentFanOut(incidentId: string, message: string) {
|
|
27
|
-
"use workflow";
|
|
28
|
-
|
|
29
|
-
const settled = await Promise.allSettled([ // [!code highlight]
|
|
30
|
-
sendSlackAlert(incidentId, message),
|
|
31
|
-
sendEmailAlert(incidentId, message),
|
|
32
|
-
sendSmsAlert(incidentId, message),
|
|
33
|
-
sendPagerDutyAlert(incidentId, message),
|
|
34
|
-
]); // [!code highlight]
|
|
35
|
-
|
|
36
|
-
const ok = settled.filter((r) => r.status === "fulfilled").length;
|
|
37
|
-
return { incidentId, delivered: ok, failed: settled.length - ok };
|
|
38
|
-
}
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
### Step functions
|
|
42
|
-
|
|
43
|
-
Each channel is a separate `"use step"` function. Steps have full Node.js access and retry automatically on transient failures.
|
|
44
|
-
|
|
45
|
-
```typescript
|
|
46
|
-
async function sendSlackAlert(incidentId: string, message: string) {
|
|
47
|
-
"use step";
|
|
48
|
-
await fetch("https://hooks.slack.com/services/T.../B.../xxx", {
|
|
49
|
-
method: "POST",
|
|
50
|
-
body: JSON.stringify({ text: `[${incidentId}] ${message}` }),
|
|
51
|
-
});
|
|
52
|
-
return { channel: "slack" };
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
async function sendEmailAlert(incidentId: string, message: string) {
|
|
56
|
-
"use step";
|
|
57
|
-
await fetch("https://api.sendgrid.com/v3/mail/send", {
|
|
58
|
-
method: "POST",
|
|
59
|
-
headers: { Authorization: `Bearer ${process.env.SENDGRID_KEY}` },
|
|
60
|
-
body: JSON.stringify({
|
|
61
|
-
to: [{ email: "oncall@example.com" }],
|
|
62
|
-
subject: `Incident ${incidentId}`,
|
|
63
|
-
content: [{ type: "text/plain", value: message }],
|
|
64
|
-
}),
|
|
65
|
-
});
|
|
66
|
-
return { channel: "email" };
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async function sendSmsAlert(incidentId: string, message: string) {
|
|
70
|
-
"use step";
|
|
71
|
-
// Call Twilio or similar SMS provider
|
|
72
|
-
return { channel: "sms" };
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async function sendPagerDutyAlert(incidentId: string, message: string) {
|
|
76
|
-
"use step";
|
|
77
|
-
// Call PagerDuty Events API
|
|
78
|
-
return { channel: "pagerduty" };
|
|
79
|
-
}
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
## Pattern: Dynamic recipient list
|
|
83
|
-
|
|
84
|
-
When recipients are determined at runtime (e.g., severity-based routing), build the list dynamically:
|
|
85
|
-
|
|
86
|
-
```typescript
|
|
87
|
-
type Severity = "info" | "warning" | "critical";
|
|
88
|
-
|
|
89
|
-
const RULES = [
|
|
90
|
-
{ channel: "slack", match: () => true },
|
|
91
|
-
{ channel: "email", match: (s: Severity) => s === "warning" || s === "critical" },
|
|
92
|
-
{ channel: "pagerduty", match: (s: Severity) => s === "critical" },
|
|
93
|
-
];
|
|
94
|
-
|
|
95
|
-
export async function alertByRecipientList(
|
|
96
|
-
alertId: string,
|
|
97
|
-
message: string,
|
|
98
|
-
severity: Severity
|
|
99
|
-
) {
|
|
100
|
-
"use workflow";
|
|
101
|
-
|
|
102
|
-
const matched = RULES.filter((r) => r.match(severity)).map((r) => r.channel);
|
|
103
|
-
|
|
104
|
-
const settled = await Promise.allSettled( // [!code highlight]
|
|
105
|
-
matched.map((channel) => deliverToChannel(channel, alertId, message))
|
|
106
|
-
); // [!code highlight]
|
|
107
|
-
|
|
108
|
-
const delivered = settled.filter((r) => r.status === "fulfilled").length;
|
|
109
|
-
return { alertId, severity, matched, delivered, failed: matched.length - delivered };
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async function deliverToChannel(
|
|
113
|
-
channel: string,
|
|
114
|
-
alertId: string,
|
|
115
|
-
message: string
|
|
116
|
-
): Promise<void> {
|
|
117
|
-
"use step";
|
|
118
|
-
// Route to the appropriate API based on channel name
|
|
119
|
-
await fetch(`https://notifications.example.com/${channel}`, {
|
|
120
|
-
method: "POST",
|
|
121
|
-
body: JSON.stringify({ alertId, message }),
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
```
|
|
125
|
-
|
|
126
|
-
## Pattern: Publish-subscribe
|
|
127
|
-
|
|
128
|
-
When subscribers are managed in a registry and filtered by topic:
|
|
129
|
-
|
|
130
|
-
```typescript
|
|
131
|
-
type Subscriber = { id: string; name: string; topics: string[] };
|
|
132
|
-
|
|
133
|
-
export async function publishEvent(topic: string, payload: string) {
|
|
134
|
-
"use workflow";
|
|
135
|
-
|
|
136
|
-
const subscribers = await loadSubscribers();
|
|
137
|
-
const matched = subscribers.filter((sub) => sub.topics.includes(topic));
|
|
138
|
-
|
|
139
|
-
await Promise.allSettled( // [!code highlight]
|
|
140
|
-
matched.map((sub) => deliverToSubscriber(sub.id, topic, payload))
|
|
141
|
-
); // [!code highlight]
|
|
142
|
-
|
|
143
|
-
return { topic, delivered: matched.length, total: subscribers.length };
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
async function loadSubscribers(): Promise<Subscriber[]> {
|
|
147
|
-
"use step";
|
|
148
|
-
// Load from database or configuration service
|
|
149
|
-
return [
|
|
150
|
-
{ id: "sub-1", name: "Order Service", topics: ["orders", "inventory"] },
|
|
151
|
-
{ id: "sub-2", name: "Email Notifier", topics: ["orders", "shipping"] },
|
|
152
|
-
{ id: "sub-3", name: "Analytics", topics: ["orders", "inventory", "shipping"] },
|
|
153
|
-
];
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
async function deliverToSubscriber(
|
|
157
|
-
subscriberId: string,
|
|
158
|
-
topic: string,
|
|
159
|
-
payload: string
|
|
160
|
-
): Promise<void> {
|
|
161
|
-
"use step";
|
|
162
|
-
await fetch(`https://subscribers.example.com/${subscriberId}/deliver`, {
|
|
163
|
-
method: "POST",
|
|
164
|
-
body: JSON.stringify({ topic, payload }),
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
## Deferred await (background steps)
|
|
170
|
-
|
|
171
|
-
You don't have to await a step immediately. Start a step, do other work, and collect the result later. This is different from `Promise.all` -- you interleave sequential and parallel work instead of waiting for everything at once.
|
|
172
|
-
|
|
173
|
-
```typescript
|
|
174
|
-
declare function generateReport(data: Record<string, string>): Promise<any>; // @setup
|
|
175
|
-
declare function sendNotification(userId: string, message: string): Promise<void>; // @setup
|
|
176
|
-
declare function updateDashboard(userId: string): Promise<void>; // @setup
|
|
177
|
-
|
|
178
|
-
export async function onboardUser(userId: string, data: Record<string, string>) {
|
|
179
|
-
"use workflow";
|
|
180
|
-
|
|
181
|
-
// Start report generation in the background
|
|
182
|
-
const reportPromise = generateReport(data); // [!code highlight]
|
|
183
|
-
|
|
184
|
-
// Do other work while the report generates
|
|
185
|
-
await sendNotification(userId, "Processing started");
|
|
186
|
-
await updateDashboard(userId);
|
|
187
|
-
|
|
188
|
-
// Now await the report when we actually need it
|
|
189
|
-
const report = await reportPromise; // [!code highlight]
|
|
190
|
-
return { userId, report };
|
|
191
|
-
}
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
The workflow runtime tracks the background step like any other. If the workflow replays, the already-completed step returns its cached result instantly.
|
|
195
|
-
|
|
196
|
-
## Tips
|
|
197
|
-
|
|
198
|
-
- **Use `Promise.allSettled` over `Promise.all`.** `allSettled` lets you know which channels failed without aborting the others.
|
|
199
|
-
- **Each delivery is an independent step.** Transient failures (e.g., Slack 503) trigger automatic retries without affecting other channels.
|
|
200
|
-
- **Use `FatalError` for permanent failures** (e.g., PagerDuty not configured) to stop retries on that channel while letting others continue.
|
|
201
|
-
- **Dynamic recipient lists** decouple routing from delivery -- adding a new channel is a configuration change, not a code change.
|
|
202
|
-
|
|
203
|
-
## Key APIs
|
|
204
|
-
|
|
205
|
-
- [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
|
|
206
|
-
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions that run with full Node.js access
|
|
207
|
-
- [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) -- fans out to all targets, isolating failures
|
|
208
|
-
- [`FatalError`](/docs/api-reference/workflow/fatal-error) -- prevents automatic retry for permanent failures
|
|
@@ -1,265 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Common Patterns
|
|
3
|
-
description: Implement distributed patterns using familiar async/await syntax with no new APIs to learn.
|
|
4
|
-
type: guide
|
|
5
|
-
summary: Apply sequential, parallel, timeout, and composition patterns in workflows.
|
|
6
|
-
prerequisites:
|
|
7
|
-
- /docs/foundations/workflows-and-steps
|
|
8
|
-
related:
|
|
9
|
-
- /docs/foundations/errors-and-retries
|
|
10
|
-
- /docs/foundations/hooks
|
|
11
|
-
---
|
|
12
|
-
|
|
13
|
-
Common distributed patterns are simple to implement in workflows and require learning no new syntax. You can just use familiar async/await patterns.
|
|
14
|
-
|
|
15
|
-
## Sequential Execution
|
|
16
|
-
|
|
17
|
-
The simplest way to orchestrate steps is to execute them one after another, where each step can be dependent on the previous step.
|
|
18
|
-
|
|
19
|
-
```typescript lineNumbers
|
|
20
|
-
declare function validateData(data: unknown): Promise<string>; // @setup
|
|
21
|
-
declare function processData(data: string): Promise<string>; // @setup
|
|
22
|
-
declare function storeData(data: string): Promise<string>; // @setup
|
|
23
|
-
|
|
24
|
-
export async function dataPipelineWorkflow(data: unknown) {
|
|
25
|
-
"use workflow";
|
|
26
|
-
|
|
27
|
-
const validated = await validateData(data);
|
|
28
|
-
const processed = await processData(validated);
|
|
29
|
-
const stored = await storeData(processed);
|
|
30
|
-
|
|
31
|
-
return stored;
|
|
32
|
-
}
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
## Parallel Execution
|
|
36
|
-
|
|
37
|
-
When you need to execute multiple steps in parallel, you can use `Promise.all` to run them all at the same time.
|
|
38
|
-
|
|
39
|
-
```typescript lineNumbers
|
|
40
|
-
declare function fetchUser(userId: string): Promise<{ name: string }>; // @setup
|
|
41
|
-
declare function fetchOrders(userId: string): Promise<{ items: string[] }>; // @setup
|
|
42
|
-
declare function fetchPreferences(userId: string): Promise<{ theme: string }>; // @setup
|
|
43
|
-
|
|
44
|
-
export async function fetchUserData(userId: string) {
|
|
45
|
-
"use workflow";
|
|
46
|
-
|
|
47
|
-
const [user, orders, preferences] = await Promise.all([ // [!code highlight]
|
|
48
|
-
fetchUser(userId), // [!code highlight]
|
|
49
|
-
fetchOrders(userId), // [!code highlight]
|
|
50
|
-
fetchPreferences(userId) // [!code highlight]
|
|
51
|
-
]); // [!code highlight]
|
|
52
|
-
|
|
53
|
-
return { user, orders, preferences };
|
|
54
|
-
}
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
This not only applies to steps - since [`sleep()`](/docs/api-reference/workflow/sleep) and [`webhook`](/docs/api-reference/workflow/create-webhook) are also just promises, we can await those in parallel too.
|
|
58
|
-
We can also use `Promise.race` instead of `Promise.all` to stop executing promises after the first one completes.
|
|
59
|
-
|
|
60
|
-
```typescript lineNumbers
|
|
61
|
-
import { sleep, createWebhook } from "workflow";
|
|
62
|
-
declare function executeExternalTask(webhookUrl: string): Promise<void>; // @setup
|
|
63
|
-
|
|
64
|
-
export async function runExternalTask(userId: string) {
|
|
65
|
-
"use workflow";
|
|
66
|
-
|
|
67
|
-
const webhook = createWebhook();
|
|
68
|
-
await executeExternalTask(webhook.url); // Send the webhook somewhere
|
|
69
|
-
|
|
70
|
-
// Wait for the external webhook to be hit, with a timeout of 1 day,
|
|
71
|
-
// whichever comes first
|
|
72
|
-
await Promise.race([ // [!code highlight]
|
|
73
|
-
webhook, // [!code highlight]
|
|
74
|
-
sleep("1 day"), // [!code highlight]
|
|
75
|
-
]); // [!code highlight]
|
|
76
|
-
|
|
77
|
-
console.log("Done")
|
|
78
|
-
}
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
## A Full Example
|
|
82
|
-
|
|
83
|
-
Here's a simplified example taken from the [birthday card generator demo](https://github.com/vercel/workflow-examples/tree/main/birthday-card-generator), to illustrate how sequential and parallel execution can be combined.
|
|
84
|
-
|
|
85
|
-
```typescript lineNumbers
|
|
86
|
-
import { createWebhook, sleep, type Webhook } from "workflow"
|
|
87
|
-
declare function makeCardText(prompt: string): Promise<string>; // @setup
|
|
88
|
-
declare function makeCardImage(text: string): Promise<string>; // @setup
|
|
89
|
-
declare function sendRSVPEmail(friend: string, webhook: Webhook): Promise<void>; // @setup
|
|
90
|
-
declare function sendBirthdayCard(text: string, image: string, rsvps: unknown[], email: string): Promise<void>; // @setup
|
|
91
|
-
|
|
92
|
-
async function birthdayWorkflow(
|
|
93
|
-
prompt: string,
|
|
94
|
-
email: string,
|
|
95
|
-
friends: string[],
|
|
96
|
-
birthday: Date
|
|
97
|
-
) {
|
|
98
|
-
"use workflow";
|
|
99
|
-
|
|
100
|
-
// Generate a birthday card with sequential steps
|
|
101
|
-
const text = await makeCardText(prompt)
|
|
102
|
-
const image = await makeCardImage(text)
|
|
103
|
-
|
|
104
|
-
// Create webhooks for each friend who's invited to the birthday party
|
|
105
|
-
const webhooks = friends.map(_ => createWebhook())
|
|
106
|
-
|
|
107
|
-
// Send out all the RSVP invites in parallel steps
|
|
108
|
-
await Promise.all(
|
|
109
|
-
friends.map(
|
|
110
|
-
(friend, i) => sendRSVPEmail(friend, webhooks[i])
|
|
111
|
-
)
|
|
112
|
-
)
|
|
113
|
-
|
|
114
|
-
// Collect RSVPs as they are made without blocking the workflow
|
|
115
|
-
let rsvps = []
|
|
116
|
-
webhooks.map(
|
|
117
|
-
webhook => webhook
|
|
118
|
-
.then(req => req.json())
|
|
119
|
-
.then(( { rsvp } ) => rsvps.push(rsvp))
|
|
120
|
-
)
|
|
121
|
-
|
|
122
|
-
// Wait until the birthday
|
|
123
|
-
await sleep(birthday)
|
|
124
|
-
|
|
125
|
-
// Send birthday card with as many rsvps were collected
|
|
126
|
-
await sendBirthdayCard(text, image, rsvps, email)
|
|
127
|
-
|
|
128
|
-
return { text, image, status: "Sent" }
|
|
129
|
-
}
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
## Timeout Pattern
|
|
133
|
-
|
|
134
|
-
A common requirement is adding timeouts to operations that might take too long. Use `Promise.race` with `sleep()` to implement this pattern.
|
|
135
|
-
|
|
136
|
-
```typescript lineNumbers
|
|
137
|
-
import { sleep } from "workflow";
|
|
138
|
-
declare function processData(data: string): Promise<string>; // @setup
|
|
139
|
-
|
|
140
|
-
export async function processWithTimeout(data: string) {
|
|
141
|
-
"use workflow";
|
|
142
|
-
|
|
143
|
-
const result = await Promise.race([ // [!code highlight]
|
|
144
|
-
processData(data), // [!code highlight]
|
|
145
|
-
sleep("30s").then(() => "timeout" as const), // [!code highlight]
|
|
146
|
-
]); // [!code highlight]
|
|
147
|
-
|
|
148
|
-
if (result === "timeout") {
|
|
149
|
-
// In workflows, any thrown error exits the workflow (FatalError is for steps)
|
|
150
|
-
throw new Error("Processing timed out after 30 seconds");
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
return result;
|
|
154
|
-
}
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
This pattern works with any promise-returning operation including steps, hooks, and webhooks. For example, you can add a timeout to a webhook that waits for external input:
|
|
158
|
-
|
|
159
|
-
```typescript lineNumbers
|
|
160
|
-
import { sleep, createWebhook } from "workflow";
|
|
161
|
-
declare function sendApprovalRequest(requestId: string, webhookUrl: string): Promise<void>; // @setup
|
|
162
|
-
|
|
163
|
-
export async function waitForApproval(requestId: string) {
|
|
164
|
-
"use workflow";
|
|
165
|
-
|
|
166
|
-
const webhook = createWebhook<{ approved: boolean }>();
|
|
167
|
-
await sendApprovalRequest(requestId, webhook.url);
|
|
168
|
-
|
|
169
|
-
const result = await Promise.race([ // [!code highlight]
|
|
170
|
-
webhook.then((req) => req.json()), // [!code highlight]
|
|
171
|
-
sleep("7 days").then(() => ({ timedOut: true }) as const), // [!code highlight]
|
|
172
|
-
]); // [!code highlight]
|
|
173
|
-
|
|
174
|
-
if ("timedOut" in result) {
|
|
175
|
-
throw new Error("Approval request expired after 7 days");
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
return result.approved;
|
|
179
|
-
}
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
## Workflow Composition
|
|
183
|
-
|
|
184
|
-
Workflows can call other workflows, enabling you to break complex processes into reusable building blocks. There are two approaches depending on your needs.
|
|
185
|
-
|
|
186
|
-
### Direct Await (Flattening)
|
|
187
|
-
|
|
188
|
-
Call a child workflow directly using `await`. This "flattens" the child workflow into the parent - the child's steps execute inline within the parent workflow's context.
|
|
189
|
-
|
|
190
|
-
```typescript lineNumbers
|
|
191
|
-
declare function sendEmail(userId: string): Promise<void>; // @setup
|
|
192
|
-
declare function sendPushNotification(userId: string): Promise<void>; // @setup
|
|
193
|
-
declare function createAccount(userId: string): Promise<void>; // @setup
|
|
194
|
-
declare function setupPreferences(userId: string): Promise<void>; // @setup
|
|
195
|
-
|
|
196
|
-
// Child workflow
|
|
197
|
-
export async function sendNotifications(userId: string) {
|
|
198
|
-
"use workflow";
|
|
199
|
-
|
|
200
|
-
await sendEmail(userId);
|
|
201
|
-
await sendPushNotification(userId);
|
|
202
|
-
return { notified: true };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// Parent workflow calls child directly
|
|
206
|
-
export async function onboardUser(userId: string) {
|
|
207
|
-
"use workflow";
|
|
208
|
-
|
|
209
|
-
await createAccount(userId);
|
|
210
|
-
await sendNotifications(userId); // [!code highlight]
|
|
211
|
-
await setupPreferences(userId);
|
|
212
|
-
|
|
213
|
-
return { userId, status: "onboarded" };
|
|
214
|
-
}
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
With direct await, the parent workflow waits for the child to complete before continuing. The child's steps appear in the parent's event log as if they were called directly from the parent.
|
|
218
|
-
|
|
219
|
-
### Background Execution via Step
|
|
220
|
-
|
|
221
|
-
To run a child workflow independently without blocking the parent, use a step that calls [`start()`](/docs/api-reference/workflow-api/start). This launches the child workflow in the background.
|
|
222
|
-
|
|
223
|
-
```typescript lineNumbers
|
|
224
|
-
import { start } from "workflow/api";
|
|
225
|
-
declare function generateReport(reportId: string): Promise<void>; // @setup
|
|
226
|
-
declare function fulfillOrder(orderId: string): Promise<{ id: string }>; // @setup
|
|
227
|
-
declare function sendConfirmation(orderId: string): Promise<void>; // @setup
|
|
228
|
-
|
|
229
|
-
// Step that starts a workflow in the background
|
|
230
|
-
async function triggerReportGeneration(reportId: string) {
|
|
231
|
-
"use step";
|
|
232
|
-
|
|
233
|
-
const run = await start(generateReport, [reportId]); // [!code highlight]
|
|
234
|
-
return run.runId;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// Parent workflow
|
|
238
|
-
export async function processOrder(orderId: string) {
|
|
239
|
-
"use workflow";
|
|
240
|
-
|
|
241
|
-
const order = await fulfillOrder(orderId);
|
|
242
|
-
|
|
243
|
-
// Fire off report generation without waiting
|
|
244
|
-
const reportRunId = await triggerReportGeneration(orderId); // [!code highlight]
|
|
245
|
-
|
|
246
|
-
// Continue immediately - report generates in background
|
|
247
|
-
await sendConfirmation(orderId);
|
|
248
|
-
|
|
249
|
-
return { orderId, reportRunId };
|
|
250
|
-
}
|
|
251
|
-
```
|
|
252
|
-
|
|
253
|
-
With background execution, the parent workflow continues immediately after starting the child. The child workflow runs independently with its own event log and can be monitored separately using the returned `runId`.
|
|
254
|
-
|
|
255
|
-
<Callout type="info">
|
|
256
|
-
If you want the child workflow to run on the latest deployment rather than the current one, you can pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. This is currently a Vercel-specific feature. 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.
|
|
257
|
-
</Callout>
|
|
258
|
-
|
|
259
|
-
**Choose direct await when:**
|
|
260
|
-
- The parent needs the child's result before continuing
|
|
261
|
-
- You want a single, unified event log
|
|
262
|
-
|
|
263
|
-
**Choose background execution when:**
|
|
264
|
-
- The parent doesn't need to wait for the result
|
|
265
|
-
- You want separate workflow runs for observability
|