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

main
ts 511 lines 17.5 KB
Raw
1 import * as alloydb from "@distilled.cloud/gcp/alloydb_v1";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { ALCHEMY_LABEL_PREFIX } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const DEFAULT_USER_TYPE = "ALLOYDB_BUILT_IN";
15 const MAX_NAME_LENGTH = 63;
16
17 const SYSTEM_USERS = new Set(["postgres"]);
18
19 export type ClustersUserProps = {
20 /**
21 * Parent cluster id or full resource name
22 * (`projects/{project}/locations/{location}/clusters/{cluster}`).
23 * Immutable — changing it replaces the user.
24 */
25 cluster: string;
26 /**
27 * Region of the parent cluster (`us-central1`, …). Ignored when
28 * `cluster` is a full resource name. Immutable — changing it replaces
29 * the user. `US-CENTRAL1` is accepted and normalized to
30 * `us-central1`.
31 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
32 */
33 location?: string;
34 /**
35 * Database user id (the `{user}` segment of
36 * `.../clusters/{cluster}/users/{user}`). If omitted, a unique
37 * PostgreSQL identifier is generated. For IAM users this is the
38 * principal email. Immutable — changing it replaces the user.
39 */
40 userId?: string;
41 /**
42 * User type. `ALLOYDB_BUILT_IN` requires `password`.
43 * `ALLOYDB_IAM_USER` uses IAM authentication. Immutable — changing
44 * it replaces the user.
45 * @default "ALLOYDB_BUILT_IN"
46 */
47 userType?: alloydb.UserUserTypeEnum | (string & {});
48 /**
49 * Password for `ALLOYDB_BUILT_IN` users. Write-only — never returned
50 * by the API. Updating this value rotates the password.
51 */
52 password?: string;
53 /**
54 * PostgreSQL roles to grant (`alloydbsuperuser`, `pg_monitor`, …).
55 */
56 databaseRoles?: string[];
57 /**
58 * Keep roles the user already has that are not listed in
59 * `databaseRoles`. Create-only.
60 */
61 keepExtraRoles?: boolean;
62 };
63
64 export type ClustersUser = Resource<
65 "GCP.AlloyDB.ClustersUser",
66 ClustersUserProps,
67 {
68 /** Full resource name `projects/{project}/locations/{location}/clusters/{cluster}/users/{user}`. */
69 name: string;
70 /** Database user id (last path segment). */
71 userId: string;
72 /** Parent cluster id. */
73 clusterId: string;
74 /** Parent cluster resource name. */
75 clusterName: string;
76 /** Project id. */
77 project: string;
78 /** Region id (`us-central1`, …). */
79 location: string;
80 /** User type (`ALLOYDB_BUILT_IN`, `ALLOYDB_IAM_USER`). */
81 userType: string;
82 /** Granted database roles. */
83 databaseRoles: string[];
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A database user on an AlloyDB cluster.
91 *
92 * AlloyDB users have no labels field. `list` enumerates non-`postgres`
93 * users on alchemy-labeled clusters so `pnpm nuke:gcp` can find leaked
94 * rows without dropping the built-in superuser.
95 *
96 * Changing `cluster`, `location`, `userId`, or `userType` replaces the
97 * user. `password` and `databaseRoles` update in place. Creating a
98 * built-in user requires a READY primary instance.
99 *
100 * ### Creating a User
101 * **Example:** Built-in user on a cluster
102 * ```typescript
103 * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", {
104 * pscConfig: { pscEnabled: true },
105 * initialUser: { user: "postgres", password: "change-me" },
106 * });
107 * const primary = yield* GCP.AlloyDB.Instance("Primary", {
108 * cluster: cluster.name,
109 * });
110 * const appUser = yield* GCP.AlloyDB.ClustersUser("AppUser", {
111 * cluster: primary.clusterName,
112 * password: "change-me-too",
113 * databaseRoles: ["alloydbsuperuser"],
114 * });
115 * ```
116 *
117 * **Example:** Explicit id and IAM user
118 * ```typescript
119 * const iamUser = yield* GCP.AlloyDB.ClustersUser("Analyst", {
120 * cluster: cluster.name,
121 * userId: "analyst@example.com",
122 * userType: "ALLOYDB_IAM_USER",
123 * databaseRoles: ["pg_read_all_data"],
124 * });
125 * ```
126 *
127 * @resource
128 * @category AlloyDB
129 */
130 export const ClustersUser = Resource<ClustersUser>("GCP.AlloyDB.ClustersUser");
131
132 export class ClustersUserNotResolved extends Data.TaggedError(
133 "GCP.AlloyDB.ClustersUserNotResolved",
134 )<{
135 resourceName: string;
136 }> {}
137
138 export class ClustersUserClusterMissing extends Data.TaggedError(
139 "GCP.AlloyDB.ClustersUserClusterMissing",
140 )<{
141 message: string;
142 }> {}
143
144 export class ClustersUserStillExists extends Data.TaggedError(
145 "GCP.AlloyDB.ClustersUserStillExists",
146 )<{
147 resourceName: string;
148 }> {}
149
150 const lastSegment = (value: string | undefined) => {
151 if (value === undefined || value.length === 0) return "";
152 const trimmed = value.replace(/\/+$/, "");
153 const parts = trimmed.split("/");
154 return parts[parts.length - 1] || trimmed;
155 };
156
157 const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
158
159 const normalizeUserType = (type: string | undefined) => {
160 const value = (type ?? DEFAULT_USER_TYPE).toUpperCase();
161 return value === "USER_TYPE_UNSPECIFIED" ? DEFAULT_USER_TYPE : value;
162 };
163
164 const isIamType = (type: string | undefined) => normalizeUserType(type) === "ALLOYDB_IAM_USER";
165
166 const pgIdentifier = (name: string): string => {
167 let next = name
168 .toLowerCase()
169 .replace(/[^a-z0-9_]/g, "_")
170 .replace(/_+/g, "_")
171 .replace(/^_+|_+$/g, "");
172 if (!/^[a-z]/.test(next)) next = `u${next}`;
173 next = next.slice(0, MAX_NAME_LENGTH).replace(/_+$/g, "");
174 return next.length > 0 ? next : "dbuser";
175 };
176
177 const resourceName = (project: string, location: string, clusterId: string, userId: string) =>
178 `projects/${project}/locations/${location}/clusters/${clusterId}/users/${userId}`;
179
180 const clusterNameOf = (project: string, location: string, clusterId: string) =>
181 `projects/${project}/locations/${location}/clusters/${clusterId}`;
182
183 const parseName = (name: string) => {
184 const parts = name.split("/").filter((part) => part.length > 0);
185 const usersAt = parts.lastIndexOf("users");
186 const clustersAt = parts.lastIndexOf("clusters");
187 const locationsAt = parts.lastIndexOf("locations");
188 const projectsAt = parts.lastIndexOf("projects");
189 return {
190 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
191 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
192 clusterId: clustersAt >= 0 && parts[clustersAt + 1] ? parts[clustersAt + 1]! : "",
193 userId: usersAt >= 0 && parts[usersAt + 1] ? parts[usersAt + 1]! : lastSegment(name),
194 };
195 };
196
197 const parseClusterRef = (cluster: string, fallbackProject: string, fallbackLocation: string) => {
198 const trimmed = cluster.trim();
199 if (trimmed.length === 0) {
200 return {
201 project: fallbackProject,
202 location: normalizeLocation(fallbackLocation),
203 clusterId: "",
204 };
205 }
206 if (trimmed.includes("/clusters/") || trimmed.includes("projects/")) {
207 const parsed = parseName(trimmed.includes("/users/") ? trimmed : `${trimmed}/users/_`);
208 return {
209 project: parsed.project || fallbackProject,
210 location: normalizeLocation(parsed.location || fallbackLocation),
211 clusterId: parsed.clusterId === "_" ? "" : parsed.clusterId,
212 };
213 }
214 return {
215 project: fallbackProject,
216 location: normalizeLocation(fallbackLocation),
217 clusterId: lastSegment(trimmed),
218 };
219 };
220
221 const toId = (
222 id: string,
223 userId: string | undefined,
224 existing: string | undefined,
225 userType: string,
226 ) =>
227 Effect.gen(function* () {
228 if (userId !== undefined) return userId;
229 if (existing !== undefined) return existing;
230 const generated = yield* createPhysicalName({
231 id,
232 maxLength: MAX_NAME_LENGTH,
233 lowercase: true,
234 delimiter: isIamType(userType) ? "-" : "_",
235 });
236 return isIamType(userType) ? generated : pgIdentifier(generated);
237 });
238
239 const rolesKey = (roles: string[] | undefined) =>
240 JSON.stringify([...(roles ?? [])].map((role) => role.toLowerCase()).sort());
241
242 const toRoles = (roles: string[] | undefined): string[] =>
243 (roles ?? []).filter((role) => role.length > 0);
244
245 const hasAlchemyClusterLabels = (labels: Record<string, string | undefined> | null | undefined) =>
246 Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
247
248 const isManagedUser = (user: alloydb.User) => {
249 const name = lastSegment(user.name).toLowerCase();
250 if (name.length === 0) return false;
251 if (SYSTEM_USERS.has(name)) return false;
252 return true;
253 };
254
255 const isPlaceholder = (user: alloydb.User) => {
256 const name = user.name ?? "";
257 return name.endsWith("/users/-") || name.endsWith("/users/");
258 };
259
260 const toAttrs = (user: alloydb.User, project: string) => {
261 const name = user.name ?? "";
262 const parsed = parseName(name);
263 const resolvedProject = parsed.project || project;
264 return {
265 name,
266 userId: parsed.userId,
267 clusterId: parsed.clusterId,
268 clusterName: clusterNameOf(resolvedProject, parsed.location, parsed.clusterId),
269 project: resolvedProject,
270 location: parsed.location,
271 userType: normalizeUserType(user.userType),
272 databaseRoles: toRoles(user.databaseRoles),
273 };
274 };
275
276 const getByName = (name: string) =>
277 alloydb
278 .getProjectsLocationsClustersUsers({ name })
279 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
280
281 const waitUntilExists = (name: string) =>
282 getByName(name).pipe(
283 Effect.flatMap((user) =>
284 user
285 ? Effect.succeed(user)
286 : Effect.fail(new ClustersUserNotResolved({ resourceName: name })),
287 ),
288 Effect.retry({
289 while: (error) => error._tag === "GCP.AlloyDB.ClustersUserNotResolved",
290 times: 8,
291 schedule: Schedule.spaced("1 second"),
292 }),
293 );
294
295 const waitUntilGone = (name: string) =>
296 getByName(name).pipe(
297 Effect.flatMap((user) =>
298 user === undefined
299 ? Effect.void
300 : Effect.fail(new ClustersUserStillExists({ resourceName: name })),
301 ),
302 Effect.retry({
303 while: (error) => error._tag === "GCP.AlloyDB.ClustersUserStillExists",
304 times: 10,
305 schedule: Schedule.spaced("1 second"),
306 }),
307 );
308
309 const toBody = (
310 news: ClustersUserProps,
311 userType: string,
312 options?: { includePassword?: boolean; includeKeepExtraRoles?: boolean },
313 ): alloydb.User => {
314 const body: alloydb.User = {
315 userType,
316 };
317 if (news.databaseRoles !== undefined) {
318 body.databaseRoles = news.databaseRoles;
319 }
320 if (options?.includePassword !== false && news.password !== undefined && !isIamType(userType)) {
321 body.password = news.password;
322 }
323 if (options?.includeKeepExtraRoles === true && news.keepExtraRoles !== undefined) {
324 body.keepExtraRoles = news.keepExtraRoles;
325 }
326 return body;
327 };
328
329 export const ClustersUserProvider = () =>
330 Provider.succeed(ClustersUser, {
331 stables: ["name", "userId", "clusterId", "clusterName", "project", "location"],
332
333 diff: Effect.fn(function* ({ news, olds, output }) {
334 if (!isResolved(news)) return undefined;
335 const env = yield* GcpEnvironment.current;
336
337 const previousId = olds?.userId ?? output?.userId;
338 const nextId = news.userId ?? previousId;
339 const previousCluster = lastSegment(olds?.cluster ?? output?.clusterId);
340 const nextCluster = lastSegment(news.cluster ?? previousCluster);
341 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
342 const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);
343 const previousType = normalizeUserType(olds?.userType ?? output?.userType);
344 const nextType = normalizeUserType(news.userType ?? output?.userType);
345
346 const replace =
347 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
348 (previousCluster.length > 0 && nextCluster.length > 0 && previousCluster !== nextCluster) ||
349 previousLocation !== nextLocation ||
350 previousType !== nextType;
351
352 if (!replace) return undefined;
353 return {
354 action: "replace" as const,
355 deleteFirst:
356 previousLocation === nextLocation &&
357 previousCluster === nextCluster &&
358 previousId !== undefined &&
359 nextId === previousId,
360 };
361 }),
362
363 read: Effect.fn(function* ({ id, olds, output }) {
364 const env = yield* GcpEnvironment.current;
365 if (output?.name) {
366 const existing = yield* getByName(output.name);
367 if (existing === undefined) return undefined;
368 return toAttrs(existing, env.project);
369 }
370 const userType = normalizeUserType(olds?.userType ?? output?.userType);
371 const userId = yield* toId(id, olds?.userId, output?.userId, userType);
372 const ref = parseClusterRef(
373 olds?.cluster ?? output?.clusterName ?? output?.clusterId ?? "",
374 env.project,
375 olds?.location ?? output?.location ?? env.region,
376 );
377 if (ref.clusterId.length === 0) return undefined;
378 const name = resourceName(ref.project, ref.location, ref.clusterId, userId);
379 const existing = yield* getByName(name);
380 if (existing === undefined) return undefined;
381 return toAttrs(existing, env.project);
382 }),
383
384 list: () =>
385 Effect.gen(function* () {
386 const env = yield* GcpEnvironment.current;
387 const clusters = yield* alloydb.listProjectsLocationsClusters
388 .pages({
389 parent: `projects/${env.project}/locations/-`,
390 pageSize: 1000,
391 })
392 .pipe(
393 Stream.flatMap((page) => Stream.fromIterable(page.clusters ?? [])),
394 Stream.filter(
395 (cluster) =>
396 (cluster.name ?? "").length > 0 && hasAlchemyClusterLabels(cluster.labels),
397 ),
398 Stream.runCollect,
399 Effect.map((chunk) => Array.from(chunk)),
400 Effect.catchTag("NotFound", () => Effect.succeed([])),
401 );
402
403 const pages = yield* Effect.forEach(
404 clusters,
405 (cluster) => {
406 const parent = cluster.name;
407 if (parent === undefined || parent.length === 0) {
408 return Effect.succeed([] as ClustersUser["Attributes"][]);
409 }
410 return alloydb.listProjectsLocationsClustersUsers
411 .pages({
412 parent,
413 pageSize: 1000,
414 })
415 .pipe(
416 Stream.flatMap((page) => Stream.fromIterable(page.users ?? [])),
417 Stream.filter((user) => !isPlaceholder(user) && isManagedUser(user)),
418 Stream.map((user) => toAttrs(user, env.project)),
419 Stream.runCollect,
420 Effect.map((chunk) => Array.from(chunk)),
421 Effect.catchTag("NotFound", () => Effect.succeed([])),
422 );
423 },
424 { concurrency: 4 },
425 );
426 return pages.flat();
427 }),
428
429 reconcile: Effect.fn(function* ({ id, news, output, olds }) {
430 const env = yield* GcpEnvironment.current;
431 const userType = normalizeUserType(news.userType);
432 const userId = yield* toId(id, news.userId, output?.userId, userType);
433 const ref = parseClusterRef(
434 news.cluster,
435 env.project,
436 news.location ?? output?.location ?? env.region,
437 );
438 if (ref.clusterId.length === 0) {
439 return yield* new ClustersUserClusterMissing({
440 message: "GCP.AlloyDB.ClustersUser requires `cluster` (cluster id or full resource name)",
441 });
442 }
443 const name = resourceName(ref.project, ref.location, ref.clusterId, userId);
444 const parent = clusterNameOf(ref.project, ref.location, ref.clusterId);
445
446 let current = yield* getByName(output?.name ?? name);
447
448 if (current === undefined) {
449 const created = yield* alloydb
450 .createProjectsLocationsClustersUsers({
451 parent,
452 userId,
453 body: toBody(news, userType, {
454 includePassword: true,
455 includeKeepExtraRoles: true,
456 }),
457 })
458 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
459 current = created !== undefined ? created : yield* waitUntilExists(name);
460 }
461
462 if (current === undefined) {
463 return yield* new ClustersUserNotResolved({ resourceName: name });
464 }
465
466 const passwordChanged =
467 news.password !== undefined &&
468 !isIamType(userType) &&
469 (olds !== undefined ? news.password !== olds.password : output !== undefined);
470 const rolesChanged =
471 news.databaseRoles !== undefined &&
472 rolesKey(news.databaseRoles) !== rolesKey(current.databaseRoles);
473
474 if (passwordChanged || rolesChanged) {
475 const updateMask = [
476 passwordChanged ? "password" : undefined,
477 rolesChanged ? "databaseRoles" : undefined,
478 ].filter((field): field is string => field !== undefined);
479
480 current = yield* alloydb
481 .patchProjectsLocationsClustersUsers({
482 name,
483 updateMask: updateMask.join(","),
484 body: toBody(news, userType, {
485 includePassword: passwordChanged,
486 }),
487 })
488 .pipe(
489 Effect.retry({
490 while: (error) => error._tag === "Conflict",
491 times: 8,
492 schedule: Schedule.spaced("2 seconds"),
493 }),
494 );
495 }
496
497 return toAttrs(current, env.project);
498 }),
499
500 delete: Effect.fn(function* ({ output }) {
501 yield* alloydb.deleteProjectsLocationsClustersUsers({ name: output.name }).pipe(
502 Effect.catchTag("NotFound", () => Effect.void),
503 Effect.retry({
504 while: (error) => error._tag === "Conflict",
505 times: 8,
506 schedule: Schedule.spaced("2 seconds"),
507 }),
508 );
509 yield* waitUntilGone(output.name);
510 }),
511 });