1import { DurableObject } from "cloudflare:workers";
2import type { AsyncWorkerEnv } from "../alchemy.run.ts";
3import wasm from "./modules/wasm-example.wasm";
4
5interface AddInstance {
6 exports: {
7 add(a: number, b: number): number;
8 };
9}
10
11export default {
12 async fetch(request, env) {
13 const url = new URL(request.url);
14 switch (url.pathname) {
15 case "/env":
16 return Response.json(env);
17 case "/wasm":
18 const instance = (await WebAssembly.instantiate(wasm)) as AddInstance;
19 return Response.json({ result: instance.exports.add(3, 4) });
20 case "/queue/send": {
21 const body = await request.json<Message["body"]>();
22 const queue = await env.QUEUE.send(body);
23 return Response.json({ queue });
24 }
25 case "/queue/messages": {
26 const storage = env.MESSAGES.getByName("global");
27 const messages = await storage.list();
28 return Response.json(messages);
29 }
30 case "/counter": {
31 const counter = env.COUNTER.getByName("my-counter");
32 const count = await counter.increment();
33 return new Response(`Hello, world! ${count}`);
34 }
35 case "/r2": {
36 await env.BUCKET.put("hello.txt", "hello from r2");
37 const object = await env.BUCKET.get("hello.txt");
38 const text = object === null ? null : await object.text();
39 const list = await env.BUCKET.list();
40 return Response.json({
41 text,
42 keys: list.objects.map((o) => o.key),
43 });
44 }
45 case "/d1": {
46 // The `greetings` table comes from ./migrations — no DDL here, so a
47 // failing migration apply fails this route loudly.
48 await env.DB.prepare("INSERT INTO greetings (text) VALUES (?)")
49 .bind("hello from d1")
50 .run();
51 const row = await env.DB.prepare(
52 "SELECT text FROM greetings ORDER BY id DESC LIMIT 1",
53 ).first<{ text: string }>();
54 return Response.json({ text: row?.text ?? null });
55 }
56 case "/cache": {
57 // The local runtime ships an always-on Cache API simulator
58 // (persisted under `.alchemy/local`), so `caches.default` works
59 // exactly like in production. The caller supplies a key to keep
60 // "first fetch misses" deterministic across runs.
61 const keyName = url.searchParams.get("key") ?? "cached-resource";
62 const key = new Request(`https://example.com/${keyName}`);
63 let hit = true;
64 let cached = await caches.default.match(key);
65 if (!cached) {
66 hit = false;
67 cached = new Response("cached-body", {
68 headers: { "Cache-Control": "public, max-age=60" },
69 });
70 await caches.default.put(key, cached.clone());
71 }
72 return Response.json({ hit, body: await cached.text() });
73 }
74 case "/ratelimit": {
75 // THROTTLE allows 2 requests per 10s per key — the third call with
76 // the same key observes `success: false`.
77 const key = url.searchParams.get("key") ?? "default";
78 const { success } = await env.THROTTLE.limit({ key });
79 return Response.json({ success });
80 }
81 case "/version": {
82 // Version metadata binding; locally stubbed with a random `id`.
83 return Response.json(env.CF_VERSION_METADATA);
84 }
85 case "/service": {
86 // Service binding: call the Effect-native worker's `/url` route
87 // (worker → worker, no public hop).
88 const response = await env.SERVICE.fetch("http://effect-worker/url");
89 return Response.json(await response.json());
90 }
91 case "/kv-live": {
92 // LIVE_KV opted out of local emulation via `Alchemy.remote()` — the
93 // roundtrip below lands in the REAL cloud namespace even in dev.
94 const key = url.searchParams.get("key") ?? "hello";
95 const value = url.searchParams.get("value");
96 if (value !== null) {
97 await env.LIVE_KV.put(key, value);
98 }
99 return Response.json({ value: await env.LIVE_KV.get(key) });
100 }
101 case "/tail-ping": {
102 // Logged marker rides the trace batch delivered to the tail worker.
103 console.log("cloudflare-dev-tail-marker");
104 return new Response("pinged");
105 }
106 default:
107 return env.ASSETS.fetch(request);
108 }
109 },
110 async queue(batch, env) {
111 const storage = env.MESSAGES.getByName("global");
112 for (const message of batch.messages) {
113 await storage.put({
114 id: message.id,
115 body: message.body as Message["body"],
116 });
117 }
118 },
119} satisfies ExportedHandler<AsyncWorkerEnv>;
120
121export class Counter extends DurableObject {
122 async increment() {
123 return ++this.counter;
124 }
125
126 get counter() {
127 return this.ctx.storage.kv.get<number>("counter") ?? 0;
128 }
129
130 set counter(value: number) {
131 this.ctx.storage.kv.put("counter", value);
132 }
133}
134
135export interface Message {
136 id: string;
137 body: {
138 text: string;
139 sentAt: number;
140 };
141}
142
143export class QueueMessages extends DurableObject {
144 async put(message: Message) {
145 this.ctx.storage.kv.put(message.id, message);
146 }
147
148 async list(): Promise<Message[]> {
149 const messages = new Map(this.ctx.storage.kv.list<Message>());
150 return Array.from(messages.values());
151 }
152}