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

main
ts 385 lines 12.1 KB
Raw
1 import * as Planetscale from "@alchemy.run/planetscale";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Plan from "alchemy/Plan";
5 import * as Stack from "alchemy/Stack";
6 import { Stage } from "alchemy/Stage";
7 import { InMemoryService, inMemoryState, State, type ResourceState } from "alchemy/State";
8 import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
10 import * as Redacted from "effect/Redacted";
11
12 const TEST_STACK = "planetscale-plan-stables";
13 const TEST_STAGE = "test";
14
15 // Fresh in-memory state per test run so seeded resources from one test
16 // don't leak into another in the same file.
17 const freshState = Layer.effect(
18 State,
19 Effect.sync(() => InMemoryService({})),
20 );
21
22 const { test } = Test.make({
23 providers: Planetscale.providers(),
24 state: freshState,
25 });
26
27 const seed = (resources: Record<string, ResourceState>) =>
28 Effect.gen(function* () {
29 const state = yield* yield* State;
30 for (const [fqn, value] of Object.entries(resources)) {
31 yield* state.set({ stack: TEST_STACK, stage: TEST_STAGE, fqn, value });
32 }
33 });
34
35 const instanceId = "852f6ec2e19b66589825efe14dca2971";
36
37 const makePlan = <A, Err = never, Req = never>(
38 effect: Effect.Effect<A, Err, Req>,
39 options?: Plan.MakePlanOptions,
40 ): Effect.Effect<Plan.Plan<A>, Err, State> =>
41 // @ts-expect-error - Stack.make's typing erases R unsoundly here
42 Effect.gen(function* () {
43 // @ts-expect-error
44 return yield* effect.pipe(
45 // @ts-expect-error
46 Stack.make({
47 name: TEST_STACK,
48 providers: Layer.empty,
49 state: inMemoryState(),
50 }),
51 Effect.provideService(Stage, TEST_STAGE),
52 Effect.flatMap((stackSpec: any) => Plan.make(stackSpec, options)),
53 Effect.provide(Planetscale.providers()),
54 );
55 });
56
57 const ORG = "test-org";
58 const DB_NAME = "relay-db";
59 const BRANCH_NAME = "relay-branch";
60 const ROLE_NAME = "relay-role";
61
62 /** Attributes of the database as persisted after a previous deploy. */
63 const databaseAttrs = (migrationsHashes: Record<string, string>) => ({
64 id: "db_123",
65 name: DB_NAME,
66 organization: ORG,
67 state: "ready",
68 defaultBranch: "main",
69 plan: "scaler",
70 createdAt: "2026-01-01T00:00:00Z",
71 updatedAt: "2026-01-01T00:00:00Z",
72 htmlUrl: `https://app.planetscale.com/${ORG}/${DB_NAME}`,
73 region: { slug: "us-east" },
74 migrationsDir: "./migrations",
75 migrationsTable: "relay_migrations",
76 migrationsHashes,
77 importHashes: {},
78 clusterSize: "PS_10",
79 arch: "x86" as const,
80 requireApprovalForDeploy: false,
81 restrictBranchRegion: false,
82 productionBranchWebConsole: false,
83 });
84
85 const branchAttrs = () => ({
86 name: BRANCH_NAME,
87 organization: ORG,
88 database: DB_NAME,
89 parentBranch: "main",
90 production: false,
91 createdAt: "2026-01-01T00:00:00Z",
92 updatedAt: "2026-01-01T00:00:00Z",
93 htmlUrl: `https://app.planetscale.com/${ORG}/${DB_NAME}/${BRANCH_NAME}`,
94 region: { slug: "us-east" },
95 migrationsDir: undefined,
96 migrationsTable: undefined,
97 migrationsHashes: {},
98 importHashes: {},
99 desiredReplicas: undefined,
100 hasReplicas: false,
101 hasReadOnlyReplicas: false,
102 });
103
104 const roleAttrs = () => ({
105 id: "role_123",
106 name: ROLE_NAME,
107 expiresAt: null,
108 host: "gateway.psdb.cloud",
109 username: ROLE_NAME,
110 password: Redacted.make("secret"),
111 database: DB_NAME,
112 databaseName: "postgres",
113 origin: {
114 scheme: "postgres",
115 host: "gateway.psdb.cloud",
116 port: 5432,
117 database: "postgres",
118 user: ROLE_NAME,
119 password: Redacted.make("secret"),
120 },
121 pooledOrigin: {
122 scheme: "postgres",
123 host: "gateway.psdb.cloud",
124 port: 6432,
125 database: "postgres",
126 user: ROLE_NAME,
127 password: Redacted.make("secret"),
128 },
129 connectionUrl: Redacted.make("postgresql://..."),
130 connectionUrlPooled: Redacted.make("postgresql://..."),
131 inheritedRoles: ["pg_read_all_data"],
132 successor: "postgres",
133 organization: ORG,
134 branch: BRANCH_NAME,
135 ttl: null,
136 });
137
138 const stateRow = (
139 fqn: string,
140 resourceType: string,
141 props: Record<string, unknown>,
142 attr: Record<string, unknown>,
143 ): ResourceState => ({
144 instanceId,
145 providerVersion: 0,
146 logicalId: fqn,
147 fqn,
148 namespace: undefined,
149 resourceType,
150 status: "created",
151 props,
152 attr,
153 bindings: [],
154 downstream: [],
155 });
156
157 describe(
158 "Planetscale plan-time name stables",
159 { tags: ["provider:planetscale", "provider:planetscale:postgres", "live"] },
160 () => {
161 // Regression: a metadata-only update on a PostgresBranch (e.g. a
162 // referenced database's `migrationsHashes` moved) must not strip
163 // `branch.name` from downstream plan resolution — PostgresRole used to
164 // compare the old branch name against `undefined` and falsely plan a
165 // replacement (rotating credentials and crashing on the replacement's
166 // reconcile with `branch: undefined`).
167 test(
168 "role updates (not replaces) when its branch gets a metadata-only update",
169 Effect.gen(function* () {
170 // The database is an external ref (another stack/stage); its attrs
171 // arrive in props as a plain object. The previous deploy persisted
172 // the old migration hash; the new plan resolves the new one.
173 const oldDatabase = databaseAttrs({ "0001_init.sql": "aaa" });
174 const newDatabase = databaseAttrs({
175 "0001_init.sql": "aaa",
176 "0002_add_table.sql": "bbb",
177 });
178
179 yield* seed({
180 Branch: stateRow(
181 "Branch",
182 "Planetscale.PostgresBranch",
183 { name: BRANCH_NAME, database: oldDatabase },
184 branchAttrs(),
185 ),
186 Role: stateRow(
187 "Role",
188 "Planetscale.PostgresRole",
189 {
190 name: ROLE_NAME,
191 database: oldDatabase,
192 branch: branchAttrs(),
193 inheritedRoles: ["pg_read_all_data"],
194 },
195 roleAttrs(),
196 ),
197 });
198
199 const plan = yield* Effect.gen(function* () {
200 const branch = yield* Planetscale.PostgresBranch("Branch", {
201 name: BRANCH_NAME,
202 database: newDatabase as unknown as Planetscale.PostgresDatabase,
203 });
204 yield* Planetscale.PostgresRole("Role", {
205 name: ROLE_NAME,
206 database: newDatabase as unknown as Planetscale.PostgresDatabase,
207 branch,
208 inheritedRoles: ["pg_read_all_data"],
209 });
210 }).pipe(makePlan);
211
212 expect(plan.resources.Branch!.action).toBe("update");
213 // The branch update is not a rename, so `branch.name` stays
214 // resolvable and the role must not be replaced.
215 expect(plan.resources.Role!.action).toBe("update");
216 }),
217 );
218
219 // Regression: an in-place update on a PostgresDatabase (settings toggle,
220 // new migration hash, …) must keep `database.name` resolvable — the
221 // branch used to compare its persisted database name against `undefined`
222 // and plan a replacement, cascading into the role.
223 test(
224 "branch and role update (not replace) when the database gets an in-place update",
225 Effect.gen(function* () {
226 const dbAttrs = databaseAttrs({});
227
228 yield* seed({
229 Db: stateRow(
230 "Db",
231 "Planetscale.PostgresDatabase",
232 {
233 name: DB_NAME,
234 clusterSize: "PS_10",
235 requireApprovalForDeploy: false,
236 },
237 dbAttrs,
238 ),
239 Branch: stateRow(
240 "Branch",
241 "Planetscale.PostgresBranch",
242 { name: BRANCH_NAME, database: dbAttrs },
243 branchAttrs(),
244 ),
245 Role: stateRow(
246 "Role",
247 "Planetscale.PostgresRole",
248 {
249 name: ROLE_NAME,
250 database: dbAttrs,
251 branch: branchAttrs(),
252 inheritedRoles: ["pg_read_all_data"],
253 },
254 roleAttrs(),
255 ),
256 });
257
258 const plan = yield* Effect.gen(function* () {
259 const db = yield* Planetscale.PostgresDatabase("Db", {
260 name: DB_NAME,
261 clusterSize: "PS_10",
262 // In-place settings change — triggers an update, not a rename.
263 requireApprovalForDeploy: true,
264 });
265 const branch = yield* Planetscale.PostgresBranch("Branch", {
266 name: BRANCH_NAME,
267 database: db,
268 });
269 yield* Planetscale.PostgresRole("Role", {
270 name: ROLE_NAME,
271 database: db,
272 branch,
273 inheritedRoles: ["pg_read_all_data"],
274 });
275 }).pipe(makePlan);
276
277 expect(plan.resources.Db!.action).toBe("update");
278 expect(plan.resources.Branch!.action).toBe("update");
279 expect(plan.resources.Role!.action).toBe("update");
280 }),
281 );
282
283 // Regression (#1832): `--force` upgrades an unchanged database's noop
284 // to an update. Its conditional `name` stable must survive that, or the
285 // branch and role see `database.name === undefined` and plan a
286 // replacement — rotating the role's credentials on every forced deploy.
287 test(
288 "forced deploy of an unchanged stack updates (not replaces) the branch and role",
289 Effect.gen(function* () {
290 const dbAttrs = databaseAttrs({});
291 const dbProps = { name: DB_NAME, clusterSize: "PS_10" as const };
292
293 yield* seed({
294 Db: stateRow("Db", "Planetscale.PostgresDatabase", dbProps, dbAttrs),
295 Branch: stateRow(
296 "Branch",
297 "Planetscale.PostgresBranch",
298 { name: BRANCH_NAME, database: dbAttrs },
299 branchAttrs(),
300 ),
301 Role: stateRow(
302 "Role",
303 "Planetscale.PostgresRole",
304 {
305 name: ROLE_NAME,
306 database: dbAttrs,
307 branch: branchAttrs(),
308 inheritedRoles: ["pg_read_all_data"],
309 },
310 roleAttrs(),
311 ),
312 });
313
314 const program = Effect.gen(function* () {
315 const db = yield* Planetscale.PostgresDatabase("Db", dbProps);
316 const branch = yield* Planetscale.PostgresBranch("Branch", {
317 name: BRANCH_NAME,
318 database: db,
319 });
320 yield* Planetscale.PostgresRole("Role", {
321 name: ROLE_NAME,
322 database: db,
323 branch,
324 inheritedRoles: ["pg_read_all_data"],
325 });
326 });
327
328 const plan = yield* makePlan(program);
329 expect(plan.resources.Db!.action).toBe("noop");
330 expect(plan.resources.Branch!.action).toBe("noop");
331 expect(plan.resources.Role!.action).toBe("noop");
332
333 const forced = yield* makePlan(program, { force: true });
334 expect(forced.resources.Db!.action).toBe("update");
335 expect(forced.resources.Branch!.action).toBe("update");
336 expect(forced.resources.Role!.action).toBe("update");
337 }),
338 );
339
340 // A rename IS an identity change for downstream consumers: `name` must
341 // not be advertised as stable, and the role must plan a replacement.
342 test(
343 "role still replaces when the branch is renamed",
344 Effect.gen(function* () {
345 const database = databaseAttrs({});
346
347 yield* seed({
348 Branch: stateRow(
349 "Branch",
350 "Planetscale.PostgresBranch",
351 { name: BRANCH_NAME, database },
352 branchAttrs(),
353 ),
354 Role: stateRow(
355 "Role",
356 "Planetscale.PostgresRole",
357 {
358 name: ROLE_NAME,
359 database,
360 branch: branchAttrs(),
361 inheritedRoles: ["pg_read_all_data"],
362 },
363 roleAttrs(),
364 ),
365 });
366
367 const plan = yield* Effect.gen(function* () {
368 const branch = yield* Planetscale.PostgresBranch("Branch", {
369 name: "renamed-branch",
370 database: database as unknown as Planetscale.PostgresDatabase,
371 });
372 yield* Planetscale.PostgresRole("Role", {
373 name: ROLE_NAME,
374 database: database as unknown as Planetscale.PostgresDatabase,
375 branch,
376 inheritedRoles: ["pg_read_all_data"],
377 });
378 }).pipe(makePlan);
379
380 expect(plan.resources.Branch!.action).toBe("update");
381 expect(plan.resources.Role!.action).toBe("replace");
382 }),
383 );
384 },
385 );