@workflow/core 5.0.0-beta.5 → 5.0.0-beta.50
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/attribute-changes.d.ts +5 -0
- package/dist/attribute-changes.d.ts.map +1 -0
- package/dist/attribute-changes.js +25 -0
- package/dist/capabilities.d.ts +35 -2
- package/dist/capabilities.d.ts.map +1 -1
- package/dist/capabilities.js +74 -5
- package/dist/capture-stack.d.ts +1 -1
- package/dist/capture-stack.js +2 -2
- package/dist/class-serialization.d.ts +32 -0
- package/dist/class-serialization.d.ts.map +1 -1
- package/dist/class-serialization.js +37 -1
- package/dist/classify-error.d.ts +19 -3
- package/dist/classify-error.d.ts.map +1 -1
- package/dist/classify-error.js +98 -6
- package/dist/context-violation-error.d.ts +5 -5
- package/dist/context-violation-error.d.ts.map +1 -1
- package/dist/context-violation-error.js +8 -6
- package/dist/create-hook.d.ts +72 -7
- package/dist/create-hook.d.ts.map +1 -1
- package/dist/create-hook.js +1 -1
- package/dist/define-hook.js +2 -2
- package/dist/describe-error.d.ts +7 -7
- package/dist/describe-error.d.ts.map +1 -1
- package/dist/describe-error.js +97 -12
- package/dist/encryption.d.ts +38 -4
- package/dist/encryption.d.ts.map +1 -1
- package/dist/encryption.js +96 -14
- package/dist/events-consumer.d.ts +271 -0
- package/dist/events-consumer.d.ts.map +1 -1
- package/dist/events-consumer.js +646 -42
- package/dist/flushable-stream.d.ts +56 -1
- package/dist/flushable-stream.d.ts.map +1 -1
- package/dist/flushable-stream.js +123 -11
- package/dist/global.d.ts +36 -2
- package/dist/global.d.ts.map +1 -1
- package/dist/global.js +21 -6
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/log-format.d.ts +2 -2
- package/dist/log-format.js +7 -7
- package/dist/logger.d.ts +1 -0
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +10 -6
- package/dist/private.d.ts +226 -9
- package/dist/private.d.ts.map +1 -1
- package/dist/private.js +626 -7
- package/dist/replay-payload-cache.d.ts +64 -0
- package/dist/replay-payload-cache.d.ts.map +1 -0
- package/dist/replay-payload-cache.js +158 -0
- package/dist/runtime/compute-instance.d.ts +13 -0
- package/dist/runtime/compute-instance.d.ts.map +1 -0
- package/dist/runtime/compute-instance.js +14 -0
- package/dist/runtime/constants.d.ts +315 -0
- package/dist/runtime/constants.d.ts.map +1 -1
- package/dist/runtime/constants.js +502 -16
- package/dist/runtime/count-step-started-events.d.ts +52 -0
- package/dist/runtime/count-step-started-events.d.ts.map +1 -0
- package/dist/runtime/count-step-started-events.js +72 -0
- package/dist/runtime/deployment-guard.d.ts +99 -0
- package/dist/runtime/deployment-guard.d.ts.map +1 -0
- package/dist/runtime/deployment-guard.js +154 -0
- package/dist/runtime/get-port-lazy.d.ts +15 -0
- package/dist/runtime/get-port-lazy.d.ts.map +1 -1
- package/dist/runtime/get-port-lazy.js +75 -6
- package/dist/runtime/get-world-lazy.d.ts +5 -14
- package/dist/runtime/get-world-lazy.d.ts.map +1 -1
- package/dist/runtime/get-world-lazy.js +19 -29
- package/dist/runtime/helpers.d.ts +341 -29
- package/dist/runtime/helpers.d.ts.map +1 -1
- package/dist/runtime/helpers.js +559 -57
- package/dist/runtime/quickjs-assets.generated.d.ts +14 -0
- package/dist/runtime/quickjs-assets.generated.d.ts.map +1 -0
- package/dist/runtime/quickjs-assets.generated.js +30 -0
- package/dist/runtime/quickjs-entrypoint.d.ts +136 -0
- package/dist/runtime/quickjs-entrypoint.d.ts.map +1 -0
- package/dist/runtime/quickjs-entrypoint.js +1686 -0
- package/dist/runtime/quickjs-runtime.d.ts +244 -0
- package/dist/runtime/quickjs-runtime.d.ts.map +1 -0
- package/dist/runtime/quickjs-runtime.js +2427 -0
- package/dist/runtime/quickjs-serde.d.ts +107 -0
- package/dist/runtime/quickjs-serde.d.ts.map +1 -0
- package/dist/runtime/quickjs-serde.js +2159 -0
- package/dist/runtime/replay-budget.d.ts +97 -0
- package/dist/runtime/replay-budget.d.ts.map +1 -0
- package/dist/runtime/replay-budget.js +139 -0
- package/dist/runtime/replay-recovery-reporter.d.ts +36 -0
- package/dist/runtime/replay-recovery-reporter.d.ts.map +1 -0
- package/dist/runtime/replay-recovery-reporter.js +64 -0
- package/dist/runtime/resume-hook.d.ts +91 -8
- package/dist/runtime/resume-hook.d.ts.map +1 -1
- package/dist/runtime/resume-hook.js +512 -89
- package/dist/runtime/resume-latency.d.ts +150 -0
- package/dist/runtime/resume-latency.d.ts.map +1 -0
- package/dist/runtime/resume-latency.js +155 -0
- package/dist/runtime/run-id-time.d.ts +19 -0
- package/dist/runtime/run-id-time.d.ts.map +1 -0
- package/dist/runtime/run-id-time.js +42 -0
- package/dist/runtime/run.d.ts +72 -7
- package/dist/runtime/run.d.ts.map +1 -1
- package/dist/runtime/run.js +280 -53
- package/dist/runtime/runs.d.ts +54 -3
- package/dist/runtime/runs.d.ts.map +1 -1
- package/dist/runtime/runs.js +126 -16
- package/dist/runtime/start.d.ts +101 -2
- package/dist/runtime/start.d.ts.map +1 -1
- package/dist/runtime/start.js +352 -61
- package/dist/runtime/step-executor.d.ts +205 -5
- package/dist/runtime/step-executor.d.ts.map +1 -1
- package/dist/runtime/step-executor.js +760 -127
- package/dist/runtime/step-latency.d.ts +220 -0
- package/dist/runtime/step-latency.d.ts.map +1 -0
- package/dist/runtime/step-latency.js +215 -0
- package/dist/runtime/step-ownership.d.ts +72 -0
- package/dist/runtime/step-ownership.d.ts.map +1 -0
- package/dist/runtime/step-ownership.js +114 -0
- package/dist/runtime/step-single-flight.d.ts +12 -0
- package/dist/runtime/step-single-flight.d.ts.map +1 -0
- package/dist/runtime/step-single-flight.js +75 -0
- package/dist/runtime/suspension-handler.d.ts +269 -7
- package/dist/runtime/suspension-handler.d.ts.map +1 -1
- package/dist/runtime/suspension-handler.js +1253 -125
- package/dist/runtime/unserializable-step.d.ts +34 -0
- package/dist/runtime/unserializable-step.d.ts.map +1 -0
- package/dist/runtime/unserializable-step.js +52 -0
- package/dist/runtime/vm-mode.d.ts +44 -0
- package/dist/runtime/vm-mode.d.ts.map +1 -0
- package/dist/runtime/vm-mode.js +62 -0
- package/dist/runtime/vm-serde-bundle.generated.d.ts +14 -0
- package/dist/runtime/vm-serde-bundle.generated.d.ts.map +1 -0
- package/dist/runtime/vm-serde-bundle.generated.js +16 -0
- package/dist/runtime/wait-continuation.d.ts +106 -0
- package/dist/runtime/wait-continuation.d.ts.map +1 -0
- package/dist/runtime/wait-continuation.js +136 -0
- package/dist/runtime/wait-until.d.ts +18 -0
- package/dist/runtime/wait-until.d.ts.map +1 -0
- package/dist/runtime/wait-until.js +42 -0
- package/dist/runtime/world-compatibility.d.ts +32 -0
- package/dist/runtime/world-compatibility.d.ts.map +1 -0
- package/dist/runtime/world-compatibility.js +44 -0
- package/dist/runtime/world-init.d.ts +17 -42
- package/dist/runtime/world-init.d.ts.map +1 -1
- package/dist/runtime/world-init.js +18 -43
- package/dist/runtime/world.d.ts +14 -2
- package/dist/runtime/world.d.ts.map +1 -1
- package/dist/runtime/world.js +75 -19
- package/dist/runtime.d.ts +10 -6
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +3741 -490
- package/dist/sealed-box.d.ts +167 -0
- package/dist/sealed-box.d.ts.map +1 -0
- package/dist/sealed-box.js +571 -0
- package/dist/serialization/client.d.ts +3 -3
- package/dist/serialization/client.d.ts.map +1 -1
- package/dist/serialization/client.js +8 -4
- package/dist/serialization/codec-devalue-vm.d.ts +16 -0
- package/dist/serialization/codec-devalue-vm.d.ts.map +1 -0
- package/dist/serialization/codec-devalue-vm.js +148 -0
- package/dist/serialization/codec-devalue.d.ts +1 -1
- package/dist/serialization/codec-devalue.d.ts.map +1 -1
- package/dist/serialization/codec-devalue.js +24 -6
- package/dist/serialization/codec.d.ts +37 -2
- package/dist/serialization/codec.d.ts.map +1 -1
- package/dist/serialization/codec.js +2 -2
- package/dist/serialization/compression.d.ts +105 -0
- package/dist/serialization/compression.d.ts.map +1 -0
- package/dist/serialization/compression.js +261 -0
- package/dist/serialization/encryption.d.ts +119 -17
- package/dist/serialization/encryption.d.ts.map +1 -1
- package/dist/serialization/encryption.js +152 -17
- package/dist/serialization/errors.d.ts +13 -0
- package/dist/serialization/errors.d.ts.map +1 -1
- package/dist/serialization/errors.js +20 -2
- package/dist/serialization/format.d.ts +6 -6
- package/dist/serialization/format.js +7 -7
- package/dist/serialization/hardened.d.ts +156 -0
- package/dist/serialization/hardened.d.ts.map +1 -0
- package/dist/serialization/hardened.js +538 -0
- package/dist/serialization/index.d.ts +10 -8
- package/dist/serialization/index.d.ts.map +1 -1
- package/dist/serialization/index.js +10 -8
- package/dist/serialization/reducers/class-vm.d.ts +20 -0
- package/dist/serialization/reducers/class-vm.d.ts.map +1 -0
- package/dist/serialization/reducers/class-vm.js +77 -0
- package/dist/serialization/reducers/class.d.ts.map +1 -1
- package/dist/serialization/reducers/class.js +11 -6
- package/dist/serialization/reducers/common-vm.d.ts +15 -0
- package/dist/serialization/reducers/common-vm.d.ts.map +1 -0
- package/dist/serialization/reducers/common-vm.js +616 -0
- package/dist/serialization/reducers/common.d.ts +1 -1
- package/dist/serialization/reducers/common.d.ts.map +1 -1
- package/dist/serialization/reducers/common.js +202 -62
- package/dist/serialization/reducers/step-function-vm.d.ts +44 -0
- package/dist/serialization/reducers/step-function-vm.d.ts.map +1 -0
- package/dist/serialization/reducers/step-function-vm.js +97 -0
- package/dist/serialization/reducers/step-function.d.ts.map +1 -1
- package/dist/serialization/reducers/step-function.js +25 -9
- package/dist/serialization/step.d.ts +4 -4
- package/dist/serialization/step.d.ts.map +1 -1
- package/dist/serialization/step.js +9 -5
- package/dist/serialization/types.d.ts +80 -1
- package/dist/serialization/types.d.ts.map +1 -1
- package/dist/serialization/types.js +15 -1
- package/dist/serialization/workflow-vm.d.ts +29 -0
- package/dist/serialization/workflow-vm.d.ts.map +1 -0
- package/dist/serialization/workflow-vm.js +74 -0
- package/dist/serialization-format.d.ts +64 -8
- package/dist/serialization-format.d.ts.map +1 -1
- package/dist/serialization-format.js +225 -73
- package/dist/serialization.d.ts +262 -34
- package/dist/serialization.d.ts.map +1 -1
- package/dist/serialization.js +1879 -274
- package/dist/set-attributes.d.ts +13 -0
- package/dist/set-attributes.d.ts.map +1 -0
- package/dist/set-attributes.js +60 -0
- package/dist/source-map.d.ts +25 -0
- package/dist/source-map.d.ts.map +1 -1
- package/dist/source-map.js +154 -10
- package/dist/step/context-storage.d.ts +61 -2
- package/dist/step/context-storage.d.ts.map +1 -1
- package/dist/step/context-storage.js +7 -5
- package/dist/step/writable-stream.d.ts +3 -3
- package/dist/step/writable-stream.d.ts.map +1 -1
- package/dist/step/writable-stream.js +72 -9
- package/dist/step.d.ts.map +1 -1
- package/dist/step.js +148 -27
- package/dist/symbols.d.ts +50 -0
- package/dist/symbols.d.ts.map +1 -1
- package/dist/symbols.js +51 -1
- package/dist/telemetry/semantic-conventions.d.ts +397 -2
- package/dist/telemetry/semantic-conventions.d.ts.map +1 -1
- package/dist/telemetry/semantic-conventions.js +297 -3
- package/dist/telemetry.d.ts +91 -0
- package/dist/telemetry.d.ts.map +1 -1
- package/dist/telemetry.js +244 -17
- package/dist/test-support/orchestrator-context.d.ts +25 -0
- package/dist/test-support/orchestrator-context.d.ts.map +1 -0
- package/dist/test-support/orchestrator-context.js +101 -0
- package/dist/types.d.ts +6 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +23 -1
- package/dist/util.d.ts +0 -5
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +1 -15
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +2 -2
- package/dist/vm/index.d.ts.map +1 -1
- package/dist/vm/index.js +84 -14
- package/dist/vm/script-cache.d.ts +26 -0
- package/dist/vm/script-cache.d.ts.map +1 -0
- package/dist/vm/script-cache.js +131 -0
- package/dist/vm/uint8array-base64.js +1 -1
- package/dist/workflow/abort-controller.d.ts +2 -2
- package/dist/workflow/abort-controller.d.ts.map +1 -1
- package/dist/workflow/abort-controller.js +88 -21
- package/dist/workflow/attribute-dispatcher.d.ts +6 -0
- package/dist/workflow/attribute-dispatcher.d.ts.map +1 -0
- package/dist/workflow/attribute-dispatcher.js +45 -0
- package/dist/workflow/create-hook.d.ts.map +1 -1
- package/dist/workflow/create-hook.js +24 -3
- package/dist/workflow/get-workflow-metadata.js +2 -2
- package/dist/workflow/hook.d.ts.map +1 -1
- package/dist/workflow/hook.js +304 -47
- package/dist/workflow/index.d.ts +1 -0
- package/dist/workflow/index.d.ts.map +1 -1
- package/dist/workflow/index.js +2 -1
- package/dist/workflow/set-attributes.d.ts +68 -0
- package/dist/workflow/set-attributes.d.ts.map +1 -0
- package/dist/workflow/set-attributes.js +60 -0
- package/dist/workflow/sleep.d.ts.map +1 -1
- package/dist/workflow/sleep.js +58 -12
- package/dist/workflow/world-init-stub.d.ts +3 -3
- package/dist/workflow/world-init-stub.js +4 -4
- package/dist/workflow.d.ts +95 -3
- package/dist/workflow.d.ts.map +1 -1
- package/dist/workflow.js +895 -561
- package/docs/api-reference/create-hook.mdx +89 -10
- package/docs/api-reference/create-webhook.mdx +16 -15
- package/docs/api-reference/define-hook.mdx +35 -33
- package/docs/api-reference/fatal-error.mdx +30 -8
- package/docs/api-reference/fetch.mdx +14 -10
- package/docs/api-reference/get-step-metadata.mdx +2 -2
- package/docs/api-reference/get-workflow-metadata.mdx +3 -3
- package/docs/api-reference/get-writable.mdx +7 -7
- package/docs/api-reference/index.mdx +4 -1
- package/docs/api-reference/retryable-error.mdx +1 -1
- package/docs/api-reference/set-attributes.mdx +61 -0
- package/docs/api-reference/sleep.mdx +4 -4
- package/docs/foundations/cancellation.mdx +31 -32
- package/docs/foundations/errors-and-retries.mdx +42 -11
- package/docs/foundations/hooks.mdx +64 -35
- package/docs/foundations/idempotency.mdx +244 -12
- package/docs/foundations/index.mdx +1 -23
- package/docs/foundations/meta.json +2 -1
- package/docs/foundations/serialization.mdx +21 -22
- package/docs/foundations/starting-workflows.mdx +106 -30
- package/docs/foundations/streaming.mdx +107 -59
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/foundations/workflows-and-steps.mdx +9 -9
- package/docs/how-it-works/cancellation.mdx +63 -63
- package/docs/how-it-works/code-transform.mdx +83 -67
- package/docs/how-it-works/encryption.mdx +30 -26
- package/docs/how-it-works/event-sourcing.mdx +98 -34
- package/docs/how-it-works/framework-integrations.mdx +96 -337
- package/docs/how-it-works/understanding-directives.mdx +22 -22
- package/package.json +24 -15
- package/dist/runtime/step-handler.d.ts +0 -2
- package/dist/runtime/step-handler.d.ts.map +0 -1
- package/dist/runtime/step-handler.js +0 -776
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Idempotency
|
|
3
|
-
description:
|
|
3
|
+
description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
|
|
4
4
|
type: conceptual
|
|
5
|
-
summary:
|
|
5
|
+
summary: Use step IDs for retry-safe external calls, and route duplicate workflow-start requests through deterministic hook tokens.
|
|
6
6
|
prerequisites:
|
|
7
7
|
- /docs/foundations/workflows-and-steps
|
|
8
8
|
related:
|
|
9
9
|
- /docs/foundations/errors-and-retries
|
|
10
|
+
- /docs/foundations/starting-workflows
|
|
11
|
+
- /docs/foundations/hooks
|
|
10
12
|
---
|
|
11
13
|
|
|
12
|
-
Idempotency is a property of an operation that ensures
|
|
14
|
+
Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
|
|
13
15
|
|
|
14
|
-
In
|
|
16
|
+
In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency coordinates duplicate requests that try to start the same workflow.
|
|
17
|
+
|
|
18
|
+
## Step idempotency
|
|
19
|
+
|
|
20
|
+
In distributed systems (calling external APIs), it is not always possible to ensure an operation has only been performed once by seeing if it succeeds.
|
|
15
21
|
Consider a payment API that charges the user $10, but due to network failures, the confirmation response is lost. When the step retries (because the previous attempt was considered a failure), it will charge the user again.
|
|
16
22
|
|
|
17
23
|
To prevent this, many external APIs support idempotency keys. An idempotency key is a unique identifier for an operation that can be used to deduplicate requests.
|
|
18
24
|
|
|
19
|
-
## The core pattern: use the step ID as your idempotency key
|
|
20
|
-
|
|
21
25
|
Every step invocation has a stable `stepId` that stays the same across retries.
|
|
22
26
|
Use it as the idempotency key when calling third-party APIs.
|
|
23
27
|
|
|
@@ -27,7 +31,7 @@ import { getStepMetadata } from "workflow";
|
|
|
27
31
|
async function chargeUser(userId: string, amount: number) {
|
|
28
32
|
"use step";
|
|
29
33
|
|
|
30
|
-
const { stepId } = getStepMetadata();
|
|
34
|
+
const { stepId } = getStepMetadata(); // [!code highlight]
|
|
31
35
|
|
|
32
36
|
// Example: Stripe-style idempotency key
|
|
33
37
|
// This guarantees only one charge is created even if the step retries
|
|
@@ -49,14 +53,242 @@ Why this works:
|
|
|
49
53
|
- **Stable across retries**: `stepId` does not change between attempts.
|
|
50
54
|
- **Globally unique per step**: Fulfills the uniqueness requirement for an idempotency key.
|
|
51
55
|
|
|
52
|
-
##
|
|
56
|
+
## Run idempotency
|
|
57
|
+
|
|
58
|
+
Step idempotency protects side effects **inside** a workflow run. Run idempotency answers a different question: if the same API request is sent twice, should it create one workflow run or two?
|
|
59
|
+
|
|
60
|
+
Because [hooks](/docs/foundations/hooks) already ensure globally unique active tokens, Workflow can use the same mechanism to coordinate duplicate requests while a run is active.
|
|
61
|
+
|
|
62
|
+
Use a hook token as the idempotency key for an active workflow run. Hook tokens are globally unique while they are active: if another run tries to create a hook with the same token, the runtime records a conflict, `hook.getConflict()` resolves with a `Run` handle for the run that owns the token, and the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict) when the workflow awaits or iterates its payload.
|
|
63
|
+
|
|
64
|
+
The token should come from your domain, such as an order ID, invoice ID, import ID, or request ID. Create the hook near the beginning of the workflow and check `await hook.getConflict()` before doing duplicate-sensitive work that depends on owning the active token. Calling `createHook()` alone does not register the hook; awaiting `getConflict()` suspends the workflow to commit the registration.
|
|
65
|
+
|
|
66
|
+
```typescript lineNumbers
|
|
67
|
+
import { createHook } from "workflow";
|
|
68
|
+
|
|
69
|
+
type OrderRequest = { confirmed: boolean };
|
|
70
|
+
type OrderResult =
|
|
71
|
+
| { status: "processed" | "cancelled" }
|
|
72
|
+
| { status: "duplicate"; runId: string };
|
|
73
|
+
declare function chargeOrder(orderId: string): Promise<void>; // @setup
|
|
74
|
+
|
|
75
|
+
export async function processOrder(orderId: string): Promise<OrderResult> {
|
|
76
|
+
"use workflow";
|
|
77
|
+
|
|
78
|
+
using request = createHook<OrderRequest>({ // [!code highlight]
|
|
79
|
+
token: `order:${orderId}`, // [!code highlight]
|
|
80
|
+
}); // [!code highlight]
|
|
81
|
+
|
|
82
|
+
const conflict = await request.getConflict(); // [!code highlight]
|
|
83
|
+
if (conflict) { // [!code highlight]
|
|
84
|
+
// Another active run already owns this order's token. // [!code highlight]
|
|
85
|
+
return { status: "duplicate" as const, runId: conflict.runId }; // [!code highlight]
|
|
86
|
+
} // [!code highlight]
|
|
87
|
+
|
|
88
|
+
const { confirmed } = await request;
|
|
89
|
+
|
|
90
|
+
if (!confirmed) {
|
|
91
|
+
return { status: "cancelled" as const };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
await chargeOrder(orderId);
|
|
95
|
+
return { status: "processed" as const };
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The runtime creates the hook atomically. At most one hook can own `order:${orderId}`, so duplicate workflow runs converge on one owner. A duplicate run observes `getConflict()` resolving with the owner's `Run` and returns before it reaches `chargeOrder()`. The conflicting run's accessors (`status`, `returnValue`, `cancel()`, …) are durable steps, so the duplicate run can do more than report the owner. See [conflict-handling strategies](#conflict-handling-strategies) below.
|
|
100
|
+
|
|
101
|
+
Outside the workflow, try to resume the hook first. If the hook is not registered yet, start the workflow and retry the resume until the new run creates the hook:
|
|
102
|
+
|
|
103
|
+
```typescript lineNumbers
|
|
104
|
+
import { resumeHook, start } from "workflow/api";
|
|
105
|
+
import { HookNotFoundError } from "workflow/errors";
|
|
106
|
+
import { processOrder } from "./workflows/process-order";
|
|
107
|
+
|
|
108
|
+
type OrderRequest = { confirmed: boolean };
|
|
109
|
+
|
|
110
|
+
async function resumeOrder(token: string, payload: OrderRequest) {
|
|
111
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
112
|
+
try {
|
|
113
|
+
return await resumeHook(token, payload); // [!code highlight]
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (!HookNotFoundError.is(error)) throw error;
|
|
116
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
throw new Error("Order workflow did not register its hook in time");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function POST(request: Request) {
|
|
124
|
+
const { orderId, confirmed } = await request.json();
|
|
125
|
+
const token = `order:${orderId}`;
|
|
126
|
+
const payload = { confirmed };
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
const hook = await resumeHook(token, payload); // [!code highlight]
|
|
130
|
+
return Response.json({ runId: hook.runId, reused: true });
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (!HookNotFoundError.is(error)) throw error;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const run = await start(processOrder, [orderId]); // [!code highlight]
|
|
136
|
+
const resumed = await resumeOrder(token, payload);
|
|
137
|
+
|
|
138
|
+
// A concurrent request's run may have won the race between `start()` // [!code highlight]
|
|
139
|
+
// and hook registration. The resume always reaches the actual active // [!code highlight]
|
|
140
|
+
// owner, so compare run IDs instead of waiting for this run to finish. // [!code highlight]
|
|
141
|
+
return Response.json({ // [!code highlight]
|
|
142
|
+
runId: resumed.runId, // [!code highlight]
|
|
143
|
+
reused: resumed.runId !== run.runId, // [!code highlight]
|
|
144
|
+
}); // [!code highlight]
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
<Callout type="warn">
|
|
149
|
+
This avoids creating a new run only after the first run has registered its hook. Because `start()` returns before the run body executes and calls `createHook()`, two concurrent requests can both observe "no hook yet" and each call `start()`. The race is resolved inside the workflow body, where the losing run observes `getConflict()` resolving with the active owner and returns without doing duplicate-sensitive work, and the route detects it by comparing the resumed hook's `runId` against the run it just started, without waiting for either run to finish. A native API for atomically starting a run and registering a hook is in the works. Until then, model recovery inside the workflow by checking `hook.getConflict()`.
|
|
150
|
+
</Callout>
|
|
151
|
+
|
|
152
|
+
This coordinates active runs by default: the token becomes available when its workflow ends. Set `experimental_minRetention` to keep it unavailable to late duplicates. After the workflow ends, the Hook can still be found with `getHookByToken()` until retention ends, but it cannot be resumed. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) for examples and supported values.
|
|
153
|
+
|
|
154
|
+
### Conflict-handling strategies
|
|
155
|
+
|
|
156
|
+
Some workflow systems resolve duplicate IDs with a fixed, pre-declared policy, typically a static choice between rejecting the new execution, deferring to the existing one, or terminating it. Workflow has no policy enum. `hook.getConflict()` hands the duplicate run the conflicting `Run` itself, and the policy is ordinary code, including policies that inspect state before deciding, which static configuration can't express.
|
|
157
|
+
|
|
158
|
+
The example above implements **reject the duplicate**: return the owner's `runId` and let the caller decide. Other common strategies:
|
|
159
|
+
|
|
160
|
+
**Adopt the owner's result.** Wait for the active run to finish and return its result, so callers cannot tell which run did the work:
|
|
161
|
+
|
|
162
|
+
```typescript lineNumbers
|
|
163
|
+
import { createHook } from "workflow";
|
|
164
|
+
|
|
165
|
+
type OrderRequest = { confirmed: boolean };
|
|
166
|
+
declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
|
|
167
|
+
|
|
168
|
+
export async function processOrder(orderId: string) {
|
|
169
|
+
"use workflow";
|
|
170
|
+
|
|
171
|
+
using request = createHook<OrderRequest>({
|
|
172
|
+
token: `order:${orderId}`,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const conflict = await request.getConflict();
|
|
176
|
+
if (conflict) {
|
|
177
|
+
// Callers get the same result regardless of which run did the work.
|
|
178
|
+
return await conflict.returnValue; // [!code highlight]
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return await processOwnedOrder(orderId);
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
**Inspect the owner before deciding.** Reuse a completed owner's result, but reject other duplicates:
|
|
186
|
+
|
|
187
|
+
```typescript lineNumbers
|
|
188
|
+
import { createHook } from "workflow";
|
|
189
|
+
|
|
190
|
+
type OrderRequest = { confirmed: boolean };
|
|
191
|
+
declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
|
|
192
|
+
|
|
193
|
+
export async function processOrder(orderId: string) {
|
|
194
|
+
"use workflow";
|
|
195
|
+
|
|
196
|
+
using request = createHook<OrderRequest>({
|
|
197
|
+
token: `order:${orderId}`,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const conflict = await request.getConflict();
|
|
201
|
+
if (conflict) {
|
|
202
|
+
const status = await conflict.status; // [!code highlight]
|
|
203
|
+
if (status === "completed") {
|
|
204
|
+
return await conflict.returnValue;
|
|
205
|
+
}
|
|
206
|
+
return { status: "duplicate" as const, runId: conflict.runId };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return await processOwnedOrder(orderId);
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
**Signal the owner instead of doing the work.** A conflict can refer to a finished run when `experimental_minRetention` is set, so check its status before sending data to its Hook:
|
|
214
|
+
|
|
215
|
+
```typescript lineNumbers
|
|
216
|
+
import { createHook } from "workflow";
|
|
217
|
+
import { resumeHook } from "workflow/api";
|
|
218
|
+
|
|
219
|
+
type OrderRequest = { confirmed: boolean };
|
|
220
|
+
|
|
221
|
+
async function forwardToOwner(token: string, payload: OrderRequest) {
|
|
222
|
+
"use step";
|
|
223
|
+
await resumeHook(token, payload); // [!code highlight]
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function processOrder(orderId: string, confirmed: boolean) {
|
|
227
|
+
"use workflow";
|
|
228
|
+
|
|
229
|
+
const token = `order:${orderId}`;
|
|
230
|
+
using request = createHook<OrderRequest>({ token });
|
|
231
|
+
|
|
232
|
+
const conflict = await request.getConflict();
|
|
233
|
+
if (conflict && ["pending", "running"].includes(await conflict.status)) {
|
|
234
|
+
await forwardToOwner(token, { confirmed }); // [!code highlight]
|
|
235
|
+
return { status: "forwarded" as const, runId: conflict.runId };
|
|
236
|
+
}
|
|
237
|
+
if (conflict) {
|
|
238
|
+
return { status: "duplicate" as const, runId: conflict.runId };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ... own the token and do the work
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
**Supersede the owner.** Without minimum retention, cancel the active run, then claim the released token. The retry loop covers the window where cancellation cleanup has not propagated yet:
|
|
246
|
+
|
|
247
|
+
```typescript lineNumbers
|
|
248
|
+
import { createHook } from "workflow";
|
|
249
|
+
|
|
250
|
+
type OrderRequest = { confirmed: boolean };
|
|
251
|
+
declare function chargeOrder(orderId: string): Promise<void>; // @setup
|
|
252
|
+
|
|
253
|
+
export async function processOrderNewestWins(orderId: string) {
|
|
254
|
+
"use workflow";
|
|
255
|
+
|
|
256
|
+
const token = `order:${orderId}`;
|
|
257
|
+
|
|
258
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
259
|
+
using request = createHook<OrderRequest>({ token });
|
|
260
|
+
|
|
261
|
+
const conflict = await request.getConflict();
|
|
262
|
+
if (!conflict) {
|
|
263
|
+
// Token claimed: this run is now the owner.
|
|
264
|
+
const { confirmed } = await request;
|
|
265
|
+
if (confirmed) {
|
|
266
|
+
await chargeOrder(orderId);
|
|
267
|
+
}
|
|
268
|
+
return { status: "processed" as const };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
await conflict.cancel(); // [!code highlight]
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
throw new Error(`Could not claim ${token} after canceling the owner`);
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
<Callout type="warn">
|
|
279
|
+
This pattern does not work with `experimental_minRetention`: canceling the old run does not make its token available early.
|
|
280
|
+
</Callout>
|
|
281
|
+
|
|
282
|
+
If duplicate requests should only reuse the active run without sending data, use [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) as an advisory pre-check before calling `start()`. The workflow should still check `hook.getConflict()`, because the lookup and `start()` are not atomic.
|
|
53
283
|
|
|
54
|
-
|
|
55
|
-
- **Prefer `stepId` as your key**; it is stable across retries and unique per step.
|
|
56
|
-
- **Keep keys deterministic**; avoid including timestamps or attempt counters.
|
|
57
|
-
- **Handle 409/conflict responses** gracefully; treat them as success if the prior attempt completed.
|
|
284
|
+
Because this pattern uses hooks for idempotency, duplicate requests can also inject additional data and steer the existing run. The route example above uses `resumeHook()` for that: if the hook already exists, the duplicate request resumes the active workflow; if the hook is not registered yet, the route starts the workflow and retries `resumeHook()` so the payload is not dropped.
|
|
58
285
|
|
|
59
286
|
## Related docs
|
|
60
287
|
|
|
61
288
|
- Learn about retries in [Errors & Retrying](/docs/foundations/errors-and-retries)
|
|
62
289
|
- API reference: [`getStepMetadata`](/docs/api-reference/workflow/get-step-metadata)
|
|
290
|
+
- API reference: [`createHook()`](/docs/api-reference/workflow/create-hook)
|
|
291
|
+
- API reference: [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token)
|
|
292
|
+
- API reference: [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook)
|
|
293
|
+
- API reference: [`start()`](/docs/api-reference/workflow-api/start)
|
|
294
|
+
- Learn about deterministic hook tokens in [Hooks](/docs/foundations/hooks)
|
|
@@ -10,26 +10,4 @@ related:
|
|
|
10
10
|
|
|
11
11
|
Workflow programming can be a slight shift from how you traditionally write real-world applications. Learning the foundations now will go a long way toward helping you use workflows effectively.
|
|
12
12
|
|
|
13
|
-
<
|
|
14
|
-
<Card href="/docs/foundations/workflows-and-steps" title="Workflows and Steps">
|
|
15
|
-
Learn about the building blocks of durability
|
|
16
|
-
</Card>
|
|
17
|
-
<Card href="/docs/foundations/starting-workflows" title="Starting Workflows">
|
|
18
|
-
Trigger workflows and track their execution using the `start()` function.
|
|
19
|
-
</Card>
|
|
20
|
-
<Card href="/docs/foundations/errors-and-retries" title="Errors & Retrying">
|
|
21
|
-
Types of errors and how retrying work in workflows.
|
|
22
|
-
</Card>
|
|
23
|
-
<Card href="/docs/foundations/hooks" title="Webhooks (and hooks)">
|
|
24
|
-
Respond to external events in your workflow using hooks and webhooks.
|
|
25
|
-
</Card>
|
|
26
|
-
<Card href="/docs/foundations/streaming" title="Streaming">
|
|
27
|
-
Stream data in real-time to clients without waiting for the workflow to complete.
|
|
28
|
-
</Card>
|
|
29
|
-
<Card href="/docs/foundations/serialization" title="Serialization">
|
|
30
|
-
Understand which types can be passed between workflow and step functions.
|
|
31
|
-
</Card>
|
|
32
|
-
<Card href="/docs/foundations/idempotency" title="Idempotency">
|
|
33
|
-
Prevent duplicate side effects when retrying operations.
|
|
34
|
-
</Card>
|
|
35
|
-
</Cards>
|
|
13
|
+
<AutoCards />
|
|
@@ -15,11 +15,11 @@ All function arguments and return values passed between workflow and step functi
|
|
|
15
15
|
The serialization system ensures that all data persists correctly across workflow suspensions and resumptions, enabling durable execution.
|
|
16
16
|
</Callout>
|
|
17
17
|
|
|
18
|
-
## Supported
|
|
18
|
+
## Supported serializable types
|
|
19
19
|
|
|
20
20
|
The following types can be serialized and passed through workflow functions:
|
|
21
21
|
|
|
22
|
-
**Standard JSON
|
|
22
|
+
**Standard JSON types:**
|
|
23
23
|
|
|
24
24
|
- `string`
|
|
25
25
|
- `number`
|
|
@@ -28,7 +28,7 @@ The following types can be serialized and passed through workflow functions:
|
|
|
28
28
|
- Arrays of serializable values
|
|
29
29
|
- Objects with string keys and serializable values
|
|
30
30
|
|
|
31
|
-
**Extended
|
|
31
|
+
**Extended types:**
|
|
32
32
|
|
|
33
33
|
- `undefined`
|
|
34
34
|
- `bigint`
|
|
@@ -58,7 +58,7 @@ These types have special handling and are explained in detail in the sections be
|
|
|
58
58
|
- `AbortController`
|
|
59
59
|
- `AbortSignal`
|
|
60
60
|
|
|
61
|
-
## Pass-by-
|
|
61
|
+
## Pass-by-value semantics
|
|
62
62
|
|
|
63
63
|
**Parameters are passed by value, not by reference.** Steps receive deserialized copies of data. Mutations inside a step won't affect the original in the workflow.
|
|
64
64
|
|
|
@@ -81,7 +81,7 @@ async function updateUserStep(user: { id: string; name: string; email: string })
|
|
|
81
81
|
}
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
-
**Correct
|
|
84
|
+
**Correct, return the modified data:**
|
|
85
85
|
|
|
86
86
|
```typescript title="workflows/correct-mutation.ts" lineNumbers
|
|
87
87
|
export async function updateUserWorkflow(userId: string) {
|
|
@@ -100,7 +100,7 @@ async function updateUserStep(user: { id: string; name: string; email: string })
|
|
|
100
100
|
}
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
**Custom
|
|
103
|
+
**Custom classes:**
|
|
104
104
|
|
|
105
105
|
- Class instances that implement [`WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE`](#custom-class-serialization)
|
|
106
106
|
|
|
@@ -110,7 +110,7 @@ async function updateUserStep(user: { id: string; name: string; email: string })
|
|
|
110
110
|
|
|
111
111
|
For complete information about using streams in workflows, including patterns for AI streaming, file processing, and progress updates, see the [Streaming Guide](/docs/foundations/streaming).
|
|
112
112
|
|
|
113
|
-
## Request &
|
|
113
|
+
## Request & response
|
|
114
114
|
|
|
115
115
|
The Web API [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) APIs are supported by the serialization system,
|
|
116
116
|
and can be passed around between workflow and step functions similarly to other data types.
|
|
@@ -140,7 +140,7 @@ export async function handleWebhookWorkflow() {
|
|
|
140
140
|
}
|
|
141
141
|
```
|
|
142
142
|
|
|
143
|
-
### Using `fetch` in
|
|
143
|
+
### Using `fetch` in workflows
|
|
144
144
|
|
|
145
145
|
Because `Request` and `Response` are serializable, Workflow SDK provides a `fetch` function that can be used directly in workflow functions:
|
|
146
146
|
|
|
@@ -158,7 +158,7 @@ export async function apiWorkflow() {
|
|
|
158
158
|
}
|
|
159
159
|
```
|
|
160
160
|
|
|
161
|
-
The
|
|
161
|
+
The `fetch` implementation from `workflow` is a step function that wraps the standard `fetch`:
|
|
162
162
|
|
|
163
163
|
```typescript title="Implementation" lineNumbers
|
|
164
164
|
export async function fetch(...args: Parameters<typeof globalThis.fetch>) {
|
|
@@ -202,11 +202,11 @@ async function fetchData(signal: AbortSignal) {
|
|
|
202
202
|
|
|
203
203
|
For usage patterns including timeouts, parallel cancellation, user-triggered cancellation, and run cancellation, see the [Cancellation Guide](/docs/foundations/cancellation). For details on the hook and stream backing that makes this work, see [How Cancellation Works](/docs/how-it-works/cancellation).
|
|
204
204
|
|
|
205
|
-
## Custom
|
|
205
|
+
## Custom class serialization
|
|
206
206
|
|
|
207
207
|
By default, custom class instances cannot be serialized because the serialization system doesn't know how to reconstruct them. You can make your classes serializable by implementing two static methods using special symbols from the `@workflow/serde` package.
|
|
208
208
|
|
|
209
|
-
### Basic
|
|
209
|
+
### Basic example
|
|
210
210
|
|
|
211
211
|
{/* @expect-error:2351 */}
|
|
212
212
|
|
|
@@ -256,13 +256,13 @@ async function doublePoint(point: Point) {
|
|
|
256
256
|
}
|
|
257
257
|
```
|
|
258
258
|
|
|
259
|
-
### How
|
|
259
|
+
### How it works
|
|
260
260
|
|
|
261
261
|
1. **`WORKFLOW_SERIALIZE`**: A static method that receives a class instance and returns serializable data (primitives, plain objects, arrays, etc.)
|
|
262
262
|
|
|
263
263
|
2. **`WORKFLOW_DESERIALIZE`**: A static method that receives the serialized data and returns a new class instance
|
|
264
264
|
|
|
265
|
-
3. **Automatic Registration**: The SWC compiler plugin automatically detects classes that implement these symbols and registers them for serialization. Each class receives a deterministic `classId` derived from its file path and class name, and is registered into the global `Symbol.for("workflow-class-registry")` registry at build time
|
|
265
|
+
3. **Automatic Registration**: The SWC compiler plugin automatically detects classes that implement these symbols and registers them for serialization. Each class receives a deterministic `classId` derived from its file path and class name, and is registered into the global `Symbol.for("workflow-class-registry")` registry at build time. No manual registration step is required
|
|
266
266
|
|
|
267
267
|
### Requirements
|
|
268
268
|
|
|
@@ -279,12 +279,12 @@ The `WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE` methods run inside the workf
|
|
|
279
279
|
- No non-deterministic operations (like `Math.random()` or `Date.now()`)
|
|
280
280
|
- No external network calls
|
|
281
281
|
|
|
282
|
-
Keep these methods
|
|
282
|
+
Keep these methods focused on data transformation only.
|
|
283
283
|
</Callout>
|
|
284
284
|
|
|
285
|
-
### Instance
|
|
285
|
+
### Instance methods as steps
|
|
286
286
|
|
|
287
|
-
In practice, many classes have methods that need Node.js APIs, perform network calls, or interact with databases
|
|
287
|
+
In practice, many classes have methods that need Node.js APIs, perform network calls, or interact with databases, operations that are not allowed in the `"use workflow"` execution context. You can make these methods workflow-compatible by adding `"use step"` to them. The SWC compiler will strip the method bodies from the workflow bundle and replace them with proxy functions that invoke the method as a step, with full Node.js runtime access. The `this` context (the class instance) is automatically serialized and deserialized across the workflow/step boundary.
|
|
288
288
|
|
|
289
289
|
This requires the class to implement `WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE`, so that the instance can be passed to the step execution context.
|
|
290
290
|
|
|
@@ -301,7 +301,7 @@ class Order {
|
|
|
301
301
|
public createdAt: Date
|
|
302
302
|
) {}
|
|
303
303
|
|
|
304
|
-
// Custom serialization
|
|
304
|
+
// Custom serialization: data must be serializable types
|
|
305
305
|
static [WORKFLOW_SERIALIZE](instance: Order) { // [!code highlight]
|
|
306
306
|
return { // [!code highlight]
|
|
307
307
|
id: instance.id, // [!code highlight]
|
|
@@ -329,7 +329,7 @@ class Order {
|
|
|
329
329
|
}
|
|
330
330
|
|
|
331
331
|
// Instance methods with "use step" run as step functions
|
|
332
|
-
// with full Node.js access
|
|
332
|
+
// with full Node.js access; `this` is automatically serialized
|
|
333
333
|
async save(): Promise<void> {
|
|
334
334
|
"use step"; // [!code highlight]
|
|
335
335
|
await db.orders.insert({ // [!code highlight]
|
|
@@ -355,7 +355,7 @@ class Order {
|
|
|
355
355
|
}
|
|
356
356
|
```
|
|
357
357
|
|
|
358
|
-
The class can then be used naturally inside a workflow function. Instance methods marked with `"use step"` are each executed as a step
|
|
358
|
+
The class can then be used naturally inside a workflow function. Instance methods marked with `"use step"` are each executed as a step, with automatic caching, retry semantics, and full Node.js runtime access. Methods _without_ `"use step"` run directly in the workflow context, so they must follow the same constraints as workflow functions:
|
|
359
359
|
|
|
360
360
|
{/* @expect-error:2693 */}
|
|
361
361
|
|
|
@@ -369,7 +369,7 @@ export async function processOrderWorkflow(
|
|
|
369
369
|
|
|
370
370
|
const order = new Order(orderId, items, new Date()); // [!code highlight]
|
|
371
371
|
|
|
372
|
-
// Runs in the workflow context
|
|
372
|
+
// Runs in the workflow context; no "use step" needed
|
|
373
373
|
const itemCount = order.total(); // [!code highlight]
|
|
374
374
|
|
|
375
375
|
// Each "use step" instance method call runs as a separate step
|
|
@@ -380,7 +380,7 @@ export async function processOrderWorkflow(
|
|
|
380
380
|
}
|
|
381
381
|
```
|
|
382
382
|
|
|
383
|
-
|
|
383
|
+
[Pass-by-value semantics](#pass-by-value-semantics) also apply to the `this` context of `"use step"` instance methods. Modifying instance properties inside a step method will not affect the original instance in the workflow. If you need to update instance state, return `this` from the step method and re-assign the variable in the workflow:
|
|
384
384
|
|
|
385
385
|
{/* @expect-error:2351 */}
|
|
386
386
|
|
|
@@ -408,4 +408,3 @@ export async function processOrderWorkflow() {
|
|
|
408
408
|
order = await order.addItem("Widget", 3); // [!code highlight]
|
|
409
409
|
}
|
|
410
410
|
```
|
|
411
|
-
|