Loading...
Loading...
Compare original and translation side by side
// src/index.ts
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from "cloudflare:workers";
interface Env {
MY_WORKFLOW: Workflow;
}
interface Params {
userId: string;
action: string;
}
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
const user = await step.do("fetch user", async () => {
const resp = await fetch(`https://api.example.com/users/${event.payload.userId}`);
return resp.json();
});
await step.sleep("wait before processing", "1 hour");
const result = await step.do("process action", async () => {
return { processed: true, user: user.id };
});
return result; // Available in instance.status().output
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const instance = await env.MY_WORKFLOW.create({
params: { userId: "123", action: "activate" },
});
return Response.json({ instanceId: instance.id });
},
};// src/index.ts
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from "cloudflare:workers";
interface Env {
MY_WORKFLOW: Workflow;
}
interface Params {
userId: string;
action: string;
}
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
const user = await step.do("fetch user", async () => {
const resp = await fetch(`https://api.example.com/users/${event.payload.userId}`);
return resp.json();
});
await step.sleep("wait before processing", "1 hour");
const result = await step.do("process action", async () => {
return { processed: true, user: user.id };
});
return result; // Available in instance.status().output
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const instance = await env.MY_WORKFLOW.create({
params: { userId: "123", action: "activate" },
});
return Response.json({ instanceId: instance.id });
},
};{
"name": "my-workflow-worker",
"main": "src/index.ts",
"workflows": [
{
"name": "my-workflow",
"binding": "MY_WORKFLOW",
"class_name": "MyWorkflow"
}
]
}{
"name": "my-workflow-worker",
"main": "src/index.ts",
"workflows": [
{
"name": "my-workflow",
"binding": "MY_WORKFLOW",
"class_name": "MyWorkflow"
}
]
}npx wrangler deploynpx wrangler deployexport class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
// Workflow logic with steps
return optionalResult;
}
}export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
// Workflow logic with steps
return optionalResult;
}
}interface WorkflowEvent<T> {
payload: Readonly<T>; // Immutable input params
timestamp: Date; // Creation time
instanceId: string; // Unique instance ID
}interface WorkflowEvent<T> {
payload: Readonly<T>; // Immutable input params
timestamp: Date; // Creation time
instanceId: string; // Unique instance ID
}interface WorkflowStep {
do<T>(name: string, callback: () => Promise<T>): Promise<T>;
do<T>(name: string, config: StepConfig, callback: () => Promise<T>): Promise<T>;
sleep(name: string, duration: Duration): Promise<void>;
sleepUntil(name: string, timestamp: Date | number): Promise<void>;
waitForEvent<T>(name: string, options: WaitOptions): Promise<T>;
}interface WorkflowStep {
do<T>(name: string, callback: () => Promise<T>): Promise<T>;
do<T>(name: string, config: StepConfig, callback: () => Promise<T>): Promise<T>;
sleep(name: string, duration: Duration): Promise<void>;
sleepUntil(name: string, timestamp: Date | number): Promise<void>;
waitForEvent<T>(name: string, options: WaitOptions): Promise<T>;
}const result = await step.do("step name", async () => {
const response = await fetch("https://api.example.com/data");
return response.json(); // State persisted
});const result = await step.do("step name", async () => {
const response = await fetch("https://api.example.com/data");
return response.json(); // State persisted
});const data = await step.do(
"call external API",
{
retries: {
limit: 10,
delay: "30 seconds",
backoff: "exponential",
},
timeout: "5 minutes",
},
async () => {
return await externalApiCall();
}
);const data = await step.do(
"call external API",
{
retries: {
limit: 10,
delay: "30 seconds",
backoff: "exponential",
},
timeout: "5 minutes",
},
async () => {
return await externalApiCall();
}
);const defaultConfig = {
retries: {
limit: 5,
delay: 10000, // 10 seconds
backoff: "exponential",
},
timeout: "10 minutes",
};| Option | Type | Default | Description |
|---|---|---|---|
| number | 5 | Max attempts (use |
| string/number | 10000 | Delay between retries |
| string | exponential | |
| string/number | 10 min | Per-attempt timeout |
const defaultConfig = {
retries: {
limit: 5,
delay: 10000, // 10 seconds
backoff: "exponential",
},
timeout: "10 minutes",
};| 选项 | 类型 | 默认值 | 描述说明 |
|---|---|---|---|
| number | 5 | 最大重试次数(使用 |
| string/number | 10000 | 重试间隔时间 |
| string | exponential | 重试策略: |
| string/number | 10 min | 单次尝试的超时时间 |
await step.sleep("wait before retry", "1 hour");
await step.sleep("short pause", 5000); // 5 seconds (ms)secondminutehourdayweekmonthyearawait step.sleep("wait before retry", "1 hour");
await step.sleep("short pause", 5000); // 5 seconds (ms)secondminutehourdayweekmonthyearconst targetDate = new Date("2024-12-31T00:00:00Z");
await step.sleepUntil("wait until new year", targetDate);
// Or with timestamp
await step.sleepUntil("wait until launch", Date.parse("24 Oct 2024 13:00:00 UTC"));step.sleepstep.sleepUntilconst targetDate = new Date("2024-12-31T00:00:00Z");
await step.sleepUntil("wait until new year", targetDate);
// 或使用时间戳
await step.sleepUntil("wait until launch", Date.parse("24 Oct 2024 13:00:00 UTC"));step.sleepstep.sleepUntilconst approval = await step.waitForEvent<{ approved: boolean }>("wait for approval", {
type: "user_approval",
timeout: "7 days",
});
if (approval.approved) {
await step.do("proceed", async () => {
/* ... */
});
}try {
const event = await step.waitForEvent("optional event", { type: "update", timeout: "1 hour" });
} catch (e) {
// Continue without event
}const approval = await step.waitForEvent<{ approved: boolean }>("wait for approval", {
type: "user_approval",
timeout: "7 days",
});
if (approval.approved) {
await step.do("proceed", async () => {
/* ... */
});
}try {
const event = await step.waitForEvent("optional event", { type: "update", timeout: "1 hour" });
} catch (e) {
// 无事件时继续执行
}export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { instanceId, approved } = await request.json();
const instance = await env.MY_WORKFLOW.get(instanceId);
await instance.sendEvent({
type: "user_approval", // Must match waitForEvent type
payload: { approved },
});
return new Response("Event sent");
},
};waitForEventexport default {
async fetch(request: Request, env: Env): Promise<Response> {
const { instanceId, approved } = await request.json();
const instance = await env.MY_WORKFLOW.get(instanceId);
await instance.sendEvent({
type: "user_approval", // 必须与waitForEvent的type匹配
payload: { approved },
});
return new Response("Event sent");
},
};waitForEventimport { NonRetryableError } from "cloudflare:workflows";
await step.do("validate input", async () => {
if (!event.payload.data) {
throw new NonRetryableError("Missing required data");
}
return event.payload.data;
});import { NonRetryableError } from "cloudflare:workflows";
await step.do("validate input", async () => {
if (!event.payload.data) {
throw new NonRetryableError("Missing required data");
}
return event.payload.data;
});try {
await step.do("risky operation", async () => {
await riskyApiCall();
});
} catch (error) {
await step.do("handle failure", async () => {
await sendAlertEmail(error.message);
});
}try {
await step.do("risky operation", async () => {
await riskyApiCall();
});
} catch (error) {
await step.do("handle failure", async () => {
await sendAlertEmail(error.message);
});
}| Status | Description |
|---|---|
| Waiting to start |
| Actively executing |
| Manually paused |
| Sleeping or waiting for event |
| Pause requested, waiting to take effect |
| Successfully finished |
| Failed (uncaught exception or retry limit) |
| Manually terminated |
| 状态 | 描述说明 |
|---|---|
| 等待启动 |
| 正在执行 |
| 手动暂停 |
| 休眠或等待事件 |
| 已请求暂停,等待生效 |
| 执行成功完成 |
| 执行失败(未捕获异常或达到重试上限) |
| 手动终止 |
const instance = await env.MY_WORKFLOW.create({
id: "order-12345", // Optional custom ID (max 100 chars)
params: { orderId: 12345 },
});
console.log(instance.id);const instance = await env.MY_WORKFLOW.create({
id: "order-12345", // 可选自定义ID(最多100字符)
params: { orderId: 12345 },
});
console.log(instance.id);const instances = await env.MY_WORKFLOW.createBatch([{ params: { userId: "1" } }, { params: { userId: "2" } }, { params: { userId: "3" } }]);
// Up to 100 instances per batchconst instances = await env.MY_WORKFLOW.createBatch([{ params: { userId: "1" } }, { params: { userId: "2" } }, { params: { userId: "3" } }]);
// 每批最多创建100个实例const instance = await env.MY_WORKFLOW.get("order-12345");const instance = await env.MY_WORKFLOW.get("order-12345");await instance.pause(); // Pause execution
await instance.resume(); // Resume paused
await instance.terminate(); // Stop permanently
await instance.restart(); // Restart from beginning
const status = await instance.status();
console.log(status.status); // "running", "complete", etc.
console.log(status.output); // Return value from run()
console.log(status.error); // { name, message } if errored
await instance.sendEvent({
type: "approval",
payload: { approved: true },
});await instance.pause(); // 暂停执行
await instance.resume(); // 恢复暂停的实例
await instance.terminate(); // 永久终止实例
await instance.restart(); // 从开头重启实例
const status = await instance.status();
console.log(status.status); // "running", "complete", 等
console.log(status.output); // run()方法的返回值
console.log(status.error); // 执行失败时的错误信息 { name, message }
await instance.sendEvent({
type: "approval",
payload: { approved: true },
});awaitevent.payloadawaitevent.payloadevent.payloadDate.now()Math.random()awaitevent.payloadDate.now()Math.random()await// ✅ Good: Return state from step
const userData = await step.do("fetch user", async () => {
return await fetchUser(userId);
});
// ❌ Bad: State stored outside step (lost on restart)
let userData;
await step.do("fetch user", async () => {
userData = await fetchUser(userId); // Will be lost!
});// ✅ 正确:从步骤返回状态
const userData = await step.do("fetch user", async () => {
return await fetchUser(userId);
});
// ❌ 错误:状态存储在步骤外部(重启后丢失)
let userData;
await step.do("fetch user", async () => {
userData = await fetchUser(userId); // 会丢失!
});undefinedundefined
---
---| Feature | Free | Paid |
|---|---|---|
| CPU time per step | 10 ms | 30 sec (max 5 min) |
| Wall clock per step | Unlimited | Unlimited |
| State per step | 1 MiB | 1 MiB |
| Event payload | 1 MiB | 1 MiB |
| Total state per instance | 100 MB | 1 GB |
| Max sleep duration | 365 days | 365 days |
| Max steps per Workflow | 1024 | 1024 |
| Concurrent instances | 25 | 10,000 |
| Instance creation rate | 100/sec | 100/sec |
| Queued instances | 100,000 | 1,000,000 |
| Subrequests per instance | 50/req | 1000/req |
| Instance ID length | 100 chars | 100 chars |
| Retention (completed) | 3 days | 30 days |
waiting| 功能项 | 免费版 | 付费版 |
|---|---|---|
| 单步骤CPU时间 | 10 ms | 30秒(最大5分钟) |
| 单步骤实际运行时间 | 无限制 | 无限制 |
| 单步骤状态大小 | 1 MiB | 1 MiB |
| 事件负载大小 | 1 MiB | 1 MiB |
| 单实例总状态大小 | 100 MB | 1 GB |
| 最大休眠时长 | 365天 | 365天 |
| 单工作流最大步骤数 | 1024 | 1024 |
| 并发实例数 | 25 | 10,000 |
| 实例创建速率 | 100/秒 | 100/秒 |
| 排队实例数 | 100,000 | 1,000,000 |
| 单实例子请求数 | 50/请求 | 1000/req |
| 实例ID长度 | 100字符 | 100 chars |
| 已完成实例保留时长 | 3天 | 30天 |
waiting{
"limits": {
"cpu_ms": 300000 // 5 minutes
}
}{
"limits": {
"cpu_ms": 300000 // 5分钟
}
}| Metric | Free | Paid |
|---|---|---|
| Requests | 100K/day (shared) | 10M/mo included, +$0.30/M |
| CPU time | 10 ms/invocation | 30M ms/mo included, +$0.02/M ms |
| Storage | 1 GB | 1 GB included, +$0.20/GB-mo |
| 指标 | 免费版 | 付费版 |
|---|---|---|
| 请求量 | 每日10万次(共享额度) | 每月1000万次免费额度,超出后$0.30/百万次 |
| CPU时间 | 每次调用10 ms | 每月3000万ms免费额度,超出后$0.02/百万ms |
| 存储 | 1 GB | 1 GB免费额度,超出后$0.20/GB-月 |
event.payloadawaitevent.payloadawaitcloudflare-workerscloudflare-queuescloudflare-r2cloudflare-kvcloudflare-workerscloudflare-queuescloudflare-r2cloudflare-kv