@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, 04:45 UTC

main
ts 201 lines 7.24 KB
Raw
1 import { describe, expect } from "bun:test";
2 import * as GCP from "@alchemy.run/gcp";
3 import * as Test from "@alchemy.run/test/Bun";
4 import * as run from "@distilled.cloud/gcp/run_v2";
5 import * as secretmanager from "@distilled.cloud/gcp/secretmanager_v1";
6 import * as sqladmin from "@distilled.cloud/gcp/sqladmin_v1";
7 import * as Alchemy from "alchemy";
8 import * as Effect from "effect/Effect";
9 import * as FetchHttpClient from "effect/http/FetchHttpClient";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Layer from "effect/Layer";
13 import * as Schedule from "effect/Schedule";
14 import Stack, { providers } from "../alchemy.run.ts";
15
16 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
17 providers: providers(),
18 state: Alchemy.localState(),
19 });
20
21 const { getWhenReady } = Test;
22
23 // Out-of-band calls to the Google APIs resolve the same stored credentials
24 // the deploy uses, so the test runs against the configured profile.
25 // Distilled routes the regional secret to its regional endpoint.
26 const GcpHttp = Layer.mergeAll(GCP.GcpAuth, GCP.fromAuthProvider(), FetchHttpClient.layer);
27
28 // Deploy, tests and destroy all sit behind the same Docker guard.
29 describe("gcp-cloud-sql-drizzle", () => {
30 // Creating a Cloud SQL instance takes 5–10 minutes (and deleting one a
31 // few more); everything else is bounded well below that.
32 const stack = beforeAll(deploy(Stack), { timeout: 1_500_000 });
33
34 afterAll.skipIf(!!process.env.NO_DESTROY)(
35 Effect.gen(function* () {
36 const outputs = yield* stack;
37 yield* destroy(Stack);
38 if (outputs === undefined) return;
39
40 const project = outputs.connectionName?.split(":")[0] ?? "";
41 const instance = yield* sqladmin
42 .getInstances({ project, instance: outputs.instanceName })
43 .pipe(
44 Effect.map(() => "present" as const),
45 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
46 Effect.orDie,
47 Effect.provide(GcpHttp),
48 );
49 expect(instance).toBe("gone");
50
51 const secret = yield* secretmanager
52 .getProjectsLocationsSecrets({ name: outputs.passwordSecretName })
53 .pipe(
54 Effect.map(() => "present" as const),
55 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
56 Effect.orDie,
57 Effect.provide(GcpHttp),
58 );
59 expect(secret).toBe("gone");
60
61 const service = yield* run.getProjectsLocationsServices({ name: outputs.serviceName }).pipe(
62 Effect.map(() => "present" as const),
63 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
64 Effect.orDie,
65 Effect.provide(GcpHttp),
66 );
67 expect(service).toBe("gone");
68 }),
69 { timeout: 1_200_000 },
70 );
71
72 const baseUrlOf = (url: string | undefined) => {
73 if (url === undefined) throw new Error("the service has no URL");
74 return url.replace(/\/+$/, "");
75 };
76
77 const request = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: unknown) =>
78 HttpClient.execute(
79 body === undefined
80 ? HttpClientRequest.make(method)(url)
81 : HttpClientRequest.make(method)(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
82 );
83
84 /** Query the database directly through the Cloud SQL Data API. */
85 const executeSql = (
86 outputs: {
87 instanceName: string;
88 connectionName: string | undefined;
89 databaseName: string;
90 userName: string;
91 passwordSecretName: string;
92 },
93 sqlStatement: string,
94 ) =>
95 sqladmin
96 .executeSqlInstances({
97 project: outputs.connectionName?.split(":")[0] ?? "",
98 instance: outputs.instanceName,
99 body: {
100 database: outputs.databaseName,
101 user: outputs.userName,
102 passwordSecretVersion: `${outputs.passwordSecretName}/versions/latest`,
103 sqlStatement,
104 },
105 })
106 .pipe(
107 Effect.map((response) => {
108 const result = response.results?.at(-1);
109 const columns = (result?.columns ?? []).map((c) => c.name ?? "");
110 return (result?.rows ?? []).map((row) =>
111 Object.fromEntries(
112 columns.map((name, index) => [
113 name,
114 row.values?.[index]?.nullValue ? null : row.values?.[index]?.value,
115 ]),
116 ),
117 );
118 }),
119 Effect.orDie,
120 Effect.provide(GcpHttp),
121 );
122
123 test(
124 "applies the drizzle migration at deploy time",
125 Effect.gen(function* () {
126 const outputs = yield* stack;
127 const applied = yield* executeSql(outputs, "SELECT name FROM __alchemy_migrations");
128 expect(applied).toHaveLength(1);
129 expect(String(applied[0]?.name)).toMatch(/^\d{14}_/);
130 const columns = yield* executeSql(
131 outputs,
132 "SELECT column_name FROM information_schema.columns WHERE table_name = 'todos' ORDER BY column_name",
133 );
134 expect(columns.map((row) => row.column_name)).toEqual(["done", "id", "title"]);
135 }),
136 { timeout: 120_000 },
137 );
138
139 test(
140 "serves CRUD over Drizzle on the Cloud SQL socket",
141 Effect.gen(function* () {
142 const outputs = yield* stack;
143 const baseUrl = baseUrlOf(outputs.url);
144 yield* getWhenReady(`${baseUrl}/`);
145
146 const id = "aaaaaaaa-0000-4000-8000-000000000001";
147 // The project-level cloudsql.client grant (under an IAM Condition) can
148 // take a few minutes to reach a fresh service account; until then the
149 // socket refuses the connection and the service answers 500.
150 const empty = yield* request("DELETE", `${baseUrl}/todos/${id}`).pipe(
151 Effect.repeat({
152 schedule: Schedule.spaced("10 seconds"),
153 until: (response) => response.status !== 500,
154 times: 42,
155 }),
156 );
157 expect(empty.status).toBe(204);
158
159 const created = yield* request("POST", `${baseUrl}/todos`, {
160 id,
161 title: "Ship the Cloud SQL guide",
162 });
163 expect(created.status).toBe(201);
164 expect(yield* created.json).toEqual([{ id, title: "Ship the Cloud SQL guide", done: false }]);
165
166 // The row is really in Cloud SQL.
167 const rows = yield* executeSql(
168 outputs,
169 `SELECT id, title, done FROM todos WHERE id = '${id}'`,
170 );
171 expect(rows).toEqual([{ id, title: "Ship the Cloud SQL guide", done: "false" }]);
172
173 const updated = yield* request("PATCH", `${baseUrl}/todos/${id}`, {
174 done: true,
175 });
176 expect(updated.status).toBe(200);
177 expect(yield* updated.json).toEqual({
178 id,
179 title: "Ship the Cloud SQL guide",
180 done: true,
181 });
182
183 const listed = yield* request("GET", `${baseUrl}/todos`);
184 expect(listed.status).toBe(200);
185 expect(yield* listed.json).toEqual([{ id, title: "Ship the Cloud SQL guide", done: true }]);
186
187 const invalid = yield* request("POST", `${baseUrl}/todos`, {
188 id: "not-a-uuid",
189 title: "",
190 });
191 expect(invalid.status).toBe(400);
192
193 const deleted = yield* request("DELETE", `${baseUrl}/todos/${id}`);
194 expect(deleted.status).toBe(204);
195 const gone = yield* request("GET", `${baseUrl}/todos/${id}`);
196 expect(gone.status).toBe(404);
197 expect(yield* executeSql(outputs, `SELECT id FROM todos WHERE id = '${id}'`)).toEqual([]);
198 }),
199 { timeout: 600_000 },
200 );
201 });