Skip to content

Commit 8d98ce3

Browse files
Draft: Workflow example
1 parent f828b04 commit 8d98ce3

File tree

1 file changed

+138
-0
lines changed

1 file changed

+138
-0
lines changed
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
---
2+
type: example
3+
summary: Backup D1 using export API and save it on R2
4+
tags:
5+
- Workflows
6+
- D1
7+
- R2
8+
pcx_content_type: configuration
9+
title: Backup and save D1 database
10+
sidebar:
11+
order: 3
12+
description: Send invoice when shopping cart is checked out and paid for
13+
14+
---
15+
16+
import { TabItem, Tabs } from "~/components"
17+
18+
In this example, we implement a Workflow for an e-commerce website that is triggered every time a shopping cart is created.
19+
20+
Once a Workflow instance is triggered, it starts polling a [D1](/d1) database for the cart ID until it has been checked out. Once the shopping cart is checked out, we proceed to process the payment with an external provider doing a fetch POST. Finally, assuming everything goes well, we try to send an email using [Email Workers](/email-routing/email-workers/) with the invoice to the customer.
21+
22+
As you can see, Workflows handles all the different service responses and failures; it will retry D1 until the cart is checked out, retry the payment processor if it fails for some reason, and retry sending the email with the invoice if it can't. The developer doesn't have to care about any of that logic, and the workflow can run for hours, handling all the possible conditions until it is completed.
23+
24+
This is a simplified example of processing a shopping cart. We would assume more steps and additional logic in a real-life scenario, but this example gives you a good idea of what you can do with Workflows.
25+
26+
```ts
27+
import {
28+
WorkflowEntrypoint,
29+
WorkflowStep,
30+
WorkflowEvent,
31+
} from "cloudflare:workers";
32+
33+
34+
// We are using R2 to store the D1 backup
35+
type Env = {
36+
BACKUP_WORKFLOW: Workflow;
37+
D1_REST_API_TOKEN: string;
38+
BACKUP_BUCKET: R2Bucket;
39+
};
40+
41+
// Workflow parameters: we expect accountId and databaseId
42+
type Params = {
43+
accountId: string;
44+
databaseId: string;
45+
};
46+
47+
// Workflow logic
48+
export class backupWorkflow extends WorkflowEntrypoint<Env, Params> {
49+
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
50+
const { accountId, databaseId } = event.payload;
51+
52+
const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${databaseId}/export`;
53+
const method = "POST";
54+
const headers = new Headers();
55+
headers.append("Content-Type", "application/json");
56+
headers.append("Authorization", `Bearer ${this.env.D1_REST_API_TOKEN}`);
57+
58+
const bookmark = step.do(`Starting backup for ${databaseId}`, async () => {
59+
const payload = { output_format: "polling" };
60+
61+
const res = await fetch(url, { method, headers, body: JSON.stringify(payload) });
62+
const { result } = (await res.json()) as any;
63+
64+
// If we don't get `at_bookmark` we throw to retry the step
65+
if (!result?.at_bookmark) throw new Error("Missing `at_bookmark`");
66+
67+
return result.at_bookmark;
68+
});
69+
70+
step.do("Check backup status and store it on R2", async () => {
71+
const payload = { current_bookmark: bookmark };
72+
73+
const res = await fetch(url, { method, headers, body: JSON.stringify(payload) });
74+
const { result } = (await res.json()) as any;
75+
76+
// The endpoint sends `signed_url` when the backup is ready.
77+
// If we don't get `signed_url` we throw to retry the step.
78+
if (!result?.signed_url) throw new Error("Missing `signed_url`");
79+
80+
const dumpResponse = await fetch(result.signed_url);
81+
// We stream the file directly to R2
82+
await this.env.BACKUP_BUCKET.put(result.filename, dumpResponse.body);
83+
});
84+
}
85+
}
86+
87+
export default {
88+
async fetch(req: Request, env: Env): Promise<Response> {
89+
return new Response("Not found", { status: 404 });
90+
},
91+
async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) {
92+
const params: Params = {
93+
accountId: "{accountId}",
94+
databaseId: "{databaseId}",
95+
};
96+
const instance = await env.BACKUP_WORKFLOW.create({ params });
97+
console.log(`Started workflow: ${instance.id}`);
98+
},
99+
};
100+
```
101+
102+
Here's a minimal package.json:
103+
104+
```json
105+
{
106+
"devDependencies": {
107+
"@cloudflare/workers-types": "^4.20241224.0",
108+
"wrangler": "^3.99.0"
109+
}
110+
}
111+
```
112+
113+
And finally wrangler.toml:
114+
115+
import { WranglerConfig } from "~/components";
116+
117+
<WranglerConfig>
118+
119+
```toml
120+
name = "backup-d1"
121+
main = "src/index.ts"
122+
compatibility_date = "2024-12-27"
123+
compatibility_flags = [ "nodejs_compat" ]
124+
125+
[[workflows]]
126+
name = "backup-workflow"
127+
binding = "BACKUP_WORKFLOW"
128+
class_name = "backupWorkflow"
129+
130+
[[r2_buckets]]
131+
binding = "BACKUP_BUCKET"
132+
bucket_name = "d1-backups"
133+
134+
[triggers]
135+
crons = [ "0 0 * * *" ]
136+
```
137+
138+
</WranglerConfig>

0 commit comments

Comments
 (0)