@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 365 lines 13.5 KB
Raw
1 import { expect } from "@alchemy.run/test";
2 import * as Test from "@alchemy.run/test/Alchemy";
3 import * as Turso from "@alchemy.run/turso";
4 import { organization } from "@alchemy.run/turso/Credentials";
5 import * as Hrana from "@alchemy.run/turso/Hrana";
6 import * as turso from "@distilled.cloud/turso/turso";
7 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
8 import { Stage } from "alchemy/Stage";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Path from "effect/Path";
12 import * as Result from "effect/Result";
13 import * as Schedule from "effect/Schedule";
14
15 const { test } = Test.make({ providers: Turso.providers() });
16
17 const fixture = (name: string) =>
18 Effect.gen(function* () {
19 const path = yield* Path.Path;
20 return path.join(import.meta.dirname, "fixtures", name);
21 });
22
23 /** Query a database out-of-band with a short-lived token. */
24 const sql = (database: string, hostname: string, statement: string) =>
25 Effect.gen(function* () {
26 const org = yield* organization;
27 const { jwt } = yield* turso.createDatabaseToken({
28 organizationSlug: org,
29 databaseName: database,
30 expiration: "5m",
31 });
32 return yield* Hrana.query({ url: `https://${hostname}`, authToken: jwt! }, statement);
33 });
34
35 /** A per-stage, account-unique name for resources with a pinned `name`. */
36 const pinned = (suffix: string) =>
37 Effect.gen(function* () {
38 const stage = yield* Stage;
39 return `alchemy-${stage}-${suffix}`.toLowerCase().replace(/[^a-z0-9-]/g, "-");
40 });
41
42 const expectDatabaseGone = (name: string) =>
43 Effect.gen(function* () {
44 const org = yield* organization;
45 const exists = yield* turso.getDatabase({ organizationSlug: org, databaseName: name }).pipe(
46 Effect.map(() => true),
47 Effect.catchTag("NotFound", () => Effect.succeed(false)),
48 Effect.repeat({ schedule: Schedule.spaced("1 second"), until: (e) => !e, times: 10 }),
49 );
50 expect(exists).toBe(false);
51 });
52
53 test.provider(
54 "create, configure, migrate, seed, and delete a database",
55 (stack) =>
56 Effect.gen(function* () {
57 yield* stack.destroy();
58 const org = yield* organization;
59 const migrations = yield* fixture("migrations");
60 const seed = yield* fixture("seed/users.sql");
61
62 const app = (props: Partial<Turso.DatabaseProps>) =>
63 Effect.gen(function* () {
64 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
65 const db = yield* Turso.Database("Db", { group: group.name, ...props });
66 return { group, db };
67 });
68
69 const { group, db } = yield* stack.deploy(app({}));
70 expect(db.group).toBe(group.name);
71 expect(db.url).toBe(`libsql://${db.hostname}`);
72 expect(db.hostname).toContain(`-${org}.`);
73 expect(db.blockWrites).toBe(false);
74 expect(db.deleteProtection).toBe(false);
75
76 // Configuration converges in place.
77 const configured = yield* stack.deploy(
78 app({ blockWrites: true, blockReads: true, deleteProtection: true }),
79 );
80 expect(configured.db.dbId).toBe(db.dbId);
81 const config = yield* turso.getDatabaseConfiguration({
82 organizationSlug: org,
83 databaseName: db.name,
84 });
85 expect(config.block_writes).toBe(true);
86 expect(config.block_reads).toBe(true);
87 expect(config.delete_protection).toBe(true);
88
89 // Removing the props reverts them.
90 const reverted = yield* stack.deploy(app({}));
91 expect(reverted.db.blockWrites).toBe(false);
92 expect(reverted.db.blockReads).toBe(false);
93 expect(reverted.db.deleteProtection).toBe(false);
94
95 // Migrations, then SQL imports.
96 const migrated = yield* stack.deploy(app({ migrations, importFiles: [seed] }));
97 expect(Object.keys(migrated.db.migrationsHashes)).toHaveLength(2);
98 expect(Object.keys(migrated.db.importHashes)).toEqual([seed]);
99 const users = yield* sql(db.name, db.hostname, "SELECT name FROM users ORDER BY id");
100 expect(users).toEqual([{ name: "alice" }, { name: "bob" }]);
101 const posts = yield* sql(db.name, db.hostname, "SELECT count(*) AS n FROM posts");
102 expect(posts).toEqual([{ n: 0 }]);
103 const applied = yield* sql(
104 db.name,
105 db.hostname,
106 "SELECT count(*) AS n FROM __alchemy_migrations",
107 );
108 expect(applied).toEqual([{ n: 2 }]);
109
110 // A redeploy with unchanged files does not re-run the imports
111 // (re-running them would violate the primary key).
112 yield* stack.deploy(app({ migrations, importFiles: [seed] }));
113
114 yield* stack.destroy();
115 yield* expectDatabaseGone(db.name);
116 }),
117 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
118 );
119
120 test.provider(
121 "moving a database to another group replaces it",
122 (stack) =>
123 Effect.gen(function* () {
124 yield* stack.destroy();
125
126 const app = (target: "A" | "B") =>
127 Effect.gen(function* () {
128 // Keep both groups deployed across the replacement.
129 const a = yield* Turso.Group("GroupA", { location: "aws-us-east-1" });
130 const b = yield* Turso.Group("GroupB", { location: "aws-us-east-1" });
131 return yield* Turso.Database("Db", { group: target === "A" ? a.name : b.name });
132 });
133
134 const first = yield* stack.deploy(app("A"));
135 const second = yield* stack.deploy(app("B"));
136 expect(second.dbId).not.toBe(first.dbId);
137 expect(second.group).not.toBe(first.group);
138 yield* expectDatabaseGone(first.name);
139
140 yield* stack.destroy();
141 yield* expectDatabaseGone(second.name);
142 }),
143 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
144 );
145
146 test.provider(
147 "fork a database from another with seed",
148 (stack) =>
149 Effect.gen(function* () {
150 yield* stack.destroy();
151 const migrations = yield* fixture("migrations");
152 const seed = yield* fixture("seed/users.sql");
153
154 const app = (withFork: boolean) =>
155 Effect.gen(function* () {
156 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
157 const source = yield* Turso.Database("Source", {
158 group: group.name,
159 migrations,
160 importFiles: [seed],
161 });
162 const fork = withFork
163 ? yield* Turso.Database("Fork", {
164 group: group.name,
165 seed: { type: "database", name: source.name },
166 })
167 : undefined;
168 return { source, fork };
169 });
170
171 // Deploy the source first so the fork copies its seeded data.
172 yield* stack.deploy(app(false));
173 const { fork } = yield* stack.deploy(app(true));
174 const users = yield* sql(fork!.name, fork!.hostname, "SELECT name FROM users ORDER BY id");
175 expect(users).toEqual([{ name: "alice" }, { name: "bob" }]);
176
177 yield* stack.destroy();
178 yield* expectDatabaseGone(fork!.name);
179 }),
180 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
181 );
182
183 test.provider(
184 "a failing import rolls back and leaves no partial schema",
185 (stack) =>
186 Effect.gen(function* () {
187 yield* stack.destroy();
188 const broken = yield* fixture("seed/broken.sql");
189
190 const app = (importFiles: string[]) =>
191 Effect.gen(function* () {
192 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
193 return yield* Turso.Database("Db", { group: group.name, importFiles });
194 });
195
196 const db = yield* stack.deploy(app([]));
197 const error = yield* stack.deploy(app([broken])).pipe(Effect.flip);
198 expect(String(error)).toContain("missing_table");
199 const tables = yield* sql(
200 db.name,
201 db.hostname,
202 "SELECT name FROM sqlite_master WHERE name = 'half_applied'",
203 );
204 expect(tables).toEqual([]);
205
206 yield* stack.destroy();
207 yield* expectDatabaseGone(db.name);
208 }),
209 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
210 );
211
212 test.provider(
213 "moving a database with a pinned name deletes the old one first",
214 (stack) =>
215 Effect.gen(function* () {
216 yield* stack.destroy();
217 const name = yield* pinned("pinned-db");
218
219 const app = (target: "A" | "B") =>
220 Effect.gen(function* () {
221 const a = yield* Turso.Group("GroupA", { location: "aws-us-east-1" });
222 const b = yield* Turso.Group("GroupB", { location: "aws-us-east-1" });
223 return yield* Turso.Database("Db", { name, group: target === "A" ? a.name : b.name });
224 });
225
226 const first = yield* stack.deploy(app("A"));
227 expect(first.name).toBe(name);
228 const second = yield* stack.deploy(app("B"));
229 expect(second.name).toBe(name);
230 expect(second.dbId).not.toBe(first.dbId);
231 expect(second.group).not.toBe(first.group);
232
233 yield* stack.destroy();
234 yield* expectDatabaseGone(name);
235 }),
236 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
237 );
238
239 test.provider(
240 "a database with a pinned name created elsewhere is refused unless adopted",
241 (stack) =>
242 Effect.gen(function* () {
243 yield* stack.destroy();
244 const org = yield* organization;
245 const name = yield* pinned("foreign-db");
246
247 const group = yield* stack.deploy(Turso.Group("Group", { location: "aws-us-east-1" }));
248 yield* turso
249 .deleteDatabase({ organizationSlug: org, databaseName: name })
250 .pipe(Effect.catchTag("NotFound", () => Effect.void));
251 const foreign = yield* turso.createDatabase({
252 organizationSlug: org,
253 name,
254 group: group.name,
255 });
256
257 const app = (allow: boolean) =>
258 Effect.gen(function* () {
259 const g = yield* Turso.Group("Group", { location: "aws-us-east-1" });
260 return yield* Turso.Database("Db", { name, group: g.name }).pipe(adopt(allow));
261 });
262
263 const refused = yield* stack.deploy(app(false)).pipe(Effect.result);
264 expect(Result.isFailure(refused)).toBe(true);
265 if (Result.isFailure(refused)) expect(refused.failure).toBeInstanceOf(OwnedBySomeoneElse);
266
267 const adopted = yield* stack.deploy(app(true));
268 expect(adopted.dbId).toBe(foreign.database?.DbId);
269
270 // Once adopted, later deploys need no adopt flag.
271 expect((yield* stack.deploy(app(false))).dbId).toBe(adopted.dbId);
272
273 yield* stack.destroy();
274 yield* expectDatabaseGone(name);
275 }),
276 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
277 );
278
279 test.provider(
280 "migrations honor a custom table and reject rewritten history",
281 (stack) =>
282 Effect.gen(function* () {
283 yield* stack.destroy();
284 const fs = yield* FileSystem.FileSystem;
285 const path = yield* Path.Path;
286 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "turso-migrations-" });
287 yield* fs.writeFileString(
288 path.join(dir, "0001_items.sql"),
289 "CREATE TABLE items (id INTEGER PRIMARY KEY);",
290 );
291
292 const app = Effect.gen(function* () {
293 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
294 return yield* Turso.Database("Db", {
295 group: group.name,
296 migrations: { dir, table: "schema_migrations" },
297 });
298 });
299
300 const db = yield* stack.deploy(app);
301 expect(db.migrationsTable).toBe("schema_migrations");
302 expect(
303 yield* sql(db.name, db.hostname, "SELECT count(*) AS n FROM schema_migrations"),
304 ).toEqual([{ n: 1 }]);
305
306 // A second file is applied on the next deploy.
307 yield* fs.writeFileString(
308 path.join(dir, "0002_tags.sql"),
309 "CREATE TABLE tags (id INTEGER PRIMARY KEY);",
310 );
311 yield* stack.deploy(app);
312 expect(
313 yield* sql(db.name, db.hostname, "SELECT count(*) AS n FROM schema_migrations"),
314 ).toEqual([{ n: 2 }]);
315
316 // Editing an applied file fails the deploy.
317 yield* fs.writeFileString(
318 path.join(dir, "0001_items.sql"),
319 "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT);",
320 );
321 const rewritten = yield* stack.deploy(app).pipe(Effect.flip);
322 expect(String(rewritten)).toContain("0001_items.sql");
323
324 yield* stack.destroy();
325 yield* expectDatabaseGone(db.name);
326 }).pipe(Effect.scoped),
327 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
328 );
329
330 test.provider(
331 "fork a database from a point in time",
332 (stack) =>
333 Effect.gen(function* () {
334 yield* stack.destroy();
335
336 const source = yield* stack.deploy(
337 Effect.gen(function* () {
338 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
339 return yield* Turso.Database("Source", { group: group.name });
340 }),
341 );
342 yield* sql(source.name, source.hostname, "CREATE TABLE t (v INTEGER)");
343 yield* Effect.sleep("3 seconds");
344 const timestamp = new Date(Date.now() - 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
345
346 const { fork } = yield* stack.deploy(
347 Effect.gen(function* () {
348 const group = yield* Turso.Group("Group", { location: "aws-us-east-1" });
349 const src = yield* Turso.Database("Source", { group: group.name });
350 const fork = yield* Turso.Database("Fork", {
351 group: group.name,
352 seed: { type: "database", name: src.name, timestamp },
353 });
354 return { fork };
355 }),
356 );
357 expect(fork.dbId).not.toBe(source.dbId);
358 expect(
359 yield* sql(fork.name, fork.hostname, "SELECT name FROM sqlite_master WHERE name = 't'"),
360 ).toEqual([{ name: "t" }]);
361
362 yield* stack.destroy();
363 }),
364 { tags: ["provider:turso", "provider:turso:database", "live"], timeout: 180_000 },
365 );