@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,397 @@
1
+ import { FlowControl, QstashError } from "@upstash/qstash";
2
+ import {
3
+ DEFAULT_CONTENT_TYPE,
4
+ DEFAULT_RETRIES,
5
+ FLOW_CONTROL_KEY_HEADER,
6
+ FLOW_CONTROL_VALUE_HEADER,
7
+ RETRIES_HEADER,
8
+ RETRY_DELAY_HEADER,
9
+ WORKFLOW_CREATED_AT_HEADER,
10
+ WORKFLOW_FAILURE_CALLBACK_HEADER,
11
+ WORKFLOW_FAILURE_HEADER,
12
+ WORKFLOW_FEATURE_HEADER,
13
+ WORKFLOW_FEATURE_SET,
14
+ WORKFLOW_ID_HEADER,
15
+ WORKFLOW_INIT_HEADER,
16
+ WORKFLOW_INVOKE_COUNT_HEADER,
17
+ WORKFLOW_PROTOCOL_VERSION,
18
+ WORKFLOW_PROTOCOL_VERSION_HEADER,
19
+ WORKFLOW_STEP_CONFIG_FEATURE,
20
+ WORKFLOW_URL_HEADER,
21
+ } from "../constants";
22
+ import { BaseLazyStep, LazyCallStep } from "../context/steps";
23
+ import { Step, StepSettings, Telemetry } from "../types";
24
+ import { getTelemetryHeaders, HeadersResponse } from "../workflow-requests";
25
+
26
+ export type WorkflowConfig = {
27
+ retries?: number;
28
+ retryDelay?: string;
29
+ flowControl?: FlowControl;
30
+ failureUrl?: string;
31
+ telemetry?: Telemetry;
32
+ workflowRunId: string;
33
+ workflowUrl: string;
34
+ /**
35
+ * creation time of the workflow run, sent in the `Upstash-Workflow-CreatedAt` header.
36
+ *
37
+ * QStash includes it in the deduplication of workflow requests, so that the
38
+ * requests of a run are not deduplicated against the requests of a previous
39
+ * run started with the same workflow run id and the same data.
40
+ *
41
+ * required so that no request of a run can leave it out by accident. 0 means
42
+ * the creation time is not known (the request didn't carry the header), in
43
+ * which case the header is not sent.
44
+ */
45
+ workflowRunCreatedAt: number;
46
+ useJSONContent?: boolean;
47
+ };
48
+
49
+ /**
50
+ * groups the headers with respect to where they should be passed
51
+ */
52
+ type WorkflowHeaderGroups = {
53
+ /**
54
+ * headers which will be returned as they are, without any prefix
55
+ */
56
+ rawHeaders: Record<string, string>;
57
+ /**
58
+ * headers which should be passed to the workflow endpoint
59
+ *
60
+ * will be prefixed with `Upstash-` or `Upstash-Callback` depending on the step
61
+ */
62
+ workflowHeaders: Record<string, string>;
63
+ /**
64
+ * Headers which should be passed to the failure URL
65
+ *
66
+ * will be prefixed with `Upstash-Failure-Callback-`
67
+ */
68
+ failureHeaders: Record<string, string>;
69
+ /**
70
+ * headers carrying step-level settings.
71
+ *
72
+ * Returned as they are, and applied last so that they win over the
73
+ * settings the run was triggered with, which the groups above carry.
74
+ */
75
+ stepSettingsHeaders: Record<string, string>;
76
+ };
77
+
78
+ type StepInfo = {
79
+ step: Step;
80
+ lazyStep: BaseLazyStep;
81
+ };
82
+
83
+ type WorkflowHeaderParams = {
84
+ userHeaders?: Headers;
85
+ workflowConfig: WorkflowConfig;
86
+ invokeCount?: number;
87
+ initHeaderValue: "true" | "false";
88
+ stepInfo?: StepInfo;
89
+ /**
90
+ * step-level settings to apply to the message being published, so that
91
+ * QStash uses them instead of the settings the run was triggered with.
92
+ */
93
+ stepSettings?: StepSettings;
94
+ };
95
+
96
+ class WorkflowHeaders {
97
+ private userHeaders?: Headers;
98
+ private workflowConfig: WorkflowConfig;
99
+ private invokeCount?: number;
100
+ private initHeaderValue: "true" | "false";
101
+ private stepInfo?: Required<StepInfo>;
102
+ private stepSettings?: StepSettings;
103
+ private headers: WorkflowHeaderGroups;
104
+
105
+ /**
106
+ * @param params workflow header parameters
107
+ */
108
+ constructor({
109
+ userHeaders,
110
+ workflowConfig,
111
+ invokeCount,
112
+ initHeaderValue,
113
+ stepInfo,
114
+ stepSettings,
115
+ }: WorkflowHeaderParams) {
116
+ this.userHeaders = userHeaders;
117
+ this.workflowConfig = workflowConfig;
118
+ this.invokeCount = invokeCount;
119
+ this.initHeaderValue = initHeaderValue;
120
+ this.stepInfo = stepInfo;
121
+ this.stepSettings = stepSettings;
122
+ this.headers = {
123
+ rawHeaders: {},
124
+ workflowHeaders: {},
125
+ failureHeaders: {},
126
+ stepSettingsHeaders: {},
127
+ };
128
+ }
129
+
130
+ getHeaders(): HeadersResponse {
131
+ this.addBaseHeaders();
132
+ this.addRetries();
133
+ this.addRetryDelay();
134
+ this.addFlowControl();
135
+ this.addUserHeaders();
136
+ this.addInvokeCount();
137
+ this.addFailureUrl();
138
+ this.addStepSettings();
139
+ const contentType = this.addContentType();
140
+
141
+ return this.prefixHeaders(contentType);
142
+ }
143
+
144
+ private addBaseHeaders() {
145
+ this.headers.rawHeaders = {
146
+ ...this.headers.rawHeaders,
147
+ [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
148
+ [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
149
+ [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
150
+ [WORKFLOW_FEATURE_HEADER]: WORKFLOW_FEATURE_SET,
151
+ [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
152
+ ...(this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}),
153
+ };
154
+
155
+ if (this.workflowConfig.workflowRunCreatedAt) {
156
+ this.headers.rawHeaders[WORKFLOW_CREATED_AT_HEADER] =
157
+ this.workflowConfig.workflowRunCreatedAt.toString();
158
+ }
159
+
160
+ if (this.stepInfo?.lazyStep.stepType !== "Call") {
161
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] =
162
+ WORKFLOW_PROTOCOL_VERSION;
163
+ }
164
+ }
165
+
166
+ private addInvokeCount() {
167
+ if (this.invokeCount === undefined || this.invokeCount === 0) {
168
+ return;
169
+ }
170
+ const invokeCount = this.invokeCount.toString();
171
+
172
+ this.headers.workflowHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
173
+ if (this.workflowConfig.failureUrl) {
174
+ this.headers.failureHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
175
+ }
176
+
177
+ // for context.call:
178
+ if (this.stepInfo?.lazyStep instanceof LazyCallStep) {
179
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
180
+ }
181
+ }
182
+
183
+ private addRetries() {
184
+ if (
185
+ this.workflowConfig.retries === undefined ||
186
+ this.workflowConfig.retries === DEFAULT_RETRIES
187
+ ) {
188
+ return;
189
+ }
190
+
191
+ const retries = this.workflowConfig.retries.toString();
192
+
193
+ this.headers.workflowHeaders["Retries"] = retries;
194
+ if (this.workflowConfig.failureUrl) {
195
+ this.headers.failureHeaders["Retries"] = retries;
196
+ }
197
+ }
198
+
199
+ private addRetryDelay() {
200
+ if (this.workflowConfig.retryDelay === undefined || this.workflowConfig.retryDelay === "") {
201
+ return;
202
+ }
203
+
204
+ const retryDelay = this.workflowConfig.retryDelay.toString();
205
+
206
+ this.headers.workflowHeaders["Retry-Delay"] = retryDelay;
207
+ if (this.workflowConfig.failureUrl) {
208
+ this.headers.failureHeaders["Retry-Delay"] = retryDelay;
209
+ }
210
+ }
211
+
212
+ private addFlowControl() {
213
+ if (!this.workflowConfig.flowControl) {
214
+ return;
215
+ }
216
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
217
+ this.workflowConfig.flowControl
218
+ );
219
+
220
+ this.headers.workflowHeaders["Flow-Control-Key"] = flowControlKey;
221
+ this.headers.workflowHeaders["Flow-Control-Value"] = flowControlValue;
222
+
223
+ if (this.workflowConfig.failureUrl) {
224
+ this.headers.failureHeaders["Flow-Control-Key"] = flowControlKey;
225
+ this.headers.failureHeaders["Flow-Control-Value"] = flowControlValue;
226
+ }
227
+ }
228
+
229
+ private addUserHeaders() {
230
+ if (!this.userHeaders) {
231
+ return;
232
+ }
233
+
234
+ for (const [key, value] of this.userHeaders.entries()) {
235
+ const forwardKey = `Forward-${key}`;
236
+ this.headers.workflowHeaders[forwardKey] = value;
237
+
238
+ if (this.workflowConfig.failureUrl) {
239
+ this.headers.failureHeaders[forwardKey] = value;
240
+ }
241
+ }
242
+ }
243
+
244
+ private addFailureUrl() {
245
+ if (!this.workflowConfig.failureUrl) {
246
+ return;
247
+ }
248
+
249
+ this.headers.workflowHeaders["Failure-Callback"] = this.workflowConfig.failureUrl;
250
+
251
+ this.headers.failureHeaders[`Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
252
+ this.headers.failureHeaders[`Forward-${WORKFLOW_FAILURE_CALLBACK_HEADER}`] = "true";
253
+ this.headers.failureHeaders["Workflow-Runid"] = this.workflowConfig.workflowRunId;
254
+ this.headers.failureHeaders["Workflow-Init"] = "false";
255
+ this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
256
+ this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
257
+ this.headers.failureHeaders["Feature-Set"] = WORKFLOW_FEATURE_SET;
258
+ if (
259
+ this.workflowConfig.retries !== undefined &&
260
+ this.workflowConfig.retries !== DEFAULT_RETRIES
261
+ ) {
262
+ this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
263
+ }
264
+ if (this.workflowConfig.retryDelay !== undefined && this.workflowConfig.retryDelay !== "") {
265
+ this.headers.failureHeaders["Retry-Delay"] = this.workflowConfig.retryDelay.toString();
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Applies the step-level settings of a step to the message.
271
+ *
272
+ * These headers configure the message itself, so that QStash uses them
273
+ * instead of the settings the run was triggered with. The delivery of
274
+ * the message is what executes the step, which is how a step's
275
+ * settings reach it.
276
+ *
277
+ * When any setting is present the feature set is extended with
278
+ * `WF_StepConfig`, which is what tells QStash to keep them. QStash
279
+ * reports that back on the delivery as `Upstash-Workflow-Step-Config`.
280
+ */
281
+ private addStepSettings() {
282
+ if (!this.stepSettings) {
283
+ return;
284
+ }
285
+
286
+ const headers: Record<string, string> = {};
287
+
288
+ if (this.stepSettings.flowControl) {
289
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
290
+ this.stepSettings.flowControl
291
+ );
292
+ headers[FLOW_CONTROL_KEY_HEADER] = flowControlKey;
293
+ headers[FLOW_CONTROL_VALUE_HEADER] = flowControlValue;
294
+ }
295
+ if (this.stepSettings.retries !== undefined) {
296
+ headers[RETRIES_HEADER] = this.stepSettings.retries.toString();
297
+ }
298
+ if (this.stepSettings.retryDelay) {
299
+ headers[RETRY_DELAY_HEADER] = this.stepSettings.retryDelay;
300
+ }
301
+
302
+ if (Object.keys(headers).length === 0) {
303
+ return;
304
+ }
305
+
306
+ headers[WORKFLOW_FEATURE_HEADER] = `${WORKFLOW_FEATURE_SET},${WORKFLOW_STEP_CONFIG_FEATURE}`;
307
+ this.headers.stepSettingsHeaders = headers;
308
+ }
309
+
310
+ private addContentType() {
311
+ if (this.workflowConfig.useJSONContent) {
312
+ this.headers.rawHeaders["content-type"] = "application/json";
313
+ return "application/json";
314
+ }
315
+
316
+ const callHeaders = new Headers(
317
+ this.stepInfo?.lazyStep instanceof LazyCallStep ? this.stepInfo.lazyStep.headers : {}
318
+ );
319
+ const contentType =
320
+ (callHeaders.get("content-type")
321
+ ? callHeaders.get("content-type")
322
+ : this.userHeaders?.get("Content-Type")
323
+ ? this.userHeaders.get("Content-Type")
324
+ : undefined) ?? DEFAULT_CONTENT_TYPE;
325
+ this.headers.rawHeaders["content-type"] = contentType;
326
+ return contentType;
327
+ }
328
+
329
+ private prefixHeaders(contentType: string): HeadersResponse {
330
+ const { rawHeaders, workflowHeaders, failureHeaders, stepSettingsHeaders } = this.headers;
331
+
332
+ const isCall = this.stepInfo?.lazyStep.stepType === "Call";
333
+ return {
334
+ headers: {
335
+ ...rawHeaders,
336
+ ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
337
+ ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
338
+ ...(isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}),
339
+ // last, so they override the run's settings above. Never
340
+ // prefixed: they configure this message, not its callback.
341
+ ...stepSettingsHeaders,
342
+ },
343
+ contentType,
344
+ };
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Adds a prefix to all header keys.
350
+ *
351
+ * @param headers headers to prefix
352
+ * @param prefix prefix to add
353
+ */
354
+ function addPrefixToHeaders(headers: Record<string, string>, prefix: string) {
355
+ const prefixedHeaders: Record<string, string> = {};
356
+ for (const [key, value] of Object.entries(headers)) {
357
+ prefixedHeaders[`${prefix}${key}`] = value;
358
+ }
359
+ return prefixedHeaders;
360
+ }
361
+
362
+ /**
363
+ * Prepares flow control headers from FlowControl object.
364
+ *
365
+ * @param flowControl flow control configuration
366
+ */
367
+ export const prepareFlowControl = (flowControl: FlowControl) => {
368
+ const parallelism = flowControl.parallelism?.toString();
369
+ const rate = (flowControl.rate ?? flowControl.ratePerSecond)?.toString();
370
+ const period =
371
+ typeof flowControl.period === "number" ? `${flowControl.period}s` : flowControl.period;
372
+
373
+ const controlValue = [
374
+ parallelism ? `parallelism=${parallelism}` : undefined,
375
+ rate ? `rate=${rate}` : undefined,
376
+ period ? `period=${period}` : undefined,
377
+ ].filter(Boolean);
378
+
379
+ if (controlValue.length === 0) {
380
+ throw new QstashError("Provide at least one of parallelism or ratePerSecond for flowControl");
381
+ }
382
+
383
+ return {
384
+ flowControlKey: flowControl.key,
385
+ flowControlValue: controlValue.join(", "),
386
+ };
387
+ };
388
+
389
+ /**
390
+ * Gets headers for workflow requests.
391
+ *
392
+ * @param params workflow header parameters
393
+ */
394
+ export const getHeaders = (params: WorkflowHeaderParams) => {
395
+ const workflowHeaders = new WorkflowHeaders(params);
396
+ return workflowHeaders.getHeaders();
397
+ };
@@ -0,0 +1,268 @@
1
+ import type { FlowControl } from "@upstash/qstash";
2
+ import {
3
+ FLOW_CONTROL_KEY_HEADER,
4
+ FLOW_CONTROL_VALUE_HEADER,
5
+ RETRIES_HEADER,
6
+ RETRY_DELAY_HEADER,
7
+ WORKFLOW_STEP_CONFIG_HEADER,
8
+ } from "../constants";
9
+ import type { Duration, StepSettings } from "../types";
10
+ import { WorkflowNonRetryableError } from "../error";
11
+
12
+ /**
13
+ * Normalize settings once when a step is declared, so delivery comparisons
14
+ * and every publication path use the same values. HTTP headers trim leading
15
+ * and trailing whitespace; an empty retry delay means no override.
16
+ *
17
+ * @param settings settings supplied to context.run
18
+ */
19
+ export const normalizeStepSettings = (settings?: StepSettings): StepSettings | undefined => {
20
+ if (settings === undefined) {
21
+ return undefined;
22
+ }
23
+ const { retries, retryDelay } = settings;
24
+ if (retryDelay !== undefined && typeof retryDelay !== "string") {
25
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
26
+ }
27
+ if (retries !== undefined && (!Number.isInteger(retries) || retries < 0)) {
28
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
29
+ }
30
+ return { ...settings, retryDelay: retryDelay?.trim() || undefined };
31
+ };
32
+
33
+ /**
34
+ * The configuration QStash applied to the delivery in hand.
35
+ *
36
+ * Reported on every delivery through the `Upstash-Flow-Control-*`,
37
+ * `Upstash-Retries` and `Upstash-Retry-Delay` headers. For an ordinary delivery this is the configuration the run was triggered with; for a
38
+ * step-configured delivery it is that step's own configuration, which
39
+ * delivery is meant to execute.
40
+ */
41
+ export type EffectiveConfig = {
42
+ /**
43
+ * flow control applied to this delivery, if any
44
+ */
45
+ flowControl?: NormalizedFlowControl;
46
+ /**
47
+ * retry limit of this delivery, or undefined when QStash did not
48
+ * report one (a version which predates the header)
49
+ */
50
+ retries?: number;
51
+ /**
52
+ * retry delay expression applied to this delivery, if any
53
+ */
54
+ retryDelay?: string;
55
+ /**
56
+ * whether the message of this delivery was published with step-level
57
+ * settings (the guard marker).
58
+ */
59
+ hasStepConfig: boolean;
60
+ };
61
+
62
+ /**
63
+ * Flow control reduced to a form both sides of the protocol agree on.
64
+ *
65
+ * Needed because the SDK and QStash format the same values differently:
66
+ * the SDK joins the control value with ", " and writes durations
67
+ * (`period=1m`), QStash joins with "," and writes whole seconds
68
+ * (`period=60`). `rate` and `ratePerSecond` are aliases on the SDK side.
69
+ * Comparing the header strings would report a mismatch for values which
70
+ * are in fact identical, so both sides are parsed into this shape first.
71
+ */
72
+ export type NormalizedFlowControl = {
73
+ key: string;
74
+ parallelism: number;
75
+ rate: number;
76
+ /**
77
+ * period in whole seconds
78
+ */
79
+ period: number;
80
+ };
81
+
82
+ /**
83
+ * Defaults QStash applies to a flow control it is given, mirrored here so
84
+ * that both sides of a comparison agree on what "unset" means.
85
+ *
86
+ * An unset period becomes one second rather than staying unset (see
87
+ * `parseFlowControl` on the server), so a flow control published without
88
+ * a period is reported back with `period=1`.
89
+ */
90
+ const DEFAULT_PARALLELISM = 0;
91
+ const DEFAULT_RATE = 0;
92
+ const DEFAULT_PERIOD_SECONDS = 1;
93
+
94
+ const SECONDS_PER_UNIT: Record<string, number> = {
95
+ s: 1,
96
+ m: 60,
97
+ h: 60 * 60,
98
+ d: 24 * 60 * 60,
99
+ };
100
+
101
+ /**
102
+ * Converts a duration to whole seconds.
103
+ *
104
+ * @param duration number of seconds, or a duration string such as "1m"
105
+ * @returns the duration in seconds, or undefined if it can't be parsed
106
+ */
107
+ export const durationToSeconds = (duration: number | Duration | string): number | undefined => {
108
+ if (typeof duration === "number") {
109
+ return Number.isFinite(duration) ? duration : undefined;
110
+ }
111
+
112
+ const match = /^(\d+)([smhd])$/.exec(duration.trim());
113
+ if (match) {
114
+ return Number(match[1]) * SECONDS_PER_UNIT[match[2]];
115
+ }
116
+
117
+ // a bare number as a string ("60"), which is how QStash reports periods
118
+ const seconds = Number(duration.trim());
119
+ return Number.isFinite(seconds) ? seconds : undefined;
120
+ };
121
+
122
+ /**
123
+ * Normalizes the flow control of a step's settings.
124
+ *
125
+ * @param flowControl flow control as the user provided it
126
+ */
127
+ export const normalizeFlowControl = (flowControl: FlowControl): NormalizedFlowControl => {
128
+ const period =
129
+ flowControl.period === undefined ? undefined : durationToSeconds(flowControl.period);
130
+ return {
131
+ key: flowControl.key,
132
+ parallelism: flowControl.parallelism ?? DEFAULT_PARALLELISM,
133
+ rate: flowControl.rate ?? flowControl.ratePerSecond ?? DEFAULT_RATE,
134
+ period: period ?? DEFAULT_PERIOD_SECONDS,
135
+ };
136
+ };
137
+
138
+ /**
139
+ * Parses the flow control QStash reports on a delivery.
140
+ *
141
+ * The value is a list of `name=value` pairs, joined with "," by QStash
142
+ * and with ", " by the SDK; both are accepted. Periods are reported in
143
+ * whole seconds by QStash and as durations by the SDK. Fields which are
144
+ * absent take the same defaults QStash applies, so that a flow control
145
+ * published without them compares equal to the one reported back.
146
+ *
147
+ * @param key value of the `Upstash-Flow-Control-Key` header
148
+ * @param value value of the `Upstash-Flow-Control-Value` header
149
+ */
150
+ export const parseFlowControlHeaders = (
151
+ key: string | null,
152
+ value: string | null
153
+ ): NormalizedFlowControl | undefined => {
154
+ if (!key) {
155
+ return undefined;
156
+ }
157
+
158
+ const flowControl: NormalizedFlowControl = {
159
+ key,
160
+ parallelism: DEFAULT_PARALLELISM,
161
+ rate: DEFAULT_RATE,
162
+ period: DEFAULT_PERIOD_SECONDS,
163
+ };
164
+ for (const entry of (value ?? "").split(",")) {
165
+ const [name, rawValue] = entry.split("=").map((part) => part.trim());
166
+ if (!name || rawValue === undefined) {
167
+ continue;
168
+ }
169
+ switch (name) {
170
+ case "parallelism": {
171
+ flowControl.parallelism = Number(rawValue);
172
+ break;
173
+ }
174
+ case "rate": {
175
+ flowControl.rate = Number(rawValue);
176
+ break;
177
+ }
178
+ case "period": {
179
+ flowControl.period = durationToSeconds(rawValue) ?? DEFAULT_PERIOD_SECONDS;
180
+ break;
181
+ }
182
+ }
183
+ }
184
+
185
+ return flowControl;
186
+ };
187
+
188
+ /**
189
+ * Reads the configuration QStash applied to a delivery from its headers.
190
+ *
191
+ * The retry limit arrives on `Upstash-Retries`, which QStash sets last
192
+ * and unconditionally on a delivery, so an absent header means the
193
+ * QStash version does not report it rather than "the limit is zero" —
194
+ * zero being a valid limit. A step's retries are left uncompared in that
195
+ * case, and the run's configuration applies to it. How many retries have
196
+ * already happened is a different header, `Upstash-Retried`.
197
+ *
198
+ * @param headers headers of the incoming request
199
+ */
200
+ export const getEffectiveConfig = (headers: Headers): EffectiveConfig => {
201
+ const retriesHeader = headers.get(RETRIES_HEADER);
202
+ return {
203
+ flowControl: parseFlowControlHeaders(
204
+ headers.get(FLOW_CONTROL_KEY_HEADER),
205
+ headers.get(FLOW_CONTROL_VALUE_HEADER)
206
+ ),
207
+ retries: retriesHeader === null ? undefined : Number(retriesHeader),
208
+ retryDelay: headers.get(RETRY_DELAY_HEADER) ?? undefined,
209
+ hasStepConfig: headers.get(WORKFLOW_STEP_CONFIG_HEADER) === "true",
210
+ };
211
+ };
212
+
213
+ /**
214
+ * Describes how a step's settings differ from the configuration applied
215
+ * to the delivery in hand, or undefined when they agree.
216
+ *
217
+ * Only the fields the step actually sets are compared. QStash falls back
218
+ * to the trigger configuration field by field for retries and retry
219
+ * delay, so a step which sets only `retries` legitimately keeps the
220
+ * run's flow control; comparing flow control there would report a
221
+ * mismatch on every delivery. Flow control itself is all or nothing on
222
+ * the QStash side, so it is compared as a whole.
223
+ *
224
+ * @param stepSettings step-level settings of the step about to execute
225
+ * @param effectiveConfig configuration applied to the current delivery
226
+ * @returns a human readable description of the first mismatch, if any
227
+ */
228
+ export const describeStepSettingsMismatch = (
229
+ stepSettings: StepSettings,
230
+ effectiveConfig: EffectiveConfig
231
+ ): string | undefined => {
232
+ if (stepSettings.flowControl) {
233
+ const wanted = normalizeFlowControl(stepSettings.flowControl);
234
+ const applied = effectiveConfig.flowControl;
235
+ if (
236
+ !applied ||
237
+ applied.key !== wanted.key ||
238
+ applied.parallelism !== wanted.parallelism ||
239
+ applied.rate !== wanted.rate ||
240
+ applied.period !== wanted.period
241
+ ) {
242
+ return (
243
+ `flow control: expected ${JSON.stringify(wanted)},` +
244
+ ` delivery has ${JSON.stringify(applied)}`
245
+ );
246
+ }
247
+ }
248
+
249
+ if (
250
+ stepSettings.retries !== undefined &&
251
+ effectiveConfig.retries !== undefined &&
252
+ stepSettings.retries !== effectiveConfig.retries
253
+ ) {
254
+ return `retries: expected ${stepSettings.retries}, delivery has ${effectiveConfig.retries}`;
255
+ }
256
+
257
+ if (
258
+ stepSettings.retryDelay !== undefined &&
259
+ stepSettings.retryDelay !== effectiveConfig.retryDelay
260
+ ) {
261
+ return (
262
+ `retry delay: expected '${stepSettings.retryDelay}',` +
263
+ ` delivery has '${effectiveConfig.retryDelay ?? ""}'`
264
+ );
265
+ }
266
+
267
+ return undefined;
268
+ };