@upstash/workflow 1.4.0 → 1.5.1-canary.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 +375 -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 +575 -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 +114 -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 +2946 -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,438 @@
1
+ ---
2
+ title: "Payment Retries"
3
+ ---
4
+
5
+ This example demonstrates a payment retry process using Upstash Workflow.
6
+ The following example handles retrying a payment, sending emails, and suspending accounts.
7
+
8
+ ## Use Case
9
+
10
+ Our workflow will:
11
+
12
+ 1. Attempt to process a payment
13
+ 2. Retry the payment if it fails with a 24-hour delay
14
+ 3. If the payment succeeds:
15
+ - Unsuspend the user's account if it was suspended
16
+ - Send an invoice email
17
+ 4. If the payment fails after 3 retries:
18
+ - Suspend the user's account
19
+
20
+ ## Code Example
21
+
22
+ <CodeGroup>
23
+
24
+ ```typescript api/workflow/route.ts
25
+ import { serve } from "@upstash/workflow/nextjs";
26
+
27
+ type ChargeUserPayload = {
28
+ email: string;
29
+ };
30
+
31
+ export const { POST } = serve<ChargeUserPayload>(async (context) => {
32
+ const { email } = context.requestPayload;
33
+
34
+ for (let i = 0; i < 3; i++) {
35
+ // attempt to charge the user
36
+ const result = await context.run("charge customer", async () => {
37
+ try {
38
+ return await chargeCustomer(i + 1)
39
+ } catch (e) {
40
+ console.error(e);
41
+ return
42
+ }
43
+ });
44
+
45
+ if (!result) {
46
+ // Wait for a day
47
+ await context.sleep("wait for retry", 24 * 60 * 60);
48
+ } else {
49
+ // Unsuspend User
50
+ const isSuspended = await context.run("check suspension", async () => {
51
+ return await checkSuspension(email);
52
+ });
53
+ if (isSuspended) {
54
+ await context.run("unsuspend user", async () => {
55
+ await unsuspendUser(email);
56
+ });
57
+ }
58
+
59
+ // send invoice email
60
+ await context.run("send invoice email", async () => {
61
+ await sendEmail(
62
+ email,
63
+ `Payment successful. Invoice: ${result.invoiceId}, Total cost: $${result.totalCost}`
64
+ );
65
+ });
66
+
67
+ // by returning, we end the workflow run
68
+ return;
69
+ }
70
+ }
71
+
72
+ // suspend user if the user isn't suspended
73
+ const isSuspended = await context.run("check suspension", async () => {
74
+ return await checkSuspension(email);
75
+ });
76
+
77
+ if (!isSuspended) {
78
+ await context.run("suspend user", async () => {
79
+ await suspendUser(email);
80
+ });
81
+
82
+ await context.run("send suspended email", async () => {
83
+ await sendEmail(
84
+ email,
85
+ "Your account has been suspended due to payment failure. Please update your payment method."
86
+ );
87
+ });
88
+ }
89
+ });
90
+
91
+ async function sendEmail(email: string, content: string) {
92
+ // Implement the logic to send an email
93
+ console.log("Sending email to", email, "with content:", content);
94
+ }
95
+
96
+ async function checkSuspension(email: string) {
97
+ // Implement the logic to check if the user is suspended
98
+ console.log("Checking suspension status for", email);
99
+ return true;
100
+ }
101
+
102
+ async function suspendUser(email: string) {
103
+ // Implement the logic to suspend the user
104
+ console.log("Suspending the user", email);
105
+ }
106
+
107
+ async function unsuspendUser(email: string) {
108
+ // Implement the logic to unsuspend the user
109
+ console.log("Unsuspending the user", email);
110
+ }
111
+
112
+ async function chargeCustomer(attempt: number) {
113
+ // Implement the logic to charge the customer
114
+ console.log("Charging the customer");
115
+
116
+ if (attempt <= 2) {
117
+ throw new Error("Payment failed");
118
+ }
119
+
120
+ return {
121
+ invoiceId: "INV123",
122
+ totalCost: 100,
123
+ } as const;
124
+ }
125
+ ```
126
+
127
+ ```python main.py
128
+ from fastapi import FastAPI
129
+ from typing import TypedDict, Optional
130
+ from dataclasses import dataclass
131
+ from upstash_workflow.fastapi import Serve
132
+ from upstash_workflow import AsyncWorkflowContext
133
+
134
+ app = FastAPI()
135
+ serve = Serve(app)
136
+
137
+
138
+ @dataclass
139
+ class ChargeResult:
140
+ invoice_id: str
141
+ total_cost: float
142
+
143
+
144
+ class ChargeUserPayload(TypedDict):
145
+ email: str
146
+
147
+
148
+ async def send_email(email: str, content: str) -> None:
149
+ # Implement the logic to send an email
150
+ print("Sending email to", email, "with content:", content)
151
+
152
+
153
+ async def check_suspension(email: str) -> bool:
154
+ # Implement the logic to check if the user is suspended
155
+ print("Checking suspension status for", email)
156
+ return True
157
+
158
+
159
+ async def suspend_user(email: str) -> None:
160
+ # Implement the logic to suspend the user
161
+ print("Suspending the user", email)
162
+
163
+
164
+ async def unsuspend_user(email: str) -> None:
165
+ # Implement the logic to unsuspend the user
166
+ print("Unsuspending the user", email)
167
+
168
+
169
+ async def charge_customer(attempt: int) -> Optional[ChargeResult]:
170
+ # Implement the logic to charge the customer
171
+ print("Charging the customer")
172
+ if attempt <= 2:
173
+ raise Exception("Payment failed")
174
+ return ChargeResult(invoice_id="INV123", total_cost=100)
175
+
176
+
177
+ @serve.post("/payment-retries")
178
+ async def payment_retries(context: AsyncWorkflowContext[ChargeUserPayload]) -> None:
179
+ email = context.request_payload["email"]
180
+
181
+ async def _check_suspension() -> bool:
182
+ return await check_suspension(email)
183
+
184
+ for i in range(3):
185
+ # attempt to charge the user
186
+ async def _charge_customer() -> Optional[ChargeResult]:
187
+ try:
188
+ return await charge_customer(i + 1)
189
+ except Exception as e:
190
+ print(f"Error: {e}")
191
+ return None
192
+
193
+ result = await context.run("charge customer", _charge_customer)
194
+
195
+ if not result:
196
+ # Wait for a day
197
+ await context.sleep("wait for retry", 24 * 60 * 60)
198
+ else:
199
+ # Unsuspend User
200
+ is_suspended = await context.run("check suspension", _check_suspension)
201
+
202
+ if is_suspended:
203
+
204
+ async def _unsuspend_user() -> None:
205
+ await unsuspend_user(email)
206
+
207
+ await context.run("unsuspend user", _unsuspend_user)
208
+
209
+ # send invoice email
210
+ async def _send_invoice_email() -> None:
211
+ await send_email(
212
+ email,
213
+ f"Payment successful. Invoice: {result.invoice_id}, Total cost: ${result.total_cost}",
214
+ )
215
+
216
+ await context.run("send invoice email", _send_invoice_email)
217
+
218
+ # by returning, we end the workflow run
219
+ return
220
+
221
+ # suspend user if the user isn't suspended
222
+ is_suspended = await context.run("check suspension", _check_suspension)
223
+
224
+ if not is_suspended:
225
+
226
+ async def _suspend_user() -> None:
227
+ await suspend_user(email)
228
+
229
+ await context.run("suspend user", _suspend_user)
230
+
231
+ async def _send_suspended_email() -> None:
232
+ await send_email(
233
+ email,
234
+ "Your account has been suspended due to payment failure. Please update your payment method.",
235
+ )
236
+
237
+ await context.run("send suspended email", _send_suspended_email)
238
+
239
+ ```
240
+
241
+ </CodeGroup>
242
+
243
+ ## Code Breakdown
244
+
245
+ ### 1. Charge Customer
246
+ We attempt to charge the customer:
247
+
248
+ <CodeGroup>
249
+
250
+ ```typescript TypeScript
251
+ const result = await context.run("charge customer", async () => {
252
+ try {
253
+ return await chargeCustomer(i + 1),
254
+ } catch (e) {
255
+ console.error(e);
256
+ return
257
+ }
258
+ });
259
+ ```
260
+
261
+ ```python Python
262
+ async def _charge_customer() -> Optional[ChargeResult]:
263
+ try:
264
+ return await charge_customer(i + 1)
265
+ except Exception as e:
266
+ print(f"Error: {e}")
267
+ return None
268
+
269
+ result = await context.run("charge customer", _charge_customer)
270
+
271
+ ```
272
+
273
+ </CodeGroup>
274
+
275
+ <Note>
276
+ If we haven't put a try-catch block here, the workflow would have retried the step.
277
+ However, because we want to run custom logic when the payment fails, we catch the error here.
278
+ </Note>
279
+
280
+ ### 2. Retry Payment
281
+
282
+ We try to charge the customer 3 times with a 24-hour delay between each attempt:
283
+
284
+ <CodeGroup>
285
+
286
+ ```typescript TypeScript
287
+ for (let i = 0; i < 3; i++) {
288
+ // attempt to charge the customer
289
+
290
+ if (!result) {
291
+ // Wait for a day
292
+ await context.sleep("wait for retry", 24 * 60 * 60);
293
+ } else {
294
+ // Payment succeeded
295
+ // Unsuspend user, send invoice email
296
+ // end the workflow:
297
+ return;
298
+ }
299
+ }
300
+ ```
301
+
302
+ ```python Python
303
+ for i in range(3):
304
+ # attempt to charge the customer
305
+
306
+ if not result:
307
+ # Wait for a day
308
+ await context.sleep("wait for retry", 24 * 60 * 60)
309
+ else:
310
+ # Payment succeeded
311
+ # Unsuspend user, send invoice email
312
+ # end the workflow:
313
+ return
314
+
315
+ ```
316
+
317
+ </CodeGroup>
318
+
319
+ ### 3. If Payment Succeeds
320
+
321
+ #### 3.1. Unsuspend User
322
+
323
+ We check if the user is suspended and unsuspend them if they are:
324
+
325
+ <CodeGroup>
326
+
327
+ ```typescript TypeScript
328
+ const isSuspended = await context.run("check suspension", async () => {
329
+ return await checkSuspension(email);
330
+ });
331
+ if (isSuspended) {
332
+ await context.run("unsuspend user", async () => {
333
+ await unsuspendUser(email);
334
+ });
335
+ }
336
+ ```
337
+
338
+ ```python Python
339
+ async def _check_suspension() -> bool:
340
+ return await check_suspension(email)
341
+
342
+ is_suspended = await context.run("check suspension", _check_suspension)
343
+
344
+ if is_suspended:
345
+
346
+ async def _unsuspend_user() -> None:
347
+ await unsuspend_user(email)
348
+
349
+ await context.run("unsuspend user", _unsuspend_user)
350
+
351
+ ```
352
+
353
+ </CodeGroup>
354
+
355
+ #### 3.2. Send Invoice Email
356
+
357
+ We send an invoice we got from the payment step to the user:
358
+
359
+ <CodeGroup>
360
+
361
+ ```typescript TypeScript
362
+ await context.run("send invoice email", async () => {
363
+ await sendEmail(
364
+ email,
365
+ `Payment successful. Invoice: ${result.invoiceId}, Total cost: $${result.totalCost}`
366
+ );
367
+ });
368
+ ```
369
+
370
+ ```python Python
371
+ async def _send_invoice_email() -> None:
372
+ await send_email(
373
+ email,
374
+ f"Payment successful. Invoice: {result.invoice_id}, Total cost: ${result.total_cost}",
375
+ )
376
+
377
+ await context.run("send invoice email", _send_invoice_email)
378
+
379
+ ```
380
+
381
+ </CodeGroup>
382
+
383
+ <Tip>
384
+ One of the biggest advantages of using Upstash Workflow is that you have access to the result of the previous steps.
385
+ This allows you to pass data between steps without having to store it in a database.
386
+ </Tip>
387
+
388
+ ### 4. If Payment Fails After 3 Retries
389
+
390
+ #### 4.1. Suspend User
391
+
392
+ If the payment fails after 3 retries, we suspend the user and send them an email to notify them:
393
+
394
+ <CodeGroup>
395
+
396
+ ```typescript TypeScript
397
+ const isSuspended = await context.run("check suspension", async () => {
398
+ return await checkSuspension(email);
399
+ });
400
+
401
+ if (!isSuspended) {
402
+ await context.run("suspend user", async () => {
403
+ await suspendUser(email);
404
+ });
405
+
406
+ await context.run("send suspended email", async () => {
407
+ await sendEmail(
408
+ context.requestPayload.email,
409
+ "Your account has been suspended due to payment failure. Please update your payment method."
410
+ );
411
+ });
412
+ }
413
+ ```
414
+
415
+ ```python Python
416
+ async def _check_suspension() -> bool:
417
+ return await check_suspension(email)
418
+
419
+ is_suspended = await context.run("check suspension", _check_suspension)
420
+
421
+ if not is_suspended:
422
+
423
+ async def _suspend_user() -> None:
424
+ await suspend_user(email)
425
+
426
+ await context.run("suspend user", _suspend_user)
427
+
428
+ async def _send_suspended_email() -> None:
429
+ await send_email(
430
+ email,
431
+ "Your account has been suspended due to payment failure. Please update your payment method.",
432
+ )
433
+
434
+ await context.run("send suspended email", _send_suspended_email)
435
+
436
+ ```
437
+
438
+ </CodeGroup>
@@ -0,0 +1,201 @@
1
+ ---
2
+ title: "Waiting for Events"
3
+ ---
4
+
5
+ <Note>
6
+ This feature is not yet available in
7
+ [workflow-py](https://github.com/upstash/workflow-py). See our
8
+ [Roadmap](/workflow/roadmap) for feature parity plans and
9
+ [Changelog](/workflow/changelog) for updates.
10
+ </Note>
11
+
12
+ ## Introduction
13
+
14
+ This example demonstrates how to handle order processing using Upstash Workflow. The workflow will wait for an external system to process an order and resume once it is 'notified'. See our documentation [for more details about events](/workflow/features/wait-for-event).
15
+
16
+ ## Use Case
17
+
18
+ Our workflow will be:
19
+
20
+ 1. Receive an order request.
21
+ 2. Send an email to request order processing.
22
+ 3. Wait for an external event that indicates the order has been processed.
23
+ 4. Handle timeout scenarios if the event is not received in time.
24
+ 5. Save the results
25
+
26
+ ## Code Example
27
+
28
+ ```typescript
29
+ import { serve } from "@upstash/workflow/nextjs";
30
+
31
+ export const { POST } = serve(async (context) => {
32
+ const { orderId, userEmail } = context.requestPayload;
33
+
34
+ // Step 1: request order processing
35
+ await context.run("request order processing", async () => {
36
+ await requestProcessing(orderId)
37
+ })
38
+
39
+ // Step 2: Wait for the order to be processed
40
+ const { eventData, timeout } = await context.waitForEvent(
41
+ "wait for order processing",
42
+ `order-${orderId}`,
43
+ {
44
+ timeout: "10m" // 10 minutes timeout
45
+ }
46
+ );
47
+
48
+ if (timeout) {
49
+ // end workflow in case of timeout
50
+ return;
51
+ }
52
+
53
+ const processedData = eventData;
54
+
55
+ // Step 3: Log the processed order
56
+ await context.run("process-order", async () => {
57
+ console.log(`Order ${orderId} processed:`, processedData);
58
+ });
59
+
60
+ // Step 4: Send a confirmation email
61
+ await context.run("send-confirmation-email", async () => {
62
+ await sendEmail(
63
+ userEmail,
64
+ "Your order has been processed!",
65
+ processedData
66
+ );
67
+ });
68
+ });
69
+ ```
70
+
71
+ Code for notifying the workflow:
72
+
73
+ ```typescript
74
+ import { Client } from "@upstash/workflow";
75
+
76
+ const client = new Client({ token: "<QSTASH_TOKEN>" })
77
+ const orderId = "1324"
78
+
79
+ await client.notify({
80
+ eventId: `order-${orderId}`,
81
+ eventData: { deliveryTime: "2 days" }
82
+ });
83
+ ```
84
+
85
+ ## Code Breakdown
86
+
87
+ ### 1. Requesting Order Processing
88
+
89
+ In its first step, we call a method to request processing of the order in the request payload:
90
+
91
+ ```typescript
92
+ await context.run("request order processing", async () => {
93
+ await requestProcessing(orderId)
94
+ })
95
+ ```
96
+
97
+ You can imagine that this step sends an email to the company responsible for the delivery.
98
+
99
+ ### 2. Waiting for the Event
100
+
101
+ <Frame>
102
+ <img src="/img/qstash-workflow/events/wait.png" alt="Workflow run waiting for an event" />
103
+ </Frame>
104
+
105
+ Next, the workflow waits for the order to be processed. It uses [the `waitForEvent` method](/workflow/steps/waitForEvent) to pause execution and listen for the event. A timeout of 10 minutes (600 seconds) is applied to avoid indefinite waiting.
106
+
107
+ ```typescript
108
+ const { eventData, timeout } = await context.waitForEvent(
109
+ "wait for order processing",
110
+ `order-${orderId}`,
111
+ {
112
+ timeout: "10m" // 10 minutes timeout
113
+ }
114
+ );
115
+
116
+ if (timeout) {
117
+ // end workflow in case of timeout
118
+ return;
119
+ }
120
+ ```
121
+
122
+ The workflow listens for the event with the ID `order-${orderId}`. When the external service notifies the workflow with this ID, the workflow resumes. If no event is received in time, the timeout ensures the workflow doesn't hang.
123
+
124
+ ### 3. Processing the Order
125
+
126
+ <Frame>
127
+ <img src="/img/qstash-workflow/events/resume.png" alt="Workflow run resumed by an event" />
128
+ </Frame>
129
+
130
+ Once the workflow resumes, the order data (`eventData`) is logged. This step could include updates to the database, inventory adjustments, or other backend operations specific to order processing.
131
+
132
+ ```typescript
133
+ await context.run("process-order", async () => {
134
+ console.log(`Order ${orderId} processed:`, processedData);
135
+ });
136
+ ```
137
+
138
+ ### 4. Sending a Confirmation Email
139
+
140
+ Once the order is processed, the workflow sends a confirmation email to the user.
141
+
142
+ ```typescript
143
+ await context.run("send-confirmation-email", async () => {
144
+ await sendEmail(
145
+ userEmail,
146
+ "Your order has been processed!",
147
+ processedData
148
+ );
149
+ });
150
+ ```
151
+
152
+ ## External Event Notification
153
+
154
+ To notify the workflow that the order has been processed, the external system sends a notification to the workflow with relevant data using the [`notify` method from the `Client`](/workflow/basics/client/notify). Alternatively, you can use [`context.notify` method](/workflow/steps/notify).
155
+
156
+ ```typescript
157
+ import { Client } from "@upstash/workflow";
158
+
159
+ const client = new Client({ token: "<QSTASH_TOKEN>" });
160
+ const orderId = "1324";
161
+
162
+ await client.notify({
163
+ eventId: `order-${orderId}`,
164
+ eventData: { deliveryTime: "2 days" }
165
+ });
166
+ ```
167
+
168
+ ## Preventing Race Conditions with Lookback
169
+
170
+ In some scenarios, the notification might arrive before the workflow reaches the `waitForEvent` step, creating a race condition. To prevent this, you can use the `workflowRunId` parameter to enable lookback:
171
+
172
+ ```typescript
173
+ import { Client } from "@upstash/workflow";
174
+
175
+ const client = new Client({ token: "<QSTASH_TOKEN>" });
176
+
177
+ // Trigger the workflow and get its run ID
178
+ const { workflowRunId } = await client.trigger({
179
+ url: "https://your-app.com/api/order-workflow",
180
+ body: { orderId: "1324", userEmail: "user@example.com" }
181
+ });
182
+
183
+ // Immediately notify with lookback enabled
184
+ // The notification will be delivered even if the workflow
185
+ // hasn't reached waitForEvent yet
186
+ await client.notify({
187
+ eventId: `order-1324`,
188
+ eventData: { deliveryTime: "2 days" },
189
+ workflowRunId: workflowRunId, // Enables lookback
190
+ });
191
+ ```
192
+
193
+ This is especially useful when you need to trigger a workflow and immediately send it an event, without worrying about timing issues.
194
+
195
+ ## Key Features
196
+
197
+ 1. **Asynchronous Event Handling**: The workflow waits for an external event (order processing) to occur and only resumes once the event is received.
198
+ 2. **Timeout Control**: A timeout mechanism ensures that the workflow doesn't hang if the event isn't received within the expected time.
199
+ 3. **Order Processing**: Once notified, the workflow handles order processing and sends a confirmation email to the customer.
200
+ 4. **External Event Notifications**: The external system can notify the workflow, providing the necessary data to resume execution and complete the process.
201
+ 5. **Race Condition Prevention**: Using `workflowRunId` with lookback ensures notifications are never lost due to timing issues.
@@ -0,0 +1,42 @@
1
+ ---
2
+ title: "Rerun Failure Function"
3
+ ---
4
+
5
+ The **Rerun Failure Function** action allows you to retry the failure function that executes when a workflow run enters the Dead Letter Queue (DLQ).
6
+
7
+ The failure function is typically a cleanup or notification operation that runs automatically whenever a workflow is moved to the DLQ.
8
+
9
+ This feature is particularly helpful for:
10
+
11
+ - Ensuring that important cleanup operations are executed.
12
+ - Guaranteeing that logging or alerting is completed after a workflow failure.
13
+ - Recovering from temporary errors in the failure function itself.
14
+
15
+ By manually rerunning this function, you can ensure that critical operations—such as cleanup tasks, logging, or alerting—complete successfully even if the main workflow has failed.
16
+
17
+
18
+ <Frame caption="You can retry the failure function of a workflow run if it has failed">
19
+ <img src="/img/workflow/retry_failure_callback.png" alt="Retry a failed workflow callback" />
20
+ </Frame>
21
+
22
+ You can perform this action programmatically as well:
23
+
24
+ <CodeGroup>
25
+ ```typescript TypeScript
26
+ import { Client } from "@upstash/workflow";
27
+
28
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
29
+
30
+ await client.dlq.retryFailureFunction({
31
+ dlqId: "dlq-12345",
32
+ });
33
+ ```
34
+ </CodeGroup>
35
+
36
+ <Note>
37
+ This action is only available if the failure function itself has failed as well.
38
+ If the failure function already succeeded, it cannot be rerun.
39
+
40
+ You can view the status of the failure function in the **DLQ** and **Logs** dashboards, which indicate whether it succeeded or failed.
41
+ </Note>
42
+
@@ -0,0 +1,29 @@
1
+ ---
2
+ title: "Delete"
3
+ ---
4
+
5
+ The **Delete** action allows you to remove failed workflow runs from the Dead Letter Queue when no recovery action is needed.
6
+
7
+ You can delete entries individually, in bulk by IDs, or by using filters such as label, URL, or date range.
8
+
9
+ <CodeGroup>
10
+ ```typescript TypeScript
11
+ import { Client } from "@upstash/workflow";
12
+
13
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
14
+
15
+ // delete a single entry
16
+ await client.dlq.delete("dlq-12345");
17
+
18
+ // delete multiple entries
19
+ await client.dlq.delete(["dlq-12345", "dlq-67890"]);
20
+
21
+ // delete by filters
22
+ await client.dlq.delete({ filter: { label: "my-label" } });
23
+
24
+ // delete all
25
+ await client.dlq.delete({ all: true });
26
+ ```
27
+ </CodeGroup>
28
+
29
+ For the full API reference, see [client.dlq.delete](/workflow/basics/client/dlq/delete).