@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 725 lines 25.4 KB
Raw
1 import * as networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitForOperation } from "./internal.ts";
22
23 const DEFAULT_LOCATION = "global";
24 const DEFAULT_USAGE = "FOR_VPC" satisfies networkconnectivity.InternalRangeUsageEnum;
25 const DEFAULT_PEERING = "FOR_SELF" satisfies networkconnectivity.InternalRangePeeringEnum;
26 const MAX_NAME_LENGTH = 63;
27
28 export type InternalRangeUsage = networkconnectivity.InternalRangeUsageEnum | (string & {});
29 export type InternalRangePeering = networkconnectivity.InternalRangePeeringEnum | (string & {});
30 export type InternalRangeOverlap =
31 | networkconnectivity.InternalRangeOverlapsItemEnum
32 | (string & {});
33 export type InternalRangeAllocationStrategy =
34 | networkconnectivity.AllocationOptionsAllocationStrategyEnum
35 | (string & {});
36
37 export type InternalRangeAllocationOptions = {
38 /**
39 * Auto-allocation strategy used when `ipCidrRange` is omitted and
40 * `prefixLength` is set.
41 */
42 allocationStrategy?: InternalRangeAllocationStrategy;
43 /**
44 * Maximum expected parallelism of range-creation requests against the
45 * same peered space. Required when `allocationStrategy` is
46 * `RANDOM_FIRST_N_AVAILABLE`.
47 */
48 firstAvailableRangesLookupSize?: number;
49 };
50
51 export type InternalRangeMigration = {
52 /**
53 * Source subnet URI, e.g.
54 * `/projects/{project}/regions/{region}/subnetworks/{subnet}`.
55 * Required when `usage` is `FOR_MIGRATION`.
56 */
57 source: string;
58 /**
59 * Target subnet URI. The target project may differ (peer-network
60 * migration).
61 */
62 target: string;
63 };
64
65 export type InternalRangeProps = {
66 /**
67 * Internal range id (the `{internal_range}` segment of
68 * `projects/{project}/locations/{location}/internalRanges/{internal_range}`).
69 * If omitted, a unique RFC1035 name is generated from the stack, stage,
70 * and logical id. Must be 1-63 characters and match
71 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the
72 * range.
73 */
74 internalRangeId?: string;
75 /**
76 * Location of the range. Internal ranges are global — always `"global"`.
77 * Immutable — changing it replaces the range. `GLOBAL` is accepted and
78 * normalized to `global`.
79 * @default "global"
80 */
81 location?: string;
82 /**
83 * VPC network to reserve the range in. Accepts a name (`app-vpc`), a
84 * resource path (`projects/{project}/global/networks/{network}`), or a
85 * Compute self-link. Immutable — changing it replaces the range.
86 */
87 network: string;
88 /**
89 * How the range may be used. `FOR_VPC` can be associated with VPC
90 * resources; `EXTERNAL_TO_VPC` blocks space (on-prem, advertised
91 * routes); `FOR_MIGRATION` locks a subnet during peer-VPC migration.
92 * Immutable — changing it replaces the range.
93 * @default "FOR_VPC"
94 */
95 usage?: InternalRangeUsage;
96 /**
97 * Peering behavior. `FOR_SELF` (default) is used in this VPC and
98 * visible to peers; `FOR_PEER` donates the range to peers;
99 * `NOT_SHARED` keeps it local. Immutable — changing it replaces the
100 * range.
101 * @default "FOR_SELF"
102 */
103 peering?: InternalRangePeering;
104 /**
105 * Explicit CIDR this range reserves (e.g. `"10.0.0.0/24"`). Required
106 * unless `prefixLength` is set. IPv6 ranges must set this field.
107 */
108 ipCidrRange?: string;
109 /**
110 * Auto-allocate a free block of this prefix length when
111 * `ipCidrRange` is omitted. If both are set, the sizes must match.
112 * Updates may resize the range.
113 */
114 prefixLength?: number;
115 /**
116 * Address spaces to search when auto-allocating. Defaults to RFC1918
117 * (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`).
118 */
119 targetCidrRange?: string[];
120 /**
121 * CIDR blocks to skip during auto-allocation, without reserving them.
122 */
123 excludeCidrRanges?: string[];
124 /**
125 * Overlaps to allow (`OVERLAP_ROUTE_RANGE`,
126 * `OVERLAP_EXISTING_SUBNET_RANGE`).
127 */
128 overlaps?: InternalRangeOverlap[];
129 /**
130 * Human-readable description of the range.
131 */
132 description?: string;
133 /**
134 * User labels. Alchemy ownership labels are merged in automatically.
135 */
136 labels?: Record<string, string>;
137 /**
138 * When true, only `labels` and `description` can change after create.
139 * Immutable — changing it replaces the range.
140 * @default false
141 */
142 immutable?: boolean;
143 /**
144 * Auto-allocation options. Set only when allocating by `prefixLength`.
145 */
146 allocationOptions?: InternalRangeAllocationOptions;
147 /**
148 * Source and target subnet URIs. Required (and only valid) when
149 * `usage` is `FOR_MIGRATION`. Immutable — changing it replaces the
150 * range.
151 */
152 migration?: InternalRangeMigration;
153 };
154
155 export type InternalRange = Resource<
156 "GCP.NetworkConnectivity.InternalRange",
157 InternalRangeProps,
158 {
159 /** Full resource name `projects/{project}/locations/{location}/internalRanges/{internal_range}`. */
160 name: string;
161 /** Internal range id (last path segment). */
162 internalRangeId: string;
163 /** Project id. */
164 project: string;
165 /** Location id. Internal ranges are global — always `"global"`. */
166 location: string;
167 /** Network URI as reported by the API. */
168 network: string | undefined;
169 /** VPC network id (last path segment). */
170 networkName: string | undefined;
171 /** Usage mode. */
172 usage: string | undefined;
173 /** Peering mode. */
174 peering: string | undefined;
175 /** Allocated CIDR. */
176 ipCidrRange: string | undefined;
177 /** Prefix length used for allocation or reported size. */
178 prefixLength: number | undefined;
179 /** Auto-allocation search spaces. */
180 targetCidrRange: ReadonlyArray<string>;
181 /** CIDRs excluded from auto-allocation. */
182 excludeCidrRanges: ReadonlyArray<string>;
183 /** Allowed overlap types. */
184 overlaps: ReadonlyArray<string>;
185 /** User-provided description. */
186 description: string | undefined;
187 /** User labels (Alchemy ownership labels stripped). */
188 labels: Record<string, string>;
189 /** Whether the range is immutable besides labels/description. */
190 immutable: boolean;
191 /** Auto-allocation options, if set. */
192 allocationOptions: InternalRangeAllocationOptions | undefined;
193 /** Migration endpoints, if set. */
194 migration: InternalRangeMigration | undefined;
195 /** Resources currently using this range (output-only). */
196 users: ReadonlyArray<string>;
197 /** RFC3339 creation timestamp. */
198 createTime: string | undefined;
199 /** RFC3339 last-update timestamp. */
200 updateTime: string | undefined;
201 },
202 never,
203 Providers
204 >;
205
206 /**
207 * A Network Connectivity internal range — an IPAM reservation inside a
208 * VPC, with usage and peering behavior.
209 *
210 * Ranges live at `locations/global`. `internalRangeId`, `location`,
211 * `network`, `usage`, `peering`, `immutable`, and `migration` are
212 * immutable. Description, labels, CIDR, prefix length, overlaps, target
213 * CIDRs, exclude CIDRs, and allocation options update in place.
214 *
215 * ### Creating an Internal Range
216 * **Example:** Generated name on a custom VPC
217 * ```typescript
218 * const network = yield* GCP.Compute.Network("Vpc", {
219 * autoCreateSubnetworks: false,
220 * });
221 * const range = yield* GCP.NetworkConnectivity.InternalRange("Reserved", {
222 * network: network.selfLink ?? network.networkName,
223 * usage: "FOR_VPC",
224 * peering: "FOR_SELF",
225 * ipCidrRange: "10.0.0.0/24",
226 * });
227 * ```
228 *
229 * **Example:** Explicit id, labels, and description
230 * ```typescript
231 * const range = yield* GCP.NetworkConnectivity.InternalRange("Reserved", {
232 * internalRangeId: "app-reserved",
233 * network: "projects/{project}/global/networks/app-vpc",
234 * usage: "FOR_VPC",
235 * peering: "FOR_SELF",
236 * ipCidrRange: "10.0.0.0/24",
237 * description: "app subnet space",
238 * labels: { env: "prod" },
239 * });
240 * ```
241 *
242 * ### Auto-allocation
243 * **Example:** Free /24 from a target space
244 * ```typescript
245 * const range = yield* GCP.NetworkConnectivity.InternalRange("Reserved", {
246 * network: network.networkName,
247 * usage: "FOR_VPC",
248 * peering: "FOR_SELF",
249 * prefixLength: 24,
250 * targetCidrRange: ["192.168.0.0/16"],
251 * allocationOptions: { allocationStrategy: "FIRST_SMALLEST_FITTING" },
252 * });
253 * ```
254 *
255 * ### External reservation
256 * **Example:** Block on-prem space
257 * ```typescript
258 * const range = yield* GCP.NetworkConnectivity.InternalRange("OnPrem", {
259 * network: network.networkName,
260 * usage: "EXTERNAL_TO_VPC",
261 * peering: "FOR_SELF",
262 * ipCidrRange: "172.16.0.0/24",
263 * labels: { role: "on-prem" },
264 * });
265 * ```
266 *
267 * ### Updating an Internal Range
268 * **Example:** Description and labels
269 * ```typescript
270 * const range = yield* GCP.NetworkConnectivity.InternalRange("Reserved", {
271 * internalRangeId: "app-reserved",
272 * network: "app-vpc",
273 * usage: "FOR_VPC",
274 * peering: "FOR_SELF",
275 * ipCidrRange: "10.0.0.0/24",
276 * description: "app subnet space v2",
277 * labels: { env: "prod", role: "ipam" },
278 * });
279 * ```
280 *
281 * @resource
282 * @category NetworkConnectivity
283 */
284 export const InternalRange = Resource<InternalRange>("GCP.NetworkConnectivity.InternalRange");
285
286 export class InternalRangeNotResolved extends Data.TaggedError(
287 "GCP.NetworkConnectivity.InternalRangeNotResolved",
288 )<{
289 resourceName: string;
290 }> {}
291
292 export class InternalRangeRangeMissing extends Data.TaggedError(
293 "GCP.NetworkConnectivity.InternalRangeRangeMissing",
294 )<{
295 resourceName: string;
296 message: string;
297 }> {}
298
299 export class InternalRangeStillExists extends Data.TaggedError(
300 "GCP.NetworkConnectivity.InternalRangeStillExists",
301 )<{
302 resourceName: string;
303 }> {}
304
305 const lastSegment = (value: string) => {
306 const trimmed = value.replace(/\/+$/, "");
307 const parts = trimmed.split("/");
308 return parts[parts.length - 1] || trimmed;
309 };
310
311 const rfc1035 = (name: string): string => {
312 let next = name
313 .toLowerCase()
314 .replace(/[^a-z0-9-]/g, "-")
315 .replace(/-+/g, "-")
316 .replace(/^-+/, "")
317 .replace(/-+$/, "");
318 if (!/^[a-z]/.test(next)) {
319 next = `r${next}`;
320 }
321 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
322 return next.length > 0 ? next : "internalrange";
323 };
324
325 const normalizeLocation = (location: string | undefined) =>
326 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
327
328 const normalizeUsage = (usage: string | undefined) => (usage ?? DEFAULT_USAGE).toUpperCase();
329
330 const normalizePeering = (peering: string | undefined) =>
331 (peering ?? DEFAULT_PEERING).toUpperCase();
332
333 const networkNameOf = (network: string | undefined) =>
334 network === undefined || network.length === 0 ? undefined : lastSegment(network);
335
336 const toNetworkResource = (project: string, network: string) => {
337 const trimmed = network.trim();
338 if (trimmed.includes("/")) return trimmed;
339 return `projects/${project}/global/networks/${trimmed}`;
340 };
341
342 const resourceName = (project: string, location: string, internalRangeId: string) =>
343 `projects/${project}/locations/${location}/internalRanges/${internalRangeId}`;
344
345 const parentOf = (project: string, location: string) => `projects/${project}/locations/${location}`;
346
347 const parseName = (name: string) => {
348 const parts = name.split("/").filter((part) => part.length > 0);
349 const rangesAt = parts.lastIndexOf("internalRanges");
350 const locationsAt = parts.lastIndexOf("locations");
351 const projectsAt = parts.lastIndexOf("projects");
352 return {
353 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
354 location:
355 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
356 internalRangeId:
357 rangesAt >= 0 && parts[rangesAt + 1] ? parts[rangesAt + 1]! : lastSegment(name),
358 };
359 };
360
361 const userLabels = (
362 labels: Record<string, string | undefined> | null | undefined,
363 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
364
365 const toId = (id: string, internalRangeId: string | undefined, existing?: string) =>
366 Effect.gen(function* () {
367 if (internalRangeId !== undefined) return internalRangeId;
368 if (existing !== undefined) return existing;
369 return rfc1035(
370 yield* createPhysicalName({
371 id,
372 maxLength: MAX_NAME_LENGTH,
373 lowercase: true,
374 }),
375 );
376 });
377
378 const toAllocationOptions = (
379 options: networkconnectivity.AllocationOptions | undefined,
380 ): InternalRangeAllocationOptions | undefined => {
381 if (options === undefined) return undefined;
382 if (
383 options.allocationStrategy === undefined &&
384 options.firstAvailableRangesLookupSize === undefined
385 ) {
386 return undefined;
387 }
388 return {
389 allocationStrategy: options.allocationStrategy,
390 firstAvailableRangesLookupSize: options.firstAvailableRangesLookupSize,
391 };
392 };
393
394 const toMigration = (
395 migration: networkconnectivity.Migration | undefined,
396 ): InternalRangeMigration | undefined => {
397 if (
398 migration === undefined ||
399 (migration.source === undefined && migration.target === undefined)
400 ) {
401 return undefined;
402 }
403 return {
404 source: migration.source ?? "",
405 target: migration.target ?? "",
406 };
407 };
408
409 const toAttrs = (range: networkconnectivity.InternalRange, project: string) => {
410 const name = range.name ?? "";
411 const parsed = parseName(name);
412 return {
413 name,
414 internalRangeId: parsed.internalRangeId,
415 project: parsed.project || project,
416 location: parsed.location || DEFAULT_LOCATION,
417 network: range.network,
418 networkName: networkNameOf(range.network),
419 usage: range.usage,
420 peering: range.peering,
421 ipCidrRange: range.ipCidrRange,
422 prefixLength: range.prefixLength,
423 targetCidrRange: range.targetCidrRange ?? [],
424 excludeCidrRanges: range.excludeCidrRanges ?? [],
425 overlaps: range.overlaps ?? [],
426 description: range.description,
427 labels: userLabels(range.labels),
428 immutable: range.immutable === true,
429 allocationOptions: toAllocationOptions(range.allocationOptions),
430 migration: toMigration(range.migration),
431 users: range.users ?? [],
432 createTime: range.createTime,
433 updateTime: range.updateTime,
434 };
435 };
436
437 const getByName = (name: string) =>
438 networkconnectivity
439 .getProjectsLocationsInternalRanges({ name })
440 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
441
442 const waitUntilExists = (name: string) =>
443 getByName(name).pipe(
444 Effect.flatMap((range) =>
445 range
446 ? Effect.succeed(range)
447 : Effect.fail(new InternalRangeNotResolved({ resourceName: name })),
448 ),
449 Effect.retry({
450 while: (error) => error._tag === "GCP.NetworkConnectivity.InternalRangeNotResolved",
451 times: 10,
452 schedule: Schedule.spaced("1 second"),
453 }),
454 );
455
456 const waitUntilGone = (name: string) =>
457 getByName(name).pipe(
458 Effect.flatMap((range) =>
459 range === undefined
460 ? Effect.void
461 : Effect.fail(new InternalRangeStillExists({ resourceName: name })),
462 ),
463 Effect.retry({
464 while: (error) => error._tag === "GCP.NetworkConnectivity.InternalRangeStillExists",
465 times: 10,
466 schedule: Schedule.spaced("1 second"),
467 }),
468 );
469
470 const listOwnedInternalRanges = (parent: string, project: string) =>
471 networkconnectivity.listProjectsLocationsInternalRanges
472 .pages({
473 parent,
474 pageSize: 1000,
475 })
476 .pipe(
477 Stream.flatMap((page) => Stream.fromIterable(page.internalRanges ?? [])),
478 Stream.filter((range) =>
479 Object.keys(range.labels ?? {}).some((key) => key.startsWith("alchemy-")),
480 ),
481 Stream.map((range) => toAttrs(range, project)),
482 Stream.runCollect,
483 Effect.map((chunk) => Array.from(chunk)),
484 Effect.catchTag("NotFound", () => Effect.succeed([])),
485 );
486
487 const sameList = (left?: readonly string[], right?: readonly string[]) =>
488 [...(left ?? [])].sort().join("\0") === [...(right ?? [])].sort().join("\0");
489
490 const sameAllocation = (
491 left: InternalRangeAllocationOptions | undefined,
492 right: networkconnectivity.AllocationOptions | undefined,
493 ) =>
494 (left?.allocationStrategy ?? "") === (right?.allocationStrategy ?? "") &&
495 (left?.firstAvailableRangesLookupSize ?? undefined) ===
496 (right?.firstAvailableRangesLookupSize ?? undefined);
497
498 const sameMigration = (
499 left: InternalRangeMigration | undefined,
500 right: InternalRangeMigration | undefined,
501 ) =>
502 (left?.source ?? "") === (right?.source ?? "") && (left?.target ?? "") === (right?.target ?? "");
503
504 const toCreateBody = (
505 news: InternalRangeProps,
506 project: string,
507 desiredLabels: Record<string, string>,
508 ): networkconnectivity.InternalRange => ({
509 description: news.description,
510 labels: desiredLabels,
511 network: toNetworkResource(project, news.network),
512 usage: news.usage ?? DEFAULT_USAGE,
513 peering: news.peering ?? DEFAULT_PEERING,
514 ipCidrRange: news.ipCidrRange,
515 prefixLength: news.prefixLength,
516 targetCidrRange: news.targetCidrRange,
517 excludeCidrRanges: news.excludeCidrRanges,
518 overlaps: news.overlaps,
519 immutable: news.immutable,
520 allocationOptions: news.allocationOptions,
521 migration: news.migration,
522 });
523
524 export const InternalRangeProvider = () =>
525 Provider.succeed(InternalRange, {
526 stables: ["name", "internalRangeId", "project", "location", "networkName", "createTime"],
527
528 diff: Effect.fn(function* ({ news, olds, output }) {
529 if (!isResolved(news)) return undefined;
530
531 const previousId = olds?.internalRangeId ?? output?.internalRangeId;
532 const nextId = news.internalRangeId ?? previousId;
533 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
534
535 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
536 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
537 const locationChanged = previousLocation !== nextLocation;
538
539 const previousNetwork = networkNameOf(
540 olds?.network ?? output?.networkName ?? output?.network,
541 );
542 const nextNetwork = networkNameOf(news.network ?? previousNetwork);
543 const networkChanged =
544 previousNetwork !== undefined &&
545 nextNetwork !== undefined &&
546 previousNetwork !== nextNetwork;
547
548 const previousUsage = normalizeUsage(olds?.usage ?? output?.usage);
549 const nextUsage = normalizeUsage(news.usage ?? olds?.usage ?? output?.usage);
550 const usageChanged = previousUsage !== nextUsage;
551
552 const previousPeering = normalizePeering(olds?.peering ?? output?.peering);
553 const nextPeering = normalizePeering(news.peering ?? olds?.peering ?? output?.peering);
554 const peeringChanged = previousPeering !== nextPeering;
555
556 const previousImmutable = olds?.immutable ?? output?.immutable ?? false;
557 const nextImmutable = news.immutable ?? previousImmutable;
558 const immutableChanged = previousImmutable !== nextImmutable;
559
560 const previousMigration = olds?.migration ?? output?.migration;
561 const nextMigration = news.migration ?? previousMigration;
562 const migrationChanged = !sameMigration(previousMigration, nextMigration);
563
564 if (
565 !idChanged &&
566 !locationChanged &&
567 !networkChanged &&
568 !usageChanged &&
569 !peeringChanged &&
570 !immutableChanged &&
571 !migrationChanged
572 ) {
573 return undefined;
574 }
575
576 return {
577 action: "replace" as const,
578 deleteFirst:
579 !idChanged && !locationChanged && previousId !== undefined && nextId === previousId,
580 };
581 }),
582
583 read: Effect.fn(function* ({ id, olds, output }) {
584 const env = yield* GcpEnvironment.current;
585 const internalRangeId = yield* toId(id, olds?.internalRangeId, output?.internalRangeId);
586 const location = normalizeLocation(olds?.location ?? output?.location);
587 const name = output?.name ?? resourceName(env.project, location, internalRangeId);
588 const existing = yield* getByName(name);
589 if (existing === undefined) return undefined;
590 const attrs = toAttrs(existing, env.project);
591 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
592 }),
593
594 list: () =>
595 Effect.gen(function* () {
596 const env = yield* GcpEnvironment.current;
597 const aggregated = yield* listOwnedInternalRanges(parentOf(env.project, "-"), env.project);
598 if (aggregated.length > 0) return aggregated;
599 return yield* listOwnedInternalRanges(parentOf(env.project, DEFAULT_LOCATION), env.project);
600 }),
601
602 reconcile: Effect.fn(function* ({ id, news, output }) {
603 const env = yield* GcpEnvironment.current;
604 const internalRangeId = yield* toId(id, news.internalRangeId, output?.internalRangeId);
605 const location = normalizeLocation(news.location ?? output?.location);
606 const name = resourceName(env.project, location, internalRangeId);
607 const desiredLabels = {
608 ...toLabels(news.labels),
609 ...(yield* createInternalLabels(id)),
610 };
611
612 let current = yield* getByName(name);
613
614 if (current === undefined) {
615 if (news.ipCidrRange === undefined && news.prefixLength === undefined) {
616 return yield* new InternalRangeRangeMissing({
617 resourceName: name,
618 message: "InternalRange requires ipCidrRange or prefixLength on create",
619 });
620 }
621 const created = yield* networkconnectivity
622 .createProjectsLocationsInternalRanges({
623 parent: parentOf(env.project, location),
624 internalRangeId,
625 body: toCreateBody(news, env.project, desiredLabels),
626 })
627 .pipe(
628 Effect.retry({
629 while: (error) => error._tag === "Conflict",
630 times: 5,
631 schedule: Schedule.spaced("2 seconds"),
632 }),
633 Effect.catchTag("Conflict", () => Effect.undefined),
634 );
635 if (created !== undefined) {
636 yield* waitForOperation(created);
637 }
638 current = yield* waitUntilExists(name);
639 }
640
641 if (current === undefined) {
642 return yield* new InternalRangeNotResolved({ resourceName: name });
643 }
644
645 const observedLabels = tagRecord(current.labels);
646 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
647 const labelsChanged = upsert.length > 0 || removed.length > 0;
648 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
649 const cidrChanged =
650 news.ipCidrRange !== undefined && (current.ipCidrRange ?? "") !== news.ipCidrRange;
651 const prefixChanged =
652 news.prefixLength !== undefined && current.prefixLength !== news.prefixLength;
653 const targetChanged =
654 news.targetCidrRange !== undefined &&
655 !sameList(news.targetCidrRange, current.targetCidrRange);
656 const excludeChanged =
657 news.excludeCidrRanges !== undefined &&
658 !sameList(news.excludeCidrRanges, current.excludeCidrRanges);
659 const overlapsChanged =
660 news.overlaps !== undefined && !sameList(news.overlaps, current.overlaps);
661 const allocationChanged =
662 news.allocationOptions !== undefined &&
663 !sameAllocation(news.allocationOptions, current.allocationOptions);
664
665 const locked = current.immutable === true;
666 const mutableChanged =
667 !locked &&
668 (cidrChanged ||
669 prefixChanged ||
670 targetChanged ||
671 excludeChanged ||
672 overlapsChanged ||
673 allocationChanged);
674
675 if (labelsChanged || descriptionChanged || mutableChanged) {
676 const updateMask = [
677 labelsChanged ? "labels" : undefined,
678 descriptionChanged ? "description" : undefined,
679 !locked && cidrChanged ? "ipCidrRange" : undefined,
680 !locked && prefixChanged ? "prefixLength" : undefined,
681 !locked && targetChanged ? "targetCidrRange" : undefined,
682 !locked && excludeChanged ? "excludeCidrRanges" : undefined,
683 !locked && overlapsChanged ? "overlaps" : undefined,
684 !locked && allocationChanged ? "allocationOptions" : undefined,
685 ].filter((field): field is string => field !== undefined);
686
687 const operation = yield* networkconnectivity.patchProjectsLocationsInternalRanges({
688 name: current.name ?? name,
689 updateMask: updateMask.join(","),
690 body: {
691 name: current.name ?? name,
692 labels: desiredLabels,
693 description: news.description,
694 ipCidrRange: news.ipCidrRange,
695 prefixLength: news.prefixLength,
696 targetCidrRange: news.targetCidrRange,
697 excludeCidrRanges: news.excludeCidrRanges,
698 overlaps: news.overlaps,
699 allocationOptions: news.allocationOptions,
700 },
701 });
702 yield* waitForOperation(operation);
703 current = yield* waitUntilExists(current.name ?? name);
704 }
705
706 return toAttrs(current, env.project);
707 }),
708
709 delete: Effect.fn(function* ({ output }) {
710 const operation = yield* networkconnectivity
711 .deleteProjectsLocationsInternalRanges({ name: output.name })
712 .pipe(
713 Effect.retry({
714 while: (error) => error._tag === "Conflict",
715 times: 8,
716 schedule: Schedule.spaced("2 seconds"),
717 }),
718 Effect.catchTag("NotFound", () => Effect.undefined),
719 );
720 if (operation !== undefined) {
721 yield* waitForOperation(operation, { notFoundOk: true });
722 }
723 yield* waitUntilGone(output.name);
724 }),
725 });