The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import * as sqladmin from "@distilled.cloud/gcp/sqladmin_v1"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { tagRecord } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import { GcpEnvironment } from "../Environment.ts"; |
| 14 | import { |
| 15 | createInternalLabels, |
| 16 | diffLabels, |
| 17 | hasAlchemyLabels, |
| 18 | stripInternalLabels, |
| 19 | toLabels, |
| 20 | } from "../Labels.ts"; |
| 21 | import type { Providers } from "../Providers.ts"; |
| 22 | import { waitForSqlOperation } from "./operations.ts"; |
| 23 | |
| 24 | const DEFAULT_DATABASE_VERSION = "MYSQL_8_0"; |
| 25 | const DEFAULT_TIER = "db-f1-micro"; |
| 26 | const DEFAULT_EDITION = "ENTERPRISE"; |
| 27 | const DEFAULT_AVAILABILITY = "ZONAL"; |
| 28 | const DEFAULT_ACTIVATION = "ALWAYS"; |
| 29 | const DEFAULT_DISK_TYPE = "PD_SSD"; |
| 30 | const DEFAULT_DISK_SIZE_GB = 10; |
| 31 | const MAX_NAME_LENGTH = 63; |
| 32 | /** |
| 33 | * Generated names stay short enough that the connection name |
| 34 | * `{project}:{region}:{instance}` fits Cloud Run's 97-character limit for |
| 35 | * Cloud SQL volumes (30-character project ids, 23-character regions). |
| 36 | */ |
| 37 | const GENERATED_NAME_MAX_LENGTH = 42; |
| 38 | |
| 39 | export type DatabaseFlag = { |
| 40 | /** Flag name (underscores, not hyphens). */ |
| 41 | name: string; |
| 42 | /** |
| 43 | * Flag value. Boolean flags use `on` / `off`. Omit for flags that take |
| 44 | * no value. |
| 45 | */ |
| 46 | value?: string; |
| 47 | }; |
| 48 | |
| 49 | export type IpConfiguration = { |
| 50 | /** |
| 51 | * Assign a public IPv4 address. Set `false` together with |
| 52 | * `privateNetwork` for a private-IP-only instance. |
| 53 | * @default true |
| 54 | */ |
| 55 | ipv4Enabled?: boolean; |
| 56 | /** |
| 57 | * VPC network the instance gets a private IP on. Accepts a name |
| 58 | * (`main`), a resource path (`projects/{project}/global/networks/{network}`), |
| 59 | * or a Compute self-link. The network needs private services access: an |
| 60 | * `INTERNAL` / `VPC_PEERING` `GCP.Compute.GlobalAddress` range and a |
| 61 | * `GCP.ServiceNetworking.Connection` to it. Cloud SQL can move an instance |
| 62 | * to another network but cannot remove private IP once set, so dropping |
| 63 | * this prop leaves the observed network in place. |
| 64 | */ |
| 65 | privateNetwork?: string; |
| 66 | /** |
| 67 | * Name of the allocated `VPC_PEERING` range to take the private IP from |
| 68 | * (`google-managed-services-default`, or a `GlobalAddress`'s |
| 69 | * `addressName`). When omitted, Cloud SQL picks any range reserved for |
| 70 | * the connection. |
| 71 | */ |
| 72 | allocatedIpRange?: string; |
| 73 | /** |
| 74 | * How SSL/TLS is enforced on database connections: |
| 75 | * `ALLOW_UNENCRYPTED_AND_ENCRYPTED`, `ENCRYPTED_ONLY`, or |
| 76 | * `TRUSTED_CLIENT_CERTIFICATE_REQUIRED` (client certificates from |
| 77 | * `GCP.SQL.SslCert`). The legacy `requireSsl` flag is set to match. |
| 78 | * @default Cloud SQL's default, `ALLOW_UNENCRYPTED_AND_ENCRYPTED` |
| 79 | */ |
| 80 | sslMode?: sqladmin.IpConfigurationSslModeEnum | (string & {}); |
| 81 | }; |
| 82 | |
| 83 | export type BackupSettings = { |
| 84 | /** |
| 85 | * Enable automated daily backups. MySQL also enables binary logs and |
| 86 | * PostgreSQL point-in-time recovery when true. |
| 87 | * @default false |
| 88 | */ |
| 89 | enabled?: boolean; |
| 90 | /** |
| 91 | * Number of automated backups to retain (1–365). |
| 92 | * @default 7 |
| 93 | */ |
| 94 | retainedBackups?: number; |
| 95 | /** |
| 96 | * Days of transaction logs kept for point-in-time restore (1–7 on |
| 97 | * `ENTERPRISE`, up to 35 on `ENTERPRISE_PLUS`). |
| 98 | * @default 7 |
| 99 | */ |
| 100 | transactionLogRetentionDays?: number; |
| 101 | /** |
| 102 | * Start of the daily backup window, UTC `HH:MM` (`03:00`). |
| 103 | */ |
| 104 | startTime?: string; |
| 105 | }; |
| 106 | |
| 107 | export type InstanceProps = { |
| 108 | /** |
| 109 | * Cloud SQL instance id (the `{instance}` segment of |
| 110 | * `projects/{project}/instances/{instance}`). If omitted, a unique name |
| 111 | * is generated from the stack, stage, and logical id. Must start with a |
| 112 | * letter, contain only lowercase letters, numbers, and hyphens, and not |
| 113 | * end with a hyphen (1–98 characters). Immutable — changing it replaces |
| 114 | * the instance. |
| 115 | */ |
| 116 | instanceName?: string; |
| 117 | /** |
| 118 | * Region (`us-central1`, `us-east1`, …). Immutable — changing it |
| 119 | * replaces the instance. `US-CENTRAL1` is accepted and normalized to |
| 120 | * `us-central1`. |
| 121 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 122 | */ |
| 123 | region?: string; |
| 124 | /** |
| 125 | * Database engine and major version (`MYSQL_8_0`, `POSTGRES_15`, …). |
| 126 | * Changing the version within the same engine (`POSTGRES_16` → |
| 127 | * `POSTGRES_17`) runs an in-place major version upgrade. Changing the |
| 128 | * engine (`MYSQL_8_0` → `POSTGRES_17`) replaces the instance. |
| 129 | * @default "MYSQL_8_0" |
| 130 | */ |
| 131 | databaseVersion?: sqladmin.DatabaseInstanceDatabaseVersionEnum | (string & {}); |
| 132 | /** |
| 133 | * Machine type (`db-f1-micro`, `db-custom-1-3840`, …). Changing it |
| 134 | * restarts the instance. |
| 135 | * @default "db-f1-micro" |
| 136 | */ |
| 137 | tier?: string; |
| 138 | /** |
| 139 | * Edition (`ENTERPRISE`, `ENTERPRISE_PLUS`, `DEVELOPER`). |
| 140 | * @default "ENTERPRISE" |
| 141 | */ |
| 142 | edition?: sqladmin.SettingsEditionEnum | (string & {}); |
| 143 | /** |
| 144 | * User labels. Alchemy ownership labels are merged in automatically |
| 145 | * onto `settings.userLabels`. |
| 146 | */ |
| 147 | labels?: Record<string, string>; |
| 148 | /** |
| 149 | * Preferred Compute Engine zone (`us-central1-a`). Changing it may |
| 150 | * restart the instance. |
| 151 | */ |
| 152 | zone?: string; |
| 153 | /** |
| 154 | * High-availability type. `REGIONAL` requires backups. |
| 155 | * @default "ZONAL" |
| 156 | */ |
| 157 | availabilityType?: sqladmin.SettingsAvailabilityTypeEnum | (string & {}); |
| 158 | /** |
| 159 | * When the instance is activated. `NEVER` stops it. |
| 160 | * @default "ALWAYS" |
| 161 | */ |
| 162 | activationPolicy?: sqladmin.SettingsActivationPolicyEnum | (string & {}); |
| 163 | /** |
| 164 | * Data disk size in GiB. Minimum 10. May only increase after create. |
| 165 | * @default 10 |
| 166 | */ |
| 167 | dataDiskSizeGb?: number; |
| 168 | /** |
| 169 | * Data disk type (`PD_SSD`, `PD_HDD`). |
| 170 | * @default "PD_SSD" |
| 171 | */ |
| 172 | dataDiskType?: sqladmin.SettingsDataDiskTypeEnum | (string & {}); |
| 173 | /** |
| 174 | * Public IP, private IP, and SSL settings. Fields left unset keep their |
| 175 | * observed values. |
| 176 | */ |
| 177 | ipConfiguration?: IpConfiguration; |
| 178 | /** |
| 179 | * Automated backup settings. Fields left unset keep their observed |
| 180 | * values. |
| 181 | */ |
| 182 | backup?: BackupSettings; |
| 183 | /** |
| 184 | * Grow the data disk automatically when it nears capacity. A grown disk |
| 185 | * cannot shrink back. |
| 186 | * @default false |
| 187 | */ |
| 188 | storageAutoResize?: boolean; |
| 189 | /** |
| 190 | * Protect against accidental instance deletion. While enabled, destroy |
| 191 | * and replacement fail with `InstanceDeletionProtected`; set it to |
| 192 | * `false` and deploy before removing the instance. |
| 193 | * @default false |
| 194 | */ |
| 195 | deletionProtectionEnabled?: boolean; |
| 196 | /** |
| 197 | * Database flags passed at instance startup. |
| 198 | */ |
| 199 | databaseFlags?: DatabaseFlag[]; |
| 200 | /** |
| 201 | * Allow Cloud SQL `instances.executeSql`. Required for `ExecuteSql`. |
| 202 | * @default false |
| 203 | */ |
| 204 | dataApiAccess?: boolean; |
| 205 | /** |
| 206 | * Initial root password. Create-only. Required to connect to |
| 207 | * PostgreSQL. |
| 208 | */ |
| 209 | rootPassword?: string; |
| 210 | }; |
| 211 | |
| 212 | export type Instance = Resource< |
| 213 | "GCP.SQL.Instance", |
| 214 | InstanceProps, |
| 215 | { |
| 216 | /** Cloud SQL instance id. */ |
| 217 | instanceName: string; |
| 218 | /** Project id. */ |
| 219 | project: string; |
| 220 | /** Region (`us-central1`, …). */ |
| 221 | region: string; |
| 222 | /** Database engine and version. */ |
| 223 | databaseVersion: string | undefined; |
| 224 | /** Installed version including minor, if reported. */ |
| 225 | databaseInstalledVersion: string | undefined; |
| 226 | /** Machine type. */ |
| 227 | tier: string | undefined; |
| 228 | /** Edition (`ENTERPRISE`, …). */ |
| 229 | edition: string | undefined; |
| 230 | /** Serving state (`RUNNABLE`, `PENDING_CREATE`, …). */ |
| 231 | state: string | undefined; |
| 232 | /** User labels (Alchemy ownership labels stripped). */ |
| 233 | labels: Record<string, string>; |
| 234 | /** Connection name `project:region:instance`. */ |
| 235 | connectionName: string | undefined; |
| 236 | /** Preferred / current GCE zone. */ |
| 237 | gceZone: string | undefined; |
| 238 | /** Public IPv4, if any. */ |
| 239 | ipAddress: string | undefined; |
| 240 | /** Private IP on `privateNetwork`, if any. */ |
| 241 | privateIpAddress: string | undefined; |
| 242 | /** Whether public IPv4 is enabled. */ |
| 243 | ipv4Enabled: boolean; |
| 244 | /** VPC network path of the private IP, if any. */ |
| 245 | privateNetwork: string | undefined; |
| 246 | /** SSL/TLS enforcement mode. */ |
| 247 | sslMode: string | undefined; |
| 248 | /** Whether deletion protection is enabled. */ |
| 249 | deletionProtectionEnabled: boolean; |
| 250 | /** Activation policy (`ALWAYS`, `NEVER`, …). */ |
| 251 | activationPolicy: string | undefined; |
| 252 | /** Availability type (`ZONAL`, `REGIONAL`). */ |
| 253 | availabilityType: string | undefined; |
| 254 | /** Data disk size in GiB. */ |
| 255 | dataDiskSizeGb: number | undefined; |
| 256 | /** Whether automated backups are enabled. */ |
| 257 | backupEnabled: boolean; |
| 258 | /** Number of automated backups retained. */ |
| 259 | retainedBackups: number | undefined; |
| 260 | /** Days of transaction logs retained for point-in-time restore. */ |
| 261 | transactionLogRetentionDays: number | undefined; |
| 262 | /** Whether the data disk grows automatically. */ |
| 263 | storageAutoResize: boolean; |
| 264 | /** Service account email used by the instance. */ |
| 265 | serviceAccountEmailAddress: string | undefined; |
| 266 | /** SQL Admin self-link. */ |
| 267 | selfLink: string | undefined; |
| 268 | /** RFC3339 creation timestamp. */ |
| 269 | createTime: string | undefined; |
| 270 | }, |
| 271 | never, |
| 272 | Providers |
| 273 | >; |
| 274 | |
| 275 | /** |
| 276 | * A Cloud SQL database instance. |
| 277 | * |
| 278 | * Changing `instanceName`, `region`, or the `databaseVersion` engine |
| 279 | * replaces the instance; a major version upgrade within the same engine |
| 280 | * runs in place. Provisioning typically takes several minutes (often 5–15). |
| 281 | * |
| 282 | * ### Creating an Instance |
| 283 | * **Example:** Generated name, MySQL 8.0 shared-core |
| 284 | * ```typescript |
| 285 | * const db = yield* GCP.SQL.Instance("AppDb", {}); |
| 286 | * ``` |
| 287 | * |
| 288 | * **Example:** Explicit name, labels, and backups off |
| 289 | * ```typescript |
| 290 | * const db = yield* GCP.SQL.Instance("AppDb", { |
| 291 | * instanceName: "app-db", |
| 292 | * region: "us-central1", |
| 293 | * databaseVersion: "MYSQL_8_0", |
| 294 | * tier: "db-f1-micro", |
| 295 | * labels: { env: "prod" }, |
| 296 | * backup: { enabled: false }, |
| 297 | * deletionProtectionEnabled: false, |
| 298 | * }); |
| 299 | * ``` |
| 300 | * |
| 301 | * ### PostgreSQL |
| 302 | * **Example:** Postgres 15 with a root password |
| 303 | * ```typescript |
| 304 | * const db = yield* GCP.SQL.Instance("AppDb", { |
| 305 | * databaseVersion: "POSTGRES_15", |
| 306 | * rootPassword: "change-me", |
| 307 | * tier: "db-f1-micro", |
| 308 | * }); |
| 309 | * ``` |
| 310 | * |
| 311 | * ### Private IP and SSL |
| 312 | * **Example:** Private-IP-only Postgres over private services access |
| 313 | * ```typescript |
| 314 | * const network = yield* GCP.Compute.Network("Vpc", { |
| 315 | * autoCreateSubnetworks: false, |
| 316 | * }); |
| 317 | * const range = yield* GCP.Compute.GlobalAddress("PsaRange", { |
| 318 | * addressType: "INTERNAL", |
| 319 | * purpose: "VPC_PEERING", |
| 320 | * network: network.selfLink, |
| 321 | * prefixLength: 20, |
| 322 | * }); |
| 323 | * const psa = yield* GCP.ServiceNetworking.Connection("Psa", { |
| 324 | * network: network.networkName, |
| 325 | * reservedPeeringRanges: [range.addressName], |
| 326 | * }); |
| 327 | * const db = yield* GCP.SQL.Instance("Control", { |
| 328 | * databaseVersion: "POSTGRES_17", |
| 329 | * tier: "db-custom-2-8192", |
| 330 | * ipConfiguration: { |
| 331 | * ipv4Enabled: false, |
| 332 | * privateNetwork: psa.network, |
| 333 | * sslMode: "ENCRYPTED_ONLY", |
| 334 | * }, |
| 335 | * }); |
| 336 | * // db.privateIpAddress is reachable from inside the VPC |
| 337 | * ``` |
| 338 | * |
| 339 | * ### Backups and Storage |
| 340 | * **Example:** Retained backups, PITR log retention, and disk auto-resize |
| 341 | * ```typescript |
| 342 | * const db = yield* GCP.SQL.Instance("AppDb", { |
| 343 | * databaseVersion: "POSTGRES_17", |
| 344 | * backup: { |
| 345 | * enabled: true, |
| 346 | * retainedBackups: 14, |
| 347 | * transactionLogRetentionDays: 7, |
| 348 | * startTime: "03:00", |
| 349 | * }, |
| 350 | * storageAutoResize: true, |
| 351 | * }); |
| 352 | * ``` |
| 353 | * |
| 354 | * @resource |
| 355 | * @category SQL |
| 356 | */ |
| 357 | export const Instance = Resource<Instance>("GCP.SQL.Instance"); |
| 358 | |
| 359 | export class InstanceNotResolved extends Data.TaggedError("GCP.SQL.InstanceNotResolved")<{ |
| 360 | instanceName: string; |
| 361 | project: string; |
| 362 | }> {} |
| 363 | |
| 364 | export class InstanceNotReady extends Data.TaggedError("GCP.SQL.InstanceNotReady")<{ |
| 365 | instanceName: string; |
| 366 | state: string; |
| 367 | }> {} |
| 368 | |
| 369 | export class InstanceFailed extends Data.TaggedError("GCP.SQL.InstanceFailed")<{ |
| 370 | instanceName: string; |
| 371 | state: string; |
| 372 | }> {} |
| 373 | |
| 374 | export class InstanceStillExists extends Data.TaggedError("GCP.SQL.InstanceStillExists")<{ |
| 375 | instanceName: string; |
| 376 | }> {} |
| 377 | |
| 378 | export class InstanceDeletionProtected extends Data.TaggedError( |
| 379 | "GCP.SQL.InstanceDeletionProtected", |
| 380 | )<{ |
| 381 | instanceName: string; |
| 382 | }> {} |
| 383 | |
| 384 | const lastSegment = (value: string | undefined): string => { |
| 385 | if (value === undefined || value.length === 0) return ""; |
| 386 | const trimmed = value.replace(/\/+$/, ""); |
| 387 | const parts = trimmed.split("/"); |
| 388 | return parts[parts.length - 1] ?? value; |
| 389 | }; |
| 390 | |
| 391 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 392 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 393 | |
| 394 | const normalizeVersion = (version: string | undefined) => |
| 395 | (version ?? DEFAULT_DATABASE_VERSION).toUpperCase(); |
| 396 | |
| 397 | const engineOf = (version: string) => version.split("_")[0]; |
| 398 | |
| 399 | const normalizeTier = (tier: string | undefined) => tier ?? DEFAULT_TIER; |
| 400 | |
| 401 | const normalizeEdition = (edition: string | undefined) => |
| 402 | (edition ?? DEFAULT_EDITION).toUpperCase(); |
| 403 | |
| 404 | const normalizeAvailability = (value: string | undefined) => |
| 405 | (value ?? DEFAULT_AVAILABILITY).toUpperCase(); |
| 406 | |
| 407 | const normalizeActivation = (value: string | undefined) => |
| 408 | (value ?? DEFAULT_ACTIVATION).toUpperCase(); |
| 409 | |
| 410 | const normalizeDiskType = (value: string | undefined) => (value ?? DEFAULT_DISK_TYPE).toUpperCase(); |
| 411 | |
| 412 | const isMysql = (version: string) => version.toUpperCase().startsWith("MYSQL_"); |
| 413 | |
| 414 | const isPostgres = (version: string) => version.toUpperCase().startsWith("POSTGRES_"); |
| 415 | |
| 416 | const rfc1035 = (name: string): string => { |
| 417 | let next = name |
| 418 | .toLowerCase() |
| 419 | .replace(/[^a-z0-9-]/g, "-") |
| 420 | .replace(/-+/g, "-") |
| 421 | .replace(/^-+|-+$/g, ""); |
| 422 | if (!/^[a-z]/.test(next)) next = `s${next}`; |
| 423 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 424 | if (next.length === 0) return "instance"; |
| 425 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 426 | return next.slice(0, MAX_NAME_LENGTH); |
| 427 | }; |
| 428 | |
| 429 | const userLabels = ( |
| 430 | labels: Record<string, string | undefined> | null | undefined, |
| 431 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 432 | |
| 433 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 434 | Effect.gen(function* () { |
| 435 | return ( |
| 436 | name ?? |
| 437 | existing ?? |
| 438 | rfc1035( |
| 439 | yield* createPhysicalName({ |
| 440 | id, |
| 441 | maxLength: GENERATED_NAME_MAX_LENGTH, |
| 442 | lowercase: true, |
| 443 | }), |
| 444 | ) |
| 445 | ); |
| 446 | }); |
| 447 | |
| 448 | const flagsKey = (flags: sqladmin.DatabaseFlagsList | undefined) => |
| 449 | JSON.stringify([...(flags ?? [])].map((flag) => `${flag.name ?? ""}=${flag.value ?? ""}`).sort()); |
| 450 | |
| 451 | const diskSizeOf = (value: string | number | undefined) => { |
| 452 | if (value === undefined) return undefined; |
| 453 | const parsed = typeof value === "number" ? value : Number(value); |
| 454 | return Number.isFinite(parsed) ? parsed : undefined; |
| 455 | }; |
| 456 | |
| 457 | const primaryIp = (instance: sqladmin.DatabaseInstance) => |
| 458 | instance.ipAddresses?.find((item) => item.type === "PRIMARY")?.ipAddress; |
| 459 | |
| 460 | const privateIp = (instance: sqladmin.DatabaseInstance) => |
| 461 | instance.ipAddresses?.find((item) => item.type === "PRIVATE")?.ipAddress; |
| 462 | |
| 463 | /** |
| 464 | * Normalize a network name, path, or self-link to |
| 465 | * `projects/{projectId}/global/networks/{network}`. Cloud SQL rejects a |
| 466 | * project number, which Service Networking paths carry, so a numeric |
| 467 | * project is resolved to its id. |
| 468 | */ |
| 469 | const resolveNetworkPath = Effect.fn(function* (value: string | undefined, project: string) { |
| 470 | if (value === undefined || value.length === 0) return undefined; |
| 471 | const match = /projects\/([^/]+)\/global\/networks\/([^/]+)/.exec(value); |
| 472 | if (!match) return `projects/${project}/global/networks/${lastSegment(value)}`; |
| 473 | const [, owner, network] = match; |
| 474 | if (!/^\d+$/.test(owner)) return `projects/${owner}/global/networks/${network}`; |
| 475 | const resolved = yield* resourcemanager.getProjects({ name: `projects/${owner}` }); |
| 476 | return `projects/${resolved.projectId ?? project}/global/networks/${network}`; |
| 477 | }); |
| 478 | |
| 479 | /** `requireSsl` must pair with `sslMode` (only certificate-required, or SQL Server encrypted-only, is true). */ |
| 480 | const requireSslOf = (sslMode: string, version: string) => |
| 481 | sslMode === "TRUSTED_CLIENT_CERTIFICATE_REQUIRED" || |
| 482 | (sslMode === "ENCRYPTED_ONLY" && version.toUpperCase().startsWith("SQLSERVER_")); |
| 483 | |
| 484 | const toAttrs = (instance: sqladmin.DatabaseInstance, project: string, defaultRegion: string) => { |
| 485 | const settings = instance.settings; |
| 486 | return { |
| 487 | instanceName: instance.name ?? "", |
| 488 | project: instance.project ?? project, |
| 489 | region: normalizeRegion(instance.region, defaultRegion), |
| 490 | databaseVersion: instance.databaseVersion, |
| 491 | databaseInstalledVersion: instance.databaseInstalledVersion, |
| 492 | tier: settings?.tier, |
| 493 | edition: settings?.edition, |
| 494 | state: instance.state, |
| 495 | labels: userLabels(settings?.userLabels), |
| 496 | connectionName: instance.connectionName, |
| 497 | gceZone: instance.gceZone ?? settings?.locationPreference?.zone, |
| 498 | ipAddress: primaryIp(instance), |
| 499 | privateIpAddress: privateIp(instance), |
| 500 | ipv4Enabled: settings?.ipConfiguration?.ipv4Enabled !== false, |
| 501 | privateNetwork: settings?.ipConfiguration?.privateNetwork, |
| 502 | sslMode: settings?.ipConfiguration?.sslMode, |
| 503 | deletionProtectionEnabled: settings?.deletionProtectionEnabled === true, |
| 504 | activationPolicy: settings?.activationPolicy, |
| 505 | availabilityType: settings?.availabilityType, |
| 506 | dataDiskSizeGb: diskSizeOf(settings?.dataDiskSizeGb), |
| 507 | backupEnabled: settings?.backupConfiguration?.enabled === true, |
| 508 | retainedBackups: settings?.backupConfiguration?.backupRetentionSettings?.retainedBackups, |
| 509 | transactionLogRetentionDays: settings?.backupConfiguration?.transactionLogRetentionDays, |
| 510 | storageAutoResize: settings?.storageAutoResize === true, |
| 511 | serviceAccountEmailAddress: instance.serviceAccountEmailAddress, |
| 512 | selfLink: instance.selfLink, |
| 513 | createTime: instance.createTime, |
| 514 | }; |
| 515 | }; |
| 516 | |
| 517 | const getByName = (project: string, instance: string) => |
| 518 | sqladmin |
| 519 | .getInstances({ project, instance }) |
| 520 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 521 | |
| 522 | /** |
| 523 | * Instance create, patch, and delete operations routinely run 5–15 |
| 524 | * minutes; poll every 10s for up to 20 minutes. |
| 525 | */ |
| 526 | const LONG_OPERATION_POLL = { |
| 527 | times: 120, |
| 528 | schedule: Schedule.spaced("10 seconds"), |
| 529 | }; |
| 530 | |
| 531 | const waitForOperation = (project: string, operation: sqladmin.Operation) => |
| 532 | waitForSqlOperation(project, operation, { |
| 533 | budget: "30 minutes", |
| 534 | notFoundOk: true, |
| 535 | }); |
| 536 | |
| 537 | const waitUntilExists = (project: string, instanceName: string) => |
| 538 | getByName(project, instanceName).pipe( |
| 539 | Effect.flatMap((instance) => |
| 540 | instance |
| 541 | ? Effect.succeed(instance) |
| 542 | : Effect.fail(new InstanceNotResolved({ instanceName, project })), |
| 543 | ), |
| 544 | Effect.retry({ |
| 545 | while: (error) => error._tag === "GCP.SQL.InstanceNotResolved", |
| 546 | times: 8, |
| 547 | schedule: Schedule.spaced("2 seconds"), |
| 548 | }), |
| 549 | ); |
| 550 | |
| 551 | const waitUntilRunnable = (project: string, instanceName: string) => |
| 552 | getByName(project, instanceName).pipe( |
| 553 | Effect.filterOrFail( |
| 554 | (instance): instance is sqladmin.DatabaseInstance => instance !== undefined, |
| 555 | () => new InstanceNotResolved({ instanceName, project }), |
| 556 | ), |
| 557 | Effect.filterOrFail( |
| 558 | (instance) => { |
| 559 | const state = instance.state ?? "SQL_INSTANCE_STATE_UNSPECIFIED"; |
| 560 | return state === "RUNNABLE" || state === "SUSPENDED"; |
| 561 | }, |
| 562 | (instance) => { |
| 563 | const state = instance.state ?? "SQL_INSTANCE_STATE_UNSPECIFIED"; |
| 564 | return state === "FAILED" |
| 565 | ? new InstanceFailed({ instanceName, state }) |
| 566 | : new InstanceNotReady({ instanceName, state }); |
| 567 | }, |
| 568 | ), |
| 569 | Effect.retry({ |
| 570 | while: (error) => |
| 571 | error._tag === "GCP.SQL.InstanceNotReady" || error._tag === "GCP.SQL.InstanceNotResolved", |
| 572 | ...LONG_OPERATION_POLL, |
| 573 | }), |
| 574 | ); |
| 575 | |
| 576 | const waitUntilGone = (project: string, instanceName: string) => |
| 577 | getByName(project, instanceName).pipe( |
| 578 | Effect.flatMap((instance) => |
| 579 | instance === undefined ? Effect.void : Effect.fail(new InstanceStillExists({ instanceName })), |
| 580 | ), |
| 581 | Effect.retry({ |
| 582 | while: (error) => error._tag === "GCP.SQL.InstanceStillExists", |
| 583 | ...LONG_OPERATION_POLL, |
| 584 | }), |
| 585 | ); |
| 586 | |
| 587 | const backupConfiguration = ( |
| 588 | enabled: boolean, |
| 589 | version: string, |
| 590 | backup: BackupSettings | undefined, |
| 591 | ): sqladmin.BackupConfiguration => ({ |
| 592 | enabled, |
| 593 | binaryLogEnabled: enabled && isMysql(version), |
| 594 | pointInTimeRecoveryEnabled: enabled && isPostgres(version), |
| 595 | backupRetentionSettings: |
| 596 | backup?.retainedBackups !== undefined |
| 597 | ? { retentionUnit: "COUNT", retainedBackups: backup.retainedBackups } |
| 598 | : undefined, |
| 599 | transactionLogRetentionDays: backup?.transactionLogRetentionDays, |
| 600 | startTime: backup?.startTime, |
| 601 | }); |
| 602 | |
| 603 | const ipConfigurationOf = ( |
| 604 | ip: IpConfiguration | undefined, |
| 605 | privateNetwork: string | undefined, |
| 606 | version: string, |
| 607 | ): sqladmin.IpConfiguration => ({ |
| 608 | ipv4Enabled: ip?.ipv4Enabled !== false, |
| 609 | privateNetwork, |
| 610 | allocatedIpRange: ip?.allocatedIpRange, |
| 611 | sslMode: ip?.sslMode, |
| 612 | requireSsl: ip?.sslMode !== undefined ? requireSslOf(ip.sslMode, version) : undefined, |
| 613 | }); |
| 614 | |
| 615 | const dataApiAccessOf = (enabled: boolean | undefined) => { |
| 616 | if (enabled === true) return "ALLOW_DATA_API"; |
| 617 | if (enabled === false) return "DISALLOW_DATA_API"; |
| 618 | return undefined; |
| 619 | }; |
| 620 | |
| 621 | const insertBody = ( |
| 622 | news: InstanceProps, |
| 623 | privateNetwork: string | undefined, |
| 624 | instanceName: string, |
| 625 | region: string, |
| 626 | version: string, |
| 627 | desiredLabels: Record<string, string>, |
| 628 | ): sqladmin.DatabaseInstance => { |
| 629 | const backupEnabled = news.backup?.enabled === true; |
| 630 | return { |
| 631 | name: instanceName, |
| 632 | region, |
| 633 | databaseVersion: version, |
| 634 | rootPassword: news.rootPassword, |
| 635 | settings: { |
| 636 | tier: normalizeTier(news.tier), |
| 637 | edition: normalizeEdition(news.edition), |
| 638 | activationPolicy: normalizeActivation(news.activationPolicy), |
| 639 | availabilityType: normalizeAvailability(news.availabilityType), |
| 640 | dataDiskSizeGb: String(news.dataDiskSizeGb ?? DEFAULT_DISK_SIZE_GB), |
| 641 | dataDiskType: normalizeDiskType(news.dataDiskType), |
| 642 | deletionProtectionEnabled: news.deletionProtectionEnabled === true, |
| 643 | userLabels: desiredLabels, |
| 644 | storageAutoResize: news.storageAutoResize === true, |
| 645 | ipConfiguration: ipConfigurationOf(news.ipConfiguration, privateNetwork, version), |
| 646 | backupConfiguration: backupConfiguration(backupEnabled, version, news.backup), |
| 647 | locationPreference: news.zone ? { zone: news.zone } : undefined, |
| 648 | databaseFlags: news.databaseFlags, |
| 649 | dataApiAccess: dataApiAccessOf(news.dataApiAccess), |
| 650 | }, |
| 651 | }; |
| 652 | }; |
| 653 | |
| 654 | const applyPatch = (project: string, instanceName: string, body: sqladmin.DatabaseInstance) => |
| 655 | sqladmin |
| 656 | .patchInstances({ |
| 657 | project, |
| 658 | instance: instanceName, |
| 659 | body, |
| 660 | }) |
| 661 | .pipe( |
| 662 | Effect.retry({ |
| 663 | while: (error) => error._tag === "Conflict", |
| 664 | times: 8, |
| 665 | schedule: Schedule.spaced("5 seconds"), |
| 666 | }), |
| 667 | ); |
| 668 | |
| 669 | export const InstanceProvider = () => |
| 670 | Provider.succeed(Instance, { |
| 671 | stables: [ |
| 672 | "instanceName", |
| 673 | "project", |
| 674 | "region", |
| 675 | "databaseVersion", |
| 676 | "connectionName", |
| 677 | "selfLink", |
| 678 | "createTime", |
| 679 | ], |
| 680 | |
| 681 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 682 | if (!isResolved(news)) return undefined; |
| 683 | const env = yield* GcpEnvironment.current; |
| 684 | |
| 685 | const previousName = olds?.instanceName ?? output?.instanceName; |
| 686 | const nextName = news.instanceName ?? previousName; |
| 687 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 688 | const nextRegion = normalizeRegion(news.region ?? output?.region, env.region); |
| 689 | const previousVersion = normalizeVersion(olds?.databaseVersion ?? output?.databaseVersion); |
| 690 | const nextVersion = normalizeVersion(news.databaseVersion ?? output?.databaseVersion); |
| 691 | |
| 692 | const nameChanged = |
| 693 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 694 | const regionChanged = previousRegion !== nextRegion; |
| 695 | const versionChanged = previousVersion !== nextVersion; |
| 696 | |
| 697 | if (!nameChanged && !regionChanged && !versionChanged) { |
| 698 | return undefined; |
| 699 | } |
| 700 | if (!nameChanged && !regionChanged && engineOf(previousVersion) === engineOf(nextVersion)) { |
| 701 | // Same-engine major version upgrades run in place via instances.patch. |
| 702 | return { |
| 703 | action: "update" as const, |
| 704 | stables: [ |
| 705 | "instanceName", |
| 706 | "project", |
| 707 | "region", |
| 708 | "connectionName", |
| 709 | "selfLink", |
| 710 | "createTime", |
| 711 | ], |
| 712 | }; |
| 713 | } |
| 714 | return { |
| 715 | action: "replace" as const, |
| 716 | deleteFirst: !nameChanged, |
| 717 | }; |
| 718 | }), |
| 719 | |
| 720 | read: Effect.fn(function* ({ id, olds, output }) { |
| 721 | const env = yield* GcpEnvironment.current; |
| 722 | const instanceName = yield* toName(id, olds?.instanceName, output?.instanceName); |
| 723 | const existing = yield* getByName(env.project, instanceName); |
| 724 | if (existing === undefined) return undefined; |
| 725 | const attrs = toAttrs(existing, env.project, env.region); |
| 726 | return (yield* hasAlchemyLabels(id, tagRecord(existing.settings?.userLabels))) |
| 727 | ? attrs |
| 728 | : Unowned(attrs); |
| 729 | }), |
| 730 | |
| 731 | list: () => |
| 732 | Effect.gen(function* () { |
| 733 | const env = yield* GcpEnvironment.current; |
| 734 | return yield* sqladmin.listInstances |
| 735 | .items({ |
| 736 | project: env.project, |
| 737 | maxResults: 1000, |
| 738 | }) |
| 739 | .pipe( |
| 740 | Stream.filter((instance) => |
| 741 | Object.keys(instance.settings?.userLabels ?? {}).some((key) => |
| 742 | key.startsWith("alchemy-"), |
| 743 | ), |
| 744 | ), |
| 745 | Stream.map((instance) => toAttrs(instance, env.project, env.region)), |
| 746 | Stream.runCollect, |
| 747 | Effect.map((chunk) => Array.from(chunk)), |
| 748 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 749 | ); |
| 750 | }), |
| 751 | |
| 752 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 753 | const env = yield* GcpEnvironment.current; |
| 754 | const instanceName = yield* toName(id, news.instanceName, output?.instanceName); |
| 755 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 756 | const version = normalizeVersion(news.databaseVersion ?? output?.databaseVersion); |
| 757 | const desiredLabels = { |
| 758 | ...toLabels(news.labels), |
| 759 | ...(yield* createInternalLabels(id)), |
| 760 | }; |
| 761 | |
| 762 | const desiredPrivateNetwork = yield* resolveNetworkPath( |
| 763 | news.ipConfiguration?.privateNetwork, |
| 764 | env.project, |
| 765 | ); |
| 766 | |
| 767 | let current = yield* getByName(env.project, output?.instanceName ?? instanceName); |
| 768 | |
| 769 | if (current === undefined) { |
| 770 | const created = yield* sqladmin |
| 771 | .insertInstances({ |
| 772 | project: env.project, |
| 773 | body: insertBody( |
| 774 | news, |
| 775 | desiredPrivateNetwork, |
| 776 | instanceName, |
| 777 | region, |
| 778 | version, |
| 779 | desiredLabels, |
| 780 | ), |
| 781 | }) |
| 782 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 783 | if (created !== undefined) { |
| 784 | yield* waitForOperation(env.project, created); |
| 785 | } |
| 786 | current = yield* waitUntilExists(env.project, instanceName); |
| 787 | } |
| 788 | |
| 789 | if (current === undefined) { |
| 790 | return yield* new InstanceNotResolved({ |
| 791 | instanceName, |
| 792 | project: env.project, |
| 793 | }); |
| 794 | } |
| 795 | |
| 796 | const state = current.state ?? ""; |
| 797 | if (state !== "RUNNABLE" && state !== "SUSPENDED") { |
| 798 | current = yield* waitUntilRunnable(env.project, instanceName); |
| 799 | } |
| 800 | |
| 801 | if (normalizeVersion(current.databaseVersion) !== version) { |
| 802 | const upgraded = yield* applyPatch(env.project, instanceName, { |
| 803 | databaseVersion: version, |
| 804 | }); |
| 805 | // A major version upgrade outlasts the default budget even on |
| 806 | // db-f1-micro (33–54 minutes observed for POSTGRES_16 → POSTGRES_17). |
| 807 | yield* waitForSqlOperation(env.project, upgraded, { budget: "2 hours" }); |
| 808 | current = yield* waitUntilRunnable(env.project, instanceName); |
| 809 | } |
| 810 | |
| 811 | const settings = current.settings; |
| 812 | const observedLabels = tagRecord(settings?.userLabels); |
| 813 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 814 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 815 | |
| 816 | const desiredTier = normalizeTier(news.tier ?? settings?.tier); |
| 817 | const tierChanged = |
| 818 | news.tier !== undefined && (settings?.tier ?? DEFAULT_TIER) !== desiredTier; |
| 819 | |
| 820 | const desiredEdition = normalizeEdition(news.edition ?? settings?.edition); |
| 821 | const editionChanged = |
| 822 | news.edition !== undefined && |
| 823 | (settings?.edition ?? DEFAULT_EDITION).toUpperCase() !== desiredEdition; |
| 824 | |
| 825 | const desiredActivation = normalizeActivation( |
| 826 | news.activationPolicy ?? settings?.activationPolicy, |
| 827 | ); |
| 828 | const activationChanged = |
| 829 | news.activationPolicy !== undefined && |
| 830 | (settings?.activationPolicy ?? DEFAULT_ACTIVATION).toUpperCase() !== desiredActivation; |
| 831 | |
| 832 | const desiredAvailability = normalizeAvailability( |
| 833 | news.availabilityType ?? settings?.availabilityType, |
| 834 | ); |
| 835 | const availabilityChanged = |
| 836 | news.availabilityType !== undefined && |
| 837 | (settings?.availabilityType ?? DEFAULT_AVAILABILITY).toUpperCase() !== desiredAvailability; |
| 838 | |
| 839 | const desiredProtection = news.deletionProtectionEnabled === true; |
| 840 | const protectionChanged = |
| 841 | (settings?.deletionProtectionEnabled === true) !== desiredProtection; |
| 842 | |
| 843 | const ip = news.ipConfiguration; |
| 844 | const observedIp = settings?.ipConfiguration; |
| 845 | const desiredSslMode = ip?.sslMode?.toUpperCase(); |
| 846 | const ipConfiguration: sqladmin.IpConfiguration = { |
| 847 | ipv4Enabled: |
| 848 | ip?.ipv4Enabled !== undefined && (observedIp?.ipv4Enabled !== false) !== ip.ipv4Enabled |
| 849 | ? ip.ipv4Enabled |
| 850 | : undefined, |
| 851 | privateNetwork: |
| 852 | desiredPrivateNetwork !== undefined && |
| 853 | /projects\/[^/]+\/global\/networks\/[^/]+/.exec(observedIp?.privateNetwork ?? "")?.[0] !== |
| 854 | desiredPrivateNetwork |
| 855 | ? desiredPrivateNetwork |
| 856 | : undefined, |
| 857 | allocatedIpRange: |
| 858 | ip?.allocatedIpRange !== undefined && observedIp?.allocatedIpRange !== ip.allocatedIpRange |
| 859 | ? ip.allocatedIpRange |
| 860 | : undefined, |
| 861 | ...(desiredSslMode !== undefined && observedIp?.sslMode !== desiredSslMode |
| 862 | ? { sslMode: desiredSslMode, requireSsl: requireSslOf(desiredSslMode, version) } |
| 863 | : {}), |
| 864 | }; |
| 865 | const ipChanged = Object.values(ipConfiguration).some((value) => value !== undefined); |
| 866 | |
| 867 | const backup = news.backup; |
| 868 | const observedBackup = settings?.backupConfiguration; |
| 869 | const desiredBackup = backup?.enabled ?? observedBackup?.enabled === true; |
| 870 | const backupChanged = |
| 871 | (backup?.enabled !== undefined && (observedBackup?.enabled === true) !== desiredBackup) || |
| 872 | (backup?.retainedBackups !== undefined && |
| 873 | observedBackup?.backupRetentionSettings?.retainedBackups !== backup.retainedBackups) || |
| 874 | (backup?.transactionLogRetentionDays !== undefined && |
| 875 | observedBackup?.transactionLogRetentionDays !== backup.transactionLogRetentionDays) || |
| 876 | (backup?.startTime !== undefined && observedBackup?.startTime !== backup.startTime); |
| 877 | |
| 878 | const autoResizeChanged = |
| 879 | news.storageAutoResize !== undefined && |
| 880 | (settings?.storageAutoResize === true) !== news.storageAutoResize; |
| 881 | |
| 882 | const desiredDisk = news.dataDiskSizeGb; |
| 883 | const currentDisk = diskSizeOf(settings?.dataDiskSizeGb); |
| 884 | const diskChanged = |
| 885 | desiredDisk !== undefined && currentDisk !== undefined && desiredDisk > currentDisk; |
| 886 | |
| 887 | const desiredZone = news.zone; |
| 888 | const zoneChanged = |
| 889 | desiredZone !== undefined && |
| 890 | (current.gceZone ?? settings?.locationPreference?.zone) !== desiredZone; |
| 891 | |
| 892 | const flagsChanged = |
| 893 | news.databaseFlags !== undefined && |
| 894 | flagsKey(settings?.databaseFlags) !== flagsKey(news.databaseFlags); |
| 895 | |
| 896 | const desiredDataApi = dataApiAccessOf(news.dataApiAccess); |
| 897 | const dataApiChanged = |
| 898 | desiredDataApi !== undefined && |
| 899 | (settings?.dataApiAccess ?? "DISALLOW_DATA_API") !== desiredDataApi; |
| 900 | |
| 901 | if ( |
| 902 | labelsChanged || |
| 903 | tierChanged || |
| 904 | editionChanged || |
| 905 | activationChanged || |
| 906 | availabilityChanged || |
| 907 | protectionChanged || |
| 908 | ipChanged || |
| 909 | backupChanged || |
| 910 | autoResizeChanged || |
| 911 | diskChanged || |
| 912 | zoneChanged || |
| 913 | flagsChanged || |
| 914 | dataApiChanged |
| 915 | ) { |
| 916 | const nextLabels: Record<string, string | null> = { |
| 917 | ...desiredLabels, |
| 918 | }; |
| 919 | for (const key of removed) { |
| 920 | nextLabels[key] = null; |
| 921 | } |
| 922 | const patched = yield* applyPatch(env.project, instanceName, { |
| 923 | settings: { |
| 924 | settingsVersion: settings?.settingsVersion, |
| 925 | userLabels: nextLabels as unknown as Record<string, string>, |
| 926 | tier: desiredTier, |
| 927 | edition: news.edition !== undefined ? desiredEdition : undefined, |
| 928 | activationPolicy: news.activationPolicy !== undefined ? desiredActivation : undefined, |
| 929 | availabilityType: news.availabilityType !== undefined ? desiredAvailability : undefined, |
| 930 | deletionProtectionEnabled: desiredProtection, |
| 931 | dataDiskSizeGb: diskChanged ? String(desiredDisk) : undefined, |
| 932 | ipConfiguration: ipChanged ? ipConfiguration : undefined, |
| 933 | backupConfiguration: backupChanged |
| 934 | ? backupConfiguration(desiredBackup, version, backup) |
| 935 | : undefined, |
| 936 | storageAutoResize: autoResizeChanged ? news.storageAutoResize : undefined, |
| 937 | locationPreference: zoneChanged ? { zone: desiredZone } : undefined, |
| 938 | databaseFlags: news.databaseFlags !== undefined ? news.databaseFlags : undefined, |
| 939 | dataApiAccess: desiredDataApi, |
| 940 | }, |
| 941 | }); |
| 942 | yield* waitForOperation(env.project, patched); |
| 943 | current = yield* waitUntilRunnable(env.project, instanceName); |
| 944 | } |
| 945 | |
| 946 | return toAttrs(current, env.project, env.region); |
| 947 | }), |
| 948 | |
| 949 | delete: Effect.fn(function* ({ output, force }) { |
| 950 | const env = yield* GcpEnvironment.current; |
| 951 | const instanceName = output.instanceName; |
| 952 | const existing = yield* getByName(env.project, instanceName); |
| 953 | if (existing === undefined) return; |
| 954 | |
| 955 | if (existing.settings?.deletionProtectionEnabled === true) { |
| 956 | if (force !== true) { |
| 957 | return yield* new InstanceDeletionProtected({ instanceName }); |
| 958 | } |
| 959 | const patched = yield* applyPatch(env.project, instanceName, { |
| 960 | settings: { |
| 961 | settingsVersion: existing.settings.settingsVersion, |
| 962 | deletionProtectionEnabled: false, |
| 963 | }, |
| 964 | }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 965 | if (patched !== undefined) { |
| 966 | yield* waitForOperation(env.project, patched); |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | const operation = yield* sqladmin |
| 971 | .deleteInstances({ |
| 972 | project: env.project, |
| 973 | instance: instanceName, |
| 974 | }) |
| 975 | .pipe( |
| 976 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 977 | Effect.retry({ |
| 978 | while: (error) => error._tag === "Conflict", |
| 979 | times: 8, |
| 980 | schedule: Schedule.spaced("5 seconds"), |
| 981 | }), |
| 982 | ); |
| 983 | if (operation !== undefined) { |
| 984 | yield* waitForOperation(env.project, operation); |
| 985 | } |
| 986 | yield* waitUntilGone(env.project, instanceName); |
| 987 | }), |
| 988 | }); |