workflow 5.0.0-beta.2 → 5.0.0-beta.21
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/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -2
- 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/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/docs/ai/index.mdx +27 -23
- package/docs/api-reference/index.mdx +24 -0
- package/docs/api-reference/meta.json +8 -0
- package/docs/api-reference/vitest/index.mdx +28 -7
- package/docs/api-reference/workflow/create-hook.mdx +38 -0
- package/docs/api-reference/workflow/create-webhook.mdx +1 -0
- package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
- package/docs/api-reference/workflow/fetch.mdx +5 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
- package/docs/api-reference/workflow-api/get-run.mdx +6 -0
- package/docs/api-reference/workflow-api/index.mdx +6 -8
- package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
- package/docs/api-reference/workflow-api/start.mdx +13 -5
- package/docs/api-reference/workflow-astro/index.mdx +18 -0
- package/docs/api-reference/workflow-astro/meta.json +4 -0
- package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
- package/docs/api-reference/workflow-errors/index.mdx +85 -0
- package/docs/api-reference/workflow-errors/meta.json +5 -0
- package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
- package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
- package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
- package/docs/api-reference/workflow-nest/index.mdx +31 -0
- package/docs/api-reference/workflow-nest/meta.json +9 -0
- package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
- package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
- package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
- package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
- package/docs/api-reference/workflow-nitro/index.mdx +59 -0
- package/docs/api-reference/workflow-nuxt/index.mdx +47 -0
- package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
- package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
- package/docs/api-reference/workflow-observability/index.mdx +64 -0
- package/docs/api-reference/workflow-observability/meta.json +11 -0
- package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
- package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
- package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
- package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
- package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
- package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
- package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
- package/docs/api-reference/workflow-runtime/index.mdx +43 -0
- package/docs/api-reference/workflow-runtime/meta.json +12 -0
- package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
- package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
- package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
- package/docs/api-reference/workflow-serde/index.mdx +0 -1
- package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
- package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
- package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
- package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
- package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
- package/docs/api-reference/workflow-vite/index.mdx +18 -0
- package/docs/api-reference/workflow-vite/meta.json +4 -0
- package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
- package/docs/changelog/attributes-mvp.mdx +380 -0
- package/docs/changelog/eager-processing.mdx +269 -0
- package/docs/changelog/index.mdx +2 -1
- package/docs/changelog/lazy-event-creation.md +127 -0
- package/docs/changelog/meta.json +7 -1
- package/docs/changelog/resilient-start.mdx +31 -283
- package/docs/changelog/turbo-mode.md +87 -0
- package/docs/cookbook/advanced/child-workflows.mdx +315 -0
- package/docs/cookbook/advanced/meta.json +2 -3
- package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
- package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
- 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 +11 -184
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
- package/docs/cookbook/agent-patterns/meta.json +1 -7
- package/docs/cookbook/common-patterns/batching.mdx +44 -118
- package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
- package/docs/cookbook/common-patterns/meta.json +4 -4
- package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
- package/docs/cookbook/common-patterns/saga.mdx +128 -33
- package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
- package/docs/cookbook/index.mdx +14 -17
- package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
- package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
- package/docs/cookbook/integrations/sandbox.mdx +482 -81
- package/docs/cookbook/meta.json +1 -1
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +5 -3
- package/docs/deploying/world/vercel-world.mdx +2 -0
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
- package/docs/errors/corrupted-event-log.mdx +5 -5
- package/docs/errors/hook-conflict.mdx +56 -4
- package/docs/errors/index.mdx +9 -0
- package/docs/errors/replay-divergence.mdx +27 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/step-executed-multiple-times.mdx +23 -0
- package/docs/errors/step-not-registered.mdx +1 -1
- package/docs/foundations/cancellation.mdx +459 -0
- package/docs/foundations/errors-and-retries.mdx +7 -3
- package/docs/foundations/hooks.mdx +29 -0
- package/docs/foundations/idempotency.mdx +236 -11
- 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/streaming.mdx +14 -23
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +6 -0
- package/docs/getting-started/index.mdx +6 -7
- package/docs/getting-started/meta.json +1 -0
- package/docs/getting-started/nestjs.mdx +9 -0
- package/docs/getting-started/next.mdx +5 -3
- package/docs/getting-started/nitro.mdx +22 -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/encryption.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 +21 -0
- package/docs/internal/meta.json +10 -0
- package/docs/internal/nitro-native-build.mdx +38 -0
- package/docs/internal/nitro-web-ui.mdx +24 -0
- package/docs/internal/serializable-abort-controller.mdx +148 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
- package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
- package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
- package/docs/observability/attributes.mdx +87 -0
- package/docs/observability/index.mdx +25 -1
- package/docs/observability/meta.json +1 -1
- package/docs/observability/tracing.mdx +106 -0
- package/docs/testing/index.mdx +2 -2
- package/package.json +14 -13
- package/docs/api-reference/workflow-api/world/meta.json +0 -4
- package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
- 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/child-workflows.mdx +0 -372
- 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
|
@@ -2,248 +2,132 @@
|
|
|
2
2
|
title: Sleep, Scheduling & Timed Workflows
|
|
3
3
|
description: Use durable sleep to schedule actions minutes, hours, days, or weeks into the future.
|
|
4
4
|
type: guide
|
|
5
|
-
summary: Schedule future actions with durable sleep that survives cold starts, and race sleeps against hooks to let external events
|
|
5
|
+
summary: Schedule future actions with durable sleep that survives cold starts, and race sleeps against hooks to let external events cancel the workflow early.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
Workflow's `sleep()` is durable
|
|
8
|
+
Workflow's `sleep()` is durable — it survives cold starts, restarts, and deployments. Combined with `defineHook()` and `Promise.race()`, it becomes the foundation for interruptible scheduled workflows like drip campaigns, reminders, and timed sequences.
|
|
9
|
+
|
|
10
|
+
<Callout type="info">
|
|
11
|
+
Scheduled workflows are still pinned to the deployment that started them. If you are building recurring or indefinitely running schedules that should adopt newer code over time, see [Versioning](/docs/foundations/versioning) for the explicit `deploymentId: "latest"` continuation pattern.
|
|
12
|
+
</Callout>
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
11
15
|
|
|
12
|
-
- Sending emails on a schedule (drip campaigns,
|
|
13
|
-
- Waiting for a deadline
|
|
14
|
-
- Any pattern where "do X, wait N hours, then do Y" needs to be reliable
|
|
16
|
+
- Sending emails on a schedule (drip campaigns, onboarding sequences, reminders)
|
|
17
|
+
- Waiting for a deadline but allowing early cancellation
|
|
18
|
+
- Any pattern where "do X, wait N hours, then do Y" needs to be both reliable and interruptible
|
|
15
19
|
|
|
16
|
-
##
|
|
20
|
+
## Drip campaign with cancellation
|
|
17
21
|
|
|
18
|
-
|
|
22
|
+
A drip campaign sends emails at intervals, sleeping between each. Each sleep races against a cancellation hook — if an external event fires the hook (e.g. user converts, unsubscribes), the campaign stops immediately.
|
|
19
23
|
|
|
20
24
|
```typescript
|
|
21
|
-
import { sleep } from "workflow";
|
|
22
|
-
|
|
23
|
-
export async function onboardingDrip(email: string) {
|
|
24
|
-
"use workflow";
|
|
25
|
-
|
|
26
|
-
await sendEmail(email, "welcome");
|
|
27
|
-
|
|
28
|
-
await sleep("1d"); // [!code highlight]
|
|
29
|
-
await sendEmail(email, "getting-started-tips");
|
|
30
|
-
|
|
31
|
-
await sleep("2d"); // [!code highlight]
|
|
32
|
-
await sendEmail(email, "feature-highlights");
|
|
33
|
-
|
|
34
|
-
await sleep("4d"); // [!code highlight]
|
|
35
|
-
await sendEmail(email, "follow-up");
|
|
25
|
+
import { defineHook, sleep } from "workflow";
|
|
36
26
|
|
|
37
|
-
|
|
38
|
-
}
|
|
27
|
+
// Hook that any API route can fire to cancel the drip
|
|
28
|
+
export const cancelDrip = defineHook<{ reason?: string }>(); // [!code highlight]
|
|
39
29
|
|
|
40
30
|
async function sendEmail(email: string, template: string): Promise<void> {
|
|
41
31
|
"use step";
|
|
42
32
|
await fetch("https://api.sendgrid.com/v3/mail/send", {
|
|
43
33
|
method: "POST",
|
|
44
34
|
headers: { Authorization: `Bearer ${process.env.SENDGRID_KEY}` },
|
|
45
|
-
body: JSON.stringify({
|
|
46
|
-
to: [{ email }],
|
|
47
|
-
template_id: template,
|
|
48
|
-
}),
|
|
35
|
+
body: JSON.stringify({ to: [{ email }], template_id: template }),
|
|
49
36
|
});
|
|
50
37
|
}
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
## Pattern: Interruptible reminder (sleep vs hook)
|
|
54
|
-
|
|
55
|
-
Race a `sleep()` against a `defineHook` so external events can cancel, snooze, or send early:
|
|
56
|
-
|
|
57
|
-
```typescript
|
|
58
|
-
import { defineHook, sleep } from "workflow";
|
|
59
|
-
|
|
60
|
-
type ReminderAction =
|
|
61
|
-
| { type: "cancel" }
|
|
62
|
-
| { type: "send_now" }
|
|
63
|
-
| { type: "snooze"; seconds: number };
|
|
64
38
|
|
|
65
|
-
export
|
|
66
|
-
|
|
67
|
-
export async function scheduleReminder(userId: string, delayMs: number) {
|
|
39
|
+
export async function emailSequence(email: string) {
|
|
68
40
|
"use workflow";
|
|
69
41
|
|
|
70
|
-
|
|
71
|
-
const action = reminderActionHook.create({ token: `reminder:${userId}` });
|
|
72
|
-
|
|
73
|
-
const outcome = await Promise.race([ // [!code highlight]
|
|
74
|
-
sleep(sendAt).then(() => ({ kind: "time" as const })), // [!code highlight]
|
|
75
|
-
action.then((payload) => ({ kind: "action" as const, payload })), // [!code highlight]
|
|
76
|
-
]);
|
|
77
|
-
|
|
78
|
-
if (outcome.kind === "action") {
|
|
79
|
-
if (outcome.payload.type === "cancel") {
|
|
80
|
-
return { userId, status: "cancelled" };
|
|
81
|
-
}
|
|
82
|
-
if (outcome.payload.type === "snooze") {
|
|
83
|
-
sendAt = new Date(Date.now() + outcome.payload.seconds * 1000);
|
|
84
|
-
await sleep(sendAt);
|
|
85
|
-
}
|
|
86
|
-
// "send_now" falls through to send immediately
|
|
87
|
-
}
|
|
42
|
+
await sendEmail(email, "welcome");
|
|
88
43
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
44
|
+
// Race durable sleep against the cancellation hook
|
|
45
|
+
const hook = cancelDrip.create({ token: `cancel-drip:${email}` }); // [!code highlight]
|
|
46
|
+
const cancelled = await Promise.race([ // [!code highlight]
|
|
47
|
+
sleep("2d").then(() => false), // [!code highlight]
|
|
48
|
+
hook.then(() => true), // [!code highlight]
|
|
49
|
+
]); // [!code highlight]
|
|
50
|
+
if (cancelled) return { status: "cancelled", email };
|
|
92
51
|
|
|
93
|
-
|
|
94
|
-
"use step";
|
|
95
|
-
await fetch("https://api.example.com/reminders/send", {
|
|
96
|
-
method: "POST",
|
|
97
|
-
body: JSON.stringify({ userId }),
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
```
|
|
52
|
+
await sendEmail(email, "getting-started-tips");
|
|
101
53
|
|
|
102
|
-
|
|
54
|
+
// Create a fresh hook for the next sleep window
|
|
55
|
+
const hook2 = cancelDrip.create({ token: `cancel-drip:${email}` }); // [!code highlight]
|
|
56
|
+
const cancelled2 = await Promise.race([ // [!code highlight]
|
|
57
|
+
sleep("2d").then(() => false), // [!code highlight]
|
|
58
|
+
hook2.then(() => true), // [!code highlight]
|
|
59
|
+
]); // [!code highlight]
|
|
60
|
+
if (cancelled2) return { status: "cancelled", email };
|
|
103
61
|
|
|
104
|
-
|
|
105
|
-
import { resumeHook } from "workflow/api";
|
|
62
|
+
await sendEmail(email, "feature-highlights");
|
|
106
63
|
|
|
107
|
-
|
|
108
|
-
export async function POST(request: Request) {
|
|
109
|
-
const { userId } = await request.json();
|
|
110
|
-
await resumeHook(`reminder:${userId}`, { type: "cancel" }); // [!code highlight]
|
|
111
|
-
return Response.json({ ok: true });
|
|
64
|
+
return { status: "drip-complete", email };
|
|
112
65
|
}
|
|
113
66
|
```
|
|
114
67
|
|
|
115
|
-
|
|
68
|
+
### Cancelling from an API route
|
|
116
69
|
|
|
117
|
-
|
|
70
|
+
Any server-side code can fire the hook by calling `.resume()` with the same token:
|
|
118
71
|
|
|
119
72
|
```typescript
|
|
120
|
-
import {
|
|
121
|
-
|
|
122
|
-
type EventPayload = { type: string; message: string };
|
|
123
|
-
|
|
124
|
-
export const digestEvent = defineHook<EventPayload>();
|
|
125
|
-
|
|
126
|
-
export async function collectAndSendDigest(
|
|
127
|
-
digestId: string,
|
|
128
|
-
userId: string,
|
|
129
|
-
windowMs: number = 3_600_000
|
|
130
|
-
) {
|
|
131
|
-
"use workflow";
|
|
132
|
-
|
|
133
|
-
const hook = digestEvent.create({ token: `digest:${digestId}` });
|
|
134
|
-
const windowClosed = sleep(`${windowMs}ms`).then(() => ({
|
|
135
|
-
kind: "window_closed" as const,
|
|
136
|
-
}));
|
|
137
|
-
const events: EventPayload[] = [];
|
|
73
|
+
import { cancelDrip } from "@/workflows/email-sequence";
|
|
138
74
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
hook.then((payload) => ({ kind: "event" as const, payload })),
|
|
142
|
-
windowClosed,
|
|
143
|
-
]);
|
|
75
|
+
export async function POST(req: Request) {
|
|
76
|
+
const { email, reason } = await req.json();
|
|
144
77
|
|
|
145
|
-
|
|
146
|
-
|
|
78
|
+
if (!email) {
|
|
79
|
+
return Response.json({ error: "email is required" }, { status: 400 });
|
|
147
80
|
}
|
|
148
81
|
|
|
149
|
-
|
|
150
|
-
await
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
## Pattern: Timeout
|
|
166
|
-
|
|
167
|
-
Add a timeout to any operation by racing it against `sleep()`:
|
|
168
|
-
|
|
169
|
-
```typescript
|
|
170
|
-
import { sleep, FatalError } from "workflow";
|
|
171
|
-
|
|
172
|
-
export async function processWithTimeout(jobId: string) {
|
|
173
|
-
"use workflow";
|
|
174
|
-
|
|
175
|
-
const result = await Promise.race([ // [!code highlight]
|
|
176
|
-
processData(jobId),
|
|
177
|
-
sleep("30s").then(() => "timeout" as const), // [!code highlight]
|
|
178
|
-
]);
|
|
179
|
-
|
|
180
|
-
if (result === "timeout") {
|
|
181
|
-
return { jobId, status: "timed_out" };
|
|
82
|
+
try {
|
|
83
|
+
await cancelDrip.resume(`cancel-drip:${email}`, { // [!code highlight]
|
|
84
|
+
reason: reason ?? "User completed action", // [!code highlight]
|
|
85
|
+
}); // [!code highlight]
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const msg = error instanceof Error ? error.message.toLowerCase() : "";
|
|
88
|
+
if (msg.includes("not found") || msg.includes("expired")) {
|
|
89
|
+
return Response.json({
|
|
90
|
+
success: true,
|
|
91
|
+
email,
|
|
92
|
+
note: "No active drip found (already completed or cancelled)",
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
throw error;
|
|
182
96
|
}
|
|
183
97
|
|
|
184
|
-
return {
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
async function processData(jobId: string): Promise<string> {
|
|
188
|
-
"use step";
|
|
189
|
-
// Long-running computation
|
|
190
|
-
return `result-for-${jobId}`;
|
|
98
|
+
return Response.json({ success: true, email });
|
|
191
99
|
}
|
|
192
100
|
```
|
|
193
101
|
|
|
194
|
-
##
|
|
195
|
-
|
|
196
|
-
When you need to poll an external service until a job completes, define your own `sleep` as a step function and use it in a polling loop. Each iteration becomes a separate step in the event log, making the entire loop durable.
|
|
102
|
+
## How it works
|
|
197
103
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
export async function waitForTranscription(jobId: string) {
|
|
205
|
-
"use workflow";
|
|
104
|
+
1. **Durable sleep** — `sleep("2d")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
|
|
105
|
+
2. **Hook creation** — `cancelDrip.create({ token })` registers a hook that resolves when any external system calls `.resume()` with the same token.
|
|
106
|
+
3. **Race** — `Promise.race([sleep(...), hook])` blocks until either the timer fires or the hook is resumed, whichever comes first.
|
|
107
|
+
4. **Fresh hooks per window** — after a sleep completes normally, the previous hook instance is consumed. A new `.create()` call registers a fresh hook for the next sleep window, reusing the same token.
|
|
206
108
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
109
|
+
<Callout type="info">
|
|
110
|
+
Deterministic hook tokens can also serve as the idempotency point for scheduled runs. If duplicate schedule starts would send duplicate campaigns or reminders, create a hook with a token derived from the campaign key near the beginning of the workflow and route retries through that hook. If two scheduled starts race, the duplicate run can detect the conflict early with `await hook.getConflict()`, which resolves with the active owner so the duplicate can defer to it. See [Idempotency](/docs/foundations/idempotency).
|
|
111
|
+
</Callout>
|
|
210
112
|
|
|
211
|
-
|
|
212
|
-
await sleep(5000); // [!code highlight]
|
|
213
|
-
attempts++;
|
|
214
|
-
const result = await checkJobStatus(jobId); // [!code highlight]
|
|
215
|
-
status = result.status;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (status !== "completed") {
|
|
219
|
-
return { jobId, status: "timed_out", attempts };
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
return { jobId, status: "completed", attempts };
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async function checkJobStatus(jobId: string): Promise<{ status: string }> {
|
|
226
|
-
"use step";
|
|
227
|
-
const res = await fetch(`https://api.example.com/jobs/${jobId}`);
|
|
228
|
-
return res.json();
|
|
229
|
-
}
|
|
230
|
-
```
|
|
113
|
+
## Adapting to your use case
|
|
231
114
|
|
|
232
|
-
**
|
|
233
|
-
-
|
|
234
|
-
-
|
|
115
|
+
- **Change durations** — replace `"2d"` with any duration string (`"1h"`, `"7d"`, `"30m"`) or a `Date` object for absolute times.
|
|
116
|
+
- **Add more steps** — the pattern scales to any number of email-then-sleep pairs.
|
|
117
|
+
- **Snooze instead of cancel** — resolve the hook with a `snooze` payload and sleep again: `sleep(new Date(Date.now() + payload.snoozeMs))`.
|
|
118
|
+
- **Timeout any operation** — the same `Promise.race(sleep, work)` pattern works for adding deadlines to slow steps.
|
|
119
|
+
- **Real providers** — swap the `sendEmail` step body for Resend, Postmark, or any HTTP API. The `"use step"` function has full Node.js access.
|
|
235
120
|
|
|
236
121
|
## Tips
|
|
237
122
|
|
|
238
123
|
- **`sleep()` accepts** duration strings (`"1d"`, `"2h"`, `"30s"`), milliseconds, or `Date` objects for sleeping until a specific time.
|
|
239
|
-
- **Durable means durable.** A `sleep("7d")` workflow costs nothing while sleeping
|
|
240
|
-
- **
|
|
241
|
-
- **Use `sleep()` in workflow context only.** Step functions cannot call `sleep()` directly. If a step needs a delay, use a standard `setTimeout` or return control to the workflow.
|
|
124
|
+
- **Durable means durable.** A `sleep("7d")` workflow costs nothing while sleeping — no compute, no memory.
|
|
125
|
+
- **Use `sleep()` in workflow context only.** Step functions cannot call `sleep()` directly. If a step needs a delay, use `setTimeout` inside the step.
|
|
242
126
|
|
|
243
127
|
## Key APIs
|
|
244
128
|
|
|
245
|
-
- [`"use workflow"`](/docs/foundations/workflows-and-steps)
|
|
246
|
-
- [`"use step"`](/docs/foundations/workflows-and-steps)
|
|
247
|
-
- [`sleep()`](/docs/api-reference/workflow/sleep)
|
|
248
|
-
- [`defineHook`](/docs/api-reference/workflow/define-hook)
|
|
249
|
-
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)
|
|
129
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
130
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions that run with full Node.js access
|
|
131
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
|
|
132
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — creates a typed hook that external systems can fire
|
|
133
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — races sleep against hooks for interruptible waits
|
|
@@ -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,100 @@
|
|
|
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, and use idempotency keys for non-idempotent side effects. See the [Cancellation Guide](/docs/foundations/cancellation) and [Idempotency](/docs/foundations/idempotency) 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
|
+
- [Idempotency](/docs/foundations/idempotency) — protect side effects that may keep running after a timeout
|
|
100
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — race operations against deadlines
|