@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 128 lines 5.17 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import * as Kubernetes from "@alchemy.run/kubernetes";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import { EntriesDatabase, entryPath, GuestbookCluster, GuestbookNamespace } from "./infra.ts";
7
8 /**
9 * The guestbook API: a `Kubernetes.Deployment` in the TAGGED form — the class
10 * declares the deployment identity, and the default export is
11 * `Api.make(props, impl)`: a Layer pairing the props with an init Effect
12 * whose impl returns `{ fetch }`, bundled into a generated image
13 * (`main: import.meta.url`). The Deployment synthesizes the Kubernetes
14 * Deployment + Service + ServiceAccount (server-side apply) and an Artifact
15 * Registry repository holding the image.
16 *
17 * The stack provides the Layer and yields the class (see `alchemy.run.ts`):
18 *
19 * ```typescript
20 * const api = yield* Api; // with Effect.provide(ApiLive)
21 * ```
22 *
23 * `serviceType: "LoadBalancer"` has GKE provision an external passthrough
24 * Network Load Balancer; `api.url` is the full URL INCLUDING the Service
25 * port (`http://<ip>:3000` — Kubernetes maps `spec.ports[].port` 1:1 to the
26 * cloud listener).
27 *
28 * Bindings work exactly as on Cloud Run:
29 * - `GCP.Firestore.ReadWriteDatabase` grants `roles/datastore.user` —
30 * project-level, under an IAM Condition naming this database — directly
31 * to the Deployment's Kubernetes ServiceAccount principal
32 * (`principal://…/subject/ns/guestbook/sa/<ksa>`), and injects the
33 * database name into the pod. At runtime the pod's GKE metadata server
34 * hands out Workload Identity Federation tokens for that principal — no
35 * keys, no Google service account.
36 *
37 * `podTemplate` is the Kubernetes escape hatch: a literal deep-partial Pod
38 * template merged into the synthesized one (objects merge recursively;
39 * arrays and primitives replace).
40 */
41 export class Api extends Kubernetes.Deployment<Api>()("Api") {}
42
43 export default Api.make(
44 // Props are themselves an Effect so they can reference shared resources.
45 Effect.gen(function* () {
46 const cluster = yield* GuestbookCluster;
47 const ns = yield* GuestbookNamespace;
48 return {
49 cluster,
50 main: import.meta.url,
51 // Reference the Manifest's attribute (not a bare string) so the
52 // Deployment depends on — and deploys after — the namespace.
53 namespace: ns.name,
54 port: 3000,
55 replicas: 2,
56 serviceType: "LoadBalancer" as const,
57 // Autopilot sizes nodes from requests (and pins limits to them).
58 resources: {
59 requests: { cpu: "250m", memory: "512Mi" },
60 limits: { cpu: "250m", memory: "512Mi" },
61 },
62 // Kubernetes escape hatch: tune the synthesized Pod template with a
63 // literal deep-partial object merged onto it.
64 podTemplate: {
65 metadata: {
66 annotations: {
67 "prometheus.io/scrape": "true",
68 "prometheus.io/port": "3000",
69 },
70 },
71 spec: { terminationGracePeriodSeconds: 30 },
72 },
73 };
74 }),
75 Effect.gen(function* () {
76 const db = yield* GCP.Firestore.ReadWriteDatabase(EntriesDatabase);
77
78 return {
79 fetch: Effect.gen(function* () {
80 const request = yield* HttpServerRequest;
81 const url = new URL(request.url, "http://guestbook");
82
83 // GET /entries — list every entry.
84 if (request.method === "GET" && url.pathname === "/entries") {
85 const page = yield* db.list("entries", { pageSize: 300 });
86 const entries = page.documents.map((document) => ({
87 id: document.name.split("/").pop(),
88 author: document.fields.author,
89 message: document.fields.message,
90 }));
91 return yield* HttpServerResponse.json({
92 count: entries.length,
93 entries,
94 });
95 }
96
97 // GET /entries/<id> — read one entry.
98 const match = url.pathname.match(/^\/entries\/([^/]+)$/);
99 if (request.method === "GET" && match) {
100 const document = yield* db.get(entryPath(match[1]!));
101 if (document === undefined) {
102 return yield* HttpServerResponse.json({ error: "not found" }, { status: 404 });
103 }
104 return yield* HttpServerResponse.json({
105 id: match[1],
106 author: document.fields.author,
107 message: document.fields.message,
108 });
109 }
110
111 // POST /entries?author=ada&message=hi — sign the guestbook.
112 if (request.method === "POST" && url.pathname === "/entries") {
113 const author = url.searchParams.get("author") ?? "anonymous";
114 const message = url.searchParams.get("message") ?? "";
115 const id = yield* Effect.sync(() => crypto.randomUUID().slice(0, 8));
116 yield* db.set(entryPath(id), { author, message });
117 return yield* HttpServerResponse.json({ id, author, message });
118 }
119
120 // Everything else — including "/" health probes.
121 return yield* HttpServerResponse.json({
122 ok: true,
123 service: "guestbook-api",
124 });
125 }).pipe(Effect.orDie),
126 };
127 }).pipe(Effect.provide(GCP.Firestore.ReadWriteDatabaseHttp)),
128 );