The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { deleteObjects, reconcileObjects } from "@alchemy.run/kubernetes/Client"; |
| 2 | import type { Connection } from "@alchemy.run/kubernetes/Connection"; |
| 3 | import { |
| 4 | type KubernetesObjectBinding, |
| 5 | type KubernetesObjectDefinition, |
| 6 | type KubernetesObjectRef, |
| 7 | } from "@alchemy.run/kubernetes/Objects"; |
| 8 | import * as container from "@distilled.cloud/gcp/container_v1"; |
| 9 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 10 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 11 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 12 | import * as Provider from "alchemy/Provider"; |
| 13 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 14 | import { tagRecord } from "alchemy/Tags"; |
| 15 | import * as Data from "effect/Data"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Schedule from "effect/Schedule"; |
| 18 | import { GcpEnvironment } from "../Environment.ts"; |
| 19 | import { |
| 20 | createInternalLabels, |
| 21 | diffLabels, |
| 22 | hasAlchemyLabels, |
| 23 | stripInternalLabels, |
| 24 | toLabels, |
| 25 | } from "../Labels.ts"; |
| 26 | import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 27 | import { matchesDesired } from "../Proto.ts"; |
| 28 | import type { Providers } from "../Providers.ts"; |
| 29 | import { |
| 30 | apiServerEndpoint, |
| 31 | gkeConnectionOf, |
| 32 | makeGkeTransport, |
| 33 | workloadPoolOf, |
| 34 | } from "./KubernetesAdapter.ts"; |
| 35 | |
| 36 | // A zone, not a region: `GCP.Region` has no zone and a regional default would triple node count. |
| 37 | const DEFAULT_LOCATION = "us-central1-a"; |
| 38 | const DEFAULT_MACHINE_TYPE = "e2-medium"; |
| 39 | const DEFAULT_DISK_TYPE = "pd-standard"; |
| 40 | const DEFAULT_DISK_SIZE_GB = 20; |
| 41 | const DEFAULT_NODE_COUNT = 1; |
| 42 | const DEFAULT_POOL_NAME = "default-pool"; |
| 43 | const MAX_NAME_LENGTH = 40; |
| 44 | |
| 45 | export type ClusterProps = { |
| 46 | /** |
| 47 | * Cluster id (the `{cluster}` segment of |
| 48 | * `projects/{project}/locations/{location}/clusters/{cluster}`). If |
| 49 | * omitted, a unique RFC1035 name is generated from the stack, stage, |
| 50 | * and logical id. Must be 1-40 characters, start with a letter, and |
| 51 | * match `[a-z]([a-z0-9-]*[a-z0-9])?`. Immutable — changing it replaces |
| 52 | * the cluster. |
| 53 | */ |
| 54 | clusterId?: string; |
| 55 | /** |
| 56 | * Zone or region (`us-central1-a`, `us-central1`, …). Immutable — |
| 57 | * changing it replaces the cluster. Autopilot clusters must be |
| 58 | * regional. `US-CENTRAL1-A` is accepted and normalized to |
| 59 | * `us-central1-a`. |
| 60 | * @default "us-central1-a" |
| 61 | */ |
| 62 | location?: string; |
| 63 | /** |
| 64 | * Optional description. Immutable — changing it replaces the cluster. |
| 65 | */ |
| 66 | description?: string; |
| 67 | /** |
| 68 | * User labels stored as GKE `resourceLabels`. Alchemy ownership labels |
| 69 | * are merged in automatically. |
| 70 | */ |
| 71 | labels?: Record<string, string>; |
| 72 | /** |
| 73 | * VPC network name or URL. Immutable — changing it replaces the cluster. |
| 74 | * Defaults to the project `default` network. |
| 75 | */ |
| 76 | network?: string; |
| 77 | /** |
| 78 | * Subnetwork name or URL. Immutable — changing it replaces the cluster. |
| 79 | */ |
| 80 | subnetwork?: string; |
| 81 | /** |
| 82 | * Alias-IP allocation for Pods and Services. Secondary range names and |
| 83 | * CIDRs are create-time topology, so changing this replaces the cluster. |
| 84 | * @default `{ useIpAliases: true }` (VPC-native) |
| 85 | */ |
| 86 | ipAllocationPolicy?: container.IPAllocationPolicy; |
| 87 | /** |
| 88 | * Private control-plane and node networking. Changing private-node mode, |
| 89 | * the control-plane CIDR, or the private endpoint subnetwork replaces the |
| 90 | * cluster; `enablePrivateEndpoint` and `masterGlobalAccessConfig` update |
| 91 | * in place. |
| 92 | */ |
| 93 | privateClusterConfig?: container.PrivateClusterConfig; |
| 94 | /** |
| 95 | * Networks allowed to reach the public control-plane endpoint. |
| 96 | */ |
| 97 | masterAuthorizedNetworksConfig?: container.MasterAuthorizedNetworksConfig; |
| 98 | /** |
| 99 | * Cluster datapath implementation (`LEGACY_DATAPATH` or |
| 100 | * `ADVANCED_DATAPATH` for Dataplane V2). |
| 101 | */ |
| 102 | datapathProvider?: container.NetworkConfigDatapathProviderEnum; |
| 103 | /** |
| 104 | * Enable Shielded GKE Nodes. |
| 105 | */ |
| 106 | enableShieldedNodes?: boolean; |
| 107 | /** |
| 108 | * GKE addon configuration (HTTP load balancing, network policy, …). |
| 109 | */ |
| 110 | addonsConfig?: container.AddonsConfig; |
| 111 | /** |
| 112 | * Fine-grained cost allocation configuration. |
| 113 | */ |
| 114 | costManagementConfig?: container.CostManagementConfig; |
| 115 | /** |
| 116 | * Create an Autopilot cluster. Immutable — changing it replaces the |
| 117 | * cluster. Node pool props (`initialNodeCount`, `machineType`, …) are |
| 118 | * ignored when Autopilot is enabled. |
| 119 | * @default false |
| 120 | */ |
| 121 | autopilot?: boolean; |
| 122 | /** |
| 123 | * Initial Kubernetes version (or alias such as `"1.31"` / `"latest"`). |
| 124 | * Applied at create time only. |
| 125 | */ |
| 126 | initialClusterVersion?: string; |
| 127 | /** |
| 128 | * Logging service (`logging.googleapis.com/kubernetes` or `none`). |
| 129 | */ |
| 130 | loggingService?: string; |
| 131 | /** |
| 132 | * Components exported through Cloud Logging. |
| 133 | */ |
| 134 | loggingConfig?: container.LoggingConfig; |
| 135 | /** |
| 136 | * Monitoring service (`monitoring.googleapis.com/kubernetes` or `none`). |
| 137 | */ |
| 138 | monitoringService?: string; |
| 139 | /** |
| 140 | * Components exported through Cloud Monitoring. |
| 141 | */ |
| 142 | monitoringConfig?: container.MonitoringConfig; |
| 143 | /** |
| 144 | * Enable Kubernetes alpha APIs. The cluster is deleted after 30 days |
| 145 | * and has no SLA. Immutable — changing it replaces the cluster. |
| 146 | * @default false |
| 147 | */ |
| 148 | enableKubernetesAlpha?: boolean; |
| 149 | /** |
| 150 | * Release channel (`RAPID`, `REGULAR`, `STABLE`, `EXTENDED`). |
| 151 | */ |
| 152 | releaseChannel?: container.ReleaseChannelChannelEnum | (string & {}); |
| 153 | /** |
| 154 | * Zones in which nodes should run. Must include the cluster's primary |
| 155 | * zone for zonal clusters. |
| 156 | */ |
| 157 | nodeLocations?: string[]; |
| 158 | /** |
| 159 | * Initial node count for the default pool. Ignored on Autopilot, and on |
| 160 | * update when `removeDefaultNodePool` is set. Otherwise immutable — |
| 161 | * changing it replaces the cluster. |
| 162 | * @default 1 |
| 163 | */ |
| 164 | initialNodeCount?: number; |
| 165 | /** |
| 166 | * Machine type for the default pool. Ignored on Autopilot, and on update |
| 167 | * when `removeDefaultNodePool` is set. Otherwise immutable — changing it |
| 168 | * replaces the cluster. |
| 169 | * @default "e2-medium" |
| 170 | */ |
| 171 | machineType?: string; |
| 172 | /** |
| 173 | * Boot disk size in GB for the default pool. Ignored on Autopilot, and on |
| 174 | * update when `removeDefaultNodePool` is set. Otherwise immutable — |
| 175 | * changing it replaces the cluster. |
| 176 | * @default 20 |
| 177 | */ |
| 178 | diskSizeGb?: number; |
| 179 | /** |
| 180 | * Boot disk type for the default pool (`pd-standard`, `pd-balanced`, |
| 181 | * `pd-ssd`). Ignored on Autopilot, and on update when |
| 182 | * `removeDefaultNodePool` is set. Otherwise immutable — changing it |
| 183 | * replaces the cluster. |
| 184 | * @default "pd-standard" |
| 185 | */ |
| 186 | diskType?: string; |
| 187 | /** |
| 188 | * Use Spot VMs for the default pool. Ignored on Autopilot, and on update |
| 189 | * when `removeDefaultNodePool` is set. Otherwise immutable — changing it |
| 190 | * replaces the cluster. |
| 191 | * @default false |
| 192 | */ |
| 193 | spot?: boolean; |
| 194 | /** |
| 195 | * Use preemptible VMs for the default pool. Ignored on Autopilot, and on |
| 196 | * update when `removeDefaultNodePool` is set. Otherwise immutable — |
| 197 | * changing it replaces the cluster. |
| 198 | * @default false |
| 199 | */ |
| 200 | preemptible?: boolean; |
| 201 | /** |
| 202 | * Service account email for the default pool's nodes, or for every node |
| 203 | * Autopilot provisions. Changing it replaces the cluster unless |
| 204 | * `removeDefaultNodePool` is set. |
| 205 | * @default the Compute Engine default service account |
| 206 | */ |
| 207 | serviceAccount?: string; |
| 208 | /** |
| 209 | * OAuth scopes for the default pool's nodes, or for every node Autopilot |
| 210 | * provisions. Changing them replaces the cluster unless |
| 211 | * `removeDefaultNodePool` is set. |
| 212 | */ |
| 213 | oauthScopes?: string[]; |
| 214 | /** |
| 215 | * Delete GKE's bootstrap `default-pool` once the cluster is ready, so |
| 216 | * separately declared `NodePool` resources own every node. While set, |
| 217 | * the default-pool props above never replace the cluster. Turning it back |
| 218 | * off replaces the cluster, since GKE only creates `default-pool` at |
| 219 | * cluster creation. |
| 220 | * @default false |
| 221 | */ |
| 222 | removeDefaultNodePool?: boolean; |
| 223 | /** |
| 224 | * Refuse replacement and destruction while set. A change that would |
| 225 | * replace a protected cluster fails at plan time, so disable protection |
| 226 | * in its own deploy first. Account-wide `nuke` bypasses this guard. |
| 227 | * @default false |
| 228 | */ |
| 229 | deletionProtection?: boolean; |
| 230 | }; |
| 231 | |
| 232 | export type Cluster = Resource< |
| 233 | "GCP.Container.Cluster", |
| 234 | ClusterProps, |
| 235 | { |
| 236 | /** Full resource name `projects/{project}/locations/{location}/clusters/{cluster}`. */ |
| 237 | name: string; |
| 238 | /** Cluster id (last path segment). */ |
| 239 | clusterId: string; |
| 240 | /** Project id. */ |
| 241 | project: string; |
| 242 | /** Zone or region id. */ |
| 243 | location: string; |
| 244 | /** Server-assigned unique cluster id. */ |
| 245 | clusterUid: string | undefined; |
| 246 | /** Current status (`RUNNING`, `PROVISIONING`, …). */ |
| 247 | status: string | undefined; |
| 248 | /** Kubernetes API server endpoint URL. */ |
| 249 | endpoint: string | undefined; |
| 250 | /** |
| 251 | * Base64-encoded cluster CA from |
| 252 | * `masterAuth.clusterCaCertificate`. |
| 253 | */ |
| 254 | certificateAuthorityData: string | undefined; |
| 255 | /** |
| 256 | * The cluster-agnostic `Kubernetes.Connection` for this cluster. |
| 257 | * Passing the whole cluster resource as a `Kubernetes.*` workload's |
| 258 | * `cluster` prop resolves through this — auth uses Google OAuth |
| 259 | * bearer tokens minted from the ambient GCP credentials. |
| 260 | */ |
| 261 | connection: Connection; |
| 262 | /** References to Kubernetes objects applied via the binding contract. */ |
| 263 | kubernetesObjects: KubernetesObjectRef[]; |
| 264 | /** |
| 265 | * Workload Identity pool (`{project}.svc.id.goog`) when enabled. |
| 266 | * Distilled has no IAM v1, so GSA CRUD is out of band; Alchemy still |
| 267 | * enables WI on the cluster and annotates KSAs when |
| 268 | * `identity.gcpServiceAccount` is set. |
| 269 | */ |
| 270 | workloadPool: string | undefined; |
| 271 | /** Current control-plane version. */ |
| 272 | currentMasterVersion: string | undefined; |
| 273 | /** User-provided description. */ |
| 274 | description: string | undefined; |
| 275 | /** User labels (Alchemy ownership labels stripped). */ |
| 276 | labels: Record<string, string>; |
| 277 | /** VPC network. */ |
| 278 | network: string | undefined; |
| 279 | /** Subnetwork. */ |
| 280 | subnetwork: string | undefined; |
| 281 | /** Alias-IP allocation. */ |
| 282 | ipAllocationPolicy: container.IPAllocationPolicy | undefined; |
| 283 | /** Private-cluster configuration. */ |
| 284 | privateClusterConfig: container.PrivateClusterConfig | undefined; |
| 285 | /** Control-plane authorized networks. */ |
| 286 | masterAuthorizedNetworksConfig: container.MasterAuthorizedNetworksConfig | undefined; |
| 287 | /** Datapath provider (omitted by GKE for `LEGACY_DATAPATH`). */ |
| 288 | datapathProvider: string | undefined; |
| 289 | /** Whether Shielded GKE Nodes are enabled. */ |
| 290 | enableShieldedNodes: boolean; |
| 291 | /** GKE addon configuration. */ |
| 292 | addonsConfig: container.AddonsConfig | undefined; |
| 293 | /** Fine-grained cost allocation configuration. */ |
| 294 | costManagementConfig: container.CostManagementConfig | undefined; |
| 295 | /** Logging service. */ |
| 296 | loggingService: string | undefined; |
| 297 | /** Cloud Logging component configuration. */ |
| 298 | loggingConfig: container.LoggingConfig | undefined; |
| 299 | /** Monitoring service. */ |
| 300 | monitoringService: string | undefined; |
| 301 | /** Cloud Monitoring component configuration. */ |
| 302 | monitoringConfig: container.MonitoringConfig | undefined; |
| 303 | /** Whether Autopilot is enabled. */ |
| 304 | autopilot: boolean; |
| 305 | /** Whether Kubernetes alpha APIs are enabled. */ |
| 306 | enableKubernetesAlpha: boolean; |
| 307 | /** Release channel (`RAPID`, `REGULAR`, …). */ |
| 308 | releaseChannel: string | undefined; |
| 309 | /** Node locations currently configured. */ |
| 310 | nodeLocations: string[]; |
| 311 | /** Services IPv4 CIDR. */ |
| 312 | servicesIpv4Cidr: string | undefined; |
| 313 | /** Server-defined URL. */ |
| 314 | selfLink: string | undefined; |
| 315 | /** RFC3339 creation timestamp. */ |
| 316 | createTime: string | undefined; |
| 317 | }, |
| 318 | KubernetesObjectBinding, |
| 319 | Providers |
| 320 | >; |
| 321 | |
| 322 | /** |
| 323 | * A Google Kubernetes Engine cluster. |
| 324 | * |
| 325 | * Changing `clusterId`, `location`, `description`, `network`, |
| 326 | * `subnetwork`, `ipAllocationPolicy`, private-node topology, `autopilot`, |
| 327 | * `enableKubernetesAlpha`, the node identity (`serviceAccount`, |
| 328 | * `oauthScopes`), or default-pool node shape (`initialNodeCount`, |
| 329 | * `machineType`, `diskSizeGb`, `diskType`, `spot`, `preemptible`) replaces |
| 330 | * the cluster — except that default-pool props are ignored on update while |
| 331 | * `removeDefaultNodePool` is set. Labels, endpoint access, Shielded Nodes, |
| 332 | * addons, datapath, logging/monitoring, cost management, release channel, |
| 333 | * and node locations update in place. |
| 334 | * |
| 335 | * Provisioning typically takes several minutes. |
| 336 | * |
| 337 | * ### Creating a Cluster |
| 338 | * **Example:** Generated name, zonal default pool |
| 339 | * ```typescript |
| 340 | * const cluster = yield* GCP.Container.Cluster("App", {}); |
| 341 | * ``` |
| 342 | * |
| 343 | * **Example:** Explicit id, labels, and Spot nodes |
| 344 | * ```typescript |
| 345 | * const cluster = yield* GCP.Container.Cluster("App", { |
| 346 | * clusterId: "app-cluster", |
| 347 | * location: "us-central1-a", |
| 348 | * machineType: "e2-medium", |
| 349 | * initialNodeCount: 1, |
| 350 | * spot: true, |
| 351 | * labels: { env: "prod" }, |
| 352 | * }); |
| 353 | * ``` |
| 354 | * |
| 355 | * ### Private Clusters |
| 356 | * **Example:** Private nodes, Dataplane V2, and separately managed pools |
| 357 | * ```typescript |
| 358 | * const nodes = yield* GCP.IAM.ServiceAccount("GkeNodes", {}); |
| 359 | * const cluster = yield* GCP.Container.Cluster("App", { |
| 360 | * network: network.networkName, |
| 361 | * subnetwork: subnet.subnetworkName, |
| 362 | * ipAllocationPolicy: { |
| 363 | * useIpAliases: true, |
| 364 | * clusterSecondaryRangeName: "pods", |
| 365 | * servicesSecondaryRangeName: "services", |
| 366 | * }, |
| 367 | * privateClusterConfig: { |
| 368 | * enablePrivateNodes: true, |
| 369 | * masterIpv4CidrBlock: "172.16.0.0/28", |
| 370 | * }, |
| 371 | * masterAuthorizedNetworksConfig: { |
| 372 | * enabled: true, |
| 373 | * cidrBlocks: [{ cidrBlock: "203.0.113.0/24", displayName: "office" }], |
| 374 | * }, |
| 375 | * datapathProvider: "ADVANCED_DATAPATH", |
| 376 | * enableShieldedNodes: true, |
| 377 | * serviceAccount: nodes.email, |
| 378 | * removeDefaultNodePool: true, |
| 379 | * deletionProtection: true, |
| 380 | * }); |
| 381 | * yield* GCP.Container.NodePool("Workers", { |
| 382 | * cluster: cluster.name, |
| 383 | * serviceAccount: nodes.email, |
| 384 | * shieldedInstanceConfig: { enableSecureBoot: true }, |
| 385 | * }); |
| 386 | * ``` |
| 387 | * |
| 388 | * ### Autopilot |
| 389 | * **Example:** Regional Autopilot cluster |
| 390 | * ```typescript |
| 391 | * const cluster = yield* GCP.Container.Cluster("App", { |
| 392 | * location: "us-central1", |
| 393 | * autopilot: true, |
| 394 | * releaseChannel: "REGULAR", |
| 395 | * }); |
| 396 | * ``` |
| 397 | * |
| 398 | * **Example:** Autopilot nodes with a dedicated service account |
| 399 | * ```typescript |
| 400 | * const nodes = yield* GCP.IAM.ServiceAccount("GkeNodes", {}); |
| 401 | * yield* GCP.IAM.Member("GkeNodesRole", { |
| 402 | * kind: "project", |
| 403 | * name: "my-project", |
| 404 | * role: "roles/container.defaultNodeServiceAccount", |
| 405 | * member: Output.interpolate`serviceAccount:${nodes.email}`, |
| 406 | * }); |
| 407 | * const cluster = yield* GCP.Container.Cluster("App", { |
| 408 | * location: "us-central1", |
| 409 | * autopilot: true, |
| 410 | * serviceAccount: nodes.email, |
| 411 | * }); |
| 412 | * ``` |
| 413 | * |
| 414 | * ### Reading a Cluster |
| 415 | * **Example:** Get the bound cluster |
| 416 | * ```typescript |
| 417 | * const getCluster = yield* GCP.Container.GetCluster(cluster); |
| 418 | * const live = yield* getCluster(); |
| 419 | * ``` |
| 420 | * |
| 421 | * ### Kubernetes Workloads |
| 422 | * **Example:** Deploy an Effect-native workload onto the cluster |
| 423 | * ```typescript |
| 424 | * const cluster = yield* GCP.Container.Cluster("App", {}); |
| 425 | * const api = yield* Kubernetes.Deployment("Api", { |
| 426 | * cluster, |
| 427 | * main: import.meta.url, |
| 428 | * port: 8080, |
| 429 | * }); |
| 430 | * ``` |
| 431 | * |
| 432 | * @resource |
| 433 | * @category Container |
| 434 | */ |
| 435 | export const Cluster = Resource<Cluster>("GCP.Container.Cluster"); |
| 436 | |
| 437 | export class ClusterNotResolved extends Data.TaggedError("GCP.Container.ClusterNotResolved")<{ |
| 438 | resourceName: string; |
| 439 | }> {} |
| 440 | |
| 441 | export class ClusterNotReady extends Data.TaggedError("GCP.Container.ClusterNotReady")<{ |
| 442 | resourceName: string; |
| 443 | status: string; |
| 444 | }> {} |
| 445 | |
| 446 | export class ClusterOperationFailed extends Data.TaggedError( |
| 447 | "GCP.Container.ClusterOperationFailed", |
| 448 | )<{ |
| 449 | operation: string; |
| 450 | message: string; |
| 451 | }> {} |
| 452 | |
| 453 | export class ClusterStillExists extends Data.TaggedError("GCP.Container.ClusterStillExists")<{ |
| 454 | resourceName: string; |
| 455 | }> {} |
| 456 | |
| 457 | export class ClusterDeletionProtected extends Data.TaggedError( |
| 458 | "GCP.Container.ClusterDeletionProtected", |
| 459 | )<{ |
| 460 | resourceName: string; |
| 461 | }> {} |
| 462 | |
| 463 | const lastSegment = (value: string) => { |
| 464 | const trimmed = value.replace(/\/+$/, ""); |
| 465 | const parts = trimmed.split("/"); |
| 466 | return parts[parts.length - 1] || trimmed; |
| 467 | }; |
| 468 | |
| 469 | const normalizeLocation = (location: string | undefined) => |
| 470 | lastSegment(location ?? DEFAULT_LOCATION).toLowerCase(); |
| 471 | |
| 472 | const normalizeChannel = (channel: string | undefined) => { |
| 473 | const value = (channel ?? "").toUpperCase(); |
| 474 | return value === "UNSPECIFIED" || value.length === 0 ? "" : value; |
| 475 | }; |
| 476 | |
| 477 | /** Order- and case-insensitive set comparison for string lists. */ |
| 478 | const sameStrings = (left: string[], right: string[]) => { |
| 479 | if (left.length !== right.length) return false; |
| 480 | const a = [...left].map((item) => item.toLowerCase()).sort(); |
| 481 | const b = [...right].map((item) => item.toLowerCase()).sort(); |
| 482 | return a.every((value, index) => value === b[index]); |
| 483 | }; |
| 484 | |
| 485 | const desiredIpAllocationPolicy = ( |
| 486 | policy: container.IPAllocationPolicy | undefined, |
| 487 | ): container.IPAllocationPolicy => ({ useIpAliases: true, ...policy }); |
| 488 | |
| 489 | /** The create-time part of `privateClusterConfig`. */ |
| 490 | const privateTopology = (config: container.PrivateClusterConfig | undefined) => ({ |
| 491 | enablePrivateNodes: config?.enablePrivateNodes === true, |
| 492 | masterIpv4CidrBlock: config?.masterIpv4CidrBlock ?? "", |
| 493 | privateEndpointSubnetwork: config?.privateEndpointSubnetwork ?? "", |
| 494 | }); |
| 495 | |
| 496 | const rfc1035 = (name: string): string => { |
| 497 | let next = name |
| 498 | .toLowerCase() |
| 499 | .replace(/[^a-z0-9-]/g, "-") |
| 500 | .replace(/-+/g, "-") |
| 501 | .replace(/^-+|-+$/g, ""); |
| 502 | if (!/^[a-z]/.test(next)) next = `c${next}`; |
| 503 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 504 | if (next.length === 0) return "cluster"; |
| 505 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 506 | return next.slice(0, MAX_NAME_LENGTH); |
| 507 | }; |
| 508 | |
| 509 | const resourceName = (project: string, location: string, clusterId: string) => |
| 510 | `projects/${project}/locations/${location}/clusters/${clusterId}`; |
| 511 | |
| 512 | const parseName = (name: string) => { |
| 513 | const parts = name.split("/").filter((part) => part.length > 0); |
| 514 | const clustersAt = parts.lastIndexOf("clusters"); |
| 515 | const locationsAt = parts.lastIndexOf("locations"); |
| 516 | const projectsAt = parts.lastIndexOf("projects"); |
| 517 | return { |
| 518 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 519 | location: |
| 520 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 521 | clusterId: |
| 522 | clustersAt >= 0 && parts[clustersAt + 1] ? parts[clustersAt + 1]! : lastSegment(name), |
| 523 | }; |
| 524 | }; |
| 525 | |
| 526 | const userLabels = ( |
| 527 | labels: Record<string, string | undefined> | null | undefined, |
| 528 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 529 | |
| 530 | const toId = (id: string, clusterId: string | undefined, existing?: string) => |
| 531 | Effect.gen(function* () { |
| 532 | return ( |
| 533 | clusterId ?? |
| 534 | existing ?? |
| 535 | rfc1035( |
| 536 | yield* createPhysicalName({ |
| 537 | id, |
| 538 | maxLength: MAX_NAME_LENGTH, |
| 539 | lowercase: true, |
| 540 | }), |
| 541 | ) |
| 542 | ); |
| 543 | }); |
| 544 | |
| 545 | const toAttrs = ( |
| 546 | cluster: container.Cluster, |
| 547 | project: string, |
| 548 | kubernetesObjects: KubernetesObjectRef[] = [], |
| 549 | ) => { |
| 550 | const selfLink = cluster.selfLink ?? ""; |
| 551 | const parsed = parseName(selfLink.length > 0 ? selfLink : (cluster.name ?? "")); |
| 552 | const clusterId = cluster.name || parsed.clusterId; |
| 553 | const location = lastSegment(cluster.location ?? parsed.location); |
| 554 | const resolvedProject = parsed.project || project; |
| 555 | const endpoint = apiServerEndpoint(cluster.endpoint) ?? cluster.endpoint; |
| 556 | const certificateAuthorityData = cluster.masterAuth?.clusterCaCertificate; |
| 557 | return { |
| 558 | name: resourceName(resolvedProject, location, clusterId), |
| 559 | clusterId, |
| 560 | project: resolvedProject, |
| 561 | location, |
| 562 | clusterUid: cluster.id, |
| 563 | status: cluster.status, |
| 564 | endpoint, |
| 565 | certificateAuthorityData, |
| 566 | connection: gkeConnectionOf({ |
| 567 | clusterId, |
| 568 | location, |
| 569 | project: resolvedProject, |
| 570 | endpoint, |
| 571 | certificateAuthorityData, |
| 572 | }), |
| 573 | kubernetesObjects, |
| 574 | workloadPool: cluster.workloadIdentityConfig?.workloadPool, |
| 575 | currentMasterVersion: cluster.currentMasterVersion, |
| 576 | description: cluster.description, |
| 577 | labels: userLabels(cluster.resourceLabels), |
| 578 | network: cluster.network, |
| 579 | subnetwork: cluster.subnetwork, |
| 580 | ipAllocationPolicy: cluster.ipAllocationPolicy, |
| 581 | privateClusterConfig: cluster.privateClusterConfig, |
| 582 | masterAuthorizedNetworksConfig: cluster.masterAuthorizedNetworksConfig, |
| 583 | datapathProvider: cluster.networkConfig?.datapathProvider, |
| 584 | enableShieldedNodes: cluster.shieldedNodes?.enabled === true, |
| 585 | addonsConfig: cluster.addonsConfig, |
| 586 | costManagementConfig: cluster.costManagementConfig, |
| 587 | loggingService: cluster.loggingService, |
| 588 | loggingConfig: cluster.loggingConfig, |
| 589 | monitoringService: cluster.monitoringService, |
| 590 | monitoringConfig: cluster.monitoringConfig, |
| 591 | autopilot: cluster.autopilot?.enabled === true, |
| 592 | enableKubernetesAlpha: cluster.enableKubernetesAlpha === true, |
| 593 | releaseChannel: cluster.releaseChannel?.channel, |
| 594 | nodeLocations: [...(cluster.locations ?? [])], |
| 595 | servicesIpv4Cidr: cluster.servicesIpv4Cidr, |
| 596 | selfLink: cluster.selfLink, |
| 597 | createTime: cluster.createTime, |
| 598 | }; |
| 599 | }; |
| 600 | |
| 601 | const getDesiredKubernetesObjects = ( |
| 602 | bindings: ReadonlyArray<ResourceBinding<KubernetesObjectBinding>>, |
| 603 | ): KubernetesObjectDefinition[] => |
| 604 | bindings |
| 605 | .filter( |
| 606 | (binding): binding is ResourceBinding<KubernetesObjectBinding> => |
| 607 | binding.data.type === "kubernetes-object", |
| 608 | ) |
| 609 | .map((binding) => binding.data.object); |
| 610 | |
| 611 | const getKubernetesTransport = ( |
| 612 | state: Pick<Cluster["Attributes"], "clusterId" | "endpoint" | "certificateAuthorityData">, |
| 613 | ) => |
| 614 | Effect.suspend(() => { |
| 615 | if (!state.endpoint || !state.certificateAuthorityData) { |
| 616 | throw new Error( |
| 617 | `GKE cluster '${state.clusterId}' is missing endpoint or certificate authority data`, |
| 618 | ); |
| 619 | } |
| 620 | return makeGkeTransport({ |
| 621 | endpoint: state.endpoint, |
| 622 | certificateAuthorityData: state.certificateAuthorityData, |
| 623 | }); |
| 624 | }); |
| 625 | |
| 626 | const getByName = (name: string) => |
| 627 | container |
| 628 | .getProjectsLocationsClusters({ name }) |
| 629 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 630 | |
| 631 | const operationResourceName = ( |
| 632 | project: string, |
| 633 | location: string, |
| 634 | operation: container.Operation, |
| 635 | ) => { |
| 636 | const raw = operation.name ?? ""; |
| 637 | if (raw.includes("/operations/")) { |
| 638 | const idx = raw.indexOf("projects/"); |
| 639 | return idx >= 0 ? raw.slice(idx) : raw; |
| 640 | } |
| 641 | const fromLink = operation.selfLink ?? ""; |
| 642 | if (fromLink.includes("/operations/")) { |
| 643 | const idx = fromLink.indexOf("projects/"); |
| 644 | return idx >= 0 ? fromLink.slice(idx) : fromLink; |
| 645 | } |
| 646 | const loc = lastSegment(operation.location ?? operation.zone ?? location); |
| 647 | return `projects/${project}/locations/${loc}/operations/${lastSegment(raw)}`; |
| 648 | }; |
| 649 | |
| 650 | // Cluster create / delete runs 5–10 min (Autopilot included) and most |
| 651 | // updates several minutes; bounded at 15 min. |
| 652 | const clusterOperationSchedule = Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(90)]); |
| 653 | |
| 654 | /** |
| 655 | * Wait for a GKE operation (create/delete runs 5–10 min, Autopilot and |
| 656 | * large updates longer). ALREADY_EXISTS (code 6) counts as success |
| 657 | * (create race); with `notFoundOk`, so does NOT_FOUND (code 5, delete |
| 658 | * race) and an operation that is already gone. |
| 659 | */ |
| 660 | const waitForOperation = ( |
| 661 | project: string, |
| 662 | location: string, |
| 663 | operation: container.Operation, |
| 664 | options?: { notFoundOk?: boolean }, |
| 665 | ) => |
| 666 | waitForGcpOperation( |
| 667 | { |
| 668 | ...operation, |
| 669 | name: operationResourceName(project, location, operation), |
| 670 | }, |
| 671 | (name) => container.getProjectsLocationsOperations({ name }), |
| 672 | { budget: "30 minutes", interval: "10 seconds" }, |
| 673 | ).pipe( |
| 674 | Effect.catchIf( |
| 675 | (error) => |
| 676 | (error._tag === "GCP.OperationFailed" && |
| 677 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5))) || |
| 678 | (options?.notFoundOk === true && error._tag === "NotFound"), |
| 679 | () => Effect.succeed(operation), |
| 680 | ), |
| 681 | ); |
| 682 | |
| 683 | const waitUntilExists = (name: string) => |
| 684 | getByName(name).pipe( |
| 685 | Effect.filterOrFail( |
| 686 | (cluster): cluster is container.Cluster => cluster !== undefined, |
| 687 | () => new ClusterNotResolved({ resourceName: name }), |
| 688 | ), |
| 689 | Effect.retry({ |
| 690 | while: (error) => error._tag === "GCP.Container.ClusterNotResolved", |
| 691 | times: 8, |
| 692 | schedule: Schedule.spaced("1 second"), |
| 693 | }), |
| 694 | ); |
| 695 | |
| 696 | const waitUntilReady = (name: string) => |
| 697 | getByName(name).pipe( |
| 698 | Effect.filterOrFail( |
| 699 | (cluster): cluster is container.Cluster => cluster !== undefined, |
| 700 | () => new ClusterNotResolved({ resourceName: name }), |
| 701 | ), |
| 702 | Effect.filterOrFail( |
| 703 | (cluster) => (cluster.status ?? "STATUS_UNSPECIFIED") !== "ERROR", |
| 704 | (cluster) => |
| 705 | new ClusterOperationFailed({ |
| 706 | operation: name, |
| 707 | message: cluster.statusMessage ?? "cluster is in ERROR", |
| 708 | }), |
| 709 | ), |
| 710 | Effect.filterOrFail( |
| 711 | (cluster) => { |
| 712 | const status = cluster.status ?? "STATUS_UNSPECIFIED"; |
| 713 | return status === "RUNNING" || status === "DEGRADED"; |
| 714 | }, |
| 715 | (cluster) => |
| 716 | new ClusterNotReady({ |
| 717 | resourceName: name, |
| 718 | status: cluster.status ?? "STATUS_UNSPECIFIED", |
| 719 | }), |
| 720 | ), |
| 721 | Effect.retry({ |
| 722 | while: (error) => |
| 723 | error._tag === "GCP.Container.ClusterNotReady" || |
| 724 | error._tag === "GCP.Container.ClusterNotResolved", |
| 725 | schedule: clusterOperationSchedule, |
| 726 | }), |
| 727 | ); |
| 728 | |
| 729 | const waitUntilGone = (name: string) => |
| 730 | getByName(name).pipe( |
| 731 | Effect.flatMap((cluster) => |
| 732 | cluster === undefined |
| 733 | ? Effect.void |
| 734 | : Effect.fail(new ClusterStillExists({ resourceName: name })), |
| 735 | ), |
| 736 | Effect.retry({ |
| 737 | while: (error) => error._tag === "GCP.Container.ClusterStillExists", |
| 738 | schedule: clusterOperationSchedule, |
| 739 | }), |
| 740 | ); |
| 741 | |
| 742 | /** |
| 743 | * GKE rejects a delete (400 "Cluster is running incompatible operation") |
| 744 | * while a create/update is still in flight — e.g. a recovery delete after an |
| 745 | * interrupted create. Wait for the cluster to leave its transitional states |
| 746 | * first; a cluster that vanishes meanwhile is fine. |
| 747 | */ |
| 748 | const waitUntilSettled = (name: string) => |
| 749 | getByName(name).pipe( |
| 750 | Effect.filterOrFail( |
| 751 | (cluster) => { |
| 752 | const status = cluster?.status ?? "STATUS_UNSPECIFIED"; |
| 753 | return status !== "PROVISIONING" && status !== "RECONCILING" && status !== "STOPPING"; |
| 754 | }, |
| 755 | (cluster) => |
| 756 | new ClusterNotReady({ |
| 757 | resourceName: name, |
| 758 | status: cluster?.status ?? "STATUS_UNSPECIFIED", |
| 759 | }), |
| 760 | ), |
| 761 | Effect.retry({ |
| 762 | while: (error) => error._tag === "GCP.Container.ClusterNotReady", |
| 763 | schedule: clusterOperationSchedule, |
| 764 | }), |
| 765 | ); |
| 766 | |
| 767 | /** Delete GKE's bootstrap `default-pool`; returns whether it existed. */ |
| 768 | const ensureDefaultPoolRemoved = (project: string, location: string, clusterName: string) => |
| 769 | Effect.gen(function* () { |
| 770 | const operation = yield* container |
| 771 | .deleteProjectsLocationsClustersNodePools({ |
| 772 | name: `${clusterName}/nodePools/${DEFAULT_POOL_NAME}`, |
| 773 | }) |
| 774 | .pipe( |
| 775 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 776 | Effect.retry({ |
| 777 | while: (error) => error._tag === "Conflict", |
| 778 | times: 8, |
| 779 | schedule: Schedule.spaced("5 seconds"), |
| 780 | }), |
| 781 | ); |
| 782 | if (operation === undefined) return false; |
| 783 | yield* waitForOperation(project, location, operation, { notFoundOk: true }); |
| 784 | return true; |
| 785 | }); |
| 786 | |
| 787 | const defaultPool = (news: ClusterProps): container.NodePool => ({ |
| 788 | name: DEFAULT_POOL_NAME, |
| 789 | initialNodeCount: news.initialNodeCount ?? DEFAULT_NODE_COUNT, |
| 790 | config: { |
| 791 | machineType: news.machineType ?? DEFAULT_MACHINE_TYPE, |
| 792 | diskSizeGb: news.diskSizeGb ?? DEFAULT_DISK_SIZE_GB, |
| 793 | diskType: news.diskType ?? DEFAULT_DISK_TYPE, |
| 794 | spot: news.spot === true, |
| 795 | preemptible: news.preemptible === true, |
| 796 | serviceAccount: news.serviceAccount, |
| 797 | oauthScopes: news.oauthScopes, |
| 798 | workloadMetadataConfig: { mode: "GKE_METADATA" }, |
| 799 | }, |
| 800 | }); |
| 801 | |
| 802 | const toCreateBody = ( |
| 803 | news: ClusterProps, |
| 804 | clusterId: string, |
| 805 | desiredLabels: Record<string, string>, |
| 806 | autopilot: boolean, |
| 807 | project: string, |
| 808 | ): container.Cluster => { |
| 809 | const channel = normalizeChannel(news.releaseChannel); |
| 810 | return { |
| 811 | name: clusterId, |
| 812 | description: news.description, |
| 813 | resourceLabels: desiredLabels, |
| 814 | network: news.network, |
| 815 | subnetwork: news.subnetwork, |
| 816 | ipAllocationPolicy: desiredIpAllocationPolicy(news.ipAllocationPolicy), |
| 817 | privateClusterConfig: news.privateClusterConfig, |
| 818 | masterAuthorizedNetworksConfig: news.masterAuthorizedNetworksConfig, |
| 819 | networkConfig: |
| 820 | news.datapathProvider !== undefined ? { datapathProvider: news.datapathProvider } : undefined, |
| 821 | shieldedNodes: |
| 822 | news.enableShieldedNodes !== undefined ? { enabled: news.enableShieldedNodes } : undefined, |
| 823 | addonsConfig: news.addonsConfig, |
| 824 | costManagementConfig: news.costManagementConfig, |
| 825 | initialClusterVersion: news.initialClusterVersion, |
| 826 | loggingService: news.loggingService, |
| 827 | loggingConfig: news.loggingConfig, |
| 828 | monitoringService: news.monitoringService, |
| 829 | monitoringConfig: news.monitoringConfig, |
| 830 | enableKubernetesAlpha: news.enableKubernetesAlpha === true, |
| 831 | locations: news.nodeLocations, |
| 832 | autopilot: autopilot ? { enabled: true } : undefined, |
| 833 | // Autopilot has no default pool: its nodes take their identity from the |
| 834 | // node auto-provisioning defaults instead. |
| 835 | autoscaling: |
| 836 | autopilot && (news.serviceAccount !== undefined || news.oauthScopes !== undefined) |
| 837 | ? { |
| 838 | autoprovisioningNodePoolDefaults: { |
| 839 | serviceAccount: news.serviceAccount, |
| 840 | oauthScopes: news.oauthScopes, |
| 841 | }, |
| 842 | } |
| 843 | : undefined, |
| 844 | workloadIdentityConfig: { workloadPool: workloadPoolOf(project) }, |
| 845 | releaseChannel: |
| 846 | channel.length > 0 ? { channel: channel as container.ReleaseChannelChannelEnum } : undefined, |
| 847 | nodePools: autopilot ? undefined : [defaultPool(news)], |
| 848 | }; |
| 849 | }; |
| 850 | |
| 851 | export const ClusterProvider = () => |
| 852 | Provider.succeed(Cluster, { |
| 853 | stables: [ |
| 854 | "name", |
| 855 | "clusterId", |
| 856 | "project", |
| 857 | "location", |
| 858 | "clusterUid", |
| 859 | "selfLink", |
| 860 | "createTime", |
| 861 | "connection", |
| 862 | ], |
| 863 | |
| 864 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 865 | if (!isResolved(news)) return undefined; |
| 866 | |
| 867 | const previousId = olds?.clusterId ?? output?.clusterId; |
| 868 | const nextId = news.clusterId ?? previousId; |
| 869 | const previousLocation = normalizeLocation(olds?.location ?? output?.location); |
| 870 | const nextLocation = normalizeLocation(news.location ?? output?.location); |
| 871 | const previousAutopilot = olds?.autopilot === true || output?.autopilot === true; |
| 872 | const nextAutopilot = news.autopilot === true; |
| 873 | const previousNetwork = olds?.network ?? output?.network ?? ""; |
| 874 | const nextNetwork = news.network ?? previousNetwork; |
| 875 | const previousSubnetwork = olds?.subnetwork ?? output?.subnetwork ?? ""; |
| 876 | const nextSubnetwork = news.subnetwork ?? previousSubnetwork; |
| 877 | const previousAlpha = |
| 878 | olds?.enableKubernetesAlpha === true || output?.enableKubernetesAlpha === true; |
| 879 | const nextAlpha = news.enableKubernetesAlpha === true; |
| 880 | const previousDescription = olds?.description ?? output?.description ?? ""; |
| 881 | const nextDescription = news.description ?? previousDescription; |
| 882 | const previousServiceAccount = olds?.serviceAccount ?? ""; |
| 883 | const nextServiceAccount = news.serviceAccount ?? previousServiceAccount; |
| 884 | const previousOauthScopes = olds?.oauthScopes ?? []; |
| 885 | const nextOauthScopes = news.oauthScopes ?? previousOauthScopes; |
| 886 | // Without previous props (adoption), compare against the observed |
| 887 | // cluster so declaring what already runs is not a replacement. |
| 888 | const ipAllocationChanged = |
| 889 | olds !== undefined |
| 890 | ? !deepEqual( |
| 891 | desiredIpAllocationPolicy(olds.ipAllocationPolicy), |
| 892 | desiredIpAllocationPolicy(news.ipAllocationPolicy), |
| 893 | { stripNullish: true }, |
| 894 | ) |
| 895 | : output !== undefined && |
| 896 | !matchesDesired( |
| 897 | output.ipAllocationPolicy, |
| 898 | desiredIpAllocationPolicy(news.ipAllocationPolicy), |
| 899 | ); |
| 900 | const privateTopologyChanged = |
| 901 | news.privateClusterConfig !== undefined && |
| 902 | (olds !== undefined |
| 903 | ? !deepEqual( |
| 904 | privateTopology(olds.privateClusterConfig), |
| 905 | privateTopology(news.privateClusterConfig), |
| 906 | ) |
| 907 | : output !== undefined && |
| 908 | !matchesDesired( |
| 909 | privateTopology(output.privateClusterConfig), |
| 910 | privateTopology(news.privateClusterConfig), |
| 911 | )); |
| 912 | // Default-pool props only describe GKE's bootstrap `default-pool`. |
| 913 | // Once it is removed (before or after this change) they describe no |
| 914 | // live node and must not replace the cluster. |
| 915 | const defaultPoolKept = |
| 916 | news.removeDefaultNodePool !== true && olds?.removeDefaultNodePool !== true; |
| 917 | // GKE only creates `default-pool` at cluster creation, so turning |
| 918 | // `removeDefaultNodePool` back off can only be honored by replacing. |
| 919 | const defaultPoolRestored = |
| 920 | !nextAutopilot && |
| 921 | olds?.removeDefaultNodePool === true && |
| 922 | news.removeDefaultNodePool !== true; |
| 923 | const nodeShapeChanged = |
| 924 | !nextAutopilot && |
| 925 | defaultPoolKept && |
| 926 | olds !== undefined && |
| 927 | ((olds.initialNodeCount ?? DEFAULT_NODE_COUNT) !== |
| 928 | (news.initialNodeCount ?? DEFAULT_NODE_COUNT) || |
| 929 | (olds.machineType ?? DEFAULT_MACHINE_TYPE) !== |
| 930 | (news.machineType ?? DEFAULT_MACHINE_TYPE) || |
| 931 | (olds.diskSizeGb ?? DEFAULT_DISK_SIZE_GB) !== (news.diskSizeGb ?? DEFAULT_DISK_SIZE_GB) || |
| 932 | (olds.diskType ?? DEFAULT_DISK_TYPE).toLowerCase() !== |
| 933 | (news.diskType ?? DEFAULT_DISK_TYPE).toLowerCase() || |
| 934 | (olds.spot === true) !== (news.spot === true) || |
| 935 | (olds.preemptible === true) !== (news.preemptible === true) || |
| 936 | previousServiceAccount !== nextServiceAccount || |
| 937 | (news.oauthScopes !== undefined && !sameStrings(previousOauthScopes, nextOauthScopes))); |
| 938 | // Autopilot fixes its nodes' identity at cluster creation. |
| 939 | const autopilotIdentityChanged = |
| 940 | nextAutopilot && |
| 941 | olds !== undefined && |
| 942 | (previousServiceAccount !== nextServiceAccount || |
| 943 | (news.oauthScopes !== undefined && !sameStrings(previousOauthScopes, nextOauthScopes))); |
| 944 | |
| 945 | const replace = |
| 946 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 947 | previousLocation !== nextLocation || |
| 948 | previousAutopilot !== nextAutopilot || |
| 949 | previousNetwork !== nextNetwork || |
| 950 | previousSubnetwork !== nextSubnetwork || |
| 951 | previousAlpha !== nextAlpha || |
| 952 | previousDescription !== nextDescription || |
| 953 | ipAllocationChanged || |
| 954 | privateTopologyChanged || |
| 955 | defaultPoolRestored || |
| 956 | nodeShapeChanged || |
| 957 | autopilotIdentityChanged; |
| 958 | |
| 959 | if (!replace) return undefined; |
| 960 | // A replacement deletes the old cluster with the OLD props, so it would |
| 961 | // create the new cluster and then strand on ClusterDeletionProtected. |
| 962 | // Fail at plan time instead. (Adoption has no previous props; the |
| 963 | // delete-side guard is the backstop there.) |
| 964 | if (olds?.deletionProtection === true) { |
| 965 | return yield* new ClusterDeletionProtected({ |
| 966 | resourceName: output?.name ?? previousId ?? nextId ?? "", |
| 967 | }); |
| 968 | } |
| 969 | return { |
| 970 | action: "replace" as const, |
| 971 | deleteFirst: |
| 972 | previousLocation === nextLocation && previousId !== undefined && nextId === previousId, |
| 973 | }; |
| 974 | }), |
| 975 | |
| 976 | read: Effect.fn(function* ({ id, olds, output }) { |
| 977 | const env = yield* GcpEnvironment.current; |
| 978 | const clusterId = yield* toId(id, olds?.clusterId, output?.clusterId); |
| 979 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 980 | const name = output?.name ?? resourceName(env.project, location, clusterId); |
| 981 | const existing = yield* getByName(name); |
| 982 | if (existing === undefined) return undefined; |
| 983 | const attrs = toAttrs(existing, env.project, output?.kubernetesObjects ?? []); |
| 984 | return (yield* hasAlchemyLabels(id, tagRecord(existing.resourceLabels))) |
| 985 | ? attrs |
| 986 | : Unowned(attrs); |
| 987 | }), |
| 988 | |
| 989 | list: () => |
| 990 | Effect.gen(function* () { |
| 991 | const env = yield* GcpEnvironment.current; |
| 992 | const page = yield* container |
| 993 | .listProjectsLocationsClusters({ |
| 994 | parent: `projects/${env.project}/locations/-`, |
| 995 | }) |
| 996 | .pipe( |
| 997 | Effect.catchTag("NotFound", () => |
| 998 | Effect.succeed({ |
| 999 | clusters: [], |
| 1000 | } satisfies container.ListClustersResponse), |
| 1001 | ), |
| 1002 | ); |
| 1003 | return (page.clusters ?? []) |
| 1004 | .filter((cluster) => |
| 1005 | Object.keys(cluster.resourceLabels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 1006 | ) |
| 1007 | .map((cluster) => toAttrs(cluster, env.project)); |
| 1008 | }), |
| 1009 | |
| 1010 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 1011 | const env = yield* GcpEnvironment.current; |
| 1012 | const clusterId = yield* toId(id, news.clusterId, output?.clusterId); |
| 1013 | const location = normalizeLocation(news.location ?? output?.location); |
| 1014 | const name = resourceName(env.project, location, clusterId); |
| 1015 | const autopilot = news.autopilot === true; |
| 1016 | const desiredLabels = { |
| 1017 | ...toLabels(news.labels), |
| 1018 | ...(yield* createInternalLabels(id)), |
| 1019 | }; |
| 1020 | const desiredObjects = getDesiredKubernetesObjects(bindings); |
| 1021 | const desiredPool = workloadPoolOf(env.project); |
| 1022 | |
| 1023 | let current = yield* getByName(output?.name ?? name); |
| 1024 | |
| 1025 | if (current === undefined) { |
| 1026 | const create = Effect.gen(function* () { |
| 1027 | const created = yield* container |
| 1028 | .createProjectsLocationsClusters({ |
| 1029 | parent: `projects/${env.project}/locations/${location}`, |
| 1030 | body: { |
| 1031 | cluster: toCreateBody(news, clusterId, desiredLabels, autopilot, env.project), |
| 1032 | }, |
| 1033 | }) |
| 1034 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 1035 | if (created !== undefined) { |
| 1036 | yield* waitForOperation(env.project, location, created); |
| 1037 | } |
| 1038 | }); |
| 1039 | // GKE intermittently fails a create with INTERNAL ("Failed to create |
| 1040 | // cluster") and leaves the cluster in ERROR; delete it and try again. |
| 1041 | const removeFailed = Effect.gen(function* () { |
| 1042 | const operation = yield* container.deleteProjectsLocationsClusters({ name }).pipe( |
| 1043 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 1044 | Effect.retry({ |
| 1045 | while: (error) => error._tag === "Conflict", |
| 1046 | times: 8, |
| 1047 | schedule: Schedule.spaced("5 seconds"), |
| 1048 | }), |
| 1049 | ); |
| 1050 | if (operation !== undefined) { |
| 1051 | yield* waitForOperation(env.project, location, operation, { |
| 1052 | notFoundOk: true, |
| 1053 | }); |
| 1054 | } |
| 1055 | yield* waitUntilGone(name); |
| 1056 | }); |
| 1057 | const isInternal = (error: { _tag: string; code?: number }) => |
| 1058 | error._tag === "GCP.OperationFailed" && error.code === 13; |
| 1059 | yield* create.pipe( |
| 1060 | Effect.tapError((error) => (isInternal(error) ? removeFailed : Effect.void)), |
| 1061 | Effect.retry({ |
| 1062 | while: isInternal, |
| 1063 | times: 2, |
| 1064 | schedule: Schedule.spaced("30 seconds"), |
| 1065 | }), |
| 1066 | ); |
| 1067 | current = yield* waitUntilExists(name); |
| 1068 | } |
| 1069 | |
| 1070 | if (current === undefined) { |
| 1071 | return yield* new ClusterNotResolved({ resourceName: name }); |
| 1072 | } |
| 1073 | |
| 1074 | let live = current; |
| 1075 | const status = live.status ?? "STATUS_UNSPECIFIED"; |
| 1076 | if (status !== "RUNNING" && status !== "DEGRADED") { |
| 1077 | live = yield* waitUntilReady(name); |
| 1078 | } |
| 1079 | |
| 1080 | if (!autopilot && news.removeDefaultNodePool === true) { |
| 1081 | const removed = yield* ensureDefaultPoolRemoved(env.project, location, name); |
| 1082 | if (removed) live = yield* waitUntilReady(name); |
| 1083 | } |
| 1084 | |
| 1085 | const observedLabels = tagRecord(live.resourceLabels); |
| 1086 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 1087 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 1088 | if (labelsChanged) { |
| 1089 | const labeled = yield* container.setResourceLabelsProjectsLocationsClusters({ |
| 1090 | name, |
| 1091 | body: { |
| 1092 | resourceLabels: desiredLabels, |
| 1093 | labelFingerprint: live.labelFingerprint, |
| 1094 | }, |
| 1095 | }); |
| 1096 | yield* waitForOperation(env.project, location, labeled); |
| 1097 | live = yield* waitUntilReady(name); |
| 1098 | } |
| 1099 | |
| 1100 | // GKE rejects a logging-only or monitoring-only change that would |
| 1101 | // implicitly flip the other service, so both are always sent together. |
| 1102 | const desiredLogging = news.loggingService ?? live.loggingService; |
| 1103 | const desiredMonitoring = news.monitoringService ?? live.monitoringService; |
| 1104 | if ( |
| 1105 | (live.loggingService ?? "") !== (desiredLogging ?? "") || |
| 1106 | (live.monitoringService ?? "") !== (desiredMonitoring ?? "") |
| 1107 | ) { |
| 1108 | const serviced = yield* container.updateProjectsLocationsClusters({ |
| 1109 | name, |
| 1110 | body: { |
| 1111 | update: { |
| 1112 | desiredLoggingService: desiredLogging, |
| 1113 | desiredMonitoringService: desiredMonitoring, |
| 1114 | }, |
| 1115 | }, |
| 1116 | }); |
| 1117 | yield* waitForOperation(env.project, location, serviced); |
| 1118 | live = yield* waitUntilReady(name); |
| 1119 | } |
| 1120 | |
| 1121 | const desiredChannel = normalizeChannel(news.releaseChannel); |
| 1122 | const observedChannel = normalizeChannel(live.releaseChannel?.channel); |
| 1123 | const desiredLocations = news.nodeLocations; |
| 1124 | const locationsChanged = |
| 1125 | desiredLocations !== undefined && !sameStrings(live.locations ?? [], desiredLocations); |
| 1126 | const channelChanged = desiredChannel.length > 0 && desiredChannel !== observedChannel; |
| 1127 | |
| 1128 | // GKE applies exactly one `desired*` field per update request. |
| 1129 | const applyUpdate = (update: container.ClusterUpdate) => |
| 1130 | Effect.gen(function* () { |
| 1131 | const updated = yield* container.updateProjectsLocationsClusters({ |
| 1132 | name, |
| 1133 | body: { update }, |
| 1134 | }); |
| 1135 | yield* waitForOperation(env.project, location, updated); |
| 1136 | return yield* waitUntilReady(name); |
| 1137 | }); |
| 1138 | |
| 1139 | if (channelChanged) { |
| 1140 | live = yield* applyUpdate({ |
| 1141 | desiredReleaseChannel: { |
| 1142 | channel: desiredChannel as container.ReleaseChannelChannelEnum, |
| 1143 | }, |
| 1144 | }); |
| 1145 | } |
| 1146 | if (locationsChanged) { |
| 1147 | live = yield* applyUpdate({ desiredLocations }); |
| 1148 | } |
| 1149 | |
| 1150 | if ( |
| 1151 | news.masterAuthorizedNetworksConfig !== undefined && |
| 1152 | !matchesDesired(live.masterAuthorizedNetworksConfig, news.masterAuthorizedNetworksConfig) |
| 1153 | ) { |
| 1154 | live = yield* applyUpdate({ |
| 1155 | desiredMasterAuthorizedNetworksConfig: news.masterAuthorizedNetworksConfig, |
| 1156 | }); |
| 1157 | } |
| 1158 | |
| 1159 | const desiredPrivateEndpoint = news.privateClusterConfig?.enablePrivateEndpoint; |
| 1160 | if ( |
| 1161 | desiredPrivateEndpoint !== undefined && |
| 1162 | !matchesDesired(live.privateClusterConfig, { |
| 1163 | enablePrivateEndpoint: desiredPrivateEndpoint, |
| 1164 | }) |
| 1165 | ) { |
| 1166 | live = yield* applyUpdate({ |
| 1167 | desiredEnablePrivateEndpoint: desiredPrivateEndpoint, |
| 1168 | }); |
| 1169 | } |
| 1170 | |
| 1171 | const desiredMasterGlobalAccess = news.privateClusterConfig?.masterGlobalAccessConfig; |
| 1172 | if ( |
| 1173 | desiredMasterGlobalAccess !== undefined && |
| 1174 | !matchesDesired( |
| 1175 | live.privateClusterConfig?.masterGlobalAccessConfig, |
| 1176 | desiredMasterGlobalAccess, |
| 1177 | ) |
| 1178 | ) { |
| 1179 | live = yield* applyUpdate({ |
| 1180 | desiredPrivateClusterConfig: { |
| 1181 | masterGlobalAccessConfig: desiredMasterGlobalAccess, |
| 1182 | }, |
| 1183 | }); |
| 1184 | } |
| 1185 | |
| 1186 | if ( |
| 1187 | news.enableShieldedNodes !== undefined && |
| 1188 | (live.shieldedNodes?.enabled === true) !== news.enableShieldedNodes |
| 1189 | ) { |
| 1190 | live = yield* applyUpdate({ |
| 1191 | desiredShieldedNodes: { enabled: news.enableShieldedNodes }, |
| 1192 | }); |
| 1193 | } |
| 1194 | |
| 1195 | if ( |
| 1196 | news.addonsConfig !== undefined && |
| 1197 | !matchesDesired(live.addonsConfig, news.addonsConfig) |
| 1198 | ) { |
| 1199 | live = yield* applyUpdate({ desiredAddonsConfig: news.addonsConfig }); |
| 1200 | } |
| 1201 | |
| 1202 | if ( |
| 1203 | news.datapathProvider !== undefined && |
| 1204 | // GKE omits the proto3 default, so an unset provider is LEGACY. |
| 1205 | (live.networkConfig?.datapathProvider ?? "LEGACY_DATAPATH") !== news.datapathProvider |
| 1206 | ) { |
| 1207 | live = yield* applyUpdate({ |
| 1208 | desiredDatapathProvider: |
| 1209 | news.datapathProvider as container.ClusterUpdateDesiredDatapathProviderEnum, |
| 1210 | }); |
| 1211 | } |
| 1212 | |
| 1213 | if ( |
| 1214 | news.loggingConfig !== undefined && |
| 1215 | !matchesDesired(live.loggingConfig, news.loggingConfig) |
| 1216 | ) { |
| 1217 | live = yield* applyUpdate({ desiredLoggingConfig: news.loggingConfig }); |
| 1218 | } |
| 1219 | |
| 1220 | if ( |
| 1221 | news.monitoringConfig !== undefined && |
| 1222 | !matchesDesired(live.monitoringConfig, news.monitoringConfig) |
| 1223 | ) { |
| 1224 | live = yield* applyUpdate({ desiredMonitoringConfig: news.monitoringConfig }); |
| 1225 | } |
| 1226 | |
| 1227 | if ( |
| 1228 | news.costManagementConfig !== undefined && |
| 1229 | !matchesDesired(live.costManagementConfig, news.costManagementConfig) |
| 1230 | ) { |
| 1231 | live = yield* applyUpdate({ |
| 1232 | desiredCostManagementConfig: news.costManagementConfig, |
| 1233 | }); |
| 1234 | } |
| 1235 | |
| 1236 | const observedPool = live.workloadIdentityConfig?.workloadPool ?? ""; |
| 1237 | if (observedPool !== desiredPool) { |
| 1238 | const identified = yield* container.updateProjectsLocationsClusters({ |
| 1239 | name, |
| 1240 | body: { |
| 1241 | update: { |
| 1242 | desiredWorkloadIdentityConfig: { workloadPool: desiredPool }, |
| 1243 | }, |
| 1244 | }, |
| 1245 | }); |
| 1246 | yield* waitForOperation(env.project, location, identified); |
| 1247 | live = yield* waitUntilReady(name); |
| 1248 | } |
| 1249 | |
| 1250 | const attrs = toAttrs(live, env.project, output?.kubernetesObjects ?? []); |
| 1251 | const kubernetesObjects = yield* reconcileObjects({ |
| 1252 | transport: yield* getKubernetesTransport(attrs), |
| 1253 | previousObjects: output?.kubernetesObjects ?? [], |
| 1254 | desiredObjects, |
| 1255 | }); |
| 1256 | return { ...attrs, kubernetesObjects }; |
| 1257 | }), |
| 1258 | |
| 1259 | delete: Effect.fn(function* ({ olds, output, force }) { |
| 1260 | if (olds.deletionProtection === true && force !== true) { |
| 1261 | return yield* new ClusterDeletionProtected({ resourceName: output.name }); |
| 1262 | } |
| 1263 | if ((output.kubernetesObjects ?? []).length > 0) { |
| 1264 | yield* deleteObjects({ |
| 1265 | transport: yield* getKubernetesTransport(output), |
| 1266 | objects: output.kubernetesObjects ?? [], |
| 1267 | }); |
| 1268 | } |
| 1269 | const env = yield* GcpEnvironment.current; |
| 1270 | const location = normalizeLocation(output.location); |
| 1271 | yield* waitUntilSettled(output.name); |
| 1272 | const operation = yield* container |
| 1273 | .deleteProjectsLocationsClusters({ name: output.name }) |
| 1274 | .pipe( |
| 1275 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 1276 | Effect.retry({ |
| 1277 | while: (error) => |
| 1278 | error._tag === "Conflict" || |
| 1279 | (error._tag === "BadRequest" && /incompatible operation/i.test(error.message)), |
| 1280 | times: 8, |
| 1281 | schedule: Schedule.spaced("5 seconds"), |
| 1282 | }), |
| 1283 | ); |
| 1284 | if (operation !== undefined) { |
| 1285 | yield* waitForOperation(env.project, location, operation, { |
| 1286 | notFoundOk: true, |
| 1287 | }); |
| 1288 | } |
| 1289 | yield* waitUntilGone(output.name); |
| 1290 | }), |
| 1291 | }); |