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 | export type SubnetworkSecondaryRange = { |
| 16 | /** Name of this secondary range. Must be unique within the subnetwork. */ |
| 17 | rangeName: string; |
| 18 | /** CIDR of this secondary range. */ |
| 19 | ipCidrRange: string; |
| 20 | }; |
| 21 | |
| 22 | export type SubnetworkLogConfig = { |
| 23 | /** Whether VPC flow logs are enabled. */ |
| 24 | enable?: boolean; |
| 25 | /** Aggregation interval for flow logs. */ |
| 26 | aggregationInterval?: compute.SubnetworkLogConfigAggregationIntervalEnum; |
| 27 | /** Sampling rate in `[0, 1]`. */ |
| 28 | flowSampling?: number; |
| 29 | /** Metadata included in flow logs. */ |
| 30 | metadata?: compute.SubnetworkLogConfigMetadataEnum; |
| 31 | /** Extra metadata fields when `metadata` is `CUSTOM_METADATA`. */ |
| 32 | metadataFields?: string[]; |
| 33 | /** Filter expression for exported flow logs. */ |
| 34 | filterExpr?: string; |
| 35 | }; |
| 36 | |
| 37 | export type SubnetworkProps = { |
| 38 | /** |
| 39 | * Subnetwork name (RFC1035, 1-63 chars). If omitted, a unique name is |
| 40 | * generated from the stack, stage, and logical id. Changing it replaces |
| 41 | * the subnetwork. |
| 42 | */ |
| 43 | subnetworkName?: string; |
| 44 | /** |
| 45 | * Region of the subnetwork. Immutable — changing it replaces the |
| 46 | * subnetwork. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 47 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 48 | */ |
| 49 | region?: string; |
| 50 | /** |
| 51 | * Parent VPC network name or URL. Immutable — changing it replaces the |
| 52 | * subnetwork. |
| 53 | */ |
| 54 | network: string; |
| 55 | /** |
| 56 | * Primary IPv4 CIDR. Changing it replaces the subnetwork (expansion via |
| 57 | * `expandIpCidrRange` is not applied in-place). |
| 58 | */ |
| 59 | ipCidrRange: string; |
| 60 | /** |
| 61 | * User description. Alchemy ownership is stamped into the description |
| 62 | * (Compute Subnetwork has no `labels` field) so `list` / nuke can find |
| 63 | * the resource. The API only accepts description at create time — |
| 64 | * changing it replaces the subnetwork. |
| 65 | */ |
| 66 | description?: string; |
| 67 | /** |
| 68 | * Whether VMs in this subnet can reach Google APIs without an external |
| 69 | * IP. Updated in place via `setPrivateIpGoogleAccess`. |
| 70 | * @default false |
| 71 | */ |
| 72 | privateIpGoogleAccess?: boolean; |
| 73 | /** |
| 74 | * IP stack. `IPV4_ONLY` by default. Updated in place via patch. |
| 75 | * @default "IPV4_ONLY" |
| 76 | */ |
| 77 | stackType?: compute.SubnetworkStackTypeEnum; |
| 78 | /** |
| 79 | * Subnet purpose (`PRIVATE`, `INTERNAL_HTTPS_LOAD_BALANCER`, |
| 80 | * `REGIONAL_MANAGED_PROXY`, …). Immutable — changing it replaces the |
| 81 | * subnetwork. |
| 82 | */ |
| 83 | purpose?: compute.SubnetworkPurposeEnum; |
| 84 | /** |
| 85 | * Secondary ranges for alias IPs. Updated in place via patch. |
| 86 | */ |
| 87 | secondaryIpRanges?: ReadonlyArray<SubnetworkSecondaryRange>; |
| 88 | /** |
| 89 | * VPC flow log options. Updated in place via patch. |
| 90 | */ |
| 91 | logConfig?: SubnetworkLogConfig; |
| 92 | /** |
| 93 | * Deprecated flow-log toggle. Prefer `logConfig.enable`. Updated in |
| 94 | * place via patch when set. |
| 95 | */ |
| 96 | enableFlowLogs?: boolean; |
| 97 | /** |
| 98 | * IPv6 Google access mode. Updated in place via patch when set. |
| 99 | */ |
| 100 | privateIpv6GoogleAccess?: compute.SubnetworkPrivateIpv6GoogleAccessEnum; |
| 101 | /** |
| 102 | * IPv6 access type (`EXTERNAL` or `INTERNAL`). Immutable after the |
| 103 | * subnet is dual-stack — changing it replaces the subnetwork. |
| 104 | */ |
| 105 | ipv6AccessType?: compute.SubnetworkIpv6AccessTypeEnum; |
| 106 | }; |
| 107 | |
| 108 | export type Subnetwork = Resource< |
| 109 | "GCP.Compute.Subnetwork", |
| 110 | SubnetworkProps, |
| 111 | { |
| 112 | /** RFC1035 subnetwork name. */ |
| 113 | subnetworkName: string; |
| 114 | /** Region short name (`us-central1`). */ |
| 115 | region: string; |
| 116 | /** Project id. */ |
| 117 | project: string; |
| 118 | /** Parent VPC network URL. */ |
| 119 | network: string; |
| 120 | /** Primary IPv4 CIDR. */ |
| 121 | ipCidrRange: string; |
| 122 | /** User description (Alchemy ownership marker stripped). */ |
| 123 | description: string | undefined; |
| 124 | /** Whether Private Google Access is enabled. */ |
| 125 | privateIpGoogleAccess: boolean; |
| 126 | /** IP stack type. */ |
| 127 | stackType: string | undefined; |
| 128 | /** Subnet purpose. */ |
| 129 | purpose: string | undefined; |
| 130 | /** Secondary alias-IP ranges. */ |
| 131 | secondaryIpRanges: ReadonlyArray<SubnetworkSecondaryRange>; |
| 132 | /** VPC flow log options. */ |
| 133 | logConfig: SubnetworkLogConfig | undefined; |
| 134 | /** Deprecated flow-log toggle. */ |
| 135 | enableFlowLogs: boolean | undefined; |
| 136 | /** IPv6 Google access mode. */ |
| 137 | privateIpv6GoogleAccess: string | undefined; |
| 138 | /** IPv6 access type. */ |
| 139 | ipv6AccessType: string | undefined; |
| 140 | /** Gateway address for default routes. */ |
| 141 | gatewayAddress: string | undefined; |
| 142 | /** Server-reported state (`READY` or `DRAINING`). */ |
| 143 | state: string | undefined; |
| 144 | /** Server-defined resource URL. */ |
| 145 | selfLink: string | undefined; |
| 146 | /** Server-assigned numeric id. */ |
| 147 | subnetworkId: string | undefined; |
| 148 | /** RFC3339 creation timestamp. */ |
| 149 | creationTimestamp: string | undefined; |
| 150 | /** Optimistic-locking fingerprint. */ |
| 151 | fingerprint: string | undefined; |
| 152 | }, |
| 153 | never, |
| 154 | Providers |
| 155 | >; |
| 156 | |
| 157 | /** |
| 158 | * A Google Compute Engine VPC subnetwork (subnet). |
| 159 | * |
| 160 | * Subnets are regional partitions of a VPC with one primary IPv4 range and |
| 161 | * optional secondary ranges. Compute Subnetwork has no `labels` field — |
| 162 | * Alchemy stamps `alchemy-stack` / `alchemy-stage` / `alchemy-id` into the |
| 163 | * description so `list` and `pnpm nuke:gcp` can identify owned subnets. |
| 164 | * |
| 165 | * The parent VPC must be custom mode (`autoCreateSubnetworks: false`) |
| 166 | * unless you are attaching to an auto-mode network's existing range. |
| 167 | * |
| 168 | * ### Creating a Subnetwork |
| 169 | * **Example:** Subnet in a custom-mode VPC |
| 170 | * ```typescript |
| 171 | * const network = yield* GCP.Compute.Network("Vpc", { |
| 172 | * autoCreateSubnetworks: false, |
| 173 | * }); |
| 174 | * const subnet = yield* GCP.Compute.Subnetwork("Private", { |
| 175 | * network: network.networkName, |
| 176 | * ipCidrRange: "10.0.0.0/24", |
| 177 | * }); |
| 178 | * ``` |
| 179 | * |
| 180 | * **Example:** Explicit name, region, and Private Google Access |
| 181 | * ```typescript |
| 182 | * const subnet = yield* GCP.Compute.Subnetwork("Private", { |
| 183 | * subnetworkName: "app-private", |
| 184 | * region: "us-central1", |
| 185 | * network: "app-vpc", |
| 186 | * ipCidrRange: "10.10.0.0/24", |
| 187 | * privateIpGoogleAccess: true, |
| 188 | * description: "application private subnet", |
| 189 | * }); |
| 190 | * ``` |
| 191 | * |
| 192 | * ### Secondary ranges |
| 193 | * **Example:** Alias-IP secondary range |
| 194 | * ```typescript |
| 195 | * const subnet = yield* GCP.Compute.Subnetwork("Private", { |
| 196 | * network: network.networkName, |
| 197 | * ipCidrRange: "10.10.0.0/24", |
| 198 | * secondaryIpRanges: [ |
| 199 | * { rangeName: "pods", ipCidrRange: "10.10.1.0/24" }, |
| 200 | * ], |
| 201 | * }); |
| 202 | * ``` |
| 203 | * |
| 204 | * @resource |
| 205 | * @category Compute |
| 206 | */ |
| 207 | export const Subnetwork = Resource<Subnetwork>("GCP.Compute.Subnetwork"); |
| 208 | |
| 209 | export class SubnetworkNotResolved extends Data.TaggedError("GCP.Compute.SubnetworkNotResolved")<{ |
| 210 | project: string; |
| 211 | region: string; |
| 212 | subnetworkName: string; |
| 213 | }> {} |
| 214 | |
| 215 | const DEFAULT_STACK_TYPE = "IPV4_ONLY"; |
| 216 | const DEFAULT_PRIVATE_GOOGLE_ACCESS = false; |
| 217 | |
| 218 | const OWNERSHIP_KEYS = ["alchemy-stack", "alchemy-stage", "alchemy-id"] as const; |
| 219 | |
| 220 | const lastSegment = (value: string) => { |
| 221 | const trimmed = value.replace(/\/+$/, ""); |
| 222 | const parts = trimmed.split("/"); |
| 223 | return parts[parts.length - 1] || trimmed; |
| 224 | }; |
| 225 | |
| 226 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 227 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 228 | |
| 229 | const linkKey = (value: string | undefined) => |
| 230 | value === undefined || value === "" ? "" : lastSegment(value).toLowerCase(); |
| 231 | |
| 232 | const networkRef = (project: string, network: string) => |
| 233 | network.includes("/") ? network : `projects/${project}/global/networks/${network}`; |
| 234 | |
| 235 | const encodeDescription = (internal: Record<string, string>, user?: string): string => { |
| 236 | const marker = OWNERSHIP_KEYS.map((key) => `${key}=${internal[key] ?? ""}`).join(" "); |
| 237 | return user && user.length > 0 ? `${marker}\n${user}` : marker; |
| 238 | }; |
| 239 | |
| 240 | const parseDescription = (description: string | undefined) => { |
| 241 | if (!description) { |
| 242 | return { labels: {} as Record<string, string>, description: undefined }; |
| 243 | } |
| 244 | const newline = description.indexOf("\n"); |
| 245 | const first = newline === -1 ? description : description.slice(0, newline); |
| 246 | const rest = newline === -1 ? undefined : description.slice(newline + 1); |
| 247 | if (!first.includes("alchemy-id=") || !first.includes("alchemy-stack=")) { |
| 248 | return { labels: {} as Record<string, string>, description }; |
| 249 | } |
| 250 | const labels: Record<string, string> = {}; |
| 251 | for (const part of first.split(/\s+/)) { |
| 252 | const eq = part.indexOf("="); |
| 253 | if (eq > 0) { |
| 254 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 255 | } |
| 256 | } |
| 257 | return { |
| 258 | labels, |
| 259 | description: rest && rest.length > 0 ? rest : undefined, |
| 260 | }; |
| 261 | }; |
| 262 | |
| 263 | const hasAlchemyMarker = (description: string | undefined) => |
| 264 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 265 | |
| 266 | const toSubnetworkName = (id: string, name: string | undefined, existing?: string) => |
| 267 | Effect.gen(function* () { |
| 268 | if (name !== undefined) return name; |
| 269 | if (existing !== undefined) return existing; |
| 270 | const generated = yield* createPhysicalName({ |
| 271 | id, |
| 272 | maxLength: 63, |
| 273 | lowercase: true, |
| 274 | }); |
| 275 | const rfc = generated.replace(/^[^a-z]+/, "n").replace(/-+$/g, ""); |
| 276 | return rfc.slice(0, 63); |
| 277 | }); |
| 278 | |
| 279 | const toSecondaryRanges = ( |
| 280 | ranges: compute.SubnetworkSecondaryRangeList | undefined, |
| 281 | ): SubnetworkSecondaryRange[] => |
| 282 | (ranges ?? []) |
| 283 | .filter( |
| 284 | ( |
| 285 | range, |
| 286 | ): range is compute.SubnetworkSecondaryRange & { |
| 287 | rangeName: string; |
| 288 | ipCidrRange: string; |
| 289 | } => !!range.rangeName && !!range.ipCidrRange, |
| 290 | ) |
| 291 | .map((range) => ({ |
| 292 | rangeName: range.rangeName, |
| 293 | ipCidrRange: range.ipCidrRange, |
| 294 | })); |
| 295 | |
| 296 | const rangesKey = (ranges: ReadonlyArray<SubnetworkSecondaryRange> | undefined) => |
| 297 | JSON.stringify( |
| 298 | [...(ranges ?? [])] |
| 299 | .map((range) => ({ |
| 300 | rangeName: range.rangeName, |
| 301 | ipCidrRange: range.ipCidrRange, |
| 302 | })) |
| 303 | .sort((a, b) => a.rangeName.localeCompare(b.rangeName)), |
| 304 | ); |
| 305 | |
| 306 | const toAggregationInterval = ( |
| 307 | value: string | undefined, |
| 308 | ): compute.SubnetworkLogConfigAggregationIntervalEnum | undefined => { |
| 309 | switch (value) { |
| 310 | case "INTERVAL_10_MIN": |
| 311 | case "INTERVAL_15_MIN": |
| 312 | case "INTERVAL_1_MIN": |
| 313 | case "INTERVAL_30_SEC": |
| 314 | case "INTERVAL_5_MIN": |
| 315 | case "INTERVAL_5_SEC": |
| 316 | return value; |
| 317 | default: |
| 318 | return undefined; |
| 319 | } |
| 320 | }; |
| 321 | |
| 322 | const toLogMetadata = ( |
| 323 | value: string | undefined, |
| 324 | ): compute.SubnetworkLogConfigMetadataEnum | undefined => { |
| 325 | switch (value) { |
| 326 | case "CUSTOM_METADATA": |
| 327 | case "EXCLUDE_ALL_METADATA": |
| 328 | case "INCLUDE_ALL_METADATA": |
| 329 | return value; |
| 330 | default: |
| 331 | return undefined; |
| 332 | } |
| 333 | }; |
| 334 | |
| 335 | const toLogConfig = ( |
| 336 | logConfig: compute.SubnetworkLogConfig | undefined, |
| 337 | ): SubnetworkLogConfig | undefined => { |
| 338 | if (logConfig === undefined) return undefined; |
| 339 | return { |
| 340 | enable: logConfig.enable, |
| 341 | aggregationInterval: toAggregationInterval(logConfig.aggregationInterval), |
| 342 | flowSampling: logConfig.flowSampling, |
| 343 | metadata: toLogMetadata(logConfig.metadata), |
| 344 | metadataFields: logConfig.metadataFields, |
| 345 | filterExpr: logConfig.filterExpr, |
| 346 | }; |
| 347 | }; |
| 348 | |
| 349 | const toAttrs = (subnetwork: compute.Subnetwork, project: string): Subnetwork["Attributes"] => { |
| 350 | const parsed = parseDescription(subnetwork.description); |
| 351 | return { |
| 352 | subnetworkName: subnetwork.name ?? "", |
| 353 | region: lastSegment(subnetwork.region ?? "").toLowerCase(), |
| 354 | project, |
| 355 | network: subnetwork.network ?? "", |
| 356 | ipCidrRange: subnetwork.ipCidrRange ?? "", |
| 357 | description: parsed.description, |
| 358 | privateIpGoogleAccess: subnetwork.privateIpGoogleAccess === true, |
| 359 | stackType: subnetwork.stackType, |
| 360 | purpose: subnetwork.purpose, |
| 361 | secondaryIpRanges: toSecondaryRanges(subnetwork.secondaryIpRanges), |
| 362 | logConfig: toLogConfig(subnetwork.logConfig), |
| 363 | enableFlowLogs: subnetwork.enableFlowLogs, |
| 364 | privateIpv6GoogleAccess: subnetwork.privateIpv6GoogleAccess, |
| 365 | ipv6AccessType: subnetwork.ipv6AccessType, |
| 366 | gatewayAddress: subnetwork.gatewayAddress, |
| 367 | state: subnetwork.state, |
| 368 | selfLink: subnetwork.selfLink, |
| 369 | subnetworkId: subnetwork.id, |
| 370 | creationTimestamp: subnetwork.creationTimestamp, |
| 371 | fingerprint: subnetwork.fingerprint, |
| 372 | }; |
| 373 | }; |
| 374 | |
| 375 | const getByName = (project: string, region: string, subnetworkName: string) => |
| 376 | compute |
| 377 | .getSubnetworks({ project, region, subnetwork: subnetworkName }) |
| 378 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 379 | |
| 380 | const requireSubnetwork = (project: string, region: string, subnetworkName: string) => |
| 381 | getByName(project, region, subnetworkName).pipe( |
| 382 | Effect.flatMap((subnetwork) => |
| 383 | subnetwork |
| 384 | ? Effect.succeed(subnetwork) |
| 385 | : Effect.fail(new SubnetworkNotResolved({ project, region, subnetworkName })), |
| 386 | ), |
| 387 | Effect.retry({ |
| 388 | while: (error) => error._tag === "GCP.Compute.SubnetworkNotResolved", |
| 389 | schedule: Schedule.spaced("1 second"), |
| 390 | times: 8, |
| 391 | }), |
| 392 | ); |
| 393 | |
| 394 | export const SubnetworkProvider = () => |
| 395 | Provider.succeed(Subnetwork, { |
| 396 | nuke: { |
| 397 | dependsOn: ["GCP.Compute.Network"], |
| 398 | }, |
| 399 | stables: [ |
| 400 | "subnetworkName", |
| 401 | "region", |
| 402 | "project", |
| 403 | "network", |
| 404 | "ipCidrRange", |
| 405 | "subnetworkId", |
| 406 | "selfLink", |
| 407 | "creationTimestamp", |
| 408 | "gatewayAddress", |
| 409 | "purpose", |
| 410 | "ipv6AccessType", |
| 411 | ], |
| 412 | |
| 413 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 414 | if (!isResolved(news)) return undefined; |
| 415 | const env = yield* GcpEnvironment.current; |
| 416 | const previousName = olds?.subnetworkName ?? output?.subnetworkName; |
| 417 | const nextName = news.subnetworkName ?? previousName; |
| 418 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 419 | const nextRegion = normalizeRegion(news.region ?? previousRegion, env.region); |
| 420 | const identityChanged = |
| 421 | previousRegion !== nextRegion || |
| 422 | (previousName !== undefined && nextName !== undefined && previousName !== nextName); |
| 423 | const replace = |
| 424 | identityChanged || |
| 425 | linkKey(news.network) !== linkKey(olds?.network ?? output?.network) || |
| 426 | news.ipCidrRange !== (olds?.ipCidrRange ?? output?.ipCidrRange ?? "") || |
| 427 | (news.description ?? "") !== (olds?.description ?? output?.description ?? "") || |
| 428 | (news.purpose !== undefined && news.purpose !== (olds?.purpose ?? output?.purpose)) || |
| 429 | (news.ipv6AccessType !== undefined && |
| 430 | news.ipv6AccessType !== (olds?.ipv6AccessType ?? output?.ipv6AccessType)); |
| 431 | if (!replace) return undefined; |
| 432 | return { |
| 433 | action: "replace" as const, |
| 434 | deleteFirst: |
| 435 | !identityChanged && |
| 436 | nextName !== undefined && |
| 437 | previousName !== undefined && |
| 438 | nextName === previousName, |
| 439 | }; |
| 440 | }), |
| 441 | |
| 442 | read: Effect.fn(function* ({ id, olds, output }) { |
| 443 | const env = yield* GcpEnvironment.current; |
| 444 | const subnetworkName = yield* toSubnetworkName( |
| 445 | id, |
| 446 | olds?.subnetworkName, |
| 447 | output?.subnetworkName, |
| 448 | ); |
| 449 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 450 | const existing = yield* getByName(env.project, region, subnetworkName); |
| 451 | if (existing === undefined) return undefined; |
| 452 | const attrs = toAttrs(existing, env.project); |
| 453 | const parsed = parseDescription(existing.description); |
| 454 | return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs); |
| 455 | }), |
| 456 | |
| 457 | list: () => |
| 458 | Effect.gen(function* () { |
| 459 | const env = yield* GcpEnvironment.current; |
| 460 | const found: Subnetwork["Attributes"][] = []; |
| 461 | let pageToken: string | undefined; |
| 462 | for (let page = 0; page < 10; page++) { |
| 463 | const response = yield* compute.aggregatedListSubnetworks({ |
| 464 | project: env.project, |
| 465 | returnPartialSuccess: true, |
| 466 | maxResults: 500, |
| 467 | pageToken, |
| 468 | }); |
| 469 | for (const scoped of Object.values(response.items ?? {})) { |
| 470 | for (const item of scoped?.subnetworks ?? []) { |
| 471 | if (!hasAlchemyMarker(item.description)) continue; |
| 472 | found.push(toAttrs(item, env.project)); |
| 473 | } |
| 474 | } |
| 475 | pageToken = response.nextPageToken; |
| 476 | if (pageToken === undefined || pageToken === "") break; |
| 477 | } |
| 478 | return found; |
| 479 | }), |
| 480 | |
| 481 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 482 | const env = yield* GcpEnvironment.current; |
| 483 | const subnetworkName = yield* toSubnetworkName( |
| 484 | id, |
| 485 | news.subnetworkName, |
| 486 | output?.subnetworkName, |
| 487 | ); |
| 488 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 489 | const network = networkRef(env.project, news.network); |
| 490 | const privateIpGoogleAccess = news.privateIpGoogleAccess ?? DEFAULT_PRIVATE_GOOGLE_ACCESS; |
| 491 | const stackType = news.stackType ?? DEFAULT_STACK_TYPE; |
| 492 | const internal = yield* createInternalLabels(id); |
| 493 | const desiredDescription = encodeDescription(internal, news.description); |
| 494 | |
| 495 | let current = yield* getByName(env.project, region, subnetworkName); |
| 496 | |
| 497 | if (current === undefined) { |
| 498 | const body: compute.Subnetwork = { |
| 499 | name: subnetworkName, |
| 500 | network, |
| 501 | ipCidrRange: news.ipCidrRange, |
| 502 | description: desiredDescription, |
| 503 | privateIpGoogleAccess, |
| 504 | stackType, |
| 505 | }; |
| 506 | if (news.purpose !== undefined) body.purpose = news.purpose; |
| 507 | if (news.secondaryIpRanges !== undefined) { |
| 508 | body.secondaryIpRanges = [...news.secondaryIpRanges]; |
| 509 | } |
| 510 | if (news.logConfig !== undefined) { |
| 511 | body.logConfig = { ...news.logConfig }; |
| 512 | } |
| 513 | if (news.enableFlowLogs !== undefined) { |
| 514 | body.enableFlowLogs = news.enableFlowLogs; |
| 515 | } |
| 516 | if (news.privateIpv6GoogleAccess !== undefined) { |
| 517 | body.privateIpv6GoogleAccess = news.privateIpv6GoogleAccess; |
| 518 | } |
| 519 | if (news.ipv6AccessType !== undefined) { |
| 520 | body.ipv6AccessType = news.ipv6AccessType; |
| 521 | } |
| 522 | yield* compute |
| 523 | .insertSubnetworks({ |
| 524 | project: env.project, |
| 525 | region, |
| 526 | body, |
| 527 | }) |
| 528 | .pipe( |
| 529 | Effect.flatMap((operation) => |
| 530 | waitRegionOperation(env.project, region, operation, { |
| 531 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 532 | }), |
| 533 | ), |
| 534 | Effect.catchTag("Conflict", () => Effect.void), |
| 535 | ); |
| 536 | current = yield* requireSubnetwork(env.project, region, subnetworkName); |
| 537 | } |
| 538 | |
| 539 | if ((current.privateIpGoogleAccess === true) !== privateIpGoogleAccess) { |
| 540 | const updated = yield* compute.setPrivateIpGoogleAccessSubnetworks({ |
| 541 | project: env.project, |
| 542 | region, |
| 543 | subnetwork: subnetworkName, |
| 544 | body: { privateIpGoogleAccess }, |
| 545 | }); |
| 546 | yield* waitRegionOperation(env.project, region, updated); |
| 547 | current = yield* requireSubnetwork(env.project, region, subnetworkName); |
| 548 | } |
| 549 | |
| 550 | const patchBody: compute.Subnetwork = {}; |
| 551 | if ((current.stackType ?? DEFAULT_STACK_TYPE) !== stackType) { |
| 552 | patchBody.stackType = stackType; |
| 553 | } |
| 554 | if ( |
| 555 | news.secondaryIpRanges !== undefined && |
| 556 | rangesKey(news.secondaryIpRanges) !== |
| 557 | rangesKey(toSecondaryRanges(current.secondaryIpRanges)) |
| 558 | ) { |
| 559 | patchBody.secondaryIpRanges = [...news.secondaryIpRanges]; |
| 560 | } |
| 561 | if (news.logConfig !== undefined) { |
| 562 | const observed = toLogConfig(current.logConfig); |
| 563 | if ( |
| 564 | (observed?.enable === true) !== (news.logConfig.enable === true) || |
| 565 | (news.logConfig.aggregationInterval !== undefined && |
| 566 | observed?.aggregationInterval !== news.logConfig.aggregationInterval) || |
| 567 | (news.logConfig.flowSampling !== undefined && |
| 568 | observed?.flowSampling !== news.logConfig.flowSampling) || |
| 569 | (news.logConfig.metadata !== undefined && |
| 570 | observed?.metadata !== news.logConfig.metadata) || |
| 571 | (news.logConfig.filterExpr !== undefined && |
| 572 | observed?.filterExpr !== news.logConfig.filterExpr) |
| 573 | ) { |
| 574 | patchBody.logConfig = { ...news.logConfig }; |
| 575 | } |
| 576 | } |
| 577 | if ( |
| 578 | news.enableFlowLogs !== undefined && |
| 579 | (current.enableFlowLogs === true) !== news.enableFlowLogs |
| 580 | ) { |
| 581 | patchBody.enableFlowLogs = news.enableFlowLogs; |
| 582 | } |
| 583 | if ( |
| 584 | news.privateIpv6GoogleAccess !== undefined && |
| 585 | current.privateIpv6GoogleAccess !== news.privateIpv6GoogleAccess |
| 586 | ) { |
| 587 | patchBody.privateIpv6GoogleAccess = news.privateIpv6GoogleAccess; |
| 588 | } |
| 589 | |
| 590 | if (Object.keys(patchBody).length > 0) { |
| 591 | patchBody.fingerprint = current.fingerprint; |
| 592 | const patched = yield* compute.patchSubnetworks({ |
| 593 | project: env.project, |
| 594 | region, |
| 595 | subnetwork: subnetworkName, |
| 596 | body: patchBody, |
| 597 | }); |
| 598 | yield* waitRegionOperation(env.project, region, patched); |
| 599 | current = yield* requireSubnetwork(env.project, region, subnetworkName); |
| 600 | } |
| 601 | |
| 602 | return toAttrs(current, env.project); |
| 603 | }), |
| 604 | |
| 605 | delete: Effect.fn(function* ({ output }) { |
| 606 | const env = yield* GcpEnvironment.current; |
| 607 | const project = output.project || env.project; |
| 608 | const region = normalizeRegion(output.region, env.region); |
| 609 | const subnetworkName = output.subnetworkName; |
| 610 | if (!subnetworkName) return; |
| 611 | yield* compute |
| 612 | .deleteSubnetworks({ |
| 613 | project, |
| 614 | region, |
| 615 | subnetwork: subnetworkName, |
| 616 | }) |
| 617 | .pipe( |
| 618 | Effect.flatMap((operation) => |
| 619 | waitRegionOperation(project, region, operation, { |
| 620 | ignore: ["RESOURCE_NOT_FOUND"], |
| 621 | }), |
| 622 | ), |
| 623 | Effect.catchTag("NotFound", () => Effect.void), |
| 624 | Effect.retry({ |
| 625 | while: (error) => |
| 626 | error._tag === "Conflict" || |
| 627 | (error._tag === "GCP.OperationFailed" && |
| 628 | error.reason === "RESOURCE_IN_USE_BY_ANOTHER_RESOURCE"), |
| 629 | times: 8, |
| 630 | schedule: Schedule.spaced("2 seconds"), |
| 631 | }), |
| 632 | // Compute rejects the delete while another operation is still in |
| 633 | // flight on the subnet (e.g. load balancer or packet-mirroring |
| 634 | // teardown on resources inside it). |
| 635 | Effect.retry({ |
| 636 | while: (error) => error._tag === "ResourceNotReady", |
| 637 | times: 20, |
| 638 | schedule: Schedule.spaced("10 seconds"), |
| 639 | }), |
| 640 | ); |
| 641 | }), |
| 642 | }); |