The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as SQL from "@alchemy.run/cloudflare/D1/SQL"; |
| 3 | import * as Http from "alchemy/Http"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 6 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 7 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 8 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { Clicks, type ClickEvent } from "./Clicks.ts"; |
| 12 | import { Db } from "./Db.ts"; |
| 13 | import { LinkNotFound, newCode, type Link } from "./Link.ts"; |
| 14 | import LinkRoom from "./LinkRoom.ts"; |
| 15 | import { ShortyApi } from "./ShortyApi.ts"; |
| 16 | |
| 17 | export default class Api extends Cloudflare.Worker<Api>()( |
| 18 | "Api", |
| 19 | { main: import.meta.url }, |
| 20 | Effect.gen(function* () { |
| 21 | const d1 = yield* Cloudflare.D1.QueryDatabase(Db); |
| 22 | const sql = yield* SQL.D1(d1); |
| 23 | const rooms = yield* LinkRoom; |
| 24 | const clicksQueue = yield* Clicks; |
| 25 | const clicks = yield* Cloudflare.Queues.WriteQueue(clicksQueue); |
| 26 | |
| 27 | // Count clicks in batches: one Durable Object call per link per batch. |
| 28 | yield* Cloudflare.Queues.consumeQueueMessages<ClickEvent>( |
| 29 | clicksQueue, |
| 30 | { batchSize: 100, maxWaitTime: "1 second", maxRetries: 10, retryDelay: "3 seconds" }, |
| 31 | (events) => |
| 32 | events.pipe( |
| 33 | Stream.runFold( |
| 34 | () => new Map<string, number>(), |
| 35 | (counts, { body }) => counts.set(body.code, (counts.get(body.code) ?? 0) + 1), |
| 36 | ), |
| 37 | Effect.flatMap((counts) => |
| 38 | Effect.forEach(counts, ([code, n]) => rooms.getByName(code).record(n), { |
| 39 | concurrency: "unbounded", |
| 40 | discard: true, |
| 41 | }), |
| 42 | ), |
| 43 | ), |
| 44 | ); |
| 45 | |
| 46 | const findLink = Effect.fn(function* (code: string) { |
| 47 | const [link] = yield* sql<Link>` |
| 48 | SELECT code, url, created_at AS "createdAt" FROM links WHERE code = ${code}`; |
| 49 | if (!link) return yield* new LinkNotFound({ code }); |
| 50 | return link; |
| 51 | }); |
| 52 | |
| 53 | const handlers = HttpApiBuilder.group(ShortyApi, "links", (handlers) => |
| 54 | handlers |
| 55 | .handle("create", ({ payload }) => |
| 56 | Effect.gen(function* () { |
| 57 | const link = { code: newCode(), url: payload.url, createdAt: new Date().toISOString() }; |
| 58 | yield* sql` |
| 59 | INSERT INTO links (code, url, created_at) |
| 60 | VALUES (${link.code}, ${link.url}, ${link.createdAt})`; |
| 61 | return link; |
| 62 | }).pipe(Effect.orDie), |
| 63 | ) |
| 64 | .handle("list", () => |
| 65 | sql<Link>` |
| 66 | SELECT code, url, created_at AS "createdAt" FROM links |
| 67 | ORDER BY created_at DESC`.pipe(Effect.orDie), |
| 68 | ) |
| 69 | .handle("get", ({ params }) => |
| 70 | findLink(params.code).pipe(Effect.catchTag("SqlError", Effect.die)), |
| 71 | ), |
| 72 | ); |
| 73 | |
| 74 | const api = yield* HttpRouter.toHttpEffect( |
| 75 | HttpApiBuilder.layer(ShortyApi).pipe( |
| 76 | Layer.provide(handlers), |
| 77 | Layer.provide(Http.Platform), |
| 78 | Layer.provide(HttpRouter.cors()), |
| 79 | ), |
| 80 | ); |
| 81 | |
| 82 | return { |
| 83 | fetch: Effect.gen(function* () { |
| 84 | const request = yield* HttpServerRequest; |
| 85 | const [, first, code, action] = new URL(request.url, "http://localhost").pathname.split( |
| 86 | "/", |
| 87 | ); |
| 88 | |
| 89 | // GET /links/:code/live → a WebSocket to the link's room |
| 90 | if (first === "links" && code && action === "live") { |
| 91 | return yield* rooms.getByName(code).fetch(request); |
| 92 | } |
| 93 | |
| 94 | // GET /:code → queue the click, redirect straight away |
| 95 | if (request.method === "GET" && first && first !== "links" && code === undefined) { |
| 96 | const link = yield* findLink(first); |
| 97 | yield* clicks.send({ |
| 98 | code: link.code, |
| 99 | at: new Date().toISOString(), |
| 100 | } satisfies ClickEvent); |
| 101 | return HttpServerResponse.redirect(link.url, { status: 302 }); |
| 102 | } |
| 103 | |
| 104 | return yield* api; |
| 105 | }).pipe( |
| 106 | Effect.catchTags({ |
| 107 | LinkNotFound: ({ code }) => |
| 108 | HttpServerResponse.json({ _tag: "LinkNotFound", code }, { status: 404 }), |
| 109 | SqlError: () => |
| 110 | HttpServerResponse.json({ error: "database unavailable" }, { status: 503 }), |
| 111 | SendError: () => HttpServerResponse.json({ error: "queue unavailable" }, { status: 503 }), |
| 112 | }), |
| 113 | ), |
| 114 | }; |
| 115 | }).pipe( |
| 116 | Effect.provide( |
| 117 | Layer.mergeAll( |
| 118 | Cloudflare.D1.QueryDatabaseBinding, |
| 119 | Cloudflare.Queues.WriteQueueBinding, |
| 120 | Cloudflare.Queues.EventSourceLive, |
| 121 | ), |
| 122 | ), |
| 123 | ), |
| 124 | ) {} |