@upstash/workflow 1.4.0 → 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 +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 +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 +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
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Custom Retry Logic"
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
## Key Features
|
|
6
|
+
|
|
7
|
+
This example demonstrates how to implement custom retry logic when using third-party services in your Upstash Workflow.
|
|
8
|
+
|
|
9
|
+
We'll use OpenAI as an example for such a third-party service. **Our retry logic uses response status codes and headers to control when to retry, sleep, or store the third-party API response**.
|
|
10
|
+
|
|
11
|
+
## Code Example
|
|
12
|
+
|
|
13
|
+
The following code:
|
|
14
|
+
|
|
15
|
+
1. Attempts to make an API call up to 10 times.
|
|
16
|
+
2. Dynamically adjusts request delays based on response headers or status.
|
|
17
|
+
3. Stores successful responses asynchronously.
|
|
18
|
+
|
|
19
|
+
<CodeGroup>
|
|
20
|
+
|
|
21
|
+
```typescript api/workflow/route.ts
|
|
22
|
+
import { serve } from "@upstash/workflow/nextjs"
|
|
23
|
+
import { storeResponse } from "@/lib/utils"
|
|
24
|
+
|
|
25
|
+
const BASE_DELAY = 10;
|
|
26
|
+
|
|
27
|
+
const createSystemMessage = () => ({
|
|
28
|
+
role: "system",
|
|
29
|
+
content: "You are an AI assistant providing a brief summary and key insights for any given data.",
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
const createUserMessage = (data: string) => ({
|
|
33
|
+
role: "user",
|
|
34
|
+
content: `Analyze this data chunk: ${data}`,
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
export const { POST } = serve<{ userData: string }>(async (context) => {
|
|
38
|
+
// 👇 initial data sent along when triggering the workflow
|
|
39
|
+
const { userData } = context.requestPayload
|
|
40
|
+
|
|
41
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
42
|
+
const response = await context.api.openai.call(`call-openai`, {
|
|
43
|
+
token: process.env.OPENAI_API_KEY!,
|
|
44
|
+
operation: "chat.completions.create",
|
|
45
|
+
body: {
|
|
46
|
+
model: "gpt-3.5-turbo",
|
|
47
|
+
messages: [createSystemMessage(), createUserMessage(userData)],
|
|
48
|
+
max_completion_tokens: 150,
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
// Success case
|
|
53
|
+
if (response.status < 300) {
|
|
54
|
+
await context.run("store-response-in-db", () => storeResponse(response.body))
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Rate limit case - wait and retry
|
|
59
|
+
if (response.status === 429) {
|
|
60
|
+
const resetTime =
|
|
61
|
+
response.header["x-ratelimit-reset-tokens"]?.[0] ||
|
|
62
|
+
response.header["x-ratelimit-reset-requests"]?.[0] ||
|
|
63
|
+
BASE_DELAY
|
|
64
|
+
|
|
65
|
+
// assuming `resetTime` is in seconds
|
|
66
|
+
await context.sleep("sleep-until-retry", Number(resetTime))
|
|
67
|
+
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Any other scenario - pause for 5 seconds to avoid overloading OpenAI API
|
|
72
|
+
await context.sleep("pause-to-avoid-spam", 5)
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```python main.py
|
|
78
|
+
from fastapi import FastAPI
|
|
79
|
+
from typing import Dict, Any, TypedDict
|
|
80
|
+
import os
|
|
81
|
+
from upstash_workflow.fastapi import Serve
|
|
82
|
+
from upstash_workflow import AsyncWorkflowContext, CallResponse
|
|
83
|
+
from utils import store_response
|
|
84
|
+
|
|
85
|
+
app = FastAPI()
|
|
86
|
+
serve = Serve(app)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class InitialData(TypedDict):
|
|
90
|
+
user_data: str
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def create_system_message() -> Dict[str, str]:
|
|
94
|
+
return {
|
|
95
|
+
"role": "system",
|
|
96
|
+
"content": "You are an AI assistant providing a brief summary and key insights for any given data.",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def create_user_message(data: str) -> Dict[str, str]:
|
|
101
|
+
return {"role": "user", "content": f"Analyze this data chunk: {data}"}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@serve.post("/custom-retry-logic")
|
|
105
|
+
async def custom_retry_logic(context: AsyncWorkflowContext[InitialData]) -> None:
|
|
106
|
+
# 👇 initial data sent along when triggering the workflow
|
|
107
|
+
user_data = context.request_payload["user_data"]
|
|
108
|
+
|
|
109
|
+
for attempt in range(10):
|
|
110
|
+
response: CallResponse[Dict[str, Any]] = await context.call(
|
|
111
|
+
"call-openai",
|
|
112
|
+
url="https://api.openai.com/v1/chat/completions",
|
|
113
|
+
method="POST",
|
|
114
|
+
headers={
|
|
115
|
+
"authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}",
|
|
116
|
+
},
|
|
117
|
+
body={
|
|
118
|
+
"model": "gpt-4",
|
|
119
|
+
"messages": [create_system_message(), create_user_message(user_data)],
|
|
120
|
+
"max_tokens": 150,
|
|
121
|
+
},
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# Success case
|
|
125
|
+
if response.status_code < 300:
|
|
126
|
+
|
|
127
|
+
async def _store_response_in_db() -> None:
|
|
128
|
+
await store_response(response.body)
|
|
129
|
+
|
|
130
|
+
await context.run("store-response-in-db", _store_response_in_db)
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
# Rate limit case - wait and retry
|
|
134
|
+
if response.status_code == 429:
|
|
135
|
+
ratelimit_tokens_header = response.header.get("x-ratelimit-reset-tokens")
|
|
136
|
+
ratelimit_requests_header = response.header.get(
|
|
137
|
+
"x-ratelimit-reset-requests"
|
|
138
|
+
)
|
|
139
|
+
reset_time = (
|
|
140
|
+
(ratelimit_tokens_header[0] if ratelimit_tokens_header else None)
|
|
141
|
+
or (ratelimit_requests_header[0] if ratelimit_requests_header else None)
|
|
142
|
+
or 10
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# assuming `reset_time` is in seconds
|
|
146
|
+
await context.sleep("sleep-until-retry", float(reset_time))
|
|
147
|
+
continue
|
|
148
|
+
|
|
149
|
+
# Any other scenario - pause for 5 seconds to avoid overloading OpenAI API
|
|
150
|
+
await context.sleep("pause-to-avoid-spam", 5)
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
</CodeGroup>
|
|
155
|
+
|
|
156
|
+
## Code Breakdown
|
|
157
|
+
|
|
158
|
+
### 1. Setting up our Workflow
|
|
159
|
+
|
|
160
|
+
This POST endpoint serves our workflow. We create a loop to attempt the API call (we're about to write) up to 10 times.
|
|
161
|
+
|
|
162
|
+
<CodeGroup>
|
|
163
|
+
|
|
164
|
+
```typescript TypeScript
|
|
165
|
+
export const { POST } = serve<{ userData: string }>(async (context) => {
|
|
166
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
167
|
+
// TODO: call API in here
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
```python Python
|
|
173
|
+
@serve.post("/custom-retry-logic")
|
|
174
|
+
async def custom_retry_logic(context: AsyncWorkflowContext[InitialData]) -> None:
|
|
175
|
+
for attempt in range(10):
|
|
176
|
+
# TODO: call API in here
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
</CodeGroup>
|
|
181
|
+
|
|
182
|
+
### 2. Making a Third-Party API Call
|
|
183
|
+
|
|
184
|
+
We use `context.api.openai.call` to send a request to OpenAI.
|
|
185
|
+
|
|
186
|
+
<Note>
|
|
187
|
+
`context.api.openai.call` uses `context.call` in the background and
|
|
188
|
+
using `context.call` to request data from an API is one of the most powerful Upstash Workflow
|
|
189
|
+
features. Your request can take much longer than any function timeout would normally allow,
|
|
190
|
+
completely bypassing any platform-specific timeout limits.
|
|
191
|
+
</Note>
|
|
192
|
+
|
|
193
|
+
Our request to OpenAI includes an auth header, model parameters, and the data to be processed by the AI. The response from this function call (`response`) is used to determine our retry logic based on its status code and headers.
|
|
194
|
+
|
|
195
|
+
<CodeGroup>
|
|
196
|
+
|
|
197
|
+
```typescript TypeScript
|
|
198
|
+
const response = await context.api.openai.call(`call-openai`, {
|
|
199
|
+
token: process.env.OPENAI_API_KEY,
|
|
200
|
+
operation: "chat.completions.create",
|
|
201
|
+
body: {
|
|
202
|
+
model: "gpt-3.5-turbo",
|
|
203
|
+
messages: [createSystemMessage(), createUserMessage(userData)],
|
|
204
|
+
max_completion_tokens: 150,
|
|
205
|
+
},
|
|
206
|
+
})
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
```python Python
|
|
210
|
+
response: CallResponse[Dict[str, Any]] = await context.call(
|
|
211
|
+
"call-openai",
|
|
212
|
+
url="https://api.openai.com/v1/chat/completions",
|
|
213
|
+
method="POST",
|
|
214
|
+
headers={
|
|
215
|
+
"authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}",
|
|
216
|
+
},
|
|
217
|
+
body={
|
|
218
|
+
"model": "gpt-4",
|
|
219
|
+
"messages": [create_system_message(), create_user_message(user_data)],
|
|
220
|
+
"max_tokens": 150,
|
|
221
|
+
},
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
</CodeGroup>
|
|
227
|
+
|
|
228
|
+
### 3. Processing a Successful Response (Status Code < 300)
|
|
229
|
+
|
|
230
|
+
If the OpenAI response is successful (status code under 300), we store the response in our database. We create a new workflow task (`workflow.run`) to do this for maximum reliability.
|
|
231
|
+
|
|
232
|
+
<CodeGroup>
|
|
233
|
+
|
|
234
|
+
```typescript TypeScript
|
|
235
|
+
if (response.status < 300) {
|
|
236
|
+
await context.run("store-response-in-db", () => storeResponse(response.body))
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
```python Python
|
|
242
|
+
if response.status_code < 300:
|
|
243
|
+
|
|
244
|
+
async def _store_response_in_db() -> None:
|
|
245
|
+
await store_response(response.body)
|
|
246
|
+
|
|
247
|
+
await context.run("store-response-in-db", _store_response_in_db)
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
</CodeGroup>
|
|
253
|
+
|
|
254
|
+
### 4. Handling Rate Limits (Status Code 429)
|
|
255
|
+
|
|
256
|
+
If the API response indicates a rate limit error (status code 429), we retrieve our rate limit reset values from the response headers. We calculate the time until the rate limit resets and then pause execution (`workflow.sleep`) for this duration.
|
|
257
|
+
|
|
258
|
+
<CodeGroup>
|
|
259
|
+
|
|
260
|
+
```typescript TypeScript
|
|
261
|
+
if (response.status === 429) {
|
|
262
|
+
const resetTime =
|
|
263
|
+
response.header["x-ratelimit-reset-tokens"]?.[0] ||
|
|
264
|
+
response.header["x-ratelimit-reset-requests"]?.[0] ||
|
|
265
|
+
BASE_DELAY
|
|
266
|
+
|
|
267
|
+
// assuming `resetTime` is in seconds
|
|
268
|
+
await context.sleep("sleep-until-retry", Number(resetTime))
|
|
269
|
+
|
|
270
|
+
continue
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
```python Python
|
|
275
|
+
if response.status_code == 429:
|
|
276
|
+
ratelimit_tokens_header = response.header.get("x-ratelimit-reset-tokens")
|
|
277
|
+
ratelimit_requests_header = response.header.get(
|
|
278
|
+
"x-ratelimit-reset-requests"
|
|
279
|
+
)
|
|
280
|
+
reset_time = (
|
|
281
|
+
(ratelimit_tokens_header[0] if ratelimit_tokens_header else None)
|
|
282
|
+
or (ratelimit_requests_header[0] if ratelimit_requests_header else None)
|
|
283
|
+
or 10
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
# assuming `reset_time` is in seconds
|
|
287
|
+
await context.sleep("sleep-until-retry", float(reset_time))
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
</CodeGroup>
|
|
293
|
+
|
|
294
|
+
### 5. Waiting Before the Next Retry Attempt
|
|
295
|
+
|
|
296
|
+
To avoid making too many requests in a short period and possibly overloading the OpenAI API, we pause our workflow before the next retry attempt (i.e., 5 seconds), regardless of rate limits.
|
|
297
|
+
|
|
298
|
+
<CodeGroup>
|
|
299
|
+
|
|
300
|
+
```typescript TypeScript
|
|
301
|
+
await context.sleep("pause-to-avoid-spam", 5)
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
```python Python
|
|
305
|
+
await context.sleep("pause-to-avoid-spam", 5)
|
|
306
|
+
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
</CodeGroup>
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Customer Onboarding"
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
This example demonstrates a customer onboarding process using Upstash Workflow. The following example workflow registers a new user, sends welcome emails, and periodically checks and responds to the user's activity state.
|
|
6
|
+
|
|
7
|
+
## Use Case
|
|
8
|
+
|
|
9
|
+
Our workflow will:
|
|
10
|
+
|
|
11
|
+
1. Register a new user to our service
|
|
12
|
+
2. Send them a welcome email
|
|
13
|
+
3. Wait for a certain time
|
|
14
|
+
4. Periodically check the user's state
|
|
15
|
+
5. Send appropriate emails based on the user's activity
|
|
16
|
+
|
|
17
|
+
## Code Example
|
|
18
|
+
|
|
19
|
+
<CodeGroup>
|
|
20
|
+
|
|
21
|
+
```typescript api/workflow/route.ts
|
|
22
|
+
import { serve } from "@upstash/workflow/nextjs"
|
|
23
|
+
|
|
24
|
+
type InitialData = {
|
|
25
|
+
email: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const { POST } = serve<InitialData>(async (context) => {
|
|
29
|
+
const { email } = context.requestPayload
|
|
30
|
+
|
|
31
|
+
await context.run("new-signup", async () => {
|
|
32
|
+
await sendEmail("Welcome to the platform", email)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
await context.sleep("wait-for-3-days", 60 * 60 * 24 * 3)
|
|
36
|
+
|
|
37
|
+
while (true) {
|
|
38
|
+
const state = await context.run("check-user-state", async () => {
|
|
39
|
+
return await getUserState()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
if (state === "non-active") {
|
|
43
|
+
await context.run("send-email-non-active", async () => {
|
|
44
|
+
await sendEmail("Email to non-active users", email)
|
|
45
|
+
})
|
|
46
|
+
} else if (state === "active") {
|
|
47
|
+
await context.run("send-email-active", async () => {
|
|
48
|
+
await sendEmail("Send newsletter to active users", email)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
await context.sleep("wait-for-1-month", 60 * 60 * 24 * 30)
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
async function sendEmail(message: string, email: string) {
|
|
57
|
+
// Implement email sending logic here
|
|
58
|
+
console.log(`Sending ${message} email to ${email}`)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type UserState = "non-active" | "active"
|
|
62
|
+
|
|
63
|
+
const getUserState = async (): Promise<UserState> => {
|
|
64
|
+
// Implement user state logic here
|
|
65
|
+
return "non-active"
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```python main.py
|
|
70
|
+
from fastapi import FastAPI
|
|
71
|
+
from typing import Literal, TypedDict
|
|
72
|
+
from upstash_workflow.fastapi import Serve
|
|
73
|
+
from upstash_workflow import AsyncWorkflowContext
|
|
74
|
+
|
|
75
|
+
app = FastAPI()
|
|
76
|
+
serve = Serve(app)
|
|
77
|
+
|
|
78
|
+
UserState = Literal["non-active", "active"]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class InitialData(TypedDict):
|
|
82
|
+
email: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def send_email(message: str, email: str) -> None:
|
|
86
|
+
# Implement email sending logic here
|
|
87
|
+
print(f"Sending {message} email to {email}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def get_user_state() -> UserState:
|
|
91
|
+
# Implement user state logic here
|
|
92
|
+
return "non-active"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@serve.post("/customer-onboarding")
|
|
96
|
+
async def customer_onboarding(context: AsyncWorkflowContext[InitialData]) -> None:
|
|
97
|
+
email = context.request_payload["email"]
|
|
98
|
+
|
|
99
|
+
async def _new_signup() -> None:
|
|
100
|
+
await send_email("Welcome to the platform", email)
|
|
101
|
+
|
|
102
|
+
await context.run("new-signup", _new_signup)
|
|
103
|
+
|
|
104
|
+
await context.sleep("wait-for-3-days", 60 * 60 * 24 * 3)
|
|
105
|
+
|
|
106
|
+
while True:
|
|
107
|
+
|
|
108
|
+
async def _check_user_state() -> UserState:
|
|
109
|
+
return await get_user_state()
|
|
110
|
+
|
|
111
|
+
state: UserState = await context.run("check-user-state", _check_user_state)
|
|
112
|
+
|
|
113
|
+
if state == "non-active":
|
|
114
|
+
|
|
115
|
+
async def _send_email_non_active() -> None:
|
|
116
|
+
await send_email("Email to non-active users", email)
|
|
117
|
+
|
|
118
|
+
await context.run("send-email-non-active", _send_email_non_active)
|
|
119
|
+
else:
|
|
120
|
+
|
|
121
|
+
async def _send_email_active() -> None:
|
|
122
|
+
await send_email("Send newsletter to active users", email)
|
|
123
|
+
|
|
124
|
+
await context.run("send-email-active", _send_email_active)
|
|
125
|
+
|
|
126
|
+
await context.sleep("wait-for-1-month", 60 * 60 * 24 * 30)
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
</CodeGroup>
|
|
131
|
+
|
|
132
|
+
## Code Breakdown
|
|
133
|
+
|
|
134
|
+
### 1. New User Signup
|
|
135
|
+
|
|
136
|
+
We start by sending a newly signed-up user a welcome email:
|
|
137
|
+
|
|
138
|
+
<CodeGroup>
|
|
139
|
+
|
|
140
|
+
```typescript api/workflow/route.ts
|
|
141
|
+
await context.run("new-signup", async () => {
|
|
142
|
+
await sendEmail("Welcome to the platform", email)
|
|
143
|
+
})
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```python main.py
|
|
147
|
+
async def _new_signup() -> None:
|
|
148
|
+
await send_email("Welcome to the platform", email)
|
|
149
|
+
|
|
150
|
+
await context.run("new-signup", _new_signup)
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
</CodeGroup>
|
|
155
|
+
|
|
156
|
+
### 2. Initial Waiting Period
|
|
157
|
+
|
|
158
|
+
To leave time for the user to interact with our platform, we use `context.sleep` to pause our workflow for 3 days:
|
|
159
|
+
|
|
160
|
+
<CodeGroup>
|
|
161
|
+
|
|
162
|
+
```typescript api/workflow/route.ts
|
|
163
|
+
await context.sleep("wait-for-3-days", 60 * 60 * 24 * 3)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
```python main.py
|
|
167
|
+
await context.sleep("wait-for-3-days", 60 * 60 * 24 * 3)
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
</CodeGroup>
|
|
172
|
+
|
|
173
|
+
### 3. Periodic State Check
|
|
174
|
+
|
|
175
|
+
We enter an infinite loop to periodically (every month) check the user's engagement level with our platform and send appropriate emails:
|
|
176
|
+
|
|
177
|
+
<CodeGroup>
|
|
178
|
+
|
|
179
|
+
```typescript api/workflow/route.ts
|
|
180
|
+
while (true) {
|
|
181
|
+
const state = await context.run("check-user-state", async () => {
|
|
182
|
+
return await getUserState()
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
if (state === "non-active") {
|
|
186
|
+
await context.run("send-email-non-active", async () => {
|
|
187
|
+
await sendEmail("Email to non-active users", email)
|
|
188
|
+
})
|
|
189
|
+
} else if (state === "active") {
|
|
190
|
+
await context.run("send-email-active", async () => {
|
|
191
|
+
await sendEmail("Send newsletter to active users", email)
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
await context.sleep("wait-for-1-month", 60 * 60 * 24 * 30)
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
```python main.py
|
|
200
|
+
while True:
|
|
201
|
+
|
|
202
|
+
async def _check_user_state() -> UserState:
|
|
203
|
+
return await get_user_state()
|
|
204
|
+
|
|
205
|
+
state: UserState = await context.run("check-user-state", _check_user_state)
|
|
206
|
+
|
|
207
|
+
if state == "non-active":
|
|
208
|
+
|
|
209
|
+
async def _send_email_non_active() -> None:
|
|
210
|
+
await send_email("Email to non-active users", email)
|
|
211
|
+
|
|
212
|
+
await context.run("send-email-non-active", _send_email_non_active)
|
|
213
|
+
else:
|
|
214
|
+
|
|
215
|
+
async def _send_email_active() -> None:
|
|
216
|
+
await send_email("Send newsletter to active users", email)
|
|
217
|
+
|
|
218
|
+
await context.run("send-email-active", _send_email_active)
|
|
219
|
+
|
|
220
|
+
await context.sleep("wait-for-1-month", 60 * 60 * 24 * 30)
|
|
221
|
+
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
</CodeGroup>
|
|
225
|
+
|
|
226
|
+
## Key Features
|
|
227
|
+
|
|
228
|
+
1. **Non-blocking sleep**: We use `context.sleep` for pausing the workflow without consuming execution time (great for optimizing serverless cost).
|
|
229
|
+
|
|
230
|
+
2. **Long-running task**: This workflow runs indefinitely, checking and responding to a users engagement state every month.
|