@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 215 lines 8.41 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Config from "effect/Config";
3 import * as Effect from "effect/Effect";
4 import * as HttpServerRequest from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Redacted from "effect/Redacted";
7 import * as Stream from "effect/Stream";
8 import { KV } from "./KV.ts";
9 import NotifyWorkflow from "./NotifyWorkflow.ts";
10 import SandboxDO from "./SandboxDO.ts";
11
12 /**
13 * Analytics Engine dataset — a plain binding value, not a cloud resource.
14 * In local dev `writeDataPoint` is accepted and discarded (Miniflare
15 * parity); on a live deploy the points land in the real dataset.
16 */
17 export const Events = Cloudflare.AnalyticsEngine.Dataset("Events", {
18 dataset: "cloudflare_dev_events",
19 });
20
21 /**
22 * Checked-in HMAC key material for the `secret_key` binding (32 bytes,
23 * base64) — never generate key material at deploy time.
24 */
25 const HMAC_KEY_BASE64 = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
26
27 interface AddInstance {
28 exports: {
29 add(a: number, b: number): number;
30 };
31 }
32 interface Message {
33 id: string;
34 body: {
35 text: string;
36 sentAt: number;
37 };
38 }
39
40 export default class EffectWorker extends Cloudflare.Worker<EffectWorker>()(
41 "EffectWorker",
42 {
43 main: import.meta.url,
44 dev: {
45 port: Config.Number("PORT").pipe(Config.withDefault(1338)),
46 },
47 build: {
48 bundleAnalyzer: true,
49 },
50 },
51 Effect.gen(function* () {
52 const publicUrl = yield* Cloudflare.Worker.URL;
53 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
54 const queue = yield* Cloudflare.Queues.Queue("EffectWorkerQueue");
55 const queueBinding = yield* Cloudflare.Queues.WriteQueue(queue);
56 const sandbox = yield* SandboxDO;
57 const queueMessages = yield* QueueMessages;
58 const workflow = yield* NotifyWorkflow;
59 const cronFires = yield* CronFires;
60 const analytics = yield* Cloudflare.AnalyticsEngine.WriteDataset(Events);
61 // `secret_key` binding: workerd imports the key material as a
62 // non-extractable CryptoKey. The accessor is deferred — `yield*` it
63 // again inside the handler to get the CryptoKey.
64 const hmacKey = yield* Cloudflare.Workers.SecretKey("HMAC_KEY", {
65 format: "raw",
66 algorithm: { name: "HMAC", hash: "SHA-256" },
67 usages: ["sign", "verify"],
68 keyBase64: Redacted.make(HMAC_KEY_BASE64),
69 });
70
71 // Cron trigger: registered at init; locally you can fire it on demand
72 // via `POST /cdn-cgi/handler/scheduled?cron=* * * * *&time=<ms>` instead
73 // of waiting for the minute boundary.
74 yield* Cloudflare.Workers.cron("* * * * *", (controller) =>
75 cronFires.getByName("default").record(controller.scheduledTime),
76 );
77
78 yield* Cloudflare.Queues.consumeQueueMessages<Message["body"]>(queue, (stream) =>
79 Stream.runForEach(stream, (msg) =>
80 queueMessages.getByName("global").put({ id: msg.id, body: msg.body }).pipe(Effect.asVoid),
81 ),
82 );
83
84 return {
85 fetch: Effect.gen(function* () {
86 const request = yield* HttpServerRequest.HttpServerRequest;
87 const url = new URL(request.url, "http://internal");
88 if (url.pathname.startsWith("/sandbox")) {
89 const stub = sandbox.getByName("sandbox-test");
90 return yield* stub.fetch(request).pipe(Effect.orDie);
91 } else if (url.pathname === "/wasm") {
92 const instance = yield* Effect.promise(async () => {
93 // This is dynamically imported so that the WASM import doesn't occur at deploy-time, which works in Bun but fails in Node.
94 const wasm = await import("./modules/wasm-example.wasm");
95 return (await WebAssembly.instantiate(wasm.default)) as AddInstance;
96 });
97 return yield* HttpServerResponse.json({
98 result: instance.exports.add(3, 4),
99 });
100 } else if (url.pathname.startsWith("/workflow/start/")) {
101 const roomId = url.pathname.split("/workflow/start/")[1];
102 if (!roomId) {
103 return yield* HttpServerResponse.json({ error: "roomId is required" }, { status: 400 });
104 }
105 const instance = yield* workflow.create({
106 params: {
107 roomId,
108 message: "hello from workflow",
109 },
110 });
111 return yield* HttpServerResponse.json({ instanceId: instance.id });
112 } else if (url.pathname.startsWith("/workflow/status/")) {
113 const instanceId = url.pathname.split("/workflow/status/")[1];
114 if (!instanceId) {
115 return yield* HttpServerResponse.json(
116 { error: "instanceId is required" },
117 { status: 400 },
118 );
119 }
120 const instance = yield* workflow.get(instanceId);
121 const status = yield* instance.status();
122 return yield* HttpServerResponse.json(status);
123 } else if (url.pathname.startsWith("/queue/send")) {
124 const body = yield* request.json;
125 yield* queueBinding.send(body).pipe(Effect.orDie);
126 return yield* HttpServerResponse.json({ sent: body });
127 } else if (url.pathname.startsWith("/queue/messages")) {
128 const messages = yield* queueMessages.getByName("global").list();
129 return yield* HttpServerResponse.json(messages);
130 } else if (url.pathname.startsWith("/url")) {
131 return yield* HttpServerResponse.json({ url: yield* publicUrl });
132 } else if (url.pathname.startsWith("/cron/times")) {
133 const snapshot = yield* cronFires.getByName("default").snapshot();
134 return yield* HttpServerResponse.json(snapshot);
135 } else if (url.pathname.startsWith("/secret-key")) {
136 const key = yield* hmacKey;
137 const data = new TextEncoder().encode(url.searchParams.get("message") ?? "hello");
138 const signature = yield* Effect.promise(() => crypto.subtle.sign("HMAC", key, data));
139 const verified = yield* Effect.promise(() =>
140 crypto.subtle.verify("HMAC", key, signature, data),
141 );
142 return yield* HttpServerResponse.json({
143 verified,
144 algorithm: key.algorithm.name,
145 // Bound keys are never extractable — local lowering matches.
146 extractable: key.extractable,
147 signatureBase64: btoa(String.fromCharCode(...new Uint8Array(signature))),
148 });
149 } else if (url.pathname.startsWith("/analytics")) {
150 // A documented no-op in local dev — the write succeeding (not
151 // throwing) is the observable behavior.
152 yield* analytics
153 .writeDataPoint({
154 indexes: ["example"],
155 blobs: ["visit"],
156 doubles: [1],
157 })
158 .pipe(Effect.orDie);
159 return yield* HttpServerResponse.json({ ok: true });
160 }
161 const value = yield* kv.list().pipe(Effect.orDie);
162 return yield* HttpServerResponse.json(value);
163 }),
164 };
165 }).pipe(
166 Effect.provide([
167 Cloudflare.KV.ReadWriteNamespaceBinding,
168 Cloudflare.Queues.WriteQueueBinding,
169 Cloudflare.Queues.EventSourceLive,
170 Cloudflare.Workers.CronEventSourceLive,
171 Cloudflare.Workers.SecretKeyBinding,
172 Cloudflare.AnalyticsEngine.WriteDatasetBinding,
173 ]),
174 ),
175 ) {}
176
177 /**
178 * Records each `scheduledTime` the cron handler observes; the integ test
179 * fires the trigger route and polls `GET /cron/times` until it shows up.
180 */
181 export class CronFires extends Cloudflare.DurableObject<CronFires>()(
182 "CronFires",
183 Effect.succeed(
184 Effect.gen(function* () {
185 const state = yield* Cloudflare.DurableObjectState;
186 return {
187 record: Effect.fn(function* (time: number) {
188 const times = (yield* state.storage.get<number[]>("times")) ?? [];
189 yield* state.storage.put("times", [...times, time]);
190 }),
191 snapshot: Effect.fn(function* () {
192 return { times: (yield* state.storage.get<number[]>("times")) ?? [] };
193 }),
194 };
195 }),
196 ),
197 ) {}
198
199 export class QueueMessages extends Cloudflare.DurableObject<QueueMessages>()(
200 "QueueMessages",
201 Effect.succeed(
202 Effect.gen(function* () {
203 const state = yield* Cloudflare.DurableObjectState;
204 return {
205 put: Effect.fn(function* (message: Message) {
206 yield* state.storage.put(message.id, message);
207 }),
208 list: Effect.fn(function* () {
209 const messages = new Map<string, Message>(state.storage.kv.list<Message>());
210 return Array.from(messages.values());
211 }),
212 };
213 }),
214 ),
215 ) {}