@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,105 @@
1
+ ---
2
+ title: "context.notify"
3
+ ---
4
+
5
+ `context.notify()` notifies workflows that are waiting for a specific event, passing along an optional payload.
6
+
7
+ It is typically used in combination with [`context.waitForEvent`](/workflow/steps/waitForEvent).
8
+
9
+ ## Arguments
10
+
11
+ <ParamField body="stepName" type="string">
12
+ A unique identifier for the step.
13
+ </ParamField>
14
+
15
+ <ParamField body="eventId" type="string">
16
+ The identifier of the event to notify.
17
+ Must match the `eventId` used in `context.waitForEvent`.
18
+ </ParamField>
19
+
20
+ <ParamField body="eventData" type="any">
21
+ Data to deliver to the waiting workflow(s).
22
+ This value will be returned in `eventData` from the corresponding `waitForEvent` call.
23
+ </ParamField>
24
+
25
+ <ParamField body="workflowRunId" type="string" optional>
26
+ The workflow run ID to notify. When provided, enables **lookback functionality** - the notification will be stored and delivered even if `notify` is called before `waitForEvent`.
27
+
28
+ This solves race conditions where notifications might be sent before a workflow reaches its wait step.
29
+ </ParamField>
30
+
31
+ ## Response
32
+
33
+ `context.notify()` returns an object containing the notified event and the list of workflows that were notified.
34
+
35
+ <ResponseField name="eventId" type="string">
36
+ The event ID that was notified.
37
+ </ResponseField>
38
+
39
+ <ResponseField name="eventData" type="any">
40
+ The event data sent with the notification.
41
+ </ResponseField>
42
+
43
+ <ResponseField name="notifyResponse" type="NotifyResponse[]">
44
+ A list of `NotifyResponse` objects, one for each workflow that was waiting on the event.
45
+ An empty list means no workflow was waiting.
46
+
47
+ <Expandable defaultOpen>
48
+ <ResponseField name="messageId" type="string">
49
+ The ID of the notification message delivered to the workflow.
50
+ This is unique to every notification.
51
+ </ResponseField>
52
+
53
+ <ResponseField name="error" type="string">
54
+ Error message if delivering the notification to this waiter failed.
55
+ </ResponseField>
56
+
57
+ <Snippet file="qstash/waiter.mdx" />
58
+ </Expandable>
59
+
60
+ </ResponseField>
61
+
62
+
63
+ ## Usage
64
+
65
+ ### Basic Notification
66
+
67
+ ```javascript
68
+ import { serve } from "@upstash/workflow/nextjs";
69
+
70
+ export const { POST } = serve<{ topic: string }>(async (context) => {
71
+ const payload = context.requestPayload;
72
+
73
+ const {
74
+ notifyResponse, // result of notify, which is a list of notified waiters
75
+ } = await context.notify("notify step", "my-event-Id", payload);
76
+ });
77
+ ```
78
+
79
+ ### Notification with Lookback
80
+
81
+ To prevent race conditions, you can provide a `workflowRunId`. This enables lookback - the notification will be stored and delivered even if sent before the target workflow reaches `waitForEvent`:
82
+
83
+ ```javascript
84
+ import { serve } from "@upstash/workflow/nextjs";
85
+
86
+ export const { POST } = serve<{ orderId: string }>(async (context) => {
87
+ const { orderId } = context.requestPayload;
88
+
89
+ // Process payment
90
+ await context.run("process-payment", async () => {
91
+ return processPayment(orderId);
92
+ });
93
+
94
+ // Notify a specific workflow run with lookback support
95
+ const {
96
+ notifyResponse,
97
+ } = await context.notify(
98
+ "notify payment complete",
99
+ "payment-processed",
100
+ { orderId, status: "success" },
101
+ "wfr_order_processor_123" // Enables lookback for this workflow run
102
+ );
103
+ });
104
+ ```
105
+
@@ -0,0 +1,150 @@
1
+ ---
2
+ title: "context.run"
3
+ ---
4
+
5
+ `context.run()` executes a piece of custom business logic as a workflow step.
6
+
7
+ It returns a `Promise`, so you can decide how steps execute:
8
+ - **Sequentially** by awaiting them one by one.
9
+ - **In parallel** by awaiting multiple steps together.
10
+
11
+ ## Arguments
12
+
13
+ <ParamField body="stepName" type="string">
14
+ A unique identifier for the step.
15
+ </ParamField>
16
+
17
+ <ParamField body="stepFunction" type="function">
18
+ The business logic to run inside this step.
19
+ </ParamField>
20
+
21
+ <ParamField body="options" type="object" optional>
22
+ Flow control and retry configuration for this step only. Fields left unset fall back to the
23
+ configuration the run was triggered with.
24
+
25
+ See [step-level flow control](/workflow/features/flow-control#step-level-flow-control) and
26
+ [retries](/workflow/features/retries#configure-retries-for-a-single-step) for details.
27
+
28
+ <Expandable title="properties">
29
+ <ParamField body="flowControl" type="object">
30
+ Flow control configuration with `key`, `rate`, `parallelism` and `period`, the same shape as in
31
+ [client.trigger](/workflow/basics/client/trigger). Replaces the run's flow control for this step.
32
+ </ParamField>
33
+
34
+ <ParamField body="retries" type="number">
35
+ How many times the step is retried when it fails.
36
+ </ParamField>
37
+
38
+ <ParamField body="retryDelay" type="string">
39
+ Delay between retries in milliseconds. Can use expressions like `"1000 * (1 + retried)"`.
40
+ </ParamField>
41
+ </Expandable>
42
+ </ParamField>
43
+
44
+ ## Response
45
+
46
+ Each step can return a JSON-serializable value—anything from simple primitives to complex objects.
47
+
48
+ The value is **JSON-serialized** and automatically restored across requests.
49
+
50
+ <Warning>
51
+ Avoid returning stateful resources such as database connections or file handles.
52
+
53
+ Instead, return plain data (numbers, strings, arrays, objects) so the result can be safely persisted and restored across workflow executions.
54
+ </Warning>
55
+
56
+ ## Usage
57
+
58
+ <CodeGroup>
59
+ ```typescript Serial execution (TypeScript) highlight={6-8, 10-12}
60
+ import { serve } from "@upstash/workflow/nextjs";
61
+
62
+ export const { POST } = serve<string>(async (context) => {
63
+ const input = context.requestPayload;
64
+
65
+ const result1 = await context.run("step-1", async () => {
66
+ return someWork(input);
67
+ });
68
+
69
+ await context.run("step-2", async () => {
70
+ someOtherWork(result1);
71
+ });
72
+ });
73
+
74
+ ```
75
+
76
+ ```typescript Parallel execution (TypeScript)
77
+ import { serve } from "@upstash/workflow/nextjs"
78
+
79
+ export const { POST } = serve<string>(
80
+ async (context) => {
81
+ const input = context.requestPayload;
82
+
83
+ const promise1 = context.run("step-1", async () => {
84
+ return someWork(input);
85
+ });
86
+
87
+ const promise2 = context.run("step-2", async () => {
88
+ return someOtherWork(input);
89
+ });
90
+
91
+ await Promise.all([promise1, promise2]);
92
+ },
93
+ );
94
+ ```
95
+
96
+ ```python Serial execution (Python)
97
+ from fastapi import FastAPI
98
+ from upstash_workflow.fastapi import Serve
99
+ from upstash_workflow import AsyncWorkflowContext
100
+
101
+ app = FastAPI()
102
+ serve = Serve(app)
103
+
104
+
105
+ @serve.post("/api/example")
106
+ async def example(context: AsyncWorkflowContext[str]) -> None:
107
+ input = context.request_payload
108
+
109
+ async def _step1():
110
+ return some_work(input)
111
+
112
+ result1 = await context.run("step-1", _step1)
113
+
114
+ async def _step2():
115
+ return some_other_work(result1)
116
+
117
+ await context.run("step-2", _step2)
118
+
119
+ ```
120
+ </CodeGroup>
121
+
122
+
123
+ <Info>
124
+ Because results are JSON-serialized, **class instances are restored as plain objects**.
125
+ This means instance methods will not be available unless you explicitly rehydrate the object.
126
+
127
+ To fix this, you can recreate the instance using Object.assign() or a custom factory:
128
+ ```typescript
129
+ export const { POST } = serve(
130
+ async (context) => {
131
+
132
+ let user = await context.run("step-1", async () => {
133
+ // 👇 Return a class instance from step
134
+ return new User("John Doe", "john.doe@example.com");
135
+ });
136
+
137
+ // 👇 Properties are accessible by default
138
+ console.log(user.name)
139
+
140
+ // 👇 Create a Proper Instance with Object.assign()
141
+ user = Object.assign(new User(), user);
142
+
143
+ await context.run("greet", async () => {
144
+ // 👇 Now instance methods are available as well
145
+ console.log(user.greet());
146
+ });
147
+ }
148
+ );
149
+ ```
150
+ </Info>
@@ -0,0 +1,97 @@
1
+ ---
2
+ title: "context.sleep"
3
+ ---
4
+
5
+ `context.sleep()` pauses workflow execution for a specified duration.
6
+
7
+ When a workflow is paused, the current request completes and a new one is automatically scheduled to resume after the delay.
8
+ This ensures no compute resources are consumed during the sleep period.
9
+
10
+ <Note>Always `await` a `sleep` step to properly pause execution.</Note>
11
+
12
+ ## Arguments
13
+
14
+ <ParamField body="stepName" type="string">
15
+ A unique identifier for the step.
16
+ </ParamField>
17
+
18
+ <ParamField body="duration" type="number|string">
19
+ The duration to pause workflow execution.
20
+
21
+ - **Human-readable string format:**
22
+
23
+ | Input | Duration |
24
+ |---------|-------------|
25
+ | `"10s"` | 10 seconds |
26
+ | `"1m"` | 1 minute |
27
+ | `"30m"` | 30 minutes |
28
+ | `"2h"` | 2 hours |
29
+ | `"1d"` | 1 day |
30
+ | `"1w"` | 1 week |
31
+ | `"1mo"` | 1 month |
32
+ | `"1y"` | 1 year |
33
+
34
+ - **Numeric format (seconds):**
35
+
36
+ | Input | Duration |
37
+ |---------|---------------|
38
+ | `60` | 60 seconds (1 minute) |
39
+ | `3600` | 3600 seconds (1 hour) |
40
+ | `86400` | 86400 seconds (1 day) |
41
+ </ParamField>
42
+
43
+ ## Usage
44
+
45
+ <CodeGroup>
46
+
47
+ ```typescript TypeScript highlight={12-13}
48
+ import { serve } from "@upstash/workflow/nextjs";
49
+ import { signIn, sendEmail } from "@/utils/onboarding-utils";
50
+
51
+ export const { POST } = serve<User>(async (context) => {
52
+ const userData = context.requestPayload;
53
+
54
+ const user = await context.run("sign-in", async () => {
55
+ const signedInUser = await signIn(userData);
56
+ return signedInUser;
57
+ });
58
+
59
+ // 👇 Wait for one day (in seconds)
60
+ await context.sleep("wait-until-welcome-email", "1d");
61
+
62
+ await context.run("send-welcome-email", async () => {
63
+ return sendEmail(user.name, user.email);
64
+ });
65
+ });
66
+ ```
67
+
68
+ ```python Python
69
+ from fastapi import FastAPI
70
+ from upstash_workflow.fastapi import Serve
71
+ from upstash_workflow import AsyncWorkflowContext
72
+ from onboarding_utils import sign_in, send_email
73
+
74
+ app = FastAPI()
75
+ serve = Serve(app)
76
+
77
+
78
+ @serve.post("/api/onboarding")
79
+ async def onboarding(context: AsyncWorkflowContext[User]) -> None:
80
+ user_data = context.request_payload
81
+
82
+ async def _sign_in():
83
+ return await sign_in(user_data)
84
+
85
+ user = await context.run("sign-in", _sign_in)
86
+
87
+ # 👇 Wait for one day (in seconds)
88
+ await context.sleep("wait-until-welcome-email", "1d")
89
+
90
+ async def _send_email():
91
+ return await send_email(user.name, user.email)
92
+
93
+ await context.run("send-welcome-email", _send_email)
94
+
95
+ ```
96
+
97
+ </CodeGroup>
@@ -0,0 +1,88 @@
1
+ ---
2
+ title: "context.sleepUntil"
3
+ ---
4
+
5
+ `context.sleepUntil()` pauses workflow execution until a specific timestamp.
6
+
7
+ When a workflow is paused, the current request completes and a new one is automatically scheduled to resume at the target time.
8
+ This ensures no compute resources are consumed while sleeping.
9
+
10
+ <Note>Always await a `sleepUntil` step to properly pause execution.</Note>
11
+
12
+ ## Arguments
13
+
14
+ <ParamField body="stepName" type="string">
15
+ A unique identifier for the step.
16
+ </ParamField>
17
+
18
+ <ParamField body="datetime" type="Date|number|string">
19
+ The target time when the workflow should resume.
20
+ Accepted formats:
21
+ - A **number**: Unix timestamp in seconds
22
+ - A **Date object**
23
+ - A **string** that can be parsed by `new Date(string)` in JavaScript
24
+ </ParamField>
25
+
26
+ ## Usage
27
+
28
+ <CodeGroup>
29
+
30
+ ```typescript TypeScript highlight={11-16}
31
+ import { serve } from "@upstash/workflow/nextjs";
32
+ import { signIn, sendEmail } from "@/utils/onboarding-utils";
33
+
34
+ export const { POST } = serve<User>(async (context) => {
35
+ const userData = context.requestPayload;
36
+
37
+ const user = await context.run("sign-in", async () => {
38
+ return signIn(userData);
39
+ });
40
+
41
+ // 👇 Calculate the date for one week from now
42
+ const oneWeekFromNow = new Date();
43
+ oneWeekFromNow.setDate(oneWeekFromNow.getDate() + 7);
44
+
45
+ // 👇 Sleep until the calculated date
46
+ await context.sleepUntil("wait-for-one-week", oneWeekFromNow);
47
+
48
+ await context.run("send-welcome-email", async () => {
49
+ return sendEmail(user.name, user.email);
50
+ });
51
+ });
52
+ ```
53
+
54
+ ```python Python
55
+ from fastapi import FastAPI
56
+ from datetime import datetime, timedelta
57
+ from upstash_workflow.fastapi import Serve
58
+ from upstash_workflow import AsyncWorkflowContext
59
+ from onboarding_utils import sign_in, send_email
60
+
61
+ app = FastAPI()
62
+ serve = Serve(app)
63
+
64
+
65
+ @serve.post("/api/onboarding")
66
+ async def onboarding(context: AsyncWorkflowContext[User]) -> None:
67
+ user_data = context.request_payload
68
+
69
+ async def _sign_in():
70
+ return await sign_in(user_data)
71
+
72
+ user = await context.run("sign-in", _sign_in)
73
+
74
+ # 👇 Calculate the date for one week from now
75
+ one_week_from_now = datetime.now() + timedelta(days=7)
76
+
77
+ # 👇 Wait until the calculated date
78
+ await context.sleep_until("wait-for-one-week", one_week_from_now)
79
+
80
+ async def _send_email():
81
+ return await send_email(user.name, user.email)
82
+
83
+ await context.run("send-welcome-email", _send_email)
84
+
85
+ ```
86
+
87
+ </CodeGroup>
88
+
@@ -0,0 +1,60 @@
1
+ ---
2
+ title: "context.waitForEvent"
3
+ ---
4
+
5
+ `context.waitForEvent` pauses workflow execution until a given event occurs or a timeout is reached.
6
+
7
+ Default timeout value is 7 days.
8
+
9
+ ## Arguments
10
+
11
+ <ParamField body="stepId" type="string" required>
12
+ A unique identifier for the step.
13
+ </ParamField>
14
+
15
+ <ParamField body="eventId" type="string" required>
16
+ A unique identifier for the event to wait on.
17
+ </ParamField>
18
+
19
+ <ParamField body="options" type="object">
20
+ <Expandable defaultOpen>
21
+ <ParamField body="timeout" type="number|string">
22
+ The maximum time to wait before continuing execution.
23
+
24
+ - **String format**: Human‑readable duration (e.g., `"10s"`, `"2h"`, `"1d"`).
25
+ - **Number format**: Duration in seconds (e.g., `60`, `3600`).
26
+
27
+ Defaults to `7d` (7 days).
28
+ </ParamField>
29
+ </Expandable>
30
+ </ParamField>
31
+
32
+ ## Response
33
+
34
+ <ResponseField name="eventData" type="TEventData">
35
+ The data passed in when the event is triggered via `notify()`.
36
+ Its type can be set with the generic parameter, e.g. `context.waitForEvent<{ approved: boolean }>(...)`. Defaults to `unknown`.
37
+ </ResponseField>
38
+
39
+ <ResponseField name="timeout" type="boolean">
40
+ `true` if execution resumed because the timeout elapsed,
41
+ `false` if resumed due to the event being received.
42
+ </ResponseField>
43
+
44
+ ## Usage
45
+
46
+ ```javascript highlight={6-11}
47
+ import { serve } from "@upstash/workflow/nextjs";
48
+
49
+ export const { POST } = serve<{ topic: string }>(async (context) => {
50
+ const request = context.requestPayload;
51
+
52
+ const {
53
+ eventData,
54
+ timeout,
55
+ } = await context.waitForEvent("wait for some event", "my-event-id", {
56
+ timeout: "1000s", // 1000 second timeout
57
+ });
58
+ });
59
+
60
+ ```
@@ -0,0 +1,78 @@
1
+ ---
2
+ title: "context.waitForWebhook"
3
+ ---
4
+
5
+ `context.waitForWebhook()` pauses workflow execution until the webhook created by `createWebhook` is called or a timeout is reached.
6
+
7
+ You can call `context.waitForWebhook` with the same `webhook` object multiple times to wait for multiple calls to the same webhook URL.
8
+
9
+ ## Arguments
10
+
11
+ <ParamField body="stepName" type="string" required>
12
+ Name of the step.
13
+ </ParamField>
14
+
15
+ <ParamField body="webhook" type="object" required>
16
+ The webhook object returned by `context.createWebhook()`.
17
+
18
+ <Expandable title="properties">
19
+ <ParamField body="webhookUrl" type="string">
20
+ The webhook URL to wait for.
21
+ </ParamField>
22
+
23
+ <ParamField body="eventId" type="string">
24
+ The internal event identifier.
25
+ </ParamField>
26
+ </Expandable>
27
+ </ParamField>
28
+
29
+ <ParamField body="timeout" type="string" required>
30
+ The maximum time to wait before continuing execution.
31
+
32
+ Should be passed in Human‑readable duration (e.g., `"10s"`, `"2h"`, `"1d"`).
33
+ </ParamField>
34
+
35
+ ## Response
36
+
37
+ The response varies depending on whether the webhook was called before the timeout:
38
+
39
+ <ResponseField name="timeout" type="boolean">
40
+ - `false` if the webhook was called successfully
41
+ - `true` if execution resumed because the timeout elapsed
42
+ </ResponseField>
43
+
44
+ <ResponseField name="request" type="Request | undefined">
45
+ The HTTP request object received by the webhook (only present when `timeout` is `false`).
46
+
47
+ Contains the full request details including method, headers, body, and URL.
48
+ </ResponseField>
49
+
50
+ ## Usage
51
+
52
+ ### Basic Example
53
+
54
+ ```typescript highlight={8-13}
55
+ import { serve } from "@upstash/workflow/nextjs";
56
+
57
+ export const { POST } = serve(async (context) => {
58
+ // Create webhook
59
+ const webhook = await context.createWebhook("create webhook");
60
+
61
+ // Wait for webhook to be called with 30 second timeout
62
+ const webhookResponse = await context.waitForWebhook(
63
+ "wait for webhook",
64
+ webhook,
65
+ "30s"
66
+ );
67
+
68
+ if (webhookResponse.timeout) {
69
+ console.log("Webhook was not called within the timeout period");
70
+ } else {
71
+ console.log("Webhook was called successfully");
72
+ console.log("Request body:", webhookResponse.request.body);
73
+ console.log("Request headers:", webhookResponse.request.headers);
74
+ }
75
+ });
76
+ ```
77
+
78
+ For more complete examples and use cases, see [the page on webhooks](/workflow/features/webhooks).
package/docs/steps.mdx ADDED
@@ -0,0 +1,108 @@
1
+ ---
2
+ title: Workflow Steps Overview
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ A workflow's **context** is an object provided by the route function.
7
+
8
+ The context object provides:
9
+ - **Workflow APIs** – functions for defining workflow steps.
10
+ - **Workflow Run Properties** – request payload, request headers, and other metadata.
11
+
12
+ <CodeGroup>
13
+ ```typescript api/workflow/route.ts highlight={4-5}
14
+ import { serve } from "@upstash/workflow/nextjs";
15
+
16
+ export const { POST } = serve(
17
+ // 👇 the workflow context
18
+ async (context) => {
19
+ // ...
20
+ }
21
+ );
22
+ ```
23
+
24
+ ```python main.py
25
+ from fastapi import FastAPI
26
+ from upstash_workflow.fastapi import Serve
27
+ from upstash_workflow import AsyncWorkflowContext
28
+
29
+ app = FastAPI()
30
+ serve = Serve(app)
31
+
32
+
33
+ @serve.post("/api/example")
34
+ async def example(context: AsyncWorkflowContext[str]) -> None: ...
35
+
36
+ ```
37
+ </CodeGroup>
38
+
39
+ ## Context Object Properties
40
+
41
+ <ParamField path="requestPayload" type="object">
42
+ The request payload passed to the workflow run via `trigger()` call.
43
+ </ParamField>
44
+
45
+ <ParamField path="headers" type="object">
46
+ The request headers passed to the workflow run via `trigger()` call.
47
+ </ParamField>
48
+
49
+ <ParamField path="workflowRunId" type="string">
50
+ The unique identifier of the current workflow run.
51
+ </ParamField>
52
+
53
+ <ParamField path="url" type="string">
54
+ The public URL of the workflow endpoint.
55
+ </ParamField>
56
+
57
+ <ParamField path="failureUrl" type="string">
58
+ The URL used for workflow failure callback.
59
+
60
+ If a failure function is defined, this is the same as the workflow's `url`.
61
+ </ParamField>
62
+
63
+ <ParamField path="env" type="object">
64
+ The environment variables available to the workflow.
65
+ </ParamField>
66
+
67
+ <ParamField path="qstashClient" type="object">
68
+ The QStash client instance used by the workflow endpoint.
69
+ </ParamField>
70
+
71
+ <ParamField path="labels" type="string[]">
72
+ The labels attached to the current workflow run, if set in [client.trigger](/workflow/basics/client/trigger).
73
+ Defaults to an empty array when no label was set.
74
+ </ParamField>
75
+
76
+ <ParamField path="flowControl" type="object | undefined">
77
+ The flow control configuration QStash applied to the current request: `key`, `parallelism`, `rate` and `period`.
78
+ Reflects [step-level flow control](/workflow/features/flow-control#step-level-flow-control) when the step sets its own.
79
+ </ParamField>
80
+
81
+ <ParamField path="retries" type="number | undefined">
82
+ The retry limit QStash applied to the current request.
83
+ </ParamField>
84
+
85
+ <ParamField path="retryDelay" type="string | undefined">
86
+ The retry delay expression QStash applied to the current request.
87
+ </ParamField>
88
+
89
+ <ParamField path="label" type="string | undefined" deprecated>
90
+ Deprecated. Use `labels` instead. When a run has multiple labels, this only
91
+ returns the first one.
92
+ </ParamField>
93
+
94
+ ## Context Object Functions
95
+
96
+ You can use the functions exposed by context object to define workflow steps.
97
+
98
+ - [context.run](/workflow/basics/context/run)
99
+ - [context.sleep](/workflow/basics/context/sleep)
100
+ - [context.sleepUntil](/workflow/basics/context/sleepUntil)
101
+ - [context.waitForEvent](/workflow/basics/context/waitForEvent)
102
+ - [context.createWebhook](/workflow/basics/context/createWebhook)
103
+ - [context.waitForWebhook](/workflow/basics/context/waitForWebhook)
104
+ - [context.notify](/workflow/basics/context/notify)
105
+ - [context.invoke](/workflow/basics/context/invoke)
106
+ - [context.call](/workflow/basics/context/call)
107
+ - [context.cancel](/workflow/basics/context/cancel)
108
+ - [context.api](/workflow/basics/context/api)