workflow 5.0.0-beta.1 → 5.0.0-beta.3
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.js +1 -1
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.js +1 -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.js +1 -1
- package/dist/runtime.js +1 -1
- 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/resumable-streams.mdx +1 -1
- package/docs/api-reference/workflow/create-webhook.mdx +37 -18
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +34 -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/cookbook/advanced/child-workflows.mdx +372 -0
- package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -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/agent-patterns/agent-cancellation.mdx +205 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +150 -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 +125 -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 +118 -0
- package/docs/cookbook/index.mdx +38 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +360 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +303 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +516 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +1 -1
- package/docs/deploying/world/vercel-world.mdx +1 -1
- package/docs/errors/start-invalid-workflow-function.mdx +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/getting-started/index.mdx +8 -1
- package/docs/getting-started/meta.json +2 -1
- package/docs/getting-started/python.mdx +165 -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 +363 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +314 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +318 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +337 -0
- package/package.json +13 -13
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Python
|
|
3
|
+
description: Build durable workflows and AI agents in Python with the Vercel SDK.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Set up the Workflow Python SDK in your Python application.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/getting-started
|
|
8
|
+
related:
|
|
9
|
+
- /docs/foundations
|
|
10
|
+
- /docs/foundations/workflows-and-steps
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
<Callout type="warn">
|
|
14
|
+
The Python SDK is currently in **beta**. APIs and behavior may change. For the latest documentation and updates, see the [official Vercel Workflow Python documentation](https://vercel.com/docs/workflow/python?language=py).
|
|
15
|
+
</Callout>
|
|
16
|
+
|
|
17
|
+
You can build durable workflows in Python using the [`vercel` Python SDK](https://pypi.org/project/vercel/). Your workflow code can pause, resume, and maintain state, just like the JavaScript and TypeScript Workflow SDK.
|
|
18
|
+
|
|
19
|
+
## Getting Started
|
|
20
|
+
|
|
21
|
+
Install the `vercel` package:
|
|
22
|
+
|
|
23
|
+
```bash filename="Terminal"
|
|
24
|
+
pip install vercel
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Configure `experimentalServices` in your `vercel.json`:
|
|
28
|
+
|
|
29
|
+
```json filename="vercel.json"
|
|
30
|
+
{
|
|
31
|
+
"experimentalServices": {
|
|
32
|
+
"ai_content_workflow": {
|
|
33
|
+
"type": "worker",
|
|
34
|
+
"entrypoint": "app/workflows/ai_content_workflow.py",
|
|
35
|
+
"topics": ["__wkf_*"]
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Workflows
|
|
42
|
+
|
|
43
|
+
A workflow is a stateful function that coordinates multi-step logic over time. Create a `Workflows` instance and use the `@wf.workflow` decorator to mark a function as durable:
|
|
44
|
+
|
|
45
|
+
```python filename="app/workflow.py" {3}
|
|
46
|
+
from vercel import workflow
|
|
47
|
+
|
|
48
|
+
wf = workflow.Workflows()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```python filename="app/workflows/ai_content_workflow.py" {3}
|
|
52
|
+
from app.workflow import wf
|
|
53
|
+
|
|
54
|
+
@wf.workflow
|
|
55
|
+
async def ai_content_workflow(*, topic: str):
|
|
56
|
+
draft = await generate_draft(topic=topic)
|
|
57
|
+
summary = await summarize_draft(draft=draft)
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
"draft": draft,
|
|
61
|
+
"summary": summary,
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Under the hood, the workflow compiles into a route that orchestrates execution. All inputs and outputs are recorded in an event log. If a deploy or crash happens, the system replays execution deterministically from where it stopped.
|
|
66
|
+
|
|
67
|
+
## Steps
|
|
68
|
+
|
|
69
|
+
A step is a stateless function that runs a unit of durable work inside a workflow. Use `@wf.step` to mark a function as a step:
|
|
70
|
+
|
|
71
|
+
```python filename="app/steps/generate_draft.py" {4,8}
|
|
72
|
+
import random
|
|
73
|
+
from app.workflow import wf
|
|
74
|
+
|
|
75
|
+
@wf.step
|
|
76
|
+
async def generate_draft(*, topic: str):
|
|
77
|
+
return await ai_generate(prompt=f"Write a blog post about {topic}")
|
|
78
|
+
|
|
79
|
+
@wf.step
|
|
80
|
+
async def summarize_draft(*, draft: str):
|
|
81
|
+
summary = await ai_summarize(text=draft)
|
|
82
|
+
|
|
83
|
+
# Simulate a transient error. The step automatically retries.
|
|
84
|
+
if random.random() < 0.3:
|
|
85
|
+
raise Exception("Transient AI provider error")
|
|
86
|
+
|
|
87
|
+
return summary
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Each step compiles into an isolated route. While the step executes, the workflow suspends without consuming resources. When the step completes, the workflow resumes automatically where it left off.
|
|
91
|
+
|
|
92
|
+
## Sleep
|
|
93
|
+
|
|
94
|
+
Sleep pauses a workflow for a specified duration without consuming compute resources:
|
|
95
|
+
|
|
96
|
+
```python filename="app/workflows/ai_refine.py" {7}
|
|
97
|
+
from vercel import workflow
|
|
98
|
+
|
|
99
|
+
@wf.workflow
|
|
100
|
+
async def ai_refine_workflow(*, draft_id: str):
|
|
101
|
+
draft = await fetch_draft(draft_id)
|
|
102
|
+
|
|
103
|
+
await workflow.sleep("7 days") # Wait 7 days to gather more signals.
|
|
104
|
+
|
|
105
|
+
refined = await refine_draft(draft)
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
"draft_id": draft_id,
|
|
109
|
+
"refined": refined,
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The sleep call pauses the workflow and consumes no resources. The workflow resumes automatically when the time expires.
|
|
114
|
+
|
|
115
|
+
## Hooks
|
|
116
|
+
|
|
117
|
+
A hook lets a workflow wait for external events such as user actions, webhooks, or third-party API responses.
|
|
118
|
+
|
|
119
|
+
Define a hook model with Pydantic and `workflow.BaseHook`:
|
|
120
|
+
|
|
121
|
+
```python filename="app/workflows/approval.py" {3,14}
|
|
122
|
+
from vercel import workflow
|
|
123
|
+
|
|
124
|
+
class Approval(BaseModel, workflow.BaseHook):
|
|
125
|
+
"""Human approval for AI-generated drafts"""
|
|
126
|
+
|
|
127
|
+
decision: Literal["approved", "changes"]
|
|
128
|
+
notes: str | None = None
|
|
129
|
+
|
|
130
|
+
@wf.workflow
|
|
131
|
+
async def ai_approval_workflow(*, topic: str):
|
|
132
|
+
draft = await generate_draft(topic=topic)
|
|
133
|
+
|
|
134
|
+
# Wait for human approval events
|
|
135
|
+
async for event in Approval.wait(token="draft-123"):
|
|
136
|
+
if event.decision == "approved":
|
|
137
|
+
await publish_draft(draft)
|
|
138
|
+
break
|
|
139
|
+
|
|
140
|
+
revised = await refine_draft(draft, event.notes)
|
|
141
|
+
await publish_draft(revised)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Resume the workflow when data arrives:
|
|
145
|
+
|
|
146
|
+
```python filename="app/api/resume.py" {5}
|
|
147
|
+
@app.post("/api/resume")
|
|
148
|
+
async def resume(approval: Approval):
|
|
149
|
+
"""Resume the workflow when an approval is received"""
|
|
150
|
+
|
|
151
|
+
await approval.resume("draft-123")
|
|
152
|
+
return {"ok": True}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
When a hook receives data, the workflow resumes automatically. You don't need polling, message queues, or manual state management.
|
|
156
|
+
|
|
157
|
+
## Learn More
|
|
158
|
+
|
|
159
|
+
For comprehensive documentation, examples, and the latest updates, visit the [official Vercel Workflow Python documentation](https://vercel.com/docs/workflow/python).
|
|
160
|
+
|
|
161
|
+
## Next Steps
|
|
162
|
+
|
|
163
|
+
- Learn more about the [Foundations](/docs/foundations).
|
|
164
|
+
- Check [Errors](/docs/errors) if you encounter issues.
|
|
165
|
+
- Explore the [API Reference](/docs/api-reference).
|
package/docs/meta.json
CHANGED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Migration Guides
|
|
3
|
+
description: Move your existing durable workflow system to the Workflow SDK with side-by-side code comparisons and a realistic migration example.
|
|
4
|
+
type: overview
|
|
5
|
+
summary: Migrate from Temporal, Inngest, AWS Step Functions, or trigger.dev to the Workflow SDK.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
- /docs/getting-started
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
<Callout type="info">
|
|
12
|
+
Install the Workflow SDK migration skill:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
|
|
16
|
+
```
|
|
17
|
+
</Callout>
|
|
18
|
+
|
|
19
|
+
Move an existing orchestration system to the Workflow SDK. Each guide pairs a concept-mapping table with side-by-side code, so you can translate one piece of your codebase at a time.
|
|
20
|
+
|
|
21
|
+
<Cards>
|
|
22
|
+
<Card href="/docs/migration-guides/migrating-from-temporal" title="Migrating from Temporal">
|
|
23
|
+
Map Activities, Workers, Signals, and Child Workflows onto workflows, steps, hooks, and `start()` / `getRun()`.
|
|
24
|
+
</Card>
|
|
25
|
+
<Card href="/docs/migration-guides/migrating-from-inngest" title="Migrating from Inngest">
|
|
26
|
+
Map `createFunction`, `step.run`, `step.sleep`, `step.waitForEvent`, and `step.invoke` onto workflows, steps, and hooks.
|
|
27
|
+
</Card>
|
|
28
|
+
<Card href="/docs/migration-guides/migrating-from-aws-step-functions" title="Migrating from AWS Step Functions">
|
|
29
|
+
Replace ASL JSON states, Task / Choice / Wait / Parallel states, and `.waitForTaskToken` callbacks with TypeScript.
|
|
30
|
+
</Card>
|
|
31
|
+
<Card href="/docs/migration-guides/migrating-from-trigger-dev" title="Migrating from trigger.dev">
|
|
32
|
+
Map `task()`, `schemaTask()`, `wait.for` / `wait.forToken`, `triggerAndWait`, and `metadata.stream` onto workflows, steps, hooks, and `start()` / `getRun()`.
|
|
33
|
+
</Card>
|
|
34
|
+
</Cards>
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Migrating from AWS Step Functions
|
|
3
|
+
description: Move an AWS Step Functions state machine to the Workflow SDK by replacing JSON state definitions, Task states, Choice/Wait/Parallel states, Retry/Catch blocks, and .waitForTaskToken callbacks with Workflows, Steps, Hooks, and idiomatic TypeScript control flow.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Translate an AWS Step Functions state machine into the Workflow SDK with side-by-side code examples.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/getting-started/next
|
|
8
|
+
- /docs/foundations/workflows-and-steps
|
|
9
|
+
related:
|
|
10
|
+
- /docs/foundations/starting-workflows
|
|
11
|
+
- /docs/foundations/errors-and-retries
|
|
12
|
+
- /docs/foundations/hooks
|
|
13
|
+
- /docs/foundations/streaming
|
|
14
|
+
- /docs/deploying/world/vercel-world
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
Move an AWS Step Functions state machine to the Workflow SDK by replacing JSON state definitions with TypeScript functions. This guide shows the direct mapping between ASL states and Workflow SDK primitives.
|
|
18
|
+
|
|
19
|
+
<Callout type="info">
|
|
20
|
+
Install the Workflow SDK migration skill:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
|
|
24
|
+
```
|
|
25
|
+
</Callout>
|
|
26
|
+
|
|
27
|
+
## Why migrate to the Workflow SDK
|
|
28
|
+
|
|
29
|
+
- Orchestration code is TypeScript, not JSON ASL. Transitions are `await`, branches are `if`/`switch`, and parallelism is `Promise.all`.
|
|
30
|
+
- Streaming is built in. Write durable progress from steps with `getWritable()` and named streams. No DynamoDB or SNS glue to surface status to clients.
|
|
31
|
+
- Infrastructure lives in one deployment. No separate state machine, per-task Lambda, IAM role wiring, or callback SQS queues.
|
|
32
|
+
- Error handling is TypeScript-native: step-level retries, `RetryableError`, and `FatalError` replace per-state Retry/Catch blocks.
|
|
33
|
+
- The `npx workflow` CLI and `npx workflow web` observability UI ship out of the box.
|
|
34
|
+
- AI/agent helpers — `@workflow/ai` for AI-SDK integration and the Claude migration skill — are available as separate installs.
|
|
35
|
+
|
|
36
|
+
## Before you migrate
|
|
37
|
+
|
|
38
|
+
This guide assumes **Standard** workflows. Express workflows have different semantics (at-least-once, 5-minute max duration, no execution history) and may need a different target — consider keeping them on Step Functions, moving them to a queue consumer, or ensuring your steps are idempotent before replaying the pattern here.
|
|
39
|
+
|
|
40
|
+
## What changes when you leave Step Functions?
|
|
41
|
+
|
|
42
|
+
AWS Step Functions defines workflows as JSON state machines using Amazon States Language (ASL). Each state (Task, Choice, Wait, Parallel, Map) is a node in a declarative graph. Lambda functions handle tasks, Retry/Catch blocks configure per-state error handling, and `.waitForTaskToken` manages callbacks.
|
|
43
|
+
|
|
44
|
+
The Workflow SDK replaces that JSON DSL with TypeScript. `"use workflow"` functions orchestrate `"use step"` functions in the same file. Branching is `if`/`else`. Waiting is `sleep()`. Parallelism is `Promise.all()`. Retries move down to the step level.
|
|
45
|
+
|
|
46
|
+
The migration replaces declarative configuration with idiomatic TypeScript and collapses the orchestrator and compute split. Business logic stays the same.
|
|
47
|
+
|
|
48
|
+
## Concept mapping
|
|
49
|
+
|
|
50
|
+
| AWS Step Functions | Workflow SDK | Migration note |
|
|
51
|
+
| --- | --- | --- |
|
|
52
|
+
| State machine (ASL JSON) | `"use workflow"` function | The workflow function is the state machine. |
|
|
53
|
+
| Task state / Lambda | `"use step"` function | Side effects go in steps. No separate Lambda. |
|
|
54
|
+
| Choice state | `if` / `else` / `switch` | Native TypeScript control flow. |
|
|
55
|
+
| Wait state | `sleep()` | Import `sleep` from `workflow`. |
|
|
56
|
+
| Parallel state | `Promise.all()` | Standard concurrency primitives. |
|
|
57
|
+
| Map state | Inline sequential → `for` loop; bounded parallel (`MaxConcurrency: N`) → batched `Promise.all` or a concurrency limiter like `p-limit`; Distributed Map / large fan-out → step-wrapped `start()` per item, then step-wrapped `getRun()` to collect. | Match the concurrency mode of the original Map. |
|
|
58
|
+
| Retry / Catch | Step retries, `RetryableError`, `FatalError` | Retry logic moves to step boundaries. |
|
|
59
|
+
| `Catch` to a compensation state | `try`/`catch` in the workflow function, calling compensation steps in reverse order (push/pop a rollback stack) | See [`/docs/foundations/errors-and-retries`](/docs/foundations/errors-and-retries) for the SAGA pattern. |
|
|
60
|
+
| `.waitForTaskToken` | `createHook()` or `createWebhook()` | Hooks for typed signals; webhooks for HTTP. |
|
|
61
|
+
| Child state machine (`StartExecution`) | `"use step"` around `start()` / `getRun()` | Return the `Run` object, await its result from another step. |
|
|
62
|
+
| Execution event history | Workflow event log | Same durable replay model. |
|
|
63
|
+
| Progress via DynamoDB / SNS for client polling | `getWritable()` + named streams | Stream durable updates; clients read from the stream. |
|
|
64
|
+
|
|
65
|
+
<Callout type="info">
|
|
66
|
+
`.waitForTaskToken` becomes `createHook()` or `createWebhook()`. Choice states become `if`/`else`. Map states become `Promise.all()`. Retry policies move from per-state configuration to step-level defaults.
|
|
67
|
+
</Callout>
|
|
68
|
+
|
|
69
|
+
## Translate your first workflow
|
|
70
|
+
|
|
71
|
+
Start with a single Task state. In ASL, even "call one Lambda" requires a state machine shell:
|
|
72
|
+
|
|
73
|
+
```json title="stateMachine.asl.json (Step Functions)"
|
|
74
|
+
"LoadOrder": {
|
|
75
|
+
"Type": "Task",
|
|
76
|
+
"Resource": "arn:aws:states:::lambda:invoke",
|
|
77
|
+
"Parameters": { "FunctionName": "loadOrder", "Payload.$": "$" },
|
|
78
|
+
"End": true
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
<Callout type="info">
|
|
83
|
+
Examples use JSONPath mode. If your state machine sets `QueryLanguage: 'JSONata'`, the shape of `Arguments`/`Output` fields differs but the TypeScript translation is identical.
|
|
84
|
+
</Callout>
|
|
85
|
+
|
|
86
|
+
```typescript title="workflow/workflows/order.ts (Workflow SDK)"
|
|
87
|
+
export async function processOrder(orderId: string) {
|
|
88
|
+
'use workflow'; // [!code highlight]
|
|
89
|
+
return await loadOrder(orderId);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function loadOrder(orderId: string) {
|
|
93
|
+
'use step'; // [!code highlight]
|
|
94
|
+
const res = await fetch(`https://example.com/api/orders/${orderId}`);
|
|
95
|
+
return res.json() as Promise<{ id: string }>;
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
What changed: the ASL state machine and its Lambda collapse into two directive-tagged functions in one file.
|
|
100
|
+
|
|
101
|
+
### Adding a second step
|
|
102
|
+
|
|
103
|
+
In ASL, a second Task means a new state and a `"Next"` transition. In the Workflow SDK, it's another `await`:
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
export async function processOrder(orderId: string) {
|
|
107
|
+
'use workflow';
|
|
108
|
+
const order = await loadOrder(orderId);
|
|
109
|
+
await reserveInventory(order.id); // [!code highlight]
|
|
110
|
+
return { orderId: order.id, status: 'reserved' };
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`await` replaces `"Next"`. Each new step is a new function with `"use step"`; no additional deployment. The second version also reshapes the return value; the workflow return type can be anything serializable.
|
|
115
|
+
|
|
116
|
+
### Starting from an API route
|
|
117
|
+
|
|
118
|
+
Step Functions starts a run via `StartExecution` (AWS SDK or API Gateway integration). The Workflow SDK starts a run with `start()` from a route handler:
|
|
119
|
+
|
|
120
|
+
```typescript title="app/api/orders/route.ts"
|
|
121
|
+
import { start } from 'workflow/api';
|
|
122
|
+
import { processOrder } from '@/workflows/order';
|
|
123
|
+
|
|
124
|
+
export async function POST(request: Request) {
|
|
125
|
+
const { orderId } = (await request.json()) as { orderId: string };
|
|
126
|
+
const run = await start(processOrder, [orderId]); // [!code highlight]
|
|
127
|
+
return Response.json({ runId: run.runId });
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Waiting for a fixed duration
|
|
132
|
+
|
|
133
|
+
A `Wait` state becomes `sleep()`:
|
|
134
|
+
|
|
135
|
+
```json title="stateMachine.asl.json (Step Functions)"
|
|
136
|
+
{ "Type": "Wait", "Seconds": 60, "Next": "Next" }
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
{/* @skip-typecheck: one-line snippet fragment */}
|
|
140
|
+
|
|
141
|
+
```typescript title="workflow/workflows/order.ts (Workflow SDK)"
|
|
142
|
+
await sleep('1m');
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Wait for an external signal
|
|
146
|
+
|
|
147
|
+
The minimal ASL for a callback is a Task with `.waitForTaskToken`:
|
|
148
|
+
|
|
149
|
+
```json title="approval.asl.json (Step Functions)"
|
|
150
|
+
"WaitForApproval": {
|
|
151
|
+
"Type": "Task",
|
|
152
|
+
"Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
|
|
153
|
+
"Parameters": {
|
|
154
|
+
"QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/approvals",
|
|
155
|
+
"MessageBody": {
|
|
156
|
+
"refundId.$": "$.refundId",
|
|
157
|
+
"TaskToken.$": "$$.Task.Token"
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
"End": true
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
```typescript title="workflow/workflows/refund.ts (Workflow SDK)"
|
|
165
|
+
import { createHook } from 'workflow';
|
|
166
|
+
|
|
167
|
+
export async function refundWorkflow(refundId: string) {
|
|
168
|
+
'use workflow';
|
|
169
|
+
using approval = createHook<{ approved: boolean }>({ // [!code highlight]
|
|
170
|
+
token: `refund:${refundId}:approval`,
|
|
171
|
+
});
|
|
172
|
+
return await approval;
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
What changed: no SQS queue, no task token, no callback Lambda. The hook suspends the workflow durably until it is resumed.
|
|
177
|
+
|
|
178
|
+
### Resuming the hook
|
|
179
|
+
|
|
180
|
+
Step Functions resumes by calling `SendTaskSuccess` with the task token. The Workflow SDK resumes by calling `resumeHook` with the hook's token:
|
|
181
|
+
|
|
182
|
+
```typescript title="app/api/refunds/[refundId]/approve/route.ts"
|
|
183
|
+
import { resumeHook } from 'workflow/api';
|
|
184
|
+
|
|
185
|
+
export async function POST(req: Request, { params }: { params: Promise<{ refundId: string }> }) {
|
|
186
|
+
const { refundId } = await params;
|
|
187
|
+
const { approved } = (await req.json()) as { approved: boolean };
|
|
188
|
+
await resumeHook(`refund:${refundId}:approval`, { approved }); // [!code highlight]
|
|
189
|
+
return Response.json({ ok: true });
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### Branching on the result
|
|
194
|
+
|
|
195
|
+
In ASL, branching after the wait requires a Choice state. In TypeScript, it's just `if`/`else`:
|
|
196
|
+
|
|
197
|
+
```json title="approval.asl.json (Step Functions)"
|
|
198
|
+
"CheckApproval": {
|
|
199
|
+
"Type": "Choice",
|
|
200
|
+
"Choices": [
|
|
201
|
+
{ "Variable": "$.approved", "BooleanEquals": true, "Next": "Approved" }
|
|
202
|
+
],
|
|
203
|
+
"Default": "Rejected"
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
{/* @skip-typecheck: continuation snippet */}
|
|
208
|
+
```typescript title="workflow/workflows/refund.ts (Workflow SDK)"
|
|
209
|
+
const { approved } = await approval;
|
|
210
|
+
if (approved) return { refundId, status: 'approved' }; // [!code highlight]
|
|
211
|
+
return { refundId, status: 'rejected' };
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## Spawn a child workflow
|
|
215
|
+
|
|
216
|
+
In ASL, a parent machine calls `StartExecution` (usually via `.sync` or `.waitForTaskToken`) to launch a child. In the Workflow SDK, `start()` and `getRun()` are runtime APIs, so wrap them in `"use step"` functions. Returning the `Run` object from the spawn step lets workflow observability deep-link to the child run.
|
|
217
|
+
|
|
218
|
+
### Parent starts a child
|
|
219
|
+
|
|
220
|
+
```typescript title="workflow/workflows/parent.ts"
|
|
221
|
+
import { start } from 'workflow/api';
|
|
222
|
+
|
|
223
|
+
async function spawnChild(item: string) {
|
|
224
|
+
'use step'; // [!code highlight]
|
|
225
|
+
return await start(childWorkflow, [item]);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function parentWorkflow(item: string) {
|
|
229
|
+
'use workflow';
|
|
230
|
+
const run = await spawnChild(item);
|
|
231
|
+
return { childRunId: run.runId };
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Awaiting the child's result
|
|
236
|
+
|
|
237
|
+
Add a second step that wraps `getRun()` and awaits `returnValue`:
|
|
238
|
+
|
|
239
|
+
```typescript
|
|
240
|
+
import { getRun } from 'workflow/api';
|
|
241
|
+
|
|
242
|
+
async function collectResult(runId: string) {
|
|
243
|
+
'use step'; // [!code highlight]
|
|
244
|
+
const run = getRun(runId);
|
|
245
|
+
return (await run.returnValue) as { item: string; result: string };
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Then in the workflow: `const result = await collectResult(run.runId);`. The child workflow itself (`childWorkflow`) is defined elsewhere with `"use workflow"`.
|
|
250
|
+
|
|
251
|
+
## What you stop operating
|
|
252
|
+
|
|
253
|
+
Moving off Step Functions removes these surfaces from the application:
|
|
254
|
+
|
|
255
|
+
- ASL state machine JSON and its reference syntax.
|
|
256
|
+
- Per-task Lambda functions, their IAM roles, and CloudFormation/CDK wiring.
|
|
257
|
+
- Task-token delivery infrastructure (SQS queues, callback Lambdas).
|
|
258
|
+
- Separate progress channels (DynamoDB, SNS) for client-visible updates.
|
|
259
|
+
- Remove CloudWatch and X-Ray wiring that was specific to orchestrator state transitions. Keep (or re-wire) any application-level CloudWatch alarms, log retention policies, or X-Ray propagation that the rest of your AWS footprint still depends on. Workflow SDK exports OTEL traces, so existing OTEL-compatible backends can continue to ingest them.
|
|
260
|
+
|
|
261
|
+
Workflow and step functions live in the same deployment as the application. State transitions are ordinary control flow (`await`, `if`, `Promise.all`, `for`). Progress streaming, retries, and observability are built in.
|
|
262
|
+
|
|
263
|
+
### What you take on
|
|
264
|
+
|
|
265
|
+
Steps that previously invoked AWS services via optimized integrations (EventBridge, DynamoDB, Bedrock, ECS.RunTask.sync, etc.) become ordinary SDK calls inside `'use step'` functions. Credentials and retries move into the step, and `.sync`-style waits for long-running jobs become explicit polling loops or hook-based callbacks.
|
|
266
|
+
|
|
267
|
+
## Step-by-step first migration
|
|
268
|
+
|
|
269
|
+
Pick one state machine and migrate it end-to-end before touching the rest. The steps below describe the smallest viable path.
|
|
270
|
+
|
|
271
|
+
### Step 1: Install the Workflow SDK
|
|
272
|
+
|
|
273
|
+
Add the `workflow` runtime package.
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
pnpm add workflow
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Step 2: Rewrite the state machine as a `"use workflow"` function
|
|
280
|
+
|
|
281
|
+
Transitions become `await` calls. Control flow (`Choice`, `Wait`, `Parallel`, `Map`) becomes `if`/`switch`, `sleep`, `Promise.all`, and loops.
|
|
282
|
+
|
|
283
|
+
```ts title="workflows/order.ts"
|
|
284
|
+
export async function processOrder(orderId: string) {
|
|
285
|
+
"use workflow"; // [!code highlight]
|
|
286
|
+
const order = await loadOrder(orderId);
|
|
287
|
+
if (order.total > 1000) await reviewManually(order);
|
|
288
|
+
await chargePayment(order);
|
|
289
|
+
}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
### Step 3: Move each Lambda into a step function
|
|
293
|
+
|
|
294
|
+
Inline the Lambda body into a function with `"use step"` on the first line. Step functions keep full Node.js access, so existing SDK calls work unchanged.
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
async function loadOrder(id: string) {
|
|
298
|
+
"use step"; // [!code highlight]
|
|
299
|
+
return fetch(`/api/orders/${id}`).then((r) => r.json());
|
|
300
|
+
}
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
### Step 4: Replace `.waitForTaskToken` with a hook
|
|
304
|
+
|
|
305
|
+
Swap the task-token callback Lambda for `createHook()`. Callers `resumeHook(token, payload)` instead of `SendTaskSuccess`.
|
|
306
|
+
|
|
307
|
+
Move Retry/Catch off per-state configuration and onto step boundaries. Set `maxRetries` as a function property; throw `RetryableError` or `FatalError` to control retry behavior:
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
async function chargePayment(orderId: string) {
|
|
311
|
+
"use step";
|
|
312
|
+
// ...
|
|
313
|
+
}
|
|
314
|
+
chargePayment.maxRetries = 5;
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
See [`/docs/foundations/errors-and-retries`](/docs/foundations/errors-and-retries) for the full retry and SAGA compensation patterns.
|
|
318
|
+
|
|
319
|
+
### Step 5: Start runs from an API route
|
|
320
|
+
|
|
321
|
+
Delete the `StartExecution` call and IAM wiring. Launch runs directly from a route handler:
|
|
322
|
+
|
|
323
|
+
```ts title="app/api/orders/route.ts"
|
|
324
|
+
import { start } from "workflow/api";
|
|
325
|
+
import { processOrder } from "@/workflows/order";
|
|
326
|
+
|
|
327
|
+
export async function POST(req: Request) {
|
|
328
|
+
const { orderId } = await req.json();
|
|
329
|
+
const run = await start(processOrder, [orderId]);
|
|
330
|
+
return Response.json({ runId: run.runId });
|
|
331
|
+
}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
### Step 6: Retire the Step Functions infrastructure
|
|
335
|
+
|
|
336
|
+
Delete the ASL JSON, per-task Lambda deployments, IAM roles, and callback queues. Remove CloudWatch and X-Ray wiring that was specific to orchestrator state transitions — keep alarms, log retention, and traces for resources you still depend on. Verify the run in `npx workflow web` before shipping.
|
|
337
|
+
|
|
338
|
+
## Features without a 1:1 equivalent
|
|
339
|
+
|
|
340
|
+
- **Express workflows.** At-least-once semantics and 5-minute duration make them a poor fit for the SDK's durable replay model. Consider keeping them on Step Functions or migrating to a queue consumer.
|
|
341
|
+
- **Distributed Map state.** Up to 10,000 concurrent child executions with S3 item sources has no 1:1 analog; fan out with step-wrapped `start()` per item, then `Promise.all` with `p-limit` to bound concurrency.
|
|
342
|
+
- **Optimized AWS service integrations (`arn:aws:states:::dynamodb:*`, `eventbridge:*`, `bedrock:*`, `ecs:runTask.sync`, etc.).** These become regular SDK calls inside `'use step'` functions — credentials, retries, and polling move into the step.
|
|
343
|
+
- **Per-state IAM roles.** ASL lets each state run under its own IAM role. In the SDK, all steps share the deployment's credentials; scope secrets and roles at deployment time.
|
|
344
|
+
- **CloudWatch alarms / X-Ray cross-service traces / CloudWatch Logs retention.** The SDK event log + observability UI replaces orchestrator state transitions, not AWS-wide observability. Keep alarms and traces for other resources.
|
|
345
|
+
- **`JSONata` `QueryLanguage` mode.** Valid at the source; the TS translation is identical regardless of mode.
|
|
346
|
+
|
|
347
|
+
## Quick-start checklist
|
|
348
|
+
|
|
349
|
+
- Replace the ASL state machine with a single `"use workflow"` function. Transitions become `await` calls.
|
|
350
|
+
- Convert each Task / Lambda into a `"use step"` function in the same file.
|
|
351
|
+
- Replace Choice states with `if`/`else`/`switch`.
|
|
352
|
+
- Replace Wait states with `sleep()` from `workflow`.
|
|
353
|
+
- Replace Parallel states with `Promise.all()`.
|
|
354
|
+
- Replace Map states based on their concurrency mode: inline sequential → `for` loop; bounded parallel (`MaxConcurrency: N`) → batched `Promise.all` or a concurrency limiter like `p-limit`; Distributed Map / large fan-out → step-wrapped `start()` per item, then step-wrapped `getRun()` to collect.
|
|
355
|
+
- Replace `StartExecution` child machines with `"use step"` wrappers around `start()` and `getRun()`.
|
|
356
|
+
- Replace `.waitForTaskToken` with `createHook()` (internal callers) or `createWebhook()` (HTTP callers).
|
|
357
|
+
- Move Retry/Catch to step boundaries using `maxRetries`, `RetryableError`, and `FatalError`.
|
|
358
|
+
- Use `getStepMetadata().stepId` as the idempotency key for external side effects.
|
|
359
|
+
- Stream progress from steps with `getWritable()` instead of polling DynamoDB or SNS.
|
|
360
|
+
- Deploy and verify runs end-to-end with built-in observability.
|
|
361
|
+
|
|
362
|
+
---
|
|
363
|
+
*Verified against `workflow@5.0.0-beta.1` and the AWS Step Functions Amazon States Language spec on 2026-04-16.*
|