@upstash/workflow 1.4.0 → 1.5.0

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.
Files changed (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
@@ -0,0 +1,203 @@
1
+ ---
2
+ title: "Dynamic Workflows"
3
+ ---
4
+
5
+ This example demonstrates how to build **dynamic, configurable workflows** using Upstash Workflow, while safely handling ordering, naming, and versioning constraints.
6
+ The workflow dynamically executes a list of steps provided at runtime, allowing different customers or versions to run different flows, without breaking the workflow resolution mechanism.
7
+
8
+ ## Use Case
9
+
10
+ Our workflow will:
11
+
12
+ 1. Receive a list of steps to execute
13
+ 2. Execute each step **in order**, one by one
14
+ 3. Persist step results between requests
15
+ 4. Support multiple workflow versions with different step orders
16
+ 5. Ensure workflows do not break when retried or resumed
17
+
18
+ This pattern is useful when:
19
+
20
+ * Customers want dynamic workflows with different type of steps and ordering
21
+ * Workflow logic is driven by configuration
22
+ * You need safe retries, resumes, and idempotency
23
+
24
+ ## Code Example
25
+
26
+ <CodeGroup>
27
+
28
+ ```typescript api/workflow/route.ts
29
+ import { WorkflowNonRetryableError } from "@upstash/workflow";
30
+ import { serve } from "@upstash/workflow/nextjs";
31
+
32
+ const addOne = (data: number): number => {
33
+ return data + 1
34
+ }
35
+
36
+ const multiplyWithTwo = (data: number): number => {
37
+ return data * 2
38
+ }
39
+
40
+ type FunctionName = "AddOne" | "MultiplyWithTwo"
41
+
42
+ const functions: Record<FunctionName, (data: number) => number> = {
43
+ AddOne: addOne,
44
+ MultiplyWithTwo: multiplyWithTwo,
45
+ }
46
+
47
+ interface WorkflowPayload {
48
+ version: string
49
+ functions: FunctionName[]
50
+ }
51
+
52
+ export const { POST } = serve<WorkflowPayload>(async (context) => {
53
+ const { functions: steps } = context.requestPayload
54
+
55
+ let lastResult = 0
56
+
57
+ for (let i = 0; i < steps.length; i++) {
58
+ const stepName = steps[i]
59
+
60
+ lastResult = await context.run(
61
+ `step-${i}:${stepName}`,
62
+ async () => {
63
+ const fn = functions[stepName]
64
+ if (!fn) throw new WorkflowNonRetryableError("Unknown step")
65
+ return fn(lastResult)
66
+ }
67
+ )
68
+ }
69
+ })
70
+ ```
71
+ </CodeGroup>
72
+
73
+ ## Code Breakdown
74
+
75
+ ### 1. Dynamic Step Configuration
76
+
77
+ Instead of hardcoding the workflow, we accept a **list of step names** from the request payload.
78
+ <CodeGroup>
79
+ ```typescript api/workflow/route.ts
80
+ interface WorkflowPayload {
81
+ version: string
82
+ functions: FunctionName[]
83
+ }
84
+ ```
85
+ </CodeGroup>
86
+
87
+ This allows different customers or versions to define workflow flows such as:
88
+
89
+ * Run X: `AddOne → MultiplyWithTwo`
90
+ * Run Y: `MultiplyWithTwo → AddOne → AddOne`
91
+ * Run Z: `AddOne`
92
+
93
+ <Info>Instead of passing the step list in the request payload, you can store it somewhere else and fetch it inside the workflow as well.</Info>
94
+
95
+ ### 2. Executing Steps One by One
96
+
97
+ At first glance, the `for` loop looks like a normal synchronous loop. However, in Upstash Workflow, **each iteration of the loop (in other terms, every step) is executed across multiple HTTP requests**, not in a single function invocation.
98
+
99
+ <CodeGroup>
100
+ ```typescript api/workflow/route.ts
101
+ let lastResult = 0
102
+
103
+ for (let i = 0; i < steps.length; i++) {
104
+ const stepName = steps[i]
105
+
106
+ lastResult = await context.run(
107
+ `step-${i}:${stepName}`,
108
+ async () => {
109
+ const fn = functions[stepName]
110
+ if (!fn) throw new WorkflowNonRetryableError("Unknown step")
111
+ return fn(lastResult)
112
+ }
113
+ )
114
+ }
115
+ ```
116
+ </CodeGroup>
117
+
118
+ Here is what actually happens behind the scenes:
119
+
120
+ **First request**
121
+ 1. The workflow endpoint is called with the initial payload.
122
+ 2. The loop starts at `i = 0`.
123
+ 3. `context.run("step-0:AddOne")` is encountered.
124
+ 4. Since this step has never run before, Upstash executes the function body.
125
+ 5. The result is stored in durable state.
126
+ 6. The HTTP request ends immediately after this step completes.
127
+
128
+ **Second request**
129
+ 1. Upstash triggers the workflow endpoint again.
130
+ 2. The request payload now includes the result of `step-0`.
131
+ 3. The loop runs again from the beginning.
132
+ 4. `context.run("step-0:AddOne")` is encountered, but it is **skipped** because it already exists in state.
133
+ 5. The loop continues to `i = 1`.
134
+ 6. `context.run("step-1:MultiplyWithTwo")` executes.
135
+ 7. The result is persisted, and the request ends.
136
+
137
+ **Subsequent requests**
138
+ - This process repeats until every step in the loop has been executed exactly once.
139
+ - Each iteration of the loop corresponds to a **separate HTTP execution**.
140
+
141
+ This is critical — **each logical step must be isolated in its own `context.run` call** so the workflow engine can:
142
+ - Resume execution safely
143
+ - Skip completed work
144
+ - Retry failed steps independently
145
+ - Guarantee exactly-once execution semantics
146
+
147
+ If you place multiple logical operations inside a single `context.run`, the engine cannot resume partway through that logic.
148
+
149
+ ### 3. Step Naming and Ordering
150
+
151
+ Upstash Workflow identifies steps using:
152
+
153
+ - The **order** of `context.run` calls
154
+ - The **step name** passed to `context.run`
155
+
156
+ For a given workflow execution:
157
+ - Step names **must not change** between retries
158
+ - Step order **must remain the same**
159
+
160
+ Changing either will break the resolve mechanism.
161
+
162
+ ### 4. Versioning Workflows Safely
163
+
164
+ If you want to change:
165
+ - Step order
166
+ - Step names
167
+ - Number of steps
168
+
169
+ You must create a **new version**:
170
+
171
+ - Keep old versions immutable
172
+ - Route versions inside the same endpoint if needed
173
+ - Ensure each version always executes the same flow
174
+
175
+ Example:
176
+
177
+ - `version = v1` → `AddOne → MultiplyWithTwo`
178
+ - `version = v2` → `MultiplyWithTwo → AddOne`
179
+
180
+ As long as each version is internally consistent, the workflow will work correctly.
181
+
182
+ ### 5. How the Step Result Resolve Mechanism Works
183
+
184
+ Behind the scenes, the workflow endpoint is called multiple times.
185
+
186
+ On each request:
187
+
188
+ 1. The request contains the initial payload
189
+ 2. Plus results of already executed steps
190
+ 3. The engine determines which step is next
191
+ 4. Only the next step is executed
192
+
193
+ As long as the workflow definition does **not change**, execution resumes correctly.
194
+
195
+ ### 6. Common Pitfalls
196
+
197
+ Avoid the following:
198
+
199
+ - ❌ Running multiple logical steps inside a single `context.run`
200
+ - ❌ Changing step names and order between executions
201
+ - ❌ Conditional execution based on non-deterministic logic (`Math.random`, `Date.now`)
202
+
203
+ All workflow logic must be **idempotent**.
@@ -0,0 +1,281 @@
1
+ ---
2
+ title: "E-commerce Order Fulfillment"
3
+ ---
4
+
5
+ ## Introduction
6
+
7
+ This example demonstrates an automated e-commerce order fulfillment process using Upstash Workflow. The workflow takes an order, verifies the stock, processes the payment, and handles order dispatch and customer notifications.
8
+
9
+ ## Use Case
10
+
11
+ Our workflow will:
12
+
13
+ 1. Receive an order request
14
+ 2. Verify the availability of the items in stock
15
+ 3. Process the payment
16
+ 4. Initiate the dispatch of the order
17
+ 5. Send confirmation and delivery notifications to the customer
18
+
19
+ ## Code Example
20
+
21
+ <CodeGroup>
22
+
23
+ ```typescript api/workflow/route.ts
24
+ import { serve } from "@upstash/workflow/nextjs"
25
+ import {
26
+ createOrderId,
27
+ checkStockAvailability,
28
+ processPayment,
29
+ dispatchOrder,
30
+ sendOrderConfirmation,
31
+ sendDispatchNotification,
32
+ } from "./utils"
33
+
34
+ type OrderPayload = {
35
+ userId: string
36
+ items: { productId: string, quantity: number }[]
37
+ }
38
+
39
+ export const { POST } = serve<OrderPayload>(async (context) => {
40
+ const { userId, items } = context.requestPayload;
41
+
42
+ // Step 1: Create Order Id
43
+ const orderId = await context.run("create-order-id", async () => {
44
+ return await createOrderId(userId);
45
+ });
46
+
47
+ // Step 2: Verify stock availability
48
+ const stockAvailable = await context.run("check-stock", async () => {
49
+ return await checkStockAvailability(items);
50
+ });
51
+
52
+ if (!stockAvailable) {
53
+ console.warn("Some items are out of stock");
54
+ return;
55
+ };
56
+
57
+ // Step 3: Process payment
58
+ await context.run("process-payment", async () => {
59
+ return await processPayment(orderId)
60
+ })
61
+
62
+ // Step 4: Dispatch the order
63
+ await context.run("dispatch-order", async () => {
64
+ return await dispatchOrder(orderId, items)
65
+ })
66
+
67
+ // Step 5: Send order confirmation email
68
+ await context.run("send-confirmation", async () => {
69
+ return await sendOrderConfirmation(userId, orderId)
70
+ })
71
+
72
+ // Step 6: Send dispatch notification
73
+ await context.run("send-dispatch-notification", async () => {
74
+ return await sendDispatchNotification(userId, orderId)
75
+ })
76
+ })
77
+ ```
78
+
79
+ ```python main.py
80
+ from fastapi import FastAPI
81
+ from typing import List, TypedDict
82
+ from upstash_workflow.fastapi import Serve
83
+ from upstash_workflow import AsyncWorkflowContext
84
+ from utils import (
85
+ create_order_id,
86
+ check_stock_availability,
87
+ process_payment,
88
+ dispatch_order,
89
+ send_order_confirmation,
90
+ send_dispatch_notification,
91
+ )
92
+
93
+ app = FastAPI()
94
+ serve = Serve(app)
95
+
96
+
97
+ class OrderItem(TypedDict):
98
+ product_id: str
99
+ quantity: int
100
+
101
+
102
+ class OrderPayload(TypedDict):
103
+ user_id: str
104
+ items: List[OrderItem]
105
+
106
+
107
+ @serve.post("/order-fulfillment")
108
+ async def order_fulfillment(context: AsyncWorkflowContext[OrderPayload]) -> None:
109
+ # Get the order payload from the request
110
+ payload = context.request_payload
111
+ user_id = payload["user_id"]
112
+ items = payload["items"]
113
+
114
+ # Step 1: Create Order Id
115
+ async def _create_order_id():
116
+ return await create_order_id(user_id)
117
+
118
+ order_id: str = await context.run("create-order-id", _create_order_id)
119
+
120
+ # Step 2: Verify stock availability
121
+ async def _check_stock():
122
+ return await check_stock_availability(items)
123
+
124
+ stock_available: bool = await context.run("check-stock", _check_stock)
125
+
126
+ if not stock_available:
127
+ print("Some items are out of stock")
128
+ return
129
+
130
+ # Step 3: Process payment
131
+ async def _process_payment():
132
+ return await process_payment(order_id)
133
+
134
+ await context.run("process-payment", _process_payment)
135
+
136
+ # Step 4: Dispatch the order
137
+ async def _dispatch_order():
138
+ return await dispatch_order(order_id, items)
139
+
140
+ await context.run("dispatch-order", _dispatch_order)
141
+
142
+ # Step 5: Send order confirmation email
143
+ async def _send_confirmation():
144
+ return await send_order_confirmation(user_id, order_id)
145
+
146
+ await context.run("send-confirmation", _send_confirmation)
147
+
148
+ # Step 6: Send dispatch notification
149
+ async def _send_dispatch_notification():
150
+ return await send_dispatch_notification(user_id, order_id)
151
+
152
+ await context.run("send-dispatch-notification", _send_dispatch_notification)
153
+
154
+ ```
155
+
156
+ </CodeGroup>
157
+
158
+ ## Code Breakdown
159
+
160
+ ### 1. Verifying Stock Availability
161
+
162
+ We start by creating an order id and verifying if the items in the order are available in stock. If not, we throw an error to halt the process:
163
+
164
+ <CodeGroup>
165
+
166
+ ```typescript api/workflow/route.ts
167
+ const orderId = await context.run("create-order-id", async () => {
168
+ return await createOrderId(userId);
169
+ });
170
+
171
+ const stockAvailable = await context.run("check-stock", async () => {
172
+ return await checkStockAvailability(items)
173
+ })
174
+
175
+ if (!stockAvailable) {
176
+ console.warn("Some items are out of stock")
177
+ return;
178
+ }
179
+ ```
180
+
181
+ ```python main.py
182
+ async def _create_order_id():
183
+ return await create_order_id(user_id)
184
+
185
+ order_id: str = await context.run("create-order-id", _create_order_id)
186
+
187
+ async def _check_stock():
188
+ return await check_stock_availability(items)
189
+
190
+ stock_available: bool = await context.run("check-stock", _check_stock)
191
+
192
+ if not stock_available:
193
+ print("Some items are out of stock")
194
+ return
195
+
196
+ ```
197
+
198
+ </CodeGroup>
199
+
200
+ ### 2. Processing Payment
201
+
202
+ Once the stock is verified, the workflow processes the payment for the order:
203
+
204
+ <CodeGroup>
205
+
206
+ ```typescript api/workflow/route.ts
207
+ await context.run("process-payment", async () => {
208
+ return await processPayment(orderId)
209
+ })
210
+ ```
211
+
212
+ ```python main.py
213
+ async def _process_payment():
214
+ return await process_payment(order_id)
215
+
216
+ await context.run("process-payment", _process_payment)
217
+
218
+ ```
219
+
220
+ </CodeGroup>
221
+
222
+ ### 3. Dispatching the Order
223
+
224
+ After payment confirmation, we dispatch the order for delivery:
225
+
226
+ <CodeGroup>
227
+
228
+ ```typescript api/workflow/route.ts
229
+ await context.run("dispatch-order", async () => {
230
+ return await dispatchOrder(orderId, items)
231
+ })
232
+ ```
233
+
234
+ ```python main.py
235
+ async def _dispatch_order():
236
+ return await dispatch_order(order_id, items)
237
+
238
+ await context.run("dispatch-order", _dispatch_order)
239
+
240
+ ```
241
+
242
+ </CodeGroup>
243
+
244
+ ### 4. Sending Confirmation and Notification Emails
245
+
246
+ Lastly, we send an order confirmation email to the customer and notify them when the order is dispatched:
247
+
248
+ <CodeGroup>
249
+
250
+ ```typescript api/workflow/route.ts
251
+ await context.run("send-confirmation", async () => {
252
+ return await sendOrderConfirmation(userId, orderId)
253
+ })
254
+
255
+ await context.run("send-dispatch-notification", async () => {
256
+ return await sendDispatchNotification(userId, orderId)
257
+ })
258
+ ```
259
+
260
+ ```python main.py
261
+ async def _send_confirmation():
262
+ return await send_order_confirmation(user_id, order_id)
263
+
264
+ await context.run("send-confirmation", _send_confirmation)
265
+
266
+ async def _send_dispatch_notification():
267
+ return await send_dispatch_notification(user_id, order_id)
268
+
269
+ await context.run("send-dispatch-notification", _send_dispatch_notification)
270
+
271
+ ```
272
+
273
+ </CodeGroup>
274
+
275
+ ## Key Features
276
+
277
+ 1. **Stock Verification**: Ensures items are available in stock before processing the payment, avoiding issues with unavailable products.
278
+
279
+ 2. **Payment Processing**: Handles payment securely and only proceeds to dispatch if successful.
280
+
281
+ 3. **Customer Notifications**: Keeps the customer informed at each step of the order process, improving user experience.