@upstash/workflow 1.4.0-rc → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +18 -2
  3. package/astro.d.ts +18 -2
  4. package/astro.js +129 -29
  5. package/astro.mjs +1 -1
  6. package/{chunk-UH6O5IJY.mjs → chunk-J3PXPHSB.mjs} +129 -29
  7. package/cloudflare.d.mts +16 -2
  8. package/cloudflare.d.ts +16 -2
  9. package/cloudflare.js +129 -29
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +18 -2
  136. package/express.d.ts +18 -2
  137. package/express.js +129 -29
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +18 -2
  140. package/h3.d.ts +18 -2
  141. package/h3.js +129 -29
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +16 -2
  144. package/hono.d.ts +16 -2
  145. package/hono.js +129 -29
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +49 -21
  148. package/index.d.ts +49 -21
  149. package/index.js +145 -41
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +39 -2
  152. package/nextjs.d.ts +39 -2
  153. package/nextjs.js +129 -29
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +15 -2
  157. package/react-router.d.ts +15 -2
  158. package/react-router.js +129 -29
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CbIV7145.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-BCtZg31b.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +9 -1
  163. package/solidjs.d.ts +9 -1
  164. package/solidjs.js +129 -29
  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 +16 -2
  215. package/svelte.d.ts +16 -2
  216. package/svelte.js +129 -29
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +14 -2
  219. package/tanstack.d.ts +14 -2
  220. package/tanstack.js +129 -29
  221. package/tanstack.mjs +1 -1
  222. package/{types-ffLPVG5_.d.ts → types-CrgK5P6p.d.mts} +124 -24
  223. package/{types-ffLPVG5_.d.mts → types-CrgK5P6p.d.ts} +124 -24
