@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,475 @@
1
+ import { startDevServer } from "@upstash/qstash";
2
+ import { makeCancelRequest } from "../client/utils";
3
+ import {
4
+ SDK_TELEMETRY,
5
+ WORKFLOW_CREATED_AT_HEADER,
6
+ WORKFLOW_INVOKE_COUNT_HEADER,
7
+ WORKFLOW_LABEL_HEADER,
8
+ WORKFLOW_ERROR_STEP_NAME_HEADER,
9
+ WORKFLOW_PROTOCOL_VERSION,
10
+ WORKFLOW_PROTOCOL_VERSION_HEADER,
11
+ WORKFLOW_RETRIED_HEADER,
12
+ } from "../constants";
13
+ import { WorkflowContext } from "../context";
14
+ import {
15
+ formatWorkflowError,
16
+ getStepNameFromError,
17
+ isInstanceOf,
18
+ WorkflowNonRetryableError,
19
+ WorkflowRetryAfterError,
20
+ } from "../error";
21
+ import { MiddlewareManager } from "../middleware/manager";
22
+ import { RouteFunction, Telemetry, WorkflowServeOptions } from "../types";
23
+ import { getPayload, handleFailure, parseRequest, validateRequest } from "../workflow-parser";
24
+ import {
25
+ handleThirdPartyCallResult,
26
+ flushPendingStep,
27
+ isThirdPartyCallResult,
28
+ recreateUserHeaders,
29
+ triggerFirstInvocation,
30
+ triggerRouteFunction,
31
+ triggerWorkflowDelete,
32
+ verifyRequest,
33
+ } from "../workflow-requests";
34
+ import { getEffectiveConfig } from "../qstash/step-config";
35
+ import { DisabledWorkflowContext } from "./authorization";
36
+ import { getHandlersForRequest } from "./multi-region/handlers";
37
+ import {
38
+ AUTH_FAIL_MESSAGE,
39
+ createResponseData,
40
+ determineUrls,
41
+ processOptions,
42
+ InternalServeOptions,
43
+ } from "./options";
44
+
45
+ /**
46
+ * Creates an async method that handles incoming requests and runs the provided
47
+ * route function as a workflow.
48
+ *
49
+ * Not exported in the package. Instead, used in framework specific serve implementations.
50
+ *
51
+ * Only difference from regular serve is the `useJSONContent` parameter.
52
+ *
53
+ * @param routeFunction - A function that uses WorkflowContext as a parameter and runs a workflow.
54
+ * @param options - Options including the client, onFinish callback, and initialPayloadParser.
55
+ * @returns An async method that consumes incoming requests and runs the workflow.
56
+ */
57
+ export const serveBase = <
58
+ TInitialPayload = unknown,
59
+ TRequest extends Request = Request,
60
+ TResponse extends Response = Response,
61
+ TResult = unknown,
62
+ >(
63
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
64
+ telemetry?: Telemetry,
65
+ options?: WorkflowServeOptions<TInitialPayload, TResult>,
66
+ internalOptions?: Partial<InternalServeOptions<TResponse>>
67
+ ): {
68
+ handler: (request: TRequest) => Promise<TResponse>;
69
+ } => {
70
+ // Prepares options with defaults if they are not provided.
71
+
72
+ const {
73
+ initialPayloadParser,
74
+ url,
75
+ failureFunction,
76
+ baseUrl,
77
+ env,
78
+ disableTelemetry,
79
+ middlewares,
80
+ internal,
81
+ } = processOptions<TInitialPayload, TResult, TResponse>(options, internalOptions);
82
+ telemetry = disableTelemetry ? undefined : telemetry;
83
+
84
+ const { generateResponse: responseGenerator, useJSONContent } = internal;
85
+
86
+ /**
87
+ * Handles the incoming request, triggering the appropriate workflow steps.
88
+ * Calls `triggerFirstInvocation()` if it's the first invocation.
89
+ * Otherwise, starts calling `triggerRouteFunction()` to execute steps in the workflow.
90
+ * Finally, calls `triggerWorkflowDelete()` to remove the workflow from QStash.
91
+ *
92
+ * @param request - The incoming request to handle.
93
+ * @returns A promise that resolves to a response.
94
+ */
95
+ const handler = async (
96
+ request: TRequest,
97
+ middlewareManager: MiddlewareManager<TInitialPayload, TResult>
98
+ ) => {
99
+ await middlewareManager.dispatchDebug("onInfo", {
100
+ info: `Received request for workflow execution.`,
101
+ });
102
+
103
+ const { workflowUrl } = await determineUrls(
104
+ request,
105
+ url,
106
+ baseUrl,
107
+ middlewareManager.dispatchDebug.bind(middlewareManager)
108
+ );
109
+
110
+ // validation & parsing to get isFirstInvocation early
111
+ const { isFirstInvocation, workflowRunId, unknownSdk } = validateRequest(request);
112
+
113
+ // Get the appropriate handlers based on region
114
+ const regionHeader = request.headers.get("upstash-region");
115
+ const { client: regionalClient, receiver: regionalReceiver } = getHandlersForRequest(
116
+ internal.qstashHandlers,
117
+ regionHeader,
118
+ isFirstInvocation
119
+ );
120
+
121
+ // get payload as raw string
122
+ const requestPayload = (await getPayload(request)) ?? "";
123
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), regionalReceiver);
124
+
125
+ middlewareManager.assignWorkflowRunId(workflowRunId);
126
+ await middlewareManager.dispatchDebug("onInfo", {
127
+ info: `Run id identified. isFirstInvocation: ${isFirstInvocation}, unknownSdk: ${unknownSdk}`,
128
+ });
129
+
130
+ // parse steps
131
+ const { rawInitialPayload, steps, isLastDuplicate, workflowRunEnded } = await parseRequest({
132
+ requestPayload,
133
+ isFirstInvocation,
134
+ unknownSdk,
135
+ workflowRunId,
136
+ requester: regionalClient.http,
137
+ messageId: request.headers.get("upstash-message-id")!,
138
+ dispatchDebug: middlewareManager.dispatchDebug.bind(middlewareManager),
139
+ });
140
+
141
+ if (workflowRunEnded) {
142
+ return responseGenerator(
143
+ createResponseData(workflowRunId, {
144
+ condition: "workflow-already-ended",
145
+ })
146
+ );
147
+ }
148
+
149
+ // terminate current call if it's a duplicate branch
150
+ if (isLastDuplicate) {
151
+ return responseGenerator(
152
+ createResponseData(workflowRunId, {
153
+ condition: "duplicate-step",
154
+ })
155
+ );
156
+ }
157
+
158
+ // check if the request is a failure callback
159
+ const failureCheck = await handleFailure<TInitialPayload>({
160
+ request,
161
+ requestPayload,
162
+ qstashClient: regionalClient,
163
+ initialPayloadParser,
164
+ routeFunction,
165
+ failureFunction,
166
+ env,
167
+ dispatchDebug: middlewareManager.dispatchDebug.bind(middlewareManager),
168
+ });
169
+ if (failureCheck.isErr()) {
170
+ // unexpected error during handleFailure
171
+ throw failureCheck.error;
172
+ } else if (failureCheck.value.result === "failure-function-executed") {
173
+ // is a failure ballback.
174
+ await middlewareManager.dispatchDebug("onInfo", {
175
+ info: `Handled failure callback.`,
176
+ });
177
+ return responseGenerator(
178
+ createResponseData(workflowRunId, {
179
+ condition: "failure-callback-executed",
180
+ result: failureCheck.value.response,
181
+ })
182
+ );
183
+ } else if (failureCheck.value.result === "failure-function-undefined") {
184
+ await middlewareManager.dispatchDebug("onInfo", {
185
+ info: `Failure callback invoked but no failure function defined.`,
186
+ });
187
+ return responseGenerator(
188
+ createResponseData(workflowRunId, {
189
+ condition: "failure-callback-undefined",
190
+ })
191
+ );
192
+ }
193
+
194
+ const invokeCount = Number(request.headers.get(WORKFLOW_INVOKE_COUNT_HEADER) ?? "0");
195
+ const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
196
+ const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? undefined;
197
+ const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
198
+ // QStash sends the creation time of the run with every request of a run. A first
199
+ // invocation which doesn't come from QStash has no run yet, so it gets the trigger
200
+ // time, which triggerFirstInvocation sends as the creation time of the new run.
201
+ const workflowRunCreatedAt = workflowRunCreatedAtHeader
202
+ ? Number(workflowRunCreatedAtHeader)
203
+ : isFirstInvocation
204
+ ? Date.now()
205
+ : 0;
206
+
207
+ // configuration QStash applied to this delivery, which the executor
208
+ // compares a step's own settings against
209
+ const effectiveConfig = getEffectiveConfig(request.headers as Headers);
210
+
211
+ // create context
212
+ const workflowContext = new WorkflowContext<TInitialPayload>({
213
+ qstashClient: regionalClient,
214
+ workflowRunId,
215
+ initialPayload: isThirdPartyCallResult(request)
216
+ ? JSON.parse(rawInitialPayload)
217
+ : initialPayloadParser(rawInitialPayload),
218
+ headers: recreateUserHeaders(request.headers as Headers),
219
+ steps,
220
+ effectiveConfig,
221
+ url: workflowUrl,
222
+ env,
223
+ telemetry,
224
+ invokeCount,
225
+ label,
226
+ retried,
227
+ workflowRunCreatedAt,
228
+ middlewareManager,
229
+ });
230
+
231
+ // attempt running routeFunction until the first step
232
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
233
+ routeFunction,
234
+ workflowContext,
235
+ effectiveConfig
236
+ );
237
+ if (authCheck.isErr()) {
238
+ // got error while running until first step
239
+ throw authCheck.error;
240
+ } else if (authCheck.value === "run-ended") {
241
+ // finished routeFunction while trying to run until first step.
242
+ // either there is no step or auth check resulted in `return`
243
+ await middlewareManager.dispatchDebug("onError", {
244
+ error: new Error(AUTH_FAIL_MESSAGE),
245
+ });
246
+ return responseGenerator(
247
+ createResponseData(isFirstInvocation ? "no-workflow-id" : workflowContext.workflowRunId, {
248
+ condition: "auth-fail",
249
+ })
250
+ );
251
+ }
252
+
253
+ // check if request is a third party call result
254
+ const callReturnCheck = await handleThirdPartyCallResult({
255
+ request,
256
+ requestPayload: rawInitialPayload,
257
+ client: regionalClient,
258
+ workflowUrl,
259
+ telemetry,
260
+ middlewareManager,
261
+ });
262
+ if (callReturnCheck.isErr()) {
263
+ throw callReturnCheck.error;
264
+ } else if (callReturnCheck.value === "continue-workflow") {
265
+ // request is not third party call. Continue workflow as usual
266
+ const result = isFirstInvocation
267
+ ? await triggerFirstInvocation({
268
+ workflowContext,
269
+ useJSONContent,
270
+ telemetry,
271
+ invokeCount,
272
+ middlewareManager,
273
+ unknownSdk,
274
+ })
275
+ : await triggerRouteFunction({
276
+ onStep: async () => {
277
+ if (steps.length === 1) {
278
+ await middlewareManager.dispatchLifecycle("runStarted", {});
279
+ }
280
+
281
+ // A step whose result is available in-process (run, sleep,
282
+ // sleepUntil, notify) is held rather than submitted, so the
283
+ // route function can carry on and reveal what comes next.
284
+ // However the function ends, that held result has to reach
285
+ // QStash before this invocation does, so it is submitted on
286
+ // every path out of here.
287
+ let outcome: { ran: true; result: TResult } | { ran: false; error: unknown };
288
+ try {
289
+ outcome = { ran: true, result: await routeFunction(workflowContext) };
290
+ } catch (error) {
291
+ // Reached whenever the route function does not run to the
292
+ // end. Usually that is the executor ending the invocation
293
+ // on purpose — a WorkflowAbort once it submitted a step,
294
+ // planned a parallel group or published a step config
295
+ // request, or a cancel / non-retryable / retry-after — but
296
+ // it is also where a step function or the code around it
297
+ // failing arrives. They are told apart below and in
298
+ // triggerRouteFunction; the submission comes first either
299
+ // way.
300
+ outcome = { ran: false, error };
301
+ }
302
+
303
+ const submitted = await flushPendingStep(workflowContext);
304
+
305
+ if (submitted.isErr()) {
306
+ // Reached when a step was held and its result could not be
307
+ // published. The step ran but the run has no record of it,
308
+ // so nothing else that happened matters: surface the
309
+ // failure and let QStash retry this delivery, which
310
+ // replays the step rather than losing it.
311
+ throw submitted.error;
312
+ }
313
+
314
+ if (submitted.value.result === "submitted-step") {
315
+ // Reached when a step ran in this invocation and was held:
316
+ // either the function returned straight after it, or it
317
+ // reached a further step, which submitted the held one and
318
+ // threw this same abort on the way out. Its result is now
319
+ // with QStash, so the invocation ends as a finished step
320
+ // and the run carries on in the delivery that submission
321
+ // produces.
322
+ //
323
+ // An error the function threw after running that step is
324
+ // dropped here. It happens again on the next delivery,
325
+ // where the step is memoized and nothing is held to take
326
+ // precedence over it.
327
+ throw submitted.value.abort;
328
+ }
329
+
330
+ if (!outcome.ran) {
331
+ // Reached when the function did not run to the end and no
332
+ // step was held — nothing ran in this invocation, or what
333
+ // ran submitted itself (a call, an invoke, a wait, a
334
+ // parallel group). triggerRouteFunction decides whether
335
+ // this ends the invocation as a finished step or fails the
336
+ // run.
337
+ throw outcome.error;
338
+ }
339
+
340
+ // Reached when the function ran to the end without executing
341
+ // a step here: every step it passed was already recorded, so
342
+ // there is nothing left to submit and the run is finished.
343
+ return outcome.result;
344
+ },
345
+ onCleanup: async (result) => {
346
+ await middlewareManager.dispatchLifecycle("runCompleted", {
347
+ result,
348
+ });
349
+ await triggerWorkflowDelete(
350
+ workflowContext,
351
+ result,
352
+ false,
353
+ middlewareManager.dispatchDebug.bind(middlewareManager)
354
+ );
355
+ },
356
+ onCancel: async () => {
357
+ await makeCancelRequest(workflowContext.qstashClient.http, workflowRunId);
358
+ },
359
+ middlewareManager,
360
+ });
361
+
362
+ if (result.isOk() && isInstanceOf(result.value, WorkflowNonRetryableError)) {
363
+ return responseGenerator(
364
+ createResponseData(workflowRunId, {
365
+ condition: "non-retryable-error",
366
+ result: result.value,
367
+ })
368
+ );
369
+ }
370
+
371
+ if (result.isOk() && isInstanceOf(result.value, WorkflowRetryAfterError)) {
372
+ return responseGenerator(
373
+ createResponseData(workflowRunId, {
374
+ condition: "retry-after-error",
375
+ result: result.value,
376
+ })
377
+ );
378
+ }
379
+
380
+ if (result.isErr()) {
381
+ // error while running the workflow or when cleaning up
382
+ throw result.error;
383
+ }
384
+
385
+ // Returns a Response with `workflowRunId` at the end of each step.
386
+ await middlewareManager.dispatchDebug("onInfo", {
387
+ info: `Workflow endpoint execution completed successfully.`,
388
+ });
389
+ return responseGenerator(
390
+ createResponseData(workflowContext.workflowRunId, {
391
+ condition: "success",
392
+ })
393
+ );
394
+ } else if (callReturnCheck.value === "workflow-ended") {
395
+ return responseGenerator(
396
+ createResponseData(workflowContext.workflowRunId, {
397
+ condition: "workflow-already-ended",
398
+ })
399
+ );
400
+ }
401
+ // response to QStash in call cases
402
+ return responseGenerator(
403
+ createResponseData(workflowContext.workflowRunId, {
404
+ condition: "fromCallback",
405
+ })
406
+ );
407
+ };
408
+
409
+ const safeHandler = async (request: TRequest) => {
410
+ // Create middleware manager for this request
411
+ const middlewareManager = new MiddlewareManager<TInitialPayload, TResult>(middlewares);
412
+
413
+ try {
414
+ return await handler(request, middlewareManager);
415
+ } catch (error) {
416
+ const formattedError = formatWorkflowError(error);
417
+ await middlewareManager.dispatchDebug("onError", {
418
+ error: isInstanceOf(error, Error) ? error : new Error(formattedError.message),
419
+ });
420
+ // if the error happened while executing a known step, report its name so
421
+ // it can be shown in Workflow Logs when the step is retried.
422
+ const stepName = getStepNameFromError(error)
423
+ // strip control characters (e.g. CR/LF) so an invalid step name
424
+ // can't produce an invalid header value and break the 500 response
425
+ // eslint-disable-next-line no-control-regex
426
+ ?.replace(/[\u0000-\u001F\u007F]+/g, " ")
427
+ .trim();
428
+ return new Response(JSON.stringify(formattedError), {
429
+ status: 500,
430
+ headers: {
431
+ [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
432
+ ...(stepName ? { [WORKFLOW_ERROR_STEP_NAME_HEADER]: stepName } : {}),
433
+ },
434
+ }) as TResponse;
435
+ }
436
+ };
437
+
438
+ return { handler: safeHandler };
439
+ };
440
+
441
+ /**
442
+ * Creates an async method that handles incoming requests and runs the provided
443
+ * route function as a workflow.
444
+ *
445
+ * Code outside steps runs again on every request of the run. Anything it branches on or
446
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
447
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
448
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
449
+ * result.
450
+ *
451
+ * @param routeFunction - A function that uses WorkflowContext as a parameter and runs a workflow.
452
+ * @param options - Options including the client and initialPayloadParser.
453
+ * @returns An async method that consumes incoming requests and runs the workflow.
454
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
455
+ * @see node_modules/@upstash/workflow/docs/quickstarts/platforms.mdx
456
+ */
457
+ export const serve = <
458
+ TInitialPayload = unknown,
459
+ TRequest extends Request = Request,
460
+ TResponse extends Response = Response,
461
+ TResult = unknown,
462
+ >(
463
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
464
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
465
+ ): ReturnType<typeof serveBase<TInitialPayload, TRequest, TResponse, TResult>> => {
466
+ void startDevServer();
467
+ return serveBase(
468
+ routeFunction,
469
+ {
470
+ sdk: SDK_TELEMETRY,
471
+ framework: "unknown",
472
+ },
473
+ options
474
+ );
475
+ };
@@ -0,0 +1,225 @@
1
+ import { Client, Receiver } from "@upstash/qstash";
2
+ import {
3
+ getRegionFromEnvironment,
4
+ normalizeRegionHeader,
5
+ QStashHandlers,
6
+ QStashRegion,
7
+ readClientEnvironmentVariables,
8
+ readReceiverEnvironmentVariables,
9
+ RegionalHandler,
10
+ } from "./utils";
11
+ import { QStashClientExtraConfig, WorkflowClient, WorkflowReceiver } from "../../types";
12
+
13
+ /**
14
+ * Get the appropriate QStash client and receiver based on the request region header
15
+ *
16
+ * @param qstashHandlers - The QStash handlers configuration
17
+ * @param regionHeader - The UPSTASH-REGION header from the request
18
+ * @param isFirstInvocation - Whether this is the first invocation
19
+ * @returns Regional handler with client and receiver
20
+ */
21
+ export const getHandlersForRequest = (
22
+ qstashHandlers: QStashHandlers,
23
+ regionHeader: string | null,
24
+ isFirstInvocation: boolean
25
+ ): RegionalHandler => {
26
+ if (qstashHandlers.mode === "single-region") {
27
+ return qstashHandlers.handlers;
28
+ }
29
+
30
+ // Multi-region mode
31
+ let targetRegion: QStashRegion;
32
+
33
+ if (isFirstInvocation && !regionHeader) {
34
+ // Use the default region for first non-qstash invocation
35
+ targetRegion = qstashHandlers.defaultRegion;
36
+ } else {
37
+ // Use the region from the header for subsequent invocations
38
+ const normalizedRegion = regionHeader ? normalizeRegionHeader(regionHeader) : undefined;
39
+ targetRegion = normalizedRegion ?? qstashHandlers.defaultRegion;
40
+ }
41
+
42
+ const handler = qstashHandlers.handlers[targetRegion];
43
+
44
+ if (!handler) {
45
+ console.warn(
46
+ `[Upstash Workflow] No handler found for region "${targetRegion}". Falling back to default region.`
47
+ );
48
+ return qstashHandlers.handlers[qstashHandlers.defaultRegion];
49
+ }
50
+
51
+ return handler;
52
+ };
53
+
54
+ /**
55
+ * Creates a regional handler with client and receiver
56
+ */
57
+ const createRegionalHandler = (
58
+ environment: Record<string, string | undefined>,
59
+ receiverConfig: WorkflowReceiver | "set-to-undefined" | "not-set",
60
+ region?: QStashRegion,
61
+ clientOptions?: QStashClientExtraConfig
62
+ ): RegionalHandler => {
63
+ const clientEnv = readClientEnvironmentVariables(environment, region);
64
+
65
+ const client = new Client({
66
+ ...clientOptions,
67
+ baseUrl: clientEnv.QSTASH_URL!,
68
+ token: clientEnv.QSTASH_TOKEN!,
69
+ // Mirror the receiver's dev-mode decision so a single QSTASH_DEV=true points
70
+ // the client at the local dev server too. Without this the QStash Client
71
+ // re-derives dev mode from its own process.env, which is blind to the
72
+ // Cloudflare worker `env` binding that actually carries QSTASH_DEV there.
73
+ // An explicit devMode in the user's client config still wins.
74
+ devMode: clientOptions?.devMode ?? isQStashDevModeEnabled(environment),
75
+ });
76
+ const receiver = getReceiver(environment, receiverConfig, region);
77
+
78
+ return { client, receiver };
79
+ };
80
+
81
+ /**
82
+ * Determines if multi-region mode should be enabled
83
+ */
84
+ const shouldUseMultiRegionMode = (
85
+ environment: Record<string, string | undefined>,
86
+ qstashClientOption?: WorkflowClient | QStashClientExtraConfig
87
+ ):
88
+ | { isMultiRegion: true; defaultRegion: QStashRegion; clientOptions?: QStashClientExtraConfig }
89
+ | { isMultiRegion: false } => {
90
+ // Multi-region mode is enabled when:
91
+ // 1. QSTASH_REGION env variable is set
92
+ // 2. qstashClient option is not a WorkflowClient instance (either undefined or config object)
93
+ const hasRegionEnv = Boolean(getRegionFromEnvironment(environment));
94
+ if (hasRegionEnv && (!qstashClientOption || !("http" in qstashClientOption))) {
95
+ return {
96
+ isMultiRegion: true,
97
+ defaultRegion: getRegionFromEnvironment(environment)!,
98
+ clientOptions: qstashClientOption,
99
+ };
100
+ } else {
101
+ return { isMultiRegion: false };
102
+ }
103
+ };
104
+
105
+ const getQStashHandlers = ({
106
+ environment,
107
+ qstashClientOption,
108
+ receiverConfig,
109
+ }: {
110
+ environment: Record<string, string | undefined>;
111
+ qstashClientOption?: WorkflowClient | QStashClientExtraConfig;
112
+ /**
113
+ * - "set-to-undefined" if user explicitly set receiver to undefined in options
114
+ * - "not-set" if user did not pass receiver in options
115
+ * - WorkflowReceiver if user passed a receiver instance in options
116
+ */
117
+ receiverConfig: WorkflowReceiver | "set-to-undefined" | "not-set";
118
+ }): QStashHandlers => {
119
+ const multiRegion = shouldUseMultiRegionMode(environment, qstashClientOption);
120
+
121
+ if (multiRegion.isMultiRegion) {
122
+ // Multi-region mode
123
+
124
+ const regions: QStashRegion[] = ["US_EAST_1", "EU_CENTRAL_1"];
125
+ const handlers: Record<QStashRegion, RegionalHandler> = {} as Record<
126
+ QStashRegion,
127
+ RegionalHandler
128
+ >;
129
+
130
+ for (const region of regions) {
131
+ try {
132
+ handlers[region] = createRegionalHandler(
133
+ environment,
134
+ receiverConfig,
135
+ region,
136
+ multiRegion.clientOptions
137
+ );
138
+ } catch (error) {
139
+ console.warn(`[Upstash Workflow] Failed to create handler for region ${region}:`, error);
140
+ }
141
+ }
142
+
143
+ return {
144
+ mode: "multi-region",
145
+ handlers,
146
+ defaultRegion: multiRegion.defaultRegion,
147
+ };
148
+ } else {
149
+ // Single-region mode
150
+ return {
151
+ mode: "single-region",
152
+ handlers: {
153
+ client:
154
+ qstashClientOption && "http" in qstashClientOption
155
+ ? qstashClientOption
156
+ : new Client({
157
+ ...qstashClientOption,
158
+ baseUrl: environment.QSTASH_URL!,
159
+ token: environment.QSTASH_TOKEN!,
160
+ // Mirror the receiver's dev-mode decision (see createRegionalHandler).
161
+ devMode: qstashClientOption?.devMode ?? isQStashDevModeEnabled(environment),
162
+ }),
163
+ receiver: getReceiver(environment, receiverConfig),
164
+ },
165
+ };
166
+ }
167
+ };
168
+
169
+ const getReceiver = (
170
+ environment: Record<string, string | undefined>,
171
+ receiverConfig: WorkflowReceiver | "set-to-undefined" | "not-set",
172
+ region?: QStashRegion
173
+ ) => {
174
+ if (typeof receiverConfig === "string") {
175
+ if (receiverConfig === "set-to-undefined") {
176
+ return undefined;
177
+ }
178
+
179
+ if (isQStashDevModeEnabled(environment)) {
180
+ return new Receiver({ devMode: true });
181
+ }
182
+
183
+ const receiverEnv = readReceiverEnvironmentVariables(environment, region);
184
+ return receiverEnv.QSTASH_CURRENT_SIGNING_KEY && receiverEnv.QSTASH_NEXT_SIGNING_KEY
185
+ ? new Receiver({
186
+ currentSigningKey: receiverEnv.QSTASH_CURRENT_SIGNING_KEY,
187
+ nextSigningKey: receiverEnv.QSTASH_NEXT_SIGNING_KEY,
188
+ })
189
+ : undefined;
190
+ } else {
191
+ return receiverConfig;
192
+ }
193
+ };
194
+
195
+ /**
196
+ * Mirrors qstash-js's `shouldUseDevelopmentMode` for the env-only case so we
197
+ * decide whether to construct a Receiver. The strict parsing (rejecting garbage
198
+ * values, etc.) is left to qstash-js itself when the Receiver/Client run.
199
+ */
200
+ const isQStashDevModeEnabled = (env: Record<string, string | undefined>): boolean => {
201
+ const value = env.QSTASH_DEV;
202
+ return value === "true" || value === "1";
203
+ };
204
+
205
+ export const getQStashHandlerOptions = (
206
+ ...params: Parameters<typeof getQStashHandlers>
207
+ ): {
208
+ qstashHandlers: ReturnType<typeof getQStashHandlers>;
209
+ defaultReceiver: WorkflowReceiver | undefined;
210
+ defaultClient: WorkflowClient;
211
+ } => {
212
+ const handlers = getQStashHandlers(...params);
213
+
214
+ return {
215
+ qstashHandlers: handlers,
216
+ defaultReceiver:
217
+ handlers.mode === "single-region"
218
+ ? handlers.handlers.receiver
219
+ : handlers.handlers[handlers.defaultRegion].receiver,
220
+ defaultClient:
221
+ handlers.mode === "single-region"
222
+ ? handlers.handlers.client
223
+ : handlers.handlers[handlers.defaultRegion].client,
224
+ };
225
+ };