workflow 5.0.0-beta.3 → 5.0.0-beta.31
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 +1 -1
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +12 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/internal/builtins.d.ts +17 -0
- package/dist/internal/builtins.d.ts.map +1 -1
- package/dist/internal/builtins.js +65 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -2
- package/docs/ai/chat-session-modeling.mdx +7 -3
- package/docs/ai/defining-tools.mdx +2 -2
- package/docs/ai/index.mdx +28 -23
- package/docs/ai/message-queueing.mdx +10 -10
- package/docs/ai/resumable-streams.mdx +9 -1
- 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/fetch.mdx +5 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow/set-attributes.mdx +65 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
- package/docs/api-reference/workflow-ai/index.mdx +2 -2
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +44 -1
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
- package/docs/api-reference/workflow-api/get-run.mdx +25 -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 +60 -0
- package/docs/api-reference/workflow-nuxt/index.mdx +48 -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 +4 -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 +8 -1
- package/docs/changelog/resilient-start.mdx +31 -283
- package/docs/changelog/step-message-ownership.mdx +360 -0
- package/docs/changelog/turbo-mode.md +87 -0
- package/docs/configuration/build-and-diagnostics.mdx +51 -0
- package/docs/configuration/cli-and-web-ui.mdx +154 -0
- package/docs/configuration/framework-options.mdx +165 -0
- package/docs/configuration/index.mdx +32 -0
- package/docs/configuration/meta.json +12 -0
- package/docs/configuration/runtime-tuning.mdx +156 -0
- package/docs/configuration/worlds.mdx +228 -0
- package/docs/cookbook/advanced/child-workflows.mdx +199 -256
- package/docs/cookbook/advanced/meta.json +1 -1
- package/docs/cookbook/advanced/publishing-libraries.mdx +13 -12
- package/docs/cookbook/advanced/serializable-steps.mdx +8 -4
- package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +31 -76
- package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -143
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +7 -3
- package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
- package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
- package/docs/cookbook/common-patterns/saga.mdx +2 -2
- package/docs/cookbook/common-patterns/scheduling.mdx +8 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +2 -1
- package/docs/cookbook/common-patterns/workflow-composition.mdx +15 -16
- package/docs/cookbook/index.mdx +3 -3
- package/docs/cookbook/integrations/ai-sdk.mdx +60 -28
- package/docs/cookbook/integrations/chat-sdk.mdx +13 -0
- package/docs/cookbook/integrations/sandbox.mdx +13 -0
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/index.mdx +1 -0
- package/docs/deploying/world/local-world.mdx +23 -6
- package/docs/deploying/world/postgres-world.mdx +79 -13
- package/docs/deploying/world/vercel-world.mdx +47 -12
- 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 +1 -35
- 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 +1 -23
- package/docs/foundations/meta.json +3 -1
- package/docs/foundations/serialization.mdx +77 -41
- package/docs/foundations/starting-workflows.mdx +5 -1
- 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/meta.json +1 -1
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +7 -12
- package/docs/migration-guides/migrating-from-inngest.mdx +7 -17
- package/docs/migration-guides/migrating-from-temporal.mdx +6 -11
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +8 -17
- package/docs/observability/attributes.mdx +81 -0
- package/docs/observability/index.mdx +18 -1
- package/docs/observability/meta.json +1 -1
- package/docs/observability/tracing.mdx +119 -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/distributed-abort-controller.mdx +0 -318
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Observability Utilities
|
|
3
|
-
description: Hydrate step I/O, parse display names, and decrypt workflow data using workflow/observability.
|
|
4
|
-
type: reference
|
|
5
|
-
summary: "Functions: hydrateResourceIO(), parseStepName(), parseWorkflowName(), parseClassName(), getEncryptionKeyForRun(), hydrateResourceIOWithKey()."
|
|
6
|
-
prerequisites:
|
|
7
|
-
- /docs/api-reference/workflow-api/get-world
|
|
8
|
-
related:
|
|
9
|
-
- /docs/api-reference/workflow-api/world/storage
|
|
10
|
-
keywords:
|
|
11
|
-
- workflow/observability
|
|
12
|
-
- hydrateResourceIO
|
|
13
|
-
- observabilityRevivers
|
|
14
|
-
- parseStepName
|
|
15
|
-
- parseWorkflowName
|
|
16
|
-
- parseClassName
|
|
17
|
-
- getEncryptionKeyForRun
|
|
18
|
-
- hydrateResourceIOWithKey
|
|
19
|
-
- data hydration
|
|
20
|
-
- devalue deserialization
|
|
21
|
-
- encryption decryption
|
|
22
|
-
- display name parsing
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
The `workflow/observability` module provides utilities for working with workflow data in observability and debugging tools. It includes functions to hydrate serialized step I/O, parse machine-readable names into display-friendly formats, and decrypt encrypted workflow data.
|
|
26
|
-
|
|
27
|
-
## Import
|
|
28
|
-
|
|
29
|
-
```typescript lineNumbers
|
|
30
|
-
import { // [!code highlight]
|
|
31
|
-
hydrateResourceIO, // [!code highlight]
|
|
32
|
-
observabilityRevivers, // [!code highlight]
|
|
33
|
-
parseStepName, // [!code highlight]
|
|
34
|
-
parseWorkflowName, // [!code highlight]
|
|
35
|
-
parseClassName, // [!code highlight]
|
|
36
|
-
} from "workflow/observability"; // [!code highlight]
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
## Data Hydration
|
|
40
|
-
|
|
41
|
-
### hydrateResourceIO()
|
|
42
|
-
|
|
43
|
-
Deserialize step or run data that was serialized using the [devalue](https://github.com/Rich-Harris/devalue) format. Required to display step input/output in your UI.
|
|
44
|
-
|
|
45
|
-
```typescript lineNumbers
|
|
46
|
-
import { hydrateResourceIO, observabilityRevivers } from "workflow/observability"; // [!code highlight]
|
|
47
|
-
|
|
48
|
-
const step = await world.steps.get(runId, stepId);
|
|
49
|
-
const hydrated = hydrateResourceIO(step, observabilityRevivers); // [!code highlight]
|
|
50
|
-
console.log(hydrated.input, hydrated.output);
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
**Parameters:**
|
|
54
|
-
|
|
55
|
-
| Parameter | Type | Description |
|
|
56
|
-
|-----------|------|-------------|
|
|
57
|
-
| `resource` | `Step \| WorkflowRun` | The step or run with serialized data |
|
|
58
|
-
| `revivers` | `Revivers` | Reviver functions for deserialization. Use `observabilityRevivers` for standard use. |
|
|
59
|
-
|
|
60
|
-
**Returns:** The resource with hydrated `input` and `output` fields.
|
|
61
|
-
|
|
62
|
-
### observabilityRevivers
|
|
63
|
-
|
|
64
|
-
A set of reviver functions that handle standard workflow serialization types (Date, Map, Set, Error, etc.).
|
|
65
|
-
|
|
66
|
-
## Name Parsing
|
|
67
|
-
|
|
68
|
-
Workflow and step names are stored as machine-readable identifiers. These utilities extract display-friendly names. All return `{ shortName: string, moduleSpecifier: string } | null`.
|
|
69
|
-
|
|
70
|
-
### parseStepName()
|
|
71
|
-
|
|
72
|
-
```typescript lineNumbers
|
|
73
|
-
import { parseStepName } from "workflow/observability"; // [!code highlight]
|
|
74
|
-
|
|
75
|
-
const parsed = parseStepName("step//./src/workflows/order//processPayment"); // [!code highlight]
|
|
76
|
-
// parsed?.shortName → "processPayment"
|
|
77
|
-
// parsed?.moduleSpecifier → "./src/workflows/order"
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
### parseWorkflowName()
|
|
81
|
-
|
|
82
|
-
```typescript lineNumbers
|
|
83
|
-
import { parseWorkflowName } from "workflow/observability"; // [!code highlight]
|
|
84
|
-
|
|
85
|
-
const parsed = parseWorkflowName("workflow//./src/workflows/order//processOrder"); // [!code highlight]
|
|
86
|
-
// parsed?.shortName → "processOrder"
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
### parseClassName()
|
|
90
|
-
|
|
91
|
-
```typescript lineNumbers
|
|
92
|
-
import { parseClassName } from "workflow/observability"; // [!code highlight]
|
|
93
|
-
|
|
94
|
-
const parsed = parseClassName("class//./src/models//User"); // [!code highlight]
|
|
95
|
-
// parsed?.shortName → "User"
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
## Encryption
|
|
99
|
-
|
|
100
|
-
For workflows with encrypted step data, decrypt before hydrating.
|
|
101
|
-
|
|
102
|
-
### getEncryptionKeyForRun()
|
|
103
|
-
|
|
104
|
-
Retrieve the encryption key used for a specific workflow run.
|
|
105
|
-
|
|
106
|
-
{/* @expect-error:2305 */}
|
|
107
|
-
```typescript lineNumbers
|
|
108
|
-
import { getEncryptionKeyForRun } from "workflow/observability"; // [!code highlight]
|
|
109
|
-
|
|
110
|
-
const key = await getEncryptionKeyForRun(runId); // [!code highlight]
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
**Parameters:**
|
|
114
|
-
|
|
115
|
-
| Parameter | Type | Description |
|
|
116
|
-
|-----------|------|-------------|
|
|
117
|
-
| `runId` | `string` | The workflow run ID |
|
|
118
|
-
|
|
119
|
-
**Returns:** Encryption key for the run
|
|
120
|
-
|
|
121
|
-
### hydrateResourceIOWithKey()
|
|
122
|
-
|
|
123
|
-
Hydrate step or run data using a decryption key. Use this instead of `hydrateResourceIO()` when data is encrypted.
|
|
124
|
-
|
|
125
|
-
{/* @expect-error:2305,2724 */}
|
|
126
|
-
```typescript lineNumbers
|
|
127
|
-
import { getEncryptionKeyForRun, hydrateResourceIOWithKey } from "workflow/observability"; // [!code highlight]
|
|
128
|
-
|
|
129
|
-
const key = await getEncryptionKeyForRun(runId); // [!code highlight]
|
|
130
|
-
const hydrated = hydrateResourceIOWithKey(step, key); // [!code highlight]
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
**Parameters:**
|
|
134
|
-
|
|
135
|
-
| Parameter | Type | Description |
|
|
136
|
-
|-----------|------|-------------|
|
|
137
|
-
| `resource` | `Step \| WorkflowRun` | The step or run with encrypted serialized data |
|
|
138
|
-
| `key` | `EncryptionKey` | The encryption key from `getEncryptionKeyForRun()` |
|
|
139
|
-
|
|
140
|
-
**Returns:** The resource with decrypted and hydrated `input` and `output` fields.
|
|
141
|
-
|
|
142
|
-
## Examples
|
|
143
|
-
|
|
144
|
-
### Parse Display Names for a Run's Steps
|
|
145
|
-
|
|
146
|
-
```typescript lineNumbers
|
|
147
|
-
import { getWorld } from "workflow/runtime";
|
|
148
|
-
import { parseStepName, parseWorkflowName } from "workflow/observability"; // [!code highlight]
|
|
149
|
-
|
|
150
|
-
const world = await getWorld();
|
|
151
|
-
const run = await world.runs.get(runId, { resolveData: "none" });
|
|
152
|
-
console.log("Workflow:", parseWorkflowName(run.workflowName)?.shortName); // [!code highlight]
|
|
153
|
-
|
|
154
|
-
const steps = await world.steps.list({ runId, resolveData: "none" });
|
|
155
|
-
for (const step of steps.data) {
|
|
156
|
-
const parsed = parseStepName(step.stepName); // [!code highlight]
|
|
157
|
-
console.log(` ${parsed?.shortName}: ${step.status}`); // [!code highlight]
|
|
158
|
-
}
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
## Related
|
|
162
|
-
|
|
163
|
-
- [Storage](/docs/api-reference/workflow-api/world/storage) — Query runs, steps, hooks, and events
|
|
164
|
-
- [Serialization](/docs/foundations/serialization) — How workflow data is serialized
|
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Distributed Abort Controller
|
|
3
|
-
description: A distributed AbortController that uses durable workflows for cross-process cancellation signaling.
|
|
4
|
-
type: guide
|
|
5
|
-
summary: Build a distributed abort controller that uses workflow streams and hooks to propagate cancellation signals across process boundaries.
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
Use this pattern when you need an `AbortController`-like interface that works across distributed systems. The controller uses a durable workflow to coordinate cancellation — calling `.abort()` on one machine triggers the `.signal` on any other machine.
|
|
9
|
-
|
|
10
|
-
## When to use this
|
|
11
|
-
|
|
12
|
-
- **Cross-process cancellation** — Cancel a long-running operation from a different server, worker, or edge function
|
|
13
|
-
- **Durable cancellation** — The abort signal persists even if the process that created it crashes
|
|
14
|
-
- **UI stop buttons** — Let users cancel operations running on the server from the browser
|
|
15
|
-
- **Timeout coordination** — The built-in TTL auto-expires stale controllers
|
|
16
|
-
|
|
17
|
-
## Pattern
|
|
18
|
-
|
|
19
|
-
The `DistributedAbortController` class encapsulates a workflow that:
|
|
20
|
-
1. Accepts a user-provided unique ID (like a chat ID or task ID)
|
|
21
|
-
2. Creates or reconnects to an existing workflow using that ID
|
|
22
|
-
3. Waits for a hook signal OR TTL expiration
|
|
23
|
-
4. Writes a cancellation message to the run's stream when triggered
|
|
24
|
-
|
|
25
|
-
### Core Implementation
|
|
26
|
-
|
|
27
|
-
```typescript lineNumbers
|
|
28
|
-
import { defineHook, getWritable, sleep } from "workflow";
|
|
29
|
-
import { start, getRun, getHookByToken } from "workflow/api";
|
|
30
|
-
|
|
31
|
-
// Default TTL: 24 hours
|
|
32
|
-
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
33
|
-
// Default grace period: 1 hour (keeps hook alive after abort for late subscribers)
|
|
34
|
-
const DEFAULT_GRACE_MS = 60 * 60 * 1000;
|
|
35
|
-
|
|
36
|
-
// Hook to trigger the abort signal
|
|
37
|
-
export const abortHook = defineHook<{ reason?: string }>();
|
|
38
|
-
|
|
39
|
-
// The abort message written to the stream
|
|
40
|
-
export type AbortMessage = {
|
|
41
|
-
type: "abort";
|
|
42
|
-
reason?: string;
|
|
43
|
-
expired?: boolean;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
// Helper to create a consistent hook token from the user ID
|
|
47
|
-
function getAbortToken(id: string): string {
|
|
48
|
-
return `abort:${id}`;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Step function that writes the abort message to the stream
|
|
52
|
-
async function writeAbortSignal(reason?: string, expired?: boolean) {
|
|
53
|
-
"use step";
|
|
54
|
-
|
|
55
|
-
const writable = getWritable<AbortMessage>();
|
|
56
|
-
const writer = writable.getWriter();
|
|
57
|
-
try {
|
|
58
|
-
await writer.write({ type: "abort", reason, expired });
|
|
59
|
-
} finally {
|
|
60
|
-
writer.releaseLock();
|
|
61
|
-
}
|
|
62
|
-
await writable.close();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Workflow that waits for abort or TTL expiration
|
|
66
|
-
export async function abortControllerWorkflow(
|
|
67
|
-
id: string,
|
|
68
|
-
ttlMs: number,
|
|
69
|
-
graceMs: number
|
|
70
|
-
) {
|
|
71
|
-
"use workflow";
|
|
72
|
-
|
|
73
|
-
const startTime = Date.now();
|
|
74
|
-
const hook = abortHook.create({ token: getAbortToken(id) });
|
|
75
|
-
|
|
76
|
-
// Race: manual abort OR TTL expiration // [!code highlight]
|
|
77
|
-
const result = await Promise.race([
|
|
78
|
-
hook.then((payload) => ({
|
|
79
|
-
reason: payload.reason,
|
|
80
|
-
expired: false,
|
|
81
|
-
})),
|
|
82
|
-
sleep(`${ttlMs}ms`).then(() => ({
|
|
83
|
-
reason: "Controller expired",
|
|
84
|
-
expired: true,
|
|
85
|
-
})),
|
|
86
|
-
]);
|
|
87
|
-
|
|
88
|
-
await writeAbortSignal(result.reason, result.expired);
|
|
89
|
-
|
|
90
|
-
// Only sleep through grace period on TTL expiration (keeps hook alive for late subscribers). // [!code highlight]
|
|
91
|
-
// Manual aborts complete immediately.
|
|
92
|
-
if (result.expired) {
|
|
93
|
-
const elapsed = Date.now() - startTime;
|
|
94
|
-
const remainingTime = graceMs - (elapsed - ttlMs);
|
|
95
|
-
if (remainingTime > 0) {
|
|
96
|
-
await sleep(`${remainingTime}ms`); // [!code highlight]
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return { aborted: true, reason: result.reason, expired: result.expired };
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* A distributed abort controller that works across process boundaries.
|
|
105
|
-
* Uses a semantically meaningful ID (like a chat ID or task ID) to coordinate.
|
|
106
|
-
*/
|
|
107
|
-
export class DistributedAbortController {
|
|
108
|
-
private id: string;
|
|
109
|
-
readonly runId: string;
|
|
110
|
-
|
|
111
|
-
private constructor(id: string, runId: string) {
|
|
112
|
-
this.id = id;
|
|
113
|
-
this.runId = runId;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Creates or reconnects to a distributed abort controller.
|
|
118
|
-
* If a controller with this ID already exists, reconnects to it.
|
|
119
|
-
* Otherwise, starts a new workflow.
|
|
120
|
-
*
|
|
121
|
-
* @param id - A unique, semantically meaningful ID (e.g., "chat:123")
|
|
122
|
-
* @param options.ttlMs - Time-to-live in ms (default: 24 hours)
|
|
123
|
-
* @param options.graceMs - Grace period after abort (default: 1 hour)
|
|
124
|
-
*/
|
|
125
|
-
static async create( // [!code highlight]
|
|
126
|
-
id: string,
|
|
127
|
-
options: { ttlMs?: number; graceMs?: number } = {}
|
|
128
|
-
): Promise<DistributedAbortController> {
|
|
129
|
-
const { ttlMs = DEFAULT_TTL_MS, graceMs = DEFAULT_GRACE_MS } = options;
|
|
130
|
-
const token = getAbortToken(id);
|
|
131
|
-
|
|
132
|
-
// Try to find an existing run with this hook token
|
|
133
|
-
const existingHook = await getHookByToken(token).catch(() => null); // [!code highlight]
|
|
134
|
-
|
|
135
|
-
if (existingHook) {
|
|
136
|
-
// Reconnect to existing controller
|
|
137
|
-
return new DistributedAbortController(id, existingHook.runId);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// Create a new workflow
|
|
141
|
-
const run = await start(abortControllerWorkflow, [id, ttlMs, graceMs]); // [!code highlight]
|
|
142
|
-
return new DistributedAbortController(id, run.runId);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Triggers the abort signal.
|
|
147
|
-
* Idempotent: safe to call multiple times or after the workflow has completed.
|
|
148
|
-
*/
|
|
149
|
-
async abort(reason?: string): Promise<void> { // [!code highlight]
|
|
150
|
-
try {
|
|
151
|
-
await abortHook.resume(getAbortToken(this.id), { reason });
|
|
152
|
-
} catch (error) {
|
|
153
|
-
const msg = error instanceof Error ? error.message.toLowerCase() : '';
|
|
154
|
-
if (msg.includes('not found') || msg.includes('expired')) {
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
throw error;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Returns an AbortSignal that fires when abort() is called or TTL expires.
|
|
163
|
-
* The signal fires with a reason indicating what triggered it.
|
|
164
|
-
*/
|
|
165
|
-
get signal(): AbortSignal { // [!code highlight]
|
|
166
|
-
const run = getRun<{ aborted: boolean; reason?: string; expired?: boolean }>(this.runId);
|
|
167
|
-
const controller = new AbortController();
|
|
168
|
-
const readable = run.getReadable<AbortMessage>();
|
|
169
|
-
|
|
170
|
-
(async () => {
|
|
171
|
-
const reader = readable.getReader();
|
|
172
|
-
try {
|
|
173
|
-
while (true) {
|
|
174
|
-
const { done, value } = await reader.read();
|
|
175
|
-
if (done) break;
|
|
176
|
-
if (value.type === "abort") {
|
|
177
|
-
const reason = value.expired
|
|
178
|
-
? `${value.reason} (expired)`
|
|
179
|
-
: value.reason;
|
|
180
|
-
controller.abort(reason);
|
|
181
|
-
break;
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
} catch (error) {
|
|
185
|
-
if (!controller.signal.aborted) {
|
|
186
|
-
controller.abort(
|
|
187
|
-
error instanceof Error ? error.message : "Stream read failed"
|
|
188
|
-
);
|
|
189
|
-
}
|
|
190
|
-
} finally {
|
|
191
|
-
reader.releaseLock();
|
|
192
|
-
}
|
|
193
|
-
})();
|
|
194
|
-
|
|
195
|
-
return controller.signal;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
```
|
|
199
|
-
|
|
200
|
-
### Usage: Single Process
|
|
201
|
-
|
|
202
|
-
```typescript lineNumbers
|
|
203
|
-
import { DistributedAbortController } from "./distributed-abort-controller";
|
|
204
|
-
|
|
205
|
-
// Create a controller with a meaningful ID
|
|
206
|
-
const controller = await DistributedAbortController.create("chat:user-123");
|
|
207
|
-
|
|
208
|
-
// Get the signal and use it with fetch
|
|
209
|
-
const signal = controller.signal;
|
|
210
|
-
const response = await fetch("https://api.example.com/long-operation", {
|
|
211
|
-
signal,
|
|
212
|
-
});
|
|
213
|
-
|
|
214
|
-
// Later: abort the operation
|
|
215
|
-
await controller.abort("User cancelled");
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
### Usage: Cross-Process Coordination
|
|
219
|
-
|
|
220
|
-
```typescript lineNumbers
|
|
221
|
-
import { DistributedAbortController } from "./distributed-abort-controller";
|
|
222
|
-
|
|
223
|
-
// Process A: Create the controller
|
|
224
|
-
const controller = await DistributedAbortController.create("task:build-123");
|
|
225
|
-
// start long operation using controller.signal...
|
|
226
|
-
|
|
227
|
-
// Process B: Reconnect and abort (no run ID sharing needed!)
|
|
228
|
-
const sameController = await DistributedAbortController.create("task:build-123"); // [!code highlight]
|
|
229
|
-
await sameController.abort("Cancelled by admin");
|
|
230
|
-
|
|
231
|
-
// Process C: Reconnect and listen
|
|
232
|
-
const anotherRef = await DistributedAbortController.create("task:build-123");
|
|
233
|
-
anotherRef.signal.addEventListener("abort", (e) => {
|
|
234
|
-
console.log("Task was cancelled:", (e.target as AbortSignal).reason);
|
|
235
|
-
});
|
|
236
|
-
```
|
|
237
|
-
|
|
238
|
-
### Custom TTL
|
|
239
|
-
|
|
240
|
-
```typescript lineNumbers
|
|
241
|
-
import { DistributedAbortController } from "./distributed-abort-controller";
|
|
242
|
-
|
|
243
|
-
// Short-lived controller for a quick operation (5 minutes)
|
|
244
|
-
const shortLived = await DistributedAbortController.create("quick-task", {
|
|
245
|
-
ttlMs: 5 * 60 * 1000,
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
// Long-lived controller for batch jobs (7 days)
|
|
249
|
-
const longLived = await DistributedAbortController.create("batch-job", {
|
|
250
|
-
ttlMs: 7 * 24 * 60 * 60 * 1000,
|
|
251
|
-
});
|
|
252
|
-
|
|
253
|
-
// When TTL expires, the signal fires with expired reason
|
|
254
|
-
shortLived.signal.addEventListener("abort", (e) => {
|
|
255
|
-
const reason = (e.target as AbortSignal).reason;
|
|
256
|
-
if (reason?.includes("expired")) {
|
|
257
|
-
console.log("Controller expired, cleaning up...");
|
|
258
|
-
}
|
|
259
|
-
});
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
### API Route for Remote Abort
|
|
263
|
-
|
|
264
|
-
```typescript lineNumbers
|
|
265
|
-
import { DistributedAbortController } from "@/lib/distributed-abort-controller";
|
|
266
|
-
|
|
267
|
-
export async function POST(
|
|
268
|
-
request: Request,
|
|
269
|
-
{ params }: { params: Promise<{ id: string }> }
|
|
270
|
-
) {
|
|
271
|
-
const { id } = await params;
|
|
272
|
-
const { reason } = await request.json();
|
|
273
|
-
|
|
274
|
-
const controller = await DistributedAbortController.create(id);
|
|
275
|
-
await controller.abort(reason || "Cancelled via API");
|
|
276
|
-
|
|
277
|
-
return Response.json({ success: true });
|
|
278
|
-
}
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
### Client Cancel Button
|
|
282
|
-
|
|
283
|
-
```tsx lineNumbers
|
|
284
|
-
"use client";
|
|
285
|
-
|
|
286
|
-
export function CancelButton({ taskId }: { taskId: string }) {
|
|
287
|
-
const handleCancel = async () => {
|
|
288
|
-
await fetch(`/api/abort/${taskId}`, {
|
|
289
|
-
method: "POST",
|
|
290
|
-
headers: { "Content-Type": "application/json" },
|
|
291
|
-
body: JSON.stringify({ reason: "User clicked cancel" }),
|
|
292
|
-
});
|
|
293
|
-
};
|
|
294
|
-
|
|
295
|
-
return (
|
|
296
|
-
<button type="button" onClick={handleCancel}>
|
|
297
|
-
Cancel Operation
|
|
298
|
-
</button>
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
```
|
|
302
|
-
|
|
303
|
-
## Tips
|
|
304
|
-
|
|
305
|
-
- **Use semantic IDs** — Use meaningful IDs like `chat:123` or `task:abc` instead of random UUIDs
|
|
306
|
-
- **Create is idempotent** — Calling `create()` with the same ID reconnects to the existing controller
|
|
307
|
-
- **TTL auto-cleanup** — Workflows self-terminate after TTL expires; no manual cleanup needed
|
|
308
|
-
- **Signal is a getter** — Each access to `.signal` creates a new listener; cache it if needed
|
|
309
|
-
- **One-shot** — Once aborted or expired, the workflow completes; create a new controller for new operations
|
|
310
|
-
|
|
311
|
-
## Key APIs
|
|
312
|
-
|
|
313
|
-
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook for the abort trigger
|
|
314
|
-
- [`getWritable()`](/docs/api-reference/workflow/get-writable) — write abort messages to the stream
|
|
315
|
-
- [`sleep()`](/docs/api-reference/workflow/sleep) — TTL timer for auto-expiration
|
|
316
|
-
- [`start()`](/docs/api-reference/workflow-api/start) — start the abort controller workflow
|
|
317
|
-
- [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) — find existing run by hook token
|
|
318
|
-
- [`getRun()`](/docs/api-reference/workflow-api/get-run) — reconnect to the workflow's readable stream
|