@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 759 lines 24.9 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 { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
14 import type { Providers } from "../Providers.ts";
15 import { waitRegionOperation } from "./operations.ts";
16
17 const DEFAULT_NETWORK_ENDPOINT_TYPE = "SERVERLESS";
18 const MAX_NAME_LENGTH = 63;
19
20 export type RegionNetworkEndpointGroupType =
21 | "GCE_VM_IP"
22 | "GCE_VM_IP_PORT"
23 | "GCE_VM_IP_PORTMAP"
24 | "INTERNET_FQDN_PORT"
25 | "INTERNET_IP_PORT"
26 | "NON_GCP_PRIVATE_IP_PORT"
27 | "PRIVATE_SERVICE_CONNECT"
28 | "SERVERLESS";
29
30 export type RegionNetworkEndpointGroupCloudRun = {
31 /** Cloud Run service name (RFC1035). Provide this or `urlMask`. */
32 service?: string;
33 /** Named Cloud Run revision tag. */
34 tag?: string;
35 /** URL mask used to parse `service` and `tag` from request URLs. */
36 urlMask?: string;
37 };
38
39 export type RegionNetworkEndpointGroupAppEngine = {
40 /** App Engine service name. */
41 service?: string;
42 /** App Engine version. */
43 version?: string;
44 /** URL mask used to parse `service` and `version` from request URLs. */
45 urlMask?: string;
46 };
47
48 export type RegionNetworkEndpointGroupCloudFunction = {
49 /** Cloud Function name. Provide this or `urlMask`. */
50 function?: string;
51 /** URL mask used to parse the function name from request URLs. */
52 urlMask?: string;
53 };
54
55 export type RegionNetworkEndpointGroupPscData = {
56 /**
57 * Producer port used to connect a PSC NEG to a specific port on the
58 * producer side. Only valid for `PRIVATE_SERVICE_CONNECT`.
59 */
60 producerPort?: number;
61 /** Address allocated from the given subnetwork for PSC. */
62 consumerPscAddress?: string;
63 /** PSC connection id. */
64 pscConnectionId?: string;
65 /** PSC forwarding-rule connection status. */
66 pscConnectionStatus?: string;
67 };
68
69 export type RegionNetworkEndpointGroupProps = {
70 /**
71 * NEG name. If omitted, a unique RFC1035 name is generated from the
72 * stack, stage, and logical id. Immutable — changing it replaces the
73 * group.
74 */
75 networkEndpointGroupName?: string;
76 /**
77 * Region the NEG lives in. Immutable — changing it replaces the group.
78 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
79 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
80 */
81 region?: string;
82 /**
83 * Optional description. Compute region NEGs have no labels field and no
84 * update API, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
85 * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke.
86 * Immutable — changing the user-facing description replaces the group.
87 */
88 description?: string;
89 /**
90 * Endpoint type. Inferred from `cloudRun` / `appEngine` /
91 * `cloudFunction` / `pscTargetService` when omitted.
92 * @default "SERVERLESS"
93 */
94 networkEndpointType?: RegionNetworkEndpointGroupType | (string & {});
95 /**
96 * Default port when an endpoint omits one. Must not be set for
97 * `SERVERLESS` or `PRIVATE_SERVICE_CONNECT`. Immutable.
98 */
99 defaultPort?: number;
100 /**
101 * VPC network URL or name. Required for internet NEGs. Must not be set
102 * for `SERVERLESS` or `PRIVATE_SERVICE_CONNECT` (except some PSC
103 * producer setups). Immutable.
104 */
105 network?: string;
106 /**
107 * Subnetwork URL or name. Immutable.
108 */
109 subnetwork?: string;
110 /**
111 * User annotations. Immutable — changing them replaces the group.
112 */
113 annotations?: Record<string, string>;
114 /**
115 * Cloud Run serverless config. Only valid when
116 * `networkEndpointType` is `SERVERLESS`. Immutable.
117 */
118 cloudRun?: RegionNetworkEndpointGroupCloudRun;
119 /**
120 * App Engine serverless config. Only valid when
121 * `networkEndpointType` is `SERVERLESS`. Immutable.
122 */
123 appEngine?: RegionNetworkEndpointGroupAppEngine;
124 /**
125 * Cloud Function serverless config. Only valid when
126 * `networkEndpointType` is `SERVERLESS`. Immutable.
127 */
128 cloudFunction?: RegionNetworkEndpointGroupCloudFunction;
129 /**
130 * Target service URL for a Private Service Connect NEG (Google API or
131 * producer service attachment). Immutable.
132 */
133 pscTargetService?: string;
134 /**
135 * PSC-specific settings (`producerPort`). Immutable.
136 */
137 pscData?: RegionNetworkEndpointGroupPscData;
138 };
139
140 export type RegionNetworkEndpointGroup = Resource<
141 "GCP.Compute.RegionNetworkEndpointGroup",
142 RegionNetworkEndpointGroupProps,
143 {
144 /** NEG name. */
145 networkEndpointGroupName: string;
146 /** Project id. */
147 project: string;
148 /** Region short name (`us-central1`). */
149 region: string;
150 /** Endpoint type. */
151 networkEndpointType: string | undefined;
152 /** User description with the Alchemy ownership prefix stripped. */
153 description: string | undefined;
154 /** Default port, if any. */
155 defaultPort: number | undefined;
156 /** Network URL, if any. */
157 network: string | undefined;
158 /** Subnetwork URL, if any. */
159 subnetwork: string | undefined;
160 /** User annotations. */
161 annotations: Record<string, string>;
162 /** Cloud Run config, if this is a Cloud Run serverless NEG. */
163 cloudRun: RegionNetworkEndpointGroupCloudRun | undefined;
164 /** App Engine config, if this is an App Engine serverless NEG. */
165 appEngine: RegionNetworkEndpointGroupAppEngine | undefined;
166 /** Cloud Function config, if this is a Cloud Function serverless NEG. */
167 cloudFunction: RegionNetworkEndpointGroupCloudFunction | undefined;
168 /** PSC target service, if any. */
169 pscTargetService: string | undefined;
170 /** PSC connection data, if any. */
171 pscData: RegionNetworkEndpointGroupPscData | undefined;
172 /** Number of endpoints in the group. */
173 size: number | undefined;
174 /** Server-assigned numeric id. */
175 networkEndpointGroupId: string | undefined;
176 /** Resource self-link. */
177 selfLink: string | undefined;
178 /** RFC3339 creation timestamp. */
179 creationTimestamp: string | undefined;
180 /** Resource kind. */
181 kind: string | undefined;
182 },
183 never,
184 Providers
185 >;
186
187 /**
188 * A regional Compute Engine network endpoint group.
189 *
190 * Regional NEGs back serverless (Cloud Run, App Engine, Cloud Functions),
191 * internet (`INTERNET_IP_PORT` / `INTERNET_FQDN_PORT`), and Private Service
192 * Connect load-balancing backends. The regional collection has no labels
193 * field and no update API — Alchemy stamps ownership into the description
194 * so `list` / nuke can find leaked groups. Name, region, type, network,
195 * serverless config, PSC target, port, annotations, and description are
196 * all immutable (changing any of them replaces the group).
197 *
198 * ### Creating a RegionNetworkEndpointGroup
199 * **Example:** Cloud Run serverless NEG with a URL mask
200 * ```typescript
201 * const neg = yield* GCP.Compute.RegionNetworkEndpointGroup("RunNeg", {
202 * region: "us-central1",
203 * networkEndpointType: "SERVERLESS",
204 * cloudRun: { urlMask: "<service>" },
205 * });
206 * ```
207 *
208 * **Example:** Cloud Run service backend
209 * ```typescript
210 * const neg = yield* GCP.Compute.RegionNetworkEndpointGroup("RunNeg", {
211 * cloudRun: { service: "api" },
212 * });
213 * ```
214 *
215 * ### Internet NEGs
216 * **Example:** Regional internet IP:port NEG
217 * ```typescript
218 * const neg = yield* GCP.Compute.RegionNetworkEndpointGroup("Internet", {
219 * network: "default",
220 * networkEndpointType: "INTERNET_IP_PORT",
221 * defaultPort: 443,
222 * });
223 * ```
224 *
225 * ### Private Service Connect
226 * **Example:** PSC NEG targeting a Google API
227 * ```typescript
228 * const neg = yield* GCP.Compute.RegionNetworkEndpointGroup("Kms", {
229 * networkEndpointType: "PRIVATE_SERVICE_CONNECT",
230 * pscTargetService: "us-central1-cloudkms.googleapis.com",
231 * subnetwork:
232 * "projects/{project}/regions/us-central1/subnetworks/default",
233 * });
234 * ```
235 *
236 * @resource
237 * @category Compute
238 */
239 export const RegionNetworkEndpointGroup = Resource<RegionNetworkEndpointGroup>(
240 "GCP.Compute.RegionNetworkEndpointGroup",
241 );
242
243 export class RegionNetworkEndpointGroupNotResolved extends Data.TaggedError(
244 "GCP.Compute.RegionNetworkEndpointGroupNotResolved",
245 )<{
246 networkEndpointGroupName: string;
247 region: string;
248 }> {}
249
250 export class RegionNetworkEndpointGroupPending extends Data.TaggedError(
251 "GCP.Compute.RegionNetworkEndpointGroupPending",
252 )<{
253 networkEndpointGroupName: string;
254 status: string;
255 }> {}
256
257 const lastSegment = (value: string) => {
258 const trimmed = value.replace(/\/+$/, "");
259 const parts = trimmed.split("/");
260 return parts[parts.length - 1] || trimmed;
261 };
262
263 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
264 lastSegment(region ?? defaultRegion).toLowerCase();
265
266 const resourceRefOf = (value: string | undefined) => {
267 if (!value) return "";
268 return lastSegment(value);
269 };
270
271 const networkUrl = (project: string, network: string) => {
272 if (network.includes("/")) {
273 return network.startsWith("projects/") || network.startsWith("http")
274 ? network
275 : `projects/${project}/${network.replace(/^\//, "")}`;
276 }
277 return `projects/${project}/global/networks/${network}`;
278 };
279
280 const subnetworkUrl = (project: string, region: string, subnetwork: string) => {
281 if (subnetwork.includes("/")) {
282 return subnetwork.startsWith("projects/") || subnetwork.startsWith("http")
283 ? subnetwork
284 : `projects/${project}/${subnetwork.replace(/^\//, "")}`;
285 }
286 return `projects/${project}/regions/${region}/subnetworks/${subnetwork}`;
287 };
288
289 const toName = (id: string, name: string | undefined, existing?: string) =>
290 Effect.gen(function* () {
291 if (name !== undefined) return name;
292 if (existing !== undefined) return existing;
293 const generated = yield* createPhysicalName({
294 id,
295 maxLength: MAX_NAME_LENGTH,
296 lowercase: true,
297 });
298 const rfc = generated.replace(/^[^a-z]+/, "n").replace(/-+$/g, "");
299 return rfc.slice(0, MAX_NAME_LENGTH);
300 });
301
302 const encodeDescription = (
303 labels: Record<string, string>,
304 description: string | undefined,
305 ): string => {
306 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
307 return description ? `${marker}\n${description}` : marker;
308 };
309
310 const parseDescription = (
311 description: string | undefined,
312 ): {
313 labels: Record<string, string>;
314 description: string | undefined;
315 } => {
316 if (!description?.startsWith("[alchemy ")) {
317 return { labels: {}, description };
318 }
319 const end = description.indexOf("]");
320 if (end < 0) return { labels: {}, description };
321 const labels: Record<string, string> = {};
322 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
323 const eq = part.indexOf("=");
324 if (eq > 0) {
325 labels[part.slice(0, eq)] = part.slice(eq + 1);
326 }
327 }
328 const rest = description.slice(end + 1).replace(/^\n/, "");
329 return { labels, description: rest.length > 0 ? rest : undefined };
330 };
331
332 const hasOwnershipMarker = (description: string | undefined) =>
333 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
334
335 const inferType = (props: RegionNetworkEndpointGroupProps): string => {
336 if (props.networkEndpointType) return props.networkEndpointType;
337 if (props.pscTargetService) return "PRIVATE_SERVICE_CONNECT";
338 if (props.cloudRun || props.appEngine || props.cloudFunction) {
339 return "SERVERLESS";
340 }
341 return DEFAULT_NETWORK_ENDPOINT_TYPE;
342 };
343
344 const annotationsOf = (
345 annotations: Record<string, string | undefined> | null | undefined,
346 ): Record<string, string> => tagRecord(annotations);
347
348 const sameAnnotations = (
349 left: Record<string, string> | undefined,
350 right: Record<string, string> | undefined,
351 ) => {
352 const a = annotationsOf(left);
353 const b = annotationsOf(right);
354 const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
355 for (const key of keys) {
356 if (a[key] !== b[key]) return false;
357 }
358 return true;
359 };
360
361 const subsetEqual = (observed: unknown, desired: unknown): boolean => {
362 if (desired === undefined) return true;
363 if (desired === null || observed === null) return desired === observed;
364 if (Array.isArray(desired)) {
365 if (!Array.isArray(observed) || desired.length !== observed.length) {
366 return false;
367 }
368 return desired.every((item, index) => subsetEqual(observed[index], item));
369 }
370 if (typeof desired === "object") {
371 if (typeof observed !== "object" || observed === undefined) return false;
372 const current = observed as Record<string, unknown>;
373 return Object.entries(desired as Record<string, unknown>).every(
374 ([key, value]) => value === undefined || subsetEqual(current[key], value),
375 );
376 }
377 return observed === desired;
378 };
379
380 const toCloudRun = (
381 value: compute.NetworkEndpointGroupCloudRun | undefined,
382 ): RegionNetworkEndpointGroupCloudRun | undefined => {
383 if (value === undefined) return undefined;
384 if (value.service === undefined && value.tag === undefined && value.urlMask === undefined) {
385 return undefined;
386 }
387 return {
388 service: value.service,
389 tag: value.tag,
390 urlMask: value.urlMask,
391 };
392 };
393
394 const toAppEngine = (
395 value: compute.NetworkEndpointGroupAppEngine | undefined,
396 ): RegionNetworkEndpointGroupAppEngine | undefined => {
397 if (value === undefined) return undefined;
398 if (value.service === undefined && value.version === undefined && value.urlMask === undefined) {
399 return undefined;
400 }
401 return {
402 service: value.service,
403 version: value.version,
404 urlMask: value.urlMask,
405 };
406 };
407
408 const toCloudFunction = (
409 value: compute.NetworkEndpointGroupCloudFunction | undefined,
410 ): RegionNetworkEndpointGroupCloudFunction | undefined => {
411 if (value === undefined) return undefined;
412 if (value.function === undefined && value.urlMask === undefined) {
413 return undefined;
414 }
415 return {
416 function: value.function,
417 urlMask: value.urlMask,
418 };
419 };
420
421 const toPscData = (
422 value: compute.NetworkEndpointGroupPscData | undefined,
423 ): RegionNetworkEndpointGroupPscData | undefined => {
424 if (value === undefined) return undefined;
425 return {
426 producerPort: value.producerPort,
427 consumerPscAddress: value.consumerPscAddress,
428 pscConnectionId: value.pscConnectionId,
429 pscConnectionStatus: value.pscConnectionStatus,
430 };
431 };
432
433 const toBody = (
434 project: string,
435 region: string,
436 networkEndpointGroupName: string,
437 props: RegionNetworkEndpointGroupProps,
438 ownership: Record<string, string>,
439 ): compute.NetworkEndpointGroup => {
440 const networkEndpointType = inferType(props);
441 const body: compute.NetworkEndpointGroup = {
442 name: networkEndpointGroupName,
443 description: encodeDescription(ownership, props.description),
444 networkEndpointType,
445 defaultPort: props.defaultPort,
446 annotations:
447 props.annotations !== undefined && Object.keys(props.annotations).length > 0
448 ? props.annotations
449 : undefined,
450 cloudRun: props.cloudRun,
451 appEngine: props.appEngine,
452 cloudFunction: props.cloudFunction,
453 pscTargetService: props.pscTargetService,
454 };
455 if (props.network !== undefined) {
456 body.network = networkUrl(project, props.network);
457 }
458 if (props.subnetwork !== undefined) {
459 body.subnetwork = subnetworkUrl(project, region, props.subnetwork);
460 }
461 if (props.pscData?.producerPort !== undefined) {
462 body.pscData = { producerPort: props.pscData.producerPort };
463 }
464 return body;
465 };
466
467 const toAttrs = (
468 group: compute.NetworkEndpointGroup,
469 project: string,
470 ): RegionNetworkEndpointGroup["Attributes"] => {
471 const parsed = parseDescription(group.description);
472 return {
473 networkEndpointGroupName: group.name ?? "",
474 project,
475 region: lastSegment(group.region ?? "").toLowerCase(),
476 networkEndpointType: group.networkEndpointType,
477 description: parsed.description,
478 defaultPort: group.defaultPort,
479 network: group.network,
480 subnetwork: group.subnetwork,
481 annotations: annotationsOf(group.annotations),
482 cloudRun: toCloudRun(group.cloudRun),
483 appEngine: toAppEngine(group.appEngine),
484 cloudFunction: toCloudFunction(group.cloudFunction),
485 pscTargetService: group.pscTargetService,
486 pscData: toPscData(group.pscData),
487 size: group.size,
488 networkEndpointGroupId: group.id,
489 selfLink: group.selfLink,
490 creationTimestamp: group.creationTimestamp,
491 kind: group.kind,
492 };
493 };
494
495 const getByName = (project: string, region: string, networkEndpointGroup: string) =>
496 compute
497 .getRegionNetworkEndpointGroups({
498 project,
499 region,
500 networkEndpointGroup,
501 })
502 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
503
504 const requireGroup = (project: string, region: string, networkEndpointGroupName: string) =>
505 getByName(project, region, networkEndpointGroupName).pipe(
506 Effect.flatMap((group) =>
507 group
508 ? Effect.succeed(group)
509 : Effect.fail(
510 new RegionNetworkEndpointGroupNotResolved({
511 networkEndpointGroupName,
512 region,
513 }),
514 ),
515 ),
516 Effect.retry({
517 while: (e) => e._tag === "GCP.Compute.RegionNetworkEndpointGroupNotResolved",
518 schedule: Schedule.spaced("1 second"),
519 times: 8,
520 }),
521 );
522
523 const waitUntilGone = (project: string, region: string, networkEndpointGroupName: string) =>
524 getByName(project, region, networkEndpointGroupName).pipe(
525 Effect.flatMap((group) =>
526 group === undefined
527 ? Effect.void
528 : Effect.fail(
529 new RegionNetworkEndpointGroupPending({
530 networkEndpointGroupName,
531 status: "EXISTS",
532 }),
533 ),
534 ),
535 Effect.retry({
536 while: (e) => e._tag === "GCP.Compute.RegionNetworkEndpointGroupPending",
537 times: 10,
538 schedule: Schedule.spaced("2 seconds"),
539 }),
540 );
541
542 const immutableChanged = (
543 news: RegionNetworkEndpointGroupProps,
544 olds: Partial<RegionNetworkEndpointGroupProps> | undefined,
545 output: RegionNetworkEndpointGroup["Attributes"] | undefined,
546 ) => {
547 const previousType =
548 (olds !== undefined ? inferType(olds) : undefined) ??
549 output?.networkEndpointType ??
550 DEFAULT_NETWORK_ENDPOINT_TYPE;
551 if (inferType(news) !== previousType) return true;
552
553 const previousDescription = olds?.description ?? output?.description ?? "";
554 if ((news.description ?? "") !== previousDescription) return true;
555
556 if (
557 news.defaultPort !== undefined &&
558 news.defaultPort !== (olds?.defaultPort ?? output?.defaultPort)
559 ) {
560 return true;
561 }
562
563 if (
564 news.network !== undefined &&
565 resourceRefOf(news.network) !== resourceRefOf(olds?.network ?? output?.network)
566 ) {
567 return true;
568 }
569
570 if (
571 news.subnetwork !== undefined &&
572 resourceRefOf(news.subnetwork) !== resourceRefOf(olds?.subnetwork ?? output?.subnetwork)
573 ) {
574 return true;
575 }
576
577 if (
578 news.pscTargetService !== undefined &&
579 news.pscTargetService !== (olds?.pscTargetService ?? output?.pscTargetService)
580 ) {
581 return true;
582 }
583
584 if (
585 news.annotations !== undefined &&
586 !sameAnnotations(news.annotations, olds?.annotations ?? output?.annotations)
587 ) {
588 return true;
589 }
590
591 if (
592 news.cloudRun !== undefined &&
593 !subsetEqual(olds?.cloudRun ?? output?.cloudRun, news.cloudRun)
594 ) {
595 return true;
596 }
597 if (
598 news.appEngine !== undefined &&
599 !subsetEqual(olds?.appEngine ?? output?.appEngine, news.appEngine)
600 ) {
601 return true;
602 }
603 if (
604 news.cloudFunction !== undefined &&
605 !subsetEqual(olds?.cloudFunction ?? output?.cloudFunction, news.cloudFunction)
606 ) {
607 return true;
608 }
609 if (
610 news.pscData?.producerPort !== undefined &&
611 news.pscData.producerPort !== (olds?.pscData?.producerPort ?? output?.pscData?.producerPort)
612 ) {
613 return true;
614 }
615 return false;
616 };
617
618 export const RegionNetworkEndpointGroupProvider = () =>
619 Provider.succeed(RegionNetworkEndpointGroup, {
620 stables: [
621 "networkEndpointGroupName",
622 "project",
623 "region",
624 "networkEndpointType",
625 "networkEndpointGroupId",
626 "selfLink",
627 "creationTimestamp",
628 ],
629
630 diff: Effect.fn(function* ({ news, olds, output }) {
631 if (!isResolved(news)) return undefined;
632 const env = yield* GcpEnvironment.current;
633 const previousName = olds.networkEndpointGroupName ?? output?.networkEndpointGroupName;
634 const nextName = news.networkEndpointGroupName ?? previousName;
635 const nameChanged =
636 previousName !== undefined && nextName !== undefined && nextName !== previousName;
637
638 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
639 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
640 const regionChanged = previousRegion !== nextRegion;
641
642 if (nameChanged || regionChanged) {
643 return { action: "replace" as const, deleteFirst: false };
644 }
645 if (immutableChanged(news, olds, output)) {
646 return { action: "replace" as const, deleteFirst: true };
647 }
648 return undefined;
649 }),
650
651 read: Effect.fn(function* ({ id, olds, output, previous }) {
652 const env = yield* GcpEnvironment.current;
653 const networkEndpointGroupName = yield* toName(
654 id,
655 olds?.networkEndpointGroupName,
656 output?.networkEndpointGroupName,
657 );
658 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
659 const existing = yield* getByName(env.project, region, networkEndpointGroupName);
660 if (existing === undefined) return undefined;
661 const attrs = toAttrs(existing, env.project);
662 const { labels } = parseDescription(existing.description);
663 return (yield* hasAlchemyLabels(id, labels))
664 ? attrs
665 : unownedUnlessPrevious(attrs, previous, "networkEndpointGroupName");
666 }),
667
668 list: () =>
669 Effect.gen(function* () {
670 const env = yield* GcpEnvironment.current;
671 const pages = yield* compute.aggregatedListNetworkEndpointGroups
672 .pages({
673 project: env.project,
674 returnPartialSuccess: true,
675 maxResults: 500,
676 })
677 .pipe(Stream.runCollect);
678 return Array.from(pages).flatMap((page) =>
679 Object.values(page.items ?? {}).flatMap((scoped) =>
680 (scoped?.networkEndpointGroups ?? [])
681 .filter((item) => item.region !== undefined && item.zone === undefined)
682 .filter((item) => hasOwnershipMarker(item.description))
683 .map((item) => toAttrs(item, env.project)),
684 ),
685 );
686 }),
687
688 reconcile: Effect.fn(function* ({ id, news, output }) {
689 const env = yield* GcpEnvironment.current;
690 const networkEndpointGroupName = yield* toName(
691 id,
692 news.networkEndpointGroupName,
693 output?.networkEndpointGroupName,
694 );
695 const region = normalizeRegion(news.region ?? output?.region, env.region);
696 const ownership = yield* createInternalLabels(id);
697 const desired = toBody(env.project, region, networkEndpointGroupName, news, ownership);
698
699 let current = yield* getByName(env.project, region, networkEndpointGroupName);
700
701 if (current === undefined) {
702 const created = yield* compute
703 .insertRegionNetworkEndpointGroups({
704 project: env.project,
705 region,
706 body: desired,
707 })
708 .pipe(
709 Effect.flatMap((operation) =>
710 waitRegionOperation(env.project, region, operation, {
711 ignore: ["RESOURCE_ALREADY_EXISTS"],
712 }).pipe(
713 Effect.flatMap(() => requireGroup(env.project, region, networkEndpointGroupName)),
714 ),
715 ),
716 Effect.catchTag("Conflict", () =>
717 getByName(env.project, region, networkEndpointGroupName),
718 ),
719 );
720 current = created ?? undefined;
721 }
722
723 if (current === undefined) {
724 return yield* new RegionNetworkEndpointGroupNotResolved({
725 networkEndpointGroupName,
726 region,
727 });
728 }
729
730 return toAttrs(current, env.project);
731 }),
732
733 delete: Effect.fn(function* ({ output }) {
734 const env = yield* GcpEnvironment.current;
735 const project = output.project || env.project;
736 const region = normalizeRegion(output.region, env.region);
737 if (!output.networkEndpointGroupName) return;
738 yield* compute
739 .deleteRegionNetworkEndpointGroups({
740 project,
741 region,
742 networkEndpointGroup: output.networkEndpointGroupName,
743 })
744 .pipe(
745 Effect.flatMap((operation) =>
746 waitRegionOperation(project, region, operation, {
747 ignore: ["RESOURCE_NOT_FOUND"],
748 }),
749 ),
750 Effect.catchTag("NotFound", () => Effect.void),
751 Effect.retry({
752 while: (e) => e._tag === "Conflict",
753 times: 8,
754 schedule: Schedule.spaced("2 seconds"),
755 }),
756 );
757 yield* waitUntilGone(project, region, output.networkEndpointGroupName);
758 }),
759 });