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 { unownedUnlessPrevious } 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 { ignoredCodes } from "./internal.ts"; |
| 15 | import { waitGlobalOperation } from "./operations.ts"; |
| 16 | |
| 17 | const DEFAULT_POLICY_TYPE = "VPC_POLICY"; |
| 18 | const RESERVED_PRIORITY_MIN = 2147483548; |
| 19 | const RESERVED_PRIORITY_MAX = 2147483647; |
| 20 | const MAX_NAME_LENGTH = 63; |
| 21 | |
| 22 | const isReservedPriority = (priority: number | undefined) => |
| 23 | priority !== undefined && priority >= RESERVED_PRIORITY_MIN && priority <= RESERVED_PRIORITY_MAX; |
| 24 | |
| 25 | export type NetworkFirewallPolicyType = compute.FirewallPolicyPolicyTypeEnum | (string & {}); |
| 26 | export type NetworkFirewallPolicyRule = compute.FirewallPolicyRule; |
| 27 | export type NetworkFirewallPolicyRuleMatcher = compute.FirewallPolicyRuleMatcher; |
| 28 | export type NetworkFirewallPolicyAssociation = compute.FirewallPolicyAssociation; |
| 29 | |
| 30 | export type NetworkFirewallPolicyProps = { |
| 31 | /** |
| 32 | * Policy name (RFC1035, 1-63 characters). If omitted, a unique name is |
| 33 | * generated from the stack, stage, and logical id. Immutable — changing |
| 34 | * it replaces the policy. |
| 35 | */ |
| 36 | networkFirewallPolicyName?: string; |
| 37 | /** |
| 38 | * Optional description. Network firewall policies have no labels field, |
| 39 | * so Alchemy ownership (`alchemy-stack` / `alchemy-stage` / |
| 40 | * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke. |
| 41 | * Updated in place via `patch`. |
| 42 | */ |
| 43 | description?: string; |
| 44 | /** |
| 45 | * Policy type. Set only at create time — changing it replaces the |
| 46 | * policy. |
| 47 | * @default "VPC_POLICY" |
| 48 | */ |
| 49 | policyType?: NetworkFirewallPolicyType; |
| 50 | /** |
| 51 | * Hierarchical firewall rules. GCP always keeps default `goto_next` |
| 52 | * rules in the reserved priority range `2147483548`–`2147483647`; |
| 53 | * Alchemy never add/patch/remove those. When this field is set, user |
| 54 | * rules are synced with `addRule` / `patchRule` / `removeRule`. When |
| 55 | * omitted on later updates, observed rules are left in place. |
| 56 | */ |
| 57 | rules?: NetworkFirewallPolicyRule[]; |
| 58 | /** |
| 59 | * VPC associations. When set, Alchemy syncs associations with |
| 60 | * `addAssociation` / `removeAssociation`. `attachmentTarget` accepts a |
| 61 | * network name or URL. When omitted on later updates, observed |
| 62 | * associations are left in place. |
| 63 | */ |
| 64 | associations?: NetworkFirewallPolicyAssociation[]; |
| 65 | }; |
| 66 | |
| 67 | export type NetworkFirewallPolicy = Resource< |
| 68 | "GCP.Compute.NetworkFirewallPolicy", |
| 69 | NetworkFirewallPolicyProps, |
| 70 | { |
| 71 | /** Policy name. */ |
| 72 | networkFirewallPolicyName: string; |
| 73 | /** Project id. */ |
| 74 | project: string; |
| 75 | /** User description with the Alchemy ownership prefix stripped. */ |
| 76 | description: string | undefined; |
| 77 | /** Policy type. */ |
| 78 | policyType: string; |
| 79 | /** Rules currently attached (including the default). */ |
| 80 | rules: NetworkFirewallPolicyRule[]; |
| 81 | /** Associations currently attached. */ |
| 82 | associations: NetworkFirewallPolicyAssociation[]; |
| 83 | /** Optimistic-locking fingerprint. */ |
| 84 | fingerprint: string | undefined; |
| 85 | /** Server-assigned numeric id. */ |
| 86 | networkFirewallPolicyId: string | undefined; |
| 87 | /** Resource self-link. */ |
| 88 | selfLink: string | undefined; |
| 89 | /** Self-link including the numeric id. */ |
| 90 | selfLinkWithId: string | undefined; |
| 91 | /** Total count of rule tuples. */ |
| 92 | ruleTupleCount: number | undefined; |
| 93 | /** RFC3339 creation timestamp. */ |
| 94 | creationTimestamp: string | undefined; |
| 95 | /** Resource kind. */ |
| 96 | kind: string | undefined; |
| 97 | }, |
| 98 | never, |
| 99 | Providers |
| 100 | >; |
| 101 | |
| 102 | /** |
| 103 | * A global Compute Engine network firewall policy. |
| 104 | * |
| 105 | * Network firewall policies live at the project level under |
| 106 | * `global/firewallPolicies` and are identified by the user-provided |
| 107 | * `name`. Name and policy type are immutable. Description updates in |
| 108 | * place via `networkFirewallPolicies.patch`. Rules are synced with |
| 109 | * `addRule` / `patchRule` / `removeRule`. Associations are synced with |
| 110 | * `addAssociation` / `removeAssociation`. Compute network firewall |
| 111 | * policies have no labels field — Alchemy stamps ownership into the |
| 112 | * description so nuke can find leaked policies. |
| 113 | * |
| 114 | * ### Creating a Network Firewall Policy |
| 115 | * **Example:** Generated name with an allow rule |
| 116 | * ```typescript |
| 117 | * const policy = yield* GCP.Compute.NetworkFirewallPolicy("VpcFw", { |
| 118 | * description: "allow internal http", |
| 119 | * rules: [ |
| 120 | * { |
| 121 | * action: "allow", |
| 122 | * priority: 1000, |
| 123 | * direction: "INGRESS", |
| 124 | * match: { |
| 125 | * srcIpRanges: ["10.0.0.0/8"], |
| 126 | * layer4Configs: [{ ipProtocol: "tcp", ports: ["80"] }], |
| 127 | * }, |
| 128 | * }, |
| 129 | * ], |
| 130 | * }); |
| 131 | * ``` |
| 132 | * |
| 133 | * **Example:** Associate with a VPC |
| 134 | * ```typescript |
| 135 | * const policy = yield* GCP.Compute.NetworkFirewallPolicy("VpcFw", { |
| 136 | * networkFirewallPolicyName: "app-nfw", |
| 137 | * associations: [{ name: "vpc", attachmentTarget: network.selfLink }], |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * @resource |
| 142 | * @category Compute |
| 143 | */ |
| 144 | export const NetworkFirewallPolicy = Resource<NetworkFirewallPolicy>( |
| 145 | "GCP.Compute.NetworkFirewallPolicy", |
| 146 | ); |
| 147 | |
| 148 | export class NetworkFirewallPolicyNotResolved extends Data.TaggedError( |
| 149 | "GCP.Compute.NetworkFirewallPolicyNotResolved", |
| 150 | )<{ |
| 151 | networkFirewallPolicyName: string; |
| 152 | }> {} |
| 153 | |
| 154 | export class NetworkFirewallPolicyStillExists extends Data.TaggedError( |
| 155 | "GCP.Compute.NetworkFirewallPolicyStillExists", |
| 156 | )<{ |
| 157 | networkFirewallPolicyName: string; |
| 158 | }> {} |
| 159 | |
| 160 | const lastSegment = (value: string | undefined): string => { |
| 161 | if (value === undefined || value.length === 0) return ""; |
| 162 | const trimmed = value.replace(/\/+$/, ""); |
| 163 | const parts = trimmed.split("/"); |
| 164 | return parts[parts.length - 1] || trimmed; |
| 165 | }; |
| 166 | |
| 167 | const rfc1035 = (name: string): string => { |
| 168 | let next = name |
| 169 | .toLowerCase() |
| 170 | .replace(/[^a-z0-9-]/g, "-") |
| 171 | .replace(/-+/g, "-") |
| 172 | .replace(/^-+/, "") |
| 173 | .replace(/-+$/, ""); |
| 174 | if (!/^[a-z]/.test(next)) next = `p${next}`; |
| 175 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 176 | return next.length > 0 ? next : "policy"; |
| 177 | }; |
| 178 | |
| 179 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 180 | Effect.gen(function* () { |
| 181 | if (name !== undefined) return rfc1035(name); |
| 182 | if (existing !== undefined) return existing; |
| 183 | return rfc1035( |
| 184 | yield* createPhysicalName({ |
| 185 | id, |
| 186 | maxLength: MAX_NAME_LENGTH, |
| 187 | lowercase: true, |
| 188 | }), |
| 189 | ); |
| 190 | }); |
| 191 | |
| 192 | const typeOf = (value: string | undefined) => (value ?? DEFAULT_POLICY_TYPE).toUpperCase(); |
| 193 | |
| 194 | const encodeDescription = ( |
| 195 | labels: Record<string, string>, |
| 196 | description: string | undefined, |
| 197 | ): string => { |
| 198 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 199 | return description ? `${marker}\n${description}` : marker; |
| 200 | }; |
| 201 | |
| 202 | const parseDescription = ( |
| 203 | description: string | undefined, |
| 204 | ): { |
| 205 | labels: Record<string, string>; |
| 206 | description: string | undefined; |
| 207 | } => { |
| 208 | if (!description?.startsWith("[alchemy ")) { |
| 209 | return { labels: {}, description }; |
| 210 | } |
| 211 | const end = description.indexOf("]"); |
| 212 | if (end < 0) return { labels: {}, description }; |
| 213 | const labels: Record<string, string> = {}; |
| 214 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 215 | const eq = part.indexOf("="); |
| 216 | if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 217 | } |
| 218 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 219 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 220 | }; |
| 221 | |
| 222 | const hasOwnershipMarker = (description: string | undefined) => |
| 223 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 224 | |
| 225 | const networkUrl = (project: string, value: string) => { |
| 226 | if (value.includes("/")) return value; |
| 227 | return `projects/${project}/global/networks/${value}`; |
| 228 | }; |
| 229 | |
| 230 | const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort(); |
| 231 | |
| 232 | const sameJson = (left: unknown, right: unknown) => |
| 233 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 234 | |
| 235 | const canonMatch = (match: NetworkFirewallPolicyRuleMatcher | undefined) => { |
| 236 | if (match === undefined) return undefined; |
| 237 | return { |
| 238 | srcIpRanges: sorted(match.srcIpRanges), |
| 239 | destIpRanges: sorted(match.destIpRanges), |
| 240 | srcFqdns: sorted(match.srcFqdns), |
| 241 | destFqdns: sorted(match.destFqdns), |
| 242 | srcRegionCodes: sorted(match.srcRegionCodes), |
| 243 | destRegionCodes: sorted(match.destRegionCodes), |
| 244 | srcAddressGroups: sorted(match.srcAddressGroups), |
| 245 | destAddressGroups: sorted(match.destAddressGroups), |
| 246 | srcThreatIntelligences: sorted(match.srcThreatIntelligences), |
| 247 | destThreatIntelligences: sorted(match.destThreatIntelligences), |
| 248 | srcNetworks: sorted(match.srcNetworks), |
| 249 | srcNetworkType: match.srcNetworkType, |
| 250 | destNetworkType: match.destNetworkType, |
| 251 | layer4Configs: [...(match.layer4Configs ?? [])] |
| 252 | .map((config) => ({ |
| 253 | ipProtocol: (config.ipProtocol ?? "").toLowerCase(), |
| 254 | ports: sorted(config.ports), |
| 255 | })) |
| 256 | .sort( |
| 257 | (left, right) => |
| 258 | left.ipProtocol.localeCompare(right.ipProtocol) || |
| 259 | JSON.stringify(left.ports).localeCompare(JSON.stringify(right.ports)), |
| 260 | ), |
| 261 | srcSecureTags: [...(match.srcSecureTags ?? [])].map((tag) => tag.name ?? "").sort(), |
| 262 | }; |
| 263 | }; |
| 264 | |
| 265 | const canonRule = (rule: NetworkFirewallPolicyRule) => ({ |
| 266 | priority: rule.priority, |
| 267 | action: rule.action, |
| 268 | description: rule.description ?? "", |
| 269 | direction: (rule.direction ?? "INGRESS").toUpperCase(), |
| 270 | enableLogging: rule.enableLogging === true, |
| 271 | disabled: rule.disabled === true, |
| 272 | ruleName: rule.ruleName ?? "", |
| 273 | tlsInspect: rule.tlsInspect === true, |
| 274 | targetType: rule.targetType ?? "INSTANCES", |
| 275 | securityProfileGroup: rule.securityProfileGroup ?? "", |
| 276 | match: canonMatch(rule.match), |
| 277 | targetResources: sorted(rule.targetResources), |
| 278 | targetServiceAccounts: sorted(rule.targetServiceAccounts), |
| 279 | targetForwardingRules: sorted(rule.targetForwardingRules), |
| 280 | targetSecureTags: [...(rule.targetSecureTags ?? [])].map((tag) => tag.name ?? "").sort(), |
| 281 | }); |
| 282 | |
| 283 | const ruleEquals = (left: NetworkFirewallPolicyRule, right: NetworkFirewallPolicyRule) => |
| 284 | sameJson(canonRule(left), canonRule(right)); |
| 285 | |
| 286 | const toRuleBody = (rule: NetworkFirewallPolicyRule): NetworkFirewallPolicyRule => ({ |
| 287 | priority: rule.priority, |
| 288 | action: rule.action, |
| 289 | description: rule.description, |
| 290 | direction: rule.direction, |
| 291 | enableLogging: rule.enableLogging === true ? true : undefined, |
| 292 | disabled: rule.disabled === true ? true : undefined, |
| 293 | ruleName: rule.ruleName, |
| 294 | tlsInspect: rule.tlsInspect === true ? true : undefined, |
| 295 | targetType: rule.targetType, |
| 296 | securityProfileGroup: rule.securityProfileGroup, |
| 297 | match: rule.match, |
| 298 | targetResources: rule.targetResources, |
| 299 | targetServiceAccounts: rule.targetServiceAccounts, |
| 300 | targetForwardingRules: rule.targetForwardingRules, |
| 301 | targetSecureTags: rule.targetSecureTags, |
| 302 | }); |
| 303 | |
| 304 | const desiredRules = ( |
| 305 | news: NetworkFirewallPolicyProps, |
| 306 | ): NetworkFirewallPolicyRule[] | undefined => { |
| 307 | if (news.rules === undefined) return undefined; |
| 308 | const byPriority = new Map<number, NetworkFirewallPolicyRule>(); |
| 309 | for (const rule of news.rules) { |
| 310 | if (rule.priority === undefined) continue; |
| 311 | if (isReservedPriority(rule.priority)) continue; |
| 312 | byPriority.set(rule.priority, rule); |
| 313 | } |
| 314 | return [...byPriority.values()].sort( |
| 315 | (left, right) => (left.priority ?? 0) - (right.priority ?? 0), |
| 316 | ); |
| 317 | }; |
| 318 | |
| 319 | const associationNameOf = (association: NetworkFirewallPolicyAssociation): string => |
| 320 | association.name && association.name.length > 0 |
| 321 | ? association.name |
| 322 | : lastSegment(association.attachmentTarget) || "assoc"; |
| 323 | |
| 324 | const toAttrs = ( |
| 325 | policy: compute.FirewallPolicy, |
| 326 | project: string, |
| 327 | ): NetworkFirewallPolicy["Attributes"] => { |
| 328 | const parsed = parseDescription(policy.description); |
| 329 | return { |
| 330 | networkFirewallPolicyName: policy.name ?? "", |
| 331 | project, |
| 332 | description: parsed.description, |
| 333 | policyType: typeOf(policy.policyType), |
| 334 | rules: policy.rules ?? [], |
| 335 | associations: policy.associations ?? [], |
| 336 | fingerprint: policy.fingerprint, |
| 337 | networkFirewallPolicyId: policy.id, |
| 338 | selfLink: policy.selfLink, |
| 339 | selfLinkWithId: policy.selfLinkWithId, |
| 340 | ruleTupleCount: policy.ruleTupleCount, |
| 341 | creationTimestamp: policy.creationTimestamp, |
| 342 | kind: policy.kind, |
| 343 | }; |
| 344 | }; |
| 345 | |
| 346 | const getByName = (project: string, firewallPolicy: string) => |
| 347 | compute |
| 348 | .getNetworkFirewallPolicies({ project, firewallPolicy }) |
| 349 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 350 | |
| 351 | const awaitResource = (project: string, networkFirewallPolicyName: string) => |
| 352 | getByName(project, networkFirewallPolicyName).pipe( |
| 353 | Effect.flatMap((policy) => |
| 354 | policy !== undefined |
| 355 | ? Effect.succeed(policy) |
| 356 | : Effect.fail( |
| 357 | new NetworkFirewallPolicyNotResolved({ |
| 358 | networkFirewallPolicyName, |
| 359 | }), |
| 360 | ), |
| 361 | ), |
| 362 | Effect.retry({ |
| 363 | while: (error) => error._tag === "GCP.Compute.NetworkFirewallPolicyNotResolved", |
| 364 | times: 8, |
| 365 | schedule: Schedule.spaced("1 second"), |
| 366 | }), |
| 367 | ); |
| 368 | |
| 369 | const waitUntilGone = (project: string, networkFirewallPolicyName: string) => |
| 370 | getByName(project, networkFirewallPolicyName).pipe( |
| 371 | Effect.flatMap((policy) => |
| 372 | policy === undefined |
| 373 | ? Effect.void |
| 374 | : Effect.fail( |
| 375 | new NetworkFirewallPolicyStillExists({ |
| 376 | networkFirewallPolicyName, |
| 377 | }), |
| 378 | ), |
| 379 | ), |
| 380 | Effect.retry({ |
| 381 | while: (error) => error._tag === "GCP.Compute.NetworkFirewallPolicyStillExists", |
| 382 | times: 10, |
| 383 | schedule: Schedule.spaced("1 second"), |
| 384 | }), |
| 385 | Effect.catchTag("GCP.Compute.NetworkFirewallPolicyStillExists", () => Effect.void), |
| 386 | ); |
| 387 | |
| 388 | const runOp = <E extends { readonly _tag: string }, R>( |
| 389 | project: string, |
| 390 | networkFirewallPolicyName: string, |
| 391 | start: Effect.Effect<compute.Operation, E, R>, |
| 392 | options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean }, |
| 393 | ) => |
| 394 | start.pipe( |
| 395 | Effect.flatMap((operation) => |
| 396 | waitGlobalOperation(project, operation, { |
| 397 | ignore: ignoredCodes(options), |
| 398 | }), |
| 399 | ), |
| 400 | Effect.retry({ |
| 401 | while: (error) => error._tag === "Conflict", |
| 402 | times: 5, |
| 403 | schedule: Schedule.spaced("1 second"), |
| 404 | }), |
| 405 | ); |
| 406 | |
| 407 | const syncRules = ( |
| 408 | project: string, |
| 409 | networkFirewallPolicyName: string, |
| 410 | observed: readonly NetworkFirewallPolicyRule[], |
| 411 | desired: readonly NetworkFirewallPolicyRule[], |
| 412 | ) => |
| 413 | Effect.gen(function* () { |
| 414 | const observedByPriority = new Map<number, NetworkFirewallPolicyRule>(); |
| 415 | for (const rule of observed) { |
| 416 | if (rule.priority !== undefined) { |
| 417 | observedByPriority.set(rule.priority, rule); |
| 418 | } |
| 419 | } |
| 420 | const desiredByPriority = new Map<number, NetworkFirewallPolicyRule>(); |
| 421 | for (const rule of desired) { |
| 422 | if (rule.priority !== undefined) { |
| 423 | desiredByPriority.set(rule.priority, rule); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | for (const [priority, rule] of desiredByPriority) { |
| 428 | if (isReservedPriority(priority)) continue; |
| 429 | const current = observedByPriority.get(priority); |
| 430 | if (current === undefined) { |
| 431 | yield* runOp( |
| 432 | project, |
| 433 | networkFirewallPolicyName, |
| 434 | compute.addRuleNetworkFirewallPolicies({ |
| 435 | project, |
| 436 | firewallPolicy: networkFirewallPolicyName, |
| 437 | body: toRuleBody(rule), |
| 438 | }), |
| 439 | { ignoreAlreadyExists: true }, |
| 440 | ); |
| 441 | continue; |
| 442 | } |
| 443 | if (!ruleEquals(current, rule)) { |
| 444 | yield* runOp( |
| 445 | project, |
| 446 | networkFirewallPolicyName, |
| 447 | compute.patchRuleNetworkFirewallPolicies({ |
| 448 | project, |
| 449 | firewallPolicy: networkFirewallPolicyName, |
| 450 | priority, |
| 451 | body: toRuleBody(rule), |
| 452 | }), |
| 453 | ); |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | for (const priority of observedByPriority.keys()) { |
| 458 | if (desiredByPriority.has(priority)) continue; |
| 459 | if (isReservedPriority(priority)) continue; |
| 460 | yield* runOp( |
| 461 | project, |
| 462 | networkFirewallPolicyName, |
| 463 | compute.removeRuleNetworkFirewallPolicies({ |
| 464 | project, |
| 465 | firewallPolicy: networkFirewallPolicyName, |
| 466 | priority, |
| 467 | }), |
| 468 | { ignoreNotFound: true }, |
| 469 | ).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 470 | } |
| 471 | }); |
| 472 | |
| 473 | const syncAssociations = ( |
| 474 | project: string, |
| 475 | networkFirewallPolicyName: string, |
| 476 | observed: readonly NetworkFirewallPolicyAssociation[], |
| 477 | desired: readonly NetworkFirewallPolicyAssociation[], |
| 478 | ) => |
| 479 | Effect.gen(function* () { |
| 480 | const observedByName = new Map<string, NetworkFirewallPolicyAssociation>(); |
| 481 | for (const association of observed) { |
| 482 | observedByName.set(associationNameOf(association), association); |
| 483 | } |
| 484 | const desiredByName = new Map<string, NetworkFirewallPolicyAssociation>(); |
| 485 | for (const association of desired) { |
| 486 | desiredByName.set(associationNameOf(association), association); |
| 487 | } |
| 488 | |
| 489 | for (const [name, association] of desiredByName) { |
| 490 | const current = observedByName.get(name); |
| 491 | const target = association.attachmentTarget |
| 492 | ? networkUrl(project, association.attachmentTarget) |
| 493 | : undefined; |
| 494 | if (current === undefined) { |
| 495 | yield* runOp( |
| 496 | project, |
| 497 | networkFirewallPolicyName, |
| 498 | compute.addAssociationNetworkFirewallPolicies({ |
| 499 | project, |
| 500 | firewallPolicy: networkFirewallPolicyName, |
| 501 | body: { name, attachmentTarget: target }, |
| 502 | }), |
| 503 | { ignoreAlreadyExists: true }, |
| 504 | ); |
| 505 | continue; |
| 506 | } |
| 507 | if (lastSegment(current.attachmentTarget) !== lastSegment(target) && target !== undefined) { |
| 508 | yield* runOp( |
| 509 | project, |
| 510 | networkFirewallPolicyName, |
| 511 | compute.addAssociationNetworkFirewallPolicies({ |
| 512 | project, |
| 513 | firewallPolicy: networkFirewallPolicyName, |
| 514 | replaceExistingAssociation: true, |
| 515 | body: { name, attachmentTarget: target }, |
| 516 | }), |
| 517 | ); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | for (const name of observedByName.keys()) { |
| 522 | if (desiredByName.has(name)) continue; |
| 523 | yield* runOp( |
| 524 | project, |
| 525 | networkFirewallPolicyName, |
| 526 | compute.removeAssociationNetworkFirewallPolicies({ |
| 527 | project, |
| 528 | firewallPolicy: networkFirewallPolicyName, |
| 529 | name, |
| 530 | }), |
| 531 | { ignoreNotFound: true }, |
| 532 | ).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 533 | } |
| 534 | }); |
| 535 | |
| 536 | export const NetworkFirewallPolicyProvider = () => |
| 537 | Provider.succeed(NetworkFirewallPolicy, { |
| 538 | stables: [ |
| 539 | "networkFirewallPolicyName", |
| 540 | "project", |
| 541 | "networkFirewallPolicyId", |
| 542 | "policyType", |
| 543 | "selfLink", |
| 544 | "selfLinkWithId", |
| 545 | "creationTimestamp", |
| 546 | ], |
| 547 | |
| 548 | diff: Effect.fn(function* ({ id, news, olds, output }) { |
| 549 | if (!isResolved(news)) return undefined; |
| 550 | // Name is immutable on GCP. Resolve the desired name the same way |
| 551 | // create does — do not fall back to previousName when news omits |
| 552 | // networkFirewallPolicyName, or a generated-name change looks like a no-op. |
| 553 | const previousName = output?.networkFirewallPolicyName ?? olds?.networkFirewallPolicyName; |
| 554 | const nextName = yield* toName(id, news.networkFirewallPolicyName); |
| 555 | const nameChanged = previousName !== undefined && previousName !== nextName; |
| 556 | const previousType = typeOf(olds?.policyType ?? output?.policyType); |
| 557 | const nextType = typeOf(news.policyType ?? previousType); |
| 558 | if (nameChanged) { |
| 559 | return { action: "replace" as const, deleteFirst: false }; |
| 560 | } |
| 561 | if (previousType !== nextType) { |
| 562 | return { action: "replace" as const, deleteFirst: true }; |
| 563 | } |
| 564 | return undefined; |
| 565 | }), |
| 566 | |
| 567 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 568 | const env = yield* GcpEnvironment.current; |
| 569 | const networkFirewallPolicyName = yield* toName( |
| 570 | id, |
| 571 | olds?.networkFirewallPolicyName, |
| 572 | output?.networkFirewallPolicyName, |
| 573 | ); |
| 574 | const existing = yield* getByName(env.project, networkFirewallPolicyName); |
| 575 | if (existing === undefined) return undefined; |
| 576 | const attrs = toAttrs(existing, env.project); |
| 577 | const { labels } = parseDescription(existing.description); |
| 578 | return (yield* hasAlchemyLabels(id, labels)) |
| 579 | ? attrs |
| 580 | : unownedUnlessPrevious(attrs, previous, "networkFirewallPolicyName"); |
| 581 | }), |
| 582 | |
| 583 | list: () => |
| 584 | Effect.gen(function* () { |
| 585 | const env = yield* GcpEnvironment.current; |
| 586 | return yield* compute.listNetworkFirewallPolicies |
| 587 | .items({ |
| 588 | project: env.project, |
| 589 | maxResults: 500, |
| 590 | returnPartialSuccess: true, |
| 591 | }) |
| 592 | .pipe( |
| 593 | Stream.filter((policy) => hasOwnershipMarker(policy.description)), |
| 594 | Stream.map((policy) => toAttrs(policy, env.project)), |
| 595 | Stream.runCollect, |
| 596 | Effect.map((items) => Array.from(items)), |
| 597 | Effect.catchTag("NotFound", () => |
| 598 | Effect.succeed([] as NetworkFirewallPolicy["Attributes"][]), |
| 599 | ), |
| 600 | ); |
| 601 | }), |
| 602 | |
| 603 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 604 | const env = yield* GcpEnvironment.current; |
| 605 | const networkFirewallPolicyName = yield* toName( |
| 606 | id, |
| 607 | news.networkFirewallPolicyName, |
| 608 | output?.networkFirewallPolicyName, |
| 609 | ); |
| 610 | const ownership = yield* createInternalLabels(id); |
| 611 | const desiredDescription = encodeDescription(ownership, news.description); |
| 612 | const policyType = typeOf(news.policyType); |
| 613 | |
| 614 | let current = yield* getByName(env.project, networkFirewallPolicyName); |
| 615 | |
| 616 | if (current === undefined) { |
| 617 | yield* compute |
| 618 | .insertNetworkFirewallPolicies({ |
| 619 | project: env.project, |
| 620 | body: { |
| 621 | name: networkFirewallPolicyName, |
| 622 | description: desiredDescription, |
| 623 | policyType, |
| 624 | }, |
| 625 | }) |
| 626 | .pipe( |
| 627 | Effect.flatMap((operation) => |
| 628 | waitGlobalOperation(env.project, operation, { |
| 629 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 630 | }), |
| 631 | ), |
| 632 | Effect.catchTag("Conflict", () => Effect.void), |
| 633 | ); |
| 634 | current = yield* awaitResource(env.project, networkFirewallPolicyName); |
| 635 | } |
| 636 | |
| 637 | if ((current.description ?? "") !== desiredDescription) { |
| 638 | yield* runOp( |
| 639 | env.project, |
| 640 | networkFirewallPolicyName, |
| 641 | compute.patchNetworkFirewallPolicies({ |
| 642 | project: env.project, |
| 643 | firewallPolicy: networkFirewallPolicyName, |
| 644 | body: { |
| 645 | description: desiredDescription, |
| 646 | fingerprint: current.fingerprint, |
| 647 | }, |
| 648 | }), |
| 649 | ); |
| 650 | current = (yield* getByName(env.project, networkFirewallPolicyName)) ?? current; |
| 651 | } |
| 652 | |
| 653 | const nextRules = desiredRules(news); |
| 654 | if (nextRules !== undefined) { |
| 655 | yield* syncRules(env.project, networkFirewallPolicyName, current.rules ?? [], nextRules); |
| 656 | current = (yield* getByName(env.project, networkFirewallPolicyName)) ?? current; |
| 657 | } |
| 658 | |
| 659 | if (news.associations !== undefined) { |
| 660 | yield* syncAssociations( |
| 661 | env.project, |
| 662 | networkFirewallPolicyName, |
| 663 | current.associations ?? [], |
| 664 | news.associations, |
| 665 | ); |
| 666 | current = (yield* getByName(env.project, networkFirewallPolicyName)) ?? current; |
| 667 | } |
| 668 | |
| 669 | return toAttrs(current, env.project); |
| 670 | }), |
| 671 | |
| 672 | delete: Effect.fn(function* ({ output }) { |
| 673 | if (!output.networkFirewallPolicyName) return; |
| 674 | const env = yield* GcpEnvironment.current; |
| 675 | const project = output.project || env.project; |
| 676 | const existing = yield* getByName(project, output.networkFirewallPolicyName); |
| 677 | for (const association of existing?.associations ?? []) { |
| 678 | const name = associationNameOf(association); |
| 679 | yield* compute |
| 680 | .removeAssociationNetworkFirewallPolicies({ |
| 681 | project, |
| 682 | firewallPolicy: output.networkFirewallPolicyName, |
| 683 | name, |
| 684 | }) |
| 685 | .pipe( |
| 686 | Effect.flatMap((operation) => |
| 687 | waitGlobalOperation(project, operation, { |
| 688 | ignore: ["RESOURCE_NOT_FOUND"], |
| 689 | }), |
| 690 | ), |
| 691 | Effect.catchTag("NotFound", () => Effect.void), |
| 692 | ); |
| 693 | } |
| 694 | yield* compute |
| 695 | .deleteNetworkFirewallPolicies({ |
| 696 | project, |
| 697 | firewallPolicy: output.networkFirewallPolicyName, |
| 698 | }) |
| 699 | .pipe( |
| 700 | Effect.flatMap((operation) => |
| 701 | waitGlobalOperation(project, operation, { |
| 702 | ignore: ["RESOURCE_NOT_FOUND"], |
| 703 | }), |
| 704 | ), |
| 705 | Effect.catchTag("NotFound", () => Effect.void), |
| 706 | Effect.retry({ |
| 707 | while: (error) => error._tag === "Conflict", |
| 708 | times: 8, |
| 709 | schedule: Schedule.spaced("2 seconds"), |
| 710 | }), |
| 711 | ); |
| 712 | yield* waitUntilGone(project, output.networkFirewallPolicyName); |
| 713 | }), |
| 714 | }); |