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 networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_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 { tagRecord } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { GcpEnvironment } from "../Environment.ts"; |
| 13 | import { |
| 14 | createInternalLabels, |
| 15 | hasAlchemyLabels, |
| 16 | stripInternalLabels, |
| 17 | toLabels, |
| 18 | } from "../Labels.ts"; |
| 19 | import type { Providers } from "../Providers.ts"; |
| 20 | import { waitForOperation } from "./internal.ts"; |
| 21 | |
| 22 | const DEFAULT_LOCATION = "global"; |
| 23 | const DEFAULT_PRIORITY = 1000; |
| 24 | const DEFAULT_IP_PROTOCOL = "ALL"; |
| 25 | const MAX_NAME_LENGTH = 63; |
| 26 | const COMPUTE_SELF_LINK_PREFIX = /^https?:\/\/[^/]+\/compute\/v1\//; |
| 27 | |
| 28 | export type PolicyBasedRouteProtocolVersion = |
| 29 | | networkconnectivity.FilterProtocolVersionEnum |
| 30 | | (string & {}); |
| 31 | |
| 32 | export type PolicyBasedRouteNextHopOtherRoutes = |
| 33 | | networkconnectivity.PolicyBasedRouteNextHopOtherRoutesEnum |
| 34 | | (string & {}); |
| 35 | |
| 36 | export type PolicyBasedRouteFilter = { |
| 37 | /** |
| 38 | * Internet protocol version this route matches (`IPV4` or `IPV6`). |
| 39 | */ |
| 40 | protocolVersion: PolicyBasedRouteProtocolVersion; |
| 41 | /** |
| 42 | * L4 protocol this route matches (`TCP`, `UDP`, or `ALL`). |
| 43 | * @default "ALL" |
| 44 | */ |
| 45 | ipProtocol?: string; |
| 46 | /** |
| 47 | * Source CIDR of matching packets. Defaults to `0.0.0.0/0` for IPv4 |
| 48 | * and `::/0` for IPv6. |
| 49 | */ |
| 50 | srcRange?: string; |
| 51 | /** |
| 52 | * Destination CIDR of matching packets. Defaults to `0.0.0.0/0` for |
| 53 | * IPv4 and `::/0` for IPv6. |
| 54 | */ |
| 55 | destRange?: string; |
| 56 | }; |
| 57 | |
| 58 | export type PolicyBasedRouteVirtualMachine = { |
| 59 | /** |
| 60 | * VM network tags this route installs on. A VM matching ANY tag |
| 61 | * receives the route. |
| 62 | */ |
| 63 | tags: string[]; |
| 64 | }; |
| 65 | |
| 66 | export type PolicyBasedRouteInterconnectAttachment = { |
| 67 | /** |
| 68 | * Region of interconnect attachments this route applies to. Use |
| 69 | * `"all"` to install it on every attachment. |
| 70 | */ |
| 71 | region: string; |
| 72 | }; |
| 73 | |
| 74 | export type PolicyBasedRouteWarning = { |
| 75 | /** Server warning code (`RESOURCE_NOT_ACTIVE`, …). */ |
| 76 | code: string | undefined; |
| 77 | /** Human-readable warning. */ |
| 78 | warningMessage: string | undefined; |
| 79 | }; |
| 80 | |
| 81 | export type PolicyBasedRouteProps = { |
| 82 | /** |
| 83 | * Policy-based route id (the `{policyBasedRoute}` segment of |
| 84 | * `projects/{project}/locations/global/policyBasedRoutes/{policyBasedRoute}`). |
| 85 | * If omitted, a unique RFC1035 name is generated from the stack, stage, |
| 86 | * and logical id. Must be 1-63 characters and match |
| 87 | * `[a-z]([a-z0-9-]*[a-z0-9])?`. Immutable — changing it replaces the |
| 88 | * route. |
| 89 | */ |
| 90 | policyBasedRouteId?: string; |
| 91 | /** |
| 92 | * VPC network this route applies to. Accepts a name (`default`), a |
| 93 | * resource path (`projects/{project}/global/networks/{network}`), or a |
| 94 | * Compute self-link. Immutable — changing it replaces the route. |
| 95 | */ |
| 96 | network: string; |
| 97 | /** |
| 98 | * L4 match filter. Immutable — changing it replaces the route. |
| 99 | */ |
| 100 | filter: PolicyBasedRouteFilter; |
| 101 | /** |
| 102 | * IP address of a global-access-enabled internal L4 load balancer used |
| 103 | * as the next hop. Exactly one of `nextHopIlbIp` or |
| 104 | * `nextHopOtherRoutes` must be set. Immutable — changing it replaces |
| 105 | * the route. |
| 106 | */ |
| 107 | nextHopIlbIp?: string; |
| 108 | /** |
| 109 | * Other routes consulted for the next hop. `DEFAULT_ROUTING` skips |
| 110 | * remaining policy-based routes and uses the VPC routing tables. |
| 111 | * Exactly one of `nextHopIlbIp` or `nextHopOtherRoutes` must be set. |
| 112 | * Immutable — changing it replaces the route. |
| 113 | */ |
| 114 | nextHopOtherRoutes?: PolicyBasedRouteNextHopOtherRoutes; |
| 115 | /** |
| 116 | * VM instances this route applies to, selected by network tags. Omit |
| 117 | * together with `interconnectAttachment` to install on every endpoint |
| 118 | * in the VPC. Immutable — changing it replaces the route. |
| 119 | */ |
| 120 | virtualMachine?: PolicyBasedRouteVirtualMachine; |
| 121 | /** |
| 122 | * Interconnect attachments this route applies to. Mutually exclusive |
| 123 | * with `virtualMachine`. Immutable — changing it replaces the route. |
| 124 | */ |
| 125 | interconnectAttachment?: PolicyBasedRouteInterconnectAttachment; |
| 126 | /** |
| 127 | * Priority used to break ties among matching policy-based routes. |
| 128 | * Lower wins. Range `1`–`65535`. |
| 129 | * @default 1000 |
| 130 | */ |
| 131 | priority?: number; |
| 132 | /** |
| 133 | * Human-readable description. Immutable — changing it replaces the |
| 134 | * route (the API has no update method). |
| 135 | */ |
| 136 | description?: string; |
| 137 | /** |
| 138 | * User labels. Alchemy ownership labels are merged in automatically. |
| 139 | * Immutable — changing them replaces the route (the API has no update |
| 140 | * method). |
| 141 | */ |
| 142 | labels?: Record<string, string>; |
| 143 | }; |
| 144 | |
| 145 | export type PolicyBasedRoute = Resource< |
| 146 | "GCP.NetworkConnectivity.PolicyBasedRoute", |
| 147 | PolicyBasedRouteProps, |
| 148 | { |
| 149 | /** |
| 150 | * Full resource name |
| 151 | * `projects/{project}/locations/global/policyBasedRoutes/{policyBasedRoute}`. |
| 152 | */ |
| 153 | name: string; |
| 154 | /** Policy-based route id (last path segment). */ |
| 155 | policyBasedRouteId: string; |
| 156 | /** Project id. */ |
| 157 | project: string; |
| 158 | /** Location id. Policy-based routes are global — always `"global"`. */ |
| 159 | location: string; |
| 160 | /** Fully-qualified VPC network path. */ |
| 161 | network: string; |
| 162 | /** L4 match filter as stored by the API. */ |
| 163 | filter: PolicyBasedRouteFilter; |
| 164 | /** Next-hop ILB IP, if set. */ |
| 165 | nextHopIlbIp: string | undefined; |
| 166 | /** Next-hop other-routes enum, if set. */ |
| 167 | nextHopOtherRoutes: string | undefined; |
| 168 | /** VM tag target, if set. */ |
| 169 | virtualMachine: PolicyBasedRouteVirtualMachine | undefined; |
| 170 | /** Interconnect attachment target, if set. */ |
| 171 | interconnectAttachment: PolicyBasedRouteInterconnectAttachment | undefined; |
| 172 | /** Route priority. */ |
| 173 | priority: number; |
| 174 | /** User-provided description. */ |
| 175 | description: string | undefined; |
| 176 | /** User labels (Alchemy ownership labels stripped). */ |
| 177 | labels: Record<string, string>; |
| 178 | /** Server-reported configuration warnings. */ |
| 179 | warnings: PolicyBasedRouteWarning[]; |
| 180 | /** Server-defined fully-qualified URL. */ |
| 181 | selfLink: string | undefined; |
| 182 | /** Resource kind (`networkconnectivity#policyBasedRoute`). */ |
| 183 | kind: string | undefined; |
| 184 | /** RFC3339 creation timestamp. */ |
| 185 | createTime: string | undefined; |
| 186 | /** RFC3339 last-update timestamp. */ |
| 187 | updateTime: string | undefined; |
| 188 | }, |
| 189 | never, |
| 190 | Providers |
| 191 | >; |
| 192 | |
| 193 | /** |
| 194 | * A VPC policy-based route. |
| 195 | * |
| 196 | * Policy-based routes match L4 traffic by source, destination, and |
| 197 | * protocol — not just destination IP — and always take precedence over |
| 198 | * other route types. They live at `locations/global`. The API has create, |
| 199 | * get, list, and delete only, so every user-facing field is immutable and |
| 200 | * changing it replaces the resource. |
| 201 | * |
| 202 | * ### Creating a Policy-Based Route |
| 203 | * **Example:** Skip other policy-based routes |
| 204 | * ```typescript |
| 205 | * const network = yield* GCP.Compute.Network("Vpc", { |
| 206 | * autoCreateSubnetworks: false, |
| 207 | * }); |
| 208 | * const route = yield* GCP.NetworkConnectivity.PolicyBasedRoute("Skip", { |
| 209 | * network: network.networkName, |
| 210 | * filter: { protocolVersion: "IPV4" }, |
| 211 | * nextHopOtherRoutes: "DEFAULT_ROUTING", |
| 212 | * }); |
| 213 | * ``` |
| 214 | * |
| 215 | * **Example:** Named route with VM tags and an ILB next hop |
| 216 | * ```typescript |
| 217 | * const route = yield* GCP.NetworkConnectivity.PolicyBasedRoute("Inspect", { |
| 218 | * policyBasedRouteId: "app-inspect", |
| 219 | * network: network.networkName, |
| 220 | * filter: { |
| 221 | * protocolVersion: "IPV4", |
| 222 | * ipProtocol: "TCP", |
| 223 | * srcRange: "10.0.0.0/8", |
| 224 | * destRange: "0.0.0.0/0", |
| 225 | * }, |
| 226 | * nextHopIlbIp: "10.10.10.20", |
| 227 | * virtualMachine: { tags: ["client"] }, |
| 228 | * priority: 500, |
| 229 | * description: "send tagged VMs to the inspection ILB", |
| 230 | * labels: { env: "prod" }, |
| 231 | * }); |
| 232 | * ``` |
| 233 | * |
| 234 | * ### Interconnect attachments |
| 235 | * **Example:** Apply to every VLAN attachment |
| 236 | * ```typescript |
| 237 | * const route = yield* GCP.NetworkConnectivity.PolicyBasedRoute("Vlan", { |
| 238 | * network: network.networkName, |
| 239 | * filter: { protocolVersion: "IPV4" }, |
| 240 | * nextHopOtherRoutes: "DEFAULT_ROUTING", |
| 241 | * interconnectAttachment: { region: "all" }, |
| 242 | * }); |
| 243 | * ``` |
| 244 | * |
| 245 | * @resource |
| 246 | * @category NetworkConnectivity |
| 247 | */ |
| 248 | export const PolicyBasedRoute = Resource<PolicyBasedRoute>( |
| 249 | "GCP.NetworkConnectivity.PolicyBasedRoute", |
| 250 | ); |
| 251 | |
| 252 | export class PolicyBasedRouteNotResolved extends Data.TaggedError( |
| 253 | "GCP.NetworkConnectivity.PolicyBasedRouteNotResolved", |
| 254 | )<{ |
| 255 | resourceName: string; |
| 256 | }> {} |
| 257 | |
| 258 | export class PolicyBasedRouteStillExists extends Data.TaggedError( |
| 259 | "GCP.NetworkConnectivity.PolicyBasedRouteStillExists", |
| 260 | )<{ |
| 261 | resourceName: string; |
| 262 | }> {} |
| 263 | |
| 264 | const lastSegment = (value: string) => { |
| 265 | const trimmed = value.replace(/\/+$/, ""); |
| 266 | const parts = trimmed.split("/"); |
| 267 | return parts[parts.length - 1] || trimmed; |
| 268 | }; |
| 269 | |
| 270 | const rfc1035 = (name: string): string => { |
| 271 | let next = name |
| 272 | .toLowerCase() |
| 273 | .replace(/[^a-z0-9-]/g, "-") |
| 274 | .replace(/-+/g, "-") |
| 275 | .replace(/^-+/, "") |
| 276 | .replace(/-+$/, ""); |
| 277 | if (!/^[a-z]/.test(next)) { |
| 278 | next = `p${next}`; |
| 279 | } |
| 280 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 281 | return next.length > 0 ? next : "policy-based-route"; |
| 282 | }; |
| 283 | |
| 284 | const resourceName = (project: string, policyBasedRouteId: string) => |
| 285 | `projects/${project}/locations/${DEFAULT_LOCATION}/policyBasedRoutes/${policyBasedRouteId}`; |
| 286 | |
| 287 | const parentOf = (project: string) => `projects/${project}/locations/${DEFAULT_LOCATION}`; |
| 288 | |
| 289 | const parseName = (name: string) => { |
| 290 | const parts = name.split("/").filter((part) => part.length > 0); |
| 291 | const routesAt = parts.lastIndexOf("policyBasedRoutes"); |
| 292 | const locationsAt = parts.lastIndexOf("locations"); |
| 293 | const projectsAt = parts.lastIndexOf("projects"); |
| 294 | return { |
| 295 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 296 | location: |
| 297 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 298 | policyBasedRouteId: |
| 299 | routesAt >= 0 && parts[routesAt + 1] ? parts[routesAt + 1]! : lastSegment(name), |
| 300 | }; |
| 301 | }; |
| 302 | |
| 303 | const toNetworkUrl = (project: string, network: string) => { |
| 304 | const stripped = network.replace(COMPUTE_SELF_LINK_PREFIX, "").replace(/^\/+/, ""); |
| 305 | const parts = stripped.split("/").filter((part) => part.length > 0); |
| 306 | const name = parts[parts.length - 1] ?? stripped; |
| 307 | const projectsAt = parts.lastIndexOf("projects"); |
| 308 | const owner = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project; |
| 309 | return `projects/${owner}/global/networks/${name}`; |
| 310 | }; |
| 311 | |
| 312 | const sameRef = (left: string | undefined, right: string | undefined) => |
| 313 | lastSegment(left ?? "").toLowerCase() === lastSegment(right ?? "").toLowerCase(); |
| 314 | |
| 315 | const protocolVersionOf = (filter: PolicyBasedRouteFilter | undefined) => |
| 316 | (filter?.protocolVersion ?? "IPV4").toUpperCase(); |
| 317 | |
| 318 | const defaultRangeOf = (filter: PolicyBasedRouteFilter | undefined) => |
| 319 | protocolVersionOf(filter) === "IPV6" ? "::/0" : "0.0.0.0/0"; |
| 320 | |
| 321 | const normalizeFilter = (filter: PolicyBasedRouteFilter | undefined) => { |
| 322 | const fallback = defaultRangeOf(filter); |
| 323 | return { |
| 324 | protocolVersion: protocolVersionOf(filter), |
| 325 | ipProtocol: (filter?.ipProtocol ?? DEFAULT_IP_PROTOCOL).toUpperCase(), |
| 326 | srcRange: filter?.srcRange ?? fallback, |
| 327 | destRange: filter?.destRange ?? fallback, |
| 328 | }; |
| 329 | }; |
| 330 | |
| 331 | const sameFilter = ( |
| 332 | left: PolicyBasedRouteFilter | undefined, |
| 333 | right: PolicyBasedRouteFilter | undefined, |
| 334 | ) => { |
| 335 | const a = normalizeFilter(left); |
| 336 | const b = normalizeFilter(right); |
| 337 | return ( |
| 338 | a.protocolVersion === b.protocolVersion && |
| 339 | a.ipProtocol === b.ipProtocol && |
| 340 | a.srcRange === b.srcRange && |
| 341 | a.destRange === b.destRange |
| 342 | ); |
| 343 | }; |
| 344 | |
| 345 | const tagsKey = (tags: readonly string[] | undefined) => |
| 346 | [...(tags ?? [])] |
| 347 | .map((tag) => tag.toLowerCase()) |
| 348 | .sort() |
| 349 | .join("\0"); |
| 350 | |
| 351 | const sameVirtualMachine = ( |
| 352 | left: PolicyBasedRouteVirtualMachine | undefined, |
| 353 | right: PolicyBasedRouteVirtualMachine | undefined, |
| 354 | ) => tagsKey(left?.tags) === tagsKey(right?.tags); |
| 355 | |
| 356 | const sameInterconnectAttachment = ( |
| 357 | left: PolicyBasedRouteInterconnectAttachment | undefined, |
| 358 | right: PolicyBasedRouteInterconnectAttachment | undefined, |
| 359 | ) => (left?.region ?? "").toLowerCase() === (right?.region ?? "").toLowerCase(); |
| 360 | |
| 361 | const labelsKey = (labels: Record<string, string> | undefined) => |
| 362 | Object.entries(toLabels(labels)) |
| 363 | .sort(([left], [right]) => left.localeCompare(right)) |
| 364 | .map(([key, value]) => `${key}=${value}`) |
| 365 | .join("\n"); |
| 366 | |
| 367 | const userLabels = ( |
| 368 | labels: Record<string, string | undefined> | null | undefined, |
| 369 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 370 | |
| 371 | const labelsCovered = ( |
| 372 | observed: Record<string, string | undefined> | null | undefined, |
| 373 | desired: Record<string, string>, |
| 374 | ) => { |
| 375 | const current = tagRecord(observed); |
| 376 | return Object.entries(desired).every(([key, value]) => current[key] === value); |
| 377 | }; |
| 378 | |
| 379 | const toId = (id: string, policyBasedRouteId: string | undefined, existing?: string) => |
| 380 | Effect.gen(function* () { |
| 381 | if (policyBasedRouteId !== undefined) return policyBasedRouteId; |
| 382 | if (existing !== undefined) return existing; |
| 383 | return rfc1035( |
| 384 | yield* createPhysicalName({ |
| 385 | id, |
| 386 | maxLength: MAX_NAME_LENGTH, |
| 387 | lowercase: true, |
| 388 | }), |
| 389 | ); |
| 390 | }); |
| 391 | |
| 392 | const toFilterAttr = (filter: networkconnectivity.Filter | undefined): PolicyBasedRouteFilter => ({ |
| 393 | protocolVersion: filter?.protocolVersion ?? "IPV4", |
| 394 | ipProtocol: filter?.ipProtocol, |
| 395 | srcRange: filter?.srcRange, |
| 396 | destRange: filter?.destRange, |
| 397 | }); |
| 398 | |
| 399 | const toVirtualMachine = ( |
| 400 | virtualMachine: networkconnectivity.VirtualMachine | undefined, |
| 401 | ): PolicyBasedRouteVirtualMachine | undefined => { |
| 402 | if (virtualMachine === undefined) return undefined; |
| 403 | return { tags: virtualMachine.tags ?? [] }; |
| 404 | }; |
| 405 | |
| 406 | const toInterconnectAttachment = ( |
| 407 | interconnectAttachment: networkconnectivity.InterconnectAttachment | undefined, |
| 408 | ): PolicyBasedRouteInterconnectAttachment | undefined => { |
| 409 | if (interconnectAttachment?.region === undefined) return undefined; |
| 410 | return { region: interconnectAttachment.region }; |
| 411 | }; |
| 412 | |
| 413 | const toWarnings = ( |
| 414 | warnings: networkconnectivity.WarningsList | undefined, |
| 415 | ): PolicyBasedRouteWarning[] => |
| 416 | (warnings ?? []).map((warning) => ({ |
| 417 | code: warning.code, |
| 418 | warningMessage: warning.warningMessage, |
| 419 | })); |
| 420 | |
| 421 | const toAttrs = (route: networkconnectivity.PolicyBasedRoute, project: string) => { |
| 422 | const name = route.name ?? ""; |
| 423 | const parsed = parseName(name); |
| 424 | return { |
| 425 | name, |
| 426 | policyBasedRouteId: parsed.policyBasedRouteId, |
| 427 | project: parsed.project || project, |
| 428 | location: parsed.location || DEFAULT_LOCATION, |
| 429 | network: route.network ?? "", |
| 430 | filter: toFilterAttr(route.filter), |
| 431 | nextHopIlbIp: route.nextHopIlbIp, |
| 432 | nextHopOtherRoutes: route.nextHopOtherRoutes, |
| 433 | virtualMachine: toVirtualMachine(route.virtualMachine), |
| 434 | interconnectAttachment: toInterconnectAttachment(route.interconnectAttachment), |
| 435 | priority: route.priority ?? DEFAULT_PRIORITY, |
| 436 | description: route.description, |
| 437 | labels: userLabels(route.labels), |
| 438 | warnings: toWarnings(route.warnings), |
| 439 | selfLink: route.selfLink, |
| 440 | kind: route.kind, |
| 441 | createTime: route.createTime, |
| 442 | updateTime: route.updateTime, |
| 443 | }; |
| 444 | }; |
| 445 | |
| 446 | const toBody = ( |
| 447 | project: string, |
| 448 | news: PolicyBasedRouteProps, |
| 449 | labels: Record<string, string>, |
| 450 | ): networkconnectivity.PolicyBasedRoute => { |
| 451 | const body: networkconnectivity.PolicyBasedRoute = { |
| 452 | network: toNetworkUrl(project, news.network), |
| 453 | filter: { |
| 454 | protocolVersion: news.filter.protocolVersion, |
| 455 | ipProtocol: news.filter.ipProtocol, |
| 456 | srcRange: news.filter.srcRange, |
| 457 | destRange: news.filter.destRange, |
| 458 | }, |
| 459 | priority: news.priority ?? DEFAULT_PRIORITY, |
| 460 | description: news.description, |
| 461 | labels, |
| 462 | }; |
| 463 | if (news.nextHopIlbIp !== undefined) { |
| 464 | body.nextHopIlbIp = news.nextHopIlbIp; |
| 465 | } |
| 466 | if (news.nextHopOtherRoutes !== undefined) { |
| 467 | body.nextHopOtherRoutes = news.nextHopOtherRoutes; |
| 468 | } |
| 469 | if (news.virtualMachine !== undefined) { |
| 470 | body.virtualMachine = { tags: news.virtualMachine.tags }; |
| 471 | } |
| 472 | if (news.interconnectAttachment !== undefined) { |
| 473 | body.interconnectAttachment = { |
| 474 | region: news.interconnectAttachment.region, |
| 475 | }; |
| 476 | } |
| 477 | return body; |
| 478 | }; |
| 479 | |
| 480 | const getByName = (name: string) => |
| 481 | networkconnectivity |
| 482 | .getProjectsLocationsGlobalPolicyBasedRoutes({ name }) |
| 483 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 484 | |
| 485 | const waitUntilExists = (name: string) => |
| 486 | getByName(name).pipe( |
| 487 | Effect.flatMap((route) => |
| 488 | route |
| 489 | ? Effect.succeed(route) |
| 490 | : Effect.fail(new PolicyBasedRouteNotResolved({ resourceName: name })), |
| 491 | ), |
| 492 | Effect.retry({ |
| 493 | while: (error) => error._tag === "GCP.NetworkConnectivity.PolicyBasedRouteNotResolved", |
| 494 | times: 8, |
| 495 | schedule: Schedule.spaced("1 second"), |
| 496 | }), |
| 497 | ); |
| 498 | |
| 499 | const waitUntilGone = (name: string) => |
| 500 | getByName(name).pipe( |
| 501 | Effect.flatMap((route) => |
| 502 | route === undefined |
| 503 | ? Effect.void |
| 504 | : Effect.fail(new PolicyBasedRouteStillExists({ resourceName: name })), |
| 505 | ), |
| 506 | Effect.retry({ |
| 507 | while: (error) => error._tag === "GCP.NetworkConnectivity.PolicyBasedRouteStillExists", |
| 508 | times: 10, |
| 509 | schedule: Schedule.spaced("1 second"), |
| 510 | }), |
| 511 | ); |
| 512 | |
| 513 | const removeRoute = (name: string) => |
| 514 | Effect.gen(function* () { |
| 515 | const operation = yield* networkconnectivity |
| 516 | .deleteProjectsLocationsGlobalPolicyBasedRoutes({ name }) |
| 517 | .pipe( |
| 518 | Effect.retry({ |
| 519 | while: (error) => error._tag === "Conflict", |
| 520 | times: 8, |
| 521 | schedule: Schedule.spaced("2 seconds"), |
| 522 | }), |
| 523 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 524 | ); |
| 525 | if (operation !== undefined) { |
| 526 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 527 | } |
| 528 | yield* waitUntilGone(name); |
| 529 | }); |
| 530 | |
| 531 | const listOwnedRoutes = (project: string) => |
| 532 | networkconnectivity.listProjectsLocationsGlobalPolicyBasedRoutes |
| 533 | .pages({ |
| 534 | parent: parentOf(project), |
| 535 | pageSize: 1000, |
| 536 | }) |
| 537 | .pipe( |
| 538 | Stream.flatMap((page) => Stream.fromIterable(page.policyBasedRoutes ?? [])), |
| 539 | Stream.filter((route) => |
| 540 | Object.keys(route.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 541 | ), |
| 542 | Stream.map((route) => toAttrs(route, project)), |
| 543 | Stream.runCollect, |
| 544 | Effect.map((chunk) => Array.from(chunk)), |
| 545 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 546 | ); |
| 547 | |
| 548 | const matchesDesired = ( |
| 549 | route: networkconnectivity.PolicyBasedRoute, |
| 550 | project: string, |
| 551 | news: PolicyBasedRouteProps, |
| 552 | desiredLabels: Record<string, string>, |
| 553 | ) => { |
| 554 | if (!sameRef(route.network, toNetworkUrl(project, news.network))) { |
| 555 | return false; |
| 556 | } |
| 557 | if (!sameFilter(toFilterAttr(route.filter), news.filter)) { |
| 558 | return false; |
| 559 | } |
| 560 | if ((route.nextHopIlbIp ?? "") !== (news.nextHopIlbIp ?? "")) { |
| 561 | return false; |
| 562 | } |
| 563 | if ((route.nextHopOtherRoutes ?? "") !== (news.nextHopOtherRoutes ?? "")) { |
| 564 | return false; |
| 565 | } |
| 566 | if (!sameVirtualMachine(toVirtualMachine(route.virtualMachine), news.virtualMachine)) { |
| 567 | return false; |
| 568 | } |
| 569 | if ( |
| 570 | !sameInterconnectAttachment( |
| 571 | toInterconnectAttachment(route.interconnectAttachment), |
| 572 | news.interconnectAttachment, |
| 573 | ) |
| 574 | ) { |
| 575 | return false; |
| 576 | } |
| 577 | if ((route.priority ?? DEFAULT_PRIORITY) !== (news.priority ?? DEFAULT_PRIORITY)) { |
| 578 | return false; |
| 579 | } |
| 580 | if ((route.description ?? "") !== (news.description ?? "")) { |
| 581 | return false; |
| 582 | } |
| 583 | return labelsCovered(route.labels, desiredLabels); |
| 584 | }; |
| 585 | |
| 586 | const immutableChanged = ( |
| 587 | news: PolicyBasedRouteProps, |
| 588 | olds: Partial<PolicyBasedRouteProps> | undefined, |
| 589 | output: PolicyBasedRoute["Attributes"] | undefined, |
| 590 | ) => { |
| 591 | const previousNetwork = olds?.network ?? output?.network; |
| 592 | if (previousNetwork !== undefined && !sameRef(news.network, previousNetwork)) { |
| 593 | return true; |
| 594 | } |
| 595 | const previousFilter = olds?.filter ?? output?.filter; |
| 596 | if (previousFilter !== undefined && !sameFilter(news.filter, previousFilter)) { |
| 597 | return true; |
| 598 | } |
| 599 | const previousIlb = olds?.nextHopIlbIp ?? output?.nextHopIlbIp ?? ""; |
| 600 | if ((news.nextHopIlbIp ?? "") !== previousIlb) { |
| 601 | return true; |
| 602 | } |
| 603 | const previousOther = olds?.nextHopOtherRoutes ?? output?.nextHopOtherRoutes ?? ""; |
| 604 | if ((news.nextHopOtherRoutes ?? "") !== previousOther) { |
| 605 | return true; |
| 606 | } |
| 607 | if (!sameVirtualMachine(news.virtualMachine, olds?.virtualMachine ?? output?.virtualMachine)) { |
| 608 | return true; |
| 609 | } |
| 610 | if ( |
| 611 | !sameInterconnectAttachment( |
| 612 | news.interconnectAttachment, |
| 613 | olds?.interconnectAttachment ?? output?.interconnectAttachment, |
| 614 | ) |
| 615 | ) { |
| 616 | return true; |
| 617 | } |
| 618 | const previousPriority = olds?.priority ?? output?.priority ?? DEFAULT_PRIORITY; |
| 619 | if ((news.priority ?? DEFAULT_PRIORITY) !== previousPriority) { |
| 620 | return true; |
| 621 | } |
| 622 | const previousDescription = olds?.description ?? output?.description ?? ""; |
| 623 | if ((news.description ?? "") !== previousDescription) { |
| 624 | return true; |
| 625 | } |
| 626 | if (labelsKey(news.labels) !== labelsKey(olds?.labels ?? output?.labels)) { |
| 627 | return true; |
| 628 | } |
| 629 | return false; |
| 630 | }; |
| 631 | |
| 632 | export const PolicyBasedRouteProvider = () => |
| 633 | Provider.succeed(PolicyBasedRoute, { |
| 634 | stables: ["name", "policyBasedRouteId", "project", "location", "createTime", "selfLink"], |
| 635 | |
| 636 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 637 | if (!isResolved(news)) return undefined; |
| 638 | const previousId = olds?.policyBasedRouteId ?? output?.policyBasedRouteId; |
| 639 | const nextId = news.policyBasedRouteId ?? previousId; |
| 640 | if (previousId === undefined && output === undefined) { |
| 641 | return undefined; |
| 642 | } |
| 643 | const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId; |
| 644 | if (idChanged || immutableChanged(news, olds, output)) { |
| 645 | return { |
| 646 | action: "replace" as const, |
| 647 | deleteFirst: nextId !== undefined && nextId === previousId, |
| 648 | }; |
| 649 | } |
| 650 | return undefined; |
| 651 | }), |
| 652 | |
| 653 | read: Effect.fn(function* ({ id, olds, output }) { |
| 654 | const env = yield* GcpEnvironment.current; |
| 655 | const policyBasedRouteId = yield* toId( |
| 656 | id, |
| 657 | olds?.policyBasedRouteId, |
| 658 | output?.policyBasedRouteId, |
| 659 | ); |
| 660 | const name = output?.name ?? resourceName(env.project, policyBasedRouteId); |
| 661 | const existing = yield* getByName(name); |
| 662 | if (existing === undefined) return undefined; |
| 663 | const attrs = toAttrs(existing, env.project); |
| 664 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 665 | }), |
| 666 | |
| 667 | list: () => |
| 668 | Effect.gen(function* () { |
| 669 | const env = yield* GcpEnvironment.current; |
| 670 | return yield* listOwnedRoutes(env.project); |
| 671 | }), |
| 672 | |
| 673 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 674 | const env = yield* GcpEnvironment.current; |
| 675 | const policyBasedRouteId = yield* toId( |
| 676 | id, |
| 677 | news.policyBasedRouteId, |
| 678 | output?.policyBasedRouteId, |
| 679 | ); |
| 680 | const name = output?.name ?? resourceName(env.project, policyBasedRouteId); |
| 681 | const desiredLabels = { |
| 682 | ...toLabels(news.labels), |
| 683 | ...(yield* createInternalLabels(id)), |
| 684 | }; |
| 685 | |
| 686 | let current = yield* getByName(name); |
| 687 | |
| 688 | if (current !== undefined && !matchesDesired(current, env.project, news, desiredLabels)) { |
| 689 | yield* removeRoute(current.name ?? name); |
| 690 | current = undefined; |
| 691 | } |
| 692 | |
| 693 | if (current === undefined) { |
| 694 | const created = yield* networkconnectivity |
| 695 | .createProjectsLocationsGlobalPolicyBasedRoutes({ |
| 696 | parent: parentOf(env.project), |
| 697 | policyBasedRouteId, |
| 698 | body: toBody(env.project, news, desiredLabels), |
| 699 | }) |
| 700 | .pipe( |
| 701 | Effect.retry({ |
| 702 | while: (error) => error._tag === "Conflict", |
| 703 | times: 5, |
| 704 | schedule: Schedule.spaced("2 seconds"), |
| 705 | }), |
| 706 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 707 | ); |
| 708 | if (created !== undefined) { |
| 709 | yield* waitForOperation(created); |
| 710 | } |
| 711 | current = yield* waitUntilExists(name); |
| 712 | } |
| 713 | |
| 714 | if (current === undefined) { |
| 715 | return yield* new PolicyBasedRouteNotResolved({ resourceName: name }); |
| 716 | } |
| 717 | |
| 718 | return toAttrs(current, env.project); |
| 719 | }), |
| 720 | |
| 721 | delete: Effect.fn(function* ({ output }) { |
| 722 | if (!output.name) return; |
| 723 | yield* removeRoute(output.name); |
| 724 | }), |
| 725 | }); |