@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.
- package/README.md +9 -0
- package/astro.d.mts +18 -2
- package/astro.d.ts +18 -2
- package/astro.js +129 -29
- package/astro.mjs +1 -1
- package/{chunk-UH6O5IJY.mjs → chunk-J3PXPHSB.mjs} +129 -29
- package/cloudflare.d.mts +16 -2
- package/cloudflare.d.ts +16 -2
- package/cloudflare.js +129 -29
- package/cloudflare.mjs +1 -1
- package/docs/agents/examples.mdx +8 -0
- package/docs/agents/features.mdx +374 -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 +567 -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 +104 -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 +2944 -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 +18 -2
- package/express.d.ts +18 -2
- package/express.js +129 -29
- package/express.mjs +1 -1
- package/h3.d.mts +18 -2
- package/h3.d.ts +18 -2
- package/h3.js +129 -29
- package/h3.mjs +1 -1
- package/hono.d.mts +16 -2
- package/hono.d.ts +16 -2
- package/hono.js +129 -29
- package/hono.mjs +1 -1
- package/index.d.mts +49 -21
- package/index.d.ts +49 -21
- package/index.js +145 -41
- package/index.mjs +17 -13
- package/nextjs.d.mts +39 -2
- package/nextjs.d.ts +39 -2
- package/nextjs.js +129 -29
- package/nextjs.mjs +1 -1
- package/package.json +1 -1
- package/react-router.d.mts +15 -2
- package/react-router.d.ts +15 -2
- package/react-router.js +129 -29
- package/react-router.mjs +1 -1
- package/{serve-many-CbIV7145.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
- package/{serve-many-BCtZg31b.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
- package/solidjs.d.mts +9 -1
- package/solidjs.d.ts +9 -1
- package/solidjs.js +129 -29
- 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 +16 -2
- package/svelte.d.ts +16 -2
- package/svelte.js +129 -29
- package/svelte.mjs +1 -1
- package/tanstack.d.mts +14 -2
- package/tanstack.d.ts +14 -2
- package/tanstack.js +129 -29
- package/tanstack.mjs +1 -1
- package/{types-ffLPVG5_.d.ts → types-CrgK5P6p.d.mts} +124 -24
- package/{types-ffLPVG5_.d.mts → types-CrgK5P6p.d.ts} +124 -24
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Human-in-the-Loop"
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Some workflows require human approval or input before proceeding. When combined with [**Upstash Realtime**](/realtime/overall/quickstart), you can create interactive workflows that pause for user input and provide real-time feedback to your frontend during the entire process.
|
|
6
|
+
|
|
7
|
+
This guide shows you how to implement a human-in-the-loop workflow pattern with real-time updates using Upstash Workflow and Upstash Realtime.
|
|
8
|
+
|
|
9
|
+
## How It Works
|
|
10
|
+
|
|
11
|
+
In a human-in-the-loop workflow:
|
|
12
|
+
|
|
13
|
+
1. The workflow executes initial steps and emits progress events
|
|
14
|
+
2. The workflow pauses at a specific point using [`context.waitForEvent()`](/workflow/features/wait-for-event)
|
|
15
|
+
3. A "waiting for input" event is emitted to notify the frontend
|
|
16
|
+
4. The user makes a decision in the frontend (approve/reject)
|
|
17
|
+
5. The frontend calls an API to notify the workflow using [`client.notify()`](/workflow/basics/client/notify)
|
|
18
|
+
6. The workflow resumes with the user's decision
|
|
19
|
+
7. An "input resolved" event is emitted so the frontend can update its UI
|
|
20
|
+
8. The workflow continues and completes based on the decision
|
|
21
|
+
|
|
22
|
+
## Prerequisites
|
|
23
|
+
|
|
24
|
+
- An Upstash account with:
|
|
25
|
+
- A QStash project for workflows
|
|
26
|
+
- A Redis database for Realtime
|
|
27
|
+
- Next.js application set up
|
|
28
|
+
- Completed the [basic real-time workflow setup](./basic)
|
|
29
|
+
|
|
30
|
+
## Event Types
|
|
31
|
+
|
|
32
|
+
For human-in-the-loop workflows, extend your schema in `lib/realtime.ts` with these additional event types:
|
|
33
|
+
|
|
34
|
+
```typescript {8-14}
|
|
35
|
+
const schema = {
|
|
36
|
+
workflow: {
|
|
37
|
+
runFinish: z.object({}),
|
|
38
|
+
stepFinish: z.object({
|
|
39
|
+
stepName: z.string(),
|
|
40
|
+
result: z.unknown().optional(),
|
|
41
|
+
}),
|
|
42
|
+
waitingForInput: z.object({
|
|
43
|
+
eventId: z.string(),
|
|
44
|
+
message: z.string(),
|
|
45
|
+
}),
|
|
46
|
+
inputResolved: z.object({
|
|
47
|
+
eventId: z.string(),
|
|
48
|
+
}),
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The new event types are:
|
|
54
|
+
|
|
55
|
+
- **`waitingForInput`**: Emitted when the workflow pauses and needs user input
|
|
56
|
+
- **`inputResolved`**: Emitted when the user provides input, so the frontend knows to clear the waiting state
|
|
57
|
+
|
|
58
|
+
## Create the Realtime Middleware
|
|
59
|
+
|
|
60
|
+
Create a custom middleware that will emit events to Realtime at `lib/middleware.ts`:
|
|
61
|
+
|
|
62
|
+
```typescript title="lib/middleware.ts"
|
|
63
|
+
import { WorkflowMiddleware } from "@upstash/workflow";
|
|
64
|
+
import { realtime } from "./realtime";
|
|
65
|
+
|
|
66
|
+
export const realtimeMiddleware = new WorkflowMiddleware({
|
|
67
|
+
name: "realtime-events",
|
|
68
|
+
callbacks: {
|
|
69
|
+
beforeExecution: async ({ context, stepName }) => {
|
|
70
|
+
const channel = realtime.channel(context.workflowRunId);
|
|
71
|
+
|
|
72
|
+
// Detect wait-for-event steps and emit waitingForInput
|
|
73
|
+
if (stepName === "wait-for-approval") {
|
|
74
|
+
await channel.emit("workflow.waitingForInput", {
|
|
75
|
+
eventId: `approval-${context.workflowRunId}`,
|
|
76
|
+
message: `Waiting for approval`,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
afterExecution: async ({ context, stepName, result }) => {
|
|
81
|
+
const channel = realtime.channel(context.workflowRunId);
|
|
82
|
+
|
|
83
|
+
// Emit inputResolved after wait-for-event steps complete
|
|
84
|
+
if (stepName === "wait-for-approval") {
|
|
85
|
+
await channel.emit("workflow.inputResolved", {
|
|
86
|
+
eventId: `approval-${context.workflowRunId}`,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Emit stepFinish for all steps
|
|
91
|
+
await channel.emit("workflow.stepFinish", {
|
|
92
|
+
stepName,
|
|
93
|
+
result,
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
runCompleted: async ({ context }) => {
|
|
97
|
+
const channel = realtime.channel(context.workflowRunId);
|
|
98
|
+
await channel.emit("workflow.runFinish", {});
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**Key points:**
|
|
105
|
+
|
|
106
|
+
- The middleware handles all realtime event emissions automatically
|
|
107
|
+
- `beforeExecution`: Detects wait-for-event steps by checking the stepName and emits `workflow.waitingForInput`
|
|
108
|
+
- `afterExecution`: Emits `workflow.inputResolved` for wait steps and `workflow.stepFinish` for all steps
|
|
109
|
+
- `runCompleted`: Emits `workflow.runFinish` when the workflow finishes
|
|
110
|
+
- All emission logic is centralized in the middleware, keeping workflow code clean
|
|
111
|
+
|
|
112
|
+
## Building the Workflow
|
|
113
|
+
|
|
114
|
+
### 1. Create the Workflow Endpoint
|
|
115
|
+
|
|
116
|
+
Create your workflow at `app/api/workflow/human-in-loop/route.ts`:
|
|
117
|
+
|
|
118
|
+
```typescript title="app/api/workflow/human-in-loop/route.ts"
|
|
119
|
+
import { serve } from "@upstash/workflow/nextjs";
|
|
120
|
+
import { realtimeMiddleware } from "@/lib/middleware";
|
|
121
|
+
|
|
122
|
+
type WorkflowPayload = {
|
|
123
|
+
userId: string;
|
|
124
|
+
action: string;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export const { POST } = serve<WorkflowPayload>(
|
|
128
|
+
async (context) => {
|
|
129
|
+
const { userId, action } = context.requestPayload;
|
|
130
|
+
|
|
131
|
+
// Step 1: Initial Processing
|
|
132
|
+
await context.run("initial-processing", async () => {
|
|
133
|
+
// Your processing logic
|
|
134
|
+
return {
|
|
135
|
+
preprocessed: true,
|
|
136
|
+
userId,
|
|
137
|
+
action,
|
|
138
|
+
requiresApproval: true,
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// Step 2: Wait for Human Approval
|
|
143
|
+
const eventId = `approval-${context.workflowRunId}`;
|
|
144
|
+
|
|
145
|
+
const { eventData, timeout } = await context.waitForEvent<{
|
|
146
|
+
approved: boolean;
|
|
147
|
+
}>("wait-for-approval", eventId, { timeout: "5m" });
|
|
148
|
+
|
|
149
|
+
// Handle timeout
|
|
150
|
+
if (timeout) {
|
|
151
|
+
return { success: false, reason: "timeout" };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const status = eventData.approved ? "approved" : "rejected";
|
|
155
|
+
|
|
156
|
+
// Step 3: Process based on approval
|
|
157
|
+
await context.run(`process-${status}`, async () => {
|
|
158
|
+
return {
|
|
159
|
+
status,
|
|
160
|
+
processedAt: Date.now(),
|
|
161
|
+
action,
|
|
162
|
+
userId,
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// Step 4: Finalize (only if approved)
|
|
167
|
+
if (eventData.approved) {
|
|
168
|
+
// Additional steps...
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
success: true,
|
|
173
|
+
approved: eventData.approved,
|
|
174
|
+
workflowRunId: context.workflowRunId,
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
middlewares: [realtimeMiddleware],
|
|
179
|
+
}
|
|
180
|
+
);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Key patterns:**
|
|
184
|
+
|
|
185
|
+
1. **Middleware for all events**: The `realtimeMiddleware` automatically handles all realtime event emissions by detecting wait-for-event steps through the stepName
|
|
186
|
+
2. **Step name detection**: The middleware checks if `stepName === "wait-for-approval"` to know when to emit `waitingForInput` and `inputResolved` events
|
|
187
|
+
3. **Unique event IDs**: Use a unique `eventId` (like `approval-${workflowRunId}`) to identify which approval request this is
|
|
188
|
+
4. **Timeout handling**: Always handle the timeout case when waiting for events
|
|
189
|
+
|
|
190
|
+
### 2. Create the Notify Endpoint
|
|
191
|
+
|
|
192
|
+
Create an endpoint at `app/api/notify/route.ts` to handle user input:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import { Client } from "@upstash/workflow";
|
|
196
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
197
|
+
|
|
198
|
+
const workflowClient = new Client({
|
|
199
|
+
baseUrl: process.env.QSTASH_URL!,
|
|
200
|
+
token: process.env.QSTASH_TOKEN!,
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
export async function POST(request: NextRequest) {
|
|
204
|
+
const body = await request.json();
|
|
205
|
+
const { eventId, eventData } = body;
|
|
206
|
+
|
|
207
|
+
if (!eventId) {
|
|
208
|
+
return NextResponse.json(
|
|
209
|
+
{ success: false, error: "eventId is required" },
|
|
210
|
+
{ status: 400 }
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Notify the workflow
|
|
215
|
+
await workflowClient.notify({
|
|
216
|
+
eventId,
|
|
217
|
+
eventData,
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return NextResponse.json({ success: true });
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
<Note>
|
|
225
|
+
**Preventing Race Conditions**: If you need to trigger a workflow and immediately send it an event, you can use the `workflowRunId` parameter to enable lookback:
|
|
226
|
+
|
|
227
|
+
```typescript
|
|
228
|
+
await workflowClient.notify({
|
|
229
|
+
eventId,
|
|
230
|
+
eventData,
|
|
231
|
+
workflowRunId: "wfr_abc123", // Ensures notification is delivered even if sent before waitForEvent
|
|
232
|
+
});
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Learn more in the [notify documentation](/workflow/basics/client/notify).
|
|
236
|
+
</Note>
|
|
237
|
+
|
|
238
|
+
## Building the Frontend
|
|
239
|
+
|
|
240
|
+
### 1. Extend the Custom Hook
|
|
241
|
+
|
|
242
|
+
Extend your hook from the basic example to handle waiting states:
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
"use client";
|
|
246
|
+
|
|
247
|
+
import { useRealtime } from "@/lib/realtime-client";
|
|
248
|
+
import { useState, useCallback } from "react";
|
|
249
|
+
|
|
250
|
+
interface WorkflowStep {
|
|
251
|
+
stepName: string;
|
|
252
|
+
result?: unknown;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
interface WaitingState {
|
|
256
|
+
eventId: string;
|
|
257
|
+
message: string;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function useWorkflowWithRealtime() {
|
|
261
|
+
const [workflowRunId, setWorkflowRunId] = useState<string | null>(null);
|
|
262
|
+
const [steps, setSteps] = useState<WorkflowStep[]>([]);
|
|
263
|
+
const [waitingState, setWaitingState] = useState<WaitingState | null>(null);
|
|
264
|
+
const [isTriggering, setIsTriggering] = useState(false);
|
|
265
|
+
const [isRunFinished, setIsRunFinished] = useState(false);
|
|
266
|
+
|
|
267
|
+
useRealtime({
|
|
268
|
+
enabled: !!workflowRunId,
|
|
269
|
+
channels: workflowRunId ? [workflowRunId] : [],
|
|
270
|
+
events: [
|
|
271
|
+
"workflow.stepFinish",
|
|
272
|
+
"workflow.runFinish",
|
|
273
|
+
"workflow.waitingForInput",
|
|
274
|
+
"workflow.inputResolved",
|
|
275
|
+
],
|
|
276
|
+
onData({ event, data }) {
|
|
277
|
+
if (event === "workflow.stepFinish") {
|
|
278
|
+
setSteps((prev) => [
|
|
279
|
+
...prev,
|
|
280
|
+
{
|
|
281
|
+
stepName: data.stepName,
|
|
282
|
+
result: data.result,
|
|
283
|
+
},
|
|
284
|
+
]);
|
|
285
|
+
} else if (event === "workflow.runFinish") {
|
|
286
|
+
setIsRunFinished(true);
|
|
287
|
+
} else if (event === "workflow.inputResolved") {
|
|
288
|
+
// Clear waiting state if it matches
|
|
289
|
+
setWaitingState((prev) =>
|
|
290
|
+
prev?.eventId === data.eventId ? null : prev
|
|
291
|
+
);
|
|
292
|
+
} else if (event === "workflow.waitingForInput") {
|
|
293
|
+
setWaitingState({
|
|
294
|
+
eventId: data.eventId,
|
|
295
|
+
message: data.message,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
const trigger = useCallback(async () => {
|
|
302
|
+
setIsTriggering(true);
|
|
303
|
+
setSteps([]);
|
|
304
|
+
setWaitingState(null);
|
|
305
|
+
setIsRunFinished(false);
|
|
306
|
+
|
|
307
|
+
const response = await fetch("/api/trigger", {
|
|
308
|
+
method: "POST",
|
|
309
|
+
headers: { "Content-Type": "application/json" },
|
|
310
|
+
body: JSON.stringify({ workflowType: "human-in-loop" }),
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
const data = await response.json();
|
|
314
|
+
setWorkflowRunId(data.workflowRunId);
|
|
315
|
+
setIsTriggering(false);
|
|
316
|
+
}, []);
|
|
317
|
+
|
|
318
|
+
const continueWorkflow = useCallback(
|
|
319
|
+
async (data: { approved: boolean }) => {
|
|
320
|
+
if (!waitingState) {
|
|
321
|
+
throw new Error("No workflow waiting for input");
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const response = await fetch("/api/notify", {
|
|
325
|
+
method: "POST",
|
|
326
|
+
headers: { "Content-Type": "application/json" },
|
|
327
|
+
body: JSON.stringify({
|
|
328
|
+
eventId: waitingState.eventId,
|
|
329
|
+
eventData: data,
|
|
330
|
+
}),
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
if (!response.ok) {
|
|
334
|
+
throw new Error("Failed to notify workflow");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// The waiting state will be cleared when we receive inputResolved event
|
|
338
|
+
},
|
|
339
|
+
[waitingState]
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
trigger,
|
|
344
|
+
continueWorkflow,
|
|
345
|
+
isTriggering,
|
|
346
|
+
workflowRunId,
|
|
347
|
+
steps,
|
|
348
|
+
waitingState,
|
|
349
|
+
isRunFinished,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
**Key additions:**
|
|
355
|
+
|
|
356
|
+
- **`waitingState`**: Tracks when the workflow is waiting for input
|
|
357
|
+
- **`continueWorkflow`**: Function to submit user decisions back to the workflow
|
|
358
|
+
- **Multiple events subscription**: Uses `events` array to subscribe to multiple event types
|
|
359
|
+
- **Input resolved handling**: Clears the waiting state when the workflow receives the user's input
|
|
360
|
+
|
|
361
|
+
### 2. Use the Hook with Approval UI
|
|
362
|
+
|
|
363
|
+
```typescript
|
|
364
|
+
"use client";
|
|
365
|
+
|
|
366
|
+
import { useWorkflowWithRealtime } from "@/hooks/useWorkflowWithRealtime";
|
|
367
|
+
|
|
368
|
+
export default function WorkflowPage() {
|
|
369
|
+
const {
|
|
370
|
+
trigger,
|
|
371
|
+
isTriggering,
|
|
372
|
+
steps,
|
|
373
|
+
isRunFinished,
|
|
374
|
+
waitingState,
|
|
375
|
+
continueWorkflow,
|
|
376
|
+
} = useWorkflowWithRealtime();
|
|
377
|
+
|
|
378
|
+
return (
|
|
379
|
+
<div
|
|
380
|
+
style={{
|
|
381
|
+
maxWidth: "600px",
|
|
382
|
+
margin: "40px auto",
|
|
383
|
+
fontFamily: "Arial, sans-serif",
|
|
384
|
+
}}
|
|
385
|
+
>
|
|
386
|
+
<button onClick={trigger} disabled={isTriggering}>
|
|
387
|
+
{isTriggering ? "Starting..." : "Click to Trigger Workflow"}
|
|
388
|
+
</button>
|
|
389
|
+
|
|
390
|
+
{isRunFinished && (
|
|
391
|
+
<h3 style={{ marginTop: "20px" }}>✅ Workflow Finished!</h3>
|
|
392
|
+
)}
|
|
393
|
+
|
|
394
|
+
{/* Show workflow steps */}
|
|
395
|
+
<h3 style={{ marginTop: "20px" }}>Workflow Steps:</h3>
|
|
396
|
+
<div>
|
|
397
|
+
{steps.map((step, index) => (
|
|
398
|
+
<div key={index}>
|
|
399
|
+
<strong>{step.stepName}</strong>
|
|
400
|
+
{Boolean(step.result) && (
|
|
401
|
+
<span>: {JSON.stringify(step.result)}</span>
|
|
402
|
+
)}
|
|
403
|
+
</div>
|
|
404
|
+
))}
|
|
405
|
+
</div>
|
|
406
|
+
|
|
407
|
+
{/* Show approval UI when waiting for input */}
|
|
408
|
+
{waitingState && (
|
|
409
|
+
<div style={{ marginTop: "20px" }} className="approval-prompt">
|
|
410
|
+
<p>{waitingState.message}</p>
|
|
411
|
+
<p>
|
|
412
|
+
<button onClick={() => continueWorkflow({ approved: true })}>
|
|
413
|
+
Click to Approve
|
|
414
|
+
</button>
|
|
415
|
+
</p>
|
|
416
|
+
<p>
|
|
417
|
+
<button onClick={() => continueWorkflow({ approved: false })}>
|
|
418
|
+
Click to Reject
|
|
419
|
+
</button>
|
|
420
|
+
</p>
|
|
421
|
+
</div>
|
|
422
|
+
)}
|
|
423
|
+
</div>
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
## How the Pattern Works
|
|
429
|
+
|
|
430
|
+
### Timeline of Events
|
|
431
|
+
|
|
432
|
+
1. **Initial processing**: `stepFinish` event → Frontend shows completed step
|
|
433
|
+
2. **Waiting for approval**: `waitingForInput` event → Frontend shows approval buttons
|
|
434
|
+
3. **User clicks approve/reject**: Frontend calls `/api/notify`
|
|
435
|
+
4. **Workflow resumes**: `inputResolved` event → Frontend hides approval buttons
|
|
436
|
+
5. **Processing continues**: More `stepFinish` events as workflow continues
|
|
437
|
+
6. **Workflow completes**: `runFinish` event → Frontend shows "Workflow Finished!"
|
|
438
|
+
|
|
439
|
+
## Benefits
|
|
440
|
+
|
|
441
|
+
- **Real-time feedback**: Users see exactly when their approval is needed
|
|
442
|
+
- **No polling**: Instant updates via Server-Sent Events
|
|
443
|
+
- **Timeout handling**: Workflows don't hang indefinitely waiting for input
|
|
444
|
+
|
|
445
|
+
## Full Example
|
|
446
|
+
|
|
447
|
+
For a complete working example with all steps, error handling, and full UI components, check out the [Upstash Realtime example on GitHub](https://github.com/upstash/workflow-js/tree/main/examples/upstash-realtime).
|
|
448
|
+
|
|
449
|
+
## Next Steps
|
|
450
|
+
|
|
451
|
+
- Review the [basic real-time workflow pattern](./basic)
|
|
452
|
+
- Learn about [workflow event handling](/workflow/features/wait-for-event)
|
|
453
|
+
- Explore [Realtime features](/realtime/overall/quickstart)
|
|
454
|
+
- Check out [workflow failure handling](/workflow/features/failure-callback)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Redact Private Data in Upstash Workflow
|
|
3
|
+
sidebarTitle: "Redact Private Data"
|
|
4
|
+
description: "How to redact private data in your workflow runs"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
Workflow runs can contain private data that you don't want visible in the Upstash Console or API responses.
|
|
8
|
+
|
|
9
|
+
Upstash Workflow allows you to redact specific fields so they appear as `REDACTED:<SHA256>` in the dashboard and API. The original values are still used when delivering requests to your workflow endpoint. The SHA256 hash lets you verify the data without revealing the original values.
|
|
10
|
+
|
|
11
|
+
To redact fields, pass the `redact` option when triggering a workflow run.
|
|
12
|
+
|
|
13
|
+
Available options:
|
|
14
|
+
| Option | Description |
|
|
15
|
+
|--|--|
|
|
16
|
+
| body | Redact the body of the workflow steps |
|
|
17
|
+
| headers | Redact the headers of the workflow steps |
|
|
18
|
+
| headers[header_name] | Redact a specific header (e.g., `headers[Authorization]`) |
|
|
19
|
+
|
|
20
|
+
<Info>
|
|
21
|
+
Redaction is one-way. Once a field is redacted, the original value cannot be retrieved from the API or dashboard.
|
|
22
|
+
</Info>
|
|
23
|
+
|
|
24
|
+
<CodeGroup>
|
|
25
|
+
```typescript TypeScript
|
|
26
|
+
import { Client } from "@upstash/workflow";
|
|
27
|
+
|
|
28
|
+
const client = new Client({ token: "<QSTASH_TOKEN>" });
|
|
29
|
+
|
|
30
|
+
const { workflowRunId } = await client.trigger({
|
|
31
|
+
url: "https://my-app.com/api/workflow",
|
|
32
|
+
body: { hello: "world" },
|
|
33
|
+
redact: {
|
|
34
|
+
body: true,
|
|
35
|
+
header: ["Authorization"] // or `header: true` to redact all headers
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
```bash cURL
|
|
42
|
+
curl -XPOST \
|
|
43
|
+
-H 'Authorization: Bearer XXX' \
|
|
44
|
+
-H "Content-Type: application/json" \
|
|
45
|
+
-H "Upstash-Redact-Fields: body, header[Authorization]" \
|
|
46
|
+
-d '{ "hello": "world" }' \
|
|
47
|
+
'https://qstash.upstash.io/v2/publish/https://my-app.com/api/workflow'
|
|
48
|
+
```
|
|
49
|
+
</CodeGroup>
|
|
50
|
+
|
|
51
|
+
<Frame caption="Logs of a workflow run with `body` and header[My-Secret-Header] redacted">
|
|
52
|
+
<img src="/img/qstash/redact-workflow.png" alt="Redacted workflow fields in the Upstash Console" />
|
|
53
|
+
</Frame>
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
Redaction is configured per workflow run, so you can redact different fields for different runs.
|
|
57
|
+
|
|
58
|
+
When `body` is redacted, the step outputs in the dashboard and API will show `REDACTED:<SHA256>` instead of the actual values. The workflow still executes with the original data.
|
|
59
|
+
|
|
60
|
+
If a workflow run fails and moves to the DLQ, the redacted fields remain redacted in the DLQ.
|
|
61
|
+
However, when you retry, resume or restart a workflow run from DLQ, Workflow delivers the original values to your endpoint.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Run a Step Now"
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
A workflow run can be waiting for two reasons: a step is sleeping because of
|
|
6
|
+
`context.sleep` or `context.sleepUntil`, or a step failed and is waiting out its
|
|
7
|
+
retry delay before the next attempt. Both can be released early from the console,
|
|
8
|
+
so the run continues immediately instead of at the scheduled time.
|
|
9
|
+
|
|
10
|
+
## From the console
|
|
11
|
+
|
|
12
|
+
Open the run in the `Logs` tab of the [Upstash Console](https://console.upstash.com/workflow).
|
|
13
|
+
Every waiting step shows a button next to its label: **Run now** on a sleeping
|
|
14
|
+
step and **Retry now** on a step in retry backoff. In a parallel block, each
|
|
15
|
+
branch has its own button.
|
|
16
|
+
|
|
17
|
+
<Frame caption="A parallel block with a sleeping branch and a retrying branch, each with its own button">
|
|
18
|
+
<img src="/img/qstash-workflow/run-now-steps.jpg" alt="Run now and Retry now buttons on workflow steps in the Upstash Console" />
|
|
19
|
+
</Frame>
|
|
20
|
+
|
|
21
|
+
The buttons are only offered while the run is still running and the step is
|
|
22
|
+
genuinely waiting. Once QStash picks the step up, the button disappears and the
|
|
23
|
+
run continues as if the sleep or delay had ended on its own.
|
|
24
|
+
|
|
25
|
+
<Note>
|
|
26
|
+
Releasing a retrying step does not add an attempt. If the step was on its
|
|
27
|
+
last retry and fails again, the run fails and the
|
|
28
|
+
[failure function](/workflow/howto/failures) is called as usual.
|
|
29
|
+
</Note>
|
|
30
|
+
|
|
31
|
+
## From the API
|
|
32
|
+
|
|
33
|
+
Under the hood, a sleeping or retrying step is a delayed QStash message. The
|
|
34
|
+
console calls the [retry a step now](/workflow/api-reference/runs/retry-a-step-now)
|
|
35
|
+
endpoint with the step's message ID, which you can find in the run's
|
|
36
|
+
[event logs](/workflow/api-reference/logs/list-workflow-run-logs).
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
curl -X POST https://qstash.upstash.io/v2/messages/<STEP_MESSAGE_ID>/retry \
|
|
40
|
+
-H "Authorization: Bearer <QSTASH_TOKEN>"
|
|
41
|
+
```
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Schedule a Workflow"
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
You can schedule a workflow to run periodically using a cron definition.
|
|
6
|
+
|
|
7
|
+
For this feature, you would need to use Upstash QStash's Schedules feature.
|
|
8
|
+
|
|
9
|
+
## Scheduling a workflow
|
|
10
|
+
|
|
11
|
+
For example, let's suppose that you have a workflow that creates a backup of some important data daily. Our workflow endpoint might look like this:
|
|
12
|
+
|
|
13
|
+
To run this endpoint on a schedule, navigate to `Schedules` in your QStash dashboard and click `Create Schedule`:
|
|
14
|
+
|
|
15
|
+
<Frame>
|
|
16
|
+
<img src="/img/qstash-workflow/create_schedule.png" alt="Create a Workflow schedule" />
|
|
17
|
+
</Frame>
|
|
18
|
+
|
|
19
|
+
Enter your live endpoint URL, add a CRON expression to define the interval at which your endpoint is called (i.e. every day, every 15 minutes, ...) and click `Schedule`:
|
|
20
|
+
|
|
21
|
+
<Frame>
|
|
22
|
+
<img src="/img/qstash-workflow/schedule_workflow.png" alt="Scheduled Workflow run" />
|
|
23
|
+
</Frame>
|
|
24
|
+
|
|
25
|
+
Your workflow will now run repeatedly at the interval you have defined. For more details on CRON expressions, see our [QStash scheduling documentation](/qstash/features/schedules).
|
|
26
|
+
|
|
27
|
+
## Programmatically Schedule
|
|
28
|
+
|
|
29
|
+
In order to massively improve the user experience, many applications send weekly summary reports to their users. These could be weekly analytics summaries or SEO statistics to keep users engaged with the platform.
|
|
30
|
+
|
|
31
|
+
Let's create a user-specific schedule, sending a first report to each user exactly 7 days after they signed up:
|
|
32
|
+
|
|
33
|
+
<CodeGroup>
|
|
34
|
+
|
|
35
|
+
```typescript api/sign-up/route.ts
|
|
36
|
+
import { signUp } from "@/utils/auth-utils";
|
|
37
|
+
import { Client } from "@upstash/qstash";
|
|
38
|
+
|
|
39
|
+
const client = new Client({ token: process.env.QSTASH_TOKEN! });
|
|
40
|
+
|
|
41
|
+
export async function POST(request: Request) {
|
|
42
|
+
const userData: UserData = await request.json();
|
|
43
|
+
|
|
44
|
+
// Schedule weekly account summary
|
|
45
|
+
await client.schedules.create({
|
|
46
|
+
scheduleId: `user-summary-${user.email}`,
|
|
47
|
+
destination: "https://<YOUR_APP_URL>/api/send-weekly-summary",
|
|
48
|
+
body: { userId: user.id },
|
|
49
|
+
cron: cron,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
return NextResponse.json(
|
|
53
|
+
{ success: true, message: "User registered and summary scheduled" },
|
|
54
|
+
{ status: 201 }
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```python main.py
|
|
60
|
+
from fastapi import FastAPI, Request
|
|
61
|
+
from fastapi.responses import JSONResponse
|
|
62
|
+
from qstash import AsyncQStash
|
|
63
|
+
from datetime import datetime, timedelta
|
|
64
|
+
|
|
65
|
+
app = FastAPI()
|
|
66
|
+
|
|
67
|
+
client = AsyncQStash("<QSTACK_TOKEN>")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@app.post("/api/sign-up")
|
|
71
|
+
async def sign_up(request: Request):
|
|
72
|
+
user_data = await request.json()
|
|
73
|
+
|
|
74
|
+
# Simulate user registration
|
|
75
|
+
user = await sign_up(user_data)
|
|
76
|
+
|
|
77
|
+
# Calculate the date for the first summary (7 days from now)
|
|
78
|
+
first_summary_date = datetime.now() + timedelta(days=7)
|
|
79
|
+
|
|
80
|
+
# Create cron expression for weekly summaries starting 7 days from signup
|
|
81
|
+
cron = f"{first_summary_date.minute} {first_summary_date.hour} * * {first_summary_date.day}"
|
|
82
|
+
|
|
83
|
+
# Schedule weekly account summary
|
|
84
|
+
await client.schedule.create_json(
|
|
85
|
+
schedule_id=f"user-summary-{user.email}",
|
|
86
|
+
destination="https://<YOUR_APP_URL>/api/send-weekly-summary",
|
|
87
|
+
body={"userId": user.id},
|
|
88
|
+
cron=cron,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
return JSONResponse(
|
|
92
|
+
content={"success": True, "message": "User registered and summary scheduled"},
|
|
93
|
+
status_code=201,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
</CodeGroup>
|
|
99
|
+
|
|
100
|
+
This code will call our workflow every week, starting exactly seven days after a user signs up. Each call to our workflow will contain the respective user's ID.
|
|
101
|
+
|
|
102
|
+
<Note>
|
|
103
|
+
When creating a per-user schedule, pass a unique `scheduleId` to identify the schedule for better management and observability.
|
|
104
|
+
</Note>
|