@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, 06:00 UTC

main
ts 1,099 lines 38.5 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 MAX_NAME_LENGTH = 63;
25
26 export type SpokeState = networkconnectivity.SpokeStateEnum | (string & {});
27 export type SpokeType = networkconnectivity.SpokeSpokeTypeEnum | (string & {});
28 export type SpokeGatewayCapacity = networkconnectivity.GatewayCapacityEnum | (string & {});
29
30 export type SpokeStateReason = {
31 /** Reason code (`PENDING_REVIEW`, `REJECTED`, `FAILED`, …). */
32 code: string | undefined;
33 /** Human-readable details. */
34 message: string | undefined;
35 /** Extra text supplied when a hub admin rejected the spoke. */
36 userDetails: string | undefined;
37 };
38
39 export type LinkedVpcNetwork = {
40 /**
41 * URI of the VPC network
42 * (`projects/{project}/global/networks/{network}` or a Compute
43 * selfLink). Immutable — changing it replaces the spoke.
44 */
45 uri: string;
46 /**
47 * Subnet CIDRs excluded from export to the hub.
48 */
49 excludeExportRanges?: ReadonlyArray<string>;
50 /**
51 * Subnet CIDRs included when exporting to the hub.
52 */
53 includeExportRanges?: ReadonlyArray<string>;
54 };
55
56 export type LinkedVpnTunnels = {
57 /**
58 * URIs of HA VPN tunnels. Immutable — changing them replaces the
59 * spoke.
60 */
61 uris: ReadonlyArray<string>;
62 /**
63 * Enable site-to-site data transfer. Immutable — changing it replaces
64 * the spoke.
65 */
66 siteToSiteDataTransfer?: boolean;
67 /** Hub routes included when importing from the hub. */
68 includeImportRanges?: ReadonlyArray<string>;
69 /** Hub routes excluded when importing from the hub. */
70 excludeImportRanges?: ReadonlyArray<string>;
71 /** Dynamic routes included when exporting to the hub. */
72 includeExportRanges?: ReadonlyArray<string>;
73 /** Dynamic routes excluded when exporting to the hub. */
74 excludeExportRanges?: ReadonlyArray<string>;
75 };
76
77 export type LinkedInterconnectAttachments = {
78 /**
79 * URIs of VLAN attachments. Immutable — changing them replaces the
80 * spoke.
81 */
82 uris: ReadonlyArray<string>;
83 /**
84 * Enable site-to-site data transfer. Immutable — changing it replaces
85 * the spoke.
86 */
87 siteToSiteDataTransfer?: boolean;
88 /** Hub routes included when importing from the hub. */
89 includeImportRanges?: ReadonlyArray<string>;
90 /** Hub routes excluded when importing from the hub. */
91 excludeImportRanges?: ReadonlyArray<string>;
92 /** Dynamic routes included when exporting to the hub. */
93 includeExportRanges?: ReadonlyArray<string>;
94 /** Dynamic routes excluded when exporting to the hub. */
95 excludeExportRanges?: ReadonlyArray<string>;
96 };
97
98 export type RouterApplianceInstance = {
99 /** URI of the VM that speaks BGP. */
100 virtualMachine: string;
101 /** Internal IP on the VM used for peering. */
102 ipAddress: string;
103 };
104
105 export type LinkedRouterApplianceInstances = {
106 /**
107 * Router appliance VMs. Replacing the set of VMs updates in place;
108 * changing `siteToSiteDataTransfer` replaces the spoke.
109 */
110 instances: ReadonlyArray<RouterApplianceInstance>;
111 /**
112 * Enable site-to-site data transfer. Immutable — changing it replaces
113 * the spoke.
114 */
115 siteToSiteDataTransfer?: boolean;
116 /** Hub routes included when importing from the hub. */
117 includeImportRanges?: ReadonlyArray<string>;
118 /** Hub routes excluded when importing from the hub. */
119 excludeImportRanges?: ReadonlyArray<string>;
120 /** Dynamic routes included when exporting to the hub. */
121 includeExportRanges?: ReadonlyArray<string>;
122 /** Dynamic routes excluded when exporting to the hub. */
123 excludeExportRanges?: ReadonlyArray<string>;
124 };
125
126 export type LinkedProducerVpcNetwork = {
127 /**
128 * Service-consumer VPC the producer VPC is peered with. Immutable —
129 * changing it replaces the spoke.
130 */
131 network: string;
132 /**
133 * Name of the ACTIVE VPC peering to the producer (tenant) VPC.
134 * Immutable — changing it replaces the spoke.
135 */
136 peering: string;
137 /** Subnet CIDRs excluded from export to the hub. */
138 excludeExportRanges?: ReadonlyArray<string>;
139 /** Subnet CIDRs included when exporting to the hub. */
140 includeExportRanges?: ReadonlyArray<string>;
141 };
142
143 export type SpokeGatewayIpRangeReservation = {
144 /**
145 * `/23` CIDR reserved for gateway infrastructure (e.g. `10.1.2.0/23`).
146 * Immutable — changing it replaces the spoke.
147 */
148 ipRange: string;
149 };
150
151 export type SpokeGateway = {
152 /**
153 * Aggregate processing capacity. Immutable — changing it replaces the
154 * spoke.
155 */
156 capacity?: SpokeGatewayCapacity;
157 /**
158 * CIDRs reserved for gateway infrastructure. Immutable — changing
159 * them replaces the spoke.
160 */
161 ipRangeReservations?: ReadonlyArray<SpokeGatewayIpRangeReservation>;
162 };
163
164 export type SpokeProps = {
165 /**
166 * Spoke id (the `{spoke}` segment of
167 * `projects/{project}/locations/{location}/spokes/{spoke}`). If
168 * omitted, a unique RFC1035 name is generated from the stack, stage,
169 * and logical id. Must be 1-63 characters and match
170 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the
171 * spoke.
172 */
173 spokeId?: string;
174 /**
175 * Location of the spoke. VPC and producer-VPC spokes must use
176 * `global`; VPN, VLAN-attachment, router-appliance, and gateway
177 * spokes use a region (`us-central1`, …). `US-CENTRAL1` is accepted
178 * and normalized to `us-central1`. Immutable — changing it replaces
179 * the spoke.
180 * @default "global"
181 */
182 location?: string;
183 /**
184 * Hub this spoke attaches to — a full resource name
185 * `projects/{project}/locations/global/hubs/{hub}` or a hub id.
186 * Immutable — changing it replaces the spoke.
187 */
188 hub: string;
189 /**
190 * Group this spoke belongs to (star / hybrid-inspection topologies).
191 * Immutable — changing it replaces the spoke.
192 */
193 group?: string;
194 /**
195 * Human-readable description of the spoke.
196 */
197 description?: string;
198 /**
199 * User labels. Alchemy ownership labels are merged in automatically.
200 */
201 labels?: Record<string, string>;
202 /**
203 * VPC network associated with the spoke. Exactly one of the `linked*`
204 * / `gateway` fields must be set.
205 */
206 linkedVpcNetwork?: LinkedVpcNetwork;
207 /**
208 * HA VPN tunnels associated with the spoke.
209 */
210 linkedVpnTunnels?: LinkedVpnTunnels;
211 /**
212 * VLAN attachments associated with the spoke.
213 */
214 linkedInterconnectAttachments?: LinkedInterconnectAttachments;
215 /**
216 * Router appliance VMs associated with the spoke.
217 */
218 linkedRouterApplianceInstances?: LinkedRouterApplianceInstances;
219 /**
220 * Producer VPC peered to a service-consumer VPC spoke.
221 */
222 linkedProducerVpcNetwork?: LinkedProducerVpcNetwork;
223 /**
224 * NCC gateway that inspects traffic.
225 */
226 gateway?: SpokeGateway;
227 };
228
229 export type Spoke = Resource<
230 "GCP.NetworkConnectivity.Spoke",
231 SpokeProps,
232 {
233 /** Full resource name `projects/{project}/locations/{location}/spokes/{spoke}`. */
234 name: string;
235 /** Spoke id (last path segment). */
236 spokeId: string;
237 /** Project id. */
238 project: string;
239 /** Location id (`global`, `us-central1`, …). */
240 location: string;
241 /** Hub resource name this spoke is attached to. */
242 hub: string | undefined;
243 /** Group resource name, if any. */
244 group: string | undefined;
245 /** User-provided description. */
246 description: string | undefined;
247 /** User labels (Alchemy ownership labels stripped). */
248 labels: Record<string, string>;
249 /** Linked VPC network, if this is a VPC spoke. */
250 linkedVpcNetwork: LinkedVpcNetwork | undefined;
251 /** Linked VPN tunnels, if this is a VPN spoke. */
252 linkedVpnTunnels: LinkedVpnTunnels | undefined;
253 /** Linked VLAN attachments, if this is an interconnect spoke. */
254 linkedInterconnectAttachments: LinkedInterconnectAttachments | undefined;
255 /** Linked router appliances, if this is a router-appliance spoke. */
256 linkedRouterApplianceInstances: LinkedRouterApplianceInstances | undefined;
257 /** Linked producer VPC, if this is a producer-VPC spoke. */
258 linkedProducerVpcNetwork: LinkedProducerVpcNetwork | undefined;
259 /** Gateway config, if this is a gateway spoke. */
260 gateway: SpokeGateway | undefined;
261 /** Server-reported spoke type (`VPC_NETWORK`, `VPN_TUNNEL`, …). */
262 spokeType: string | undefined;
263 /** Server-generated UUID, unique across spokes. */
264 uniqueId: string | undefined;
265 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
266 state: string | undefined;
267 /** Reasons the spoke is not `ACTIVE`, if any. */
268 reasons: ReadonlyArray<SpokeStateReason>;
269 /** RFC3339 creation timestamp. */
270 createTime: string | undefined;
271 /** RFC3339 last-update timestamp. */
272 updateTime: string | undefined;
273 },
274 never,
275 Providers
276 >;
277
278 /**
279 * A Network Connectivity Center spoke — one VPC, VPN tunnel set, VLAN
280 * attachment set, router-appliance set, producer VPC, or gateway
281 * attached to a hub.
282 *
283 * Set exactly one of `linkedVpcNetwork`, `linkedVpnTunnels`,
284 * `linkedInterconnectAttachments`, `linkedRouterApplianceInstances`,
285 * `linkedProducerVpcNetwork`, or `gateway`. VPC spokes live at
286 * `location: "global"`; hybrid spokes are regional.
287 *
288 * Changing `spokeId`, `location`, `hub`, `group`, or the linked
289 * resource identity replaces the spoke. Description, labels, and
290 * include/exclude CIDR ranges update in place.
291 *
292 * ### Creating a Spoke
293 * **Example:** VPC spoke on a generated name
294 * ```typescript
295 * const network = yield* GCP.Compute.Network("AppVpc", {
296 * autoCreateSubnetworks: false,
297 * });
298 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {});
299 * const spoke = yield* GCP.NetworkConnectivity.Spoke("AppVpcSpoke", {
300 * hub: hub.name,
301 * linkedVpcNetwork: { uri: network.selfLink! },
302 * });
303 * ```
304 *
305 * **Example:** Named VPC spoke with labels and export filters
306 * ```typescript
307 * const spoke = yield* GCP.NetworkConnectivity.Spoke("AppVpcSpoke", {
308 * spokeId: "app-vpc",
309 * location: "global",
310 * hub: hub.name,
311 * description: "app vpc",
312 * labels: { env: "prod" },
313 * linkedVpcNetwork: {
314 * uri: network.selfLink!,
315 * includeExportRanges: ["10.0.0.0/8"],
316 * },
317 * });
318 * ```
319 *
320 * ### Updating a Spoke
321 * **Example:** Description, labels, and export filters
322 * ```typescript
323 * const spoke = yield* GCP.NetworkConnectivity.Spoke("AppVpcSpoke", {
324 * spokeId: "app-vpc",
325 * location: "global",
326 * hub: hub.name,
327 * description: "app vpc v2",
328 * labels: { env: "prod", role: "spoke" },
329 * linkedVpcNetwork: {
330 * uri: network.selfLink!,
331 * includeExportRanges: ["10.0.0.0/8", "192.168.0.0/16"],
332 * },
333 * });
334 * ```
335 *
336 * @resource
337 * @category NetworkConnectivity
338 */
339 export const Spoke = Resource<Spoke>("GCP.NetworkConnectivity.Spoke");
340
341 export class SpokeNotResolved extends Data.TaggedError("GCP.NetworkConnectivity.SpokeNotResolved")<{
342 resourceName: string;
343 }> {}
344
345 export class SpokeFailed extends Data.TaggedError("GCP.NetworkConnectivity.SpokeFailed")<{
346 resourceName: string;
347 state: string | undefined;
348 }> {}
349
350 export class SpokeStillExists extends Data.TaggedError("GCP.NetworkConnectivity.SpokeStillExists")<{
351 resourceName: string;
352 }> {}
353
354 const lastSegment = (value: string) => {
355 const trimmed = value.replace(/\/+$/, "");
356 const parts = trimmed.split("/");
357 return parts[parts.length - 1] || trimmed;
358 };
359
360 const rfc1035 = (name: string): string => {
361 let next = name
362 .toLowerCase()
363 .replace(/[^a-z0-9-]/g, "-")
364 .replace(/-+/g, "-")
365 .replace(/^-+/, "")
366 .replace(/-+$/, "");
367 if (!/^[a-z]/.test(next)) {
368 next = `s${next}`;
369 }
370 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
371 return next.length > 0 ? next : "spoke";
372 };
373
374 const normalizeLocation = (location: string | undefined) =>
375 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
376
377 const resourceName = (project: string, location: string, spokeId: string) =>
378 `projects/${project}/locations/${location}/spokes/${spokeId}`;
379
380 const parentOf = (project: string, location: string) => `projects/${project}/locations/${location}`;
381
382 const parseName = (name: string) => {
383 const parts = name.split("/").filter((part) => part.length > 0);
384 const spokesAt = parts.lastIndexOf("spokes");
385 const locationsAt = parts.lastIndexOf("locations");
386 const projectsAt = parts.lastIndexOf("projects");
387 return {
388 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
389 location:
390 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
391 spokeId: spokesAt >= 0 && parts[spokesAt + 1] ? parts[spokesAt + 1]! : lastSegment(name),
392 };
393 };
394
395 const userLabels = (
396 labels: Record<string, string | undefined> | null | undefined,
397 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
398
399 const toId = (id: string, spokeId: string | undefined, existing?: string) =>
400 Effect.gen(function* () {
401 if (spokeId !== undefined) return spokeId;
402 if (existing !== undefined) return existing;
403 return rfc1035(
404 yield* createPhysicalName({
405 id,
406 maxLength: MAX_NAME_LENGTH,
407 lowercase: true,
408 }),
409 );
410 });
411
412 const resolveHub = (hub: string, project: string) =>
413 hub.includes("/") ? hub : `projects/${project}/locations/${DEFAULT_LOCATION}/hubs/${hub}`;
414
415 const rangesKey = (ranges: ReadonlyArray<string> | undefined) =>
416 JSON.stringify([...(ranges ?? [])].slice().sort());
417
418 const resourceKey = (uri: string | undefined) => {
419 if (uri === undefined || uri.length === 0) return "";
420 return lastSegment(uri);
421 };
422
423 const resourceKeys = (uris: ReadonlyArray<string> | undefined) =>
424 JSON.stringify([...(uris ?? [])].map(resourceKey).sort());
425
426 const instancesKey = (instances: ReadonlyArray<RouterApplianceInstance> | undefined) =>
427 JSON.stringify(
428 [...(instances ?? [])]
429 .map((instance) => ({
430 vm: resourceKey(instance.virtualMachine),
431 ip: instance.ipAddress,
432 }))
433 .sort((left, right) =>
434 left.vm === right.vm ? left.ip.localeCompare(right.ip) : left.vm.localeCompare(right.vm),
435 ),
436 );
437
438 const gatewayKey = (gateway: SpokeGateway | undefined) =>
439 JSON.stringify({
440 capacity: gateway?.capacity ?? "",
441 reservations: [...(gateway?.ipRangeReservations ?? [])]
442 .map((reservation) => reservation.ipRange)
443 .sort(),
444 });
445
446 const linkedIdentity = (props: {
447 linkedVpcNetwork?: LinkedVpcNetwork;
448 linkedVpnTunnels?: LinkedVpnTunnels;
449 linkedInterconnectAttachments?: LinkedInterconnectAttachments;
450 linkedRouterApplianceInstances?: LinkedRouterApplianceInstances;
451 linkedProducerVpcNetwork?: LinkedProducerVpcNetwork;
452 gateway?: SpokeGateway;
453 }) => {
454 if (props.linkedVpcNetwork) {
455 return `vpc:${resourceKey(props.linkedVpcNetwork.uri)}`;
456 }
457 if (props.linkedVpnTunnels) {
458 return `vpn:${resourceKeys(props.linkedVpnTunnels.uris)}:${
459 props.linkedVpnTunnels.siteToSiteDataTransfer === true
460 }`;
461 }
462 if (props.linkedInterconnectAttachments) {
463 return `interconnect:${resourceKeys(props.linkedInterconnectAttachments.uris)}:${
464 props.linkedInterconnectAttachments.siteToSiteDataTransfer === true
465 }`;
466 }
467 if (props.linkedRouterApplianceInstances) {
468 return `appliance:${props.linkedRouterApplianceInstances.siteToSiteDataTransfer === true}`;
469 }
470 if (props.linkedProducerVpcNetwork) {
471 return `producer:${resourceKey(props.linkedProducerVpcNetwork.network)}:${
472 props.linkedProducerVpcNetwork.peering
473 }`;
474 }
475 if (props.gateway) {
476 return `gateway:${gatewayKey(props.gateway)}`;
477 }
478 return "";
479 };
480
481 const toReasons = (reasons: networkconnectivity.StateReasonList | undefined): SpokeStateReason[] =>
482 (reasons ?? []).map((reason) => ({
483 code: reason.code,
484 message: reason.message,
485 userDetails: reason.userDetails,
486 }));
487
488 const toLinkedVpc = (
489 value: networkconnectivity.LinkedVpcNetwork | undefined,
490 ): LinkedVpcNetwork | undefined => {
491 if (value?.uri === undefined || value.uri.length === 0) return undefined;
492 return {
493 uri: value.uri,
494 excludeExportRanges: value.excludeExportRanges,
495 includeExportRanges: value.includeExportRanges,
496 };
497 };
498
499 const toLinkedVpn = (
500 value: networkconnectivity.LinkedVpnTunnels | undefined,
501 ): LinkedVpnTunnels | undefined => {
502 if (value === undefined) return undefined;
503 const uris = value.uris ?? [];
504 if (uris.length === 0 && value.vpcNetwork === undefined) return undefined;
505 return {
506 uris,
507 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
508 includeImportRanges: value.includeImportRanges,
509 excludeImportRanges: value.excludeImportRanges,
510 includeExportRanges: value.includeExportRanges,
511 excludeExportRanges: value.excludeExportRanges,
512 };
513 };
514
515 const toLinkedInterconnect = (
516 value: networkconnectivity.LinkedInterconnectAttachments | undefined,
517 ): LinkedInterconnectAttachments | undefined => {
518 if (value === undefined) return undefined;
519 const uris = value.uris ?? [];
520 if (uris.length === 0 && value.vpcNetwork === undefined) return undefined;
521 return {
522 uris,
523 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
524 includeImportRanges: value.includeImportRanges,
525 excludeImportRanges: value.excludeImportRanges,
526 includeExportRanges: value.includeExportRanges,
527 excludeExportRanges: value.excludeExportRanges,
528 };
529 };
530
531 const toLinkedAppliances = (
532 value: networkconnectivity.LinkedRouterApplianceInstances | undefined,
533 ): LinkedRouterApplianceInstances | undefined => {
534 if (value === undefined) return undefined;
535 const instances = (value.instances ?? [])
536 .filter(
537 (
538 instance,
539 ): instance is networkconnectivity.RouterApplianceInstance & {
540 virtualMachine: string;
541 ipAddress: string;
542 } => typeof instance.virtualMachine === "string" && typeof instance.ipAddress === "string",
543 )
544 .map((instance) => ({
545 virtualMachine: instance.virtualMachine,
546 ipAddress: instance.ipAddress,
547 }));
548 if (instances.length === 0 && value.vpcNetwork === undefined) {
549 return undefined;
550 }
551 return {
552 instances,
553 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
554 includeImportRanges: value.includeImportRanges,
555 excludeImportRanges: value.excludeImportRanges,
556 includeExportRanges: value.includeExportRanges,
557 excludeExportRanges: value.excludeExportRanges,
558 };
559 };
560
561 const toLinkedProducer = (
562 value: networkconnectivity.LinkedProducerVpcNetwork | undefined,
563 ): LinkedProducerVpcNetwork | undefined => {
564 if (value?.network === undefined || value.peering === undefined) {
565 return undefined;
566 }
567 return {
568 network: value.network,
569 peering: value.peering,
570 excludeExportRanges: value.excludeExportRanges,
571 includeExportRanges: value.includeExportRanges,
572 };
573 };
574
575 const toGateway = (value: networkconnectivity.Gateway | undefined): SpokeGateway | undefined => {
576 if (value === undefined) return undefined;
577 const ipRangeReservations = (value.ipRangeReservations ?? [])
578 .filter(
579 (
580 reservation,
581 ): reservation is networkconnectivity.IpRangeReservation & {
582 ipRange: string;
583 } => typeof reservation.ipRange === "string",
584 )
585 .map((reservation) => ({ ipRange: reservation.ipRange }));
586 if (
587 value.capacity === undefined &&
588 ipRangeReservations.length === 0 &&
589 (value.cloudRouters ?? []).length === 0
590 ) {
591 return undefined;
592 }
593 return {
594 capacity: value.capacity,
595 ipRangeReservations: ipRangeReservations.length > 0 ? ipRangeReservations : undefined,
596 };
597 };
598
599 const toAttrs = (spoke: networkconnectivity.Spoke, project: string) => {
600 const name = spoke.name ?? "";
601 const parsed = parseName(name);
602 return {
603 name,
604 spokeId: parsed.spokeId,
605 project: parsed.project || project,
606 location: parsed.location || DEFAULT_LOCATION,
607 hub: spoke.hub,
608 group: spoke.group,
609 description: spoke.description,
610 labels: userLabels(spoke.labels),
611 linkedVpcNetwork: toLinkedVpc(spoke.linkedVpcNetwork),
612 linkedVpnTunnels: toLinkedVpn(spoke.linkedVpnTunnels),
613 linkedInterconnectAttachments: toLinkedInterconnect(spoke.linkedInterconnectAttachments),
614 linkedRouterApplianceInstances: toLinkedAppliances(spoke.linkedRouterApplianceInstances),
615 linkedProducerVpcNetwork: toLinkedProducer(spoke.linkedProducerVpcNetwork),
616 gateway: toGateway(spoke.gateway),
617 spokeType: spoke.spokeType,
618 uniqueId: spoke.uniqueId,
619 state: spoke.state,
620 reasons: toReasons(spoke.reasons),
621 createTime: spoke.createTime,
622 updateTime: spoke.updateTime,
623 };
624 };
625
626 const fromLinkedVpc = (value: LinkedVpcNetwork): networkconnectivity.LinkedVpcNetwork => ({
627 uri: value.uri,
628 excludeExportRanges: value.excludeExportRanges ? [...value.excludeExportRanges] : undefined,
629 includeExportRanges: value.includeExportRanges ? [...value.includeExportRanges] : undefined,
630 });
631
632 const fromLinkedVpn = (value: LinkedVpnTunnels): networkconnectivity.LinkedVpnTunnels => ({
633 uris: [...value.uris],
634 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
635 includeImportRanges: value.includeImportRanges ? [...value.includeImportRanges] : undefined,
636 excludeImportRanges: value.excludeImportRanges ? [...value.excludeImportRanges] : undefined,
637 includeExportRanges: value.includeExportRanges ? [...value.includeExportRanges] : undefined,
638 excludeExportRanges: value.excludeExportRanges ? [...value.excludeExportRanges] : undefined,
639 });
640
641 const fromLinkedInterconnect = (
642 value: LinkedInterconnectAttachments,
643 ): networkconnectivity.LinkedInterconnectAttachments => ({
644 uris: [...value.uris],
645 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
646 includeImportRanges: value.includeImportRanges ? [...value.includeImportRanges] : undefined,
647 excludeImportRanges: value.excludeImportRanges ? [...value.excludeImportRanges] : undefined,
648 includeExportRanges: value.includeExportRanges ? [...value.includeExportRanges] : undefined,
649 excludeExportRanges: value.excludeExportRanges ? [...value.excludeExportRanges] : undefined,
650 });
651
652 const fromLinkedAppliances = (
653 value: LinkedRouterApplianceInstances,
654 ): networkconnectivity.LinkedRouterApplianceInstances => ({
655 instances: value.instances.map((instance) => ({
656 virtualMachine: instance.virtualMachine,
657 ipAddress: instance.ipAddress,
658 })),
659 siteToSiteDataTransfer: value.siteToSiteDataTransfer,
660 includeImportRanges: value.includeImportRanges ? [...value.includeImportRanges] : undefined,
661 excludeImportRanges: value.excludeImportRanges ? [...value.excludeImportRanges] : undefined,
662 includeExportRanges: value.includeExportRanges ? [...value.includeExportRanges] : undefined,
663 excludeExportRanges: value.excludeExportRanges ? [...value.excludeExportRanges] : undefined,
664 });
665
666 const fromLinkedProducer = (
667 value: LinkedProducerVpcNetwork,
668 ): networkconnectivity.LinkedProducerVpcNetwork => ({
669 network: value.network,
670 peering: value.peering,
671 excludeExportRanges: value.excludeExportRanges ? [...value.excludeExportRanges] : undefined,
672 includeExportRanges: value.includeExportRanges ? [...value.includeExportRanges] : undefined,
673 });
674
675 const fromGateway = (value: SpokeGateway): networkconnectivity.Gateway => ({
676 capacity: value.capacity,
677 ipRangeReservations: value.ipRangeReservations?.map((reservation) => ({
678 ipRange: reservation.ipRange,
679 })),
680 });
681
682 const desiredSpokeBody = (
683 news: SpokeProps,
684 project: string,
685 labels: Record<string, string>,
686 ): networkconnectivity.Spoke => ({
687 hub: resolveHub(news.hub, project),
688 group: news.group,
689 description: news.description,
690 labels,
691 linkedVpcNetwork: news.linkedVpcNetwork ? fromLinkedVpc(news.linkedVpcNetwork) : undefined,
692 linkedVpnTunnels: news.linkedVpnTunnels ? fromLinkedVpn(news.linkedVpnTunnels) : undefined,
693 linkedInterconnectAttachments: news.linkedInterconnectAttachments
694 ? fromLinkedInterconnect(news.linkedInterconnectAttachments)
695 : undefined,
696 linkedRouterApplianceInstances: news.linkedRouterApplianceInstances
697 ? fromLinkedAppliances(news.linkedRouterApplianceInstances)
698 : undefined,
699 linkedProducerVpcNetwork: news.linkedProducerVpcNetwork
700 ? fromLinkedProducer(news.linkedProducerVpcNetwork)
701 : undefined,
702 gateway: news.gateway ? fromGateway(news.gateway) : undefined,
703 });
704
705 const getByName = (name: string) =>
706 networkconnectivity
707 .getProjectsLocationsSpokes({ name })
708 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
709
710 const isPendingState = (state: string | undefined) =>
711 state === "CREATING" ||
712 state === "UPDATING" ||
713 state === "DELETING" ||
714 state === "ACCEPTING" ||
715 state === "REJECTING" ||
716 state === "INACTIVE" ||
717 state === "STATE_UNSPECIFIED";
718
719 const isFailedState = (spoke: networkconnectivity.Spoke) =>
720 spoke.state === "FAILED" ||
721 spoke.state === "OBSOLETE" ||
722 (spoke.reasons ?? []).some((reason) => reason.code === "REJECTED");
723
724 const waitUntilReady = (name: string) =>
725 getByName(name).pipe(
726 Effect.filterOrFail(
727 (spoke): spoke is networkconnectivity.Spoke => spoke !== undefined,
728 () => new SpokeNotResolved({ resourceName: name }),
729 ),
730 Effect.filterOrFail(
731 (spoke) => !isFailedState(spoke),
732 (spoke) => new SpokeFailed({ resourceName: name, state: spoke.state }),
733 ),
734 Effect.filterOrFail(
735 (spoke) => !isPendingState(spoke.state),
736 () => new SpokeNotResolved({ resourceName: name }),
737 ),
738 Effect.retry({
739 while: (error) => error._tag === "GCP.NetworkConnectivity.SpokeNotResolved",
740 times: 120,
741 schedule: Schedule.spaced("10 seconds"),
742 }),
743 );
744
745 const waitUntilGone = (name: string) =>
746 getByName(name).pipe(
747 Effect.flatMap((spoke) =>
748 spoke === undefined ? Effect.void : Effect.fail(new SpokeStillExists({ resourceName: name })),
749 ),
750 Effect.retry({
751 while: (error) => error._tag === "GCP.NetworkConnectivity.SpokeStillExists",
752 times: 60,
753 schedule: Schedule.spaced("10 seconds"),
754 }),
755 );
756
757 const waitUntilHubDropsSpoke = (hub: string, spokeName: string) =>
758 networkconnectivity
759 .listSpokesProjectsLocationsGlobalHubs({
760 name: hub,
761 pageSize: 100,
762 })
763 .pipe(
764 Effect.flatMap((page) => {
765 const still = (page.spokes ?? []).some(
766 (spoke) => spoke.name === spokeName || resourceKey(spoke.name) === resourceKey(spokeName),
767 );
768 return still ? Effect.fail(new SpokeStillExists({ resourceName: spokeName })) : Effect.void;
769 }),
770 Effect.retry({
771 while: (error) => error._tag === "GCP.NetworkConnectivity.SpokeStillExists",
772 times: 8,
773 schedule: Schedule.spaced("3 seconds"),
774 }),
775 Effect.catchTags({
776 "GCP.NetworkConnectivity.SpokeStillExists": () => Effect.void,
777 NotFound: () => Effect.void,
778 }),
779 );
780
781 const waitUntilHubDropsVpc = (hub: string, networkKey: string) => {
782 if (networkKey.length === 0) return Effect.void;
783 return networkconnectivity.getProjectsLocationsGlobalHubs({ name: hub }).pipe(
784 Effect.flatMap((hubResource) => {
785 const still = (hubResource.routingVpcs ?? []).some(
786 (vpc) => resourceKey(vpc.uri) === networkKey,
787 );
788 return still ? Effect.fail(new SpokeStillExists({ resourceName: hub })) : Effect.void;
789 }),
790 Effect.retry({
791 while: (error) => error._tag === "GCP.NetworkConnectivity.SpokeStillExists",
792 times: 8,
793 schedule: Schedule.spaced("3 seconds"),
794 }),
795 Effect.catchTags({
796 "GCP.NetworkConnectivity.SpokeStillExists": () => Effect.void,
797 NotFound: () => Effect.void,
798 }),
799 );
800 };
801
802 const listOwnedSpokes = (project: string, location: string) =>
803 networkconnectivity.listProjectsLocationsSpokes
804 .pages({
805 parent: parentOf(project, location),
806 pageSize: 1000,
807 })
808 .pipe(
809 Stream.flatMap((page) => Stream.fromIterable(page.spokes ?? [])),
810 Stream.filter((spoke) =>
811 Object.keys(spoke.labels ?? {}).some((key) => key.startsWith("alchemy-")),
812 ),
813 Stream.map((spoke) => toAttrs(spoke, project)),
814 Stream.runCollect,
815 Effect.map((chunk) => Array.from(chunk)),
816 Effect.catchTag("NotFound", () => Effect.succeed([])),
817 );
818
819 const rangeFieldsChanged = (current: ReturnType<typeof toAttrs>, news: SpokeProps) => {
820 const masks: string[] = [];
821 if (news.linkedVpcNetwork) {
822 const observed = current.linkedVpcNetwork;
823 if (
824 rangesKey(observed?.includeExportRanges) !==
825 rangesKey(news.linkedVpcNetwork.includeExportRanges)
826 ) {
827 masks.push("linkedVpcNetwork.includeExportRanges");
828 }
829 if (
830 rangesKey(observed?.excludeExportRanges) !==
831 rangesKey(news.linkedVpcNetwork.excludeExportRanges)
832 ) {
833 masks.push("linkedVpcNetwork.excludeExportRanges");
834 }
835 }
836 if (news.linkedVpnTunnels) {
837 const observed = current.linkedVpnTunnels;
838 if (
839 rangesKey(observed?.includeImportRanges) !==
840 rangesKey(news.linkedVpnTunnels.includeImportRanges)
841 ) {
842 masks.push("linkedVpnTunnels.includeImportRanges");
843 }
844 if (
845 rangesKey(observed?.excludeImportRanges) !==
846 rangesKey(news.linkedVpnTunnels.excludeImportRanges)
847 ) {
848 masks.push("linkedVpnTunnels.excludeImportRanges");
849 }
850 if (
851 rangesKey(observed?.includeExportRanges) !==
852 rangesKey(news.linkedVpnTunnels.includeExportRanges)
853 ) {
854 masks.push("linkedVpnTunnels.includeExportRanges");
855 }
856 if (
857 rangesKey(observed?.excludeExportRanges) !==
858 rangesKey(news.linkedVpnTunnels.excludeExportRanges)
859 ) {
860 masks.push("linkedVpnTunnels.excludeExportRanges");
861 }
862 }
863 if (news.linkedInterconnectAttachments) {
864 const observed = current.linkedInterconnectAttachments;
865 if (
866 rangesKey(observed?.includeImportRanges) !==
867 rangesKey(news.linkedInterconnectAttachments.includeImportRanges)
868 ) {
869 masks.push("linkedInterconnectAttachments.includeImportRanges");
870 }
871 if (
872 rangesKey(observed?.excludeImportRanges) !==
873 rangesKey(news.linkedInterconnectAttachments.excludeImportRanges)
874 ) {
875 masks.push("linkedInterconnectAttachments.excludeImportRanges");
876 }
877 if (
878 rangesKey(observed?.includeExportRanges) !==
879 rangesKey(news.linkedInterconnectAttachments.includeExportRanges)
880 ) {
881 masks.push("linkedInterconnectAttachments.includeExportRanges");
882 }
883 if (
884 rangesKey(observed?.excludeExportRanges) !==
885 rangesKey(news.linkedInterconnectAttachments.excludeExportRanges)
886 ) {
887 masks.push("linkedInterconnectAttachments.excludeExportRanges");
888 }
889 }
890 if (news.linkedRouterApplianceInstances) {
891 const observed = current.linkedRouterApplianceInstances;
892 if (
893 instancesKey(observed?.instances) !==
894 instancesKey(news.linkedRouterApplianceInstances.instances)
895 ) {
896 masks.push("linkedRouterApplianceInstances.instances");
897 }
898 if (
899 rangesKey(observed?.includeImportRanges) !==
900 rangesKey(news.linkedRouterApplianceInstances.includeImportRanges)
901 ) {
902 masks.push("linkedRouterApplianceInstances.includeImportRanges");
903 }
904 if (
905 rangesKey(observed?.excludeImportRanges) !==
906 rangesKey(news.linkedRouterApplianceInstances.excludeImportRanges)
907 ) {
908 masks.push("linkedRouterApplianceInstances.excludeImportRanges");
909 }
910 if (
911 rangesKey(observed?.includeExportRanges) !==
912 rangesKey(news.linkedRouterApplianceInstances.includeExportRanges)
913 ) {
914 masks.push("linkedRouterApplianceInstances.includeExportRanges");
915 }
916 if (
917 rangesKey(observed?.excludeExportRanges) !==
918 rangesKey(news.linkedRouterApplianceInstances.excludeExportRanges)
919 ) {
920 masks.push("linkedRouterApplianceInstances.excludeExportRanges");
921 }
922 }
923 if (news.linkedProducerVpcNetwork) {
924 const observed = current.linkedProducerVpcNetwork;
925 if (
926 rangesKey(observed?.includeExportRanges) !==
927 rangesKey(news.linkedProducerVpcNetwork.includeExportRanges)
928 ) {
929 masks.push("linkedProducerVpcNetwork.includeExportRanges");
930 }
931 if (
932 rangesKey(observed?.excludeExportRanges) !==
933 rangesKey(news.linkedProducerVpcNetwork.excludeExportRanges)
934 ) {
935 masks.push("linkedProducerVpcNetwork.excludeExportRanges");
936 }
937 }
938 return masks;
939 };
940
941 export const SpokeProvider = () =>
942 Provider.succeed(Spoke, {
943 stables: ["name", "spokeId", "project", "location", "hub", "uniqueId", "createTime"],
944
945 diff: Effect.fn(function* ({ news, olds, output }) {
946 if (!isResolved(news)) return undefined;
947 const previousId = olds?.spokeId ?? output?.spokeId;
948 const nextId = news.spokeId ?? previousId;
949 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
950
951 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
952 const nextLocation = normalizeLocation(news.location ?? output?.location);
953 const locationChanged = previousLocation !== nextLocation;
954
955 const previousHub = resourceKey(olds?.hub ?? output?.hub);
956 const nextHub = resourceKey(news.hub);
957 const hubChanged = previousHub.length > 0 && nextHub.length > 0 && previousHub !== nextHub;
958
959 const previousGroup = resourceKey(olds?.group ?? output?.group);
960 const nextGroup = resourceKey(news.group);
961 const groupChanged =
962 news.group !== undefined &&
963 previousGroup.length > 0 &&
964 nextGroup.length > 0 &&
965 previousGroup !== nextGroup;
966
967 const previousLinked = linkedIdentity({
968 linkedVpcNetwork: olds?.linkedVpcNetwork ?? output?.linkedVpcNetwork,
969 linkedVpnTunnels: olds?.linkedVpnTunnels ?? output?.linkedVpnTunnels,
970 linkedInterconnectAttachments:
971 olds?.linkedInterconnectAttachments ?? output?.linkedInterconnectAttachments,
972 linkedRouterApplianceInstances:
973 olds?.linkedRouterApplianceInstances ?? output?.linkedRouterApplianceInstances,
974 linkedProducerVpcNetwork:
975 olds?.linkedProducerVpcNetwork ?? output?.linkedProducerVpcNetwork,
976 gateway: olds?.gateway ?? output?.gateway,
977 });
978 const nextLinked = linkedIdentity(news);
979 const linkedChanged =
980 nextLinked.length > 0 && previousLinked.length > 0 && nextLinked !== previousLinked;
981
982 if (!idChanged && !locationChanged && !hubChanged && !groupChanged && !linkedChanged) {
983 return undefined;
984 }
985 return {
986 action: "replace" as const,
987 deleteFirst:
988 !idChanged && !locationChanged && (hubChanged || groupChanged || linkedChanged),
989 };
990 }),
991
992 read: Effect.fn(function* ({ id, olds, output }) {
993 const env = yield* GcpEnvironment.current;
994 const spokeId = yield* toId(id, olds?.spokeId, output?.spokeId);
995 const location = normalizeLocation(olds?.location ?? output?.location);
996 const name = output?.name ?? resourceName(env.project, location, spokeId);
997 const existing = yield* getByName(name);
998 if (existing === undefined) return undefined;
999 const attrs = toAttrs(existing, env.project);
1000 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
1001 }),
1002
1003 list: () =>
1004 Effect.gen(function* () {
1005 const env = yield* GcpEnvironment.current;
1006 const aggregated = yield* listOwnedSpokes(env.project, "-");
1007 if (aggregated.length > 0) return aggregated;
1008 return yield* listOwnedSpokes(env.project, DEFAULT_LOCATION);
1009 }),
1010
1011 reconcile: Effect.fn(function* ({ id, news, output }) {
1012 const env = yield* GcpEnvironment.current;
1013 const spokeId = yield* toId(id, news.spokeId, output?.spokeId);
1014 const location = normalizeLocation(news.location ?? output?.location);
1015 const name = output?.name ?? resourceName(env.project, location, spokeId);
1016 const desiredLabels = {
1017 ...toLabels(news.labels),
1018 ...(yield* createInternalLabels(id)),
1019 };
1020 const body = desiredSpokeBody(news, env.project, desiredLabels);
1021
1022 let current = yield* getByName(name);
1023
1024 if (current === undefined) {
1025 const created = yield* networkconnectivity
1026 .createProjectsLocationsSpokes({
1027 parent: parentOf(env.project, location),
1028 spokeId,
1029 body,
1030 })
1031 .pipe(
1032 Effect.retry({
1033 while: (error) => error._tag === "Conflict",
1034 times: 5,
1035 schedule: Schedule.spaced("2 seconds"),
1036 }),
1037 Effect.catchTag("Conflict", () => Effect.undefined),
1038 );
1039 if (created !== undefined) {
1040 yield* waitForOperation(created);
1041 }
1042 current = yield* waitUntilReady(name);
1043 }
1044
1045 if (current === undefined) {
1046 return yield* new SpokeNotResolved({ resourceName: name });
1047 }
1048
1049 const attrs = toAttrs(current, env.project);
1050 const observedLabels = tagRecord(current.labels);
1051 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
1052 const labelsChanged = upsert.length > 0 || removed.length > 0;
1053 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
1054 const rangeMasks = rangeFieldsChanged(attrs, news);
1055
1056 if (labelsChanged || descriptionChanged || rangeMasks.length > 0) {
1057 const updateMask = [
1058 labelsChanged ? "labels" : undefined,
1059 descriptionChanged ? "description" : undefined,
1060 ...rangeMasks,
1061 ].filter((field): field is string => field !== undefined);
1062
1063 const operation = yield* networkconnectivity.patchProjectsLocationsSpokes({
1064 name: current.name ?? name,
1065 updateMask: updateMask.join(","),
1066 body: {
1067 name: current.name ?? name,
1068 etag: current.etag,
1069 ...body,
1070 },
1071 });
1072 yield* waitForOperation(operation);
1073 current = yield* waitUntilReady(current.name ?? name);
1074 }
1075
1076 return toAttrs(current, env.project);
1077 }),
1078
1079 delete: Effect.fn(function* ({ output }) {
1080 const operation = yield* networkconnectivity
1081 .deleteProjectsLocationsSpokes({ name: output.name })
1082 .pipe(
1083 Effect.retry({
1084 while: (error) => error._tag === "Conflict",
1085 times: 8,
1086 schedule: Schedule.spaced("2 seconds"),
1087 }),
1088 Effect.catchTag("NotFound", () => Effect.undefined),
1089 );
1090 if (operation !== undefined) {
1091 yield* waitForOperation(operation, { notFoundOk: true });
1092 }
1093 yield* waitUntilGone(output.name);
1094 if (output.hub) {
1095 yield* waitUntilHubDropsSpoke(output.hub, output.name);
1096 yield* waitUntilHubDropsVpc(output.hub, resourceKey(output.linkedVpcNetwork?.uri));
1097 }
1098 }),
1099 });