The best way to control Claude Code, Codex and more from any computer or phone

main
ts 434 lines 16.1 KB
Raw
1 import * as Planetscale from "@alchemy.run/planetscale";
2 import { hashMigrations } from "@alchemy.run/sql/SqlFile";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as ps from "@distilled.cloud/planetscale";
6 import { adopt } from "alchemy/AdoptPolicy";
7 import * as Drift from "alchemy/Drift";
8 import * as Provider from "alchemy/Provider";
9 import { Data, Schedule } from "effect";
10 import * as Cause from "effect/Cause";
11 import * as Effect from "effect/Effect";
12 import * as Exit from "effect/Exit";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Path from "effect/Path";
15 import { MinimumLogLevel } from "effect/References";
16
17 const { test } = Test.make({ providers: Planetscale.providers() });
18
19 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
20
21 const fixturesDir = `${import.meta.dirname}/Postgres/fixtures`;
22
23 const branchOutput = (
24 overrides: Partial<Planetscale.PostgresBranchAttributes> = {},
25 ): Planetscale.PostgresBranchAttributes => ({
26 name: "branch",
27 organization: "org",
28 database: "database",
29 parentBranch: "main",
30 production: false,
31 createdAt: "2026-01-01T00:00:00.000Z",
32 updatedAt: "2026-01-01T00:00:00.000Z",
33 htmlUrl: "https://planetscale.com/org/database/branch/branch",
34 region: { slug: "us-east" },
35 migrationsDir: undefined,
36 migrationsTable: undefined,
37 migrationsHashes: {},
38 importHashes: {},
39 desiredReplicas: undefined,
40 hasReplicas: undefined,
41 hasReadOnlyReplicas: undefined,
42 ...overrides,
43 });
44
45 test.provider(
46 "diff tracks Postgres branch replica intent",
47 () =>
48 Effect.gen(function* () {
49 const provider = yield* Provider.findProvider(Planetscale.PostgresBranch);
50 const props = (replicas: number): Planetscale.PostgresBranchProps => ({
51 database: "database",
52 parentBranch: "main",
53 replicas,
54 });
55
56 const alreadyConvergedToNonHa = yield* provider.diff!({
57 id: "Branch",
58 fqn: "Branch",
59 instanceId: "instance",
60 olds: props(0),
61 news: props(0),
62 oldBindings: [],
63 newBindings: [],
64 output: branchOutput({
65 desiredReplicas: 0,
66 hasReplicas: false,
67 hasReadOnlyReplicas: false,
68 }),
69 });
70 // Converged: a noop that still carries the `name` stable for `--force`.
71 expect(alreadyConvergedToNonHa).toEqual({
72 action: "noop",
73 stables: ["organization", "database", "name"],
74 });
75
76 const exactHaCountChanged = yield* provider.diff!({
77 id: "Branch",
78 fqn: "Branch",
79 instanceId: "instance",
80 olds: props(2),
81 news: props(3),
82 oldBindings: [],
83 newBindings: [],
84 output: branchOutput({ desiredReplicas: 2, hasReplicas: true, hasReadOnlyReplicas: false }),
85 });
86 // A non-renaming update advertises `name` as stable so downstream
87 // consumers keep resolving `branch.name` at plan time.
88 expect(exactHaCountChanged).toEqual({
89 action: "update",
90 stables: ["organization", "database", "name"],
91 });
92 }),
93 { tags: ["provider:planetscale", "provider:planetscale:postgres", "live"] },
94 );
95
96 describe.skipIf(!process.env.PLANETSCALE_TEST)(
97 "Branch",
98 { tags: ["provider:planetscale", "live"] },
99 () => {
100 test.provider.skipIf(
101 !process.env.PLANETSCALE_BRANCH_REPLICA_TEST ||
102 !process.env.PLANETSCALE_BRANCH_REPLICA_DATABASE,
103 )(
104 "Postgres branch persists replica intent and plans no-op once converged",
105 (stack) =>
106 Effect.gen(function* () {
107 const dbName = process.env.PLANETSCALE_BRANCH_REPLICA_DATABASE!;
108 const branchName = `replica-target-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
109 const { organization } = yield* yield* Planetscale.Credentials;
110
111 yield* Effect.gen(function* () {
112 yield* stack.destroy();
113 yield* deleteBranchIfExists(dbName, branchName, organization);
114
115 const program = Effect.gen(function* () {
116 const branch = yield* Planetscale.PostgresBranch("ReplicaBranch", {
117 name: branchName,
118 database: dbName,
119 parentBranch: "main",
120 replicas: 0,
121 });
122
123 return { branch };
124 });
125
126 const { branch } = yield* stack.deploy(program);
127
128 expect(branch).toMatchObject({
129 name: branchName,
130 database: dbName,
131 desiredReplicas: 0,
132 hasReplicas: false,
133 hasReadOnlyReplicas: false,
134 });
135
136 const live = yield* ps.getBranch({
137 organization,
138 database: dbName,
139 branch: branchName,
140 });
141
142 expect(live.has_replicas).toBe(false);
143 expect(live.has_read_only_replicas).toBe(false);
144
145 const plan = yield* stack.plan(program);
146 expect(plan.resources.ReplicaBranch).toMatchObject({ action: "noop" });
147
148 yield* stack.destroy();
149 yield* waitForBranchToBeDeleted(dbName, branchName, organization);
150 }).pipe(Effect.ensuring(deleteBranchIfExists(dbName, branchName, organization)));
151 }).pipe(logLevel),
152 { timeout: 5_000_000, tags: ["provider:planetscale:postgres"] },
153 );
154
155 test.provider(
156 "Postgres branch off an ARM parent expands a short cluster size to an ARM SKU",
157 (stack) =>
158 Effect.gen(function* () {
159 yield* stack.destroy();
160
161 const { database, branch } = yield* stack.deploy(
162 Effect.gen(function* () {
163 const database = yield* Planetscale.PostgresDatabase("ArmParentDatabase", {
164 clusterSize: "PS_10",
165 arch: "arm",
166 });
167 const branch = yield* Planetscale.PostgresBranch("ArmChildBranch", {
168 database,
169 parentBranch: "main",
170 clusterSize: "PS_DEV",
171 });
172
173 return { database, branch };
174 }),
175 );
176
177 const live = yield* ps.getBranch({
178 organization: database.organization,
179 database: database.name,
180 branch: branch.name,
181 });
182
183 expect(live.cluster_architecture).toEqual("aarch64");
184 expect(live.cluster_name).toEqual("PS_DEV_AWS_ARM");
185
186 yield* stack.destroy();
187 yield* waitForDatabaseToBeDeleted(database.name, database.organization);
188 }).pipe(logLevel),
189 { timeout: 5_000_000, tags: ["provider:planetscale:postgres"] },
190 );
191
192 // Regression for #1955: a PostgresBranch adopting the database's default
193 // `main` branch (with a role on it, as in the issue) must report no drift
194 // right after a successful deploy.
195 test.provider(
196 "Postgres default branch reports no drift after deploy",
197 (stack) =>
198 Effect.gen(function* () {
199 yield* stack.destroy();
200
201 const { database, branch } = yield* stack.deploy(
202 Effect.gen(function* () {
203 const database = yield* Planetscale.PostgresDatabase("DriftDatabase", {
204 clusterSize: "PS_10",
205 });
206 const branch = yield* Planetscale.PostgresBranch("Branch", {
207 database,
208 name: "main",
209 migrations: `${fixturesDir}/migrations`,
210 }).pipe(adopt(true));
211 yield* Planetscale.PostgresRole("Role", {
212 database,
213 branch,
214 inheritedRoles: [],
215 });
216
217 return { database, branch };
218 }),
219 );
220
221 expect(branch.name).toEqual("main");
222 expect(branch.migrationsHashes["0001_create_widgets.sql"]).toEqual(expect.any(String));
223
224 // PlanetScale bumps the branch's `updated_at` a few seconds after the
225 // deploy (no config change). Wait for that bump so drift detection
226 // observes the volatile timestamp.
227 yield* ps
228 .getBranch({
229 organization: branch.organization,
230 database: branch.database,
231 branch: branch.name,
232 })
233 .pipe(
234 Effect.repeat({
235 schedule: Schedule.spaced("3 seconds"),
236 until: (live) => live.updated_at !== branch.updatedAt,
237 times: 20,
238 }),
239 );
240
241 const { plan } = yield* Drift.plan({ name: stack.name, stage: stack.stage }).pipe(
242 Effect.provide(stack.state),
243 );
244 const { action, drift } = plan.resources.Branch!;
245 expect({ action, drift }).toEqual({ action: "noop", drift: undefined });
246 expect(plan.resources.DriftDatabase).toMatchObject({ action: "noop" });
247
248 yield* stack.destroy();
249 yield* waitForDatabaseToBeDeleted(database.name, database.organization);
250 }).pipe(logLevel),
251 { timeout: 5_000_000, tags: ["provider:planetscale:postgres"] },
252 );
253
254 // #1389: an edited already-applied migration used to plan as an
255 // in-place update; the runner skipped it by name and persisted the new
256 // hash, silently accepting rewritten history.
257 test.provider(
258 "rewritten migration history replaces a development branch and fails on production",
259 (stack) =>
260 Effect.gen(function* () {
261 const fs = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const root = path.join(import.meta.dirname, "../../.tmp", `ps-rewrite-${stack.stage}`);
264 const databaseDir = path.join(root, "database");
265 const branchDir = path.join(root, "branch");
266 yield* fs.remove(root, { recursive: true, force: true });
267 yield* fs.makeDirectory(databaseDir, { recursive: true });
268 yield* fs.makeDirectory(branchDir, { recursive: true });
269 const init = "CREATE TABLE users (id int);";
270 yield* fs.writeFileString(path.join(databaseDir, "0001_init.sql"), init);
271 yield* fs.writeFileString(path.join(branchDir, "0001_init.sql"), init);
272 // Applied only on the development branch, never on main.
273 yield* fs.writeFileString(
274 path.join(branchDir, "0002_posts.sql"),
275 "CREATE TABLE posts (id int);",
276 );
277
278 const program = Effect.gen(function* () {
279 const database = yield* Planetscale.PostgresDatabase("RewriteDatabase", {
280 clusterSize: "PS_5",
281 migrations: databaseDir,
282 });
283 const branch = yield* Planetscale.PostgresBranch("RewriteBranch", {
284 database,
285 parentBranch: "main",
286 migrations: branchDir,
287 });
288 return { database, branch };
289 });
290
291 yield* stack.destroy();
292
293 const first = yield* stack.deploy(program);
294 expect(first.branch.production).toBe(false);
295
296 // Rewrite the branch-only migration: the branch re-forks from main
297 // (which never ran it) and applies the new version.
298 yield* fs.writeFileString(
299 path.join(branchDir, "0002_posts.sql"),
300 "CREATE TABLE posts (id int, title text);",
301 );
302 const plan = yield* stack.plan(program);
303 expect(plan.resources.RewriteBranch).toMatchObject({ action: "replace" });
304
305 const second = yield* stack.deploy(program);
306 expect(second.branch.name).not.toEqual(first.branch.name);
307 expect(second.branch.migrationsHashes).toEqual(yield* hashMigrations(branchDir));
308 yield* waitForBranchToBeDeleted(
309 first.database.name,
310 first.branch.name,
311 first.database.organization,
312 );
313
314 // Rewrite a migration main (a production branch) already ran: no
315 // replacement is possible, so the deploy fails and keeps the
316 // recorded history.
317 yield* fs.writeFileString(
318 path.join(databaseDir, "0001_init.sql"),
319 "CREATE TABLE users (id int, name text);",
320 );
321 const rewrite = yield* Effect.exit(stack.deploy(program));
322 expect(Exit.isFailure(rewrite)).toBe(true);
323 if (Exit.isFailure(rewrite)) {
324 expect(Cause.pretty(rewrite.cause)).toContain("forward migration");
325 }
326
327 yield* stack.destroy();
328 yield* waitForDatabaseToBeDeleted(first.database.name, first.database.organization);
329 }).pipe(logLevel),
330 { timeout: 5_000_000, tags: ["provider:planetscale:postgres"] },
331 );
332
333 // Canonical `list()` test (PARENT FAN-OUT): branches live under a database
334 // within the credentialed organization. `list()` enumerates every database
335 // in the org, lists each database's branches, and keeps only the engine's
336 // kind (here MySQL). Deploy one branch, then assert it appears in the
337 // exhaustively-paginated result.
338 test.provider(
339 "list enumerates the deployed branch across the org",
340 (stack) =>
341 Effect.gen(function* () {
342 const dbName = "alchemy-branch-list";
343 const branchName = "list-target";
344
345 yield* stack.destroy();
346
347 const { database, branch } = yield* stack.deploy(
348 Effect.gen(function* () {
349 const database = yield* Planetscale.MySQLDatabase("Database", {
350 name: dbName,
351 region: { slug: "us-east" },
352 clusterSize: "PS_10",
353 });
354 const branch = yield* Planetscale.MySQLBranch("ListBranch", {
355 name: branchName,
356 database,
357 parentBranch: "main",
358 isProduction: false,
359 });
360
361 return { database, branch };
362 }),
363 );
364
365 const provider = yield* Provider.findProvider(Planetscale.MySQLBranch);
366 const all = yield* provider.list();
367
368 const found = all.find(
369 (b) =>
370 b.organization === database.organization &&
371 b.database === dbName &&
372 b.name === branch.name,
373 );
374
375 expect(found).toBeDefined();
376 expect(found).toMatchObject({
377 organization: database.organization,
378 database: dbName,
379 name: branch.name,
380 parentBranch: "main",
381 production: false,
382 createdAt: expect.any(String),
383 updatedAt: expect.any(String),
384 htmlUrl: expect.any(String),
385 region: { slug: expect.any(String) },
386 });
387
388 // Every item is hydrated into the exact `read` Attributes shape — the
389 // org's `main` branch is enumerated too, only as MySQL kind.
390 expect(all.every((b) => b.organization === database.organization)).toBe(true);
391
392 yield* stack.destroy();
393 yield* waitForDatabaseToBeDeleted(dbName, database.organization);
394 }).pipe(logLevel),
395 { timeout: 5_000_000, tags: ["provider:planetscale:mysql"] },
396 );
397 },
398 );
399
400 const waitForDatabaseToBeDeleted = Effect.fn(function* (database: string, organization: string) {
401 yield* ps.getDatabase({ organization, database }).pipe(
402 Effect.flatMap(() => Effect.fail(new DatabaseStillExists())),
403 Effect.retry({
404 while: (e): e is DatabaseStillExists => e instanceof DatabaseStillExists,
405 schedule: Schedule.exponential(100),
406 }),
407 Effect.catchTag("NotFound", () => Effect.void),
408 );
409 });
410
411 const waitForBranchToBeDeleted = Effect.fn(function* (
412 database: string,
413 branch: string,
414 organization: string,
415 ) {
416 yield* ps.getBranch({ organization, database, branch }).pipe(
417 Effect.flatMap(() => Effect.fail(new BranchStillExists())),
418 Effect.retry({
419 while: (e): e is BranchStillExists => e instanceof BranchStillExists,
420 schedule: Schedule.exponential(100),
421 }),
422 Effect.catchTag("NotFound", () => Effect.void),
423 );
424 });
425
426 const deleteBranchIfExists = (database: string, branch: string, organization: string) =>
427 ps.deleteBranch({ organization, database, branch }).pipe(
428 Effect.catchTag("NotFound", () => Effect.void),
429 Effect.flatMap(() => waitForBranchToBeDeleted(database, branch, organization)),
430 Effect.ignore,
431 );
432
433 class BranchStillExists extends Data.TaggedError("BranchStillExists") {}
434 class DatabaseStillExists extends Data.TaggedError("DatabaseStillExists") {}