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 compute from "@distilled.cloud/gcp/compute_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { waitRegionOperation } from "./operations.ts"; |
| 15 | |
| 16 | const DEFAULT_TARGET_SIZE = 0; |
| 17 | const MAX_NAME_LENGTH = 63; |
| 18 | const MAX_BASE_NAME_LENGTH = 58; |
| 19 | |
| 20 | export type RegionInstanceGroupManagerNamedPort = { |
| 21 | /** RFC1035 name for this port mapping (e.g. `"http"`). */ |
| 22 | name: string; |
| 23 | /** TCP port number (`1`–`65535`). */ |
| 24 | port: number; |
| 25 | }; |
| 26 | |
| 27 | export type RegionInstanceGroupManagerVersion = { |
| 28 | /** |
| 29 | * Instance template URL or name used for this version. The group |
| 30 | * creates VMs from this template until `targetSize` is reached. |
| 31 | */ |
| 32 | instanceTemplate?: string; |
| 33 | /** Version name unique within this manager. */ |
| 34 | name?: string; |
| 35 | /** Fixed count or percent of the group's `targetSize` for this version. */ |
| 36 | targetSize?: { |
| 37 | fixed?: number; |
| 38 | percent?: number; |
| 39 | }; |
| 40 | }; |
| 41 | |
| 42 | export type RegionInstanceGroupManagerProps = { |
| 43 | /** |
| 44 | * Manager name (RFC1035, 1-63 characters). If omitted, a unique name is |
| 45 | * generated from the stack, stage, and logical id. Changing the name |
| 46 | * replaces the manager. |
| 47 | */ |
| 48 | managerName?: string; |
| 49 | /** |
| 50 | * Region the manager lives in (e.g. `us-central1`). Immutable — |
| 51 | * changing it replaces the manager. `US-CENTRAL1` is accepted and |
| 52 | * normalized to `us-central1`. |
| 53 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 54 | */ |
| 55 | region?: string; |
| 56 | /** |
| 57 | * Instance template URL or name used to create VMs. Accepts a name |
| 58 | * (`web`), a partial URL (`projects/{project}/global/instanceTemplates/web`), |
| 59 | * or a full self-link. Mutable in place via patch. |
| 60 | */ |
| 61 | instanceTemplate: string; |
| 62 | /** |
| 63 | * Prefix attached to every VM name in the group (RFC1035, 1-58 |
| 64 | * characters). Defaults to the manager name truncated to 58 characters. |
| 65 | * Immutable — changing it replaces the manager. |
| 66 | */ |
| 67 | baseInstanceName?: string; |
| 68 | /** |
| 69 | * Optional description. Regional MIGs have no labels API, so Alchemy |
| 70 | * stamps ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) |
| 71 | * into this field for `list` / nuke. |
| 72 | */ |
| 73 | description?: string; |
| 74 | /** |
| 75 | * Target number of running VMs. Keep this `0` in tests unless you |
| 76 | * intend to provision instances. |
| 77 | * @default 0 |
| 78 | */ |
| 79 | targetSize?: number; |
| 80 | /** |
| 81 | * Named ports published on the complementary regional instance group. |
| 82 | * When omitted, observed ports are left as-is. When set (including |
| 83 | * `[]`), observed ports are replaced via `setNamedPorts`. |
| 84 | */ |
| 85 | namedPorts?: RegionInstanceGroupManagerNamedPort[]; |
| 86 | /** |
| 87 | * Canary / multi-template versions. When set, this field is patched |
| 88 | * instead of the top-level `instanceTemplate`. Exactly one version must |
| 89 | * leave `targetSize` unset. |
| 90 | */ |
| 91 | versions?: RegionInstanceGroupManagerVersion[]; |
| 92 | /** |
| 93 | * Autohealing health checks. When omitted, observed policy is left |
| 94 | * as-is. |
| 95 | */ |
| 96 | autoHealingPolicies?: compute.InstanceGroupManagerAutoHealingPolicy[]; |
| 97 | /** |
| 98 | * Rolling-update policy (type, surge, redistribution). When omitted, |
| 99 | * observed policy is left as-is. |
| 100 | */ |
| 101 | updatePolicy?: compute.InstanceGroupManagerUpdatePolicy; |
| 102 | /** |
| 103 | * Zone distribution for the regional group. `zones` is immutable — |
| 104 | * changing it replaces the manager. `targetShape` updates in place. |
| 105 | */ |
| 106 | distributionPolicy?: compute.DistributionPolicy; |
| 107 | /** |
| 108 | * Target-pool URLs that receive new VMs. When omitted, observed pools |
| 109 | * are left as-is. |
| 110 | */ |
| 111 | targetPools?: string[]; |
| 112 | /** |
| 113 | * Repair / failure policy for managed VMs. When omitted, observed |
| 114 | * policy is left as-is. |
| 115 | */ |
| 116 | instanceLifecyclePolicy?: compute.InstanceGroupManagerInstanceLifecyclePolicy; |
| 117 | }; |
| 118 | |
| 119 | export type RegionInstanceGroupManager = Resource< |
| 120 | "GCP.Compute.RegionInstanceGroupManager", |
| 121 | RegionInstanceGroupManagerProps, |
| 122 | { |
| 123 | /** Manager name. */ |
| 124 | managerName: string; |
| 125 | /** Project id. */ |
| 126 | project: string; |
| 127 | /** Region short name (`us-central1`). */ |
| 128 | region: string; |
| 129 | /** User-facing description (ownership marker stripped). */ |
| 130 | description: string | undefined; |
| 131 | /** Instance template URL currently configured on the group. */ |
| 132 | instanceTemplate: string | undefined; |
| 133 | /** Prefix used for VM names. */ |
| 134 | baseInstanceName: string | undefined; |
| 135 | /** Target number of running VMs. */ |
| 136 | targetSize: number; |
| 137 | /** Named ports currently configured on the complementary group. */ |
| 138 | namedPorts: RegionInstanceGroupManagerNamedPort[]; |
| 139 | /** Template versions currently configured. */ |
| 140 | versions: RegionInstanceGroupManagerVersion[]; |
| 141 | /** Complementary instance-group URL. */ |
| 142 | instanceGroup: string | undefined; |
| 143 | /** Server-assigned numeric id. */ |
| 144 | managerId: string | undefined; |
| 145 | /** Compute Engine self-link. */ |
| 146 | selfLink: string | undefined; |
| 147 | /** RFC3339 creation timestamp. */ |
| 148 | creationTimestamp: string | undefined; |
| 149 | /** Whether the group reports as stable. */ |
| 150 | isStable: boolean | undefined; |
| 151 | /** Zone last-segments from the distribution policy, if any. */ |
| 152 | distributionPolicyZones: string[]; |
| 153 | }, |
| 154 | never, |
| 155 | Providers |
| 156 | >; |
| 157 | |
| 158 | /** |
| 159 | * A regional Compute Engine managed instance group. |
| 160 | * |
| 161 | * The manager creates and heals VMs from an instance template, spread |
| 162 | * across zones in a region. Compute Engine has no labels on this |
| 163 | * resource, so Alchemy stamps ownership into the description |
| 164 | * (`[alchemy alchemy-stack=… alchemy-stage=… alchemy-id=…]`) so `list` / |
| 165 | * `pnpm nuke:gcp` can find them. |
| 166 | * |
| 167 | * Name, region, `baseInstanceName`, and `distributionPolicy.zones` are |
| 168 | * immutable — changing them replaces the manager. `targetSize`, |
| 169 | * `instanceTemplate` / `versions`, description, autohealing, and update |
| 170 | * policy patch in place. Named ports are synced onto the complementary |
| 171 | * regional instance group. |
| 172 | * |
| 173 | * ### Creating a Regional MIG |
| 174 | * **Example:** Generated name, no running VMs |
| 175 | * ```typescript |
| 176 | * const template = yield* GCP.Compute.InstanceTemplate("web", {}); |
| 177 | * const mig = yield* GCP.Compute.RegionInstanceGroupManager("web", { |
| 178 | * instanceTemplate: template.selfLink, |
| 179 | * targetSize: 0, |
| 180 | * }); |
| 181 | * ``` |
| 182 | * |
| 183 | * **Example:** Named group with named ports |
| 184 | * ```typescript |
| 185 | * const mig = yield* GCP.Compute.RegionInstanceGroupManager("web", { |
| 186 | * managerName: "web-mig", |
| 187 | * region: "us-central1", |
| 188 | * instanceTemplate: |
| 189 | * "projects/{project}/global/instanceTemplates/web", |
| 190 | * baseInstanceName: "web", |
| 191 | * targetSize: 3, |
| 192 | * namedPorts: [{ name: "http", port: 80 }], |
| 193 | * }); |
| 194 | * ``` |
| 195 | * |
| 196 | * @resource |
| 197 | * @category Compute |
| 198 | */ |
| 199 | export const RegionInstanceGroupManager = Resource<RegionInstanceGroupManager>( |
| 200 | "GCP.Compute.RegionInstanceGroupManager", |
| 201 | ); |
| 202 | |
| 203 | export class RegionInstanceGroupManagerNotResolved extends Data.TaggedError( |
| 204 | "GCP.Compute.RegionInstanceGroupManagerNotResolved", |
| 205 | )<{ |
| 206 | managerName: string; |
| 207 | region: string; |
| 208 | }> {} |
| 209 | |
| 210 | export class RegionInstanceGroupManagerStillExists extends Data.TaggedError( |
| 211 | "GCP.Compute.RegionInstanceGroupManagerStillExists", |
| 212 | )<{ |
| 213 | managerName: string; |
| 214 | region: string; |
| 215 | }> {} |
| 216 | |
| 217 | const lastSegment = (value: string | undefined): string => { |
| 218 | if (value === undefined || value.length === 0) return ""; |
| 219 | const trimmed = value.split("?")[0]!.replace(/\/+$/, ""); |
| 220 | const parts = trimmed.split("/").filter((part) => part.length > 0); |
| 221 | return parts[parts.length - 1] || trimmed; |
| 222 | }; |
| 223 | |
| 224 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 225 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 226 | |
| 227 | const rfc1035Name = (name: string, fallback: string, maxLength: number) => { |
| 228 | let next = name |
| 229 | .toLowerCase() |
| 230 | .replace(/[^a-z0-9-]/g, "-") |
| 231 | .replace(/-+/g, "-") |
| 232 | .replace(/^-+|-+$/g, ""); |
| 233 | if (!/^[a-z]/.test(next)) { |
| 234 | next = `m${next}`; |
| 235 | } |
| 236 | next = next.slice(0, maxLength).replace(/-+$/g, ""); |
| 237 | return next.length > 0 ? next : fallback; |
| 238 | }; |
| 239 | |
| 240 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 241 | Effect.gen(function* () { |
| 242 | return rfc1035Name( |
| 243 | name ?? |
| 244 | existing ?? |
| 245 | (yield* createPhysicalName({ |
| 246 | id, |
| 247 | maxLength: MAX_NAME_LENGTH, |
| 248 | lowercase: true, |
| 249 | })), |
| 250 | "mig", |
| 251 | MAX_NAME_LENGTH, |
| 252 | ); |
| 253 | }); |
| 254 | |
| 255 | const toBaseName = (name: string | undefined, managerName: string) => |
| 256 | rfc1035Name(name ?? managerName, "mig", MAX_BASE_NAME_LENGTH); |
| 257 | |
| 258 | const encodeDescription = (user: string | undefined, labels: Record<string, string>) => { |
| 259 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 260 | const trimmed = user?.trim(); |
| 261 | return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker; |
| 262 | }; |
| 263 | |
| 264 | const parseDescription = (description: string | undefined) => { |
| 265 | if (!description?.startsWith("[alchemy ")) { |
| 266 | return { user: description, labels: {} as Record<string, string> }; |
| 267 | } |
| 268 | const end = description.indexOf("]"); |
| 269 | if (end < 0) { |
| 270 | return { user: description, labels: {} as Record<string, string> }; |
| 271 | } |
| 272 | const labels: Record<string, string> = {}; |
| 273 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 274 | const eq = part.indexOf("="); |
| 275 | if (eq > 0) { |
| 276 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 277 | } |
| 278 | } |
| 279 | const rest = description |
| 280 | .slice(end + 1) |
| 281 | .replace(/^\n/, "") |
| 282 | .trim(); |
| 283 | return { |
| 284 | user: rest.length > 0 ? rest : undefined, |
| 285 | labels, |
| 286 | }; |
| 287 | }; |
| 288 | |
| 289 | const hasOwnershipMarker = (description: string | undefined) => |
| 290 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 291 | |
| 292 | const toTemplateUrl = (project: string, template: string) => |
| 293 | template.includes("/") ? template : `projects/${project}/global/instanceTemplates/${template}`; |
| 294 | |
| 295 | const canonPorts = ( |
| 296 | ports: readonly RegionInstanceGroupManagerNamedPort[] | undefined, |
| 297 | ): RegionInstanceGroupManagerNamedPort[] => |
| 298 | [...(ports ?? [])] |
| 299 | .map((port) => ({ name: port.name, port: port.port })) |
| 300 | .sort((a, b) => a.name.localeCompare(b.name) || a.port - b.port); |
| 301 | |
| 302 | const samePorts = ( |
| 303 | left: readonly RegionInstanceGroupManagerNamedPort[] | undefined, |
| 304 | right: readonly RegionInstanceGroupManagerNamedPort[] | undefined, |
| 305 | ) => JSON.stringify(canonPorts(left)) === JSON.stringify(canonPorts(right)); |
| 306 | |
| 307 | const fromApiPorts = ( |
| 308 | ports: readonly compute.NamedPort[] | undefined, |
| 309 | ): RegionInstanceGroupManagerNamedPort[] => |
| 310 | canonPorts( |
| 311 | (ports ?? []) |
| 312 | .filter( |
| 313 | (port): port is { name: string; port: number } => |
| 314 | typeof port.name === "string" && typeof port.port === "number", |
| 315 | ) |
| 316 | .map((port) => ({ name: port.name, port: port.port })), |
| 317 | ); |
| 318 | |
| 319 | const fromApiVersions = ( |
| 320 | versions: readonly compute.InstanceGroupManagerVersion[] | undefined, |
| 321 | ): RegionInstanceGroupManagerVersion[] => |
| 322 | (versions ?? []).map((version) => ({ |
| 323 | instanceTemplate: version.instanceTemplate, |
| 324 | name: version.name, |
| 325 | targetSize: version.targetSize |
| 326 | ? { |
| 327 | fixed: version.targetSize.fixed, |
| 328 | percent: version.targetSize.percent, |
| 329 | } |
| 330 | : undefined, |
| 331 | })); |
| 332 | |
| 333 | const sortedRefs = (values: readonly string[] | undefined) => |
| 334 | [...(values ?? [])].map(lastSegment).filter(Boolean).sort(); |
| 335 | |
| 336 | const sameRefs = (left: readonly string[] | undefined, right: readonly string[] | undefined) => |
| 337 | JSON.stringify(sortedRefs(left)) === JSON.stringify(sortedRefs(right)); |
| 338 | |
| 339 | const zonesOf = (policy: compute.DistributionPolicy | undefined) => |
| 340 | sortedRefs((policy?.zones ?? []).map((zone) => zone.zone ?? "")); |
| 341 | |
| 342 | const subsetEqual = (observed: unknown, desired: unknown): boolean => { |
| 343 | if (desired === undefined) return true; |
| 344 | if (typeof desired !== typeof observed) return false; |
| 345 | if (desired === null || observed === null) return desired === observed; |
| 346 | if (Array.isArray(desired)) { |
| 347 | if (!Array.isArray(observed) || desired.length !== observed.length) { |
| 348 | return false; |
| 349 | } |
| 350 | return desired.every((item, index) => subsetEqual(observed[index], item)); |
| 351 | } |
| 352 | if (typeof desired === "object") { |
| 353 | if (typeof observed !== "object") return false; |
| 354 | const current = observed as Record<string, unknown>; |
| 355 | return Object.entries(desired as Record<string, unknown>).every( |
| 356 | ([key, value]) => value === undefined || subsetEqual(current[key], value), |
| 357 | ); |
| 358 | } |
| 359 | return observed === desired; |
| 360 | }; |
| 361 | |
| 362 | const sameJson = (left: unknown, right: unknown) => |
| 363 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 364 | |
| 365 | const versionsChanged = ( |
| 366 | observed: readonly compute.InstanceGroupManagerVersion[] | undefined, |
| 367 | desired: readonly RegionInstanceGroupManagerVersion[] | undefined, |
| 368 | ) => { |
| 369 | if (desired === undefined) return false; |
| 370 | const left = (observed ?? []).map((version) => ({ |
| 371 | name: version.name ?? "", |
| 372 | instanceTemplate: lastSegment(version.instanceTemplate), |
| 373 | targetSize: version.targetSize ?? {}, |
| 374 | })); |
| 375 | const right = desired.map((version) => ({ |
| 376 | name: version.name ?? "", |
| 377 | instanceTemplate: lastSegment(version.instanceTemplate), |
| 378 | targetSize: version.targetSize ?? {}, |
| 379 | })); |
| 380 | return !sameJson(left, right); |
| 381 | }; |
| 382 | |
| 383 | const toAttrs = (manager: compute.InstanceGroupManager, project: string) => { |
| 384 | const { user } = parseDescription(manager.description); |
| 385 | return { |
| 386 | managerName: manager.name ?? lastSegment(manager.selfLink), |
| 387 | project, |
| 388 | region: lastSegment(manager.region).toLowerCase(), |
| 389 | description: user, |
| 390 | instanceTemplate: manager.instanceTemplate, |
| 391 | baseInstanceName: manager.baseInstanceName, |
| 392 | targetSize: manager.targetSize ?? 0, |
| 393 | namedPorts: fromApiPorts(manager.namedPorts), |
| 394 | versions: fromApiVersions(manager.versions), |
| 395 | instanceGroup: manager.instanceGroup, |
| 396 | managerId: manager.id, |
| 397 | selfLink: manager.selfLink, |
| 398 | creationTimestamp: manager.creationTimestamp, |
| 399 | isStable: manager.status?.isStable, |
| 400 | distributionPolicyZones: zonesOf(manager.distributionPolicy), |
| 401 | }; |
| 402 | }; |
| 403 | |
| 404 | const getByName = (project: string, region: string, instanceGroupManager: string) => |
| 405 | compute |
| 406 | .getRegionInstanceGroupManagers({ |
| 407 | project, |
| 408 | region, |
| 409 | instanceGroupManager, |
| 410 | }) |
| 411 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 412 | |
| 413 | const waitUntilPresent = (project: string, region: string, managerName: string) => |
| 414 | getByName(project, region, managerName).pipe( |
| 415 | Effect.flatMap((manager) => |
| 416 | manager !== undefined |
| 417 | ? Effect.succeed(manager) |
| 418 | : Effect.fail( |
| 419 | new RegionInstanceGroupManagerNotResolved({ |
| 420 | managerName, |
| 421 | region, |
| 422 | }), |
| 423 | ), |
| 424 | ), |
| 425 | Effect.retry({ |
| 426 | while: (error) => error._tag === "GCP.Compute.RegionInstanceGroupManagerNotResolved", |
| 427 | times: 8, |
| 428 | schedule: Schedule.spaced("1 second"), |
| 429 | }), |
| 430 | Effect.catchTag("GCP.Compute.RegionInstanceGroupManagerNotResolved", () => Effect.undefined), |
| 431 | ); |
| 432 | |
| 433 | const waitUntilGone = (project: string, region: string, managerName: string) => |
| 434 | getByName(project, region, managerName).pipe( |
| 435 | Effect.flatMap((manager) => |
| 436 | manager === undefined |
| 437 | ? Effect.void |
| 438 | : Effect.fail( |
| 439 | new RegionInstanceGroupManagerStillExists({ |
| 440 | managerName, |
| 441 | region, |
| 442 | }), |
| 443 | ), |
| 444 | ), |
| 445 | Effect.retry({ |
| 446 | while: (error) => error._tag === "GCP.Compute.RegionInstanceGroupManagerStillExists", |
| 447 | times: 15, |
| 448 | schedule: Schedule.spaced("2 seconds"), |
| 449 | }), |
| 450 | ); |
| 451 | |
| 452 | const getInstanceGroup = (project: string, region: string, instanceGroup: string) => |
| 453 | compute |
| 454 | .getRegionInstanceGroups({ project, region, instanceGroup }) |
| 455 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 456 | |
| 457 | const syncNamedPorts = ( |
| 458 | project: string, |
| 459 | region: string, |
| 460 | managerName: string, |
| 461 | instanceGroupUrl: string | undefined, |
| 462 | namedPorts: RegionInstanceGroupManagerNamedPort[], |
| 463 | ) => |
| 464 | Effect.gen(function* () { |
| 465 | const instanceGroup = lastSegment(instanceGroupUrl) || managerName; |
| 466 | const group = yield* getInstanceGroup(project, region, instanceGroup).pipe( |
| 467 | Effect.flatMap((current) => |
| 468 | current !== undefined |
| 469 | ? Effect.succeed(current) |
| 470 | : Effect.fail( |
| 471 | new RegionInstanceGroupManagerNotResolved({ |
| 472 | managerName, |
| 473 | region, |
| 474 | }), |
| 475 | ), |
| 476 | ), |
| 477 | Effect.retry({ |
| 478 | while: (error) => error._tag === "GCP.Compute.RegionInstanceGroupManagerNotResolved", |
| 479 | times: 8, |
| 480 | schedule: Schedule.spaced("1 second"), |
| 481 | }), |
| 482 | ); |
| 483 | const operation = yield* compute |
| 484 | .setNamedPortsRegionInstanceGroups({ |
| 485 | project, |
| 486 | region, |
| 487 | instanceGroup, |
| 488 | body: { |
| 489 | namedPorts, |
| 490 | fingerprint: group.fingerprint, |
| 491 | }, |
| 492 | }) |
| 493 | .pipe( |
| 494 | Effect.retry({ |
| 495 | while: (error) => error._tag === "Conflict", |
| 496 | times: 5, |
| 497 | schedule: Schedule.exponential("250 millis"), |
| 498 | }), |
| 499 | ); |
| 500 | yield* waitRegionOperation(project, region, operation); |
| 501 | }); |
| 502 | |
| 503 | const toVersionBodies = ( |
| 504 | project: string, |
| 505 | versions: readonly RegionInstanceGroupManagerVersion[], |
| 506 | ): compute.InstanceGroupManagerVersion[] => |
| 507 | versions.map((version) => ({ |
| 508 | name: version.name, |
| 509 | instanceTemplate: |
| 510 | version.instanceTemplate !== undefined |
| 511 | ? toTemplateUrl(project, version.instanceTemplate) |
| 512 | : undefined, |
| 513 | targetSize: version.targetSize, |
| 514 | })); |
| 515 | |
| 516 | export const RegionInstanceGroupManagerProvider = () => |
| 517 | Provider.succeed(RegionInstanceGroupManager, { |
| 518 | stables: [ |
| 519 | "managerName", |
| 520 | "project", |
| 521 | "region", |
| 522 | "baseInstanceName", |
| 523 | "managerId", |
| 524 | "instanceGroup", |
| 525 | "selfLink", |
| 526 | "creationTimestamp", |
| 527 | ], |
| 528 | |
| 529 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 530 | if (!isResolved(news)) return undefined; |
| 531 | const env = yield* GcpEnvironment.current; |
| 532 | const previousName = olds?.managerName ?? output?.managerName; |
| 533 | const nextName = news.managerName ?? previousName; |
| 534 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 535 | const nextRegion = normalizeRegion(news.region ?? output?.region, env.region); |
| 536 | const previousBase = olds?.baseInstanceName ?? output?.baseInstanceName ?? previousName; |
| 537 | const nextBase = |
| 538 | news.baseInstanceName !== undefined |
| 539 | ? toBaseName(news.baseInstanceName, nextName ?? previousName ?? "mig") |
| 540 | : previousBase; |
| 541 | const nameChanged = |
| 542 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 543 | const regionChanged = previousRegion !== nextRegion; |
| 544 | const baseChanged = |
| 545 | previousBase !== undefined && nextBase !== undefined && previousBase !== nextBase; |
| 546 | const previousZones = |
| 547 | olds?.distributionPolicy !== undefined |
| 548 | ? zonesOf(olds.distributionPolicy) |
| 549 | : (output?.distributionPolicyZones ?? []); |
| 550 | const nextZones = zonesOf(news.distributionPolicy); |
| 551 | const zonesChanged = |
| 552 | news.distributionPolicy?.zones !== undefined && |
| 553 | previousZones.length > 0 && |
| 554 | nextZones.length > 0 && |
| 555 | !sameJson(previousZones, nextZones); |
| 556 | if (!nameChanged && !regionChanged && !baseChanged && !zonesChanged) { |
| 557 | return undefined; |
| 558 | } |
| 559 | const sameIdentity = previousName === nextName && previousRegion === nextRegion; |
| 560 | return { |
| 561 | action: "replace" as const, |
| 562 | deleteFirst: sameIdentity, |
| 563 | }; |
| 564 | }), |
| 565 | |
| 566 | read: Effect.fn(function* ({ id, olds, output }) { |
| 567 | const env = yield* GcpEnvironment.current; |
| 568 | const managerName = yield* toName(id, olds?.managerName, output?.managerName); |
| 569 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 570 | const existing = yield* getByName(env.project, region, managerName); |
| 571 | if (existing === undefined) return undefined; |
| 572 | const attrs = toAttrs(existing, env.project); |
| 573 | const { labels } = parseDescription(existing.description); |
| 574 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 575 | }), |
| 576 | |
| 577 | list: () => |
| 578 | Effect.gen(function* () { |
| 579 | const env = yield* GcpEnvironment.current; |
| 580 | const pages = yield* compute.aggregatedListInstanceGroupManagers |
| 581 | .pages({ |
| 582 | project: env.project, |
| 583 | maxResults: 500, |
| 584 | returnPartialSuccess: true, |
| 585 | }) |
| 586 | .pipe(Stream.runCollect); |
| 587 | return Array.from(pages).flatMap((page) => |
| 588 | Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => { |
| 589 | if (!scope.startsWith("regions/")) return []; |
| 590 | return (scoped?.instanceGroupManagers ?? []) |
| 591 | .filter( |
| 592 | (manager) => |
| 593 | hasOwnershipMarker(manager.description) && lastSegment(manager.region).length > 0, |
| 594 | ) |
| 595 | .map((manager) => toAttrs(manager, env.project)); |
| 596 | }), |
| 597 | ); |
| 598 | }), |
| 599 | |
| 600 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 601 | const env = yield* GcpEnvironment.current; |
| 602 | const managerName = yield* toName(id, news.managerName, output?.managerName); |
| 603 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 604 | const ownership = yield* createInternalLabels(id); |
| 605 | const description = encodeDescription(news.description, ownership); |
| 606 | const instanceTemplate = toTemplateUrl(env.project, news.instanceTemplate); |
| 607 | const baseInstanceName = toBaseName(news.baseInstanceName, managerName); |
| 608 | const targetSize = news.targetSize ?? DEFAULT_TARGET_SIZE; |
| 609 | const namedPorts = news.namedPorts !== undefined ? canonPorts(news.namedPorts) : undefined; |
| 610 | |
| 611 | let current = yield* getByName(env.project, region, managerName); |
| 612 | |
| 613 | if (current === undefined) { |
| 614 | yield* compute |
| 615 | .insertRegionInstanceGroupManagers({ |
| 616 | project: env.project, |
| 617 | region, |
| 618 | body: { |
| 619 | name: managerName, |
| 620 | description, |
| 621 | instanceTemplate, |
| 622 | baseInstanceName, |
| 623 | targetSize, |
| 624 | namedPorts: |
| 625 | namedPorts !== undefined && namedPorts.length > 0 ? namedPorts : undefined, |
| 626 | versions: |
| 627 | news.versions !== undefined |
| 628 | ? toVersionBodies(env.project, news.versions) |
| 629 | : undefined, |
| 630 | autoHealingPolicies: news.autoHealingPolicies, |
| 631 | updatePolicy: news.updatePolicy, |
| 632 | distributionPolicy: news.distributionPolicy, |
| 633 | targetPools: news.targetPools, |
| 634 | instanceLifecyclePolicy: news.instanceLifecyclePolicy, |
| 635 | }, |
| 636 | }) |
| 637 | .pipe( |
| 638 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 639 | Effect.flatMap((operation) => |
| 640 | operation === undefined |
| 641 | ? Effect.void |
| 642 | : waitRegionOperation(env.project, region, operation, { |
| 643 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 644 | }).pipe(Effect.asVoid), |
| 645 | ), |
| 646 | ); |
| 647 | current = yield* waitUntilPresent(env.project, region, managerName); |
| 648 | } |
| 649 | |
| 650 | if (current === undefined) { |
| 651 | return yield* new RegionInstanceGroupManagerNotResolved({ |
| 652 | managerName, |
| 653 | region, |
| 654 | }); |
| 655 | } |
| 656 | |
| 657 | const patch: compute.InstanceGroupManager = { |
| 658 | fingerprint: current.fingerprint, |
| 659 | }; |
| 660 | let dirty = false; |
| 661 | |
| 662 | if ((current.description ?? "") !== description) { |
| 663 | patch.description = description; |
| 664 | dirty = true; |
| 665 | } |
| 666 | if ((current.targetSize ?? 0) !== targetSize) { |
| 667 | patch.targetSize = targetSize; |
| 668 | dirty = true; |
| 669 | } |
| 670 | if (lastSegment(current.instanceTemplate) !== lastSegment(instanceTemplate)) { |
| 671 | patch.instanceTemplate = instanceTemplate; |
| 672 | dirty = true; |
| 673 | } |
| 674 | if (versionsChanged(current.versions, news.versions)) { |
| 675 | patch.versions = toVersionBodies(env.project, news.versions ?? []); |
| 676 | dirty = true; |
| 677 | } |
| 678 | if ( |
| 679 | news.autoHealingPolicies !== undefined && |
| 680 | !subsetEqual(current.autoHealingPolicies ?? [], news.autoHealingPolicies) |
| 681 | ) { |
| 682 | patch.autoHealingPolicies = news.autoHealingPolicies; |
| 683 | dirty = true; |
| 684 | } |
| 685 | if ( |
| 686 | news.updatePolicy !== undefined && |
| 687 | !subsetEqual(current.updatePolicy ?? {}, news.updatePolicy) |
| 688 | ) { |
| 689 | patch.updatePolicy = news.updatePolicy; |
| 690 | dirty = true; |
| 691 | } |
| 692 | if (news.targetPools !== undefined && !sameRefs(current.targetPools, news.targetPools)) { |
| 693 | patch.targetPools = news.targetPools; |
| 694 | dirty = true; |
| 695 | } |
| 696 | if ( |
| 697 | news.instanceLifecyclePolicy !== undefined && |
| 698 | !subsetEqual(current.instanceLifecyclePolicy ?? {}, news.instanceLifecyclePolicy) |
| 699 | ) { |
| 700 | patch.instanceLifecyclePolicy = news.instanceLifecyclePolicy; |
| 701 | dirty = true; |
| 702 | } |
| 703 | if ( |
| 704 | news.distributionPolicy?.targetShape !== undefined && |
| 705 | news.distributionPolicy.targetShape !== current.distributionPolicy?.targetShape |
| 706 | ) { |
| 707 | patch.distributionPolicy = { |
| 708 | targetShape: news.distributionPolicy.targetShape, |
| 709 | }; |
| 710 | dirty = true; |
| 711 | } |
| 712 | |
| 713 | if (dirty) { |
| 714 | yield* compute |
| 715 | .patchRegionInstanceGroupManagers({ |
| 716 | project: env.project, |
| 717 | region, |
| 718 | instanceGroupManager: managerName, |
| 719 | body: patch, |
| 720 | }) |
| 721 | .pipe( |
| 722 | Effect.retry({ |
| 723 | while: (error) => error._tag === "Conflict", |
| 724 | times: 5, |
| 725 | schedule: Schedule.exponential("250 millis"), |
| 726 | }), |
| 727 | Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)), |
| 728 | ); |
| 729 | current = (yield* getByName(env.project, region, managerName)) ?? current; |
| 730 | } |
| 731 | |
| 732 | if (namedPorts !== undefined && !samePorts(fromApiPorts(current.namedPorts), namedPorts)) { |
| 733 | yield* syncNamedPorts(env.project, region, managerName, current.instanceGroup, namedPorts); |
| 734 | current = (yield* getByName(env.project, region, managerName)) ?? current; |
| 735 | } |
| 736 | |
| 737 | return toAttrs(current, env.project); |
| 738 | }), |
| 739 | |
| 740 | delete: Effect.fn(function* ({ output }) { |
| 741 | const env = yield* GcpEnvironment.current; |
| 742 | const project = output.project || env.project; |
| 743 | const region = normalizeRegion(output.region, env.region); |
| 744 | const operation = yield* compute |
| 745 | .deleteRegionInstanceGroupManagers({ |
| 746 | project, |
| 747 | region, |
| 748 | instanceGroupManager: output.managerName, |
| 749 | }) |
| 750 | .pipe( |
| 751 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 752 | Effect.retry({ |
| 753 | while: (error) => error._tag === "Conflict", |
| 754 | times: 8, |
| 755 | schedule: Schedule.spaced("2 seconds"), |
| 756 | }), |
| 757 | ); |
| 758 | if (operation !== undefined) { |
| 759 | yield* waitRegionOperation(project, region, operation, { |
| 760 | ignore: ["RESOURCE_NOT_FOUND"], |
| 761 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 762 | } |
| 763 | yield* waitUntilGone(project, region, output.managerName); |
| 764 | }), |
| 765 | }); |