@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 707 lines 25.4 KB
Raw
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 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import {
22 encodeDescription,
23 hasOwnershipMarker,
24 lastSegment,
25 parseDescription,
26 } from "./internal.ts";
27 import { waitGlobalOperation } from "./operations.ts";
28
29 const DEFAULT_PROTOCOL = "TCP";
30 const DEFAULT_SCHEME = "EXTERNAL";
31 const DEFAULT_TIER = "PREMIUM";
32 const MAX_NAME_LENGTH = 63;
33
34 export type GlobalForwardingRuleProps = {
35 /**
36 * Name of the forwarding rule. If omitted, a unique RFC1035 name is
37 * generated from the stack, stage, and logical id. Immutable —
38 * changing it replaces the rule.
39 */
40 forwardingRuleName?: string;
41 /**
42 * Optional description. Immutable — changing it replaces the rule.
43 * Alchemy stamps ownership into the stored description so `list` /
44 * nuke can find a rule even if `setLabels` never ran (labels cannot
45 * be set on insert).
46 */
47 description?: string;
48 /**
49 * URL of the target that receives matched traffic (a global target
50 * HTTP/HTTPS/SSL/TCP/gRPC proxy self-link, a PSC service attachment,
51 * or `all-apis` / `vpc-sc`).
52 */
53 target: string;
54 /**
55 * IP this rule accepts traffic on. A reserved global address
56 * (self-link, `global/addresses/name`, or the IP itself). If omitted,
57 * GCP assigns an ephemeral address. Immutable.
58 */
59 ipAddress?: string;
60 /**
61 * IP protocol (`TCP`, `UDP`, `ESP`, `AH`, `SCTP`, `ICMP`,
62 * `L3_DEFAULT`). Immutable.
63 * @default "TCP"
64 */
65 ipProtocol?: compute.ForwardingRuleIPProtocolEnum | (string & {});
66 /**
67 * `IPV4` or `IPV6`. Immutable.
68 */
69 ipVersion?: compute.ForwardingRuleIpVersionEnum | (string & {});
70 /**
71 * Port or range (`80` or `80-80`). Required for HTTP(S) / proxy NLB
72 * frontends. Immutable.
73 */
74 portRange?: string;
75 /**
76 * Forwarding-rule type. `EXTERNAL` is classic HTTP(S) LB;
77 * `EXTERNAL_MANAGED` is the global external Application Load
78 * Balancer. Immutable — changing it replaces the rule.
79 * @default "EXTERNAL"
80 */
81 loadBalancingScheme?: compute.ForwardingRuleLoadBalancingSchemeEnum | (string & {});
82 /**
83 * VPC network URL. Unused for external HTTP(S) LB; required for
84 * PSC-to-Google-APIs. Immutable.
85 */
86 network?: string;
87 /**
88 * Networking tier. Global forwarding rules only support `PREMIUM`.
89 * Mutable via `patch`.
90 * @default "PREMIUM"
91 */
92 networkTier?: compute.ForwardingRuleNetworkTierEnum | (string & {});
93 /**
94 * User labels. Alchemy ownership labels are merged in and synced via
95 * `setLabels` (labels cannot be set on insert).
96 */
97 labels?: Record<string, string>;
98 /**
99 * xDS metadata filters (`INTERNAL_SELF_MANAGED` only). Immutable.
100 */
101 metadataFilters?: compute.MetadataFilter[];
102 /**
103 * Restrict forwarding to these source IPs / CIDRs (regional EXTERNAL
104 * only). Immutable.
105 */
106 sourceIpRanges?: string[];
107 /**
108 * Skip auto-creating a DNS zone on a PSC consumer rule. Immutable.
109 */
110 noAutomateDnsZone?: boolean;
111 /**
112 * Service Directory registration (PSC for Google APIs). Immutable.
113 */
114 serviceDirectoryRegistrations?: compute.ForwardingRuleServiceDirectoryRegistration[];
115 /**
116 * Public delegated prefix URL for BYOIP IPv6. Immutable.
117 */
118 ipCollection?: string;
119 /**
120 * Canary state when migrating backend buckets from `EXTERNAL` to
121 * `EXTERNAL_MANAGED` (`PREPARE`, `TEST_BY_PERCENTAGE`,
122 * `TEST_ALL_TRAFFIC`).
123 */
124 externalManagedBackendBucketMigrationState?:
125 | compute.ForwardingRuleExternalManagedBackendBucketMigrationStateEnum
126 | (string & {});
127 /**
128 * Percent of backend-bucket traffic on the new scheme when the
129 * migration state is `TEST_BY_PERCENTAGE` (`0`–`100`).
130 */
131 externalManagedBackendBucketMigrationTestingPercentage?: number;
132 };
133
134 export type GlobalForwardingRule = Resource<
135 "GCP.Compute.GlobalForwardingRule",
136 GlobalForwardingRuleProps,
137 {
138 /** RFC1035 resource name. */
139 forwardingRuleName: string;
140 /** Project id. */
141 project: string;
142 /** Server-assigned numeric id. */
143 forwardingRuleId: string | undefined;
144 /** Compute self-link. */
145 selfLink: string | undefined;
146 /** Assigned IP address number. */
147 ipAddress: string | undefined;
148 /** IP protocol. */
149 ipProtocol: string | undefined;
150 /** `IPV4` or `IPV6`. */
151 ipVersion: string | undefined;
152 /** Port or range. */
153 portRange: string | undefined;
154 /** Target proxy / PSC URL. */
155 target: string | undefined;
156 /** Load balancer type. */
157 loadBalancingScheme: string | undefined;
158 /** Networking tier. */
159 networkTier: string | undefined;
160 /** Network URL, if set. */
161 network: string | undefined;
162 /** Description. */
163 description: string | undefined;
164 /** User labels (Alchemy ownership labels stripped). */
165 labels: Record<string, string>;
166 /** Optimistic-locking fingerprint. */
167 fingerprint: string | undefined;
168 /** Label fingerprint for `setLabels`. */
169 labelFingerprint: string | undefined;
170 /** RFC3339 creation timestamp. */
171 creationTimestamp: string | undefined;
172 /** PSC connection id, if this is a PSC rule. */
173 pscConnectionId: string | undefined;
174 /** PSC connection status, if this is a PSC rule. */
175 pscConnectionStatus: string | undefined;
176 /** Base forwarding-rule URL when `sourceIpRanges` is set. */
177 baseForwardingRule: string | undefined;
178 /** Resource kind (`compute#forwardingRule`). */
179 kind: string | undefined;
180 },
181 never,
182 Providers
183 >;
184
185 /**
186 * A global Compute Engine forwarding rule — the frontend of a global
187 * load balancer. It binds an IP and port range to a target HTTP/HTTPS
188 * proxy (or SSL/TCP/gRPC proxy, or a Private Service Connect bundle).
189 *
190 * Labels cannot be set on insert — Alchemy applies them with
191 * `setLabels` after the rule exists and also stamps ownership into the
192 * description so `list` / `pnpm nuke:gcp` can find a rule if labeling
193 * is interrupted. `list` also includes unlabeled rules whose `target`
194 * is an Alchemy-owned HTTP(S) proxy. `target` and `networkTier` update
195 * in place (`setTarget` / `patch`). Name, IP, protocol, port range,
196 * description, network, and load-balancing scheme replace the rule.
197 *
198 * ### Creating a Global Forwarding Rule
199 * **Example:** HTTP frontend in front of a target HTTP proxy
200 * ```typescript
201 * const map = yield* GCP.Compute.UrlMap("web", {
202 * defaultUrlRedirect: {
203 * httpsRedirect: true,
204 * hostRedirect: "example.com",
205 * stripQuery: false,
206 * },
207 * });
208 * const proxy = yield* GCP.Compute.TargetHttpProxy("http", {
209 * urlMap: map.urlMapName,
210 * });
211 * const rule = yield* GCP.Compute.GlobalForwardingRule("frontend", {
212 * target: proxy.selfLink,
213 * portRange: "80",
214 * });
215 * ```
216 *
217 * **Example:** Named rule with labels and a reserved IP
218 * ```typescript
219 * const ip = yield* GCP.Compute.GlobalAddress("FrontendIp", {});
220 * const rule = yield* GCP.Compute.GlobalForwardingRule("frontend", {
221 * forwardingRuleName: "app-http",
222 * description: "public HTTP frontend",
223 * target: proxy.selfLink,
224 * ipAddress: ip.address,
225 * portRange: "80",
226 * loadBalancingScheme: "EXTERNAL",
227 * labels: { env: "prod" },
228 * });
229 * ```
230 *
231 * ### Updating a Global Forwarding Rule
232 * **Example:** Retarget and relabel
233 * ```typescript
234 * const rule = yield* GCP.Compute.GlobalForwardingRule("frontend", {
235 * forwardingRuleName: "app-http",
236 * target: otherProxy.selfLink,
237 * portRange: "80",
238 * labels: { env: "prod", role: "edge" },
239 * });
240 * ```
241 *
242 * @resource
243 * @category Compute
244 */
245 export const GlobalForwardingRule = Resource<GlobalForwardingRule>(
246 "GCP.Compute.GlobalForwardingRule",
247 );
248
249 export class GlobalForwardingRuleNotResolved extends Data.TaggedError(
250 "GCP.Compute.GlobalForwardingRuleNotResolved",
251 )<{
252 forwardingRuleName: string;
253 }> {}
254
255 export class GlobalForwardingRulePending extends Data.TaggedError(
256 "GCP.Compute.GlobalForwardingRulePending",
257 )<{
258 forwardingRuleName: string;
259 status: string;
260 }> {}
261
262 const userLabels = (
263 labels: Record<string, string | undefined> | null | undefined,
264 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
265
266 const toName = (id: string, name: string | undefined, existing?: string) =>
267 Effect.gen(function* () {
268 if (name !== undefined) return name;
269 if (existing !== undefined) return existing;
270 const generated = yield* createPhysicalName({
271 id,
272 maxLength: MAX_NAME_LENGTH,
273 lowercase: true,
274 });
275 return /^[a-z]/.test(generated) ? generated : `f${generated}`.slice(0, MAX_NAME_LENGTH);
276 });
277
278 const resourceTail = (value: string | undefined): string => lastSegment(value).toLowerCase();
279
280 const proxyName = (proxy: { name?: string; description?: string }) =>
281 hasOwnershipMarker(proxy.description) ? lastSegment(proxy.name).toLowerCase() : "";
282
283 const ownedProxyNames = (project: string) =>
284 Effect.gen(function* () {
285 const http = yield* compute.listTargetHttpProxies.items({ project, maxResults: 500 }).pipe(
286 Stream.map(proxyName),
287 Stream.filter((name) => name.length > 0),
288 Stream.runCollect,
289 Effect.map((chunk) => Array.from(chunk)),
290 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
291 );
292 const https = yield* compute.listTargetHttpsProxies.items({ project, maxResults: 500 }).pipe(
293 Stream.map(proxyName),
294 Stream.filter((name) => name.length > 0),
295 Stream.runCollect,
296 Effect.map((chunk) => Array.from(chunk)),
297 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
298 );
299 return new Set<string>([...http, ...https]);
300 });
301
302 const isOwnedForwardingRule = (rule: compute.ForwardingRule, ownedTargets: ReadonlySet<string>) => {
303 if (Object.keys(rule.labels ?? {}).some((key) => key.startsWith("alchemy-"))) {
304 return true;
305 }
306 if (hasOwnershipMarker(rule.description)) return true;
307 const target = resourceTail(rule.target);
308 if (target.length > 0 && ownedTargets.has(target)) return true;
309 // Insert cannot set labels; a crash before setLabels leaves an unlabeled
310 // rule whose name is still the engine physical name (`gcp-…` in tests).
311 const name = (rule.name ?? "").toLowerCase();
312 return (
313 name.startsWith("gcp-") && (rule.description === undefined || rule.description.length === 0)
314 );
315 };
316
317 const normalizePortRange = (value: string | undefined): string => {
318 if (value === undefined || value.length === 0) return "";
319 const trimmed = value.trim();
320 return /^\d+$/.test(trimmed) ? `${trimmed}-${trimmed}` : trimmed;
321 };
322
323 const isRawIp = (value: string): boolean =>
324 !value.includes("/") && (value.includes(".") || value.includes(":"));
325
326 const sameJson = (left: unknown, right: unknown) =>
327 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
328
329 const schemeOf = (value: string | undefined) => value ?? DEFAULT_SCHEME;
330
331 const protocolOf = (value: string | undefined) => (value ?? DEFAULT_PROTOCOL).toUpperCase();
332
333 const tierOf = (value: string | undefined) => value ?? DEFAULT_TIER;
334
335 const ipVersionOf = (value: string | undefined) =>
336 value && value !== "UNSPECIFIED_VERSION" ? value : "";
337
338 const toAttrs = (rule: compute.ForwardingRule, project: string) => ({
339 forwardingRuleName: rule.name ?? "",
340 project,
341 forwardingRuleId: rule.id,
342 selfLink: rule.selfLink,
343 ipAddress: rule.IPAddress,
344 ipProtocol: rule.IPProtocol,
345 ipVersion: rule.ipVersion,
346 portRange: rule.portRange,
347 target: rule.target,
348 loadBalancingScheme: rule.loadBalancingScheme,
349 networkTier: rule.networkTier,
350 network: rule.network,
351 description: parseDescription(rule.description).description,
352 labels: userLabels(rule.labels),
353 fingerprint: rule.fingerprint,
354 labelFingerprint: rule.labelFingerprint,
355 creationTimestamp: rule.creationTimestamp,
356 pscConnectionId: rule.pscConnectionId,
357 pscConnectionStatus: rule.pscConnectionStatus,
358 baseForwardingRule: rule.baseForwardingRule,
359 kind: rule.kind,
360 });
361
362 const toInsertBody = (
363 forwardingRuleName: string,
364 news: GlobalForwardingRuleProps,
365 description: string,
366 ): compute.ForwardingRule => {
367 const body: compute.ForwardingRule = {
368 name: forwardingRuleName,
369 target: news.target,
370 description,
371 IPProtocol: news.ipProtocol ?? DEFAULT_PROTOCOL,
372 loadBalancingScheme: news.loadBalancingScheme ?? DEFAULT_SCHEME,
373 networkTier: news.networkTier ?? DEFAULT_TIER,
374 };
375 if (news.ipAddress !== undefined) body.IPAddress = news.ipAddress;
376 if (news.ipVersion !== undefined) body.ipVersion = news.ipVersion;
377 if (news.portRange !== undefined) body.portRange = news.portRange;
378 if (news.network !== undefined) body.network = news.network;
379 if (news.metadataFilters !== undefined) {
380 body.metadataFilters = news.metadataFilters;
381 }
382 if (news.sourceIpRanges !== undefined) {
383 body.sourceIpRanges = news.sourceIpRanges;
384 }
385 if (news.noAutomateDnsZone !== undefined) {
386 body.noAutomateDnsZone = news.noAutomateDnsZone;
387 }
388 if (news.serviceDirectoryRegistrations !== undefined) {
389 body.serviceDirectoryRegistrations = news.serviceDirectoryRegistrations;
390 }
391 if (news.ipCollection !== undefined) {
392 body.ipCollection = news.ipCollection;
393 }
394 if (news.externalManagedBackendBucketMigrationState !== undefined) {
395 body.externalManagedBackendBucketMigrationState =
396 news.externalManagedBackendBucketMigrationState;
397 }
398 if (news.externalManagedBackendBucketMigrationTestingPercentage !== undefined) {
399 body.externalManagedBackendBucketMigrationTestingPercentage =
400 news.externalManagedBackendBucketMigrationTestingPercentage;
401 }
402 return body;
403 };
404
405 const getByName = (project: string, forwardingRule: string) =>
406 compute
407 .getGlobalForwardingRules({ project, forwardingRule })
408 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
409
410 const awaitResource = (project: string, forwardingRuleName: string) =>
411 getByName(project, forwardingRuleName).pipe(
412 Effect.flatMap((rule) =>
413 rule === undefined
414 ? Effect.fail(
415 new GlobalForwardingRulePending({
416 forwardingRuleName,
417 status: "MISSING",
418 }),
419 )
420 : Effect.succeed(rule),
421 ),
422 Effect.retry({
423 while: (error) => error._tag === "GCP.Compute.GlobalForwardingRulePending",
424 times: 8,
425 schedule: Schedule.spaced("1 second"),
426 }),
427 );
428
429 const waitUntilGone = (project: string, forwardingRuleName: string) =>
430 getByName(project, forwardingRuleName).pipe(
431 Effect.flatMap((rule) =>
432 rule === undefined
433 ? Effect.void
434 : Effect.fail(
435 new GlobalForwardingRulePending({
436 forwardingRuleName,
437 status: "EXISTS",
438 }),
439 ),
440 ),
441 Effect.retry({
442 while: (error) => error._tag === "GCP.Compute.GlobalForwardingRulePending",
443 times: 10,
444 schedule: Schedule.spaced("1 second"),
445 }),
446 Effect.catchTag("GCP.Compute.GlobalForwardingRulePending", () => Effect.void),
447 );
448
449 export const GlobalForwardingRuleProvider = () =>
450 Provider.succeed(GlobalForwardingRule, {
451 nuke: {
452 dependsOn: ["GCP.Compute.TargetHttpProxy", "GCP.Compute.TargetHttpsProxy"],
453 },
454 stables: [
455 "forwardingRuleName",
456 "project",
457 "forwardingRuleId",
458 "selfLink",
459 "ipAddress",
460 "ipProtocol",
461 "ipVersion",
462 "portRange",
463 "loadBalancingScheme",
464 "network",
465 "creationTimestamp",
466 ],
467
468 diff: Effect.fn(function* ({ news, olds, output }) {
469 if (!isResolved(news)) return undefined;
470 const previousName = olds?.forwardingRuleName ?? output?.forwardingRuleName;
471 const nextName = news.forwardingRuleName ?? previousName;
472 const nameChanged =
473 previousName !== undefined && nextName !== undefined && nextName !== previousName;
474
475 const previousProtocol = protocolOf(olds?.ipProtocol ?? output?.ipProtocol);
476 const previousPort = normalizePortRange(olds?.portRange ?? output?.portRange);
477 const nextPort = normalizePortRange(news.portRange);
478 const previousNetwork = resourceTail(olds?.network ?? output?.network);
479 const previousDescription = olds?.description ?? output?.description ?? "";
480 const previousVersion = ipVersionOf(olds?.ipVersion ?? output?.ipVersion);
481 const previousCollection = resourceTail(olds?.ipCollection);
482 const previousDns = olds?.noAutomateDnsZone;
483 const previousScheme = schemeOf(olds?.loadBalancingScheme ?? output?.loadBalancingScheme);
484
485 const previousIp = output?.ipAddress;
486 const ipChanged =
487 news.ipAddress !== undefined &&
488 isRawIp(news.ipAddress) &&
489 previousIp !== undefined &&
490 news.ipAddress !== previousIp;
491
492 const immutableChanged =
493 (news.description !== undefined && (news.description ?? "") !== previousDescription) ||
494 ipChanged ||
495 (news.ipProtocol !== undefined && protocolOf(news.ipProtocol) !== previousProtocol) ||
496 (news.ipVersion !== undefined && ipVersionOf(news.ipVersion) !== previousVersion) ||
497 (news.portRange !== undefined && nextPort !== previousPort) ||
498 (news.loadBalancingScheme !== undefined &&
499 schemeOf(news.loadBalancingScheme) !== previousScheme) ||
500 (news.network !== undefined && resourceTail(news.network) !== previousNetwork) ||
501 (news.ipCollection !== undefined &&
502 resourceTail(news.ipCollection) !== previousCollection) ||
503 (news.noAutomateDnsZone !== undefined && news.noAutomateDnsZone !== previousDns) ||
504 (news.metadataFilters !== undefined &&
505 !sameJson(news.metadataFilters, olds?.metadataFilters)) ||
506 (news.sourceIpRanges !== undefined &&
507 !sameJson([...news.sourceIpRanges].sort(), [...(olds?.sourceIpRanges ?? [])].sort())) ||
508 (news.serviceDirectoryRegistrations !== undefined &&
509 !sameJson(news.serviceDirectoryRegistrations, olds?.serviceDirectoryRegistrations));
510
511 if (nameChanged) {
512 return { action: "replace" as const, deleteFirst: false };
513 }
514 if (immutableChanged) {
515 return {
516 action: "replace" as const,
517 deleteFirst:
518 previousName !== undefined && (nextName === undefined || nextName === previousName),
519 };
520 }
521 return undefined;
522 }),
523
524 read: Effect.fn(function* ({ id, olds, output }) {
525 const env = yield* GcpEnvironment.current;
526 const forwardingRuleName = yield* toName(
527 id,
528 olds?.forwardingRuleName,
529 output?.forwardingRuleName,
530 );
531 const existing = yield* getByName(env.project, forwardingRuleName);
532 if (existing === undefined) return undefined;
533 const attrs = toAttrs(existing, env.project);
534 const { labels: descriptionLabels } = parseDescription(existing.description);
535 return (yield* hasAlchemyLabels(id, {
536 ...descriptionLabels,
537 ...tagRecord(existing.labels),
538 }))
539 ? attrs
540 : Unowned(attrs);
541 }),
542
543 list: () =>
544 Effect.gen(function* () {
545 const env = yield* GcpEnvironment.current;
546 const ownedTargets = yield* ownedProxyNames(env.project);
547 return yield* compute.listGlobalForwardingRules
548 .items({ project: env.project, maxResults: 500 })
549 .pipe(
550 Stream.filter((rule) => isOwnedForwardingRule(rule, ownedTargets)),
551 Stream.map((rule) => toAttrs(rule, env.project)),
552 Stream.runCollect,
553 Effect.map((chunk) => Array.from(chunk)),
554 Effect.catchTag("NotFound", () =>
555 Effect.succeed([] as GlobalForwardingRule["Attributes"][]),
556 ),
557 );
558 }),
559
560 reconcile: Effect.fn(function* ({ id, news, output }) {
561 const env = yield* GcpEnvironment.current;
562 const forwardingRuleName = yield* toName(
563 id,
564 news.forwardingRuleName,
565 output?.forwardingRuleName,
566 );
567 const ownership = yield* createInternalLabels(id);
568 const desiredDescription = encodeDescription(ownership, news.description);
569 const desiredLabels = {
570 ...toLabels(news.labels),
571 ...ownership,
572 };
573
574 let current = yield* getByName(env.project, forwardingRuleName);
575
576 if (current === undefined) {
577 const created = yield* compute
578 .insertGlobalForwardingRules({
579 project: env.project,
580 body: toInsertBody(forwardingRuleName, news, desiredDescription),
581 })
582 .pipe(
583 Effect.flatMap((operation) =>
584 waitGlobalOperation(env.project, operation, {
585 ignore: ["RESOURCE_ALREADY_EXISTS"],
586 }).pipe(Effect.flatMap(() => getByName(env.project, forwardingRuleName))),
587 ),
588 Effect.catchTag("Conflict", () => getByName(env.project, forwardingRuleName)),
589 );
590 current = created ?? undefined;
591 if (current === undefined) {
592 current = yield* awaitResource(env.project, forwardingRuleName).pipe(
593 Effect.catchTag("GCP.Compute.GlobalForwardingRulePending", () => Effect.undefined),
594 );
595 }
596 }
597
598 if (current === undefined) {
599 return yield* new GlobalForwardingRuleNotResolved({
600 forwardingRuleName,
601 });
602 }
603 const resolved = current;
604
605 if (news.target !== undefined && resourceTail(current.target) !== resourceTail(news.target)) {
606 yield* compute
607 .setTargetGlobalForwardingRules({
608 project: env.project,
609 forwardingRule: forwardingRuleName,
610 body: { target: news.target },
611 })
612 .pipe(
613 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
614 Effect.retry({
615 while: (error) => error._tag === "Conflict",
616 times: 8,
617 schedule: Schedule.spaced("2 seconds"),
618 }),
619 );
620 current = (yield* getByName(env.project, forwardingRuleName)) ?? current;
621 }
622
623 const tierChanged =
624 news.networkTier !== undefined && tierOf(current.networkTier) !== tierOf(news.networkTier);
625 const migrationStateChanged =
626 news.externalManagedBackendBucketMigrationState !== undefined &&
627 current.externalManagedBackendBucketMigrationState !==
628 news.externalManagedBackendBucketMigrationState;
629 const migrationPctChanged =
630 news.externalManagedBackendBucketMigrationTestingPercentage !== undefined &&
631 current.externalManagedBackendBucketMigrationTestingPercentage !==
632 news.externalManagedBackendBucketMigrationTestingPercentage;
633
634 if (tierChanged || migrationStateChanged || migrationPctChanged) {
635 const patch: compute.ForwardingRule = {
636 fingerprint: current.fingerprint,
637 };
638 if (tierChanged) patch.networkTier = news.networkTier;
639 if (migrationStateChanged) {
640 patch.externalManagedBackendBucketMigrationState =
641 news.externalManagedBackendBucketMigrationState;
642 }
643 if (migrationPctChanged) {
644 patch.externalManagedBackendBucketMigrationTestingPercentage =
645 news.externalManagedBackendBucketMigrationTestingPercentage;
646 }
647 yield* compute
648 .patchGlobalForwardingRules({
649 project: env.project,
650 forwardingRule: forwardingRuleName,
651 body: patch,
652 })
653 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
654 current = (yield* getByName(env.project, forwardingRuleName)) ?? current;
655 }
656
657 const observedLabels = tagRecord(current.labels);
658 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
659 if (upsert.length > 0 || removed.length > 0) {
660 yield* Effect.gen(function* () {
661 const latest = (yield* getByName(env.project, forwardingRuleName)) ?? resolved;
662 yield* compute
663 .setLabelsGlobalForwardingRules({
664 project: env.project,
665 resource: forwardingRuleName,
666 body: {
667 labels: desiredLabels,
668 labelFingerprint: latest.labelFingerprint,
669 },
670 })
671 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
672 }).pipe(
673 Effect.retry({
674 while: (error) => error._tag === "Conflict",
675 times: 8,
676 schedule: Schedule.spaced("2 seconds"),
677 }),
678 );
679 current = (yield* getByName(env.project, forwardingRuleName)) ?? resolved;
680 }
681
682 return toAttrs(current ?? resolved, env.project);
683 }),
684
685 delete: Effect.fn(function* ({ output }) {
686 const env = yield* GcpEnvironment.current;
687 yield* compute
688 .deleteGlobalForwardingRules({
689 project: env.project,
690 forwardingRule: output.forwardingRuleName,
691 })
692 .pipe(
693 Effect.flatMap((operation) =>
694 waitGlobalOperation(env.project, operation, {
695 ignore: ["RESOURCE_NOT_FOUND"],
696 }),
697 ),
698 Effect.catchTag("NotFound", () => Effect.void),
699 Effect.retry({
700 while: (error) => error._tag === "Conflict",
701 times: 8,
702 schedule: Schedule.spaced("2 seconds"),
703 }),
704 );
705 yield* waitUntilGone(env.project, output.forwardingRuleName);
706 }),
707 });