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

main
ts 61 lines 2.26 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5
6 export const Bucket = Cloudflare.R2.Bucket("Bucket", { forceDestroy: true });
7
8 export default class Backend extends Cloudflare.Worker<Backend>()(
9 "Backend",
10 {
11 main: import.meta.url,
12 },
13 Effect.gen(function* () {
14 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Bucket);
15
16 return {
17 // RPC method — read an object from R2 by key, returning the body as
18 // text or `null` if the key is missing. Other workers can call this
19 // directly via the service binding (option 3 in `api.hello.ts`).
20 hello: Effect.fn("Backend.hello")(function* (key: string) {
21 const object = yield* bucket.get(key);
22 if (object === null) return null;
23 return yield* object.text();
24 }),
25
26 // HTTP handler — supports `GET` and `PUT` against R2 by `?key=...`.
27 // Other workers can call this via `env.BACKEND.fetch(...)` (option 2
28 // in `api.hello.ts`).
29 fetch: Effect.gen(function* () {
30 const request = yield* HttpServerRequest;
31 const key = new URL(request.url, "http://backend").searchParams.get("key");
32 if (!key) {
33 return HttpServerResponse.text("Missing 'key' query parameter", {
34 status: 400,
35 });
36 }
37
38 if (request.method === "GET") {
39 const object = yield* bucket.get(key);
40 if (object === null) {
41 return HttpServerResponse.text("Not found", { status: 404 });
42 }
43 return HttpServerResponse.stream(object.body);
44 }
45
46 if (request.method === "PUT") {
47 yield* bucket.put(key, request.stream, {
48 contentLength: Number(request.headers["content-length"] ?? 0),
49 });
50 return HttpServerResponse.empty({ status: 204 });
51 }
52
53 return HttpServerResponse.text("Method not allowed", { status: 405 });
54 }).pipe(
55 Effect.catchTag("R2Error", (error) =>
56 Effect.succeed(HttpServerResponse.text(error.message, { status: 500 })),
57 ),
58 ),
59 };
60 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
61 ) {}