@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 183 lines 6.67 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 FetchHttpClient from "effect/http/FetchHttpClient";
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 LinkRoom from "./LinkRoom.ts";
12 import { Links, type Link } from "./Links.ts";
13 import { LinksDynamo } from "./LinksDynamo.ts";
14 import { Clicks, Jobs, type ClickEvent, type UnfurlJob } from "./Queues.ts";
15 import { ShortyApi } from "./ShortyApi.ts";
16 import { unfurl } from "./unfurl.ts";
17
18 const DAY = 24 * 60 * 60 * 1000;
19
20 export default class Api extends Cloudflare.Worker<Api>()(
21 "Api",
22 { main: import.meta.url },
23 Effect.gen(function* () {
24 const links = yield* Links;
25 const rooms = yield* LinkRoom;
26 const jobsQueue = yield* Jobs;
27 const clicksQueue = yield* Clicks;
28 const jobs = yield* Cloudflare.Queues.WriteQueue(jobsQueue);
29 const jobsSink = yield* Cloudflare.Queues.QueueSink(jobsQueue);
30 const clicks = yield* Cloudflare.Queues.WriteQueue(clicksQueue);
31
32 // Every chunk of the stream becomes one sendBatch call.
33 const enqueueUnfurls = (stream: Stream.Stream<UnfurlJob>) =>
34 stream.pipe(Stream.rechunk(100), Stream.run(jobsSink));
35
36 const withClicks = (link: Link) =>
37 rooms
38 .getByName(link.code)
39 .clicks()
40 .pipe(Effect.map((clicks) => ({ ...link, clicks })));
41
42 // Background job: fetch each new link's page and store its title.
43 yield* Cloudflare.Queues.consumeQueueMessages<UnfurlJob>(
44 jobsQueue,
45 { batchSize: 10, maxRetries: 3 },
46 (messages) =>
47 messages.pipe(
48 Stream.mapEffect(
49 ({ body }) =>
50 unfurl(body.url).pipe(
51 Effect.flatMap((preview) => links.setPreview(body.code, preview)),
52 Effect.tap(() => Effect.log(`unfurled ${body.code} → ${body.url}`)),
53 // A deleted link has nothing left to unfurl.
54 Effect.catchTag("LinkNotFound", () => Effect.void),
55 ),
56 { concurrency: 5 },
57 ),
58 Stream.runDrain,
59 ),
60 );
61
62 // Event source: count clicks per link, one Durable Object call per link per batch.
63 yield* Cloudflare.Queues.consumeQueueMessages<ClickEvent>(
64 clicksQueue,
65 { batchSize: 100, maxWaitTime: "1 second" },
66 (messages) =>
67 messages.pipe(
68 Stream.runFold(
69 () => new Map<string, number>(),
70 (counts, { body }) => counts.set(body.code, (counts.get(body.code) ?? 0) + 1),
71 ),
72 Effect.flatMap((counts) =>
73 Effect.forEach(
74 counts,
75 ([code, n]) =>
76 rooms
77 .getByName(code)
78 .record(n)
79 .pipe(Effect.tap((total) => Effect.log(`${code}: +${n} → ${total}`))),
80 { concurrency: "unbounded", discard: true },
81 ),
82 ),
83 ),
84 );
85
86 // Hourly: re-unfurl previews older than a day.
87 yield* Cloudflare.Workers.cron("0 * * * *", () =>
88 Effect.gen(function* () {
89 const all = yield* links.list();
90 yield* Stream.fromIterable(all).pipe(
91 Stream.filter((link) => (link.preview?.fetchedAt ?? 0) < Date.now() - DAY),
92 Stream.map((link) => ({ code: link.code, url: link.url })),
93 enqueueUnfurls,
94 );
95 }),
96 );
97
98 const handlers = HttpApiBuilder.group(ShortyApi, "links", (handlers) =>
99 handlers
100 .handle("create", ({ payload }) =>
101 Effect.gen(function* () {
102 const link = yield* links.create(payload.url);
103 yield* jobs.send({ code: link.code, url: link.url } satisfies UnfurlJob);
104 return { ...link, clicks: 0 };
105 }).pipe(Effect.orDie),
106 )
107 .handle("import", ({ payload }) =>
108 Effect.gen(function* () {
109 const created = yield* Stream.fromIterable(payload.urls).pipe(
110 Stream.mapEffect(links.create, { concurrency: 10 }),
111 Stream.runCollect,
112 );
113 yield* Stream.fromIterable(created).pipe(
114 Stream.map((link) => ({ code: link.code, url: link.url })),
115 enqueueUnfurls,
116 );
117 return created.map((link) => ({ ...link, clicks: 0 }));
118 }).pipe(Effect.orDie),
119 )
120 .handle("list", () =>
121 links.list().pipe(
122 Effect.flatMap((all) => Effect.forEach(all, withClicks, { concurrency: "unbounded" })),
123 Effect.orDie,
124 ),
125 )
126 .handle("get", ({ params }) =>
127 links
128 .get(params.code)
129 .pipe(Effect.flatMap(withClicks), Effect.catchTag("LinkStoreError", Effect.die)),
130 ),
131 );
132
133 const api = yield* HttpRouter.toHttpEffect(
134 HttpApiBuilder.layer(ShortyApi).pipe(
135 Layer.provide(handlers),
136 Layer.provide(Http.Platform),
137 Layer.provide(HttpRouter.cors()),
138 ),
139 );
140
141 return {
142 fetch: Effect.gen(function* () {
143 const request = yield* HttpServerRequest;
144 const [, first, code, action] = new URL(request.url, "http://localhost").pathname.split(
145 "/",
146 );
147
148 // Live click counts: hand the WebSocket to the link's Durable Object.
149 if (first === "links" && code && action === "live") {
150 return yield* rooms.getByName(code).fetch(request);
151 }
152
153 // Short links: redirect now, count the click in the background.
154 if (first && first !== "links" && !code && request.method === "GET") {
155 const link = yield* links.get(first);
156 yield* clicks.send({ code: link.code, at: Date.now() } satisfies ClickEvent);
157 return HttpServerResponse.redirect(link.url, { status: 302 });
158 }
159
160 return yield* api;
161 }).pipe(
162 Effect.catchTags({
163 LinkNotFound: ({ code }) =>
164 HttpServerResponse.json({ error: `no link ${code}` }, { status: 404 }),
165 LinkStoreError: () =>
166 HttpServerResponse.json({ error: "storage unavailable" }, { status: 503 }),
167 SendError: () => HttpServerResponse.json({ error: "queue unavailable" }, { status: 503 }),
168 }),
169 ),
170 };
171 }).pipe(
172 Effect.provide(
173 Layer.mergeAll(
174 LinksDynamo,
175 Cloudflare.Queues.WriteQueueBinding,
176 Cloudflare.Queues.QueueSinkBinding,
177 Cloudflare.Queues.EventSourceLive,
178 Cloudflare.Workers.CronEventSourceLive,
179 FetchHttpClient.layer,
180 ),
181 ),
182 ),
183 ) {}