The best way to control Claude Code, Codex and more from any computer or phone

main
ts 839 lines 28.3 KB
Raw
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 { 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 { waitRegionOperation } from "./operations.ts";
22
23 const DEFAULT_SCHEME = "EXTERNAL";
24 const DEFAULT_NETWORK_TIER = "PREMIUM";
25 const MAX_NAME_LENGTH = 63;
26
27 export type ForwardingRuleServiceDirectoryRegistration =
28 compute.ForwardingRuleServiceDirectoryRegistration;
29
30 export type ForwardingRuleProps = {
31 /**
32 * Name of the forwarding rule. If omitted, a unique RFC1035 name is
33 * generated from the stack, stage, and logical id. Immutable — changing
34 * it replaces the rule.
35 */
36 forwardingRuleName?: string;
37 /**
38 * Region the rule lives in. Immutable — changing it replaces the rule.
39 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
40 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
41 */
42 region?: string;
43 /**
44 * Optional description. Immutable — changing it replaces the rule.
45 */
46 description?: string;
47 /**
48 * IP address or Address URL this rule accepts traffic on. When omitted,
49 * GCP assigns an ephemeral address. Immutable — changing a literal IP
50 * replaces the rule.
51 */
52 ipAddress?: string;
53 /**
54 * IP protocol (`TCP`, `UDP`, `ESP`, `AH`, `SCTP`, `ICMP`, `L3_DEFAULT`).
55 * Immutable — changing it replaces the rule.
56 */
57 ipProtocol?: compute.ForwardingRuleIPProtocolEnum | (string & {});
58 /**
59 * Single port or `start-end` range. Mutually exclusive with `ports` and
60 * `allPorts`. Immutable — changing it replaces the rule.
61 */
62 portRange?: string;
63 /**
64 * Up to five discrete ports. Mutually exclusive with `portRange` and
65 * `allPorts`. Immutable — changing it replaces the rule.
66 */
67 ports?: string[];
68 /**
69 * Forward every port (and packets with no port). Mutually exclusive with
70 * `portRange` and `ports`. Immutable — changing it replaces the rule.
71 */
72 allPorts?: boolean;
73 /**
74 * Target resource URL (target pool, target instance, target HTTP(S)/TCP
75 * proxy, target VPN gateway, or a PSC service attachment / Google API
76 * bundle). Updated in place via `setTarget`.
77 */
78 target?: string;
79 /**
80 * Backend service URL. Required for internal and external passthrough
81 * Network Load Balancers; omitted for other products. Immutable —
82 * changing it replaces the rule.
83 */
84 backendService?: string;
85 /**
86 * Forwarding rule type (`EXTERNAL`, `EXTERNAL_MANAGED`, `INTERNAL`,
87 * `INTERNAL_MANAGED`). Use `""` for some PSC endpoints. Immutable —
88 * changing it replaces the rule.
89 * @default "EXTERNAL"
90 */
91 loadBalancingScheme?: compute.ForwardingRuleLoadBalancingSchemeEnum | "" | (string & {});
92 /**
93 * VPC network URL or name. Used for internal load balancing and PSC.
94 * Immutable — changing it replaces the rule.
95 */
96 network?: string;
97 /**
98 * Subnetwork URL or name. Required for custom-mode VPCs and IPv6
99 * external rules. Immutable — changing it replaces the rule.
100 */
101 subnetwork?: string;
102 /**
103 * Networking tier (`PREMIUM` or `STANDARD`). Immutable — changing it
104 * replaces the rule.
105 * @default "PREMIUM"
106 */
107 networkTier?: compute.ForwardingRuleNetworkTierEnum | (string & {});
108 /**
109 * `IPV4` or `IPV6`. Immutable — changing it replaces the rule.
110 */
111 ipVersion?: compute.ForwardingRuleIpVersionEnum | (string & {});
112 /**
113 * Allow clients in other regions to reach this internal load balancer.
114 * Updated in place via `patch`, except `INTERNAL_MANAGED` where a change
115 * replaces the rule.
116 */
117 allowGlobalAccess?: boolean;
118 /**
119 * Allow a PSC consumer endpoint to be reached from another region.
120 * Updated in place via `patch`.
121 */
122 allowPscGlobalAccess?: boolean;
123 /**
124 * Skip auto-creating a DNS zone for a PSC consumer endpoint. Immutable
125 * — changing it replaces the rule.
126 */
127 noAutomateDnsZone?: boolean;
128 /**
129 * Use this INTERNAL load balancer as a packet-mirroring collector.
130 * Immutable — changing it replaces the rule.
131 */
132 isMirroringCollector?: boolean;
133 /**
134 * Optional prefix of the fully-qualified INTERNAL service name.
135 * Immutable — changing it replaces the rule.
136 */
137 serviceLabel?: string;
138 /**
139 * Restrict EXTERNAL regional rules to these source IPs or CIDRs (max
140 * 64). Immutable — changing it replaces the rule.
141 */
142 sourceIpRanges?: string[];
143 /**
144 * Public delegated prefix used to draw a BYOIP IPv6 address. Immutable
145 * — changing it replaces the rule.
146 */
147 ipCollection?: string;
148 /**
149 * Service Directory registrations. Currently a single entry. Immutable
150 * — changing it replaces the rule.
151 */
152 serviceDirectoryRegistrations?: ForwardingRuleServiceDirectoryRegistration[];
153 /**
154 * User labels. Alchemy ownership labels are merged in automatically
155 * and synced via `setLabels` (labels cannot be set on insert).
156 */
157 labels?: Record<string, string>;
158 };
159
160 export type ForwardingRule = Resource<
161 "GCP.Compute.ForwardingRule",
162 ForwardingRuleProps,
163 {
164 /** Forwarding rule name. */
165 forwardingRuleName: string;
166 /** Project id. */
167 project: string;
168 /** Region short name (`us-central1`). */
169 region: string;
170 /** Server-assigned numeric id. */
171 forwardingRuleId: string | undefined;
172 /** Resource self-link. */
173 selfLink: string | undefined;
174 /** Assigned IP address number. */
175 ipAddress: string | undefined;
176 /** IP protocol. */
177 ipProtocol: string | undefined;
178 /** Port range, if set. */
179 portRange: string | undefined;
180 /** Discrete ports, if set. */
181 ports: ReadonlyArray<string>;
182 /** Whether every port is forwarded. */
183 allPorts: boolean;
184 /** Target resource URL, if set. */
185 target: string | undefined;
186 /** Backend service URL, if set. */
187 backendService: string | undefined;
188 /** Load balancing scheme. */
189 loadBalancingScheme: string | undefined;
190 /** Network URL, if set. */
191 network: string | undefined;
192 /** Subnetwork URL, if set. */
193 subnetwork: string | undefined;
194 /** Networking tier. */
195 networkTier: string | undefined;
196 /** IP version. */
197 ipVersion: string | undefined;
198 /** Cross-region ILB access. */
199 allowGlobalAccess: boolean;
200 /** Cross-region PSC access. */
201 allowPscGlobalAccess: boolean;
202 /** PSC DNS-zone automation disabled. */
203 noAutomateDnsZone: boolean;
204 /** Packet-mirroring collector. */
205 isMirroringCollector: boolean;
206 /** INTERNAL service-name prefix, if set. */
207 serviceLabel: string | undefined;
208 /** Fully-qualified INTERNAL service name, if any. */
209 serviceName: string | undefined;
210 /** Source IP filters. */
211 sourceIpRanges: ReadonlyArray<string>;
212 /** BYOIP public delegated prefix, if any. */
213 ipCollection: string | undefined;
214 /** PSC connection id, if any. */
215 pscConnectionId: string | undefined;
216 /** PSC connection status, if any. */
217 pscConnectionStatus: string | undefined;
218 /** Corresponding base forwarding rule, if any. */
219 baseForwardingRule: string | undefined;
220 /** Description. */
221 description: string | undefined;
222 /** User labels (Alchemy ownership labels stripped). */
223 labels: Record<string, string>;
224 /** RFC3339 creation timestamp. */
225 creationTimestamp: string | undefined;
226 /** Resource kind. */
227 kind: string | undefined;
228 },
229 never,
230 Providers
231 >;
232
233 /**
234 * A regional Compute Engine forwarding rule.
235 *
236 * Forwarding rules are the frontend of a Google Cloud load balancer: an
237 * IP address, protocol, and port that send traffic to a target (pool,
238 * instance, HTTP(S)/TCP proxy, VPN gateway) or a backend service. This
239 * resource maps to the regional `forwardingRules` collection
240 * (`globalForwardingRules` is a separate resource).
241 *
242 * Labels cannot be set on insert — Alchemy applies them with `setLabels`
243 * after the rule exists. `target`, `allowGlobalAccess`, and
244 * `allowPscGlobalAccess` update in place; name, region, IP, protocol,
245 * ports, scheme, network, subnetwork, backend service, and description
246 * replace the rule.
247 *
248 * ### Creating a Forwarding Rule
249 * **Example:** Classic Network Load Balancer frontend
250 * ```typescript
251 * const rule = yield* GCP.Compute.ForwardingRule("Frontend", {
252 * region: "us-central1",
253 * target: targetPool.selfLink,
254 * portRange: "80",
255 * });
256 * ```
257 *
258 * **Example:** Named rule with labels
259 * ```typescript
260 * const rule = yield* GCP.Compute.ForwardingRule("Frontend", {
261 * forwardingRuleName: "app-frontend",
262 * region: "us-central1",
263 * ipProtocol: "TCP",
264 * portRange: "80-80",
265 * target: targetPool.selfLink,
266 * labels: { env: "prod" },
267 * });
268 * ```
269 *
270 * ### Internal Load Balancing
271 * **Example:** Regional internal passthrough NLB
272 * ```typescript
273 * const rule = yield* GCP.Compute.ForwardingRule("Ilb", {
274 * region: "us-central1",
275 * loadBalancingScheme: "INTERNAL",
276 * backendService: backend.selfLink,
277 * network: vpc.selfLink,
278 * subnetwork: subnet.selfLink,
279 * ipProtocol: "TCP",
280 * ports: ["80"],
281 * allowGlobalAccess: true,
282 * });
283 * ```
284 *
285 * @resource
286 * @category Compute
287 */
288 export const ForwardingRule = Resource<ForwardingRule>("GCP.Compute.ForwardingRule");
289
290 export class ForwardingRuleNotResolved extends Data.TaggedError(
291 "GCP.Compute.ForwardingRuleNotResolved",
292 )<{
293 forwardingRuleName: string;
294 region: string;
295 }> {}
296
297 export class ForwardingRulePending extends Data.TaggedError("GCP.Compute.ForwardingRulePending")<{
298 forwardingRuleName: string;
299 status: string;
300 }> {}
301
302 const userLabels = (
303 labels: Record<string, string | undefined> | null | undefined,
304 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
305
306 const lastSegment = (value: string) => {
307 const trimmed = value.replace(/\/+$/, "");
308 const parts = trimmed.split("/");
309 return parts[parts.length - 1] || trimmed;
310 };
311
312 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
313 lastSegment(region ?? defaultRegion).toLowerCase();
314
315 const resourceRefOf = (value: string | undefined) => {
316 if (!value) return "";
317 return lastSegment(value);
318 };
319
320 const schemeOf = (value: string | undefined) => (value === undefined ? DEFAULT_SCHEME : value);
321
322 const networkTierOf = (value: string | undefined) => value ?? DEFAULT_NETWORK_TIER;
323
324 const ipVersionOf = (value: string | undefined) =>
325 value && value !== "UNSPECIFIED_VERSION" ? value : "";
326
327 const normalizePortRange = (value: string | undefined) => {
328 if (value === undefined || value.length === 0) return "";
329 const trimmed = value.trim();
330 return /^\d+$/.test(trimmed) ? `${trimmed}-${trimmed}` : trimmed;
331 };
332
333 const portsKey = (ports: ReadonlyArray<string> | undefined) =>
334 [...(ports ?? [])].map(String).sort().join(",");
335
336 const rangesKey = (ranges: ReadonlyArray<string> | undefined) =>
337 [...(ranges ?? [])].map(String).sort().join(",");
338
339 const registrationsKey = (
340 registrations: ReadonlyArray<ForwardingRuleServiceDirectoryRegistration> | undefined,
341 ) =>
342 JSON.stringify(
343 (registrations ?? []).map((item) => ({
344 namespace: item.namespace ?? "",
345 service: item.service ?? "",
346 serviceDirectoryRegion: item.serviceDirectoryRegion ?? "",
347 })),
348 );
349
350 const isLiteralIp = (value: string) => {
351 if (value.includes("/")) return false;
352 if (/^[0-9.]+$/.test(value)) return true;
353 return value.includes(":");
354 };
355
356 const toName = (id: string, name: string | undefined, existing?: string) =>
357 Effect.gen(function* () {
358 if (name !== undefined) return name;
359 if (existing !== undefined) return existing;
360 const generated = yield* createPhysicalName({
361 id,
362 maxLength: MAX_NAME_LENGTH,
363 lowercase: true,
364 });
365 return /^[a-z]/.test(generated) ? generated : `f${generated}`.slice(0, MAX_NAME_LENGTH);
366 });
367
368 const toAttrs = (rule: compute.ForwardingRule, project: string) => ({
369 forwardingRuleName: rule.name ?? "",
370 project,
371 region: lastSegment(rule.region ?? "").toLowerCase(),
372 forwardingRuleId: rule.id,
373 selfLink: rule.selfLink,
374 ipAddress: rule.IPAddress,
375 ipProtocol: rule.IPProtocol,
376 portRange: rule.portRange,
377 ports: rule.ports ?? [],
378 allPorts: rule.allPorts === true,
379 target: rule.target,
380 backendService: rule.backendService,
381 loadBalancingScheme: rule.loadBalancingScheme,
382 network: rule.network,
383 subnetwork: rule.subnetwork,
384 networkTier: rule.networkTier,
385 ipVersion: rule.ipVersion,
386 allowGlobalAccess: rule.allowGlobalAccess === true,
387 allowPscGlobalAccess: rule.allowPscGlobalAccess === true,
388 noAutomateDnsZone: rule.noAutomateDnsZone === true,
389 isMirroringCollector: rule.isMirroringCollector === true,
390 serviceLabel: rule.serviceLabel,
391 serviceName: rule.serviceName,
392 sourceIpRanges: rule.sourceIpRanges ?? [],
393 ipCollection: rule.ipCollection,
394 pscConnectionId: rule.pscConnectionId,
395 pscConnectionStatus: rule.pscConnectionStatus,
396 baseForwardingRule: rule.baseForwardingRule,
397 description: rule.description,
398 labels: userLabels(rule.labels),
399 creationTimestamp: rule.creationTimestamp,
400 kind: rule.kind,
401 });
402
403 const toInsertBody = (
404 forwardingRuleName: string,
405 news: ForwardingRuleProps,
406 ): compute.ForwardingRule => ({
407 name: forwardingRuleName,
408 description: news.description,
409 IPAddress: news.ipAddress,
410 IPProtocol: news.ipProtocol,
411 portRange: news.allPorts === true || news.ports !== undefined ? undefined : news.portRange,
412 ports: news.allPorts === true || news.portRange !== undefined ? undefined : news.ports,
413 allPorts: news.allPorts,
414 target: news.target,
415 backendService: news.backendService,
416 loadBalancingScheme: news.loadBalancingScheme,
417 network: news.network,
418 subnetwork: news.subnetwork,
419 networkTier: news.networkTier,
420 ipVersion: news.ipVersion,
421 allowGlobalAccess: news.allowGlobalAccess,
422 allowPscGlobalAccess: news.allowPscGlobalAccess,
423 noAutomateDnsZone: news.noAutomateDnsZone,
424 isMirroringCollector: news.isMirroringCollector,
425 serviceLabel: news.serviceLabel,
426 sourceIpRanges: news.sourceIpRanges,
427 ipCollection: news.ipCollection,
428 serviceDirectoryRegistrations: news.serviceDirectoryRegistrations,
429 });
430
431 const getByName = (project: string, region: string, forwardingRule: string) =>
432 compute
433 .getForwardingRules({ project, region, forwardingRule })
434 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
435
436 const requireForwardingRule = (project: string, region: string, forwardingRuleName: string) =>
437 getByName(project, region, forwardingRuleName).pipe(
438 Effect.flatMap((rule) =>
439 rule
440 ? Effect.succeed(rule)
441 : Effect.fail(new ForwardingRuleNotResolved({ forwardingRuleName, region })),
442 ),
443 Effect.retry({
444 while: (e) => e._tag === "GCP.Compute.ForwardingRuleNotResolved",
445 schedule: Schedule.spaced("1 second"),
446 times: 8,
447 }),
448 );
449
450 const waitUntilGone = (project: string, region: string, forwardingRuleName: string) =>
451 getByName(project, region, forwardingRuleName).pipe(
452 Effect.flatMap((rule) =>
453 rule === undefined
454 ? Effect.void
455 : Effect.fail(
456 new ForwardingRulePending({
457 forwardingRuleName,
458 status: "EXISTS",
459 }),
460 ),
461 ),
462 Effect.retry({
463 while: (e) => e._tag === "GCP.Compute.ForwardingRulePending",
464 times: 10,
465 schedule: Schedule.spaced("2 seconds"),
466 }),
467 );
468
469 const immutableChanged = (
470 news: ForwardingRuleProps,
471 previous: {
472 description: string;
473 ipAddress: string;
474 ipProtocol: string;
475 portRange: string;
476 ports: string;
477 allPorts: boolean;
478 backendService: string;
479 loadBalancingScheme: string;
480 network: string;
481 subnetwork: string;
482 networkTier: string;
483 ipVersion: string;
484 noAutomateDnsZone: boolean;
485 isMirroringCollector: boolean;
486 serviceLabel: string;
487 sourceIpRanges: string;
488 ipCollection: string;
489 serviceDirectoryRegistrations: string;
490 allowGlobalAccess: boolean;
491 },
492 ) => {
493 if (news.description !== undefined && (news.description ?? "") !== previous.description) {
494 return true;
495 }
496 if (
497 news.ipAddress !== undefined &&
498 isLiteralIp(news.ipAddress) &&
499 previous.ipAddress.length > 0 &&
500 news.ipAddress !== previous.ipAddress
501 ) {
502 return true;
503 }
504 if (
505 news.ipProtocol !== undefined &&
506 news.ipProtocol.toUpperCase() !== (previous.ipProtocol || "TCP").toUpperCase()
507 ) {
508 return true;
509 }
510 if (news.portRange !== undefined && normalizePortRange(news.portRange) !== previous.portRange) {
511 return true;
512 }
513 if (news.ports !== undefined && portsKey(news.ports) !== previous.ports) {
514 return true;
515 }
516 if (news.allPorts !== undefined && news.allPorts !== previous.allPorts) {
517 return true;
518 }
519 if (
520 news.backendService !== undefined &&
521 resourceRefOf(news.backendService) !== previous.backendService
522 ) {
523 return true;
524 }
525 if (
526 news.loadBalancingScheme !== undefined &&
527 schemeOf(news.loadBalancingScheme) !== previous.loadBalancingScheme
528 ) {
529 return true;
530 }
531 if (news.network !== undefined && resourceRefOf(news.network) !== previous.network) {
532 return true;
533 }
534 if (news.subnetwork !== undefined && resourceRefOf(news.subnetwork) !== previous.subnetwork) {
535 return true;
536 }
537 if (news.networkTier !== undefined && networkTierOf(news.networkTier) !== previous.networkTier) {
538 return true;
539 }
540 if (news.ipVersion !== undefined && ipVersionOf(news.ipVersion) !== previous.ipVersion) {
541 return true;
542 }
543 if (
544 news.noAutomateDnsZone !== undefined &&
545 news.noAutomateDnsZone !== previous.noAutomateDnsZone
546 ) {
547 return true;
548 }
549 if (
550 news.isMirroringCollector !== undefined &&
551 news.isMirroringCollector !== previous.isMirroringCollector
552 ) {
553 return true;
554 }
555 if (news.serviceLabel !== undefined && (news.serviceLabel ?? "") !== previous.serviceLabel) {
556 return true;
557 }
558 if (
559 news.sourceIpRanges !== undefined &&
560 rangesKey(news.sourceIpRanges) !== previous.sourceIpRanges
561 ) {
562 return true;
563 }
564 if (
565 news.ipCollection !== undefined &&
566 resourceRefOf(news.ipCollection) !== previous.ipCollection
567 ) {
568 return true;
569 }
570 if (
571 news.serviceDirectoryRegistrations !== undefined &&
572 registrationsKey(news.serviceDirectoryRegistrations) !== previous.serviceDirectoryRegistrations
573 ) {
574 return true;
575 }
576 if (
577 schemeOf(news.loadBalancingScheme ?? previous.loadBalancingScheme) === "INTERNAL_MANAGED" &&
578 news.allowGlobalAccess !== undefined &&
579 news.allowGlobalAccess !== previous.allowGlobalAccess
580 ) {
581 return true;
582 }
583 return false;
584 };
585
586 export const ForwardingRuleProvider = () =>
587 Provider.succeed(ForwardingRule, {
588 stables: [
589 "forwardingRuleName",
590 "project",
591 "region",
592 "forwardingRuleId",
593 "selfLink",
594 "ipAddress",
595 "ipProtocol",
596 "portRange",
597 "loadBalancingScheme",
598 "network",
599 "subnetwork",
600 "networkTier",
601 "creationTimestamp",
602 ],
603
604 diff: Effect.fn(function* ({ news, olds, output }) {
605 if (!isResolved(news)) return undefined;
606 const env = yield* GcpEnvironment.current;
607 const previousName = olds.forwardingRuleName ?? output?.forwardingRuleName;
608 const nextName = news.forwardingRuleName ?? previousName;
609 const nameChanged =
610 previousName !== undefined && nextName !== undefined && nextName !== previousName;
611
612 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
613 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
614 const regionChanged = previousRegion !== nextRegion;
615
616 const previous = {
617 description: olds.description ?? output?.description ?? "",
618 ipAddress: olds.ipAddress ?? output?.ipAddress ?? "",
619 ipProtocol: olds.ipProtocol ?? output?.ipProtocol ?? "",
620 portRange: normalizePortRange(olds.portRange ?? output?.portRange),
621 ports: portsKey(olds.ports ?? output?.ports),
622 allPorts: olds.allPorts ?? output?.allPorts ?? false,
623 backendService: resourceRefOf(olds.backendService ?? output?.backendService),
624 loadBalancingScheme: schemeOf(olds.loadBalancingScheme ?? output?.loadBalancingScheme),
625 network: resourceRefOf(olds.network ?? output?.network),
626 subnetwork: resourceRefOf(olds.subnetwork ?? output?.subnetwork),
627 networkTier: networkTierOf(olds.networkTier ?? output?.networkTier),
628 ipVersion: ipVersionOf(olds.ipVersion ?? output?.ipVersion),
629 noAutomateDnsZone: olds.noAutomateDnsZone ?? output?.noAutomateDnsZone ?? false,
630 isMirroringCollector: olds.isMirroringCollector ?? output?.isMirroringCollector ?? false,
631 serviceLabel: olds.serviceLabel ?? output?.serviceLabel ?? "",
632 sourceIpRanges: rangesKey(olds.sourceIpRanges ?? output?.sourceIpRanges),
633 ipCollection: resourceRefOf(olds.ipCollection ?? output?.ipCollection),
634 serviceDirectoryRegistrations: registrationsKey(olds.serviceDirectoryRegistrations),
635 allowGlobalAccess: olds.allowGlobalAccess ?? output?.allowGlobalAccess ?? false,
636 };
637
638 if (nameChanged || regionChanged) {
639 return { action: "replace" as const, deleteFirst: false };
640 }
641 if (immutableChanged(news, previous)) {
642 return { action: "replace" as const, deleteFirst: true };
643 }
644 return undefined;
645 }),
646
647 read: Effect.fn(function* ({ id, olds, output, previous }) {
648 const env = yield* GcpEnvironment.current;
649 const forwardingRuleName = yield* toName(
650 id,
651 olds?.forwardingRuleName,
652 output?.forwardingRuleName,
653 );
654 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
655 const existing = yield* getByName(env.project, region, forwardingRuleName);
656 if (existing === undefined) return undefined;
657 const attrs = toAttrs(existing, env.project);
658 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
659 ? attrs
660 : unownedUnlessPrevious(attrs, previous, "forwardingRuleName");
661 }),
662
663 list: () =>
664 Effect.gen(function* () {
665 const env = yield* GcpEnvironment.current;
666 const pages = yield* compute.aggregatedListForwardingRules
667 .pages({
668 project: env.project,
669 filter: "labels.alchemy-id:*",
670 returnPartialSuccess: true,
671 maxResults: 500,
672 })
673 .pipe(Stream.runCollect);
674 return Array.from(pages).flatMap((page) =>
675 Object.values(page.items ?? {}).flatMap((scoped) =>
676 (scoped?.forwardingRules ?? [])
677 .filter((item) => item.region !== undefined)
678 .filter((item) =>
679 Object.keys(item.labels ?? {}).some((key) => key.startsWith("alchemy-")),
680 )
681 .map((item) => toAttrs(item, env.project)),
682 ),
683 );
684 }),
685
686 reconcile: Effect.fn(function* ({ id, news, output }) {
687 const env = yield* GcpEnvironment.current;
688 const forwardingRuleName = yield* toName(
689 id,
690 news.forwardingRuleName,
691 output?.forwardingRuleName,
692 );
693 const region = normalizeRegion(news.region ?? output?.region, env.region);
694 const desiredLabels = {
695 ...toLabels(news.labels),
696 ...(yield* createInternalLabels(id)),
697 };
698
699 let current = yield* getByName(env.project, region, forwardingRuleName);
700
701 if (current === undefined) {
702 const created = yield* compute
703 .insertForwardingRules({
704 project: env.project,
705 region,
706 body: toInsertBody(forwardingRuleName, news),
707 })
708 .pipe(
709 Effect.flatMap((operation) =>
710 waitRegionOperation(env.project, region, operation, {
711 ignore: ["RESOURCE_ALREADY_EXISTS"],
712 }).pipe(
713 Effect.flatMap(() =>
714 requireForwardingRule(env.project, region, forwardingRuleName),
715 ),
716 ),
717 ),
718 Effect.catchTag("Conflict", () =>
719 requireForwardingRule(env.project, region, forwardingRuleName),
720 ),
721 );
722 current = created ?? undefined;
723 }
724
725 if (current === undefined) {
726 return yield* new ForwardingRuleNotResolved({
727 forwardingRuleName,
728 region,
729 });
730 }
731 const resolved = current;
732
733 if (
734 news.target !== undefined &&
735 resourceRefOf(news.target) !== resourceRefOf(current.target)
736 ) {
737 yield* compute
738 .setTargetForwardingRules({
739 project: env.project,
740 region,
741 forwardingRule: forwardingRuleName,
742 body: { target: news.target },
743 })
744 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
745 current = (yield* getByName(env.project, region, forwardingRuleName)) ?? current;
746 }
747
748 const scheme = schemeOf(current.loadBalancingScheme);
749 if (
750 news.allowGlobalAccess !== undefined &&
751 scheme !== "INTERNAL_MANAGED" &&
752 news.allowGlobalAccess !== (current.allowGlobalAccess === true)
753 ) {
754 yield* compute
755 .patchForwardingRules({
756 project: env.project,
757 region,
758 forwardingRule: forwardingRuleName,
759 body: { allowGlobalAccess: news.allowGlobalAccess },
760 })
761 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
762 current = (yield* getByName(env.project, region, forwardingRuleName)) ?? current;
763 }
764
765 if (
766 news.allowPscGlobalAccess !== undefined &&
767 news.allowPscGlobalAccess !== (current.allowPscGlobalAccess === true)
768 ) {
769 yield* compute
770 .patchForwardingRules({
771 project: env.project,
772 region,
773 forwardingRule: forwardingRuleName,
774 body: {
775 fingerprint: current.fingerprint,
776 allowPscGlobalAccess: news.allowPscGlobalAccess,
777 },
778 })
779 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
780 current = (yield* getByName(env.project, region, forwardingRuleName)) ?? current;
781 }
782
783 const observedLabels = tagRecord(current.labels);
784 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
785 if (upsert.length > 0 || removed.length > 0) {
786 yield* Effect.gen(function* () {
787 const latest = (yield* getByName(env.project, region, forwardingRuleName)) ?? resolved;
788 yield* compute
789 .setLabelsForwardingRules({
790 project: env.project,
791 region,
792 resource: forwardingRuleName,
793 body: {
794 labels: desiredLabels,
795 labelFingerprint: latest.labelFingerprint,
796 },
797 })
798 .pipe(
799 Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)),
800 );
801 }).pipe(
802 Effect.retry({
803 while: (e) => e._tag === "Conflict",
804 times: 5,
805 schedule: Schedule.spaced("1 second"),
806 }),
807 );
808 current = (yield* getByName(env.project, region, forwardingRuleName)) ?? resolved;
809 }
810
811 return toAttrs(current ?? resolved, env.project);
812 }),
813
814 delete: Effect.fn(function* ({ output }) {
815 const env = yield* GcpEnvironment.current;
816 const project = output.project || env.project;
817 const region = normalizeRegion(output.region, env.region);
818 yield* compute
819 .deleteForwardingRules({
820 project,
821 region,
822 forwardingRule: output.forwardingRuleName,
823 })
824 .pipe(
825 Effect.flatMap((operation) =>
826 waitRegionOperation(project, region, operation, {
827 ignore: ["RESOURCE_NOT_FOUND"],
828 }),
829 ),
830 Effect.catchTag("NotFound", () => Effect.void),
831 Effect.retry({
832 while: (e) => e._tag === "Conflict",
833 times: 8,
834 schedule: Schedule.spaced("2 seconds"),
835 }),
836 );
837 yield* waitUntilGone(project, region, output.forwardingRuleName);
838 }),
839 });