sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ AlloyDB/ Cluster.ts

import * as alloydb from "@distilled.cloud/gcp/alloydb_v1";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { tagRecord } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { GcpEnvironment } from "../Environment.ts";
import {
  createInternalLabels,
  diffLabels,
  hasAlchemyLabels,
  stripInternalLabels,
  toLabels,
} from "../Labels.ts";
import type { Providers } from "../Providers.ts";
import { waitForDeleteOperation, waitForOperation } from "./operations.ts";

const DEFAULT_CLUSTER_TYPE = "PRIMARY";
const DEFAULT_NETWORK = "default";
/** Cluster ids must match `^[a-z]([a-z0-9-]{0,53}[a-z0-9])?

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/AlloyDB/Cluster.ts at main · sailfork/t3code-github · Sailfork
	
		
. */ const MAX_NAME_LENGTH = 55; export type ClusterTimeOfDay = { /** Hours of day in 24-hour format (`0`–`23`). */ hours?: number; /** Minutes of hour (`0`–`59`). */ minutes?: number; /** Seconds of minute (`0`–`59`). */ seconds?: number; /** Fractional seconds, in nanoseconds. */ nanos?: number; }; export type MaintenanceWindow = { /** Preferred day of week (`MONDAY` … `SUNDAY`). */ day?: alloydb.MaintenanceWindowDayEnum | (string & {}); /** Preferred UTC start time. Maintenance starts within 1 hour. */ startTime?: ClusterTimeOfDay; }; export type DenyMaintenancePeriod = { /** Inclusive start date. */ startDate?: { year?: number; month?: number; day?: number }; /** Inclusive end date. */ endDate?: { year?: number; month?: number; day?: number }; /** UTC time of day for the window bounds. */ time?: ClusterTimeOfDay; }; export type MaintenanceUpdatePolicy = { /** Preferred windows. Currently limited to 1. */ maintenanceWindows?: MaintenanceWindow[]; /** Periods to deny maintenance. Currently limited to 1. */ denyMaintenancePeriods?: DenyMaintenancePeriod[]; }; export type NetworkConfig = { /** * VPC network * (`projects/{project}/global/networks/{network}`). Immutable. * Required unless Private Service Connect is enabled. */ network?: string; /** * Allocated IP range name for private IP (e.g. * `google-managed-services-default`). Immutable. */ allocatedIpRange?: string; }; export type PscConfig = { /** * Allow Private Service Connect endpoints. When true, a VPC network is * not required. Immutable. */ pscEnabled?: boolean; }; export type EncryptionConfig = { /** * Customer-managed KMS key * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`). * Immutable — changing it replaces the cluster. */ kmsKeyName?: string; }; export type WeeklySchedule = { /** UTC start times (typically exact hours). */ startTimes?: ClusterTimeOfDay[]; /** Days of week. Empty means every day. */ daysOfWeek?: Array<alloydb.WeeklyScheduleDaysOfWeekItemEnum | (string & {})>; }; export type AutomatedBackupPolicy = { /** Whether automated backups are enabled. Defaults to true when omitted. */ enabled?: boolean; /** Backup window duration (e.g. `"1800s"`). */ backupWindow?: string; /** Weekly schedule. */ weeklySchedule?: WeeklySchedule; /** Keep the most recent N backups. */ quantityBasedRetention?: { count?: number }; /** Keep backups for a duration (e.g. `"1209600s"`). */ timeBasedRetention?: { retentionPeriod?: string }; /** Backup location. Defaults to the cluster region. */ location?: string; /** Labels applied to created backups. */ labels?: Record<string, string>; /** CMEK for backups. Defaults to the cluster encryption config. */ encryptionConfig?: EncryptionConfig; }; export type ContinuousBackupConfig = { /** Whether continuous backup (PITR) is enabled. */ enabled?: boolean; /** Recovery window in days. Defaults to 14. */ recoveryWindowDays?: number; /** CMEK for continuous backups. */ encryptionConfig?: EncryptionConfig; }; export type InitialUser = { /** Database username. Defaults to `postgres` when omitted. */ user?: string; /** Initial password. Create-only. */ password?: string; }; export type SslConfig = { /** Client-server SSL mode. */ sslMode?: alloydb.SslConfigSslModeEnum | (string & {}); /** Certificate authority source. Only `CA_SOURCE_MANAGED` is supported. */ caSource?: alloydb.SslConfigCaSourceEnum | (string & {}); }; export type DataplexConfig = { /** Integrate AlloyDB PG resources with Dataplex. */ enabled?: boolean; }; export type SecondaryConfig = { /** * Primary cluster name * `projects/{project}/locations/{location}/clusters/{cluster}`. * Required when `clusterType` is `SECONDARY`. Immutable. */ primaryClusterName?: string; }; export type ClusterProps = { /** * Cluster id (the `{cluster}` segment of * `projects/{project}/locations/{location}/clusters/{cluster}`). * If omitted, a unique name is generated from the stack, stage, and * logical id. Must match `[a-z0-9-]{1,63}`. Immutable — changing it * replaces the cluster. */ clusterId?: string; /** * Region (`us-central1`, `us-east1`, …). Immutable — changing it * replaces the cluster. `US-CENTRAL1` is accepted and normalized to * `us-central1`. * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) */ location?: string; /** * User-facing display name. */ displayName?: string; /** * User labels. Alchemy ownership labels are merged in automatically. */ labels?: Record<string, string>; /** * Arbitrary client annotations (distinct from labels). */ annotations?: Record<string, string>; /** * Convenience alias for `networkConfig.network`. A bare network id * (`default`) is expanded to * `projects/{project}/global/networks/{network}`. Immutable. */ network?: string; /** * Private IP network configuration. Immutable. Defaults to the project * `default` network when Private Service Connect is not enabled. */ networkConfig?: NetworkConfig; /** * Private Service Connect configuration. `pscEnabled` is immutable. */ pscConfig?: PscConfig; /** * Customer-managed encryption. Immutable — changing it replaces the * cluster. */ encryptionConfig?: EncryptionConfig; /** * Database engine major version (`POSTGRES_14`, `POSTGRES_15`, …). * Upgrading patches in place; downgrading replaces the cluster. If * omitted at create time, AlloyDB picks a default. */ databaseVersion?: alloydb.ClusterDatabaseVersionEnum | (string & {}); /** * Cluster type. `SECONDARY` uses `clusters.createsecondary` and * requires `secondaryConfig`. Immutable — changing it replaces the * cluster. * @default "PRIMARY" */ clusterType?: alloydb.ClusterClusterTypeEnum | (string & {}); /** * Cross-region replica config. Required for `SECONDARY` clusters. * Immutable. */ secondaryConfig?: SecondaryConfig; /** * Initial database user. Create-only; ignored on update. */ initialUser?: InitialUser; /** * Automated backup policy. If omitted, AlloyDB applies its default * (daily backups, 14-day retention). */ automatedBackupPolicy?: AutomatedBackupPolicy; /** * Continuous backup (PITR) configuration. */ continuousBackupConfig?: ContinuousBackupConfig; /** * Preferred maintenance windows and deny periods. */ maintenanceUpdatePolicy?: MaintenanceUpdatePolicy; /** * Client-server SSL configuration. */ sslConfig?: SslConfig; /** * Dataplex integration. */ dataplexConfig?: DataplexConfig; /** * Subscription type (`STANDARD`, `TRIAL`). */ subscriptionType?: alloydb.ClusterSubscriptionTypeEnum | (string & {}); }; export type Cluster = Resource< "GCP.AlloyDB.Cluster", ClusterProps, { /** Full resource name `projects/{project}/locations/{location}/clusters/{cluster}`. */ name: string; /** Cluster id (last path segment). */ clusterId: string; /** Project id. */ project: string; /** Region id (`us-central1`, …). */ location: string; /** User-facing display name. */ displayName: string | undefined; /** User labels (Alchemy ownership labels stripped). */ labels: Record<string, string>; /** Client annotations. */ annotations: Record<string, string>; /** Serving state (`READY`, `EMPTY`, `CREATING`, …). */ state: string | undefined; /** Cluster type (`PRIMARY`, `SECONDARY`). */ clusterType: string; /** Database engine major version. */ databaseVersion: string | undefined; /** VPC network, if any. */ network: string | undefined; /** Private IP network configuration. */ networkConfig: NetworkConfig | undefined; /** Private Service Connect configuration. */ pscConfig: PscConfig | undefined; /** Customer-managed encryption, if any. */ encryptionConfig: EncryptionConfig | undefined; /** Automated backup policy currently applied. */ automatedBackupPolicy: AutomatedBackupPolicy | undefined; /** Continuous backup configuration currently applied. */ continuousBackupConfig: ContinuousBackupConfig | undefined; /** SSL configuration currently applied. */ sslConfig: SslConfig | undefined; /** Subscription type. */ subscriptionType: string | undefined; /** System-generated UID. */ uid: string | undefined; /** Whether the service is reconciling intended vs actual state. */ reconciling: boolean; /** Secondary-cluster config, if any. */ secondaryConfig: SecondaryConfig | undefined; /** RFC3339 creation timestamp. */ createTime: string | undefined; /** RFC3339 last-update timestamp. */ updateTime: string | undefined; }, never, Providers >; /** * An AlloyDB for PostgreSQL cluster (regional storage layer). * * Changing `clusterId`, `location`, `network` / `networkConfig`, * `encryptionConfig`, `clusterType`, `secondaryConfig`, or * `pscConfig.pscEnabled` replaces the cluster. A database version * upgrade patches in place; a downgrade replaces. * * Provisioning typically takes several minutes. Delete always sends * `force=true` so child instances do not block teardown. * * ### Creating a Cluster * **Example:** Generated name with Private Service Connect * ```typescript * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", { * location: "us-central1", * pscConfig: { pscEnabled: true }, * initialUser: { user: "postgres", password: "change-me" }, * automatedBackupPolicy: { enabled: false }, * continuousBackupConfig: { enabled: false }, * }); * ``` * * **Example:** Explicit id, default VPC, and labels * ```typescript * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", { * clusterId: "app-db", * location: "us-central1", * network: "default", * displayName: "app-db", * labels: { env: "prod" }, * initialUser: { user: "postgres", password: "change-me" }, * }); * ``` * * ### Backups * **Example:** Disable automated and continuous backups * ```typescript * const cluster = yield* GCP.AlloyDB.Cluster("AppDb", { * pscConfig: { pscEnabled: true }, * automatedBackupPolicy: { enabled: false }, * continuousBackupConfig: { enabled: false }, * }); * ``` * * @resource * @category AlloyDB */ export const Cluster = Resource<Cluster>("GCP.AlloyDB.Cluster"); export class ClusterNotResolved extends Data.TaggedError("GCP.AlloyDB.ClusterNotResolved")<{ resourceName: string; }> {} export class ClusterNotReady extends Data.TaggedError("GCP.AlloyDB.ClusterNotReady")<{ resourceName: string; state: string; }> {} export class ClusterFailed extends Data.TaggedError("GCP.AlloyDB.ClusterFailed")<{ resourceName: string; state: string; }> {} export class ClusterStillExists extends Data.TaggedError("GCP.AlloyDB.ClusterStillExists")<{ resourceName: string; }> {} const lastSegment = (value: string | undefined) => { if (value === undefined || value.length === 0) return ""; const trimmed = value.replace(/\/+$/, ""); const parts = trimmed.split("/"); return parts[parts.length - 1] || trimmed; }; const normalizeLocation = (location: string) => lastSegment(location).toLowerCase(); const normalizeClusterType = (type: string | undefined) => { const value = (type ?? DEFAULT_CLUSTER_TYPE).toUpperCase(); return value === "CLUSTER_TYPE_UNSPECIFIED" ? DEFAULT_CLUSTER_TYPE : value; }; const normalizeVersion = (version: string | undefined) => { if (version === undefined || version.length === 0) return undefined; const value = version.toUpperCase(); return value === "DATABASE_VERSION_UNSPECIFIED" ? undefined : value; }; const parsePostgresVersion = (version: string | undefined) => { const normalized = normalizeVersion(version); if (normalized === undefined) return undefined; const match = normalized.match(/^POSTGRES_(\d+)$/); return match ? Number(match[1]) : undefined; }; const versionDecreasing = (previous: string | undefined, next: string) => { const oldN = parsePostgresVersion(previous); const newN = parsePostgresVersion(next); if (oldN === undefined || newN === undefined) return previous !== next; return newN < oldN; }; const rfc1035 = (name: string): string => { let next = name .toLowerCase() .replace(/[^a-z0-9-]/g, "-") .replace(/-+/g, "-") .replace(/^-+|-+$/g, ""); if (!/^[a-z]/.test(next)) next = `c${next}`; next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); if (next.length === 0) return "cluster"; if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; return next.slice(0, MAX_NAME_LENGTH); }; const resourceName = (project: string, location: string, clusterId: string) => `projects/${project}/locations/${location}/clusters/${clusterId}`; const parseName = (name: string) => { const parts = name.split("/").filter((part) => part.length > 0); const clustersAt = parts.lastIndexOf("clusters"); const locationsAt = parts.lastIndexOf("locations"); const projectsAt = parts.lastIndexOf("projects"); return { project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "", clusterId: clustersAt >= 0 && parts[clustersAt + 1] ? parts[clustersAt + 1]! : lastSegment(name), }; }; const userLabels = ( labels: Record<string, string | undefined> | null | undefined, ): Record<string, string> => stripInternalLabels(tagRecord(labels)); const stringMapOf = ( map: Record<string, string | undefined> | null | undefined, ): Record<string, string> => Object.fromEntries( Object.entries(map ?? {}).filter( (entry): entry is [string, string] => entry[1] !== undefined && entry[1].length > 0, ), ); const expandNetwork = (project: string, network: string | undefined) => { if (network === undefined || network.length === 0) return undefined; if (network.includes("/")) return network; return `projects/${project}/global/networks/${network}`; }; const networkIdOf = (network: string | undefined) => lastSegment(network); const toId = (id: string, clusterId: string | undefined, existing?: string) => Effect.gen(function* () { return ( clusterId ?? existing ?? rfc1035( yield* createPhysicalName({ id, maxLength: MAX_NAME_LENGTH, lowercase: true, }), ) ); }); const canonical = (value: unknown): unknown => { if (value === undefined || value === null) return undefined; if (typeof value === "boolean" || typeof value === "number") return value; if (typeof value === "string") { return value.length === 0 ? undefined : value; } if (Array.isArray(value)) { const items = value.map(canonical).filter((item) => item !== undefined); return items.length === 0 ? undefined : items; } if (typeof value === "object") { const entries = Object.entries(value as Record<string, unknown>) .map(([key, item]) => [key, canonical(item)] as const) .filter(([, item]) => item !== undefined) .sort(([left], [right]) => left.localeCompare(right)); if (entries.length === 0) return undefined; return Object.fromEntries(entries); } return undefined; }; const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); const specifiedEquals = (desired: unknown, observed: unknown): boolean => { if (desired === undefined) return true; if ( typeof desired === "boolean" || typeof desired === "number" || typeof desired === "string" || Array.isArray(desired) ) { return fingerprint(desired) === fingerprint(observed); } if (desired !== null && typeof desired === "object") { const obs = observed !== null && typeof observed === "object" ? (observed as Record<string, unknown>) : {}; return Object.entries(desired as Record<string, unknown>).every(([key, value]) => specifiedEquals(value, obs[key]), ); } return fingerprint(desired) === fingerprint(observed); }; const toNetworkConfig = ( config: alloydb.NetworkConfig | NetworkConfig | undefined, fallbackNetwork?: string, ): NetworkConfig | undefined => { const network = config?.network ?? fallbackNetwork; const allocatedIpRange = config?.allocatedIpRange; if ( (network === undefined || network.length === 0) && (allocatedIpRange === undefined || allocatedIpRange.length === 0) ) { return undefined; } return { network: network || undefined, allocatedIpRange: allocatedIpRange || undefined, }; }; const toPscConfig = (config: alloydb.PscConfig | PscConfig | undefined): PscConfig | undefined => { if (config === undefined) return undefined; return { pscEnabled: config.pscEnabled === true }; }; const toEncryptionConfig = ( config: alloydb.EncryptionConfig | EncryptionConfig | undefined, ): EncryptionConfig | undefined => { const kmsKeyName = config?.kmsKeyName; if (kmsKeyName === undefined || kmsKeyName.length === 0) return undefined; return { kmsKeyName }; }; const toSslConfig = (config: alloydb.SslConfig | SslConfig | undefined): SslConfig | undefined => { if (config === undefined) return undefined; return { sslMode: config.sslMode, caSource: config.caSource, }; }; const toSecondaryConfig = ( config: alloydb.SecondaryConfig | SecondaryConfig | undefined, ): SecondaryConfig | undefined => { const primaryClusterName = config?.primaryClusterName; if (primaryClusterName === undefined || primaryClusterName.length === 0) { return undefined; } return { primaryClusterName }; }; const toAutomatedBackupPolicy = ( policy: alloydb.AutomatedBackupPolicy | AutomatedBackupPolicy | undefined, ): AutomatedBackupPolicy | undefined => { if (policy === undefined) return undefined; return canonical(policy) as AutomatedBackupPolicy | undefined; }; const toContinuousBackupConfig = ( config: alloydb.ContinuousBackupConfig | ContinuousBackupConfig | undefined, ): ContinuousBackupConfig | undefined => { if (config === undefined) return undefined; return canonical(config) as ContinuousBackupConfig | undefined; }; const isAvailable = (state: string | undefined) => { const value = (state ?? "").toUpperCase(); return value === "READY" || value === "EMPTY"; }; const isFailed = (state: string | undefined) => (state ?? "").toUpperCase() === "FAILED"; const toAttrs = (cluster: alloydb.Cluster, project: string) => { const name = cluster.name ?? ""; const parsed = parseName(name); const networkConfig = toNetworkConfig(cluster.networkConfig, cluster.network); return { name, clusterId: parsed.clusterId, project: parsed.project || project, location: parsed.location, displayName: cluster.displayName, labels: userLabels(cluster.labels), annotations: stringMapOf(cluster.annotations), state: cluster.state, clusterType: normalizeClusterType(cluster.clusterType), databaseVersion: cluster.databaseVersion, network: networkConfig?.network ?? cluster.network, networkConfig, pscConfig: toPscConfig(cluster.pscConfig), encryptionConfig: toEncryptionConfig(cluster.encryptionConfig), automatedBackupPolicy: toAutomatedBackupPolicy(cluster.automatedBackupPolicy), continuousBackupConfig: toContinuousBackupConfig(cluster.continuousBackupConfig), sslConfig: toSslConfig(cluster.sslConfig), subscriptionType: cluster.subscriptionType, uid: cluster.uid, reconciling: cluster.reconciling === true, secondaryConfig: toSecondaryConfig(cluster.secondaryConfig), createTime: cluster.createTime, updateTime: cluster.updateTime, }; }; const isPlaceholder = (cluster: alloydb.Cluster) => { const name = cluster.name ?? ""; return name.endsWith("/clusters/-") || name.endsWith("/clusters/"); }; const getByName = (name: string) => alloydb .getProjectsLocationsClusters({ name }) .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); const waitUntilExists = (name: string) => getByName(name).pipe( Effect.flatMap((cluster) => cluster ? Effect.succeed(cluster) : Effect.fail(new ClusterNotResolved({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.AlloyDB.ClusterNotResolved", times: 8, schedule: Schedule.spaced("1 second"), }), ); const waitUntilReady = (name: string) => Effect.gen(function* () { const cluster = yield* getByName(name); if (cluster === undefined) { return yield* new ClusterNotReady({ resourceName: name, state: "MISSING" }); } if (isFailed(cluster.state)) { return yield* new ClusterFailed({ resourceName: name, state: cluster.state ?? "FAILED", }); } if (!(isAvailable(cluster.state) && cluster.reconciling !== true)) { return yield* new ClusterNotReady({ resourceName: name, state: cluster.state ?? "STATE_UNSPECIFIED", }); } return cluster; }).pipe( Effect.retry({ while: (error) => error._tag === "GCP.AlloyDB.ClusterNotReady", times: 120, schedule: Schedule.spaced("15 seconds"), }), ); const waitUntilGone = (name: string) => getByName(name).pipe( Effect.flatMap((cluster) => cluster === undefined ? Effect.void : Effect.fail(new ClusterStillExists({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.AlloyDB.ClusterStillExists", times: 120, schedule: Schedule.spaced("15 seconds"), }), ); const desiredNetworkConfig = ( news: ClusterProps, project: string, pscEnabled: boolean, ): NetworkConfig | undefined => { const network = expandNetwork(project, news.networkConfig?.network ?? news.network); const allocatedIpRange = news.networkConfig?.allocatedIpRange; if (pscEnabled) { if ( (network === undefined || network.length === 0) && (allocatedIpRange === undefined || allocatedIpRange.length === 0) ) { return undefined; } return { network, allocatedIpRange }; } return { network: network ?? expandNetwork(project, DEFAULT_NETWORK), allocatedIpRange, }; }; const toCreateBody = ( news: ClusterProps, desiredLabels: Record<string, string>, clusterType: string, networkConfig: NetworkConfig | undefined, pscEnabled: boolean, ): alloydb.Cluster => { const body: alloydb.Cluster = { displayName: news.displayName, labels: desiredLabels, clusterType, }; if (news.annotations !== undefined) { body.annotations = news.annotations; } if (networkConfig !== undefined) { body.networkConfig = networkConfig; } if (news.pscConfig !== undefined || pscEnabled) { body.pscConfig = { pscEnabled }; } const encryption = toEncryptionConfig(news.encryptionConfig); if (encryption !== undefined) { body.encryptionConfig = encryption; } const version = normalizeVersion(news.databaseVersion); if (version !== undefined) { body.databaseVersion = version; } if (clusterType === "SECONDARY" && news.secondaryConfig !== undefined) { body.secondaryConfig = news.secondaryConfig; } if (news.initialUser !== undefined) { body.initialUser = news.initialUser; } if (news.automatedBackupPolicy !== undefined) { body.automatedBackupPolicy = news.automatedBackupPolicy; } if (news.continuousBackupConfig !== undefined) { body.continuousBackupConfig = news.continuousBackupConfig; } if (news.maintenanceUpdatePolicy !== undefined) { body.maintenanceUpdatePolicy = news.maintenanceUpdatePolicy; } if (news.sslConfig !== undefined) { body.sslConfig = news.sslConfig; } if (news.dataplexConfig !== undefined) { body.dataplexConfig = news.dataplexConfig; } if (news.subscriptionType !== undefined) { body.subscriptionType = news.subscriptionType; } return body; }; export const ClusterProvider = () => Provider.succeed(Cluster, { stables: ["name", "clusterId", "project", "location", "uid", "createTime"], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const env = yield* GcpEnvironment.current; const previousId = olds?.clusterId ?? output?.clusterId; const nextId = news.clusterId ?? previousId; const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region); const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region); const previousType = normalizeClusterType(olds?.clusterType ?? output?.clusterType); const nextType = normalizeClusterType(news.clusterType ?? output?.clusterType); const previousNetwork = networkIdOf( olds?.networkConfig?.network ?? olds?.network ?? output?.networkConfig?.network ?? output?.network, ); const nextNetwork = networkIdOf( news.networkConfig?.network ?? news.network ?? previousNetwork, ); const previousRange = olds?.networkConfig?.allocatedIpRange ?? output?.networkConfig?.allocatedIpRange ?? ""; const nextRange = news.networkConfig?.allocatedIpRange ?? previousRange; const previousPsc = olds?.pscConfig?.pscEnabled === true || output?.pscConfig?.pscEnabled === true; const nextPsc = news.pscConfig?.pscEnabled !== undefined ? news.pscConfig.pscEnabled === true : previousPsc; const previousKey = olds?.encryptionConfig?.kmsKeyName ?? output?.encryptionConfig?.kmsKeyName ?? ""; const nextKey = news.encryptionConfig?.kmsKeyName ?? previousKey; const previousPrimary = olds?.secondaryConfig?.primaryClusterName ?? output?.secondaryConfig?.primaryClusterName ?? ""; const nextPrimary = news.secondaryConfig?.primaryClusterName ?? previousPrimary; const previousVersion = normalizeVersion(olds?.databaseVersion ?? output?.databaseVersion); const nextVersion = normalizeVersion(news.databaseVersion); const downgrade = nextVersion !== undefined && previousVersion !== undefined && versionDecreasing(previousVersion, nextVersion); const replace = (previousId !== undefined && nextId !== undefined && nextId !== previousId) || previousLocation !== nextLocation || previousType !== nextType || previousNetwork !== nextNetwork || previousRange !== nextRange || previousPsc !== nextPsc || previousKey !== nextKey || previousPrimary !== nextPrimary || downgrade; if (!replace) return undefined; return { action: "replace" as const, deleteFirst: previousLocation === nextLocation && previousId !== undefined && nextId === previousId, }; }), read: Effect.fn(function* ({ id, olds, output }) { const env = yield* GcpEnvironment.current; const clusterId = yield* toId(id, olds?.clusterId, output?.clusterId); const location = normalizeLocation(olds?.location ?? output?.location ?? env.region); const name = output?.name ?? resourceName(env.project, location, clusterId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, env.project); return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); }), list: () => Effect.gen(function* () { const env = yield* GcpEnvironment.current; return yield* alloydb.listProjectsLocationsClusters .pages({ parent: `projects/${env.project}/locations/-`, pageSize: 1000, }) .pipe( Stream.flatMap((page) => Stream.fromIterable(page.clusters ?? [])), Stream.filter( (cluster) => !isPlaceholder(cluster) && Object.keys(cluster.labels ?? {}).some((key) => key.startsWith("alchemy-")), ), Stream.map((cluster) => toAttrs(cluster, env.project)), Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), Effect.catchTag("NotFound", () => Effect.succeed([])), ); }), reconcile: Effect.fn(function* ({ id, news, olds, output }) { const env = yield* GcpEnvironment.current; const clusterId = yield* toId(id, news.clusterId, output?.clusterId); const location = normalizeLocation(news.location ?? output?.location ?? env.region); const name = resourceName(env.project, location, clusterId); const clusterType = normalizeClusterType(news.clusterType); const pscEnabled = news.pscConfig?.pscEnabled === true; const networkConfig = desiredNetworkConfig(news, env.project, pscEnabled); const desiredLabels = { ...toLabels(news.labels), ...(yield* createInternalLabels(id)), }; let current = yield* getByName(output?.name ?? name); if (current === undefined) { const parent = `projects/${env.project}/locations/${location}`; const body = toCreateBody(news, desiredLabels, clusterType, networkConfig, pscEnabled); const created = yield* ( clusterType === "SECONDARY" ? alloydb.createsecondaryProjectsLocationsClusters({ parent, clusterId, body, }) : alloydb.createProjectsLocationsClusters({ parent, clusterId, body, }) ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); if (created !== undefined) { yield* waitForOperation(created); } current = yield* waitUntilExists(name); } if (current === undefined) { return yield* new ClusterNotResolved({ resourceName: name }); } if (!isAvailable(current.state) || current.reconciling === true) { current = yield* waitUntilReady(name); } const desiredVersion = normalizeVersion(news.databaseVersion); const currentVersion = normalizeVersion(current.databaseVersion); const versionChanged = desiredVersion !== undefined && currentVersion !== undefined && desiredVersion !== currentVersion && !versionDecreasing(currentVersion, desiredVersion); const observedLabels = tagRecord(current.labels); const { upsert, removed } = diffLabels(observedLabels, desiredLabels); const labelsChanged = upsert.length > 0 || removed.length > 0; // AlloyDB has been observed to omit `displayName` from reads; when it // does, compare against what was last applied instead of re-patching // on every deploy. const observedDisplayName = current.displayName ?? output?.displayName ?? olds?.displayName; const displayNameChanged = (observedDisplayName ?? "") !== (news.displayName ?? ""); const annotationsChanged = news.annotations !== undefined && fingerprint(stringMapOf(current.annotations)) !== fingerprint(news.annotations); const backupChanged = news.automatedBackupPolicy !== undefined && !specifiedEquals(news.automatedBackupPolicy, current.automatedBackupPolicy); const continuousChanged = news.continuousBackupConfig !== undefined && !specifiedEquals(news.continuousBackupConfig, current.continuousBackupConfig); const maintenanceChanged = news.maintenanceUpdatePolicy !== undefined && !specifiedEquals(news.maintenanceUpdatePolicy, current.maintenanceUpdatePolicy); const sslChanged = news.sslConfig !== undefined && !specifiedEquals(news.sslConfig, toSslConfig(current.sslConfig)); const dataplexChanged = news.dataplexConfig !== undefined && !specifiedEquals(news.dataplexConfig, current.dataplexConfig); const subscriptionChanged = news.subscriptionType !== undefined && (current.subscriptionType ?? "") !== news.subscriptionType; if ( labelsChanged || displayNameChanged || annotationsChanged || backupChanged || continuousChanged || maintenanceChanged || sslChanged || dataplexChanged || subscriptionChanged || versionChanged ) { const updateMask = [ labelsChanged ? "labels" : undefined, displayNameChanged ? "displayName" : undefined, annotationsChanged ? "annotations" : undefined, backupChanged ? "automatedBackupPolicy" : undefined, continuousChanged ? "continuousBackupConfig" : undefined, maintenanceChanged ? "maintenanceUpdatePolicy" : undefined, sslChanged ? "sslConfig" : undefined, dataplexChanged ? "dataplexConfig" : undefined, subscriptionChanged ? "subscriptionType" : undefined, versionChanged ? "databaseVersion" : undefined, ].filter((field): field is string => field !== undefined); const patched = yield* alloydb .patchProjectsLocationsClusters({ name, updateMask: updateMask.join(","), body: { name, labels: desiredLabels, displayName: news.displayName, annotations: news.annotations, automatedBackupPolicy: news.automatedBackupPolicy, continuousBackupConfig: news.continuousBackupConfig, maintenanceUpdatePolicy: news.maintenanceUpdatePolicy, sslConfig: news.sslConfig, dataplexConfig: news.dataplexConfig, subscriptionType: news.subscriptionType, databaseVersion: desiredVersion, }, }) .pipe( Effect.retry({ while: (error) => error._tag === "Conflict", times: 40, schedule: Schedule.spaced("15 seconds"), }), ); yield* waitForOperation(patched); current = yield* waitUntilReady(name); } // When the read omits `displayName`, the desired value is what is // deployed: it was sent on create, patched above, or observed equal. return { ...toAttrs(current, env.project), displayName: current.displayName ?? news.displayName, }; }), delete: Effect.fn(function* ({ output }) { const operation = yield* alloydb .deleteProjectsLocationsClusters({ name: output.name, force: true, }) .pipe( Effect.catchTag("NotFound", () => Effect.undefined), Effect.retry({ while: (error) => error._tag === "Conflict", times: 40, schedule: Schedule.spaced("15 seconds"), }), ); if (operation !== undefined) { yield* waitForDeleteOperation(operation); } yield* waitUntilGone(output.name); }), });
.repos/alchemy-effect/packages/gcp/src/AlloyDB/Cluster.ts at main · sailfork/t3code-github · Sailfork
. */\nconst MAX_NAME_LENGTH = 55;\n\nexport type ClusterTimeOfDay = {\n /** Hours of day in 24-hour format (`0`–`23`). */\n hours?: number;\n /** Minutes of hour (`0`–`59`). */\n minutes?: number;\n /** Seconds of minute (`0`–`59`). */\n seconds?: number;\n /** Fractional seconds, in nanoseconds. */\n nanos?: number;\n};\n\nexport type MaintenanceWindow = {\n /** Preferred day of week (`MONDAY` … `SUNDAY`). */\n day?: alloydb.MaintenanceWindowDayEnum | (string & {});\n /** Preferred UTC start time. Maintenance starts within 1 hour. */\n startTime?: ClusterTimeOfDay;\n};\n\nexport type DenyMaintenancePeriod = {\n /** Inclusive start date. */\n startDate?: { year?: number; month?: number; day?: number };\n /** Inclusive end date. */\n endDate?: { year?: number; month?: number; day?: number };\n /** UTC time of day for the window bounds. */\n time?: ClusterTimeOfDay;\n};\n\nexport type MaintenanceUpdatePolicy = {\n /** Preferred windows. Currently limited to 1. */\n maintenanceWindows?: MaintenanceWindow[];\n /** Periods to deny maintenance. Currently limited to 1. */\n denyMaintenancePeriods?: DenyMaintenancePeriod[];\n};\n\nexport type NetworkConfig = {\n /**\n * VPC network\n * (`projects/{project}/global/networks/{network}`). Immutable.\n * Required unless Private Service Connect is enabled.\n */\n network?: string;\n /**\n * Allocated IP range name for private IP (e.g.\n * `google-managed-services-default`). Immutable.\n */\n allocatedIpRange?: string;\n};\n\nexport type PscConfig = {\n /**\n * Allow Private Service Connect endpoints. When true, a VPC network is\n * not required. Immutable.\n */\n pscEnabled?: boolean;\n};\n\nexport type EncryptionConfig = {\n /**\n * Customer-managed KMS key\n * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).\n * Immutable — changing it replaces the cluster.\n */\n kmsKeyName?: string;\n};\n\nexport type WeeklySchedule = {\n /** UTC start times (typically exact hours). */\n startTimes?: ClusterTimeOfDay[];\n /** Days of week. Empty means every day. */\n daysOfWeek?: Array\u003calloydb.WeeklyScheduleDaysOfWeekItemEnum | (string & {})>;\n};\n\nexport type AutomatedBackupPolicy = {\n /** Whether automated backups are enabled. Defaults to true when omitted. */\n enabled?: boolean;\n /** Backup window duration (e.g. `\"1800s\"`). */\n backupWindow?: string;\n /** Weekly schedule. */\n weeklySchedule?: WeeklySchedule;\n /** Keep the most recent N backups. */\n quantityBasedRetention?: { count?: number };\n /** Keep backups for a duration (e.g. `\"1209600s\"`). */\n timeBasedRetention?: { retentionPeriod?: string };\n /** Backup location. Defaults to the cluster region. */\n location?: string;\n /** Labels applied to created backups. */\n labels?: Record\u003cstring, string>;\n /** CMEK for backups. Defaults to the cluster encryption config. */\n encryptionConfig?: EncryptionConfig;\n};\n\nexport type ContinuousBackupConfig = {\n /** Whether continuous backup (PITR) is enabled. */\n enabled?: boolean;\n /** Recovery window in days. Defaults to 14. */\n recoveryWindowDays?: number;\n /** CMEK for continuous backups. */\n encryptionConfig?: EncryptionConfig;\n};\n\nexport type InitialUser = {\n /** Database username. Defaults to `postgres` when omitted. */\n user?: string;\n /** Initial password. Create-only. */\n password?: string;\n};\n\nexport type SslConfig = {\n /** Client-server SSL mode. */\n sslMode?: alloydb.SslConfigSslModeEnum | (string & {});\n /** Certificate authority source. Only `CA_SOURCE_MANAGED` is supported. */\n caSource?: alloydb.SslConfigCaSourceEnum | (string & {});\n};\n\nexport type DataplexConfig = {\n /** Integrate AlloyDB PG resources with Dataplex. */\n enabled?: boolean;\n};\n\nexport type SecondaryConfig = {\n /**\n * Primary cluster name\n * `projects/{project}/locations/{location}/clusters/{cluster}`.\n * Required when `clusterType` is `SECONDARY`. Immutable.\n */\n primaryClusterName?: string;\n};\n\nexport type ClusterProps = {\n /**\n * Cluster id (the `{cluster}` segment of\n * `projects/{project}/locations/{location}/clusters/{cluster}`).\n * If omitted, a unique name is generated from the stack, stage, and\n * logical id. Must match `[a-z0-9-]{1,63}`. Immutable — changing it\n * replaces the cluster.\n */\n clusterId?: string;\n /**\n * Region (`us-central1`, `us-east1`, …). Immutable — changing it\n * replaces the cluster. `US-CENTRAL1` is accepted and normalized to\n * `us-central1`.\n * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)\n */\n location?: string;\n /**\n * User-facing display name.\n */\n displayName?: string;\n /**\n * User labels. Alchemy ownership labels are merged in automatically.\n */\n labels?: Record\u003cstring, string>;\n /**\n * Arbitrary client annotations (distinct from labels).\n */\n annotations?: Record\u003cstring, string>;\n /**\n * Convenience alias for `networkConfig.network`. A bare network id\n * (`default`) is expanded to\n * `projects/{project}/global/networks/{network}`. Immutable.\n */\n network?: string;\n /**\n * Private IP network configuration. Immutable. Defaults to the project\n * `default` network when Private Service Connect is not enabled.\n */\n networkConfig?: NetworkConfig;\n /**\n * Private Service Connect configuration. `pscEnabled` is immutable.\n */\n pscConfig?: PscConfig;\n /**\n * Customer-managed encryption. Immutable — changing it replaces the\n * cluster.\n */\n encryptionConfig?: EncryptionConfig;\n /**\n * Database engine major version (`POSTGRES_14`, `POSTGRES_15`, …).\n * Upgrading patches in place; downgrading replaces the cluster. If\n * omitted at create time, AlloyDB picks a default.\n */\n databaseVersion?: alloydb.ClusterDatabaseVersionEnum | (string & {});\n /**\n * Cluster type. `SECONDARY` uses `clusters.createsecondary` and\n * requires `secondaryConfig`. Immutable — changing it replaces the\n * cluster.\n * @default \"PRIMARY\"\n */\n clusterType?: alloydb.ClusterClusterTypeEnum | (string & {});\n /**\n * Cross-region replica config. Required for `SECONDARY` clusters.\n * Immutable.\n */\n secondaryConfig?: SecondaryConfig;\n /**\n * Initial database user. Create-only; ignored on update.\n */\n initialUser?: InitialUser;\n /**\n * Automated backup policy. If omitted, AlloyDB applies its default\n * (daily backups, 14-day retention).\n */\n automatedBackupPolicy?: AutomatedBackupPolicy;\n /**\n * Continuous backup (PITR) configuration.\n */\n continuousBackupConfig?: ContinuousBackupConfig;\n /**\n * Preferred maintenance windows and deny periods.\n */\n maintenanceUpdatePolicy?: MaintenanceUpdatePolicy;\n /**\n * Client-server SSL configuration.\n */\n sslConfig?: SslConfig;\n /**\n * Dataplex integration.\n */\n dataplexConfig?: DataplexConfig;\n /**\n * Subscription type (`STANDARD`, `TRIAL`).\n */\n subscriptionType?: alloydb.ClusterSubscriptionTypeEnum | (string & {});\n};\n\nexport type Cluster = Resource\u003c\n \"GCP.AlloyDB.Cluster\",\n ClusterProps,\n {\n /** Full resource name `projects/{project}/locations/{location}/clusters/{cluster}`. */\n name: string;\n /** Cluster id (last path segment). */\n clusterId: string;\n /** Project id. */\n project: string;\n /** Region id (`us-central1`, …). */\n location: string;\n /** User-facing display name. */\n displayName: string | undefined;\n /** User labels (Alchemy ownership labels stripped). */\n labels: Record\u003cstring, string>;\n /** Client annotations. */\n annotations: Record\u003cstring, string>;\n /** Serving state (`READY`, `EMPTY`, `CREATING`, …). */\n state: string | undefined;\n /** Cluster type (`PRIMARY`, `SECONDARY`). */\n clusterType: string;\n /** Database engine major version. */\n databaseVersion: string | undefined;\n /** VPC network, if any. */\n network: string | undefined;\n /** Private IP network configuration. */\n networkConfig: NetworkConfig | undefined;\n /** Private Service Connect configuration. */\n pscConfig: PscConfig | undefined;\n /** Customer-managed encryption, if any. */\n encryptionConfig: EncryptionConfig | undefined;\n /** Automated backup policy currently applied. */\n automatedBackupPolicy: AutomatedBackupPolicy | undefined;\n /** Continuous backup configuration currently applied. */\n continuousBackupConfig: ContinuousBackupConfig | undefined;\n /** SSL configuration currently applied. */\n sslConfig: SslConfig | undefined;\n /** Subscription type. */\n subscriptionType: string | undefined;\n /** System-generated UID. */\n uid: string | undefined;\n /** Whether the service is reconciling intended vs actual state. */\n reconciling: boolean;\n /** Secondary-cluster config, if any. */\n secondaryConfig: SecondaryConfig | undefined;\n /** RFC3339 creation timestamp. */\n createTime: string | undefined;\n /** RFC3339 last-update timestamp. */\n updateTime: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * An AlloyDB for PostgreSQL cluster (regional storage layer).\n *\n * Changing `clusterId`, `location`, `network` / `networkConfig`,\n * `encryptionConfig`, `clusterType`, `secondaryConfig`, or\n * `pscConfig.pscEnabled` replaces the cluster. A database version\n * upgrade patches in place; a downgrade replaces.\n *\n * Provisioning typically takes several minutes. Delete always sends\n * `force=true` so child instances do not block teardown.\n *\n * ### Creating a Cluster\n * **Example:** Generated name with Private Service Connect\n * ```typescript\n * const cluster = yield* GCP.AlloyDB.Cluster(\"AppDb\", {\n * location: \"us-central1\",\n * pscConfig: { pscEnabled: true },\n * initialUser: { user: \"postgres\", password: \"change-me\" },\n * automatedBackupPolicy: { enabled: false },\n * continuousBackupConfig: { enabled: false },\n * });\n * ```\n *\n * **Example:** Explicit id, default VPC, and labels\n * ```typescript\n * const cluster = yield* GCP.AlloyDB.Cluster(\"AppDb\", {\n * clusterId: \"app-db\",\n * location: \"us-central1\",\n * network: \"default\",\n * displayName: \"app-db\",\n * labels: { env: \"prod\" },\n * initialUser: { user: \"postgres\", password: \"change-me\" },\n * });\n * ```\n *\n * ### Backups\n * **Example:** Disable automated and continuous backups\n * ```typescript\n * const cluster = yield* GCP.AlloyDB.Cluster(\"AppDb\", {\n * pscConfig: { pscEnabled: true },\n * automatedBackupPolicy: { enabled: false },\n * continuousBackupConfig: { enabled: false },\n * });\n * ```\n *\n * @resource\n * @category AlloyDB\n */\nexport const Cluster = Resource\u003cCluster>(\"GCP.AlloyDB.Cluster\");\n\nexport class ClusterNotResolved extends Data.TaggedError(\"GCP.AlloyDB.ClusterNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nexport class ClusterNotReady extends Data.TaggedError(\"GCP.AlloyDB.ClusterNotReady\")\u003c{\n resourceName: string;\n state: string;\n}> {}\n\nexport class ClusterFailed extends Data.TaggedError(\"GCP.AlloyDB.ClusterFailed\")\u003c{\n resourceName: string;\n state: string;\n}> {}\n\nexport class ClusterStillExists extends Data.TaggedError(\"GCP.AlloyDB.ClusterStillExists\")\u003c{\n resourceName: string;\n}> {}\n\nconst lastSegment = (value: string | undefined) => {\n if (value === undefined || value.length === 0) return \"\";\n const trimmed = value.replace(/\\/+$/, \"\");\n const parts = trimmed.split(\"/\");\n return parts[parts.length - 1] || trimmed;\n};\n\nconst normalizeLocation = (location: string) => lastSegment(location).toLowerCase();\n\nconst normalizeClusterType = (type: string | undefined) => {\n const value = (type ?? DEFAULT_CLUSTER_TYPE).toUpperCase();\n return value === \"CLUSTER_TYPE_UNSPECIFIED\" ? DEFAULT_CLUSTER_TYPE : value;\n};\n\nconst normalizeVersion = (version: string | undefined) => {\n if (version === undefined || version.length === 0) return undefined;\n const value = version.toUpperCase();\n return value === \"DATABASE_VERSION_UNSPECIFIED\" ? undefined : value;\n};\n\nconst parsePostgresVersion = (version: string | undefined) => {\n const normalized = normalizeVersion(version);\n if (normalized === undefined) return undefined;\n const match = normalized.match(/^POSTGRES_(\\d+)$/);\n return match ? Number(match[1]) : undefined;\n};\n\nconst versionDecreasing = (previous: string | undefined, next: string) => {\n const oldN = parsePostgresVersion(previous);\n const newN = parsePostgresVersion(next);\n if (oldN === undefined || newN === undefined) return previous !== next;\n return newN \u003c oldN;\n};\n\nconst rfc1035 = (name: string): string => {\n let next = name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (!/^[a-z]/.test(next)) next = `c${next}`;\n next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, \"\");\n if (next.length === 0) return \"cluster\";\n if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;\n return next.slice(0, MAX_NAME_LENGTH);\n};\n\nconst resourceName = (project: string, location: string, clusterId: string) =>\n `projects/${project}/locations/${location}/clusters/${clusterId}`;\n\nconst parseName = (name: string) => {\n const parts = name.split(\"/\").filter((part) => part.length > 0);\n const clustersAt = parts.lastIndexOf(\"clusters\");\n const locationsAt = parts.lastIndexOf(\"locations\");\n const projectsAt = parts.lastIndexOf(\"projects\");\n return {\n project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : \"\",\n location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : \"\",\n clusterId:\n clustersAt >= 0 && parts[clustersAt + 1] ? parts[clustersAt + 1]! : lastSegment(name),\n };\n};\n\nconst userLabels = (\n labels: Record\u003cstring, string | undefined> | null | undefined,\n): Record\u003cstring, string> => stripInternalLabels(tagRecord(labels));\n\nconst stringMapOf = (\n map: Record\u003cstring, string | undefined> | null | undefined,\n): Record\u003cstring, string> =>\n Object.fromEntries(\n Object.entries(map ?? {}).filter(\n (entry): entry is [string, string] => entry[1] !== undefined && entry[1].length > 0,\n ),\n );\n\nconst expandNetwork = (project: string, network: string | undefined) => {\n if (network === undefined || network.length === 0) return undefined;\n if (network.includes(\"/\")) return network;\n return `projects/${project}/global/networks/${network}`;\n};\n\nconst networkIdOf = (network: string | undefined) => lastSegment(network);\n\nconst toId = (id: string, clusterId: string | undefined, existing?: string) =>\n Effect.gen(function* () {\n return (\n clusterId ??\n existing ??\n rfc1035(\n yield* createPhysicalName({\n id,\n maxLength: MAX_NAME_LENGTH,\n lowercase: true,\n }),\n )\n );\n });\n\nconst canonical = (value: unknown): unknown => {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"boolean\" || typeof value === \"number\") return value;\n if (typeof value === \"string\") {\n return value.length === 0 ? undefined : value;\n }\n if (Array.isArray(value)) {\n const items = value.map(canonical).filter((item) => item !== undefined);\n return items.length === 0 ? undefined : items;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record\u003cstring, unknown>)\n .map(([key, item]) => [key, canonical(item)] as const)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => left.localeCompare(right));\n if (entries.length === 0) return undefined;\n return Object.fromEntries(entries);\n }\n return undefined;\n};\n\nconst fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);\n\nconst specifiedEquals = (desired: unknown, observed: unknown): boolean => {\n if (desired === undefined) return true;\n if (\n typeof desired === \"boolean\" ||\n typeof desired === \"number\" ||\n typeof desired === \"string\" ||\n Array.isArray(desired)\n ) {\n return fingerprint(desired) === fingerprint(observed);\n }\n if (desired !== null && typeof desired === \"object\") {\n const obs =\n observed !== null && typeof observed === \"object\"\n ? (observed as Record\u003cstring, unknown>)\n : {};\n return Object.entries(desired as Record\u003cstring, unknown>).every(([key, value]) =>\n specifiedEquals(value, obs[key]),\n );\n }\n return fingerprint(desired) === fingerprint(observed);\n};\n\nconst toNetworkConfig = (\n config: alloydb.NetworkConfig | NetworkConfig | undefined,\n fallbackNetwork?: string,\n): NetworkConfig | undefined => {\n const network = config?.network ?? fallbackNetwork;\n const allocatedIpRange = config?.allocatedIpRange;\n if (\n (network === undefined || network.length === 0) &&\n (allocatedIpRange === undefined || allocatedIpRange.length === 0)\n ) {\n return undefined;\n }\n return {\n network: network || undefined,\n allocatedIpRange: allocatedIpRange || undefined,\n };\n};\n\nconst toPscConfig = (config: alloydb.PscConfig | PscConfig | undefined): PscConfig | undefined => {\n if (config === undefined) return undefined;\n return { pscEnabled: config.pscEnabled === true };\n};\n\nconst toEncryptionConfig = (\n config: alloydb.EncryptionConfig | EncryptionConfig | undefined,\n): EncryptionConfig | undefined => {\n const kmsKeyName = config?.kmsKeyName;\n if (kmsKeyName === undefined || kmsKeyName.length === 0) return undefined;\n return { kmsKeyName };\n};\n\nconst toSslConfig = (config: alloydb.SslConfig | SslConfig | undefined): SslConfig | undefined => {\n if (config === undefined) return undefined;\n return {\n sslMode: config.sslMode,\n caSource: config.caSource,\n };\n};\n\nconst toSecondaryConfig = (\n config: alloydb.SecondaryConfig | SecondaryConfig | undefined,\n): SecondaryConfig | undefined => {\n const primaryClusterName = config?.primaryClusterName;\n if (primaryClusterName === undefined || primaryClusterName.length === 0) {\n return undefined;\n }\n return { primaryClusterName };\n};\n\nconst toAutomatedBackupPolicy = (\n policy: alloydb.AutomatedBackupPolicy | AutomatedBackupPolicy | undefined,\n): AutomatedBackupPolicy | undefined => {\n if (policy === undefined) return undefined;\n return canonical(policy) as AutomatedBackupPolicy | undefined;\n};\n\nconst toContinuousBackupConfig = (\n config: alloydb.ContinuousBackupConfig | ContinuousBackupConfig | undefined,\n): ContinuousBackupConfig | undefined => {\n if (config === undefined) return undefined;\n return canonical(config) as ContinuousBackupConfig | undefined;\n};\n\nconst isAvailable = (state: string | undefined) => {\n const value = (state ?? \"\").toUpperCase();\n return value === \"READY\" || value === \"EMPTY\";\n};\n\nconst isFailed = (state: string | undefined) => (state ?? \"\").toUpperCase() === \"FAILED\";\n\nconst toAttrs = (cluster: alloydb.Cluster, project: string) => {\n const name = cluster.name ?? \"\";\n const parsed = parseName(name);\n const networkConfig = toNetworkConfig(cluster.networkConfig, cluster.network);\n return {\n name,\n clusterId: parsed.clusterId,\n project: parsed.project || project,\n location: parsed.location,\n displayName: cluster.displayName,\n labels: userLabels(cluster.labels),\n annotations: stringMapOf(cluster.annotations),\n state: cluster.state,\n clusterType: normalizeClusterType(cluster.clusterType),\n databaseVersion: cluster.databaseVersion,\n network: networkConfig?.network ?? cluster.network,\n networkConfig,\n pscConfig: toPscConfig(cluster.pscConfig),\n encryptionConfig: toEncryptionConfig(cluster.encryptionConfig),\n automatedBackupPolicy: toAutomatedBackupPolicy(cluster.automatedBackupPolicy),\n continuousBackupConfig: toContinuousBackupConfig(cluster.continuousBackupConfig),\n sslConfig: toSslConfig(cluster.sslConfig),\n subscriptionType: cluster.subscriptionType,\n uid: cluster.uid,\n reconciling: cluster.reconciling === true,\n secondaryConfig: toSecondaryConfig(cluster.secondaryConfig),\n createTime: cluster.createTime,\n updateTime: cluster.updateTime,\n };\n};\n\nconst isPlaceholder = (cluster: alloydb.Cluster) => {\n const name = cluster.name ?? \"\";\n return name.endsWith(\"/clusters/-\") || name.endsWith(\"/clusters/\");\n};\n\nconst getByName = (name: string) =>\n alloydb\n .getProjectsLocationsClusters({ name })\n .pipe(Effect.catchTag(\"NotFound\", () => Effect.undefined));\n\nconst waitUntilExists = (name: string) =>\n getByName(name).pipe(\n Effect.flatMap((cluster) =>\n cluster\n ? Effect.succeed(cluster)\n : Effect.fail(new ClusterNotResolved({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.AlloyDB.ClusterNotResolved\",\n times: 8,\n schedule: Schedule.spaced(\"1 second\"),\n }),\n );\n\nconst waitUntilReady = (name: string) =>\n Effect.gen(function* () {\n const cluster = yield* getByName(name);\n if (cluster === undefined) {\n return yield* new ClusterNotReady({ resourceName: name, state: \"MISSING\" });\n }\n if (isFailed(cluster.state)) {\n return yield* new ClusterFailed({\n resourceName: name,\n state: cluster.state ?? \"FAILED\",\n });\n }\n if (!(isAvailable(cluster.state) && cluster.reconciling !== true)) {\n return yield* new ClusterNotReady({\n resourceName: name,\n state: cluster.state ?? \"STATE_UNSPECIFIED\",\n });\n }\n return cluster;\n }).pipe(\n Effect.retry({\n while: (error) => error._tag === \"GCP.AlloyDB.ClusterNotReady\",\n times: 120,\n schedule: Schedule.spaced(\"15 seconds\"),\n }),\n );\n\nconst waitUntilGone = (name: string) =>\n getByName(name).pipe(\n Effect.flatMap((cluster) =>\n cluster === undefined\n ? Effect.void\n : Effect.fail(new ClusterStillExists({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.AlloyDB.ClusterStillExists\",\n times: 120,\n schedule: Schedule.spaced(\"15 seconds\"),\n }),\n );\n\nconst desiredNetworkConfig = (\n news: ClusterProps,\n project: string,\n pscEnabled: boolean,\n): NetworkConfig | undefined => {\n const network = expandNetwork(project, news.networkConfig?.network ?? news.network);\n const allocatedIpRange = news.networkConfig?.allocatedIpRange;\n if (pscEnabled) {\n if (\n (network === undefined || network.length === 0) &&\n (allocatedIpRange === undefined || allocatedIpRange.length === 0)\n ) {\n return undefined;\n }\n return { network, allocatedIpRange };\n }\n return {\n network: network ?? expandNetwork(project, DEFAULT_NETWORK),\n allocatedIpRange,\n };\n};\n\nconst toCreateBody = (\n news: ClusterProps,\n desiredLabels: Record\u003cstring, string>,\n clusterType: string,\n networkConfig: NetworkConfig | undefined,\n pscEnabled: boolean,\n): alloydb.Cluster => {\n const body: alloydb.Cluster = {\n displayName: news.displayName,\n labels: desiredLabels,\n clusterType,\n };\n if (news.annotations !== undefined) {\n body.annotations = news.annotations;\n }\n if (networkConfig !== undefined) {\n body.networkConfig = networkConfig;\n }\n if (news.pscConfig !== undefined || pscEnabled) {\n body.pscConfig = { pscEnabled };\n }\n const encryption = toEncryptionConfig(news.encryptionConfig);\n if (encryption !== undefined) {\n body.encryptionConfig = encryption;\n }\n const version = normalizeVersion(news.databaseVersion);\n if (version !== undefined) {\n body.databaseVersion = version;\n }\n if (clusterType === \"SECONDARY\" && news.secondaryConfig !== undefined) {\n body.secondaryConfig = news.secondaryConfig;\n }\n if (news.initialUser !== undefined) {\n body.initialUser = news.initialUser;\n }\n if (news.automatedBackupPolicy !== undefined) {\n body.automatedBackupPolicy = news.automatedBackupPolicy;\n }\n if (news.continuousBackupConfig !== undefined) {\n body.continuousBackupConfig = news.continuousBackupConfig;\n }\n if (news.maintenanceUpdatePolicy !== undefined) {\n body.maintenanceUpdatePolicy = news.maintenanceUpdatePolicy;\n }\n if (news.sslConfig !== undefined) {\n body.sslConfig = news.sslConfig;\n }\n if (news.dataplexConfig !== undefined) {\n body.dataplexConfig = news.dataplexConfig;\n }\n if (news.subscriptionType !== undefined) {\n body.subscriptionType = news.subscriptionType;\n }\n return body;\n};\n\nexport const ClusterProvider = () =>\n Provider.succeed(Cluster, {\n stables: [\"name\", \"clusterId\", \"project\", \"location\", \"uid\", \"createTime\"],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const env = yield* GcpEnvironment.current;\n\n const previousId = olds?.clusterId ?? output?.clusterId;\n const nextId = news.clusterId ?? previousId;\n const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);\n const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);\n const previousType = normalizeClusterType(olds?.clusterType ?? output?.clusterType);\n const nextType = normalizeClusterType(news.clusterType ?? output?.clusterType);\n const previousNetwork = networkIdOf(\n olds?.networkConfig?.network ??\n olds?.network ??\n output?.networkConfig?.network ??\n output?.network,\n );\n const nextNetwork = networkIdOf(\n news.networkConfig?.network ?? news.network ?? previousNetwork,\n );\n const previousRange =\n olds?.networkConfig?.allocatedIpRange ?? output?.networkConfig?.allocatedIpRange ?? \"\";\n const nextRange = news.networkConfig?.allocatedIpRange ?? previousRange;\n const previousPsc =\n olds?.pscConfig?.pscEnabled === true || output?.pscConfig?.pscEnabled === true;\n const nextPsc =\n news.pscConfig?.pscEnabled !== undefined ? news.pscConfig.pscEnabled === true : previousPsc;\n const previousKey =\n olds?.encryptionConfig?.kmsKeyName ?? output?.encryptionConfig?.kmsKeyName ?? \"\";\n const nextKey = news.encryptionConfig?.kmsKeyName ?? previousKey;\n const previousPrimary =\n olds?.secondaryConfig?.primaryClusterName ??\n output?.secondaryConfig?.primaryClusterName ??\n \"\";\n const nextPrimary = news.secondaryConfig?.primaryClusterName ?? previousPrimary;\n const previousVersion = normalizeVersion(olds?.databaseVersion ?? output?.databaseVersion);\n const nextVersion = normalizeVersion(news.databaseVersion);\n const downgrade =\n nextVersion !== undefined &&\n previousVersion !== undefined &&\n versionDecreasing(previousVersion, nextVersion);\n\n const replace =\n (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||\n previousLocation !== nextLocation ||\n previousType !== nextType ||\n previousNetwork !== nextNetwork ||\n previousRange !== nextRange ||\n previousPsc !== nextPsc ||\n previousKey !== nextKey ||\n previousPrimary !== nextPrimary ||\n downgrade;\n\n if (!replace) return undefined;\n return {\n action: \"replace\" as const,\n deleteFirst:\n previousLocation === nextLocation && previousId !== undefined && nextId === previousId,\n };\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const clusterId = yield* toId(id, olds?.clusterId, output?.clusterId);\n const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);\n const name = output?.name ?? resourceName(env.project, location, clusterId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project);\n return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);\n }),\n\n list: () =>\n Effect.gen(function* () {\n const env = yield* GcpEnvironment.current;\n return yield* alloydb.listProjectsLocationsClusters\n .pages({\n parent: `projects/${env.project}/locations/-`,\n pageSize: 1000,\n })\n .pipe(\n Stream.flatMap((page) => Stream.fromIterable(page.clusters ?? [])),\n Stream.filter(\n (cluster) =>\n !isPlaceholder(cluster) &&\n Object.keys(cluster.labels ?? {}).some((key) => key.startsWith(\"alchemy-\")),\n ),\n Stream.map((cluster) => toAttrs(cluster, env.project)),\n Stream.runCollect,\n Effect.map((chunk) => Array.from(chunk)),\n Effect.catchTag(\"NotFound\", () => Effect.succeed([])),\n );\n }),\n\n reconcile: Effect.fn(function* ({ id, news, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const clusterId = yield* toId(id, news.clusterId, output?.clusterId);\n const location = normalizeLocation(news.location ?? output?.location ?? env.region);\n const name = resourceName(env.project, location, clusterId);\n const clusterType = normalizeClusterType(news.clusterType);\n const pscEnabled = news.pscConfig?.pscEnabled === true;\n const networkConfig = desiredNetworkConfig(news, env.project, pscEnabled);\n const desiredLabels = {\n ...toLabels(news.labels),\n ...(yield* createInternalLabels(id)),\n };\n\n let current = yield* getByName(output?.name ?? name);\n\n if (current === undefined) {\n const parent = `projects/${env.project}/locations/${location}`;\n const body = toCreateBody(news, desiredLabels, clusterType, networkConfig, pscEnabled);\n const created = yield* (\n clusterType === \"SECONDARY\"\n ? alloydb.createsecondaryProjectsLocationsClusters({\n parent,\n clusterId,\n body,\n })\n : alloydb.createProjectsLocationsClusters({\n parent,\n clusterId,\n body,\n })\n ).pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n if (created !== undefined) {\n yield* waitForOperation(created);\n }\n current = yield* waitUntilExists(name);\n }\n\n if (current === undefined) {\n return yield* new ClusterNotResolved({ resourceName: name });\n }\n\n if (!isAvailable(current.state) || current.reconciling === true) {\n current = yield* waitUntilReady(name);\n }\n\n const desiredVersion = normalizeVersion(news.databaseVersion);\n const currentVersion = normalizeVersion(current.databaseVersion);\n const versionChanged =\n desiredVersion !== undefined &&\n currentVersion !== undefined &&\n desiredVersion !== currentVersion &&\n !versionDecreasing(currentVersion, desiredVersion);\n\n const observedLabels = tagRecord(current.labels);\n const { upsert, removed } = diffLabels(observedLabels, desiredLabels);\n const labelsChanged = upsert.length > 0 || removed.length > 0;\n // AlloyDB has been observed to omit `displayName` from reads; when it\n // does, compare against what was last applied instead of re-patching\n // on every deploy.\n const observedDisplayName = current.displayName ?? output?.displayName ?? olds?.displayName;\n const displayNameChanged = (observedDisplayName ?? \"\") !== (news.displayName ?? \"\");\n const annotationsChanged =\n news.annotations !== undefined &&\n fingerprint(stringMapOf(current.annotations)) !== fingerprint(news.annotations);\n const backupChanged =\n news.automatedBackupPolicy !== undefined &&\n !specifiedEquals(news.automatedBackupPolicy, current.automatedBackupPolicy);\n const continuousChanged =\n news.continuousBackupConfig !== undefined &&\n !specifiedEquals(news.continuousBackupConfig, current.continuousBackupConfig);\n const maintenanceChanged =\n news.maintenanceUpdatePolicy !== undefined &&\n !specifiedEquals(news.maintenanceUpdatePolicy, current.maintenanceUpdatePolicy);\n const sslChanged =\n news.sslConfig !== undefined &&\n !specifiedEquals(news.sslConfig, toSslConfig(current.sslConfig));\n const dataplexChanged =\n news.dataplexConfig !== undefined &&\n !specifiedEquals(news.dataplexConfig, current.dataplexConfig);\n const subscriptionChanged =\n news.subscriptionType !== undefined &&\n (current.subscriptionType ?? \"\") !== news.subscriptionType;\n\n if (\n labelsChanged ||\n displayNameChanged ||\n annotationsChanged ||\n backupChanged ||\n continuousChanged ||\n maintenanceChanged ||\n sslChanged ||\n dataplexChanged ||\n subscriptionChanged ||\n versionChanged\n ) {\n const updateMask = [\n labelsChanged ? \"labels\" : undefined,\n displayNameChanged ? \"displayName\" : undefined,\n annotationsChanged ? \"annotations\" : undefined,\n backupChanged ? \"automatedBackupPolicy\" : undefined,\n continuousChanged ? \"continuousBackupConfig\" : undefined,\n maintenanceChanged ? \"maintenanceUpdatePolicy\" : undefined,\n sslChanged ? \"sslConfig\" : undefined,\n dataplexChanged ? \"dataplexConfig\" : undefined,\n subscriptionChanged ? \"subscriptionType\" : undefined,\n versionChanged ? \"databaseVersion\" : undefined,\n ].filter((field): field is string => field !== undefined);\n\n const patched = yield* alloydb\n .patchProjectsLocationsClusters({\n name,\n updateMask: updateMask.join(\",\"),\n body: {\n name,\n labels: desiredLabels,\n displayName: news.displayName,\n annotations: news.annotations,\n automatedBackupPolicy: news.automatedBackupPolicy,\n continuousBackupConfig: news.continuousBackupConfig,\n maintenanceUpdatePolicy: news.maintenanceUpdatePolicy,\n sslConfig: news.sslConfig,\n dataplexConfig: news.dataplexConfig,\n subscriptionType: news.subscriptionType,\n databaseVersion: desiredVersion,\n },\n })\n .pipe(\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 40,\n schedule: Schedule.spaced(\"15 seconds\"),\n }),\n );\n yield* waitForOperation(patched);\n current = yield* waitUntilReady(name);\n }\n\n // When the read omits `displayName`, the desired value is what is\n // deployed: it was sent on create, patched above, or observed equal.\n return {\n ...toAttrs(current, env.project),\n displayName: current.displayName ?? news.displayName,\n };\n }),\n\n delete: Effect.fn(function* ({ output }) {\n const operation = yield* alloydb\n .deleteProjectsLocationsClusters({\n name: output.name,\n force: true,\n })\n .pipe(\n Effect.catchTag(\"NotFound\", () => Effect.undefined),\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 40,\n schedule: Schedule.spaced(\"15 seconds\"),\n }),\n );\n if (operation !== undefined) {\n yield* waitForDeleteOperation(operation);\n }\n yield* waitUntilGone(output.name);\n }),\n });\n","preview":null,"history":null,"version":"84d21811ace137279377f7e1225709dfdb6123e6"},"/_session?shell=1":null}