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_ENABLE: compute.PacketMirroringEnableEnum = "TRUE"; |
| 17 | const DEFAULT_PRIORITY = 1000; |
| 18 | const DEFAULT_DIRECTION: compute.PacketMirroringFilterDirectionEnum = "BOTH"; |
| 19 | const MAX_NAME_LENGTH = 63; |
| 20 | |
| 21 | export type PacketMirroringEnable = compute.PacketMirroringEnableEnum; |
| 22 | |
| 23 | export type PacketMirroringFilterDirection = compute.PacketMirroringFilterDirectionEnum; |
| 24 | |
| 25 | export type PacketMirroringFilter = { |
| 26 | /** |
| 27 | * Traffic direction to copy (`INGRESS`, `EGRESS`, or `BOTH`). |
| 28 | * @default "BOTH" |
| 29 | */ |
| 30 | direction?: PacketMirroringFilterDirection | (string & {}); |
| 31 | /** |
| 32 | * IP protocols to copy (`tcp`, `udp`, `icmp`, `esp`, …). Empty (the |
| 33 | * default) copies every protocol that matches `cidrRanges`. |
| 34 | */ |
| 35 | ipProtocols?: string[]; |
| 36 | /** |
| 37 | * IPv4 or IPv6 CIDR ranges matched against the source (ingress) or |
| 38 | * destination (egress) address. Empty (the default) copies every IPv4 |
| 39 | * packet that matches `ipProtocols`. Use `0.0.0.0/0,::/0` to copy both |
| 40 | * IPv4 and IPv6. |
| 41 | */ |
| 42 | cidrRanges?: string[]; |
| 43 | }; |
| 44 | |
| 45 | export type PacketMirroringMirroredResources = { |
| 46 | /** |
| 47 | * Subnetwork names or URLs whose VMs are mirrored (max 5). Subnets must |
| 48 | * live in the same region and VPC as this policy. |
| 49 | */ |
| 50 | subnetworks?: string[]; |
| 51 | /** |
| 52 | * Instance names or URLs to mirror (max 50). Instances must live in a |
| 53 | * zone of this policy's region and have a NIC on `network`. |
| 54 | */ |
| 55 | instances?: string[]; |
| 56 | /** |
| 57 | * Network tags. Traffic from/to every VM that has at least one of these |
| 58 | * tags is mirrored. |
| 59 | */ |
| 60 | tags?: string[]; |
| 61 | }; |
| 62 | |
| 63 | export type PacketMirroringProps = { |
| 64 | /** |
| 65 | * PacketMirroring name (RFC1035, 1-63 characters). If omitted, a unique |
| 66 | * name is generated from the stack, stage, and logical id. Immutable — |
| 67 | * changing it replaces the policy. |
| 68 | */ |
| 69 | packetMirroringName?: string; |
| 70 | /** |
| 71 | * Region the policy lives in. Immutable — changing it replaces the |
| 72 | * policy. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 73 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 74 | */ |
| 75 | region?: string; |
| 76 | /** |
| 77 | * Optional description. Alchemy ownership is stored in a `[alchemy …]` |
| 78 | * prefix so `list` / nuke can find resources (Compute PacketMirroring has |
| 79 | * no labels field). Immutable — changing it replaces the policy. |
| 80 | */ |
| 81 | description?: string; |
| 82 | /** |
| 83 | * Mirrored VPC network name (`default`), partial URL |
| 84 | * (`global/networks/default`), or self-link. Only packets on this |
| 85 | * network are copied. Immutable — changing it replaces the policy. |
| 86 | */ |
| 87 | network: string; |
| 88 | /** |
| 89 | * Collector internal passthrough Network Load Balancer: a regional |
| 90 | * forwarding-rule name, path, or URL whose `loadBalancingScheme` is |
| 91 | * `INTERNAL` and `isMirroringCollector` is `true`. Updated in place. |
| 92 | */ |
| 93 | collectorIlb: string; |
| 94 | /** |
| 95 | * Mirrored sources — at least one of `tags`, `instances`, or |
| 96 | * `subnetworks`. Updated in place. |
| 97 | */ |
| 98 | mirroredResources: PacketMirroringMirroredResources; |
| 99 | /** |
| 100 | * Whether the policy is enforced. `false` / `"FALSE"` leaves the |
| 101 | * resource in place but stops copying packets. |
| 102 | * @default true |
| 103 | */ |
| 104 | enable?: boolean | PacketMirroringEnable | (string & {}); |
| 105 | /** |
| 106 | * Tie-breaker when two policies match the same VM. Lower wins. |
| 107 | * Valid range is `0`–`65535`. |
| 108 | * @default 1000 |
| 109 | */ |
| 110 | priority?: number; |
| 111 | /** |
| 112 | * Optional traffic filter. When omitted, every IPv4 packet is copied. |
| 113 | * Updated in place. |
| 114 | */ |
| 115 | filter?: PacketMirroringFilter; |
| 116 | }; |
| 117 | |
| 118 | export type PacketMirroring = Resource< |
| 119 | "GCP.Compute.PacketMirroring", |
| 120 | PacketMirroringProps, |
| 121 | { |
| 122 | /** PacketMirroring name. */ |
| 123 | packetMirroringName: string; |
| 124 | /** Project id. */ |
| 125 | project: string; |
| 126 | /** Region short name (`us-central1`). */ |
| 127 | region: string; |
| 128 | /** User description with the Alchemy ownership prefix stripped. */ |
| 129 | description: string | undefined; |
| 130 | /** Mirrored VPC network URL. */ |
| 131 | network: string; |
| 132 | /** Server-canonical network URL, if reported. */ |
| 133 | networkCanonicalUrl: string | undefined; |
| 134 | /** Collector forwarding-rule URL. */ |
| 135 | collectorIlb: string; |
| 136 | /** Server-canonical collector URL, if reported. */ |
| 137 | collectorIlbCanonicalUrl: string | undefined; |
| 138 | /** Mirrored sources currently configured. */ |
| 139 | mirroredResources: { |
| 140 | subnetworks: ReadonlyArray<string>; |
| 141 | instances: ReadonlyArray<string>; |
| 142 | tags: ReadonlyArray<string>; |
| 143 | }; |
| 144 | /** Whether the policy is enforced. */ |
| 145 | enable: boolean; |
| 146 | /** Tie-breaker priority. */ |
| 147 | priority: number; |
| 148 | /** Traffic filter, if set. */ |
| 149 | filter: |
| 150 | | { |
| 151 | direction: string | undefined; |
| 152 | ipProtocols: ReadonlyArray<string>; |
| 153 | cidrRanges: ReadonlyArray<string>; |
| 154 | } |
| 155 | | undefined; |
| 156 | /** Server-defined URL. */ |
| 157 | selfLink: string | undefined; |
| 158 | /** Server-assigned numeric id. */ |
| 159 | packetMirroringId: string | undefined; |
| 160 | /** RFC3339 creation timestamp. */ |
| 161 | creationTimestamp: string | undefined; |
| 162 | /** Resource kind. */ |
| 163 | kind: string | undefined; |
| 164 | }, |
| 165 | never, |
| 166 | Providers |
| 167 | >; |
| 168 | |
| 169 | /** |
| 170 | * A regional Compute Engine packet mirroring policy. |
| 171 | * |
| 172 | * Packet Mirroring copies traffic from selected VMs, subnets, or network |
| 173 | * tags in a VPC and sends it to a collector internal passthrough Network |
| 174 | * Load Balancer (`ForwardingRule` with `isMirroringCollector: true`). |
| 175 | * Compute PacketMirroring has no labels field — Alchemy ownership is |
| 176 | * stored in the description so nuke can find leaked resources. |
| 177 | * |
| 178 | * Name, region, network, and description are immutable; collector ILB, |
| 179 | * mirrored sources, filter, enable, and priority update in place. |
| 180 | * |
| 181 | * ### Creating a Packet Mirroring Policy |
| 182 | * **Example:** Mirror VMs by network tag |
| 183 | * ```typescript |
| 184 | * const policy = yield* GCP.Compute.PacketMirroring("Capture", { |
| 185 | * network: vpc.selfLink, |
| 186 | * collectorIlb: collector.selfLink, |
| 187 | * mirroredResources: { tags: ["mirror-me"] }, |
| 188 | * }); |
| 189 | * ``` |
| 190 | * |
| 191 | * **Example:** Named policy with a traffic filter |
| 192 | * ```typescript |
| 193 | * const policy = yield* GCP.Compute.PacketMirroring("Capture", { |
| 194 | * packetMirroringName: "app-capture", |
| 195 | * region: "us-central1", |
| 196 | * description: "tcp to the collector", |
| 197 | * network: "default", |
| 198 | * collectorIlb: collector.selfLink, |
| 199 | * mirroredResources: { |
| 200 | * subnetworks: [subnet.selfLink], |
| 201 | * tags: ["web"], |
| 202 | * }, |
| 203 | * filter: { |
| 204 | * direction: "BOTH", |
| 205 | * ipProtocols: ["tcp"], |
| 206 | * cidrRanges: ["0.0.0.0/0"], |
| 207 | * }, |
| 208 | * priority: 800, |
| 209 | * }); |
| 210 | * ``` |
| 211 | * |
| 212 | * ### Updating a Policy |
| 213 | * **Example:** Disable mirroring without deleting the policy |
| 214 | * ```typescript |
| 215 | * const policy = yield* GCP.Compute.PacketMirroring("Capture", { |
| 216 | * packetMirroringName: "app-capture", |
| 217 | * network: vpc.selfLink, |
| 218 | * collectorIlb: collector.selfLink, |
| 219 | * mirroredResources: { tags: ["mirror-me"] }, |
| 220 | * enable: false, |
| 221 | * }); |
| 222 | * ``` |
| 223 | * |
| 224 | * @resource |
| 225 | * @category Compute |
| 226 | */ |
| 227 | export const PacketMirroring = Resource<PacketMirroring>("GCP.Compute.PacketMirroring"); |
| 228 | |
| 229 | export class PacketMirroringNotResolved extends Data.TaggedError( |
| 230 | "GCP.Compute.PacketMirroringNotResolved", |
| 231 | )<{ |
| 232 | packetMirroringName: string; |
| 233 | region: string; |
| 234 | }> {} |
| 235 | |
| 236 | const lastSegment = (value: string | undefined): string => { |
| 237 | if (value === undefined || value.length === 0) return ""; |
| 238 | const trimmed = value.replace(/\/+$/, ""); |
| 239 | const parts = trimmed.split("/").filter((part) => part.length > 0); |
| 240 | return parts[parts.length - 1] ?? ""; |
| 241 | }; |
| 242 | |
| 243 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 244 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 245 | |
| 246 | const rfc1035 = (name: string): string => { |
| 247 | let next = name |
| 248 | .toLowerCase() |
| 249 | .replace(/[^a-z0-9-]/g, "-") |
| 250 | .replace(/-+/g, "-") |
| 251 | .replace(/^-+|-+$/g, ""); |
| 252 | if (!/^[a-z]/.test(next)) next = `p${next}`; |
| 253 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 254 | return next.length > 0 ? next : "packet"; |
| 255 | }; |
| 256 | |
| 257 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 258 | Effect.gen(function* () { |
| 259 | if (name !== undefined) return name; |
| 260 | if (existing !== undefined) return existing; |
| 261 | return rfc1035( |
| 262 | yield* createPhysicalName({ |
| 263 | id, |
| 264 | maxLength: MAX_NAME_LENGTH, |
| 265 | lowercase: true, |
| 266 | }), |
| 267 | ); |
| 268 | }); |
| 269 | |
| 270 | const encodeDescription = ( |
| 271 | labels: Record<string, string>, |
| 272 | description: string | undefined, |
| 273 | ): string => { |
| 274 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 275 | return description ? `${marker}\n${description}` : marker; |
| 276 | }; |
| 277 | |
| 278 | const parseDescription = ( |
| 279 | description: string | undefined, |
| 280 | ): { |
| 281 | labels: Record<string, string>; |
| 282 | description: string | undefined; |
| 283 | } => { |
| 284 | if (!description?.startsWith("[alchemy ")) { |
| 285 | return { labels: {}, description }; |
| 286 | } |
| 287 | const end = description.indexOf("]"); |
| 288 | if (end < 0) return { labels: {}, description }; |
| 289 | const labels: Record<string, string> = {}; |
| 290 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 291 | const eq = part.indexOf("="); |
| 292 | if (eq > 0) { |
| 293 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 294 | } |
| 295 | } |
| 296 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 297 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 298 | }; |
| 299 | |
| 300 | const toNetworkUrl = (project: string, network: string) => { |
| 301 | if (network.includes("/")) { |
| 302 | return network.startsWith("projects/") || network.startsWith("http") |
| 303 | ? network |
| 304 | : `projects/${project}/${network.replace(/^\//, "")}`; |
| 305 | } |
| 306 | return `projects/${project}/global/networks/${network}`; |
| 307 | }; |
| 308 | |
| 309 | const toForwardingRuleUrl = (project: string, region: string, collectorIlb: string) => { |
| 310 | if (collectorIlb.includes("/")) { |
| 311 | return collectorIlb.startsWith("projects/") || collectorIlb.startsWith("http") |
| 312 | ? collectorIlb |
| 313 | : `projects/${project}/${collectorIlb.replace(/^\//, "")}`; |
| 314 | } |
| 315 | return `projects/${project}/regions/${region}/forwardingRules/${collectorIlb}`; |
| 316 | }; |
| 317 | |
| 318 | const toSubnetworkUrl = (project: string, region: string, subnet: string) => { |
| 319 | if (subnet.includes("/")) { |
| 320 | return subnet.startsWith("projects/") || subnet.startsWith("http") |
| 321 | ? subnet |
| 322 | : `projects/${project}/${subnet.replace(/^\//, "")}`; |
| 323 | } |
| 324 | return `projects/${project}/regions/${region}/subnetworks/${subnet}`; |
| 325 | }; |
| 326 | |
| 327 | const toInstanceUrl = (project: string, instance: string) => { |
| 328 | if (instance.includes("/")) { |
| 329 | return instance.startsWith("projects/") || instance.startsWith("http") |
| 330 | ? instance |
| 331 | : `projects/${project}/${instance.replace(/^\//, "")}`; |
| 332 | } |
| 333 | return instance; |
| 334 | }; |
| 335 | |
| 336 | const enableOf = (value: boolean | string | undefined): compute.PacketMirroringEnableEnum => |
| 337 | value === false || value === "FALSE" ? "FALSE" : DEFAULT_ENABLE; |
| 338 | |
| 339 | const enableFlag = (value: string | undefined) => enableOf(value) === "TRUE"; |
| 340 | |
| 341 | const sorted = (values: ReadonlyArray<string> | undefined) => |
| 342 | [...(values ?? [])].map(String).sort(); |
| 343 | |
| 344 | const urlsKey = (values: ReadonlyArray<string> | undefined) => |
| 345 | sorted((values ?? []).map(lastSegment)).join(","); |
| 346 | |
| 347 | const listsKey = (values: ReadonlyArray<string> | undefined) => sorted(values).join(","); |
| 348 | |
| 349 | const toApiMirrored = ( |
| 350 | project: string, |
| 351 | region: string, |
| 352 | resources: PacketMirroringMirroredResources, |
| 353 | ): compute.PacketMirroringMirroredResourceInfo => ({ |
| 354 | tags: resources.tags, |
| 355 | subnetworks: resources.subnetworks?.map((url) => ({ |
| 356 | url: toSubnetworkUrl(project, region, url), |
| 357 | })), |
| 358 | instances: resources.instances?.map((url) => ({ |
| 359 | url: toInstanceUrl(project, url), |
| 360 | })), |
| 361 | }); |
| 362 | |
| 363 | const fromApiMirrored = (resources: compute.PacketMirroringMirroredResourceInfo | undefined) => ({ |
| 364 | subnetworks: (resources?.subnetworks ?? []).flatMap((item) => (item.url ? [item.url] : [])), |
| 365 | instances: (resources?.instances ?? []).flatMap((item) => (item.url ? [item.url] : [])), |
| 366 | tags: resources?.tags ?? [], |
| 367 | }); |
| 368 | |
| 369 | const toApiFilter = ( |
| 370 | filter: PacketMirroringFilter | undefined, |
| 371 | ): compute.PacketMirroringFilter | undefined => { |
| 372 | if (filter === undefined) return undefined; |
| 373 | return { |
| 374 | direction: filter.direction ?? DEFAULT_DIRECTION, |
| 375 | IPProtocols: filter.ipProtocols, |
| 376 | cidrRanges: filter.cidrRanges, |
| 377 | }; |
| 378 | }; |
| 379 | |
| 380 | const fromApiFilter = (filter: compute.PacketMirroringFilter | undefined) => { |
| 381 | if (filter === undefined) return undefined; |
| 382 | const ipProtocols = filter.IPProtocols ?? []; |
| 383 | const cidrRanges = filter.cidrRanges ?? []; |
| 384 | const direction = filter.direction; |
| 385 | if (direction === undefined && ipProtocols.length === 0 && cidrRanges.length === 0) { |
| 386 | return undefined; |
| 387 | } |
| 388 | return { |
| 389 | direction, |
| 390 | ipProtocols, |
| 391 | cidrRanges, |
| 392 | }; |
| 393 | }; |
| 394 | |
| 395 | const filterKey = (filter: PacketMirroringFilter | undefined) => { |
| 396 | const direction = (filter?.direction ?? DEFAULT_DIRECTION).toUpperCase(); |
| 397 | return `${direction}|${listsKey(filter?.ipProtocols)}|${listsKey(filter?.cidrRanges)}`; |
| 398 | }; |
| 399 | |
| 400 | const mirroredKey = (resources: PacketMirroringMirroredResources) => |
| 401 | [ |
| 402 | `tags=${listsKey(resources.tags)}`, |
| 403 | `subnets=${urlsKey(resources.subnetworks)}`, |
| 404 | `instances=${urlsKey(resources.instances)}`, |
| 405 | ].join("|"); |
| 406 | |
| 407 | const toAttrs = (policy: compute.PacketMirroring, project: string) => { |
| 408 | const parsed = parseDescription(policy.description); |
| 409 | const mirrored = fromApiMirrored(policy.mirroredResources); |
| 410 | return { |
| 411 | packetMirroringName: policy.name ?? policy.id ?? "", |
| 412 | project, |
| 413 | region: lastSegment(policy.region).toLowerCase(), |
| 414 | description: parsed.description, |
| 415 | network: policy.network?.url ?? "", |
| 416 | networkCanonicalUrl: policy.network?.canonicalUrl, |
| 417 | collectorIlb: policy.collectorIlb?.url ?? "", |
| 418 | collectorIlbCanonicalUrl: policy.collectorIlb?.canonicalUrl, |
| 419 | mirroredResources: mirrored, |
| 420 | enable: enableFlag(policy.enable), |
| 421 | priority: policy.priority ?? DEFAULT_PRIORITY, |
| 422 | filter: fromApiFilter(policy.filter), |
| 423 | selfLink: policy.selfLink, |
| 424 | packetMirroringId: policy.id, |
| 425 | creationTimestamp: policy.creationTimestamp, |
| 426 | kind: policy.kind, |
| 427 | }; |
| 428 | }; |
| 429 | |
| 430 | const getByName = (project: string, region: string, packetMirroring: string) => |
| 431 | compute |
| 432 | .getPacketMirrorings({ project, region, packetMirroring }) |
| 433 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 434 | |
| 435 | const requirePolicy = (project: string, region: string, packetMirroringName: string) => |
| 436 | getByName(project, region, packetMirroringName).pipe( |
| 437 | Effect.flatMap((existing) => |
| 438 | existing !== undefined |
| 439 | ? Effect.succeed(existing) |
| 440 | : Effect.fail(new PacketMirroringNotResolved({ packetMirroringName, region })), |
| 441 | ), |
| 442 | Effect.retry({ |
| 443 | while: (error) => error._tag === "GCP.Compute.PacketMirroringNotResolved", |
| 444 | schedule: Schedule.spaced("1 second"), |
| 445 | times: 8, |
| 446 | }), |
| 447 | ); |
| 448 | |
| 449 | export const PacketMirroringProvider = () => |
| 450 | Provider.succeed(PacketMirroring, { |
| 451 | stables: [ |
| 452 | "packetMirroringName", |
| 453 | "project", |
| 454 | "region", |
| 455 | "network", |
| 456 | "packetMirroringId", |
| 457 | "selfLink", |
| 458 | "creationTimestamp", |
| 459 | ], |
| 460 | |
| 461 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 462 | if (!isResolved(news)) return undefined; |
| 463 | const env = yield* GcpEnvironment.current; |
| 464 | const previousName = olds?.packetMirroringName ?? output?.packetMirroringName; |
| 465 | const nextName = news.packetMirroringName ?? previousName; |
| 466 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 467 | const nextRegion = normalizeRegion(news.region ?? previousRegion, env.region); |
| 468 | const previousNetwork = lastSegment(olds?.network ?? output?.network); |
| 469 | const nextNetwork = lastSegment(news.network); |
| 470 | const previousDescription = olds?.description ?? output?.description ?? ""; |
| 471 | const nextDescription = news.description ?? ""; |
| 472 | |
| 473 | const replace = |
| 474 | (previousName !== undefined && nextName !== undefined && previousName !== nextName) || |
| 475 | previousRegion !== nextRegion || |
| 476 | (previousNetwork.length > 0 && nextNetwork.length > 0 && previousNetwork !== nextNetwork) || |
| 477 | previousDescription !== nextDescription; |
| 478 | |
| 479 | if (!replace) return undefined; |
| 480 | return { |
| 481 | action: "replace" as const, |
| 482 | deleteFirst: |
| 483 | previousName !== undefined && |
| 484 | nextName !== undefined && |
| 485 | previousName === nextName && |
| 486 | previousRegion === nextRegion, |
| 487 | }; |
| 488 | }), |
| 489 | |
| 490 | read: Effect.fn(function* ({ id, olds, output }) { |
| 491 | const env = yield* GcpEnvironment.current; |
| 492 | const packetMirroringName = yield* toName( |
| 493 | id, |
| 494 | olds?.packetMirroringName, |
| 495 | output?.packetMirroringName, |
| 496 | ); |
| 497 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 498 | const existing = yield* getByName(env.project, region, packetMirroringName); |
| 499 | if (existing === undefined) return undefined; |
| 500 | const attrs = toAttrs(existing, env.project); |
| 501 | const { labels } = parseDescription(existing.description); |
| 502 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 503 | }), |
| 504 | |
| 505 | list: () => |
| 506 | Effect.gen(function* () { |
| 507 | const env = yield* GcpEnvironment.current; |
| 508 | const pages = yield* compute.aggregatedListPacketMirrorings |
| 509 | .pages({ |
| 510 | project: env.project, |
| 511 | returnPartialSuccess: true, |
| 512 | maxResults: 500, |
| 513 | }) |
| 514 | .pipe(Stream.runCollect); |
| 515 | return Array.from(pages).flatMap((page) => |
| 516 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 517 | (scoped?.packetMirrorings ?? []) |
| 518 | .filter((item) => { |
| 519 | const { labels } = parseDescription(item.description); |
| 520 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 521 | }) |
| 522 | .map((item) => toAttrs(item, env.project)), |
| 523 | ), |
| 524 | ); |
| 525 | }), |
| 526 | |
| 527 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 528 | const env = yield* GcpEnvironment.current; |
| 529 | const packetMirroringName = yield* toName( |
| 530 | id, |
| 531 | news.packetMirroringName, |
| 532 | output?.packetMirroringName, |
| 533 | ); |
| 534 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 535 | const ownership = yield* createInternalLabels(id); |
| 536 | const desiredDescription = encodeDescription(ownership, news.description); |
| 537 | const desiredNetwork = toNetworkUrl(env.project, news.network); |
| 538 | const desiredCollector = toForwardingRuleUrl(env.project, region, news.collectorIlb); |
| 539 | const desiredEnable = enableOf(news.enable); |
| 540 | const desiredPriority = news.priority ?? DEFAULT_PRIORITY; |
| 541 | const desiredMirrored = toApiMirrored(env.project, region, news.mirroredResources); |
| 542 | const desiredFilter = toApiFilter(news.filter); |
| 543 | |
| 544 | let current = yield* getByName(env.project, region, packetMirroringName); |
| 545 | |
| 546 | if (current === undefined) { |
| 547 | const inserted = yield* compute |
| 548 | .insertPacketMirrorings({ |
| 549 | project: env.project, |
| 550 | region, |
| 551 | body: { |
| 552 | name: packetMirroringName, |
| 553 | description: desiredDescription, |
| 554 | enable: desiredEnable, |
| 555 | priority: desiredPriority, |
| 556 | network: { url: desiredNetwork }, |
| 557 | collectorIlb: { url: desiredCollector }, |
| 558 | mirroredResources: desiredMirrored, |
| 559 | filter: desiredFilter, |
| 560 | }, |
| 561 | }) |
| 562 | .pipe( |
| 563 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 564 | // A just-created collector forwarding rule is briefly not ready. |
| 565 | Effect.retry({ |
| 566 | while: (error) => error._tag === "CollectorIlbNotReady", |
| 567 | times: 8, |
| 568 | schedule: Schedule.spaced("3 seconds"), |
| 569 | }), |
| 570 | ); |
| 571 | if (inserted !== undefined) { |
| 572 | yield* waitRegionOperation(env.project, region, inserted); |
| 573 | } |
| 574 | current = yield* requirePolicy(env.project, region, packetMirroringName); |
| 575 | } |
| 576 | |
| 577 | if (current === undefined) { |
| 578 | return yield* new PacketMirroringNotResolved({ |
| 579 | packetMirroringName, |
| 580 | region, |
| 581 | }); |
| 582 | } |
| 583 | |
| 584 | const observed = toAttrs(current, env.project); |
| 585 | const patch: compute.PacketMirroring = {}; |
| 586 | |
| 587 | if ((current.description ?? "") !== desiredDescription) { |
| 588 | patch.description = desiredDescription; |
| 589 | } |
| 590 | if (enableOf(current.enable) !== desiredEnable) { |
| 591 | patch.enable = desiredEnable; |
| 592 | } |
| 593 | if (observed.priority !== desiredPriority) { |
| 594 | patch.priority = desiredPriority; |
| 595 | } |
| 596 | if (lastSegment(observed.collectorIlb) !== lastSegment(desiredCollector)) { |
| 597 | patch.collectorIlb = { url: desiredCollector }; |
| 598 | } |
| 599 | if (mirroredKey(observed.mirroredResources) !== mirroredKey(news.mirroredResources)) { |
| 600 | patch.mirroredResources = desiredMirrored; |
| 601 | } |
| 602 | if (filterKey(observed.filter) !== filterKey(news.filter)) { |
| 603 | patch.filter = desiredFilter ?? { |
| 604 | direction: DEFAULT_DIRECTION, |
| 605 | IPProtocols: [], |
| 606 | cidrRanges: [], |
| 607 | }; |
| 608 | } |
| 609 | |
| 610 | if (Object.keys(patch).length > 0) { |
| 611 | yield* compute |
| 612 | .patchPacketMirrorings({ |
| 613 | project: env.project, |
| 614 | region, |
| 615 | packetMirroring: packetMirroringName, |
| 616 | body: patch, |
| 617 | }) |
| 618 | .pipe( |
| 619 | Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)), |
| 620 | Effect.retry({ |
| 621 | while: (error) => error._tag === "Conflict", |
| 622 | times: 5, |
| 623 | schedule: Schedule.spaced("2 seconds"), |
| 624 | }), |
| 625 | ); |
| 626 | current = yield* requirePolicy(env.project, region, packetMirroringName); |
| 627 | } |
| 628 | |
| 629 | return toAttrs(current, env.project); |
| 630 | }), |
| 631 | |
| 632 | delete: Effect.fn(function* ({ output }) { |
| 633 | const env = yield* GcpEnvironment.current; |
| 634 | const region = normalizeRegion(output.region, env.region); |
| 635 | const operation = yield* compute |
| 636 | .deletePacketMirrorings({ |
| 637 | project: env.project, |
| 638 | region, |
| 639 | packetMirroring: output.packetMirroringName, |
| 640 | }) |
| 641 | .pipe( |
| 642 | Effect.retry({ |
| 643 | while: (error) => error._tag === "Conflict", |
| 644 | times: 8, |
| 645 | schedule: Schedule.spaced("2 seconds"), |
| 646 | }), |
| 647 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 648 | ); |
| 649 | if (operation !== undefined) { |
| 650 | yield* waitRegionOperation(env.project, region, operation, { |
| 651 | ignore: ["RESOURCE_NOT_FOUND"], |
| 652 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 653 | } |
| 654 | }), |
| 655 | }); |