@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.
- package/README.md +9 -0
- package/astro.d.mts +19 -2
- package/astro.d.ts +19 -2
- package/astro.js +670 -159
- package/astro.mjs +1 -1
- package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
- package/cloudflare.d.mts +17 -2
- package/cloudflare.d.ts +17 -2
- package/cloudflare.js +670 -159
- package/cloudflare.mjs +1 -1
- package/docs/agents/examples.mdx +8 -0
- package/docs/agents/features.mdx +375 -0
- package/docs/agents/getting-started.mdx +139 -0
- package/docs/agents/overview.mdx +40 -0
- package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
- package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
- package/docs/agents/patterns/parallelization.mdx +77 -0
- package/docs/agents/patterns/prompt-chaining.mdx +84 -0
- package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
- package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
- package/docs/basics/best-practices/deterministic-code.mdx +132 -0
- package/docs/basics/best-practices/idempotency.mdx +38 -0
- package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
- package/docs/basics/best-practices/overview.mdx +35 -0
- package/docs/basics/best-practices/promise-any.mdx +9 -0
- package/docs/basics/best-practices/return-step-results.mdx +80 -0
- package/docs/basics/best-practices/workflow-limits.mdx +62 -0
- package/docs/basics/client/cancel.mdx +137 -0
- package/docs/basics/client/dlq/callback.mdx +21 -0
- package/docs/basics/client/dlq/delete.mdx +120 -0
- package/docs/basics/client/dlq/list.mdx +96 -0
- package/docs/basics/client/dlq/restart.mdx +164 -0
- package/docs/basics/client/dlq/resume.mdx +167 -0
- package/docs/basics/client/logs.mdx +139 -0
- package/docs/basics/client/notify.mdx +79 -0
- package/docs/basics/client/trigger.mdx +139 -0
- package/docs/basics/client/waiters.mdx +31 -0
- package/docs/basics/client.mdx +40 -0
- package/docs/basics/how.mdx +65 -0
- package/docs/basics/serve/advanced.mdx +435 -0
- package/docs/basics/serve.mdx +142 -0
- package/docs/changelog.mdx +174 -0
- package/docs/examples/allInOne.mdx +377 -0
- package/docs/examples/authWebhook.mdx +575 -0
- package/docs/examples/customRetry.mdx +309 -0
- package/docs/examples/customerOnboarding.mdx +230 -0
- package/docs/examples/dynamicWorkflow.mdx +203 -0
- package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
- package/docs/examples/imageProcessing.mdx +339 -0
- package/docs/examples/paymentRetry.mdx +438 -0
- package/docs/examples/waitForEvent.mdx +201 -0
- package/docs/features/dlq/callback.mdx +42 -0
- package/docs/features/dlq/delete.mdx +29 -0
- package/docs/features/dlq/restart.mdx +33 -0
- package/docs/features/dlq/resume.mdx +37 -0
- package/docs/features/dlq.mdx +39 -0
- package/docs/features/failure-callback.mdx +102 -0
- package/docs/features/failureFunction/advanced.mdx +36 -0
- package/docs/features/failureFunction/reliability.mdx +33 -0
- package/docs/features/flow-control/monitor.mdx +22 -0
- package/docs/features/flow-control/parallelism.mdx +45 -0
- package/docs/features/flow-control/rate-period.mdx +46 -0
- package/docs/features/flow-control.mdx +164 -0
- package/docs/features/invoke/serveMany.mdx +109 -0
- package/docs/features/invoke.mdx +39 -0
- package/docs/features/notify.mdx +127 -0
- package/docs/features/parallel-steps.mdx +41 -0
- package/docs/features/retries/prevent-retries.mdx +140 -0
- package/docs/features/retries.mdx +93 -0
- package/docs/features/wait-for-event.mdx +104 -0
- package/docs/features/wait.mdx +44 -0
- package/docs/features/webhooks.mdx +116 -0
- package/docs/getstarted.mdx +200 -0
- package/docs/howto/cancel.mdx +50 -0
- package/docs/howto/changes.mdx +33 -0
- package/docs/howto/configure.mdx +42 -0
- package/docs/howto/failures.mdx +185 -0
- package/docs/howto/get-token.mdx +18 -0
- package/docs/howto/local-development/development-server.mdx +130 -0
- package/docs/howto/local-development/local-tunnel.mdx +73 -0
- package/docs/howto/middlewares.mdx +263 -0
- package/docs/howto/migrations.mdx +335 -0
- package/docs/howto/multi-region.mdx +107 -0
- package/docs/howto/parallel-runs.mdx +52 -0
- package/docs/howto/readonly-token.mdx +19 -0
- package/docs/howto/realtime/basic.mdx +315 -0
- package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
- package/docs/howto/redact-fields.mdx +61 -0
- package/docs/howto/retry-now.mdx +41 -0
- package/docs/howto/schedule.mdx +114 -0
- package/docs/howto/security.mdx +143 -0
- package/docs/howto/singleton.mdx +137 -0
- package/docs/howto/start.mdx +69 -0
- package/docs/howto/use-webhooks.mdx +256 -0
- package/docs/integrations/aisdk.mdx +316 -0
- package/docs/integrations/anthropic.mdx +51 -0
- package/docs/integrations/datadog.mdx +69 -0
- package/docs/integrations/openai.mdx +87 -0
- package/docs/integrations/prometheus.mdx +65 -0
- package/docs/integrations/resend.mdx +82 -0
- package/docs/llms-txt.mdx +4 -0
- package/docs/openapi.yaml +2946 -0
- package/docs/pricing.mdx +22 -0
- package/docs/quickstarts/astro.mdx +185 -0
- package/docs/quickstarts/cloudflare-workers.mdx +190 -0
- package/docs/quickstarts/express.mdx +190 -0
- package/docs/quickstarts/fastapi.mdx +282 -0
- package/docs/quickstarts/flask.mdx +282 -0
- package/docs/quickstarts/hono.mdx +221 -0
- package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
- package/docs/quickstarts/nextjs-flask.mdx +147 -0
- package/docs/quickstarts/nuxt.mdx +169 -0
- package/docs/quickstarts/platforms.mdx +78 -0
- package/docs/quickstarts/solidjs.mdx +161 -0
- package/docs/quickstarts/svelte.mdx +170 -0
- package/docs/quickstarts/tanstack-start.mdx +205 -0
- package/docs/quickstarts/vercel-nextjs.mdx +233 -0
- package/docs/roadmap.mdx +8 -0
- package/docs/sdk/workflow-js.mdx +4 -0
- package/docs/sdk/workflow-py.mdx +4 -0
- package/docs/steps/api.mdx +64 -0
- package/docs/steps/call.mdx +183 -0
- package/docs/steps/cancel.mdx +25 -0
- package/docs/steps/createWebhook.mdx +40 -0
- package/docs/steps/invoke.mdx +100 -0
- package/docs/steps/notify.mdx +105 -0
- package/docs/steps/run.mdx +150 -0
- package/docs/steps/sleep.mdx +97 -0
- package/docs/steps/sleepUntil.mdx +88 -0
- package/docs/steps/waitForEvent.mdx +60 -0
- package/docs/steps/waitForWebhook.mdx +78 -0
- package/docs/steps.mdx +108 -0
- package/docs/troubleshooting/general.mdx +331 -0
- package/docs/troubleshooting/vercel.mdx +82 -0
- package/express.d.mts +19 -2
- package/express.d.ts +19 -2
- package/express.js +670 -159
- package/express.mjs +1 -1
- package/h3.d.mts +19 -2
- package/h3.d.ts +19 -2
- package/h3.js +670 -159
- package/h3.mjs +1 -1
- package/hono.d.mts +17 -2
- package/hono.d.ts +17 -2
- package/hono.js +670 -159
- package/hono.mjs +1 -1
- package/index.d.mts +50 -21
- package/index.d.ts +50 -21
- package/index.js +686 -171
- package/index.mjs +17 -13
- package/nextjs.d.mts +40 -2
- package/nextjs.d.ts +40 -2
- package/nextjs.js +670 -159
- package/nextjs.mjs +1 -1
- package/package.json +1 -1
- package/react-router.d.mts +16 -2
- package/react-router.d.ts +16 -2
- package/react-router.js +670 -159
- package/react-router.mjs +1 -1
- package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
- package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
- package/solidjs.d.mts +10 -1
- package/solidjs.d.ts +10 -1
- package/solidjs.js +670 -159
- package/solidjs.mjs +1 -1
- package/src/platforms/astro.ts +84 -0
- package/src/platforms/cloudflare.ts +127 -0
- package/src/platforms/express.ts +147 -0
- package/src/platforms/h3.ts +105 -0
- package/src/platforms/hono.ts +103 -0
- package/src/platforms/nextjs.ts +193 -0
- package/src/platforms/react-router.ts +92 -0
- package/src/platforms/solidjs.ts +59 -0
- package/src/platforms/svelte.ts +99 -0
- package/src/platforms/tanstack.ts +96 -0
- package/src/src/client/dlq.ts +387 -0
- package/src/src/client/filter-types.ts +166 -0
- package/src/src/client/index.ts +350 -0
- package/src/src/client/types.ts +501 -0
- package/src/src/client/utils.ts +307 -0
- package/src/src/constants.ts +82 -0
- package/src/src/context/api/anthropic.ts +58 -0
- package/src/src/context/api/base.ts +52 -0
- package/src/src/context/api/index.ts +24 -0
- package/src/src/context/api/openai.ts +125 -0
- package/src/src/context/api/resend.ts +57 -0
- package/src/src/context/auto-executor.ts +707 -0
- package/src/src/context/context.ts +681 -0
- package/src/src/context/index.ts +1 -0
- package/src/src/context/provider.ts +37 -0
- package/src/src/context/steps.ts +965 -0
- package/src/src/error.ts +203 -0
- package/src/src/index.ts +13 -0
- package/src/src/middleware/default-callbacks.ts +20 -0
- package/src/src/middleware/index.ts +2 -0
- package/src/src/middleware/logging.ts +39 -0
- package/src/src/middleware/manager.ts +148 -0
- package/src/src/middleware/middleware.ts +46 -0
- package/src/src/middleware/types.ts +72 -0
- package/src/src/qstash/headers.ts +397 -0
- package/src/src/qstash/step-config.ts +268 -0
- package/src/src/qstash/submit-steps.ts +284 -0
- package/src/src/serve/authorization.ts +118 -0
- package/src/src/serve/index.ts +475 -0
- package/src/src/serve/multi-region/handlers.ts +225 -0
- package/src/src/serve/multi-region/utils.ts +88 -0
- package/src/src/serve/options.ts +241 -0
- package/src/src/serve/serve-many.ts +117 -0
- package/src/src/serve/utils.ts +11 -0
- package/src/src/types.ts +590 -0
- package/src/src/utils.ts +141 -0
- package/src/src/workflow-parser.ts +472 -0
- package/src/src/workflow-requests.ts +575 -0
- package/svelte.d.mts +17 -2
- package/svelte.d.ts +17 -2
- package/svelte.js +670 -159
- package/svelte.mjs +1 -1
- package/tanstack.d.mts +15 -2
- package/tanstack.d.ts +15 -2
- package/tanstack.js +670 -159
- package/tanstack.mjs +1 -1
- package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
- package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
package/src/src/utils.ts
ADDED
|
@@ -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
|
+
};
|