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 { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { waitRegionOperation } from "./operations.ts"; |
| 14 | |
| 15 | const DEFAULT_ADVERTISE_MODE = "DEFAULT"; |
| 16 | const DEFAULT_KEEPALIVE = 20; |
| 17 | const MAX_NAME_LENGTH = 63; |
| 18 | |
| 19 | const OWNERSHIP_KEYS = ["alchemy-stack", "alchemy-stage", "alchemy-id"] as const; |
| 20 | |
| 21 | export type RouterAdvertisedIpRange = { |
| 22 | /** CIDR to advertise (for example `10.0.0.0/8`). */ |
| 23 | range: string; |
| 24 | /** Optional description of this advertised range. */ |
| 25 | description?: string; |
| 26 | }; |
| 27 | |
| 28 | export type RouterBgp = { |
| 29 | /** |
| 30 | * Local BGP ASN. Must be an RFC6996 private ASN (16-bit or 32-bit). |
| 31 | * Shared by every VPN tunnel attached to this router. |
| 32 | */ |
| 33 | asn: number; |
| 34 | /** |
| 35 | * Advertisement mode. `CUSTOM` requires `advertisedGroups` and/or |
| 36 | * `advertisedIpRanges`. |
| 37 | * @default "DEFAULT" |
| 38 | */ |
| 39 | advertiseMode?: compute.RouterBgpAdvertiseModeEnum; |
| 40 | /** |
| 41 | * Prefix groups to advertise when `advertiseMode` is `CUSTOM`. The only |
| 42 | * valid value today is `ALL_SUBNETS`. |
| 43 | */ |
| 44 | advertisedGroups?: string[]; |
| 45 | /** |
| 46 | * Individual CIDRs to advertise when `advertiseMode` is `CUSTOM`. |
| 47 | */ |
| 48 | advertisedIpRanges?: RouterAdvertisedIpRange[]; |
| 49 | /** |
| 50 | * Seconds between BGP keepalives (20–60). Hold time is 3× this value. |
| 51 | * @default 20 |
| 52 | */ |
| 53 | keepaliveInterval?: number; |
| 54 | /** |
| 55 | * Link-local IPv4 `/30` or larger from `169.254.0.0/16` used as the BGP |
| 56 | * identifier (router ID). |
| 57 | */ |
| 58 | identifierRange?: string; |
| 59 | }; |
| 60 | |
| 61 | export type RouterNatSubnetwork = { |
| 62 | /** Subnetwork name, partial URL, or full resource URL. */ |
| 63 | name: string; |
| 64 | /** |
| 65 | * Ranges of this subnetwork to translate (`ALL_IP_RANGES`, |
| 66 | * `PRIMARY_IP_RANGE`, `LIST_OF_SECONDARY_IP_RANGES`). |
| 67 | * @default ["ALL_IP_RANGES"] |
| 68 | */ |
| 69 | sourceIpRangesToNat?: compute.RouterNatSubnetworkToNatSourceIpRangesToNatItemEnum[]; |
| 70 | /** |
| 71 | * Secondary range names to translate. Requires |
| 72 | * `LIST_OF_SECONDARY_IP_RANGES` in `sourceIpRangesToNat`. |
| 73 | */ |
| 74 | secondaryIpRangeNames?: string[]; |
| 75 | }; |
| 76 | |
| 77 | export type RouterNatLogConfig = { |
| 78 | /** Export NAT logs. */ |
| 79 | enable: boolean; |
| 80 | /** |
| 81 | * Which connections to log (`ERRORS_ONLY`, `TRANSLATIONS_ONLY`, `ALL`). |
| 82 | * @default "ALL" |
| 83 | */ |
| 84 | filter?: compute.RouterNatLogConfigFilterEnum; |
| 85 | }; |
| 86 | |
| 87 | export type RouterNat = { |
| 88 | /** NAT name, unique within the router (RFC1035, 1-63 chars). */ |
| 89 | name: string; |
| 90 | /** |
| 91 | * Which subnetwork ranges are translated: `ALL_SUBNETWORKS_ALL_IP_RANGES`, |
| 92 | * `ALL_SUBNETWORKS_ALL_PRIMARY_IP_RANGES`, or `LIST_OF_SUBNETWORKS` |
| 93 | * (with `subnetworks`). |
| 94 | */ |
| 95 | sourceSubnetworkIpRangesToNat: compute.RouterNatSourceSubnetworkIpRangesToNatEnum; |
| 96 | /** Subnetworks to translate when `LIST_OF_SUBNETWORKS` is selected. */ |
| 97 | subnetworks?: RouterNatSubnetwork[]; |
| 98 | /** |
| 99 | * `AUTO_ONLY` lets Google allocate external IPs; `MANUAL_ONLY` uses |
| 100 | * `natIps`. |
| 101 | * @default "AUTO_ONLY" |
| 102 | */ |
| 103 | natIpAllocateOption?: compute.RouterNatNatIpAllocateOptionEnum; |
| 104 | /** |
| 105 | * Static external addresses (`GCP.Compute.Address` self links or names) |
| 106 | * used with `MANUAL_ONLY`. |
| 107 | */ |
| 108 | natIps?: string[]; |
| 109 | /** Minimum ports allocated to each VM. */ |
| 110 | minPortsPerVm?: number; |
| 111 | /** Maximum ports per VM when dynamic port allocation is enabled. */ |
| 112 | maxPortsPerVm?: number; |
| 113 | /** Enable dynamic port allocation. */ |
| 114 | enableDynamicPortAllocation?: boolean; |
| 115 | /** Enable endpoint-independent mapping. */ |
| 116 | enableEndpointIndependentMapping?: boolean; |
| 117 | /** UDP idle timeout in seconds. */ |
| 118 | udpIdleTimeoutSec?: number; |
| 119 | /** ICMP idle timeout in seconds. */ |
| 120 | icmpIdleTimeoutSec?: number; |
| 121 | /** TCP established-connection idle timeout in seconds. */ |
| 122 | tcpEstablishedIdleTimeoutSec?: number; |
| 123 | /** TCP transitory-connection idle timeout in seconds. */ |
| 124 | tcpTransitoryIdleTimeoutSec?: number; |
| 125 | /** |
| 126 | * TCP TIME_WAIT timeout in seconds. |
| 127 | * @default 120 |
| 128 | */ |
| 129 | tcpTimeWaitTimeoutSec?: number; |
| 130 | /** |
| 131 | * Network tier for automatically allocated NAT addresses (`PREMIUM` or |
| 132 | * `STANDARD`). |
| 133 | * @default the project's default network tier |
| 134 | */ |
| 135 | autoNetworkTier?: compute.RouterNatAutoNetworkTierEnum; |
| 136 | /** |
| 137 | * Endpoint types whose traffic is translated (`ENDPOINT_TYPE_VM`, |
| 138 | * `ENDPOINT_TYPE_SWG`, `ENDPOINT_TYPE_MANAGED_PROXY_LB`). |
| 139 | * @default ["ENDPOINT_TYPE_VM"] |
| 140 | */ |
| 141 | endpointTypes?: compute.RouterNatEndpointTypesItemEnum[]; |
| 142 | /** NAT logging. */ |
| 143 | logConfig?: RouterNatLogConfig; |
| 144 | }; |
| 145 | |
| 146 | export type RouterProps = { |
| 147 | /** |
| 148 | * Router name (RFC1035, 1-63 chars). If omitted, a unique name is |
| 149 | * generated from the stack, stage, and logical id. Immutable — changing |
| 150 | * it replaces the router. |
| 151 | */ |
| 152 | routerName?: string; |
| 153 | /** |
| 154 | * Region the router lives in. Immutable — changing it replaces the |
| 155 | * router. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 156 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 157 | */ |
| 158 | region?: string; |
| 159 | /** |
| 160 | * VPC network this router belongs to. Accepts a name (`default`), a |
| 161 | * partial URL (`global/networks/default`), or a full resource URL. |
| 162 | * Immutable — changing it replaces the router. |
| 163 | */ |
| 164 | network: string; |
| 165 | /** |
| 166 | * Optional description. Compute Router has no `labels` field, so Alchemy |
| 167 | * ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is stored |
| 168 | * in the description for `list` / nuke. |
| 169 | */ |
| 170 | description?: string; |
| 171 | /** |
| 172 | * BGP configuration. Omit when the router is NAT-only. |
| 173 | */ |
| 174 | bgp?: RouterBgp; |
| 175 | /** |
| 176 | * Cloud NAT gateways hosted on this router. Updated in place. Omit to |
| 177 | * leave the router's NATs unmanaged; `[]` removes all of them. |
| 178 | */ |
| 179 | nats?: RouterNat[]; |
| 180 | /** |
| 181 | * Dedicated for encrypted VLAN attachments. Immutable — changing it |
| 182 | * replaces the router. |
| 183 | * @default false |
| 184 | */ |
| 185 | encryptedInterconnectRouter?: boolean; |
| 186 | /** |
| 187 | * NCC Gateway spoke URI. Immutable — changing it replaces the router. |
| 188 | * Mutually exclusive with `network` at the API. |
| 189 | */ |
| 190 | nccGateway?: string; |
| 191 | }; |
| 192 | |
| 193 | export type Router = Resource< |
| 194 | "GCP.Compute.Router", |
| 195 | RouterProps, |
| 196 | { |
| 197 | /** RFC1035 router name. */ |
| 198 | routerName: string; |
| 199 | /** Project id. */ |
| 200 | project: string; |
| 201 | /** Region short name (`us-central1`). */ |
| 202 | region: string; |
| 203 | /** Parent VPC network URL. */ |
| 204 | network: string; |
| 205 | /** User description (Alchemy ownership marker stripped). */ |
| 206 | description: string | undefined; |
| 207 | /** BGP configuration, if set. */ |
| 208 | bgp: RouterBgp | undefined; |
| 209 | /** Cloud NAT gateways on this router. */ |
| 210 | nats: RouterNat[]; |
| 211 | /** Whether this router is dedicated to encrypted interconnect. */ |
| 212 | encryptedInterconnectRouter: boolean; |
| 213 | /** NCC Gateway spoke URI, if any. */ |
| 214 | nccGateway: string | undefined; |
| 215 | /** Server-defined resource URL. */ |
| 216 | selfLink: string | undefined; |
| 217 | /** Server-assigned numeric id. */ |
| 218 | routerId: string | undefined; |
| 219 | /** RFC3339 creation timestamp. */ |
| 220 | creationTimestamp: string | undefined; |
| 221 | }, |
| 222 | never, |
| 223 | Providers |
| 224 | >; |
| 225 | |
| 226 | /** |
| 227 | * A regional Cloud Router. |
| 228 | * |
| 229 | * Cloud Routers advertise VPC routes over BGP to VPN tunnels and |
| 230 | * interconnects, and they host Cloud NAT. Compute Router has no `labels` |
| 231 | * field — Alchemy stamps `alchemy-stack` / `alchemy-stage` / `alchemy-id` |
| 232 | * into the description so `list` and `pnpm nuke:gcp` can find owned |
| 233 | * routers. |
| 234 | * |
| 235 | * Name, region, network, `encryptedInterconnectRouter`, and `nccGateway` |
| 236 | * are immutable. Description and BGP (ASN, advertise mode, advertised |
| 237 | * ranges, keepalive) and Cloud NAT gateways (`nats`) update in place via |
| 238 | * `routers.patch`. |
| 239 | * |
| 240 | * ### Creating a Router |
| 241 | * **Example:** Generated name on a custom-mode VPC |
| 242 | * ```typescript |
| 243 | * const network = yield* GCP.Compute.Network("Vpc", { |
| 244 | * autoCreateSubnetworks: false, |
| 245 | * }); |
| 246 | * const router = yield* GCP.Compute.Router("Edge", { |
| 247 | * network: network.networkName, |
| 248 | * }); |
| 249 | * ``` |
| 250 | * |
| 251 | * **Example:** Named router with BGP |
| 252 | * ```typescript |
| 253 | * const router = yield* GCP.Compute.Router("Edge", { |
| 254 | * routerName: "app-router", |
| 255 | * region: "us-central1", |
| 256 | * network: "app-vpc", |
| 257 | * description: "edge bgp", |
| 258 | * bgp: { asn: 65001, advertiseMode: "DEFAULT" }, |
| 259 | * }); |
| 260 | * ``` |
| 261 | * |
| 262 | * ### Cloud NAT |
| 263 | * **Example:** NAT a subnet through a static egress IP |
| 264 | * ```typescript |
| 265 | * const egressIp = yield* GCP.Compute.Address("EgressIp", { |
| 266 | * addressType: "EXTERNAL", |
| 267 | * }); |
| 268 | * const router = yield* GCP.Compute.Router("Nat", { |
| 269 | * network: network.networkName, |
| 270 | * nats: [ |
| 271 | * { |
| 272 | * name: "egress", |
| 273 | * sourceSubnetworkIpRangesToNat: "LIST_OF_SUBNETWORKS", |
| 274 | * subnetworks: [{ name: subnet.subnetworkName }], |
| 275 | * natIpAllocateOption: "MANUAL_ONLY", |
| 276 | * natIps: [egressIp.selfLink.as<string>()], |
| 277 | * logConfig: { enable: true, filter: "ERRORS_ONLY" }, |
| 278 | * }, |
| 279 | * ], |
| 280 | * }); |
| 281 | * ``` |
| 282 | * |
| 283 | * ### Custom advertisements |
| 284 | * **Example:** Advertise all subnets plus a CIDR |
| 285 | * ```typescript |
| 286 | * const router = yield* GCP.Compute.Router("Edge", { |
| 287 | * network: network.networkName, |
| 288 | * bgp: { |
| 289 | * asn: 65001, |
| 290 | * advertiseMode: "CUSTOM", |
| 291 | * advertisedGroups: ["ALL_SUBNETS"], |
| 292 | * advertisedIpRanges: [ |
| 293 | * { range: "10.0.0.0/8", description: "rfc1918" }, |
| 294 | * ], |
| 295 | * }, |
| 296 | * }); |
| 297 | * ``` |
| 298 | * |
| 299 | * @resource |
| 300 | * @category Compute |
| 301 | */ |
| 302 | export const Router = Resource<Router>("GCP.Compute.Router"); |
| 303 | |
| 304 | export class RouterNotResolved extends Data.TaggedError("GCP.Compute.RouterNotResolved")<{ |
| 305 | routerName: string; |
| 306 | region: string; |
| 307 | }> {} |
| 308 | |
| 309 | export class RouterOperationPending extends Data.TaggedError("GCP.Compute.RouterOperationPending")<{ |
| 310 | operation: string; |
| 311 | status: string | undefined; |
| 312 | }> {} |
| 313 | |
| 314 | const lastSegment = (value: string) => { |
| 315 | const trimmed = value.replace(/\/+$/, ""); |
| 316 | const parts = trimmed.split("/"); |
| 317 | return parts[parts.length - 1] || trimmed; |
| 318 | }; |
| 319 | |
| 320 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 321 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 322 | |
| 323 | const linkKey = (value: string | undefined) => |
| 324 | value === undefined || value === "" ? "" : lastSegment(value).toLowerCase(); |
| 325 | |
| 326 | const networkRef = (project: string, network: string) => { |
| 327 | if (network.includes("/")) { |
| 328 | return network.startsWith("projects/") || network.startsWith("http") |
| 329 | ? network |
| 330 | : `projects/${project}/${network.replace(/^\//, "")}`; |
| 331 | } |
| 332 | return `projects/${project}/global/networks/${network}`; |
| 333 | }; |
| 334 | |
| 335 | const encodeDescription = (internal: Record<string, string>, user?: string): string => { |
| 336 | const marker = OWNERSHIP_KEYS.map((key) => `${key}=${internal[key] ?? ""}`).join(" "); |
| 337 | return user && user.length > 0 ? `${marker}\n${user}` : marker; |
| 338 | }; |
| 339 | |
| 340 | const parseDescription = (description: string | undefined) => { |
| 341 | if (!description) { |
| 342 | return { labels: {} as Record<string, string>, description: undefined }; |
| 343 | } |
| 344 | const newline = description.indexOf("\n"); |
| 345 | const first = newline === -1 ? description : description.slice(0, newline); |
| 346 | const rest = newline === -1 ? undefined : description.slice(newline + 1); |
| 347 | if (!first.includes("alchemy-id=") || !first.includes("alchemy-stack=")) { |
| 348 | return { labels: {} as Record<string, string>, description }; |
| 349 | } |
| 350 | const labels: Record<string, string> = {}; |
| 351 | for (const part of first.split(/\s+/)) { |
| 352 | const eq = part.indexOf("="); |
| 353 | if (eq > 0) { |
| 354 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 355 | } |
| 356 | } |
| 357 | return { |
| 358 | labels, |
| 359 | description: rest && rest.length > 0 ? rest : undefined, |
| 360 | }; |
| 361 | }; |
| 362 | |
| 363 | const hasAlchemyMarker = (description: string | undefined) => |
| 364 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 365 | |
| 366 | const toRouterName = (id: string, name: string | undefined, existing?: string) => |
| 367 | Effect.gen(function* () { |
| 368 | if (name !== undefined) return name; |
| 369 | if (existing !== undefined) return existing; |
| 370 | const generated = yield* createPhysicalName({ |
| 371 | id, |
| 372 | maxLength: MAX_NAME_LENGTH, |
| 373 | lowercase: true, |
| 374 | }); |
| 375 | return /^[a-z]/.test(generated) ? generated : `r${generated}`.slice(0, MAX_NAME_LENGTH); |
| 376 | }); |
| 377 | |
| 378 | const groupsKey = (groups: ReadonlyArray<string> | undefined) => |
| 379 | [...(groups ?? [])] |
| 380 | .map((group) => group.toUpperCase()) |
| 381 | .sort() |
| 382 | .join("\0"); |
| 383 | |
| 384 | const rangesKey = (ranges: ReadonlyArray<RouterAdvertisedIpRange> | undefined) => |
| 385 | JSON.stringify( |
| 386 | [...(ranges ?? [])] |
| 387 | .map((range) => ({ |
| 388 | range: range.range, |
| 389 | description: range.description ?? "", |
| 390 | })) |
| 391 | .sort((a, b) => a.range.localeCompare(b.range)), |
| 392 | ); |
| 393 | |
| 394 | const toAdvertiseMode = ( |
| 395 | value: string | undefined, |
| 396 | ): compute.RouterBgpAdvertiseModeEnum | undefined => { |
| 397 | switch (value) { |
| 398 | case "CUSTOM": |
| 399 | case "DEFAULT": |
| 400 | return value; |
| 401 | default: |
| 402 | return undefined; |
| 403 | } |
| 404 | }; |
| 405 | |
| 406 | const toBgp = (bgp: compute.RouterBgp | undefined): RouterBgp | undefined => { |
| 407 | if (bgp === undefined || bgp.asn === undefined) return undefined; |
| 408 | return { |
| 409 | asn: bgp.asn, |
| 410 | advertiseMode: toAdvertiseMode(bgp.advertiseMode), |
| 411 | advertisedGroups: bgp.advertisedGroups, |
| 412 | advertisedIpRanges: (bgp.advertisedIpRanges ?? []) |
| 413 | .filter( |
| 414 | (range): range is compute.RouterAdvertisedIpRange & { range: string } => |
| 415 | typeof range.range === "string" && range.range.length > 0, |
| 416 | ) |
| 417 | .map((range) => ({ |
| 418 | range: range.range, |
| 419 | description: range.description, |
| 420 | })), |
| 421 | keepaliveInterval: bgp.keepaliveInterval, |
| 422 | identifierRange: bgp.identifierRange, |
| 423 | }; |
| 424 | }; |
| 425 | |
| 426 | const desiredBgp = (bgp: RouterBgp): compute.RouterBgp => { |
| 427 | const advertiseMode = bgp.advertiseMode ?? DEFAULT_ADVERTISE_MODE; |
| 428 | const body: compute.RouterBgp = { |
| 429 | asn: bgp.asn, |
| 430 | advertiseMode, |
| 431 | keepaliveInterval: bgp.keepaliveInterval ?? DEFAULT_KEEPALIVE, |
| 432 | }; |
| 433 | if (advertiseMode === "CUSTOM") { |
| 434 | body.advertisedGroups = bgp.advertisedGroups ?? []; |
| 435 | body.advertisedIpRanges = (bgp.advertisedIpRanges ?? []).map((range) => ({ |
| 436 | range: range.range, |
| 437 | description: range.description, |
| 438 | })); |
| 439 | } |
| 440 | if (bgp.identifierRange !== undefined) { |
| 441 | body.identifierRange = bgp.identifierRange; |
| 442 | } |
| 443 | return body; |
| 444 | }; |
| 445 | |
| 446 | const bgpEqual = (observed: RouterBgp | undefined, desired: RouterBgp) => { |
| 447 | if (observed === undefined) return false; |
| 448 | const advertiseMode = desired.advertiseMode ?? DEFAULT_ADVERTISE_MODE; |
| 449 | if (observed.asn !== desired.asn) return false; |
| 450 | if ((observed.advertiseMode ?? DEFAULT_ADVERTISE_MODE) !== advertiseMode) { |
| 451 | return false; |
| 452 | } |
| 453 | if ( |
| 454 | (observed.keepaliveInterval ?? DEFAULT_KEEPALIVE) !== |
| 455 | (desired.keepaliveInterval ?? DEFAULT_KEEPALIVE) |
| 456 | ) { |
| 457 | return false; |
| 458 | } |
| 459 | if ( |
| 460 | desired.identifierRange !== undefined && |
| 461 | observed.identifierRange !== desired.identifierRange |
| 462 | ) { |
| 463 | return false; |
| 464 | } |
| 465 | if (advertiseMode !== "CUSTOM") return true; |
| 466 | return ( |
| 467 | groupsKey(observed.advertisedGroups) === groupsKey(desired.advertisedGroups) && |
| 468 | rangesKey(observed.advertisedIpRanges) === rangesKey(desired.advertisedIpRanges) |
| 469 | ); |
| 470 | }; |
| 471 | |
| 472 | const regionalRef = ( |
| 473 | project: string, |
| 474 | region: string, |
| 475 | collection: "subnetworks" | "addresses", |
| 476 | value: string, |
| 477 | ) => { |
| 478 | if (value.startsWith("http") || value.startsWith("projects/")) return value; |
| 479 | if (value.includes("/")) { |
| 480 | return `projects/${project}/${value.replace(/^\//, "")}`; |
| 481 | } |
| 482 | return `projects/${project}/regions/${region}/${collection}/${value}`; |
| 483 | }; |
| 484 | |
| 485 | const toNats = (nats: compute.RouterNat[] | undefined): RouterNat[] => |
| 486 | (nats ?? []).map((nat) => ({ |
| 487 | name: nat.name ?? "", |
| 488 | sourceSubnetworkIpRangesToNat: |
| 489 | nat.sourceSubnetworkIpRangesToNat as compute.RouterNatSourceSubnetworkIpRangesToNatEnum, |
| 490 | subnetworks: nat.subnetworks?.map((subnetwork) => ({ |
| 491 | name: subnetwork.name ?? "", |
| 492 | sourceIpRangesToNat: |
| 493 | subnetwork.sourceIpRangesToNat as RouterNatSubnetwork["sourceIpRangesToNat"], |
| 494 | secondaryIpRangeNames: subnetwork.secondaryIpRangeNames, |
| 495 | })), |
| 496 | natIpAllocateOption: nat.natIpAllocateOption as compute.RouterNatNatIpAllocateOptionEnum, |
| 497 | natIps: nat.natIps, |
| 498 | minPortsPerVm: nat.minPortsPerVm, |
| 499 | maxPortsPerVm: nat.maxPortsPerVm, |
| 500 | enableDynamicPortAllocation: nat.enableDynamicPortAllocation, |
| 501 | enableEndpointIndependentMapping: nat.enableEndpointIndependentMapping, |
| 502 | udpIdleTimeoutSec: nat.udpIdleTimeoutSec, |
| 503 | icmpIdleTimeoutSec: nat.icmpIdleTimeoutSec, |
| 504 | tcpEstablishedIdleTimeoutSec: nat.tcpEstablishedIdleTimeoutSec, |
| 505 | tcpTransitoryIdleTimeoutSec: nat.tcpTransitoryIdleTimeoutSec, |
| 506 | tcpTimeWaitTimeoutSec: nat.tcpTimeWaitTimeoutSec, |
| 507 | autoNetworkTier: nat.autoNetworkTier as compute.RouterNatAutoNetworkTierEnum | undefined, |
| 508 | endpointTypes: nat.endpointTypes as compute.RouterNatEndpointTypesItemEnum[] | undefined, |
| 509 | logConfig: |
| 510 | nat.logConfig === undefined |
| 511 | ? undefined |
| 512 | : { |
| 513 | enable: nat.logConfig.enable === true, |
| 514 | filter: nat.logConfig.filter as compute.RouterNatLogConfigFilterEnum, |
| 515 | }, |
| 516 | })); |
| 517 | |
| 518 | const desiredNats = ( |
| 519 | project: string, |
| 520 | region: string, |
| 521 | nats: ReadonlyArray<RouterNat>, |
| 522 | ): compute.RouterNat[] => |
| 523 | nats.map((nat) => ({ |
| 524 | ...nat, |
| 525 | natIpAllocateOption: |
| 526 | nat.natIpAllocateOption ?? |
| 527 | (nat.natIps !== undefined && nat.natIps.length > 0 ? "MANUAL_ONLY" : "AUTO_ONLY"), |
| 528 | subnetworks: nat.subnetworks?.map((subnetwork) => ({ |
| 529 | ...subnetwork, |
| 530 | name: regionalRef(project, region, "subnetworks", subnetwork.name), |
| 531 | sourceIpRangesToNat: subnetwork.sourceIpRangesToNat ?? ["ALL_IP_RANGES"], |
| 532 | })), |
| 533 | natIps: nat.natIps?.map((ip) => regionalRef(project, region, "addresses", ip)), |
| 534 | logConfig: |
| 535 | nat.logConfig === undefined |
| 536 | ? undefined |
| 537 | : { |
| 538 | enable: nat.logConfig.enable, |
| 539 | filter: nat.logConfig.filter ?? "ALL", |
| 540 | }, |
| 541 | })); |
| 542 | |
| 543 | const sortedKey = (values: ReadonlyArray<string> | undefined) => |
| 544 | [...(values ?? [])].sort().join("\0"); |
| 545 | |
| 546 | // Compare only fields the desired NAT specifies: the API fills in defaults |
| 547 | // (timeouts, endpoint types, tier) that the user never declared. |
| 548 | const natMatches = (desired: compute.RouterNat, observed: compute.RouterNat) => { |
| 549 | for (const [key, value] of Object.entries(desired)) { |
| 550 | if (value === undefined) continue; |
| 551 | const current = observed[key as keyof compute.RouterNat]; |
| 552 | switch (key) { |
| 553 | case "natIps": |
| 554 | if ( |
| 555 | sortedKey((value as string[]).map(linkKey)) !== |
| 556 | sortedKey(((current as string[] | undefined) ?? []).map(linkKey)) |
| 557 | ) { |
| 558 | return false; |
| 559 | } |
| 560 | break; |
| 561 | case "subnetworks": { |
| 562 | const subnetKey = (list: compute.RouterNatSubnetworkToNat[]) => |
| 563 | JSON.stringify( |
| 564 | list |
| 565 | .map((subnetwork) => ({ |
| 566 | name: linkKey(subnetwork.name), |
| 567 | ranges: sortedKey(subnetwork.sourceIpRangesToNat), |
| 568 | secondary: sortedKey(subnetwork.secondaryIpRangeNames), |
| 569 | })) |
| 570 | .sort((a, b) => a.name.localeCompare(b.name)), |
| 571 | ); |
| 572 | if ( |
| 573 | subnetKey(value as compute.RouterNatSubnetworkToNat[]) !== |
| 574 | subnetKey((current as compute.RouterNatSubnetworkToNat[]) ?? []) |
| 575 | ) { |
| 576 | return false; |
| 577 | } |
| 578 | break; |
| 579 | } |
| 580 | case "endpointTypes": |
| 581 | if (sortedKey(value as string[]) !== sortedKey(current as string[] | undefined)) { |
| 582 | return false; |
| 583 | } |
| 584 | break; |
| 585 | case "logConfig": { |
| 586 | const log = current as compute.RouterNatLogConfig | undefined; |
| 587 | const want = value as compute.RouterNatLogConfig; |
| 588 | if ((log?.enable === true) !== (want.enable === true)) return false; |
| 589 | if (want.enable === true && log?.filter !== want.filter) return false; |
| 590 | break; |
| 591 | } |
| 592 | default: |
| 593 | if (current !== value) return false; |
| 594 | } |
| 595 | } |
| 596 | return true; |
| 597 | }; |
| 598 | |
| 599 | const natsEqual = (observed: compute.RouterNat[] | undefined, desired: compute.RouterNat[]) => { |
| 600 | const byName = new Map((observed ?? []).map((nat) => [nat.name, nat])); |
| 601 | if (byName.size !== desired.length) return false; |
| 602 | return desired.every((nat) => { |
| 603 | const current = byName.get(nat.name); |
| 604 | return current !== undefined && natMatches(nat, current); |
| 605 | }); |
| 606 | }; |
| 607 | |
| 608 | const toAttrs = (router: compute.Router, project: string): Router["Attributes"] => { |
| 609 | const parsed = parseDescription(router.description); |
| 610 | return { |
| 611 | routerName: router.name ?? "", |
| 612 | project, |
| 613 | region: lastSegment(router.region ?? "").toLowerCase(), |
| 614 | network: router.network ?? "", |
| 615 | description: parsed.description, |
| 616 | bgp: toBgp(router.bgp), |
| 617 | nats: toNats(router.nats), |
| 618 | encryptedInterconnectRouter: router.encryptedInterconnectRouter === true, |
| 619 | nccGateway: router.nccGateway, |
| 620 | selfLink: router.selfLink, |
| 621 | routerId: router.id, |
| 622 | creationTimestamp: router.creationTimestamp, |
| 623 | }; |
| 624 | }; |
| 625 | |
| 626 | const getByName = (project: string, region: string, router: string) => |
| 627 | compute |
| 628 | .getRouters({ project, region, router }) |
| 629 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 630 | |
| 631 | const requireRouter = (project: string, region: string, routerName: string) => |
| 632 | getByName(project, region, routerName).pipe( |
| 633 | Effect.flatMap((router) => |
| 634 | router ? Effect.succeed(router) : Effect.fail(new RouterNotResolved({ routerName, region })), |
| 635 | ), |
| 636 | Effect.retry({ |
| 637 | while: (error) => error._tag === "GCP.Compute.RouterNotResolved", |
| 638 | schedule: Schedule.spaced("1 second"), |
| 639 | times: 8, |
| 640 | }), |
| 641 | ); |
| 642 | |
| 643 | const waitUntilRouterGone = (project: string, region: string, routerName: string) => |
| 644 | getByName(project, region, routerName).pipe( |
| 645 | Effect.flatMap((router) => |
| 646 | router === undefined |
| 647 | ? Effect.void |
| 648 | : Effect.fail( |
| 649 | new RouterOperationPending({ |
| 650 | operation: `delete:${routerName}`, |
| 651 | status: "EXISTS", |
| 652 | }), |
| 653 | ), |
| 654 | ), |
| 655 | Effect.retry({ |
| 656 | while: (error) => error._tag === "GCP.Compute.RouterOperationPending", |
| 657 | schedule: Schedule.spaced("2 seconds"), |
| 658 | times: 20, |
| 659 | }), |
| 660 | ); |
| 661 | |
| 662 | export const RouterProvider = () => |
| 663 | Provider.succeed(Router, { |
| 664 | nuke: { |
| 665 | dependsOn: ["GCP.Compute.Network"], |
| 666 | }, |
| 667 | stables: [ |
| 668 | "routerName", |
| 669 | "project", |
| 670 | "region", |
| 671 | "network", |
| 672 | "encryptedInterconnectRouter", |
| 673 | "nccGateway", |
| 674 | "routerId", |
| 675 | "selfLink", |
| 676 | "creationTimestamp", |
| 677 | ], |
| 678 | |
| 679 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 680 | if (!isResolved(news)) return undefined; |
| 681 | const env = yield* GcpEnvironment.current; |
| 682 | const previousName = olds?.routerName ?? output?.routerName; |
| 683 | const nextName = news.routerName ?? previousName; |
| 684 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 685 | const nextRegion = normalizeRegion(news.region ?? output?.region, env.region); |
| 686 | const identityChanged = |
| 687 | previousRegion !== nextRegion || |
| 688 | (previousName !== undefined && nextName !== undefined && previousName !== nextName); |
| 689 | const previousEncrypted = |
| 690 | olds?.encryptedInterconnectRouter ?? output?.encryptedInterconnectRouter ?? false; |
| 691 | const nextEncrypted = news.encryptedInterconnectRouter ?? false; |
| 692 | const previousAsn = olds?.bgp?.asn ?? output?.bgp?.asn; |
| 693 | const nextAsn = news.bgp?.asn; |
| 694 | const replace = |
| 695 | identityChanged || |
| 696 | linkKey(news.network) !== linkKey(olds?.network ?? output?.network) || |
| 697 | previousEncrypted !== nextEncrypted || |
| 698 | (previousAsn !== undefined && nextAsn !== undefined && previousAsn !== nextAsn) || |
| 699 | (news.nccGateway !== undefined && |
| 700 | linkKey(news.nccGateway) !== linkKey(olds?.nccGateway ?? output?.nccGateway)); |
| 701 | if (!replace) return undefined; |
| 702 | return { |
| 703 | action: "replace" as const, |
| 704 | deleteFirst: |
| 705 | !identityChanged && |
| 706 | nextName !== undefined && |
| 707 | previousName !== undefined && |
| 708 | nextName === previousName, |
| 709 | }; |
| 710 | }), |
| 711 | |
| 712 | read: Effect.fn(function* ({ id, olds, output }) { |
| 713 | const env = yield* GcpEnvironment.current; |
| 714 | const routerName = yield* toRouterName(id, olds?.routerName, output?.routerName); |
| 715 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 716 | const existing = yield* getByName(env.project, region, routerName); |
| 717 | if (existing === undefined) return undefined; |
| 718 | const attrs = toAttrs(existing, env.project); |
| 719 | const parsed = parseDescription(existing.description); |
| 720 | return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs); |
| 721 | }), |
| 722 | |
| 723 | list: () => |
| 724 | Effect.gen(function* () { |
| 725 | const env = yield* GcpEnvironment.current; |
| 726 | const found: Router["Attributes"][] = []; |
| 727 | let pageToken: string | undefined; |
| 728 | for (let page = 0; page < 10; page++) { |
| 729 | const response = yield* compute.aggregatedListRouters({ |
| 730 | project: env.project, |
| 731 | returnPartialSuccess: true, |
| 732 | maxResults: 500, |
| 733 | pageToken, |
| 734 | }); |
| 735 | for (const scoped of Object.values(response.items ?? {})) { |
| 736 | for (const item of scoped?.routers ?? []) { |
| 737 | if (!hasAlchemyMarker(item.description)) continue; |
| 738 | found.push(toAttrs(item, env.project)); |
| 739 | } |
| 740 | } |
| 741 | pageToken = response.nextPageToken; |
| 742 | if (pageToken === undefined || pageToken === "") break; |
| 743 | } |
| 744 | return found; |
| 745 | }), |
| 746 | |
| 747 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 748 | const env = yield* GcpEnvironment.current; |
| 749 | const routerName = yield* toRouterName(id, news.routerName, output?.routerName); |
| 750 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 751 | const network = networkRef(env.project, news.network); |
| 752 | const internal = yield* createInternalLabels(id); |
| 753 | const desiredDescription = encodeDescription(internal, news.description); |
| 754 | const encrypted = news.encryptedInterconnectRouter === true; |
| 755 | const nats = |
| 756 | news.nats === undefined ? undefined : desiredNats(env.project, region, news.nats); |
| 757 | |
| 758 | let current = yield* getByName(env.project, region, routerName); |
| 759 | |
| 760 | if (current === undefined) { |
| 761 | const body: compute.Router = { |
| 762 | name: routerName, |
| 763 | network, |
| 764 | description: desiredDescription, |
| 765 | }; |
| 766 | if (news.bgp !== undefined) { |
| 767 | body.bgp = desiredBgp(news.bgp); |
| 768 | } |
| 769 | if (nats !== undefined && nats.length > 0) { |
| 770 | body.nats = nats; |
| 771 | } |
| 772 | if (encrypted) { |
| 773 | body.encryptedInterconnectRouter = true; |
| 774 | } |
| 775 | if (news.nccGateway !== undefined) { |
| 776 | body.nccGateway = news.nccGateway; |
| 777 | } |
| 778 | yield* compute |
| 779 | .insertRouters({ |
| 780 | project: env.project, |
| 781 | region, |
| 782 | body, |
| 783 | }) |
| 784 | .pipe( |
| 785 | Effect.flatMap((operation) => |
| 786 | waitRegionOperation(env.project, region, operation, { |
| 787 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 788 | }), |
| 789 | ), |
| 790 | Effect.catchTag("Conflict", () => Effect.void), |
| 791 | ); |
| 792 | current = yield* requireRouter(env.project, region, routerName); |
| 793 | } |
| 794 | |
| 795 | const patchBody: compute.Router = {}; |
| 796 | if ((current.description ?? "") !== desiredDescription) { |
| 797 | patchBody.description = desiredDescription; |
| 798 | } |
| 799 | if (news.bgp !== undefined && !bgpEqual(toBgp(current.bgp), news.bgp)) { |
| 800 | patchBody.bgp = desiredBgp(news.bgp); |
| 801 | } |
| 802 | if (nats !== undefined && !natsEqual(current.nats, nats)) { |
| 803 | patchBody.nats = nats; |
| 804 | } |
| 805 | if (Object.keys(patchBody).length > 0) { |
| 806 | const patched = yield* compute.patchRouters({ |
| 807 | project: env.project, |
| 808 | region, |
| 809 | router: routerName, |
| 810 | body: patchBody, |
| 811 | }); |
| 812 | yield* waitRegionOperation(env.project, region, patched); |
| 813 | current = yield* requireRouter(env.project, region, routerName); |
| 814 | } |
| 815 | |
| 816 | return toAttrs(current, env.project); |
| 817 | }), |
| 818 | |
| 819 | delete: Effect.fn(function* ({ output }) { |
| 820 | const env = yield* GcpEnvironment.current; |
| 821 | const project = output.project || env.project; |
| 822 | const region = normalizeRegion(output.region, env.region); |
| 823 | const routerName = output.routerName; |
| 824 | if (!routerName) return; |
| 825 | yield* compute |
| 826 | .deleteRouters({ |
| 827 | project, |
| 828 | region, |
| 829 | router: routerName, |
| 830 | }) |
| 831 | .pipe( |
| 832 | Effect.retry({ |
| 833 | while: (error) => error._tag === "Conflict" || error._tag === "BadRequest", |
| 834 | times: 15, |
| 835 | schedule: Schedule.spaced("3 seconds"), |
| 836 | }), |
| 837 | Effect.flatMap((operation) => |
| 838 | waitRegionOperation(project, region, operation, { |
| 839 | ignore: ["RESOURCE_NOT_FOUND"], |
| 840 | }), |
| 841 | ), |
| 842 | Effect.catchTag("NotFound", () => Effect.void), |
| 843 | Effect.retry({ |
| 844 | while: (error) => |
| 845 | error._tag === "GCP.OperationFailed" && |
| 846 | error.reason === "RESOURCE_IN_USE_BY_ANOTHER_RESOURCE", |
| 847 | times: 10, |
| 848 | schedule: Schedule.spaced("3 seconds"), |
| 849 | }), |
| 850 | ); |
| 851 | yield* waitUntilRouterGone(project, region, routerName); |
| 852 | }), |
| 853 | }); |