@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,707 @@
1
+ import type { Err, Ok } from "neverthrow";
2
+ import { err, ok } from "neverthrow";
3
+ import { attachStepNameToError, isInstanceOf, WorkflowAbort, WorkflowError } from "../error";
4
+ import type { WorkflowContext } from "./context";
5
+ import type { StepFunction, ParallelCallState, Step, StepSettings, Telemetry } from "../types";
6
+ import { type BaseLazyStep } from "./steps";
7
+ import { QstashError } from "@upstash/qstash";
8
+ import {
9
+ executeStep,
10
+ publishStepConfigRequest,
11
+ submitParallelSteps,
12
+ submitStepResult,
13
+ } from "../qstash/submit-steps";
14
+ import { describeStepSettingsMismatch, type EffectiveConfig } from "../qstash/step-config";
15
+ import { DispatchDebug, DispatchLifecycle } from "../middleware/types";
16
+ import { NO_CONCURRENCY } from "../constants";
17
+
18
+ /**
19
+ * What came of submitting the step being held, if one was.
20
+ */
21
+ export type PendingStepOutcome =
22
+ | { result: "submitted-step"; abort: WorkflowAbort }
23
+ | { result: "no-pending-step" };
24
+
25
+ /**
26
+ * A step which executed but whose result QStash doesn't have yet: either
27
+ * still held, or already on its way. Never both, and never neither while
28
+ * a submission is outstanding.
29
+ */
30
+ type PendingStep =
31
+ | { status: "held"; lazyStep: BaseLazyStep; resultStep: Step }
32
+ | { status: "submitting"; submitted: Promise<WorkflowAbort> };
33
+
34
+ export class AutoExecutor {
35
+ private context: WorkflowContext;
36
+ private promises = new WeakMap<BaseLazyStep[], Promise<unknown>>();
37
+ private activeLazyStepList?: BaseLazyStep[];
38
+
39
+ private readonly nonPlanStepCount: number;
40
+ private readonly steps: Step[];
41
+ private indexInCurrentList = 0;
42
+ private readonly invokeCount: number;
43
+ private readonly telemetry?: Telemetry;
44
+ private readonly dispatchDebug: DispatchDebug;
45
+ private readonly dispatchLifecycle: DispatchLifecycle;
46
+
47
+ public stepCount = 0;
48
+ public planStepCount = 0;
49
+
50
+ protected executingStep: string | false = false;
51
+
52
+ /**
53
+ * an executed step whose result hasn't been submitted to QStash yet.
54
+ *
55
+ * Set when a step which can produce its result in-process executes. The
56
+ * submission waits so that the route function can continue and reveal
57
+ * what comes next: if that is a single step with step-level settings,
58
+ * the settings ride on this submission and no step config request is
59
+ * needed, since the delivery of the submission is what executes it.
60
+ *
61
+ * Flushed when the next step is reached (see `addStep`) or when the
62
+ * route function ends (see `flushPendingStep` in `serve`).
63
+ */
64
+ private pendingStep?: PendingStep;
65
+ /**
66
+ * configuration QStash applied to the delivery being handled. A step
67
+ * with step-level settings is settled by comparing its settings against
68
+ * this.
69
+ */
70
+ private readonly effectiveConfig: EffectiveConfig;
71
+
72
+ /**
73
+ * @param context workflow context
74
+ * @param steps list of steps
75
+ * @param dispatchDebug debug event dispatcher
76
+ * @param dispatchLifecycle lifecycle event dispatcher
77
+ * @param telemetry optional telemetry information
78
+ * @param invokeCount optional invoke count
79
+ * @param effectiveConfig configuration QStash applied to the delivery
80
+ * being handled
81
+ */
82
+ constructor(
83
+ context: WorkflowContext,
84
+ steps: Step[],
85
+ dispatchDebug: DispatchDebug,
86
+ dispatchLifecycle: DispatchLifecycle,
87
+ telemetry?: Telemetry,
88
+ invokeCount?: number,
89
+ effectiveConfig?: EffectiveConfig
90
+ ) {
91
+ this.context = context;
92
+ this.steps = steps;
93
+ this.dispatchDebug = dispatchDebug;
94
+ this.dispatchLifecycle = dispatchLifecycle;
95
+ this.telemetry = telemetry;
96
+ this.invokeCount = invokeCount ?? 0;
97
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
98
+
99
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
100
+ }
101
+
102
+ /**
103
+ * Adds the step function to the list of step functions to run in
104
+ * parallel. After adding the function, defers the execution, so
105
+ * that if there is another step function to be added, it's also
106
+ * added.
107
+ *
108
+ * After all functions are added, list of functions are executed.
109
+ * If there is a single function, it's executed by itself. If there
110
+ * are multiple, they are run in parallel.
111
+ *
112
+ * If a function is already executing (this.executingStep), this
113
+ * means that there is a nested step which is not allowed. In this
114
+ * case, addStep throws WorkflowError.
115
+ *
116
+ * @param stepInfo step plan to add
117
+ * @returns result of the step function
118
+ */
119
+ public async addStep<TResult>(stepInfo: BaseLazyStep<TResult>) {
120
+ if (this.executingStep) {
121
+ throw new WorkflowError(
122
+ "A step can not be run inside another step." +
123
+ ` Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
124
+ );
125
+ }
126
+
127
+ this.stepCount += 1;
128
+
129
+ const lazyStepList = this.activeLazyStepList ?? [];
130
+
131
+ if (!this.activeLazyStepList) {
132
+ this.activeLazyStepList = lazyStepList;
133
+ this.indexInCurrentList = 0;
134
+ }
135
+
136
+ lazyStepList.push(stepInfo);
137
+ const index = this.indexInCurrentList++;
138
+
139
+ const requestComplete = this.deferExecution().then(async () => {
140
+ // A step executed in this invocation and its result is still
141
+ // pending: this new step list is what comes next. Submit the
142
+ // pending result and abort. When what comes next is a single step
143
+ // with step-level settings, the settings ride on that submission,
144
+ // so the delivery it produces is step-configured and executes the step. A
145
+ // parallel group carries its settings on its own plan steps
146
+ // instead, so nothing is attached for it.
147
+ //
148
+ // This runs before `getExecutionPromise`, so the new step's
149
+ // function never executes here — only its settings are read.
150
+ const submitted = await this.submitPendingStep(
151
+ lazyStepList.length === 1 ? lazyStepList[0].stepSettings : undefined
152
+ );
153
+ if (submitted.isErr()) {
154
+ throw submitted.error;
155
+ }
156
+ if (submitted.value.result === "submitted-step") {
157
+ // the held step is on its way to QStash, so this invocation ends
158
+ // here and the next step runs in the delivery it produces
159
+ throw submitted.value.abort;
160
+ }
161
+
162
+ if (!this.promises.has(lazyStepList)) {
163
+ const promise = this.getExecutionPromise(lazyStepList);
164
+ this.promises.set(lazyStepList, promise);
165
+ this.activeLazyStepList = undefined;
166
+
167
+ // if there are more than 1 functions, increment the plan step count
168
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
169
+ }
170
+ const promise = this.promises.get(lazyStepList);
171
+ return promise;
172
+ });
173
+
174
+ const result = await requestComplete;
175
+ return AutoExecutor.getResult<TResult>(lazyStepList, result, index);
176
+ }
177
+
178
+ /**
179
+ * Wraps a step function to set this.executingStep to step name
180
+ * before running and set this.executingStep to False after execution
181
+ * ends.
182
+ *
183
+ * this.executingStep allows us to detect nested steps which are not
184
+ * allowed.
185
+ *
186
+ * @param stepName name of the step being wrapped
187
+ * @param stepFunction step function to wrap
188
+ * @returns wrapped step function
189
+ */
190
+ public wrapStep<TResult = unknown>(
191
+ stepName: string,
192
+ stepFunction: StepFunction<TResult>
193
+ ): TResult | Promise<TResult> {
194
+ this.executingStep = stepName;
195
+ const result = stepFunction();
196
+ this.executingStep = false;
197
+ return result;
198
+ }
199
+
200
+ /**
201
+ * Executes a step:
202
+ * - If the step result is available in the steps, returns the result
203
+ * - If the result is not available, runs the function
204
+ * - Sends the result to QStash
205
+ *
206
+ * @param lazyStep lazy step to execute
207
+ * @returns step result
208
+ */
209
+ protected async runSingle<TResult>(lazyStep: BaseLazyStep<TResult>): Promise<TResult> {
210
+ if (this.stepCount < this.nonPlanStepCount) {
211
+ const step = this.steps[this.stepCount + this.planStepCount];
212
+ validateStep(lazyStep, step);
213
+ const parsedOut = lazyStep.parseOut(step);
214
+
215
+ const isLastMemoized =
216
+ this.stepCount + 1 === this.nonPlanStepCount && this.steps.at(-1)!.stepId !== 0;
217
+
218
+ if (isLastMemoized) {
219
+ await this.dispatchLifecycle("afterExecution", {
220
+ stepName: lazyStep.stepName,
221
+ result: parsedOut,
222
+ });
223
+ }
224
+
225
+ return parsedOut;
226
+ }
227
+
228
+ // A step's settings have to be on the message whose delivery executes
229
+ // it, so before running it, compare what it asked for against the
230
+ // configuration QStash applied to the delivery in hand.
231
+ const mismatch = lazyStep.stepSettings
232
+ ? describeStepSettingsMismatch(lazyStep.stepSettings, this.effectiveConfig)
233
+ : undefined;
234
+
235
+ if (mismatch) {
236
+ if (!this.effectiveConfig.hasStepConfig) {
237
+ // This delivery was not published with step-level settings, so ask
238
+ // for one that is. The step runs in the step-configured delivery that
239
+ // request produces, not here.
240
+ await publishStepConfigRequest({
241
+ context: this.context,
242
+ lazyStep,
243
+ targetStep: this.stepCount,
244
+ invokeCount: this.invokeCount,
245
+ telemetry: this.telemetry,
246
+ dispatchDebug: this.dispatchDebug,
247
+ });
248
+ throw new WorkflowAbort(lazyStep.stepName);
249
+ } else {
250
+ // The settings this SDK published came back in a form it does not
251
+ // recognize, which is a bug in it. Run the step with the settings
252
+ // of the delivery rather than publish a second step config
253
+ // request: that would loop forever, and invisibly, since these
254
+ // requests are hidden from the step logs.
255
+ //
256
+ // `dispatchDebug` writes warnings to the console itself, on top of
257
+ // handing them to any user middleware.
258
+ await this.dispatchDebug("onWarning", {
259
+ warning:
260
+ `The step-level settings of step '${lazyStep.stepName}' were published but are not` +
261
+ ` recognized on the delivery which carries them (${mismatch}). Executing the step with` +
262
+ ` the settings of the delivery instead. This is a bug in @upstash/workflow, please report it.`,
263
+ });
264
+ }
265
+ }
266
+
267
+ const resultStep = await executeStep({
268
+ lazyStep,
269
+ stepId: this.stepCount,
270
+ concurrency: NO_CONCURRENCY,
271
+ dispatchLifecycle: this.dispatchLifecycle,
272
+ });
273
+
274
+ if (lazyStep.supportsDeferredSubmission) {
275
+ // Hold the result instead of submitting it. Returning it lets the
276
+ // route function continue and reveal what comes next, so that a
277
+ // next step's settings can ride on this submission instead of
278
+ // needing a step config request of their own.
279
+ // Capture the output before continuing the route. Neither mutations
280
+ // to the original value nor to the returned copy may change what is
281
+ // recorded for replay. Keep a detached value for getBody to serialize
282
+ // later, so the output is not double-encoded on submission.
283
+ const serializedOut = JSON.stringify(resultStep.out);
284
+ this.pendingStep = {
285
+ status: "held",
286
+ lazyStep,
287
+ resultStep: {
288
+ ...resultStep,
289
+ out: serializedOut === undefined ? undefined : JSON.parse(serializedOut),
290
+ },
291
+ };
292
+
293
+ // Parse a separate copy for the route function, as on replay.
294
+ return lazyStep.parseOut({
295
+ ...resultStep,
296
+ out: serializedOut,
297
+ });
298
+ }
299
+
300
+ await submitStepResult({
301
+ context: this.context,
302
+ lazyStep,
303
+ resultStep,
304
+ invokeCount: this.invokeCount,
305
+ concurrency: NO_CONCURRENCY,
306
+ telemetry: this.telemetry,
307
+ dispatchDebug: this.dispatchDebug,
308
+ });
309
+ throw new WorkflowAbort(lazyStep.stepName, resultStep);
310
+ }
311
+
312
+ /**
313
+ * Submits the result of the step being held, if there is one, and
314
+ * returns the abort the caller has to throw to end the invocation.
315
+ *
316
+ * Returns undefined when no step is being held, which is the caller's
317
+ * signal that there is nothing to end. Throws instead of returning
318
+ * when the submission itself fails, so that error reaches the caller
319
+ * rather than an abort claiming the step was submitted.
320
+ *
321
+ * Callers which arrive while a submission is already under way (the
322
+ * steps of a parallel group, added together) wait for that one and get
323
+ * the same abort, rather than submitting a second time.
324
+ *
325
+ * The next step's settings are attached whenever it has any, without
326
+ * checking them against the current delivery: the executor only knows
327
+ * the configuration of the delivery in hand, which inside a
328
+ * delivery is the *previous* step's, so such a check would be wrong
329
+ * exactly when two steps with settings follow each other.
330
+ *
331
+ * @param nextStepSettings step-level settings of the next step
332
+ * @returns `submitted-step` with the abort which ends this invocation,
333
+ * or `no-pending-step` when nothing was held and there is nothing to
334
+ * end
335
+ */
336
+ public async submitPendingStep(
337
+ nextStepSettings?: StepSettings
338
+ ): Promise<Ok<PendingStepOutcome, never> | Err<never, Error>> {
339
+ if (!this.pendingStep) {
340
+ return ok({ result: "no-pending-step" });
341
+ }
342
+
343
+ try {
344
+ if (this.pendingStep.status === "submitting") {
345
+ return ok({ result: "submitted-step", abort: await this.pendingStep.submitted });
346
+ }
347
+
348
+ const { lazyStep, resultStep } = this.pendingStep;
349
+ const submitted = (async () => {
350
+ await submitStepResult({
351
+ context: this.context,
352
+ lazyStep,
353
+ resultStep,
354
+ invokeCount: this.invokeCount,
355
+ concurrency: NO_CONCURRENCY,
356
+ telemetry: this.telemetry,
357
+ dispatchDebug: this.dispatchDebug,
358
+ nextStepSettings,
359
+ });
360
+ return new WorkflowAbort(lazyStep.stepName, resultStep);
361
+ })();
362
+ this.pendingStep = { status: "submitting", submitted };
363
+
364
+ return ok({ result: "submitted-step", abort: await submitted });
365
+ } catch (error) {
366
+ return err(error as Error);
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Runs steps in parallel.
372
+ *
373
+ * @param parallelSteps list of lazy steps to run in parallel
374
+ * @returns results of the functions run in parallel
375
+ */
376
+ protected async runParallel<TResults extends unknown[]>(parallelSteps: {
377
+ [K in keyof TResults]: BaseLazyStep<TResults[K]>;
378
+ }): Promise<TResults> {
379
+ // get the step count before the parallel steps were added + 1
380
+ // so if there are two initial steps followed by a parallel step,
381
+ // initialStepCount would be 3.
382
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
383
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
384
+
385
+ const sortedSteps = sortSteps(this.steps);
386
+
387
+ // get the expected concurrency. Will be undefined in the `first` case.
388
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
389
+
390
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
391
+ // user has added/removed a parallel step
392
+ throw new WorkflowError(
393
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'.` +
394
+ ` Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
395
+ );
396
+ }
397
+
398
+ await this.dispatchDebug("onInfo", {
399
+ info:
400
+ `Executing parallel steps with: ` +
401
+ JSON.stringify({
402
+ parallelCallState,
403
+ initialStepCount,
404
+ plannedParallelStepCount,
405
+ stepCount: this.stepCount,
406
+ planStepCount: this.planStepCount,
407
+ }),
408
+ });
409
+
410
+ switch (parallelCallState) {
411
+ case "first": {
412
+ await submitParallelSteps({
413
+ context: this.context,
414
+ steps: parallelSteps,
415
+ initialStepCount,
416
+ invokeCount: this.invokeCount,
417
+ telemetry: this.telemetry,
418
+ dispatchDebug: this.dispatchDebug,
419
+ });
420
+ break;
421
+ }
422
+ case "partial": {
423
+ /**
424
+ * Being called by QStash to run one of the parallel steps. Last step in the steps list
425
+ * indicates which step is to be run
426
+ *
427
+ * Execute the step and call QStash with the result
428
+ */
429
+ const planStep = this.steps.at(-1);
430
+ if (!planStep || planStep.targetStep === undefined) {
431
+ throw new WorkflowError(
432
+ `There must be a last step and it should have targetStep larger than 0.` +
433
+ `Received: ${JSON.stringify(planStep)}`
434
+ );
435
+ }
436
+ const stepIndex = planStep.targetStep - initialStepCount;
437
+
438
+ // even though we check for differences in the `last` case, we still need to check
439
+ // here because it's not possible to detect name/type changes in sleep/sleepUntil
440
+ // steps if we don't check here. This is because we wait after submitting the plan
441
+ // step which has the _original step_ name/type but use the 'changed' step name/type
442
+ // when submitting the _result step_.
443
+
444
+ // So in the 'last' case it's not possible to detect step name/type changes for
445
+ // sleep/sleepUntil. It's only possible here:
446
+ validateStep(parallelSteps[stepIndex], planStep);
447
+ try {
448
+ // Unlike a single step, this result is submitted straight away
449
+ // rather than held for the next step's settings to ride on.
450
+ // Holding it would mean carrying on past the parallel group,
451
+ // and a delivery cannot tell whether it is the last of the
452
+ // group: its own result is unrecorded, and so is at least one
453
+ // sibling's. So the step after a parallel group is always
454
+ // reached in an ordinary delivery, and asks for its own.
455
+ const parallelStep = parallelSteps[stepIndex];
456
+ const resultStep = await executeStep({
457
+ lazyStep: parallelStep,
458
+ stepId: planStep.targetStep,
459
+ concurrency: parallelSteps.length,
460
+ dispatchLifecycle: this.dispatchLifecycle,
461
+ });
462
+ await submitStepResult({
463
+ context: this.context,
464
+ lazyStep: parallelStep,
465
+ resultStep,
466
+ invokeCount: this.invokeCount,
467
+ concurrency: parallelSteps.length,
468
+ telemetry: this.telemetry,
469
+ dispatchDebug: this.dispatchDebug,
470
+ });
471
+ throw new WorkflowAbort(parallelStep.stepName, resultStep);
472
+ } catch (error) {
473
+ if (
474
+ isInstanceOf(error, WorkflowAbort) ||
475
+ (isInstanceOf(error, QstashError) && error.status === 400) ||
476
+ (isInstanceOf(error, QstashError) && error.status === 412)
477
+ ) {
478
+ throw error;
479
+ }
480
+ const wrappedError = new WorkflowError(
481
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
482
+ );
483
+ // preserve the failing step name through the re-wrap so it still
484
+ // reaches the error response header
485
+ attachStepNameToError(wrappedError, parallelSteps[stepIndex].stepName);
486
+ throw wrappedError;
487
+ }
488
+ break;
489
+ }
490
+ case "discard": {
491
+ /**
492
+ * We are still executing a parallel step but the last step is not a plan step, which means the parallel
493
+ * execution is in progress (other parallel steps are still running) but one of the parallel steps has
494
+ * called QStash with its result.
495
+ *
496
+ * This call to the API should be discarded: no operations are to be made. Parallel steps which are still
497
+ * running will finish and call QStash eventually.
498
+ */
499
+
500
+ const resultStep = this.steps.at(-1)!;
501
+ const lazyStep = parallelSteps.find(
502
+ (planStep, index) => resultStep.stepId - index === initialStepCount
503
+ );
504
+
505
+ if (lazyStep) {
506
+ await this.dispatchLifecycle("afterExecution", {
507
+ stepName: lazyStep.stepName,
508
+ result: lazyStep.parseOut(resultStep),
509
+ });
510
+ }
511
+
512
+ throw new WorkflowAbort("discarded parallel");
513
+ }
514
+ case "last": {
515
+ /**
516
+ * All steps of the parallel execution have finished.
517
+ *
518
+ * validate the results and return them
519
+ */
520
+
521
+ const parallelResultSteps = sortedSteps
522
+ .filter((step) => step.stepId >= initialStepCount) // filter out plan steps
523
+ .slice(0, parallelSteps.length); // get the result steps of parallel run
524
+
525
+ validateParallelSteps(parallelSteps, parallelResultSteps);
526
+
527
+ const isLastMemoized =
528
+ this.stepCount + 1 === this.nonPlanStepCount && this.steps.at(-1)!.stepId !== 0;
529
+ if (isLastMemoized) {
530
+ const resultStep = this.steps.at(-1)!;
531
+ const lazyStep = parallelSteps.find(
532
+ (planStep, index) => resultStep.stepId - index === initialStepCount
533
+ )!;
534
+
535
+ await this.dispatchLifecycle("afterExecution", {
536
+ stepName: lazyStep.stepName,
537
+ result: lazyStep.parseOut(resultStep),
538
+ });
539
+ }
540
+
541
+ return parallelResultSteps.map((step, index) =>
542
+ parallelSteps[index].parseOut(step)
543
+ ) as TResults;
544
+ }
545
+ }
546
+ const fillValue = undefined;
547
+ return Array.from({ length: parallelSteps.length }).fill(fillValue) as TResults;
548
+ }
549
+
550
+ /**
551
+ * Determines the parallel call state
552
+ *
553
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
554
+ *
555
+ * Depending on the remaining steps, decides the parallel state:
556
+ * - "first": If there are no steps
557
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
558
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
559
+ * step.
560
+ * - "partial": If the last step is a plan step
561
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
562
+ * is in progress (there are still steps to run) and one step has finished and submitted
563
+ * its result to QStash
564
+ *
565
+ * @param parallelStepCount number of steps to run in parallel
566
+ * @param initialStepCount steps after the parallel invocation
567
+ * @returns parallel call state
568
+ */
569
+ protected getParallelCallState(
570
+ parallelStepCount: number,
571
+ initialStepCount: number
572
+ ): ParallelCallState {
573
+ const remainingSteps = this.steps.filter(
574
+ (step) => (step.targetStep || step.stepId) >= initialStepCount
575
+ );
576
+
577
+ if (remainingSteps.length === 0) {
578
+ return "first";
579
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
580
+ // multipying by two since each step in parallel step will result in two
581
+ // steps: one plan step and one result step. If there are 3 parallel steps
582
+ // and steps list has at least 3*2=6 steps, the parallel steps have finished
583
+ return "last";
584
+ } else if (remainingSteps.at(-1)?.targetStep) {
585
+ // if the last step is a plan step, it means the step corresponding to the
586
+ // plan step will execute
587
+ return "partial";
588
+ } else {
589
+ // if the call is not the first/last/partial, it means that it's the result
590
+ // of one of the parallel calls but others are still running, meaning that
591
+ // the current call should be discarded
592
+ return "discard";
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Get the promise by executing the lazt steps list. If there is a single
598
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
599
+ *
600
+ * @param lazyStepList steps list to execute
601
+ * @returns promise corresponding to the execution
602
+ */
603
+ private getExecutionPromise(lazyStepList: BaseLazyStep[]): Promise<unknown> {
604
+ return lazyStepList.length === 1
605
+ ? this.runSingle(lazyStepList[0])
606
+ : this.runParallel(lazyStepList);
607
+ }
608
+
609
+ /**
610
+ * @param lazyStepList steps we executed
611
+ * @param result result of the promise from `getExecutionPromise`
612
+ * @param index index of the current step
613
+ * @returns result[index] if lazyStepList > 1, otherwise result
614
+ */
615
+ private static getResult<TResult>(lazyStepList: BaseLazyStep[], result: unknown, index: number) {
616
+ if (lazyStepList.length === 1) {
617
+ return result as TResult;
618
+ } else if (
619
+ Array.isArray(result) &&
620
+ lazyStepList.length === result.length &&
621
+ index < lazyStepList.length
622
+ ) {
623
+ return result[index] as TResult;
624
+ } else {
625
+ throw new WorkflowError(
626
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
627
+ );
628
+ }
629
+ }
630
+
631
+ private async deferExecution() {
632
+ await Promise.resolve();
633
+ await Promise.resolve();
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Given a BaseLazyStep which is created during execution and a Step parsed
639
+ * from the incoming request; compare the step names and types to make sure
640
+ * that they are the same.
641
+ *
642
+ * Raises `WorkflowError` if there is a difference.
643
+ *
644
+ * @param lazyStep lazy step created during execution
645
+ * @param stepFromRequest step parsed from incoming request
646
+ */
647
+ const validateStep = (lazyStep: BaseLazyStep, stepFromRequest: Step): void => {
648
+ // check step name
649
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
650
+ throw new WorkflowError(
651
+ `Incompatible step name. Expected '${lazyStep.stepName}',` +
652
+ ` got '${stepFromRequest.stepName}' from the request`
653
+ );
654
+ }
655
+ // check type name
656
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
657
+ throw new WorkflowError(
658
+ `Incompatible step type. Expected '${lazyStep.stepType}',` +
659
+ ` got '${stepFromRequest.stepType}' from the request`
660
+ );
661
+ }
662
+ };
663
+
664
+ /**
665
+ * validates that each lazy step and step from request has the same step
666
+ * name and type using `validateStep` method.
667
+ *
668
+ * If there is a difference, raises `WorkflowError` with information
669
+ * about the difference.
670
+ *
671
+ * @param lazySteps list of lazy steps created during parallel execution
672
+ * @param stepsFromRequest list of steps corresponding to the parallel execution
673
+ */
674
+ const validateParallelSteps = (lazySteps: BaseLazyStep[], stepsFromRequest: Step[]): void => {
675
+ try {
676
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
677
+ validateStep(lazySteps[index], stepFromRequest);
678
+ }
679
+ } catch (error) {
680
+ if (isInstanceOf(error, WorkflowError)) {
681
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
682
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
683
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
684
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
685
+ throw new WorkflowError(
686
+ `Incompatible steps detected in parallel execution: ${error.message}` +
687
+ `\n > Step Names from the request: ${JSON.stringify(requestStepNames)}` +
688
+ `\n Step Types from the request: ${JSON.stringify(requestStepTypes)}` +
689
+ `\n > Step Names expected: ${JSON.stringify(lazyStepNames)}` +
690
+ `\n Step Types expected: ${JSON.stringify(lazyStepTypes)}`
691
+ );
692
+ }
693
+ throw error;
694
+ }
695
+ };
696
+
697
+ /**
698
+ * Given a set of steps, sorts them according to their `stepId`s. For plan steps,
699
+ * `targetStep` field is used
700
+ *
701
+ * @param steps list of steps
702
+ * @returns sorted steps
703
+ */
704
+ const sortSteps = (steps: Step[]): Step[] => {
705
+ const getStepId = (step: Step) => step.targetStep || step.stepId;
706
+ return [...steps].sort((step, stepOther) => getStepId(step) - getStepId(stepOther));
707
+ };