@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, 06:00 UTC

main
ts 224 lines 7.96 KB
Raw
1 import { isResolved } from "alchemy/Diff";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Path from "effect/Path";
6 import * as Redacted from "effect/Redacted";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9 import {
10 isTransientDbError,
11 type MigrateResult,
12 type MigrateShowResult,
13 readMigrationPackages,
14 resolveGraphHead,
15 runPrismaCli,
16 } from "./internal.ts";
17
18 export type MigrateProps = {
19 /**
20 * Postgres connection string of the database to migrate. Accepts the
21 * redacted connection outputs produced by database resources (e.g.
22 * `branch.origin.connectionString`, `database.directConnectionString`).
23 */
24 url: Redacted.Redacted<string> | string;
25 /**
26 * The {@link Contract} this database tracks. Passing the contract's output
27 * both orders the deploy (plan migrations before applying them) and drives
28 * the diff: the database is up to date exactly when its marker hash equals
29 * `contract.contractHash`.
30 */
31 contract: {
32 /** The emitted contract's storage hash (see {@link Contract}). */
33 contractHash: string;
34 /** Path to `prisma.config.ts`, relative to the current working directory. */
35 config: string;
36 /** Migration graph directory, relative to the current working directory. */
37 migrationsDir: string;
38 };
39 /**
40 * Path to the project's `prisma.config.ts`, relative to the current
41 * working directory. Defaults to the config the {@link Contract} was
42 * emitted from.
43 *
44 * @default contract.config
45 */
46 config?: string;
47 /**
48 * Target contract reference (hash, prefix, ref name, or migration dir
49 * name) to migrate to instead of the graph head. Useful for pinning an
50 * environment to a signed-off contract.
51 */
52 to?: string;
53 };
54
55 export type Migrate = Resource<
56 "Prisma.Migrate",
57 MigrateProps,
58 {
59 /**
60 * The database marker's contract hash after the last apply — the
61 * database's current contract identity, equal to the target contract's
62 * `contractHash` when converged.
63 */
64 markerHash: string;
65 },
66 never,
67 Providers
68 >;
69
70 /**
71 * Applies pending Prisma migration packages to a Postgres database
72 * during `alchemy deploy` — the deploy-graph equivalent of running
73 * `prisma db migrate --db $DATABASE_URL` by hand.
74 *
75 * The apply is idempotent: Prisma records the applied contract in the
76 * database's `prisma_contract.marker` table and only walks the pending part
77 * of the migration graph, so re-deploys are no-ops and a database
78 * provisioned in the same deploy is bootstrapped from empty. Fresh databases
79 * that are still coming up are retried briefly (bounded) before failing.
80 *
81 * Destroying the resource never touches the database — dropping tables is
82 * not the IaC engine's call to make.
83 *
84 * ### Migrating a database on deploy
85 * **Example:** Neon branch
86 * ```typescript
87 * const contract = yield* Prisma.Contract("contract");
88 * const project = yield* Neon.Project("db");
89 * const branch = yield* Neon.Branch("main", { project });
90 *
91 * yield* Prisma.Migrate("migrate", {
92 * url: branch.origin.connectionString,
93 * contract,
94 * });
95 * ```
96 *
97 * **Example:** Prisma Postgres
98 * ```typescript
99 * const contract = yield* Prisma.Contract("contract");
100 * const database = yield* Prisma.Database("db", { project });
101 *
102 * yield* Prisma.Migrate("migrate", {
103 * url: database.directConnectionString,
104 * contract,
105 * });
106 * ```
107 *
108 * **Example:** Pinning an environment to a contract ref
109 * ```typescript
110 * yield* Prisma.Migrate("migrate", {
111 * url: branch.origin.connectionString,
112 * contract,
113 * to: "production",
114 * });
115 * ```
116 *
117 * @resource
118 * @category ORM
119 */
120 export const Migrate = Resource<Migrate>("Prisma.Migrate");
121
122 const urlValue = (url: Redacted.Redacted<string> | string): string =>
123 Redacted.isRedacted(url) ? Redacted.value(url) : url;
124
125 export const MigrateProvider = () =>
126 Provider.effect(
127 Migrate,
128 Effect.gen(function* () {
129 const path = yield* Path.Path;
130
131 const resolveConfig = (p: MigrateProps) =>
132 path.resolve(process.cwd(), p.config ?? p.contract.config ?? "./prisma.config.ts");
133
134 const configDir = (p: MigrateProps) => path.dirname(resolveConfig(p));
135
136 return {
137 // Non-listable: the marker row lives inside an arbitrary database
138 // reachable only through the props' connection string — there is no
139 // account-level API to enumerate migrated databases.
140 list: () => Effect.succeed([]),
141 diff: Effect.fn(function* ({ news, output }) {
142 if (!isResolved(news)) return undefined;
143 if (!output) return undefined;
144 // The database is converged when its marker matches the contract
145 // the props point at; anything else (new migration planned, marker
146 // reset, database recreated out-of-band) is an update. `reconcile`
147 // observes the real database, so update is always safe.
148 return news.contract.contractHash !== output.markerHash
149 ? { action: "update" }
150 : undefined;
151 }),
152 read: Effect.fn(function* ({ olds, output }) {
153 if (!output || !olds) return output;
154 // `db migrate --show` is a read-only preview of the pending path
155 // from the database's current marker. An empty path means the marker is
156 // at the on-disk graph head; otherwise the first pending package's
157 // `from` IS the marker ("empty" = database was never initialized).
158 const show = yield* runPrismaCli<MigrateShowResult>(
159 [
160 "db",
161 "migrate",
162 "--show",
163 "--db",
164 urlValue(olds.url),
165 "--config",
166 resolveConfig(olds),
167 ],
168 { cwd: configDir(olds) },
169 ).pipe(
170 // An unreachable database is not evidence the resource is gone —
171 // keep the last observed state rather than failing refresh.
172 Effect.catchTag("Prisma.CliError", () => Effect.undefined),
173 );
174 if (show === undefined) return output;
175 const pending = show.migrations;
176 if (pending.length === 0) {
177 const packages = yield* readMigrationPackages(
178 path.resolve(process.cwd(), olds.contract.migrationsDir),
179 );
180 const head = resolveGraphHead(packages);
181 return { markerHash: head?.to ?? output.markerHash };
182 }
183 const marker = pending[0]?.from;
184 if (marker === undefined || marker === "empty") return undefined;
185 return { markerHash: marker };
186 }),
187 reconcile: Effect.fn(function* ({ news, session }) {
188 yield* session.note(
189 `Applying Prisma migrations (target ${news.contract.contractHash.slice(0, 8)})`,
190 );
191 const result = yield* runPrismaCli<MigrateResult>(
192 [
193 "db",
194 "migrate",
195 "--db",
196 urlValue(news.url),
197 "--config",
198 resolveConfig(news),
199 ...(news.to ? ["--to", news.to] : []),
200 ],
201 { cwd: configDir(news) },
202 ).pipe(
203 // A database provisioned earlier in this deploy may still be
204 // warming up — retry connection-flavored failures briefly.
205 Effect.retry({
206 while: (error) => isTransientDbError(error),
207 schedule: Schedule.exponential("1 second"),
208 times: 5,
209 }),
210 );
211 yield* session.note(
212 result.migrationsApplied > 0
213 ? `Applied ${result.migrationsApplied} migration(s) → ${result.markerHash.slice(0, 8)}`
214 : "Database already up to date",
215 );
216 return { markerHash: result.markerHash };
217 }),
218 delete: Effect.fn(function* () {
219 // Never drop tables or unwind migrations on teardown — the
220 // database's contents outlive the stack by design.
221 }),
222 };
223 }),
224 );