@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, 06:00 UTC

main
ts 110 lines 3.96 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Http from "alchemy/Http";
3 import * as Effect from "effect/Effect";
4 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
5 import * as HttpRouter from "effect/http/HttpRouter";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Stream from "effect/Stream";
10 import { Clicks, type ClickEvent } from "./Clicks.ts";
11 import LinkRoom from "./LinkRoom.ts";
12 import { Links, LinksSql } from "./Links.ts";
13 import { Telemetry } from "./Observability.ts";
14 import { ShortyApi } from "./ShortyApi.ts";
15 import { NeonStorage } from "./Storage.ts";
16
17 export default class Api extends Cloudflare.Worker<Api>()(
18 "Api",
19 { main: import.meta.url },
20 Effect.gen(function* () {
21 const links = yield* Links;
22 const rooms = yield* LinkRoom;
23 const clicksQueue = yield* Clicks;
24 const clicks = yield* Cloudflare.Queues.WriteQueue(clicksQueue);
25
26 // Count clicks in batches: one Durable Object call per link per batch.
27 yield* Cloudflare.Queues.consumeQueueMessages<ClickEvent>(
28 clicksQueue,
29 { batchSize: 100, maxWaitTime: "1 second", maxRetries: 10, retryDelay: "3 seconds" },
30 (events) =>
31 events.pipe(
32 Stream.runFold(
33 () => new Map<string, number>(),
34 (counts, { body }) => counts.set(body.code, (counts.get(body.code) ?? 0) + 1),
35 ),
36 Effect.flatMap((counts) =>
37 Effect.forEach(
38 counts,
39 ([code, n]) =>
40 rooms
41 .getByName(code)
42 .record(n)
43 .pipe(Effect.withSpan("clicks.record", { attributes: { code, n } })),
44 { concurrency: "unbounded", discard: true },
45 ),
46 ),
47 ),
48 );
49
50 const handlers = HttpApiBuilder.group(ShortyApi, "links", (handlers) =>
51 handlers
52 .handle("create", ({ payload }) => links.create(payload.url).pipe(Effect.orDie))
53 .handle("list", () => links.list().pipe(Effect.orDie))
54 .handle("get", ({ params }) =>
55 links.get(params.code).pipe(Effect.catchTag("LinkStoreError", Effect.die)),
56 ),
57 );
58
59 const api = yield* HttpRouter.toHttpEffect(
60 HttpApiBuilder.layer(ShortyApi).pipe(
61 Layer.provide(handlers),
62 Layer.provide(Http.Platform),
63 Layer.provide(HttpRouter.cors()),
64 ),
65 );
66
67 return {
68 fetch: Effect.gen(function* () {
69 const request = yield* HttpServerRequest;
70 const [, first, code, action] = new URL(request.url, "http://localhost").pathname.split(
71 "/",
72 );
73
74 // GET /links/:code/live → a WebSocket to the link's room
75 if (first === "links" && code && action === "live") {
76 return yield* rooms.getByName(code).fetch(request);
77 }
78
79 // GET /:code → queue the click, redirect straight away
80 if (request.method === "GET" && first && first !== "links" && code === undefined) {
81 const link = yield* links.get(first);
82 yield* clicks.send({
83 code: link.code,
84 at: new Date().toISOString(),
85 } satisfies ClickEvent);
86 return HttpServerResponse.redirect(link.url, { status: 302 });
87 }
88
89 return yield* api;
90 }).pipe(
91 Effect.catchTags({
92 LinkNotFound: ({ code }) =>
93 HttpServerResponse.json({ _tag: "LinkNotFound", code }, { status: 404 }),
94 LinkStoreError: () =>
95 HttpServerResponse.json({ error: "storage unavailable" }, { status: 503 }),
96 SendError: () => HttpServerResponse.json({ error: "queue unavailable" }, { status: 503 }),
97 }),
98 ),
99 };
100 }).pipe(
101 Effect.provide(
102 Layer.mergeAll(
103 LinksSql.pipe(Layer.provide(NeonStorage)),
104 Cloudflare.Queues.WriteQueueBinding,
105 Cloudflare.Queues.EventSourceLive,
106 Telemetry,
107 ),
108 ),
109 ),
110 ) {}