@@ -0,0 +1,141 @@
1
+ import { WorkflowError, WorkflowNonRetryableError } from "./error";
2
+ import type { FlowControl } from "@upstash/qstash";
3
+ import { WorkflowClient } from "./types";
4
+
5
+ const NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
6
+ const NANOID_LENGTH = 21;
7
+
8
+ const RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
9
+
10
+ export function validateLabel(label: string | string[] | undefined): void {
11
+ if (label === undefined) return;
12
+
13
+ const labels = Array.isArray(label) ? label : [label];
14
+ if (labels.length === 0) {
15
+ throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
16
+ }
17
+
18
+ for (const value of labels) {
19
+ if (!RESOURCE_NAME_PATTERN.test(value)) {
20
+ throw new WorkflowNonRetryableError(
21
+ `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
22
+ );
23
+ }
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Serializes a label (string or array of strings) into the header value.
29
+ * Arrays are joined with `,` so multiple labels can be sent in a single
30
+ * `Upstash-Label` header.
31
+ */
32
+ export function serializeLabel(label: string | string[]): string {
33
+ return Array.isArray(label) ? label.join(",") : label;
34
+ }
35
+
36
+ export function validateFlowControl(flowControl: FlowControl | undefined): void {
37
+ if (flowControl?.key !== undefined && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
38
+ throw new WorkflowNonRetryableError(
39
+ `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
40
+ );
41
+ }
42
+ }
43
+
44
+ function getRandomInt() {
45
+ return Math.floor(Math.random() * NANOID_CHARS.length);
46
+ }
47
+
48
+ /**
49
+ * @param length length of the generated id
50
+ */
51
+ export function nanoid(length: number = NANOID_LENGTH): string {
52
+ return Array.from({ length })
53
+ .map(() => NANOID_CHARS[getRandomInt()])
54
+ .join("");
55
+ }
56
+
57
+ /**
58
+ * @param id optional id to use as suffix
59
+ */
60
+ export function getWorkflowRunId(id?: string): string {
61
+ return `wfr_${id ?? nanoid()}`;
62
+ }
63
+
64
+ /**
65
+ * When the base64 string has unicode characters, atob doesn't decode
66
+ * them correctly since it only outputs ASCII characters. Therefore,
67
+ * instead of using atob, we properly decode them.
68
+ *
69
+ * If the decoding into unicode somehow fails, returns the result of atob
70
+ *
71
+ * https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
72
+ *
73
+ * @param base64 encoded string
74
+ */
75
+ export function decodeBase64(base64: string) {
76
+ const binString = atob(base64);
77
+ try {
78
+ // @ts-expect-error m will always be defined
79
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
80
+ return new TextDecoder().decode(intArray);
81
+ } catch (error) {
82
+ // this error should never happen essentially. It's only a failsafe
83
+ console.warn(
84
+ `Upstash Qstash: Failed while decoding base64 "${base64}".` +
85
+ ` Decoding with atob and returning it instead. ${error}`
86
+ );
87
+ return binString;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * @param qstashClient QStash client to extract user ID from
93
+ */
94
+ export function getUserIdFromToken(qstashClient: WorkflowClient): string {
95
+ try {
96
+ const token = (qstashClient as WorkflowClient & { token: string }).token;
97
+ const decodedToken = decodeBase64(token);
98
+ const tokenPayload = JSON.parse(decodedToken) as { UserID: string };
99
+ const userId = tokenPayload.UserID;
100
+
101
+ if (!userId) {
102
+ throw new WorkflowError("QStash token payload does not contain userId");
103
+ }
104
+ return userId;
105
+ } catch (error) {
106
+ throw new WorkflowError(
107
+ `Failed to decode QStash token while running create webhook step: ${(error as Error).message}`
108
+ );
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @param qstashClient QStash client to extract URL from
114
+ */
115
+ export function getQStashUrl(qstashClient: WorkflowClient): string {
116
+ try {
117
+ const requester = qstashClient.http;
118
+ const baseUrl = (requester as typeof requester & { baseUrl: string }).baseUrl;
119
+
120
+ if (!baseUrl) {
121
+ throw new WorkflowError("QStash client does not have a baseUrl");
122
+ }
123
+ return baseUrl;
124
+ } catch (error) {
125
+ throw new WorkflowError(`Failed to get QStash URL from client: ${(error as Error).message}`);
126
+ }
127
+ }
128
+
129
+ export function getEventId(): string {
130
+ return `evt_${nanoid(15)}`;
131
+ }
132
+
133
+ export function stringifyBody(body: unknown): string | undefined {
134
+ if (body === undefined) {
135
+ return undefined;
136
+ }
137
+ if (typeof body === "string") {
138
+ return body;
139
+ }
140
+ return JSON.stringify(body);
141
+ }
@@ -0,0 +1,472 @@
1
+ import type { Err, Ok } from "neverthrow";
2
+ import { err, ok } from "neverthrow";
3
+ import { WorkflowError } from "./error";
4
+ import {
5
+ NO_CONCURRENCY,
6
+ WORKFLOW_FAILURE_CALLBACK_HEADER,
7
+ WORKFLOW_FAILURE_HEADER,
8
+ WORKFLOW_ID_HEADER,
9
+ WORKFLOW_LABEL_HEADER,
10
+ WORKFLOW_PROTOCOL_VERSION,
11
+ WORKFLOW_PROTOCOL_VERSION_HEADER,
12
+ WORKFLOW_RETRIED_HEADER,
13
+ WORKFLOW_UNKOWN_SDK_VERSION_HEADER,
14
+ } from "./constants";
15
+ import type {
16
+ FailureFunctionPayload,
17
+ RawStep,
18
+ Step,
19
+ WorkflowServeOptions,
20
+ WorkflowClient,
21
+ RouteFunction,
22
+ } from "./types";
23
+ import { WorkflowContext } from "./context";
24
+ import { recreateUserHeaders } from "./workflow-requests";
25
+ import { decodeBase64, getWorkflowRunId } from "./utils";
26
+ import { getSteps } from "./client/utils";
27
+ import { getEffectiveConfig } from "./qstash/step-config";
28
+ import { Client } from "@upstash/qstash";
29
+ import { DisabledWorkflowContext } from "./serve/authorization";
30
+ import { DispatchDebug } from "./middleware/types";
31
+
32
+ /**
33
+ * Gets the request body. If that fails, returns undefined
34
+ *
35
+ * @param request request received in the workflow api
36
+ * @returns request body
37
+ */
38
+ export const getPayload = async (request: Request) => {
39
+ try {
40
+ return await request.text();
41
+ } catch {
42
+ return;
43
+ }
44
+ };
45
+
46
+ /**
47
+ * Parses a request coming from QStash. First parses the string as JSON, which will result
48
+ * in a list of objects with messageId & body fields. Body will be base64 encoded.
49
+ *
50
+ * Body of the first item will be the body of the first request received in the workflow API.
51
+ * Rest are steps in Upstash Workflow Step format.
52
+ *
53
+ * When returning steps, we add the initial payload as initial step. This is to make it simpler
54
+ * in the rest of the code.
55
+ *
56
+ * @param rawSteps list of raw steps from QStash
57
+ * @returns initial payload and list of steps
58
+ */
59
+ const processRawSteps = (rawSteps: RawStep[]) => {
60
+ const [encodedInitialPayload, ...encodedSteps] = rawSteps;
61
+
62
+ // decode initial payload:
63
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
64
+ const initialStep: Step = {
65
+ stepId: 0,
66
+ stepName: "init",
67
+ stepType: "Initial",
68
+ out: rawInitialPayload,
69
+ concurrent: NO_CONCURRENCY,
70
+ };
71
+
72
+ // only keep step entries (skips "toCallback", "fromCallback" and "stepConfig"):
73
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
74
+
75
+ // decode & parse other steps:
76
+ const otherSteps = stepsToDecode.map((rawStep) => {
77
+ const step = JSON.parse(decodeBase64(rawStep.body)) as Step;
78
+ return step;
79
+ });
80
+
81
+ // join and deduplicate steps:
82
+ const steps: Step[] = [initialStep, ...otherSteps];
83
+ return {
84
+ rawInitialPayload,
85
+ steps,
86
+ };
87
+ };
88
+
89
+ /**
90
+ * Our steps list can potentially have duplicates. In this case, the
91
+ * workflow SDK should get rid of the duplicates
92
+ *
93
+ * There are two potentials cases:
94
+ * 1. Two results steps with equal stepId fields.
95
+ * 2. Two plan steps with equal targetStep fields.
96
+ *
97
+ * @param steps steps with possible duplicates
98
+ * @returns deduplicated steps
99
+ */
100
+ const deduplicateSteps = (steps: Step[]): Step[] => {
101
+ const targetStepIds: number[] = [];
102
+ const stepIds: number[] = [];
103
+ const deduplicatedSteps: Step[] = [];
104
+
105
+ for (const step of steps) {
106
+ if (step.stepId === 0) {
107
+ // Step is a plan step
108
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
109
+ deduplicatedSteps.push(step);
110
+ targetStepIds.push(step.targetStep ?? 0);
111
+ }
112
+ } else {
113
+ // Step is a result step
114
+ if (!stepIds.includes(step.stepId)) {
115
+ deduplicatedSteps.push(step);
116
+ stepIds.push(step.stepId);
117
+ }
118
+ }
119
+ }
120
+
121
+ return deduplicatedSteps;
122
+ };
123
+
124
+ /**
125
+ * Checks if the last step is duplicate. If so, we will discard
126
+ * this call.
127
+ *
128
+ * @param steps steps list to check
129
+ * @param dispatchDebug optional debug dispatcher
130
+ * @returns boolean denoting whether the last one is duplicate
131
+ */
132
+ const checkIfLastOneIsDuplicate = async (
133
+ steps: Step[],
134
+ dispatchDebug?: DispatchDebug
135
+ ): Promise<boolean> => {
136
+ // return false if the length is 0 or 1
137
+ if (steps.length < 2) {
138
+ return false;
139
+ }
140
+
141
+ const lastStep = steps.at(-1)!;
142
+ const lastStepId = lastStep.stepId;
143
+ const lastTargetStepId = lastStep.targetStep;
144
+ for (let index = 0; index < steps.length - 1; index++) {
145
+ const step = steps[index];
146
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
147
+ const message =
148
+ `Upstash Workflow: The step '${step.stepName}' with id '${step.stepId}'` +
149
+ " has run twice during workflow execution. Rest of the workflow will continue running as usual.";
150
+
151
+ await dispatchDebug?.("onWarning", {
152
+ warning: message,
153
+ });
154
+ return true;
155
+ }
156
+ }
157
+ return false;
158
+ };
159
+
160
+ /**
161
+ * Validates the incoming request checking the workflow protocol
162
+ * version and whether it is the first invocation.
163
+ *
164
+ * Raises `WorkflowError` if:
165
+ * - it's not the first invocation and expected protocol version doesn't match
166
+ * the request.
167
+ * - it's not the first invocation but there is no workflow id in the headers.
168
+ *
169
+ * @param request request received
170
+ * @returns whether it's the first invocation and the workflow id
171
+ */
172
+ export const validateRequest = (
173
+ request: Request
174
+ ): { isFirstInvocation: boolean; workflowRunId: string; unknownSdk: boolean } => {
175
+ if (request.headers.get(WORKFLOW_UNKOWN_SDK_VERSION_HEADER)) {
176
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
177
+
178
+ if (!workflowRunId) {
179
+ throw new WorkflowError(
180
+ "Couldn't get workflow id from header when handling unknown sdk request"
181
+ );
182
+ }
183
+
184
+ return {
185
+ unknownSdk: true,
186
+ isFirstInvocation: true,
187
+ workflowRunId,
188
+ };
189
+ }
190
+
191
+ if (request.headers.get(WORKFLOW_FAILURE_CALLBACK_HEADER)) {
192
+ // when failure callback is called, WORKFLOW_PROTOCOL_VERSION_HEADER isn't set, so
193
+ // we consider it as first invocation. But in the case of /trigger endpoint,
194
+ // WORKFLOW_PROTOCOL_VERSION_HEADER is set, so we check for
195
+ // WORKFLOW_FAILURE_CALLBACK_HEADER
196
+
197
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
198
+
199
+ if (!workflowRunId) {
200
+ throw new WorkflowError(
201
+ "Couldn't get workflow id from header when handling failure callback request"
202
+ );
203
+ }
204
+ return {
205
+ unknownSdk: false,
206
+ isFirstInvocation: true,
207
+ workflowRunId,
208
+ };
209
+ }
210
+
211
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
212
+ const isFirstInvocation = !versionHeader;
213
+
214
+ // if it's not the first invocation, verify that the workflow protocal version is correct
215
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
216
+ throw new WorkflowError(
217
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION},` +
218
+ ` got ${versionHeader} from the request.`
219
+ );
220
+ }
221
+
222
+ // get workflow id
223
+ const workflowRunId = isFirstInvocation
224
+ ? getWorkflowRunId()
225
+ : (request.headers.get(WORKFLOW_ID_HEADER) ?? "");
226
+ if (workflowRunId.length === 0) {
227
+ throw new WorkflowError("Couldn't get workflow id from header");
228
+ }
229
+
230
+ return {
231
+ isFirstInvocation,
232
+ workflowRunId,
233
+ unknownSdk: false,
234
+ };
235
+ };
236
+
237
+ /**
238
+ * Checks request headers and body
239
+ * - Reads the request body as raw text
240
+ * - Returns the steps. If it's the first invocation, steps are empty.
241
+ * Otherwise, steps are generated from the request body.
242
+ *
243
+ * @param requestPayload payload from the request
244
+ * @param isFirstInvocation whether this is the first invocation
245
+ * @param unknownSdk whether the request is from an unkown sdk version
246
+ * @param workflowRunId workflow run id
247
+ * @param requester QStash client HTTP requester
248
+ * @param messageId optional message id
249
+ * @param dispatchDebug optional debug dispatcher
250
+ * @returns raw initial payload and the steps
251
+ */
252
+ export const parseRequest = async ({
253
+ requestPayload,
254
+ isFirstInvocation,
255
+ unknownSdk,
256
+ workflowRunId,
257
+ requester,
258
+ messageId,
259
+ dispatchDebug,
260
+ }: {
261
+ requestPayload: string | undefined;
262
+ isFirstInvocation: boolean;
263
+ unknownSdk: boolean;
264
+ workflowRunId: string;
265
+ requester: Client["http"];
266
+ messageId?: string;
267
+ dispatchDebug?: DispatchDebug;
268
+ }): Promise<
269
+ | {
270
+ rawInitialPayload: string;
271
+ steps: Step[];
272
+ isLastDuplicate: boolean;
273
+ workflowRunEnded: false;
274
+ }
275
+ | {
276
+ rawInitialPayload: undefined;
277
+ steps: undefined;
278
+ isLastDuplicate: undefined;
279
+ workflowRunEnded: true;
280
+ }
281
+ > => {
282
+ if (isFirstInvocation && !unknownSdk) {
283
+ // if first invocation, return and `serve` will handle publishing the JSON to QStash
284
+ return {
285
+ rawInitialPayload: requestPayload ?? "",
286
+ steps: [],
287
+ isLastDuplicate: false,
288
+ workflowRunEnded: false,
289
+ };
290
+ } else {
291
+ let rawSteps: RawStep[];
292
+
293
+ if (!requestPayload) {
294
+ await dispatchDebug?.("onInfo", {
295
+ info: "request payload is empty, steps will be fetched from QStash.",
296
+ });
297
+
298
+ const { steps: fetchedSteps, workflowRunEnded } = await getSteps(
299
+ requester,
300
+ workflowRunId,
301
+ messageId,
302
+ dispatchDebug
303
+ );
304
+ if (workflowRunEnded) {
305
+ return {
306
+ rawInitialPayload: undefined,
307
+ steps: undefined,
308
+ isLastDuplicate: undefined,
309
+ workflowRunEnded: true,
310
+ };
311
+ }
312
+ rawSteps = fetchedSteps;
313
+ } else {
314
+ rawSteps = JSON.parse(requestPayload) as RawStep[];
315
+ }
316
+ const { rawInitialPayload, steps } = processRawSteps(rawSteps);
317
+
318
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, dispatchDebug);
319
+ const deduplicatedSteps = deduplicateSteps(steps);
320
+
321
+ return {
322
+ rawInitialPayload,
323
+ steps: deduplicatedSteps,
324
+ isLastDuplicate,
325
+ workflowRunEnded: false,
326
+ };
327
+ }
328
+ };
329
+
330
+ /**
331
+ * checks if Upstash-Workflow-Is-Failure header is set to "true". If so,
332
+ * attempts to call the failureFunction function.
333
+ *
334
+ * If the header is set but failureFunction is not passed, returns
335
+ * WorkflowError.
336
+ *
337
+ * @param request incoming request
338
+ * @param requestPayload payload from the request
339
+ * @param qstashClient QStash client
340
+ * @param initialPayloadParser parser for the initial payload
341
+ * @param routeFunction route function to run
342
+ * @param failureFunction function to handle the failure
343
+ * @param env environment variables
344
+ * @param dispatchDebug optional debug dispatcher
345
+ */
346
+ export const handleFailure = async <TInitialPayload>({
347
+ request,
348
+ requestPayload,
349
+ qstashClient,
350
+ initialPayloadParser,
351
+ routeFunction,
352
+ failureFunction,
353
+ env,
354
+ dispatchDebug,
355
+ }: {
356
+ request: Request;
357
+ requestPayload: string;
358
+ qstashClient: WorkflowClient;
359
+ initialPayloadParser: Required<WorkflowServeOptions<TInitialPayload>>["initialPayloadParser"];
360
+ routeFunction: RouteFunction<TInitialPayload>;
361
+ failureFunction?: WorkflowServeOptions<TInitialPayload>["failureFunction"];
362
+ env: WorkflowServeOptions["env"];
363
+ dispatchDebug?: DispatchDebug;
364
+ }): Promise<
365
+ | Ok<
366
+ | { result: "not-failure-callback" }
367
+ | { result: "failure-function-executed"; response: string | void }
368
+ | { result: "failure-function-undefined" },
369
+ never
370
+ >
371
+ | Err<never, Error>
372
+ > => {
373
+ if (
374
+ request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true" &&
375
+ !request.headers.get(WORKFLOW_FAILURE_CALLBACK_HEADER)
376
+ ) {
377
+ return ok({ result: "not-failure-callback" });
378
+ }
379
+
380
+ if (!failureFunction) {
381
+ return ok({ result: "failure-function-undefined" });
382
+ }
383
+
384
+ try {
385
+ const { status, header, body, url, sourceBody, workflowRunId, workflowCreatedAt } = JSON.parse(
386
+ requestPayload
387
+ ) as {
388
+ status: number;
389
+ header: Record<string, string[]>;
390
+ body: string;
391
+ url: string;
392
+ sourceHeader: Record<string, string[]>;
393
+ sourceBody: string;
394
+ workflowRunId: string;
395
+ workflowCreatedAt: number;
396
+ sourceMessageId: string;
397
+ };
398
+
399
+ const decodedBody = body ? decodeBase64(body) : "{}";
400
+ let errorMessage: string = "";
401
+ let failStack: string = "";
402
+ try {
403
+ const errorPayload = JSON.parse(decodedBody) as FailureFunctionPayload;
404
+ if (errorPayload.message) {
405
+ errorMessage = errorPayload.message;
406
+ }
407
+ if (errorPayload.stack) {
408
+ failStack = errorPayload.stack;
409
+ }
410
+ } catch {
411
+ // skip
412
+ }
413
+
414
+ if (!errorMessage) {
415
+ errorMessage = `Couldn't parse 'failResponse' in 'failureFunction', received: '${decodedBody}'`;
416
+ }
417
+
418
+ const userHeaders = recreateUserHeaders(request.headers as Headers);
419
+ const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
420
+ // configuration QStash applied to the failure callback delivery,
421
+ // which is the request in hand here
422
+ const effectiveConfig = getEffectiveConfig(request.headers as Headers);
423
+
424
+ // create context
425
+ const workflowContext = new WorkflowContext<TInitialPayload>({
426
+ qstashClient,
427
+ workflowRunId,
428
+ initialPayload: sourceBody
429
+ ? initialPayloadParser(decodeBase64(sourceBody))
430
+ : (undefined as TInitialPayload),
431
+ headers: userHeaders,
432
+ steps: [],
433
+ url: url,
434
+ env,
435
+ telemetry: undefined, // not going to make requests in authentication check
436
+ label: userHeaders.get(WORKFLOW_LABEL_HEADER) ?? undefined,
437
+ retried,
438
+ workflowRunCreatedAt: workflowCreatedAt,
439
+ middlewareManager: undefined,
440
+ effectiveConfig,
441
+ });
442
+
443
+ // attempt running routeFunction until the first step
444
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
445
+ routeFunction,
446
+ workflowContext,
447
+ effectiveConfig
448
+ );
449
+ if (authCheck.isErr()) {
450
+ // got error while running until first step
451
+ await dispatchDebug?.("onError", {
452
+ error: authCheck.error,
453
+ });
454
+ return err(authCheck.error);
455
+ } else if (authCheck.value === "run-ended") {
456
+ // finished routeFunction while trying to run until first step.
457
+ // either there is no step or auth check resulted in `return`
458
+ return err(new WorkflowError("Not authorized to run the failure function."));
459
+ }
460
+
461
+ const failureResponse = await failureFunction({
462
+ context: workflowContext,
463
+ failStatus: status,
464
+ failResponse: errorMessage,
465
+ failHeaders: header,
466
+ failStack,
467
+ });
468
+ return ok({ result: "failure-function-executed", response: failureResponse });
469
+ } catch (error) {
470
+ return err(error as Error);
471
+ }
472
+ };