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 { 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 { waitRegionOperation } from "./operations.ts"; |
| 21 | |
| 22 | const DEFAULT_PROTOCOL = "HTTP"; |
| 23 | const DEFAULT_SCHEME = "INTERNAL_MANAGED"; |
| 24 | const DEFAULT_TIMEOUT_SEC = 30; |
| 25 | const MAX_NAME_LENGTH = 63; |
| 26 | |
| 27 | export type RegionBackendServiceBackend = { |
| 28 | /** Fully-qualified instance group or NEG URL. */ |
| 29 | group: string; |
| 30 | /** Optional backend description. */ |
| 31 | description?: string; |
| 32 | /** Balancing mode (`UTILIZATION`, `RATE`, `CONNECTION`, …). */ |
| 33 | balancingMode?: string; |
| 34 | /** Capacity scaler in `[0.0, 1.0]`. */ |
| 35 | capacityScaler?: number; |
| 36 | /** Max requests per second (RATE mode). */ |
| 37 | maxRate?: number; |
| 38 | /** Max RPS per instance. */ |
| 39 | maxRatePerInstance?: number; |
| 40 | /** Target utilization in `[0.0, 1.0]`. */ |
| 41 | maxUtilization?: number; |
| 42 | /** Whether this backend is a failover group. */ |
| 43 | failover?: boolean; |
| 44 | }; |
| 45 | |
| 46 | export type RegionBackendServiceLogConfigProps = { |
| 47 | /** |
| 48 | * Export load-balancer logs to Cloud Logging. |
| 49 | * @default false |
| 50 | */ |
| 51 | enable?: boolean; |
| 52 | /** |
| 53 | * Sampling rate in `[0, 1]` when logging is enabled. |
| 54 | * @default 1.0 |
| 55 | */ |
| 56 | sampleRate?: number; |
| 57 | }; |
| 58 | |
| 59 | export type RegionBackendServiceProps = { |
| 60 | /** |
| 61 | * Name of the backend service. If omitted, a unique RFC1035 name is |
| 62 | * generated from the stack, stage, and logical id. Must be 1-63 |
| 63 | * characters and match `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — |
| 64 | * changing it replaces the resource. |
| 65 | */ |
| 66 | name?: string; |
| 67 | /** |
| 68 | * Region the backend service lives in (e.g. `us-central1`). Immutable — |
| 69 | * changing it replaces the resource. `US-CENTRAL1` is accepted and |
| 70 | * normalized to `us-central1`. |
| 71 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 72 | */ |
| 73 | region?: string; |
| 74 | /** |
| 75 | * User-facing description. Alchemy ownership is stamped into the stored |
| 76 | * description (`[alchemy alchemy-stack=… alchemy-stage=… alchemy-id=…]`); |
| 77 | * regional backend services have no labels API. |
| 78 | */ |
| 79 | description?: string; |
| 80 | /** |
| 81 | * Protocol used to talk to backends (`HTTP`, `HTTPS`, `HTTP2`, `TCP`, |
| 82 | * `SSL`, `UDP`, `GRPC`, `H2C`). |
| 83 | * @default "HTTP" |
| 84 | */ |
| 85 | protocol?: string; |
| 86 | /** |
| 87 | * Load balancer type. Immutable — changing it replaces the resource. |
| 88 | * @default "INTERNAL_MANAGED" |
| 89 | */ |
| 90 | loadBalancingScheme?: string; |
| 91 | /** |
| 92 | * Backend timeout in seconds. |
| 93 | * @default 30 |
| 94 | */ |
| 95 | timeoutSec?: number; |
| 96 | /** |
| 97 | * Named port on instance-group backends. Ignored for NEGs and for |
| 98 | * passthrough Network Load Balancers. |
| 99 | */ |
| 100 | portName?: string; |
| 101 | /** |
| 102 | * Enable Cloud CDN. Only valid for some Application Load Balancer |
| 103 | * schemes; ignored or rejected otherwise. |
| 104 | * @default false |
| 105 | */ |
| 106 | enableCDN?: boolean; |
| 107 | /** |
| 108 | * Session affinity (`NONE`, `CLIENT_IP`, `GENERATED_COOKIE`, …). |
| 109 | * @default "NONE" |
| 110 | */ |
| 111 | sessionAffinity?: string; |
| 112 | /** |
| 113 | * Cookie lifetime in seconds for `GENERATED_COOKIE` / `HTTP_COOKIE` |
| 114 | * affinity. `0` is a session cookie. |
| 115 | */ |
| 116 | affinityCookieTtlSec?: number; |
| 117 | /** |
| 118 | * Fully-qualified health-check URLs. At most one is typically allowed. |
| 119 | * Required for instance-group / zonal NEG backends; forbidden for |
| 120 | * internet and serverless NEGs. |
| 121 | */ |
| 122 | healthChecks?: string[]; |
| 123 | /** |
| 124 | * Backends (instance groups or NEGs) that serve this service. |
| 125 | */ |
| 126 | backends?: RegionBackendServiceBackend[]; |
| 127 | /** |
| 128 | * Connection-draining timeout in seconds. GCP defaults this to `300` |
| 129 | * when omitted. |
| 130 | */ |
| 131 | connectionDrainingTimeoutSec?: number; |
| 132 | /** |
| 133 | * Compress text responses (`AUTOMATIC` or `DISABLED`). |
| 134 | */ |
| 135 | compressionMode?: string; |
| 136 | /** |
| 137 | * Headers the load balancer adds to proxied requests. |
| 138 | */ |
| 139 | customRequestHeaders?: string[]; |
| 140 | /** |
| 141 | * Headers the load balancer adds to proxied responses. |
| 142 | */ |
| 143 | customResponseHeaders?: string[]; |
| 144 | /** |
| 145 | * Cloud Logging options for traffic served by this backend service. |
| 146 | */ |
| 147 | logConfig?: RegionBackendServiceLogConfigProps; |
| 148 | /** |
| 149 | * Intra-locality load-balancing algorithm (`ROUND_ROBIN`, `MAGLEV`, |
| 150 | * `RING_HASH`, …). Applicable to `INTERNAL_MANAGED` HTTP(S) services. |
| 151 | */ |
| 152 | localityLbPolicy?: string; |
| 153 | /** |
| 154 | * VPC network URL or name. Only valid for passthrough Network Load |
| 155 | * Balancers (`INTERNAL` / some `EXTERNAL` HA setups). Immutable — |
| 156 | * changing it replaces the resource. |
| 157 | */ |
| 158 | network?: string; |
| 159 | /** |
| 160 | * User labels. Encoded into the description marker alongside Alchemy |
| 161 | * ownership labels (the API has no `labels` field). |
| 162 | */ |
| 163 | labels?: Record<string, string>; |
| 164 | }; |
| 165 | |
| 166 | export type RegionBackendService = Resource< |
| 167 | "GCP.Compute.RegionBackendService", |
| 168 | RegionBackendServiceProps, |
| 169 | { |
| 170 | /** RFC1035 resource name. */ |
| 171 | name: string; |
| 172 | /** Project id. */ |
| 173 | project: string; |
| 174 | /** Region short name (`us-central1`). */ |
| 175 | region: string; |
| 176 | /** Server-assigned numeric id. */ |
| 177 | backendServiceId: string | undefined; |
| 178 | /** Compute self-link. */ |
| 179 | selfLink: string | undefined; |
| 180 | /** RFC3339 creation timestamp. */ |
| 181 | creationTimestamp: string | undefined; |
| 182 | /** Optimistic-locking fingerprint. */ |
| 183 | fingerprint: string | undefined; |
| 184 | /** User-facing description (ownership marker stripped). */ |
| 185 | description: string | undefined; |
| 186 | /** Protocol used to talk to backends. */ |
| 187 | protocol: string | undefined; |
| 188 | /** Load balancer type. */ |
| 189 | loadBalancingScheme: string | undefined; |
| 190 | /** Backend timeout in seconds. */ |
| 191 | timeoutSec: number | undefined; |
| 192 | /** Named port on instance-group backends. */ |
| 193 | portName: string | undefined; |
| 194 | /** Whether Cloud CDN is enabled. */ |
| 195 | enableCDN: boolean; |
| 196 | /** Session affinity mode. */ |
| 197 | sessionAffinity: string | undefined; |
| 198 | /** Cookie TTL in seconds, if set. */ |
| 199 | affinityCookieTtlSec: number | undefined; |
| 200 | /** Fully-qualified health-check URLs. */ |
| 201 | healthChecks: string[]; |
| 202 | /** Attached backends. */ |
| 203 | backends: RegionBackendServiceBackend[]; |
| 204 | /** Connection-draining timeout in seconds. */ |
| 205 | connectionDrainingTimeoutSec: number | undefined; |
| 206 | /** Response compression mode. */ |
| 207 | compressionMode: string | undefined; |
| 208 | /** Custom request headers. */ |
| 209 | customRequestHeaders: string[]; |
| 210 | /** Custom response headers. */ |
| 211 | customResponseHeaders: string[]; |
| 212 | /** Logging configuration. */ |
| 213 | logConfig: RegionBackendServiceLogConfigProps | undefined; |
| 214 | /** Intra-locality load-balancing algorithm. */ |
| 215 | localityLbPolicy: string | undefined; |
| 216 | /** Network URL, if set. */ |
| 217 | network: string | undefined; |
| 218 | /** User labels (Alchemy ownership labels stripped). */ |
| 219 | labels: Record<string, string>; |
| 220 | /** Resource kind (`compute#backendService`). */ |
| 221 | kind: string | undefined; |
| 222 | }, |
| 223 | never, |
| 224 | Providers |
| 225 | >; |
| 226 | |
| 227 | /** |
| 228 | * A regional Compute Engine backend service. Backend services define how |
| 229 | * Google Cloud load balancers distribute traffic — protocol, timeout, |
| 230 | * session affinity, health checks, and the backends themselves. |
| 231 | * |
| 232 | * Compute Engine backend services have no labels field, so Alchemy stamps |
| 233 | * ownership into the description (`[alchemy alchemy-stack=… alchemy-stage=… |
| 234 | * alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find them. Changing |
| 235 | * `name`, `region`, `loadBalancingScheme`, or `network` replaces the |
| 236 | * resource. |
| 237 | * |
| 238 | * ### Creating a Region Backend Service |
| 239 | * **Example:** Generated name |
| 240 | * ```typescript |
| 241 | * const backend = yield* GCP.Compute.RegionBackendService("web", { |
| 242 | * protocol: "HTTP", |
| 243 | * loadBalancingScheme: "INTERNAL_MANAGED", |
| 244 | * }); |
| 245 | * ``` |
| 246 | * |
| 247 | * **Example:** Explicit name, timeout, and labels |
| 248 | * ```typescript |
| 249 | * const backend = yield* GCP.Compute.RegionBackendService("web", { |
| 250 | * name: "web-backend", |
| 251 | * region: "us-central1", |
| 252 | * protocol: "HTTP", |
| 253 | * loadBalancingScheme: "INTERNAL_MANAGED", |
| 254 | * timeoutSec: 30, |
| 255 | * localityLbPolicy: "ROUND_ROBIN", |
| 256 | * labels: { env: "prod" }, |
| 257 | * }); |
| 258 | * ``` |
| 259 | * |
| 260 | * ### Updating a Region Backend Service |
| 261 | * **Example:** Raise the timeout |
| 262 | * ```typescript |
| 263 | * const backend = yield* GCP.Compute.RegionBackendService("web", { |
| 264 | * name: "web-backend", |
| 265 | * timeoutSec: 60, |
| 266 | * }); |
| 267 | * ``` |
| 268 | * |
| 269 | * @resource |
| 270 | * @category Compute |
| 271 | */ |
| 272 | export const RegionBackendService = Resource<RegionBackendService>( |
| 273 | "GCP.Compute.RegionBackendService", |
| 274 | ); |
| 275 | |
| 276 | export class RegionBackendServiceNotResolved extends Data.TaggedError( |
| 277 | "GCP.Compute.RegionBackendServiceNotResolved", |
| 278 | )<{ |
| 279 | resourceName: string; |
| 280 | region: string; |
| 281 | }> {} |
| 282 | |
| 283 | export class RegionBackendServiceStillExists extends Data.TaggedError( |
| 284 | "GCP.Compute.RegionBackendServiceStillExists", |
| 285 | )<{ |
| 286 | resourceName: string; |
| 287 | region: string; |
| 288 | }> {} |
| 289 | |
| 290 | const lastSegment = (value: string | undefined): string => { |
| 291 | if (value === undefined || value.length === 0) return ""; |
| 292 | const parts = value.split("/").filter((part) => part.length > 0); |
| 293 | return parts[parts.length - 1] ?? value; |
| 294 | }; |
| 295 | |
| 296 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 297 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 298 | |
| 299 | const rfc1035 = (name: string): string => { |
| 300 | let next = name |
| 301 | .toLowerCase() |
| 302 | .replace(/[^a-z0-9-]/g, "-") |
| 303 | .replace(/-+/g, "-") |
| 304 | .replace(/^-+/, "") |
| 305 | .replace(/-+$/, ""); |
| 306 | if (!/^[a-z]/.test(next)) { |
| 307 | next = `b${next}`; |
| 308 | } |
| 309 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 310 | return next.length > 0 ? next : "backend"; |
| 311 | }; |
| 312 | |
| 313 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 314 | Effect.gen(function* () { |
| 315 | if (name !== undefined) return name; |
| 316 | if (existing !== undefined) return existing; |
| 317 | return rfc1035( |
| 318 | yield* createPhysicalName({ |
| 319 | id, |
| 320 | maxLength: MAX_NAME_LENGTH, |
| 321 | lowercase: true, |
| 322 | }), |
| 323 | ); |
| 324 | }); |
| 325 | |
| 326 | const toNetworkUrl = (project: string, network: string) => |
| 327 | network.includes("/") ? network : `projects/${project}/global/networks/${network}`; |
| 328 | |
| 329 | const encodeDescription = (user: string | undefined, labels: Record<string, string>): string => { |
| 330 | const packed = Object.entries(labels) |
| 331 | .sort(([a], [b]) => a.localeCompare(b)) |
| 332 | .map(([key, value]) => `${key}=${value}`) |
| 333 | .join(" "); |
| 334 | const marker = `[alchemy ${packed}]`; |
| 335 | return user ? `${marker}\n${user}` : marker; |
| 336 | }; |
| 337 | |
| 338 | const parseDescription = ( |
| 339 | description: string | undefined, |
| 340 | ): { labels: Record<string, string>; user: string | undefined } => { |
| 341 | if (!description?.startsWith("[alchemy ")) { |
| 342 | return { labels: {}, user: description }; |
| 343 | } |
| 344 | const end = description.indexOf("]"); |
| 345 | if (end < 0) return { labels: {}, user: description }; |
| 346 | const labels: Record<string, string> = {}; |
| 347 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 348 | const eq = part.indexOf("="); |
| 349 | if (eq > 0) { |
| 350 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 351 | } |
| 352 | } |
| 353 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 354 | return { labels, user: rest.length > 0 ? rest : undefined }; |
| 355 | }; |
| 356 | |
| 357 | const hasOwnershipMarker = (description: string | undefined): boolean => |
| 358 | (description ?? "").startsWith("[alchemy "); |
| 359 | |
| 360 | const userLabels = ( |
| 361 | labels: Record<string, string | undefined> | null | undefined, |
| 362 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 363 | |
| 364 | const toBackend = (backend: compute.Backend): RegionBackendServiceBackend => ({ |
| 365 | group: backend.group ?? "", |
| 366 | description: backend.description, |
| 367 | balancingMode: backend.balancingMode, |
| 368 | capacityScaler: backend.capacityScaler, |
| 369 | maxRate: backend.maxRate, |
| 370 | maxRatePerInstance: backend.maxRatePerInstance, |
| 371 | maxUtilization: backend.maxUtilization, |
| 372 | failover: backend.failover, |
| 373 | }); |
| 374 | |
| 375 | const toLogConfig = ( |
| 376 | logConfig: compute.BackendServiceLogConfig | undefined, |
| 377 | ): RegionBackendServiceLogConfigProps | undefined => { |
| 378 | if (logConfig === undefined) return undefined; |
| 379 | return { |
| 380 | enable: logConfig.enable, |
| 381 | sampleRate: logConfig.sampleRate, |
| 382 | }; |
| 383 | }; |
| 384 | |
| 385 | const toAttrs = (service: compute.BackendService, project: string) => { |
| 386 | const decoded = parseDescription(service.description); |
| 387 | return { |
| 388 | name: service.name ?? "", |
| 389 | project, |
| 390 | region: lastSegment(service.region).toLowerCase(), |
| 391 | backendServiceId: service.id, |
| 392 | selfLink: service.selfLink, |
| 393 | creationTimestamp: service.creationTimestamp, |
| 394 | fingerprint: service.fingerprint, |
| 395 | description: decoded.user, |
| 396 | protocol: service.protocol, |
| 397 | loadBalancingScheme: service.loadBalancingScheme, |
| 398 | timeoutSec: service.timeoutSec, |
| 399 | portName: service.portName, |
| 400 | enableCDN: service.enableCDN === true, |
| 401 | sessionAffinity: service.sessionAffinity, |
| 402 | affinityCookieTtlSec: service.affinityCookieTtlSec, |
| 403 | healthChecks: [...(service.healthChecks ?? [])], |
| 404 | backends: (service.backends ?? []).map(toBackend), |
| 405 | connectionDrainingTimeoutSec: service.connectionDraining?.drainingTimeoutSec, |
| 406 | compressionMode: service.compressionMode, |
| 407 | customRequestHeaders: [...(service.customRequestHeaders ?? [])], |
| 408 | customResponseHeaders: [...(service.customResponseHeaders ?? [])], |
| 409 | logConfig: toLogConfig(service.logConfig), |
| 410 | localityLbPolicy: service.localityLbPolicy, |
| 411 | network: service.network, |
| 412 | labels: userLabels(decoded.labels), |
| 413 | kind: service.kind, |
| 414 | }; |
| 415 | }; |
| 416 | |
| 417 | const sameStringList = ( |
| 418 | left: readonly string[] | undefined, |
| 419 | right: readonly string[] | undefined, |
| 420 | ) => JSON.stringify([...(left ?? [])].sort()) === JSON.stringify([...(right ?? [])].sort()); |
| 421 | |
| 422 | const backendKey = (backend: RegionBackendServiceBackend) => |
| 423 | JSON.stringify({ |
| 424 | group: backend.group, |
| 425 | description: backend.description ?? "", |
| 426 | balancingMode: backend.balancingMode ?? "", |
| 427 | capacityScaler: backend.capacityScaler ?? null, |
| 428 | maxRate: backend.maxRate ?? null, |
| 429 | maxRatePerInstance: backend.maxRatePerInstance ?? null, |
| 430 | maxUtilization: backend.maxUtilization ?? null, |
| 431 | failover: backend.failover ?? false, |
| 432 | }); |
| 433 | |
| 434 | const sameBackends = ( |
| 435 | left: readonly RegionBackendServiceBackend[] | undefined, |
| 436 | right: readonly RegionBackendServiceBackend[] | undefined, |
| 437 | ) => |
| 438 | JSON.stringify([...(left ?? [])].map(backendKey).sort()) === |
| 439 | JSON.stringify([...(right ?? [])].map(backendKey).sort()); |
| 440 | |
| 441 | const sameLogConfig = ( |
| 442 | left: RegionBackendServiceLogConfigProps | undefined, |
| 443 | right: compute.BackendServiceLogConfig | undefined, |
| 444 | ) => |
| 445 | (left?.enable ?? false) === (right?.enable ?? false) && |
| 446 | (left?.sampleRate === undefined || left.sampleRate === right?.sampleRate); |
| 447 | |
| 448 | const getByName = (project: string, region: string, name: string) => |
| 449 | compute |
| 450 | .getRegionBackendServices({ project, region, backendService: name }) |
| 451 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 452 | |
| 453 | const waitPresent = (project: string, region: string, name: string) => |
| 454 | getByName(project, region, name).pipe( |
| 455 | Effect.flatMap((service) => |
| 456 | service === undefined |
| 457 | ? Effect.fail(new RegionBackendServiceNotResolved({ resourceName: name, region })) |
| 458 | : Effect.succeed(service), |
| 459 | ), |
| 460 | Effect.retry({ |
| 461 | while: (error) => error._tag === "GCP.Compute.RegionBackendServiceNotResolved", |
| 462 | times: 8, |
| 463 | schedule: Schedule.exponential("250 millis"), |
| 464 | }), |
| 465 | Effect.catchTag("GCP.Compute.RegionBackendServiceNotResolved", () => Effect.undefined), |
| 466 | ); |
| 467 | |
| 468 | const waitGone = (project: string, region: string, name: string) => |
| 469 | getByName(project, region, name).pipe( |
| 470 | Effect.flatMap((service) => |
| 471 | service === undefined |
| 472 | ? Effect.void |
| 473 | : Effect.fail(new RegionBackendServiceStillExists({ resourceName: name, region })), |
| 474 | ), |
| 475 | Effect.retry({ |
| 476 | while: (error) => error._tag === "GCP.Compute.RegionBackendServiceStillExists", |
| 477 | times: 8, |
| 478 | schedule: Schedule.spaced("1 second"), |
| 479 | }), |
| 480 | ); |
| 481 | |
| 482 | export const RegionBackendServiceProvider = () => |
| 483 | Provider.succeed(RegionBackendService, { |
| 484 | stables: [ |
| 485 | "name", |
| 486 | "project", |
| 487 | "region", |
| 488 | "backendServiceId", |
| 489 | "selfLink", |
| 490 | "creationTimestamp", |
| 491 | "loadBalancingScheme", |
| 492 | ], |
| 493 | |
| 494 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 495 | if (!isResolved(news)) return undefined; |
| 496 | const env = yield* GcpEnvironment.current; |
| 497 | const previousName = olds?.name ?? output?.name; |
| 498 | const nextName = news.name ?? previousName; |
| 499 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 500 | const nextRegion = normalizeRegion(news.region ?? previousRegion, env.region); |
| 501 | const nameChanged = |
| 502 | news.name !== undefined && previousName !== undefined && news.name !== previousName; |
| 503 | const regionChanged = previousRegion !== nextRegion; |
| 504 | const previousScheme = |
| 505 | olds?.loadBalancingScheme ?? output?.loadBalancingScheme ?? DEFAULT_SCHEME; |
| 506 | const nextScheme = news.loadBalancingScheme ?? DEFAULT_SCHEME; |
| 507 | const schemeChanged = previousScheme !== nextScheme; |
| 508 | const previousNetwork = lastSegment(olds?.network ?? output?.network).toLowerCase(); |
| 509 | const nextNetwork = |
| 510 | news.network !== undefined ? lastSegment(news.network).toLowerCase() : previousNetwork; |
| 511 | const networkChanged = previousNetwork !== nextNetwork; |
| 512 | if (!nameChanged && !regionChanged && !schemeChanged && !networkChanged) { |
| 513 | return undefined; |
| 514 | } |
| 515 | const samePhysicalName = |
| 516 | previousName !== undefined && |
| 517 | (nextName === undefined || nextName === previousName) && |
| 518 | previousRegion === nextRegion; |
| 519 | return { |
| 520 | action: "replace" as const, |
| 521 | deleteFirst: samePhysicalName && (schemeChanged || networkChanged), |
| 522 | }; |
| 523 | }), |
| 524 | |
| 525 | read: Effect.fn(function* ({ id, olds, output }) { |
| 526 | const env = yield* GcpEnvironment.current; |
| 527 | const name = yield* toName(id, olds?.name, output?.name); |
| 528 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 529 | const existing = yield* getByName(env.project, region, name); |
| 530 | if (existing === undefined) return undefined; |
| 531 | const attrs = toAttrs(existing, env.project); |
| 532 | const parsed = parseDescription(existing.description); |
| 533 | return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs); |
| 534 | }), |
| 535 | |
| 536 | list: () => |
| 537 | Effect.gen(function* () { |
| 538 | const env = yield* GcpEnvironment.current; |
| 539 | const pages = yield* compute.aggregatedListBackendServices |
| 540 | .pages({ |
| 541 | project: env.project, |
| 542 | maxResults: 500, |
| 543 | returnPartialSuccess: true, |
| 544 | }) |
| 545 | .pipe(Stream.runCollect); |
| 546 | return Array.from(pages).flatMap((page) => |
| 547 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 548 | (scoped?.backendServices ?? []) |
| 549 | .filter( |
| 550 | (service) => |
| 551 | (service.region ?? "").length > 0 && hasOwnershipMarker(service.description), |
| 552 | ) |
| 553 | .map((service) => toAttrs(service, env.project)), |
| 554 | ), |
| 555 | ); |
| 556 | }), |
| 557 | |
| 558 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 559 | const env = yield* GcpEnvironment.current; |
| 560 | const name = yield* toName(id, news.name, output?.name); |
| 561 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 562 | const desiredLabels = { |
| 563 | ...toLabels(news.labels), |
| 564 | ...(yield* createInternalLabels(id)), |
| 565 | }; |
| 566 | const desiredDescription = encodeDescription(news.description, desiredLabels); |
| 567 | const protocol = news.protocol ?? DEFAULT_PROTOCOL; |
| 568 | const loadBalancingScheme = news.loadBalancingScheme ?? DEFAULT_SCHEME; |
| 569 | const timeoutSec = news.timeoutSec ?? DEFAULT_TIMEOUT_SEC; |
| 570 | const enableCDN = news.enableCDN === true; |
| 571 | const desiredBackends = (news.backends ?? []).map((backend) => ({ |
| 572 | group: backend.group, |
| 573 | description: backend.description, |
| 574 | balancingMode: backend.balancingMode, |
| 575 | capacityScaler: backend.capacityScaler, |
| 576 | maxRate: backend.maxRate, |
| 577 | maxRatePerInstance: backend.maxRatePerInstance, |
| 578 | maxUtilization: backend.maxUtilization, |
| 579 | failover: backend.failover, |
| 580 | })); |
| 581 | const network = |
| 582 | news.network !== undefined ? toNetworkUrl(env.project, news.network) : undefined; |
| 583 | |
| 584 | let current = yield* getByName(env.project, region, name); |
| 585 | |
| 586 | if (current === undefined) { |
| 587 | yield* compute |
| 588 | .insertRegionBackendServices({ |
| 589 | project: env.project, |
| 590 | region, |
| 591 | body: { |
| 592 | name, |
| 593 | description: desiredDescription, |
| 594 | protocol, |
| 595 | loadBalancingScheme, |
| 596 | timeoutSec, |
| 597 | portName: news.portName, |
| 598 | enableCDN, |
| 599 | sessionAffinity: news.sessionAffinity, |
| 600 | affinityCookieTtlSec: news.affinityCookieTtlSec, |
| 601 | healthChecks: (news.healthChecks?.length ?? 0) > 0 ? news.healthChecks : undefined, |
| 602 | backends: desiredBackends.length > 0 ? desiredBackends : undefined, |
| 603 | connectionDraining: |
| 604 | news.connectionDrainingTimeoutSec !== undefined |
| 605 | ? { |
| 606 | drainingTimeoutSec: news.connectionDrainingTimeoutSec, |
| 607 | } |
| 608 | : undefined, |
| 609 | compressionMode: news.compressionMode, |
| 610 | customRequestHeaders: |
| 611 | (news.customRequestHeaders?.length ?? 0) > 0 |
| 612 | ? news.customRequestHeaders |
| 613 | : undefined, |
| 614 | customResponseHeaders: |
| 615 | (news.customResponseHeaders?.length ?? 0) > 0 |
| 616 | ? news.customResponseHeaders |
| 617 | : undefined, |
| 618 | logConfig: news.logConfig, |
| 619 | localityLbPolicy: news.localityLbPolicy, |
| 620 | network, |
| 621 | }, |
| 622 | }) |
| 623 | .pipe( |
| 624 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 625 | Effect.flatMap((operation) => |
| 626 | operation === undefined |
| 627 | ? Effect.void |
| 628 | : waitRegionOperation(env.project, region, operation, { |
| 629 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 630 | }).pipe(Effect.asVoid), |
| 631 | ), |
| 632 | ); |
| 633 | current = yield* waitPresent(env.project, region, name); |
| 634 | } |
| 635 | |
| 636 | if (current === undefined) { |
| 637 | return yield* new RegionBackendServiceNotResolved({ resourceName: name, region }); |
| 638 | } |
| 639 | |
| 640 | const timeoutChanged = (current.timeoutSec ?? DEFAULT_TIMEOUT_SEC) !== timeoutSec; |
| 641 | const protocolChanged = (current.protocol ?? DEFAULT_PROTOCOL) !== protocol; |
| 642 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 643 | const enableCDNChanged = (current.enableCDN === true) !== enableCDN; |
| 644 | const sessionAffinityChanged = |
| 645 | (current.sessionAffinity ?? "NONE") !== (news.sessionAffinity ?? "NONE"); |
| 646 | const affinityCookieChanged = |
| 647 | news.affinityCookieTtlSec !== undefined && |
| 648 | current.affinityCookieTtlSec !== news.affinityCookieTtlSec; |
| 649 | const portNameChanged = news.portName !== undefined && current.portName !== news.portName; |
| 650 | const healthChecksChanged = !sameStringList(current.healthChecks, news.healthChecks); |
| 651 | const backendsChanged = !sameBackends((current.backends ?? []).map(toBackend), news.backends); |
| 652 | const drainingChanged = |
| 653 | news.connectionDrainingTimeoutSec !== undefined && |
| 654 | current.connectionDraining?.drainingTimeoutSec !== news.connectionDrainingTimeoutSec; |
| 655 | const compressionChanged = |
| 656 | news.compressionMode !== undefined && current.compressionMode !== news.compressionMode; |
| 657 | const requestHeadersChanged = |
| 658 | news.customRequestHeaders !== undefined && |
| 659 | !sameStringList(current.customRequestHeaders, news.customRequestHeaders); |
| 660 | const responseHeadersChanged = |
| 661 | news.customResponseHeaders !== undefined && |
| 662 | !sameStringList(current.customResponseHeaders, news.customResponseHeaders); |
| 663 | const logConfigChanged = |
| 664 | news.logConfig !== undefined && !sameLogConfig(news.logConfig, current.logConfig); |
| 665 | const localityChanged = |
| 666 | news.localityLbPolicy !== undefined && |
| 667 | (current.localityLbPolicy ?? "") !== news.localityLbPolicy; |
| 668 | |
| 669 | if ( |
| 670 | timeoutChanged || |
| 671 | protocolChanged || |
| 672 | descriptionChanged || |
| 673 | enableCDNChanged || |
| 674 | sessionAffinityChanged || |
| 675 | affinityCookieChanged || |
| 676 | portNameChanged || |
| 677 | healthChecksChanged || |
| 678 | backendsChanged || |
| 679 | drainingChanged || |
| 680 | compressionChanged || |
| 681 | requestHeadersChanged || |
| 682 | responseHeadersChanged || |
| 683 | logConfigChanged || |
| 684 | localityChanged |
| 685 | ) { |
| 686 | const patch: compute.BackendService = { |
| 687 | fingerprint: current.fingerprint, |
| 688 | }; |
| 689 | if (timeoutChanged) patch.timeoutSec = timeoutSec; |
| 690 | if (protocolChanged) patch.protocol = protocol; |
| 691 | if (descriptionChanged) patch.description = desiredDescription; |
| 692 | if (enableCDNChanged) patch.enableCDN = enableCDN; |
| 693 | if (sessionAffinityChanged) { |
| 694 | patch.sessionAffinity = news.sessionAffinity ?? "NONE"; |
| 695 | } |
| 696 | if (affinityCookieChanged) { |
| 697 | patch.affinityCookieTtlSec = news.affinityCookieTtlSec; |
| 698 | } |
| 699 | if (portNameChanged) patch.portName = news.portName; |
| 700 | if (healthChecksChanged) patch.healthChecks = news.healthChecks ?? []; |
| 701 | if (backendsChanged) patch.backends = desiredBackends; |
| 702 | if (drainingChanged) { |
| 703 | patch.connectionDraining = { |
| 704 | drainingTimeoutSec: news.connectionDrainingTimeoutSec, |
| 705 | }; |
| 706 | } |
| 707 | if (compressionChanged) patch.compressionMode = news.compressionMode; |
| 708 | if (requestHeadersChanged) { |
| 709 | patch.customRequestHeaders = news.customRequestHeaders; |
| 710 | } |
| 711 | if (responseHeadersChanged) { |
| 712 | patch.customResponseHeaders = news.customResponseHeaders; |
| 713 | } |
| 714 | if (logConfigChanged) patch.logConfig = news.logConfig; |
| 715 | if (localityChanged) patch.localityLbPolicy = news.localityLbPolicy; |
| 716 | |
| 717 | yield* compute |
| 718 | .patchRegionBackendServices({ |
| 719 | project: env.project, |
| 720 | region, |
| 721 | backendService: name, |
| 722 | body: patch, |
| 723 | }) |
| 724 | .pipe( |
| 725 | Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)), |
| 726 | Effect.retry({ |
| 727 | while: (error) => error._tag === "Conflict", |
| 728 | times: 5, |
| 729 | schedule: Schedule.exponential("250 millis"), |
| 730 | }), |
| 731 | ); |
| 732 | current = (yield* getByName(env.project, region, name)) ?? current; |
| 733 | } |
| 734 | |
| 735 | return toAttrs(current, env.project); |
| 736 | }), |
| 737 | |
| 738 | delete: Effect.fn(function* ({ output }) { |
| 739 | yield* compute |
| 740 | .deleteRegionBackendServices({ |
| 741 | project: output.project, |
| 742 | region: output.region, |
| 743 | backendService: output.name, |
| 744 | }) |
| 745 | .pipe( |
| 746 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 747 | Effect.flatMap((operation) => |
| 748 | operation === undefined |
| 749 | ? Effect.void |
| 750 | : waitRegionOperation(output.project, output.region, operation, { |
| 751 | ignore: ["RESOURCE_NOT_FOUND"], |
| 752 | }).pipe(Effect.asVoid), |
| 753 | ), |
| 754 | Effect.catchTag("NotFound", () => Effect.void), |
| 755 | Effect.retry({ |
| 756 | while: (error) => error._tag === "Conflict", |
| 757 | times: 5, |
| 758 | schedule: Schedule.spaced("1 second"), |
| 759 | }), |
| 760 | // Compute rejects the delete while another operation is still in |
| 761 | // flight on the backend (e.g. packet-mirroring teardown of the |
| 762 | // forwarding rule that fronted it). |
| 763 | Effect.retry({ |
| 764 | while: (error) => error._tag === "ResourceNotReady", |
| 765 | times: 20, |
| 766 | schedule: Schedule.spaced("10 seconds"), |
| 767 | }), |
| 768 | ); |
| 769 | yield* waitGone(output.project, output.region, output.name); |
| 770 | }), |
| 771 | }); |