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

main
ts 122 lines 3.92 KB
Raw
1 import {
2 runMigrations,
3 withPgExecutor,
4 type NormalizedMigrationsInput,
5 type SqlExecutor,
6 type StampedMigrationsState,
7 } from "@alchemy.run/sql/Migrations";
8 import { stripSslQueryParams } from "@alchemy.run/sql/PostgresDriver";
9 import { applySqlImports } from "@alchemy.run/sql/SqlFile";
10 import * as ps from "@distilled.cloud/planetscale";
11 import * as Effect from "effect/Effect";
12 import * as Redacted from "effect/Redacted";
13 import * as Schedule from "effect/Schedule";
14
15 const MIGRATION_ROLE_TTL_SECONDS = 600;
16
17 export interface PostgresMigrationTarget {
18 organization: string;
19 database: string;
20 branch: string;
21 }
22
23 /**
24 * PlanetScale Postgres's migration adaptation is exactly this: the shared
25 * pipeline with a temp-role-scoped pg client as its executor.
26 */
27 export const runPostgresMigrations = (
28 target: PostgresMigrationTarget,
29 input: NormalizedMigrationsInput,
30 stamped: StampedMigrationsState,
31 ) =>
32 runMigrations({
33 input,
34 stamped,
35 withExecutor: (apply) => withPostgresExecutor(target, apply),
36 });
37
38 /** Apply `importFiles`, each once and again only when it changes. */
39 export const runPostgresImports = (
40 target: PostgresMigrationTarget,
41 importFiles: ReadonlyArray<string>,
42 rootDir: string,
43 previous: Record<string, string>,
44 ) =>
45 applySqlImports({
46 importFiles,
47 rootDir,
48 previous,
49 apply: (file) =>
50 withPostgresExecutor(target, (executor) => executor.query(file.sql)).pipe(Effect.asVoid),
51 });
52
53 /** A verified-TLS `pg` session as a short-lived migration role. */
54 const withPostgresExecutor = <A, E, R>(
55 target: PostgresMigrationTarget,
56 use: (executor: SqlExecutor) => Effect.Effect<A, E, R>,
57 ) =>
58 withTemporaryPostgresRole(target, (role) =>
59 withPgExecutor(
60 {
61 connectionString: role.connectionUrl.pipe(Redacted.value, stripSslQueryParams),
62 ssl: { rejectUnauthorized: true },
63 },
64 use,
65 ),
66 );
67
68 const withTemporaryPostgresRole = <A, E, R>(
69 target: PostgresMigrationTarget,
70 use: (role: { id: string; connectionUrl: Redacted.Redacted<string> }) => Effect.Effect<A, E, R>,
71 ) =>
72 Effect.acquireUseRelease(
73 Effect.gen(function* () {
74 const created = yield* ps.createRole({
75 organization: target.organization,
76 database: target.database,
77 branch: target.branch,
78 ttl: MIGRATION_ROLE_TTL_SECONDS,
79 inherited_roles: ["postgres"],
80 });
81
82 const password = created.password!;
83 const value = Redacted.value(password);
84 const connectionUrl = yield* Effect.sync(
85 () =>
86 `postgresql://${encodeURIComponent(created.username)}:${encodeURIComponent(value)}@${created.access_host_url}:5432/${created.database_name}?sslmode=verify-full`,
87 );
88 return {
89 id: created.id,
90 connectionUrl: Redacted.make(connectionUrl),
91 };
92 }),
93 use,
94 (role) =>
95 ps
96 .deleteRole({
97 organization: target.organization,
98 database: target.database,
99 branch: target.branch,
100 id: role.id,
101 successor: "postgres",
102 })
103 .pipe(
104 // Already-deleted roles are a success: nothing to clean up.
105 Effect.catchTag("NotFound", () => Effect.void),
106 Effect.retry({
107 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(5)]),
108 }),
109 // Migrations succeeded; don't fail the parent over a release-step
110 // hiccup. The role's TTL bounds the orphan window; log loudly so
111 // an operator can clean it up manually if needed.
112 Effect.catch((cause: unknown) =>
113 Effect.logWarning(
114 `Failed to delete temporary Planetscale migration role after retries. ` +
115 `It will expire via TTL (~${MIGRATION_ROLE_TTL_SECONDS}s). ` +
116 `organization=${target.organization} database=${target.database} ` +
117 `branch=${target.branch} id=${role.id}`,
118 cause,
119 ),
120 ),
121 ),
122 );