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

main
ts 1,025 lines 35.4 KB
Raw
1 import * as alloydb from "@distilled.cloud/gcp/alloydb_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { 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 { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitForDeleteOperation, waitForOperation } from "./operations.ts";
22
23 const DEFAULT_CLUSTER_TYPE = "PRIMARY";
24 const DEFAULT_NETWORK = "default";
25 /** Cluster ids must match `^[a-z]([a-z0-9-]{0,53}[a-z0-9])?$`. */
26 const MAX_NAME_LENGTH = 55;
27
28 export type ClusterTimeOfDay = {
29 /** Hours of day in 24-hour format (`0`–`23`). */
30 hours?: number;
31 /** Minutes of hour (`0`–`59`). */
32 minutes?: number;
33 /** Seconds of minute (`0`–`59`). */
34 seconds?: number;
35 /** Fractional seconds, in nanoseconds. */
36 nanos?: number;
37 };
38
39 export type MaintenanceWindow = {
40 /** Preferred day of week (`MONDAY` … `SUNDAY`). */
41 day?: alloydb.MaintenanceWindowDayEnum | (string & {});
42 /** Preferred UTC start time. Maintenance starts within 1 hour. */
43 startTime?: ClusterTimeOfDay;
44 };
45
46 export type DenyMaintenancePeriod = {
47 /** Inclusive start date. */
48 startDate?: { year?: number; month?: number; day?: number };
49 /** Inclusive end date. */
50 endDate?: { year?: number; month?: number; day?: number };
51 /** UTC time of day for the window bounds. */
52 time?: ClusterTimeOfDay;
53 };
54
55 export type MaintenanceUpdatePolicy = {
56 /** Preferred windows. Currently limited to 1. */
57 maintenanceWindows?: MaintenanceWindow[];
58 /** Periods to deny maintenance. Currently limited to 1. */
59 denyMaintenancePeriods?: DenyMaintenancePeriod[];
60 };
61
62 export type NetworkConfig = {
63 /**
64 * VPC network
65 * (`projects/{project}/global/networks/{network}`). Immutable.
66 * Required unless Private Service Connect is enabled.
67 */
68 network?: string;
69 /**
70 * Allocated IP range name for private IP (e.g.
71 * `google-managed-services-default`). Immutable.
72 */
73 allocatedIpRange?: string;
74 };
75
76 export type PscConfig = {
77 /**
78 * Allow Private Service Connect endpoints. When true, a VPC network is
79 * not required. Immutable.
80 */
81 pscEnabled?: boolean;
82 };
83
84 export type EncryptionConfig = {
85 /**
86 * Customer-managed KMS key
87 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
88 * Immutable — changing it replaces the cluster.
89 */
90 kmsKeyName?: string;
91 };
92
93 export type WeeklySchedule = {
94 /** UTC start times (typically exact hours). */
95 startTimes?: ClusterTimeOfDay[];
96 /** Days of week. Empty means every day. */
97 daysOfWeek?: Array<alloydb.WeeklyScheduleDaysOfWeekItemEnum | (string & {})>;
98 };
99
100 export type AutomatedBackupPolicy = {
101 /** Whether automated backups are enabled. Defaults to true when omitted. */
102 enabled?: boolean;
103 /** Backup window duration (e.g. `"1800s"`). */
104 backupWindow?: string;
105 /** Weekly schedule. */
106 weeklySchedule?: WeeklySchedule;
107 /** Keep the most recent N backups. */
108 quantityBasedRetention?: { count?: number };
109 /** Keep backups for a duration (e.g. `"1209600s"`). */
110 timeBasedRetention?: { retentionPeriod?: string };
111 /** Backup location. Defaults to the cluster region. */
112 location?: string;
113 /** Labels applied to created backups. */
114 labels?: Record<string, string>;
115 /** CMEK for backups. Defaults to the cluster encryption config. */
116 encryptionConfig?: EncryptionConfig;
117 };
118
119 export type ContinuousBackupConfig = {
120 /** Whether continuous backup (PITR) is enabled. */
121 enabled?: boolean;
122 /** Recovery window in days. Defaults to 14. */
123 recoveryWindowDays?: number;
124 /** CMEK for continuous backups. */
125 encryptionConfig?: EncryptionConfig;
126 };
127
128 export type InitialUser = {
129 /** Database username. Defaults to `postgres` when omitted. */
130 user?: string;
131 /** Initial password. Create-only. */
132 password?: string;
133 };
134
135 export type SslConfig = {
136 /** Client-server SSL mode. */
137 sslMode?: alloydb.SslConfigSslModeEnum | (string & {});
138 /** Certificate authority source. Only `CA_SOURCE_MANAGED` is supported. */
139 caSource?: alloydb.SslConfigCaSourceEnum | (string & {});
140 };
141
142 export type DataplexConfig = {
143 /** Integrate AlloyDB PG resources with Dataplex. */
144 enabled?: boolean;
145 };
146
147 export type SecondaryConfig = {
148 /**
149 * Primary cluster name
150 * `projects/{project}/locations/{location}/clusters/{cluster}`.
151 * Required when `clusterType` is `SECONDARY`. Immutable.
152 */
153 primaryClusterName?: string;
154 };
155
156 export type ClusterProps = {
157 /**
158 * Cluster id (the `{cluster}` segment of
159 * `projects/{project}/locations/{location}/clusters/{cluster}`).
160 * If omitted, a unique name is generated from the stack, stage, and
161 * logical id. Must match `[a-z0-9-]{1,63}`. Immutable — changing it
162 * replaces the cluster.
163 */
164 clusterId?: string;
165 /**
166 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
167 * replaces the cluster. `US-CENTRAL1` is accepted and normalized to
168 * `us-central1`.
169 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
170 */
171 location?: string;
172 /**
173 * User-facing display name.
174 */
175 displayName?: string;
176 /**
177 * User labels. Alchemy ownership labels are merged in automatically.
178 */
179 labels?: Record<string, string>;
180 /**
181 * Arbitrary client annotations (distinct from labels).
182 */
183 annotations?: Record<string, string>;
184 /**
185 * Convenience alias for `networkConfig.network`. A bare network id
186 * (`default`) is expanded to
187 * `projects/{project}/global/networks/{network}`. Immutable.
188 */
189 network?: string;
190 /**
191 * Private IP network configuration. Immutable. Defaults to the project
192 * `default` network when Private Service Connect is not enabled.
193 */
194 networkConfig?: NetworkConfig;
195 /**
196 * Private Service Connect configuration. `pscEnabled` is immutable.
197 */
198 pscConfig?: PscConfig;
199 /**
200 * Customer-managed encryption. Immutable — changing it replaces the
201 * cluster.
202 */
203 encryptionConfig?: EncryptionConfig;
204 /**
205 * Database engine major version (`POSTGRES_14`, `POSTGRES_15`, …).
206 * Upgrading patches in place; downgrading replaces the cluster. If
207 * omitted at create time, AlloyDB picks a default.
208 */
209 databaseVersion?: alloydb.ClusterDatabaseVersionEnum | (string & {});
210 /**
211 * Cluster type. `SECONDARY` uses `clusters.createsecondary` and
212 * requires `secondaryConfig`. Immutable — changing it replaces the
213 * cluster.
214 * @default "PRIMARY"
215 */
216 clusterType?: alloydb.ClusterClusterTypeEnum | (string & {});
217 /**
218 * Cross-region replica config. Required for `SECONDARY` clusters.
219 * Immutable.
220 */
221 secondaryConfig?: SecondaryConfig;
222 /**
223 * Initial database user. Create-only; ignored on update.
224 */
225 initialUser?: InitialUser;
226 /**
227 * Automated backup policy. If omitted, AlloyDB applies its default
228 * (daily backups, 14-day retention).
229 */
230 automatedBackupPolicy?: AutomatedBackupPolicy;
231 /**
232 * Continuous backup (PITR) configuration.
233 */
234 continuousBackupConfig?: ContinuousBackupConfig;
235 /**
236 * Preferred maintenance windows and deny periods.
237 */
238 maintenanceUpdatePolicy?: MaintenanceUpdatePolicy;
239 /**
240 * Client-server SSL configuration.
241 */
242 sslConfig?: SslConfig;
243 /**
244 * Dataplex integration.
245 */
246 dataplexConfig?: DataplexConfig;
247 /**
248 * Subscription type (`STANDARD`, `TRIAL`).
249 */
250 subscriptionType?: alloydb.ClusterSubscriptionTypeEnum | (string & {});
251 };
252
253 export type Cluster = Resource<
254 "GCP.AlloyDB.Cluster",
255 ClusterProps,
256 {
257 /** Full resource name `projects/{project}/locations/{location}/clusters/{cluster}`. */
258 name: string;
259 /** Cluster id (last path segment). */
260 clusterId: string;
261 /** Project id. */
262 project: string;
263 /** Region id (`us-central1`, …). */
264 location: string;
265 /** User-facing display name. */
266 displayName: string | undefined;
267 /** User labels (Alchemy ownership labels stripped). */
268 labels: Record<string, string>;
269 /** Client annotations. */
270 annotations: Record<string, string>;
271 /** Serving state (`READY`, `EMPTY`, `CREATING`, …). */
272 state: string | undefined;
273 /** Cluster type (`PRIMARY`, `SECONDARY`). */
274 clusterType: string;
275 /** Database engine major version. */
276 databaseVersion: string | undefined;
277 /** VPC network, if any. */
278 network: string | undefined;
279 /** Private IP network configuration. */
280 networkConfig: NetworkConfig | undefined;
281 /** Private Service Connect configuration. */
282 pscConfig: PscConfig | undefined;
283 /** Customer-managed encryption, if any. */
284 encryptionConfig: EncryptionConfig | undefined;
285 /** Automated backup policy currently applied. */
286 automatedBackupPolicy: AutomatedBackupPolicy | undefined;
287 /** Continuous backup configuration currently applied. */
288 continuousBackupConfig: ContinuousBackupConfig | undefined;
289 /** SSL configuration currently applied. */
290 sslConfig: SslConfig | undefined;
291 /** Subscription type. */
292 subscriptionType: string | undefined;
293 /** System-generated UID. */
294 uid: string | undefined;
295 /** Whether the service is reconciling intended vs actual state. */
296 reconciling: boolean;
297 /** Secondary-cluster config, if any. */
298 secondaryConfig: SecondaryConfig | undefined;
299 /** RFC3339 creation timestamp. */
300 createTime: string | undefined;
301 /** RFC3339 last-update timestamp. */
302 updateTime: string | undefined;
303 },
304 never,
305 Providers
306 >;
307
308 /**
309 * An AlloyDB for PostgreSQL cluster (regional storage layer).
310 *
311 * Changing `clusterId`, `location`, `network` / `networkConfig`,
312 * `encryptionConfig`, `clusterType`, `secondaryConfig`, or
313 * `pscConfig.pscEnabled` replaces the cluster. A database version
314 * upgrade patches in place; a downgrade replaces.
315 *
316 * Provisioning typically takes several minutes. Delete always sends
317 * `force=true` so child instances do not block teardown.
318 *
319 * ### Creating a Cluster
320 * **Example:** Generated name with Private Service Connect
321 * ```typescript
322 * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", {
323 * location: "us-central1",
324 * pscConfig: { pscEnabled: true },
325 * initialUser: { user: "postgres", password: "change-me" },
326 * automatedBackupPolicy: { enabled: false },
327 * continuousBackupConfig: { enabled: false },
328 * });
329 * ```
330 *
331 * **Example:** Explicit id, default VPC, and labels
332 * ```typescript
333 * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", {
334 * clusterId: "app-db",
335 * location: "us-central1",
336 * network: "default",
337 * displayName: "app-db",
338 * labels: { env: "prod" },
339 * initialUser: { user: "postgres", password: "change-me" },
340 * });
341 * ```
342 *
343 * ### Backups
344 * **Example:** Disable automated and continuous backups
345 * ```typescript
346 * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", {
347 * pscConfig: { pscEnabled: true },
348 * automatedBackupPolicy: { enabled: false },
349 * continuousBackupConfig: { enabled: false },
350 * });
351 * ```
352 *
353 * @resource
354 * @category AlloyDB
355 */
356 export const Cluster = Resource<Cluster>("GCP.AlloyDB.Cluster");
357
358 export class ClusterNotResolved extends Data.TaggedError("GCP.AlloyDB.ClusterNotResolved")<{
359 resourceName: string;
360 }> {}
361
362 export class ClusterNotReady extends Data.TaggedError("GCP.AlloyDB.ClusterNotReady")<{
363 resourceName: string;
364 state: string;
365 }> {}
366
367 export class ClusterFailed extends Data.TaggedError("GCP.AlloyDB.ClusterFailed")<{
368 resourceName: string;
369 state: string;
370 }> {}
371
372 export class ClusterStillExists extends Data.TaggedError("GCP.AlloyDB.ClusterStillExists")<{
373 resourceName: string;
374 }> {}
375
376 const lastSegment = (value: string | undefined) => {
377 if (value === undefined || value.length === 0) return "";
378 const trimmed = value.replace(/\/+$/, "");
379 const parts = trimmed.split("/");
380 return parts[parts.length - 1] || trimmed;
381 };
382
383 const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
384
385 const normalizeClusterType = (type: string | undefined) => {
386 const value = (type ?? DEFAULT_CLUSTER_TYPE).toUpperCase();
387 return value === "CLUSTER_TYPE_UNSPECIFIED" ? DEFAULT_CLUSTER_TYPE : value;
388 };
389
390 const normalizeVersion = (version: string | undefined) => {
391 if (version === undefined || version.length === 0) return undefined;
392 const value = version.toUpperCase();
393 return value === "DATABASE_VERSION_UNSPECIFIED" ? undefined : value;
394 };
395
396 const parsePostgresVersion = (version: string | undefined) => {
397 const normalized = normalizeVersion(version);
398 if (normalized === undefined) return undefined;
399 const match = normalized.match(/^POSTGRES_(\d+)$/);
400 return match ? Number(match[1]) : undefined;
401 };
402
403 const versionDecreasing = (previous: string | undefined, next: string) => {
404 const oldN = parsePostgresVersion(previous);
405 const newN = parsePostgresVersion(next);
406 if (oldN === undefined || newN === undefined) return previous !== next;
407 return newN < oldN;
408 };
409
410 const rfc1035 = (name: string): string => {
411 let next = name
412 .toLowerCase()
413 .replace(/[^a-z0-9-]/g, "-")
414 .replace(/-+/g, "-")
415 .replace(/^-+|-+$/g, "");
416 if (!/^[a-z]/.test(next)) next = `c${next}`;
417 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
418 if (next.length === 0) return "cluster";
419 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
420 return next.slice(0, MAX_NAME_LENGTH);
421 };
422
423 const resourceName = (project: string, location: string, clusterId: string) =>
424 `projects/${project}/locations/${location}/clusters/${clusterId}`;
425
426 const parseName = (name: string) => {
427 const parts = name.split("/").filter((part) => part.length > 0);
428 const clustersAt = parts.lastIndexOf("clusters");
429 const locationsAt = parts.lastIndexOf("locations");
430 const projectsAt = parts.lastIndexOf("projects");
431 return {
432 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
433 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
434 clusterId:
435 clustersAt >= 0 && parts[clustersAt + 1] ? parts[clustersAt + 1]! : lastSegment(name),
436 };
437 };
438
439 const userLabels = (
440 labels: Record<string, string | undefined> | null | undefined,
441 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
442
443 const stringMapOf = (
444 map: Record<string, string | undefined> | null | undefined,
445 ): Record<string, string> =>
446 Object.fromEntries(
447 Object.entries(map ?? {}).filter(
448 (entry): entry is [string, string] => entry[1] !== undefined && entry[1].length > 0,
449 ),
450 );
451
452 const expandNetwork = (project: string, network: string | undefined) => {
453 if (network === undefined || network.length === 0) return undefined;
454 if (network.includes("/")) return network;
455 return `projects/${project}/global/networks/${network}`;
456 };
457
458 const networkIdOf = (network: string | undefined) => lastSegment(network);
459
460 const toId = (id: string, clusterId: string | undefined, existing?: string) =>
461 Effect.gen(function* () {
462 return (
463 clusterId ??
464 existing ??
465 rfc1035(
466 yield* createPhysicalName({
467 id,
468 maxLength: MAX_NAME_LENGTH,
469 lowercase: true,
470 }),
471 )
472 );
473 });
474
475 const canonical = (value: unknown): unknown => {
476 if (value === undefined || value === null) return undefined;
477 if (typeof value === "boolean" || typeof value === "number") return value;
478 if (typeof value === "string") {
479 return value.length === 0 ? undefined : value;
480 }
481 if (Array.isArray(value)) {
482 const items = value.map(canonical).filter((item) => item !== undefined);
483 return items.length === 0 ? undefined : items;
484 }
485 if (typeof value === "object") {
486 const entries = Object.entries(value as Record<string, unknown>)
487 .map(([key, item]) => [key, canonical(item)] as const)
488 .filter(([, item]) => item !== undefined)
489 .sort(([left], [right]) => left.localeCompare(right));
490 if (entries.length === 0) return undefined;
491 return Object.fromEntries(entries);
492 }
493 return undefined;
494 };
495
496 const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
497
498 const specifiedEquals = (desired: unknown, observed: unknown): boolean => {
499 if (desired === undefined) return true;
500 if (
501 typeof desired === "boolean" ||
502 typeof desired === "number" ||
503 typeof desired === "string" ||
504 Array.isArray(desired)
505 ) {
506 return fingerprint(desired) === fingerprint(observed);
507 }
508 if (desired !== null && typeof desired === "object") {
509 const obs =
510 observed !== null && typeof observed === "object"
511 ? (observed as Record<string, unknown>)
512 : {};
513 return Object.entries(desired as Record<string, unknown>).every(([key, value]) =>
514 specifiedEquals(value, obs[key]),
515 );
516 }
517 return fingerprint(desired) === fingerprint(observed);
518 };
519
520 const toNetworkConfig = (
521 config: alloydb.NetworkConfig | NetworkConfig | undefined,
522 fallbackNetwork?: string,
523 ): NetworkConfig | undefined => {
524 const network = config?.network ?? fallbackNetwork;
525 const allocatedIpRange = config?.allocatedIpRange;
526 if (
527 (network === undefined || network.length === 0) &&
528 (allocatedIpRange === undefined || allocatedIpRange.length === 0)
529 ) {
530 return undefined;
531 }
532 return {
533 network: network || undefined,
534 allocatedIpRange: allocatedIpRange || undefined,
535 };
536 };
537
538 const toPscConfig = (config: alloydb.PscConfig | PscConfig | undefined): PscConfig | undefined => {
539 if (config === undefined) return undefined;
540 return { pscEnabled: config.pscEnabled === true };
541 };
542
543 const toEncryptionConfig = (
544 config: alloydb.EncryptionConfig | EncryptionConfig | undefined,
545 ): EncryptionConfig | undefined => {
546 const kmsKeyName = config?.kmsKeyName;
547 if (kmsKeyName === undefined || kmsKeyName.length === 0) return undefined;
548 return { kmsKeyName };
549 };
550
551 const toSslConfig = (config: alloydb.SslConfig | SslConfig | undefined): SslConfig | undefined => {
552 if (config === undefined) return undefined;
553 return {
554 sslMode: config.sslMode,
555 caSource: config.caSource,
556 };
557 };
558
559 const toSecondaryConfig = (
560 config: alloydb.SecondaryConfig | SecondaryConfig | undefined,
561 ): SecondaryConfig | undefined => {
562 const primaryClusterName = config?.primaryClusterName;
563 if (primaryClusterName === undefined || primaryClusterName.length === 0) {
564 return undefined;
565 }
566 return { primaryClusterName };
567 };
568
569 const toAutomatedBackupPolicy = (
570 policy: alloydb.AutomatedBackupPolicy | AutomatedBackupPolicy | undefined,
571 ): AutomatedBackupPolicy | undefined => {
572 if (policy === undefined) return undefined;
573 return canonical(policy) as AutomatedBackupPolicy | undefined;
574 };
575
576 const toContinuousBackupConfig = (
577 config: alloydb.ContinuousBackupConfig | ContinuousBackupConfig | undefined,
578 ): ContinuousBackupConfig | undefined => {
579 if (config === undefined) return undefined;
580 return canonical(config) as ContinuousBackupConfig | undefined;
581 };
582
583 const isAvailable = (state: string | undefined) => {
584 const value = (state ?? "").toUpperCase();
585 return value === "READY" || value === "EMPTY";
586 };
587
588 const isFailed = (state: string | undefined) => (state ?? "").toUpperCase() === "FAILED";
589
590 const toAttrs = (cluster: alloydb.Cluster, project: string) => {
591 const name = cluster.name ?? "";
592 const parsed = parseName(name);
593 const networkConfig = toNetworkConfig(cluster.networkConfig, cluster.network);
594 return {
595 name,
596 clusterId: parsed.clusterId,
597 project: parsed.project || project,
598 location: parsed.location,
599 displayName: cluster.displayName,
600 labels: userLabels(cluster.labels),
601 annotations: stringMapOf(cluster.annotations),
602 state: cluster.state,
603 clusterType: normalizeClusterType(cluster.clusterType),
604 databaseVersion: cluster.databaseVersion,
605 network: networkConfig?.network ?? cluster.network,
606 networkConfig,
607 pscConfig: toPscConfig(cluster.pscConfig),
608 encryptionConfig: toEncryptionConfig(cluster.encryptionConfig),
609 automatedBackupPolicy: toAutomatedBackupPolicy(cluster.automatedBackupPolicy),
610 continuousBackupConfig: toContinuousBackupConfig(cluster.continuousBackupConfig),
611 sslConfig: toSslConfig(cluster.sslConfig),
612 subscriptionType: cluster.subscriptionType,
613 uid: cluster.uid,
614 reconciling: cluster.reconciling === true,
615 secondaryConfig: toSecondaryConfig(cluster.secondaryConfig),
616 createTime: cluster.createTime,
617 updateTime: cluster.updateTime,
618 };
619 };
620
621 const isPlaceholder = (cluster: alloydb.Cluster) => {
622 const name = cluster.name ?? "";
623 return name.endsWith("/clusters/-") || name.endsWith("/clusters/");
624 };
625
626 const getByName = (name: string) =>
627 alloydb
628 .getProjectsLocationsClusters({ name })
629 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
630
631 const waitUntilExists = (name: string) =>
632 getByName(name).pipe(
633 Effect.flatMap((cluster) =>
634 cluster
635 ? Effect.succeed(cluster)
636 : Effect.fail(new ClusterNotResolved({ resourceName: name })),
637 ),
638 Effect.retry({
639 while: (error) => error._tag === "GCP.AlloyDB.ClusterNotResolved",
640 times: 8,
641 schedule: Schedule.spaced("1 second"),
642 }),
643 );
644
645 const waitUntilReady = (name: string) =>
646 Effect.gen(function* () {
647 const cluster = yield* getByName(name);
648 if (cluster === undefined) {
649 return yield* new ClusterNotReady({ resourceName: name, state: "MISSING" });
650 }
651 if (isFailed(cluster.state)) {
652 return yield* new ClusterFailed({
653 resourceName: name,
654 state: cluster.state ?? "FAILED",
655 });
656 }
657 if (!(isAvailable(cluster.state) && cluster.reconciling !== true)) {
658 return yield* new ClusterNotReady({
659 resourceName: name,
660 state: cluster.state ?? "STATE_UNSPECIFIED",
661 });
662 }
663 return cluster;
664 }).pipe(
665 Effect.retry({
666 while: (error) => error._tag === "GCP.AlloyDB.ClusterNotReady",
667 times: 120,
668 schedule: Schedule.spaced("15 seconds"),
669 }),
670 );
671
672 const waitUntilGone = (name: string) =>
673 getByName(name).pipe(
674 Effect.flatMap((cluster) =>
675 cluster === undefined
676 ? Effect.void
677 : Effect.fail(new ClusterStillExists({ resourceName: name })),
678 ),
679 Effect.retry({
680 while: (error) => error._tag === "GCP.AlloyDB.ClusterStillExists",
681 times: 120,
682 schedule: Schedule.spaced("15 seconds"),
683 }),
684 );
685
686 const desiredNetworkConfig = (
687 news: ClusterProps,
688 project: string,
689 pscEnabled: boolean,
690 ): NetworkConfig | undefined => {
691 const network = expandNetwork(project, news.networkConfig?.network ?? news.network);
692 const allocatedIpRange = news.networkConfig?.allocatedIpRange;
693 if (pscEnabled) {
694 if (
695 (network === undefined || network.length === 0) &&
696 (allocatedIpRange === undefined || allocatedIpRange.length === 0)
697 ) {
698 return undefined;
699 }
700 return { network, allocatedIpRange };
701 }
702 return {
703 network: network ?? expandNetwork(project, DEFAULT_NETWORK),
704 allocatedIpRange,
705 };
706 };
707
708 const toCreateBody = (
709 news: ClusterProps,
710 desiredLabels: Record<string, string>,
711 clusterType: string,
712 networkConfig: NetworkConfig | undefined,
713 pscEnabled: boolean,
714 ): alloydb.Cluster => {
715 const body: alloydb.Cluster = {
716 displayName: news.displayName,
717 labels: desiredLabels,
718 clusterType,
719 };
720 if (news.annotations !== undefined) {
721 body.annotations = news.annotations;
722 }
723 if (networkConfig !== undefined) {
724 body.networkConfig = networkConfig;
725 }
726 if (news.pscConfig !== undefined || pscEnabled) {
727 body.pscConfig = { pscEnabled };
728 }
729 const encryption = toEncryptionConfig(news.encryptionConfig);
730 if (encryption !== undefined) {
731 body.encryptionConfig = encryption;
732 }
733 const version = normalizeVersion(news.databaseVersion);
734 if (version !== undefined) {
735 body.databaseVersion = version;
736 }
737 if (clusterType === "SECONDARY" && news.secondaryConfig !== undefined) {
738 body.secondaryConfig = news.secondaryConfig;
739 }
740 if (news.initialUser !== undefined) {
741 body.initialUser = news.initialUser;
742 }
743 if (news.automatedBackupPolicy !== undefined) {
744 body.automatedBackupPolicy = news.automatedBackupPolicy;
745 }
746 if (news.continuousBackupConfig !== undefined) {
747 body.continuousBackupConfig = news.continuousBackupConfig;
748 }
749 if (news.maintenanceUpdatePolicy !== undefined) {
750 body.maintenanceUpdatePolicy = news.maintenanceUpdatePolicy;
751 }
752 if (news.sslConfig !== undefined) {
753 body.sslConfig = news.sslConfig;
754 }
755 if (news.dataplexConfig !== undefined) {
756 body.dataplexConfig = news.dataplexConfig;
757 }
758 if (news.subscriptionType !== undefined) {
759 body.subscriptionType = news.subscriptionType;
760 }
761 return body;
762 };
763
764 export const ClusterProvider = () =>
765 Provider.succeed(Cluster, {
766 stables: ["name", "clusterId", "project", "location", "uid", "createTime"],
767
768 diff: Effect.fn(function* ({ news, olds, output }) {
769 if (!isResolved(news)) return undefined;
770 const env = yield* GcpEnvironment.current;
771
772 const previousId = olds?.clusterId ?? output?.clusterId;
773 const nextId = news.clusterId ?? previousId;
774 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
775 const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);
776 const previousType = normalizeClusterType(olds?.clusterType ?? output?.clusterType);
777 const nextType = normalizeClusterType(news.clusterType ?? output?.clusterType);
778 const previousNetwork = networkIdOf(
779 olds?.networkConfig?.network ??
780 olds?.network ??
781 output?.networkConfig?.network ??
782 output?.network,
783 );
784 const nextNetwork = networkIdOf(
785 news.networkConfig?.network ?? news.network ?? previousNetwork,
786 );
787 const previousRange =
788 olds?.networkConfig?.allocatedIpRange ?? output?.networkConfig?.allocatedIpRange ?? "";
789 const nextRange = news.networkConfig?.allocatedIpRange ?? previousRange;
790 const previousPsc =
791 olds?.pscConfig?.pscEnabled === true || output?.pscConfig?.pscEnabled === true;
792 const nextPsc =
793 news.pscConfig?.pscEnabled !== undefined ? news.pscConfig.pscEnabled === true : previousPsc;
794 const previousKey =
795 olds?.encryptionConfig?.kmsKeyName ?? output?.encryptionConfig?.kmsKeyName ?? "";
796 const nextKey = news.encryptionConfig?.kmsKeyName ?? previousKey;
797 const previousPrimary =
798 olds?.secondaryConfig?.primaryClusterName ??
799 output?.secondaryConfig?.primaryClusterName ??
800 "";
801 const nextPrimary = news.secondaryConfig?.primaryClusterName ?? previousPrimary;
802 const previousVersion = normalizeVersion(olds?.databaseVersion ?? output?.databaseVersion);
803 const nextVersion = normalizeVersion(news.databaseVersion);
804 const downgrade =
805 nextVersion !== undefined &&
806 previousVersion !== undefined &&
807 versionDecreasing(previousVersion, nextVersion);
808
809 const replace =
810 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
811 previousLocation !== nextLocation ||
812 previousType !== nextType ||
813 previousNetwork !== nextNetwork ||
814 previousRange !== nextRange ||
815 previousPsc !== nextPsc ||
816 previousKey !== nextKey ||
817 previousPrimary !== nextPrimary ||
818 downgrade;
819
820 if (!replace) return undefined;
821 return {
822 action: "replace" as const,
823 deleteFirst:
824 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
825 };
826 }),
827
828 read: Effect.fn(function* ({ id, olds, output }) {
829 const env = yield* GcpEnvironment.current;
830 const clusterId = yield* toId(id, olds?.clusterId, output?.clusterId);
831 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
832 const name = output?.name ?? resourceName(env.project, location, clusterId);
833 const existing = yield* getByName(name);
834 if (existing === undefined) return undefined;
835 const attrs = toAttrs(existing, env.project);
836 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
837 }),
838
839 list: () =>
840 Effect.gen(function* () {
841 const env = yield* GcpEnvironment.current;
842 return yield* alloydb.listProjectsLocationsClusters
843 .pages({
844 parent: `projects/${env.project}/locations/-`,
845 pageSize: 1000,
846 })
847 .pipe(
848 Stream.flatMap((page) => Stream.fromIterable(page.clusters ?? [])),
849 Stream.filter(
850 (cluster) =>
851 !isPlaceholder(cluster) &&
852 Object.keys(cluster.labels ?? {}).some((key) => key.startsWith("alchemy-")),
853 ),
854 Stream.map((cluster) => toAttrs(cluster, env.project)),
855 Stream.runCollect,
856 Effect.map((chunk) => Array.from(chunk)),
857 Effect.catchTag("NotFound", () => Effect.succeed([])),
858 );
859 }),
860
861 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
862 const env = yield* GcpEnvironment.current;
863 const clusterId = yield* toId(id, news.clusterId, output?.clusterId);
864 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
865 const name = resourceName(env.project, location, clusterId);
866 const clusterType = normalizeClusterType(news.clusterType);
867 const pscEnabled = news.pscConfig?.pscEnabled === true;
868 const networkConfig = desiredNetworkConfig(news, env.project, pscEnabled);
869 const desiredLabels = {
870 ...toLabels(news.labels),
871 ...(yield* createInternalLabels(id)),
872 };
873
874 let current = yield* getByName(output?.name ?? name);
875
876 if (current === undefined) {
877 const parent = `projects/${env.project}/locations/${location}`;
878 const body = toCreateBody(news, desiredLabels, clusterType, networkConfig, pscEnabled);
879 const created = yield* (
880 clusterType === "SECONDARY"
881 ? alloydb.createsecondaryProjectsLocationsClusters({
882 parent,
883 clusterId,
884 body,
885 })
886 : alloydb.createProjectsLocationsClusters({
887 parent,
888 clusterId,
889 body,
890 })
891 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
892 if (created !== undefined) {
893 yield* waitForOperation(created);
894 }
895 current = yield* waitUntilExists(name);
896 }
897
898 if (current === undefined) {
899 return yield* new ClusterNotResolved({ resourceName: name });
900 }
901
902 if (!isAvailable(current.state) || current.reconciling === true) {
903 current = yield* waitUntilReady(name);
904 }
905
906 const desiredVersion = normalizeVersion(news.databaseVersion);
907 const currentVersion = normalizeVersion(current.databaseVersion);
908 const versionChanged =
909 desiredVersion !== undefined &&
910 currentVersion !== undefined &&
911 desiredVersion !== currentVersion &&
912 !versionDecreasing(currentVersion, desiredVersion);
913
914 const observedLabels = tagRecord(current.labels);
915 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
916 const labelsChanged = upsert.length > 0 || removed.length > 0;
917 // AlloyDB has been observed to omit `displayName` from reads; when it
918 // does, compare against what was last applied instead of re-patching
919 // on every deploy.
920 const observedDisplayName = current.displayName ?? output?.displayName ?? olds?.displayName;
921 const displayNameChanged = (observedDisplayName ?? "") !== (news.displayName ?? "");
922 const annotationsChanged =
923 news.annotations !== undefined &&
924 fingerprint(stringMapOf(current.annotations)) !== fingerprint(news.annotations);
925 const backupChanged =
926 news.automatedBackupPolicy !== undefined &&
927 !specifiedEquals(news.automatedBackupPolicy, current.automatedBackupPolicy);
928 const continuousChanged =
929 news.continuousBackupConfig !== undefined &&
930 !specifiedEquals(news.continuousBackupConfig, current.continuousBackupConfig);
931 const maintenanceChanged =
932 news.maintenanceUpdatePolicy !== undefined &&
933 !specifiedEquals(news.maintenanceUpdatePolicy, current.maintenanceUpdatePolicy);
934 const sslChanged =
935 news.sslConfig !== undefined &&
936 !specifiedEquals(news.sslConfig, toSslConfig(current.sslConfig));
937 const dataplexChanged =
938 news.dataplexConfig !== undefined &&
939 !specifiedEquals(news.dataplexConfig, current.dataplexConfig);
940 const subscriptionChanged =
941 news.subscriptionType !== undefined &&
942 (current.subscriptionType ?? "") !== news.subscriptionType;
943
944 if (
945 labelsChanged ||
946 displayNameChanged ||
947 annotationsChanged ||
948 backupChanged ||
949 continuousChanged ||
950 maintenanceChanged ||
951 sslChanged ||
952 dataplexChanged ||
953 subscriptionChanged ||
954 versionChanged
955 ) {
956 const updateMask = [
957 labelsChanged ? "labels" : undefined,
958 displayNameChanged ? "displayName" : undefined,
959 annotationsChanged ? "annotations" : undefined,
960 backupChanged ? "automatedBackupPolicy" : undefined,
961 continuousChanged ? "continuousBackupConfig" : undefined,
962 maintenanceChanged ? "maintenanceUpdatePolicy" : undefined,
963 sslChanged ? "sslConfig" : undefined,
964 dataplexChanged ? "dataplexConfig" : undefined,
965 subscriptionChanged ? "subscriptionType" : undefined,
966 versionChanged ? "databaseVersion" : undefined,
967 ].filter((field): field is string => field !== undefined);
968
969 const patched = yield* alloydb
970 .patchProjectsLocationsClusters({
971 name,
972 updateMask: updateMask.join(","),
973 body: {
974 name,
975 labels: desiredLabels,
976 displayName: news.displayName,
977 annotations: news.annotations,
978 automatedBackupPolicy: news.automatedBackupPolicy,
979 continuousBackupConfig: news.continuousBackupConfig,
980 maintenanceUpdatePolicy: news.maintenanceUpdatePolicy,
981 sslConfig: news.sslConfig,
982 dataplexConfig: news.dataplexConfig,
983 subscriptionType: news.subscriptionType,
984 databaseVersion: desiredVersion,
985 },
986 })
987 .pipe(
988 Effect.retry({
989 while: (error) => error._tag === "Conflict",
990 times: 40,
991 schedule: Schedule.spaced("15 seconds"),
992 }),
993 );
994 yield* waitForOperation(patched);
995 current = yield* waitUntilReady(name);
996 }
997
998 // When the read omits `displayName`, the desired value is what is
999 // deployed: it was sent on create, patched above, or observed equal.
1000 return {
1001 ...toAttrs(current, env.project),
1002 displayName: current.displayName ?? news.displayName,
1003 };
1004 }),
1005
1006 delete: Effect.fn(function* ({ output }) {
1007 const operation = yield* alloydb
1008 .deleteProjectsLocationsClusters({
1009 name: output.name,
1010 force: true,
1011 })
1012 .pipe(
1013 Effect.catchTag("NotFound", () => Effect.undefined),
1014 Effect.retry({
1015 while: (error) => error._tag === "Conflict",
1016 times: 40,
1017 schedule: Schedule.spaced("15 seconds"),
1018 }),
1019 );
1020 if (operation !== undefined) {
1021 yield* waitForDeleteOperation(operation);
1022 }
1023 yield* waitUntilGone(output.name);
1024 }),
1025 });