@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 428 lines 14.6 KB
Raw
1 import * as planetscale from "@distilled.cloud/planetscale";
2 import { Credentials } from "@distilled.cloud/planetscale/Credentials";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Redacted from "effect/Redacted";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import type { MySQLBranch } from "./MySQLBranch.ts";
12 import type { MySQLDatabase } from "./MySQLDatabase.ts";
13 import type { MySQLOrigin } from "./MySQLOrigin.ts";
14
15 /**
16 * Properties for creating or updating a PlanetScale MySQL password.
17 *
18 * Passwords are only meant for MySQL databases. For PostgreSQL,
19 * use {@link PostgresRole} instead.
20 */
21 export interface MySQLPasswordProps {
22 /**
23 * Password name. If omitted, a unique name is generated from
24 * `${app}-${stage}-${id}`.
25 */
26 name?: string;
27
28 /**
29 * MySQL database — string name or {@link MySQLDatabase} resource.
30 */
31 database: string | MySQLDatabase;
32
33 /**
34 * Branch — string name or {@link MySQLBranch} resource.
35 * @default "main"
36 */
37 branch?: string | MySQLBranch;
38
39 /**
40 * The MySQL role granted to the password.
41 */
42 role: "reader" | "writer" | "admin" | "readwriter";
43
44 /**
45 * Whether the password is for a read replica.
46 */
47 replica?: boolean;
48
49 /**
50 * Time to live (seconds). The password is invalidated after this period.
51 */
52 ttl?: number;
53
54 /**
55 * IP CIDR ranges allowed to use this password.
56 */
57 cidrs?: string[];
58 }
59
60 /**
61 * Output attributes of a deployed PlanetScale password.
62 */
63 export interface MySQLPasswordAttributes {
64 /** Unique identifier for the password (stable). */
65 id: string;
66 /** Password name. If omitted, a unique name is generated from `${app}-${stage}-${id}`. */
67 name: string;
68 /** ISO 8601 timestamp at which the password expires. `null` if no TTL. */
69 expiresAt: string | null;
70 /** Hostname for the database connection. */
71 host: string;
72 /** Username for database authentication. */
73 username: string;
74 /** Password for database authentication (Redacted). */
75 password: Redacted.Redacted<string>;
76 /** Parsed connection components ready to feed into Cloudflare Hyperdrive. */
77 origin: MySQLOrigin;
78 /** Resolved organization slug. */
79 organization: string;
80 /** Resolved database name. */
81 database: string;
82 /** Resolved branch name. */
83 branch: string;
84 /** The role granted. */
85 role: "reader" | "writer" | "admin" | "readwriter" | (string & {});
86 /** Whether this password is for a read replica. */
87 replica: boolean | undefined;
88 /** TTL in seconds (if set). */
89 ttl: number | undefined;
90 /** IP CIDR ranges allowed to use this password. */
91 cidrs: readonly string[] | undefined;
92 }
93
94 /**
95 * A PlanetScale password for accessing a MySQL database branch.
96 *
97 * For PostgreSQL databases, use {@link PostgresRole} instead.
98 *
99 * ### Creating a Password
100 * **Example:** Reader password
101 * ```typescript
102 * const reader = yield* Planetscale.MySQLPassword("AppReader", {
103 * database: "my-db",
104 * role: "reader",
105 * });
106 * ```
107 *
108 * **Example:** Writer password with TTL
109 * ```typescript
110 * const writer = yield* Planetscale.MySQLPassword("AppWriter", {
111 * database: "my-db",
112 * role: "writer",
113 * ttl: 86400,
114 * });
115 * ```
116 *
117 * **Example:** Admin password with IP allowlist
118 * ```typescript
119 * const admin = yield* Planetscale.MySQLPassword("Admin", {
120 * database: "my-db",
121 * role: "admin",
122 * cidrs: ["203.0.113.0/24", "198.51.100.0/24"],
123 * });
124 * ```
125 */
126 export type MySQLPassword = Resource<
127 "Planetscale.MySQLPassword",
128 MySQLPasswordProps,
129 MySQLPasswordAttributes,
130 never,
131 Providers
132 >;
133
134 /** @resource */
135 export const MySQLPassword = Resource<MySQLPassword>("Planetscale.MySQLPassword");
136
137 export const MySQLPasswordProvider = () =>
138 Provider.succeed(MySQLPassword, {
139 stables: ["id"],
140 diff: Effect.fn(function* ({ olds = {}, news }) {
141 if (!isResolved(news)) return undefined;
142
143 // Replace on any immutable-in-place change; engine falls through
144 // to reconcile for everything else (which authoritatively diffs
145 // against observed cloud state).
146 if (news.role !== olds.role) return { action: "replace" } as const;
147 if (news.replica !== olds.replica) {
148 return { action: "replace" } as const;
149 }
150 if (news.ttl !== olds.ttl) return { action: "replace" } as const;
151
152 const newDb = resolveDatabaseName(news.database);
153 const oldDb = olds.database ? resolveDatabaseName(olds.database) : undefined;
154 if (oldDb && newDb !== oldDb) {
155 return { action: "replace" } as const;
156 }
157 const newBranch = resolveBranchName(news.branch);
158 const oldBranch = resolveBranchName(olds.branch);
159 if (newBranch !== oldBranch) {
160 return { action: "replace" } as const;
161 }
162 return undefined;
163 }),
164
165 read: Effect.fn(function* ({ output }) {
166 // Adoption (no cached output) is impossible: the PlanetScale API
167 // never re-issues plaintext, so even if we found a matching live
168 // password by listing+name we couldn't deliver the `password`
169 // attribute. Fall through to greenfield create in `reconcile`.
170 if (!output) return undefined;
171
172 // Refresh — verify the cached password still exists and
173 // re-emit the persisted output (with plaintext intact).
174 // If it's gone, return undefined so the engine routes to
175 // reconcile, which will surface the unrecoverable-rotation
176 // condition explicitly.
177 return yield* planetscale
178 .getPassword({
179 organization: output.organization,
180 database: output.database,
181 branch: output.branch,
182 id: output.id,
183 })
184 .pipe(
185 Effect.map((password) =>
186 buildAttributes(password, output.password, {
187 organization: output.organization,
188 database: output.database,
189 branch: output.branch,
190 }),
191 ),
192 Effect.catchTag("NotFound", () => Effect.undefined),
193 );
194 }),
195
196 reconcile: Effect.fn(function* ({ id, news, output }) {
197 const newName = yield* createPasswordName(id, news.name);
198
199 // Identifiers — stable across update (diff replaces on
200 // database/branch changes), so we can pull from `output` first
201 // and fall back to `news` for greenfield.
202 const { organization: envOrg } = yield* yield* Credentials;
203 const organization = output?.organization ?? resolveDatabaseOrg(news.database) ?? envOrg;
204 const databaseName = output?.database ?? resolveDatabaseName(news.database);
205 const branchName = output?.branch ?? resolveBranchName(news.branch);
206
207 // 1. Observe — read live state. The PlanetScale API has no
208 // "lookup by name" path (names aren't unique within a branch)
209 // so the only way to find the live password is by id. Without
210 // a cached output we cannot observe and fall straight through
211 // to ensure (greenfield create).
212 const observed = output
213 ? yield* planetscale
214 .getPassword({
215 organization,
216 database: databaseName,
217 branch: branchName,
218 id: output.id,
219 })
220 .pipe(Effect.catchTag("NotFound", () => Effect.undefined))
221 : undefined;
222
223 // 2. Ensure — create the password if it doesn't exist live.
224 // This single branch covers greenfield (no output) AND the
225 // out-of-band-deletion case (output cached but cloud lost it).
226 // The latter is structurally a rotation: the new password
227 // has a fresh id/host/username/plaintext that propagate
228 // downstream through the dependency graph. There is no path
229 // to recover the original plaintext, so recreating is the
230 // only way to converge.
231 let live: planetscale.GetPasswordOutput;
232 let plaintext: Redacted.Redacted<string>;
233 if (observed) {
234 live = observed;
235 // We re-use the cached plaintext: the API never re-issues it.
236 plaintext = output!.password;
237 } else {
238 const created = yield* planetscale.createPassword({
239 organization,
240 database: databaseName,
241 branch: branchName,
242 name: newName,
243 role: news.role,
244 replica: news.replica,
245 ttl: news.ttl,
246 cidrs: news.cidrs,
247 });
248 plaintext = created.plain_text;
249 live = created;
250 }
251
252 // 3. Sync — diff observed cloud state against desired and patch
253 // only what changed. Only `name` and `cidrs` are mutable in
254 // place; everything else triggers a replace via diff().
255 // Skip the API entirely when there's no delta.
256 const wantsRename = newName !== live.name;
257 const observedCidrs = normalizeCidrs(live.cidrs);
258 const desiredCidrs = normalizeCidrs(news.cidrs);
259 const wantsCidrs = !deepEqual(desiredCidrs, observedCidrs);
260
261 if (wantsRename || wantsCidrs) {
262 live = yield* planetscale.updatePassword({
263 organization,
264 database: databaseName,
265 branch: branchName,
266 id: live.id,
267 name: wantsRename ? newName : undefined,
268 cidrs: wantsCidrs ? news.cidrs : undefined,
269 });
270 }
271
272 // 4. Return — fresh attrs sourced from observed cloud state,
273 // re-using cached plaintext when we didn't just create.
274 return buildAttributes(live, plaintext, {
275 organization,
276 database: databaseName,
277 branch: branchName,
278 });
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 yield* planetscale
283 .deletePassword({
284 organization: output.organization,
285 database: output.database,
286 branch: output.branch,
287 id: output.id,
288 })
289 .pipe(Effect.catchTag("NotFound", () => Effect.void));
290 }),
291
292 list: Effect.fn(function* () {
293 const { organization } = yield* yield* Credentials;
294
295 const databases = yield* planetscale.listDatabases.pages({ organization }).pipe(
296 Stream.runCollect,
297 Effect.map((chunk) =>
298 Array.from(chunk).flatMap((page) => page.data.filter((db) => db.kind === "mysql")),
299 ),
300 );
301
302 const rows = yield* Effect.forEach(
303 databases,
304 (db) =>
305 planetscale.listBranches.pages({ organization, database: db.name }).pipe(
306 Stream.runCollect,
307 Effect.map((branchPages) =>
308 Array.from(branchPages).flatMap((page) =>
309 page.data.filter((branch) => branch.kind === "mysql"),
310 ),
311 ),
312 Effect.catchTag("NotFound", () =>
313 Effect.succeed([{ name: db.default_branch ?? "main" }]),
314 ),
315 Effect.flatMap((branches) =>
316 Effect.forEach(
317 branches,
318 (branch) =>
319 planetscale.listPasswords
320 .pages({
321 organization,
322 database: db.name,
323 branch: branch.name,
324 })
325 .pipe(
326 Stream.runCollect,
327 Effect.map((passwordPages): MySQLPasswordAttributes[] =>
328 Array.from(passwordPages).flatMap((page) =>
329 page.data.map((password) =>
330 buildAttributes(password, Redacted.make(""), {
331 organization,
332 database: db.name,
333 branch: branch.name,
334 }),
335 ),
336 ),
337 ),
338 Effect.catchTag("NotFound", () =>
339 Effect.succeed([] as MySQLPasswordAttributes[]),
340 ),
341 ),
342 { concurrency: 10 },
343 ).pipe(Effect.map((perBranch) => perBranch.flat())),
344 ),
345 ),
346 { concurrency: 10 },
347 );
348
349 return rows.flat();
350 }),
351 });
352
353 // At runtime, Resource references in props are resolved to their full
354 // attributes — so `news.database` (when a Database resource was passed)
355 // is `{ name: string; organization: string; ... }` rather than the
356 // statically-typed Resource (whose attributes are `Output<...>`). We
357 // cast through structural shapes here.
358 type DatabaseRef = string | { name: string; organization?: string };
359 type BranchRef = string | { name: string };
360
361 const resolveDatabaseName = (database: string | MySQLDatabase): string => {
362 const ref = database as unknown as DatabaseRef;
363 return typeof ref === "string" ? ref : ref.name;
364 };
365
366 const resolveDatabaseOrg = (database: string | MySQLDatabase): string | undefined => {
367 const ref = database as unknown as DatabaseRef;
368 return typeof ref === "string" ? undefined : ref.organization;
369 };
370
371 const resolveBranchName = (branch: string | MySQLBranch | undefined): string => {
372 const ref = branch as unknown as BranchRef | undefined;
373 return !ref ? "main" : typeof ref === "string" ? ref : ref.name;
374 };
375
376 const createPasswordName = (id: string, name: string | undefined) =>
377 Effect.gen(function* () {
378 return name ?? (yield* createPhysicalName({ id, lowercase: true, maxLength: 63 }));
379 });
380
381 // Normalize the API's nullable `cidrs` field into the `string[] | undefined`
382 // shape we persist so downstream comparisons line up regardless of the
383 // API returning `null` vs `[]` vs an actual list.
384 const normalizeCidrs = (
385 cidrs: readonly string[] | null | undefined,
386 ): readonly string[] | undefined => (cidrs == null || cidrs.length === 0 ? undefined : cidrs);
387
388 const buildAttributes = (
389 password: {
390 id: string;
391 name: string;
392 expires_at: string | null;
393 access_host_url: string;
394 username: string;
395 role: "reader" | "writer" | "admin" | "readwriter" | (string & {});
396 replica: boolean;
397 ttl_seconds: number | null;
398 cidrs: readonly string[] | null;
399 },
400 plaintext: Redacted.Redacted<string>,
401 context: {
402 organization: string;
403 database: string;
404 branch: string;
405 },
406 ): MySQLPasswordAttributes => ({
407 id: password.id,
408 name: password.name,
409 expiresAt: password.expires_at,
410 host: password.access_host_url,
411 username: password.username,
412 password: plaintext,
413 origin: {
414 scheme: "mysql",
415 host: password.access_host_url,
416 port: 3306,
417 database: context.database,
418 user: password.username,
419 password: plaintext,
420 },
421 organization: context.organization,
422 database: context.database,
423 branch: context.branch,
424 role: password.role,
425 replica: password.replica,
426 ttl: password.ttl_seconds ?? undefined,
427 cidrs: normalizeCidrs(password.cidrs),
428 });