Open History to see the last commit
1import * as Cloudflare from "alchemy/Cloudflare";
2import * as Config from "effect/Config";
3import * as Effect from "effect/Effect";
4import * as Stream from "effect/Stream";
5import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
6import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
7import { KV } from "./KV.ts";
8import NotifyWorkflow from "./NotifyWorkflow.ts";
9import SandboxDO from "./SandboxDO.ts";
10
11interface AddInstance {
12 exports: {
13 add(a: number, b: number): number;
14 };
15}
16interface Message {
17 id: string;
18 body: {
19 text: string;
20 sentAt: number;
21 };
22}
23
24export default class EffectWorker extends Cloudflare.Worker<EffectWorker>()(
25 "EffectWorker",
26 {
27 main: import.meta.url,
28 dev: {
29 port: Config.number("PORT").pipe(Config.withDefault(1338)),
30 },
31 build: {
32 bundleAnalyzer: true,
33 },
34 },
35 Effect.gen(function* () {
36 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
37 const queue = yield* Cloudflare.Queues.Queue("EffectWorkerQueue");
38 const queueBinding = yield* Cloudflare.Queues.WriteQueue(queue);
39 const sandbox = yield* SandboxDO;
40 const queueMessages = yield* QueueMessages;
41 const workflow = yield* NotifyWorkflow;
42
43 yield* Cloudflare.Queues.consumeQueueMessages<Message["body"]>(
44 queue,
45 (stream) =>
46 Stream.runForEach(stream, (msg) =>
47 queueMessages
48 .getByName("global")
49 .put({ id: msg.id, body: msg.body })
50 .pipe(Effect.asVoid),
51 ),
52 );
53
54 return {
55 fetch: Effect.gen(function* () {
56 const request = yield* HttpServerRequest.HttpServerRequest;
57 const url = new URL(request.url, "http://internal");
58 if (url.pathname.startsWith("/sandbox")) {
59 const stub = sandbox.getByName("sandbox-test");
60 return yield* stub.fetch(request).pipe(Effect.orDie);
61 } else if (url.pathname === "/wasm") {
62 const instance = yield* Effect.promise(async () => {
63 // This is dynamically imported so that the WASM import doesn't occur at deploy-time, which works in Bun but fails in Node.
64 const wasm = await import("./modules/wasm-example.wasm");
65 return (await WebAssembly.instantiate(wasm.default)) as AddInstance;
66 });
67 return yield* HttpServerResponse.json({
68 result: instance.exports.add(3, 4),
69 });
70 } else if (url.pathname.startsWith("/workflow/start/")) {
71 const roomId = url.pathname.split("/workflow/start/")[1];
72 if (!roomId) {
73 return yield* HttpServerResponse.json(
74 { error: "roomId is required" },
75 { status: 400 },
76 );
77 }
78 const instance = yield* workflow.create({
79 params: {
80 roomId,
81 message: "hello from workflow",
82 },
83 });
84 return yield* HttpServerResponse.json({ instanceId: instance.id });
85 } else if (url.pathname.startsWith("/workflow/status/")) {
86 const instanceId = url.pathname.split("/workflow/status/")[1];
87 if (!instanceId) {
88 return yield* HttpServerResponse.json(
89 { error: "instanceId is required" },
90 { status: 400 },
91 );
92 }
93 const instance = yield* workflow.get(instanceId);
94 const status = yield* instance.status();
95 return yield* HttpServerResponse.json(status);
96 } else if (url.pathname.startsWith("/queue/send")) {
97 const body = yield* request.json;
98 yield* queueBinding.send(body).pipe(Effect.orDie);
99 return yield* HttpServerResponse.json({ sent: body });
100 } else if (url.pathname.startsWith("/queue/messages")) {
101 const messages = yield* queueMessages.getByName("global").list();
102 return yield* HttpServerResponse.json(messages);
103 }
104 const value = yield* kv.list().pipe(Effect.orDie);
105 return yield* HttpServerResponse.json(value);
106 }),
107 };
108 }).pipe(
109 Effect.provide([
110 Cloudflare.KV.ReadWriteNamespaceBinding,
111 Cloudflare.Queues.WriteQueueBinding,
112 Cloudflare.Queues.EventSourceLive,
113 ]),
114 ),
115) {}
116
117export class QueueMessages extends Cloudflare.DurableObject<QueueMessages>()(
118 "QueueMessages",
119 Effect.succeed(
120 Effect.gen(function* () {
121 const state = yield* Cloudflare.DurableObjectState;
122 return {
123 put: Effect.fn(function* (message: Message) {
124 yield* state.storage.put(message.id, message);
125 }),
126 list: Effect.fn(function* () {
127 const messages = new Map<string, Message>(
128 state.storage.kv.list<Message>(),
129 );
130 return Array.from(messages.values());
131 }),
132 };
133 }),
134 ),
135) {}