@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 478 lines 15.7 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_POLICY_MODE = "PRESET" satisfies networkconnectivity.HubPolicyModeEnum;
25 const DEFAULT_PRESET_TOPOLOGY = "MESH" satisfies networkconnectivity.HubPresetTopologyEnum;
26 const MAX_NAME_LENGTH = 63;
27
28 export type HubState = networkconnectivity.HubStateEnum | (string & {});
29 export type HubPolicyMode = networkconnectivity.HubPolicyModeEnum | (string & {});
30 export type HubPresetTopology = networkconnectivity.HubPresetTopologyEnum | (string & {});
31
32 export type HubRoutingVpc = {
33 /** URI of the VPC network attached via a spoke. */
34 uri: string | undefined;
35 /**
36 * Whether this VPC must be used for new site-to-site data-transfer
37 * spokes.
38 */
39 requiredForNewSiteToSiteDataTransferSpokes: boolean | undefined;
40 };
41
42 export type HubProps = {
43 /**
44 * Hub id (the `{hub}` segment of
45 * `projects/{project}/locations/global/hubs/{hub}`). If omitted, a
46 * unique RFC1035 name is generated from the stack, stage, and logical
47 * id. Must be 1-63 characters and match `[a-z]([-a-z0-9]*[a-z0-9])?`.
48 * Immutable — changing it replaces the hub.
49 */
50 hubId?: string;
51 /**
52 * Human-readable description of the hub.
53 */
54 description?: string;
55 /**
56 * Whether Private Service Connect connection propagation is enabled.
57 * When true, PSC endpoints in VPC spokes are reachable from other VPC
58 * spokes on this hub.
59 * @default false
60 */
61 exportPsc?: boolean;
62 /**
63 * Policy mode. `PRESET` applies `presetTopology`; `CUSTOM` leaves
64 * topology unspecified.
65 * @default "PRESET"
66 */
67 policyMode?: HubPolicyMode;
68 /**
69 * Preset topology used when `policyMode` is `PRESET`. Ignored (and
70 * reported as `PRESET_TOPOLOGY_UNSPECIFIED`) when `policyMode` is
71 * `CUSTOM`.
72 * @default "MESH"
73 */
74 presetTopology?: HubPresetTopology;
75 /**
76 * User labels. Alchemy ownership labels are merged in automatically.
77 */
78 labels?: Record<string, string>;
79 };
80
81 export type Hub = Resource<
82 "GCP.NetworkConnectivity.Hub",
83 HubProps,
84 {
85 /** Full resource name `projects/{project}/locations/global/hubs/{hub}`. */
86 name: string;
87 /** Hub id (last path segment). */
88 hubId: string;
89 /** Project id. */
90 project: string;
91 /** Location id. Hubs are global — always `"global"`. */
92 location: string;
93 /** User-provided description. */
94 description: string | undefined;
95 /** Whether PSC connection propagation is enabled. */
96 exportPsc: boolean;
97 /** Policy mode currently configured on the hub. */
98 policyMode: string | undefined;
99 /** Preset topology currently configured on the hub. */
100 presetTopology: string | undefined;
101 /** User labels (Alchemy ownership labels stripped). */
102 labels: Record<string, string>;
103 /** Server-generated UUID, unique across hubs. */
104 uniqueId: string | undefined;
105 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
106 state: string | undefined;
107 /** VPC networks associated with this hub's spokes (output-only). */
108 routingVpcs: HubRoutingVpc[];
109 /** Route table names nested under this hub (output-only). */
110 routeTables: ReadonlyArray<string>;
111 /** RFC3339 creation timestamp. */
112 createTime: string | undefined;
113 /** RFC3339 last-update timestamp. */
114 updateTime: string | undefined;
115 },
116 never,
117 Providers
118 >;
119
120 /**
121 * A Network Connectivity Center hub — the global attachment point for
122 * VPC, VPN, and interconnect spokes.
123 *
124 * Hubs live at `locations/global`. Changing `hubId` replaces the hub.
125 * Description, labels, `exportPsc`, `policyMode`, and `presetTopology`
126 * update in place. A hub can only be deleted when it has no spokes.
127 *
128 * ### Creating a Hub
129 * **Example:** Generated name
130 * ```typescript
131 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {});
132 * ```
133 *
134 * **Example:** Named hub with labels
135 * ```typescript
136 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {
137 * hubId: "app-mesh",
138 * description: "prod mesh",
139 * labels: { env: "prod" },
140 * });
141 * ```
142 *
143 * ### Preset topology
144 * **Example:** STAR hub
145 * ```typescript
146 * const hub = yield* GCP.NetworkConnectivity.Hub("Star", {
147 * policyMode: "PRESET",
148 * presetTopology: "STAR",
149 * });
150 * ```
151 *
152 * ### Private Service Connect
153 * **Example:** Enable PSC transitivity
154 * ```typescript
155 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {
156 * exportPsc: true,
157 * });
158 * ```
159 *
160 * ### Updating a Hub
161 * **Example:** Description, labels, and PSC
162 * ```typescript
163 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {
164 * hubId: "app-mesh",
165 * description: "prod mesh v2",
166 * exportPsc: true,
167 * labels: { env: "prod", role: "ncc" },
168 * });
169 * ```
170 *
171 * @resource
172 * @category NetworkConnectivity
173 */
174 export const Hub = Resource<Hub>("GCP.NetworkConnectivity.Hub");
175
176 export class HubNotResolved extends Data.TaggedError("GCP.NetworkConnectivity.HubNotResolved")<{
177 resourceName: string;
178 }> {}
179
180 export class HubFailed extends Data.TaggedError("GCP.NetworkConnectivity.HubFailed")<{
181 resourceName: string;
182 state: string | undefined;
183 }> {}
184
185 export class HubStillExists extends Data.TaggedError("GCP.NetworkConnectivity.HubStillExists")<{
186 resourceName: string;
187 }> {}
188
189 const lastSegment = (value: string) => {
190 const trimmed = value.replace(/\/+$/, "");
191 const parts = trimmed.split("/");
192 return parts[parts.length - 1] || trimmed;
193 };
194
195 const rfc1035 = (name: string): string => {
196 let next = name
197 .toLowerCase()
198 .replace(/[^a-z0-9-]/g, "-")
199 .replace(/-+/g, "-")
200 .replace(/^-+/, "")
201 .replace(/-+$/, "");
202 if (!/^[a-z]/.test(next)) {
203 next = `h${next}`;
204 }
205 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
206 return next.length > 0 ? next : "hub";
207 };
208
209 const resourceName = (project: string, hubId: string) =>
210 `projects/${project}/locations/${DEFAULT_LOCATION}/hubs/${hubId}`;
211
212 const parentOf = (project: string) => `projects/${project}/locations/${DEFAULT_LOCATION}`;
213
214 const parseName = (name: string) => {
215 const parts = name.split("/").filter((part) => part.length > 0);
216 const hubsAt = parts.lastIndexOf("hubs");
217 const locationsAt = parts.lastIndexOf("locations");
218 const projectsAt = parts.lastIndexOf("projects");
219 return {
220 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
221 location:
222 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
223 hubId: hubsAt >= 0 && parts[hubsAt + 1] ? parts[hubsAt + 1]! : lastSegment(name),
224 };
225 };
226
227 const userLabels = (
228 labels: Record<string, string | undefined> | null | undefined,
229 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
230
231 const toId = (id: string, hubId: string | undefined, existing?: string) =>
232 Effect.gen(function* () {
233 if (hubId !== undefined) return hubId;
234 if (existing !== undefined) return existing;
235 return rfc1035(
236 yield* createPhysicalName({
237 id,
238 maxLength: MAX_NAME_LENGTH,
239 lowercase: true,
240 }),
241 );
242 });
243
244 const desiredPolicyMode = (news: HubProps): HubPolicyMode => news.policyMode ?? DEFAULT_POLICY_MODE;
245
246 const desiredPresetTopology = (news: HubProps): HubPresetTopology => {
247 if (desiredPolicyMode(news) === "CUSTOM") {
248 return "PRESET_TOPOLOGY_UNSPECIFIED";
249 }
250 return news.presetTopology ?? DEFAULT_PRESET_TOPOLOGY;
251 };
252
253 const toRoutingVpcs = (vpcs: networkconnectivity.RoutingVPCList | undefined): HubRoutingVpc[] =>
254 (vpcs ?? []).map((vpc) => ({
255 uri: vpc.uri,
256 requiredForNewSiteToSiteDataTransferSpokes: vpc.requiredForNewSiteToSiteDataTransferSpokes,
257 }));
258
259 const toAttrs = (hub: networkconnectivity.Hub, project: string) => {
260 const name = hub.name ?? "";
261 const parsed = parseName(name);
262 return {
263 name,
264 hubId: parsed.hubId,
265 project: parsed.project || project,
266 location: parsed.location || DEFAULT_LOCATION,
267 description: hub.description,
268 exportPsc: hub.exportPsc === true,
269 policyMode: hub.policyMode,
270 presetTopology: hub.presetTopology,
271 labels: userLabels(hub.labels),
272 uniqueId: hub.uniqueId,
273 state: hub.state,
274 routingVpcs: toRoutingVpcs(hub.routingVpcs),
275 routeTables: hub.routeTables ?? [],
276 createTime: hub.createTime,
277 updateTime: hub.updateTime,
278 };
279 };
280
281 const getByName = (name: string) =>
282 networkconnectivity
283 .getProjectsLocationsGlobalHubs({ name })
284 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
285
286 const isPendingState = (state: string | undefined) =>
287 state === "CREATING" ||
288 state === "UPDATING" ||
289 state === "DELETING" ||
290 state === "ACCEPTING" ||
291 state === "REJECTING" ||
292 state === "STATE_UNSPECIFIED";
293
294 const waitUntilReady = (name: string) =>
295 getByName(name).pipe(
296 Effect.filterOrFail(
297 (hub): hub is networkconnectivity.Hub => hub !== undefined,
298 () => new HubNotResolved({ resourceName: name }),
299 ),
300 Effect.filterOrFail(
301 (hub) => hub.state !== "FAILED" && hub.state !== "OBSOLETE",
302 (hub) => new HubFailed({ resourceName: name, state: hub.state }),
303 ),
304 Effect.filterOrFail(
305 (hub) => !isPendingState(hub.state),
306 () => new HubNotResolved({ resourceName: name }),
307 ),
308 Effect.retry({
309 while: (error) => error._tag === "GCP.NetworkConnectivity.HubNotResolved",
310 times: 10,
311 schedule: Schedule.spaced("2 seconds"),
312 }),
313 );
314
315 const waitUntilGone = (name: string) =>
316 getByName(name).pipe(
317 Effect.flatMap((hub) =>
318 hub === undefined ? Effect.void : Effect.fail(new HubStillExists({ resourceName: name })),
319 ),
320 Effect.retry({
321 while: (error) => error._tag === "GCP.NetworkConnectivity.HubStillExists",
322 times: 10,
323 schedule: Schedule.spaced("3 seconds"),
324 }),
325 );
326
327 const listOwnedHubs = (project: string) =>
328 networkconnectivity.listProjectsLocationsGlobalHubs
329 .pages({
330 parent: parentOf(project),
331 pageSize: 1000,
332 })
333 .pipe(
334 Stream.flatMap((page) => Stream.fromIterable(page.hubs ?? [])),
335 Stream.filter((hub) =>
336 Object.keys(hub.labels ?? {}).some((key) => key.startsWith("alchemy-")),
337 ),
338 Stream.map((hub) => toAttrs(hub, project)),
339 Stream.runCollect,
340 Effect.map((chunk) => Array.from(chunk)),
341 Effect.catchTag("NotFound", () => Effect.succeed([])),
342 );
343
344 export const HubProvider = () =>
345 Provider.succeed(Hub, {
346 stables: ["name", "hubId", "project", "location", "uniqueId", "createTime"],
347
348 diff: Effect.fn(function* ({ news, olds, output }) {
349 if (!isResolved(news)) return undefined;
350 const previousId = olds?.hubId ?? output?.hubId;
351 const nextId = news.hubId ?? previousId;
352 if (previousId !== undefined && nextId !== undefined && nextId !== previousId) {
353 return { action: "replace" as const };
354 }
355 return undefined;
356 }),
357
358 read: Effect.fn(function* ({ id, olds, output }) {
359 const env = yield* GcpEnvironment.current;
360 const hubId = yield* toId(id, olds?.hubId, output?.hubId);
361 const name = output?.name ?? resourceName(env.project, hubId);
362 const existing = yield* getByName(name);
363 if (existing === undefined) return undefined;
364 const attrs = toAttrs(existing, env.project);
365 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
366 }),
367
368 list: () =>
369 Effect.gen(function* () {
370 const env = yield* GcpEnvironment.current;
371 return yield* listOwnedHubs(env.project);
372 }),
373
374 reconcile: Effect.fn(function* ({ id, news, output }) {
375 const env = yield* GcpEnvironment.current;
376 const hubId = yield* toId(id, news.hubId, output?.hubId);
377 const name = output?.name ?? resourceName(env.project, hubId);
378 const desiredLabels = {
379 ...toLabels(news.labels),
380 ...(yield* createInternalLabels(id)),
381 };
382 const policyMode = desiredPolicyMode(news);
383 const presetTopology = desiredPresetTopology(news);
384 const exportPsc = news.exportPsc === true;
385
386 let current = yield* getByName(name);
387
388 if (current === undefined) {
389 const created = yield* networkconnectivity
390 .createProjectsLocationsGlobalHubs({
391 parent: parentOf(env.project),
392 hubId,
393 body: {
394 description: news.description,
395 labels: desiredLabels,
396 exportPsc,
397 policyMode,
398 presetTopology,
399 },
400 })
401 .pipe(
402 Effect.retry({
403 while: (error) => error._tag === "Conflict",
404 times: 5,
405 schedule: Schedule.spaced("2 seconds"),
406 }),
407 Effect.catchTag("Conflict", () => Effect.undefined),
408 );
409 if (created !== undefined) {
410 yield* waitForOperation(created);
411 }
412 current = yield* waitUntilReady(name);
413 }
414
415 if (current === undefined) {
416 return yield* new HubNotResolved({ resourceName: name });
417 }
418
419 const observedLabels = tagRecord(current.labels);
420 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
421 const labelsChanged = upsert.length > 0 || removed.length > 0;
422 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
423 const exportPscChanged = (current.exportPsc === true) !== exportPsc;
424 const policyModeChanged = (current.policyMode ?? DEFAULT_POLICY_MODE) !== policyMode;
425 const presetTopologyChanged =
426 (current.presetTopology ?? DEFAULT_PRESET_TOPOLOGY) !== presetTopology;
427
428 if (
429 labelsChanged ||
430 descriptionChanged ||
431 exportPscChanged ||
432 policyModeChanged ||
433 presetTopologyChanged
434 ) {
435 const updateMask = [
436 labelsChanged ? "labels" : undefined,
437 descriptionChanged ? "description" : undefined,
438 exportPscChanged ? "exportPsc" : undefined,
439 policyModeChanged ? "policyMode" : undefined,
440 presetTopologyChanged ? "presetTopology" : undefined,
441 ].filter((field): field is string => field !== undefined);
442
443 const operation = yield* networkconnectivity.patchProjectsLocationsGlobalHubs({
444 name: current.name ?? name,
445 updateMask: updateMask.join(","),
446 body: {
447 name: current.name ?? name,
448 labels: desiredLabels,
449 description: news.description,
450 exportPsc,
451 policyMode,
452 presetTopology,
453 },
454 });
455 yield* waitForOperation(operation);
456 current = yield* waitUntilReady(current.name ?? name);
457 }
458
459 return toAttrs(current, env.project);
460 }),
461
462 delete: Effect.fn(function* ({ output }) {
463 const operation = yield* networkconnectivity
464 .deleteProjectsLocationsGlobalHubs({ name: output.name })
465 .pipe(
466 Effect.retry({
467 while: (error) => error._tag === "Conflict",
468 times: 8,
469 schedule: Schedule.spaced("2 seconds"),
470 }),
471 Effect.catchTag("NotFound", () => Effect.undefined),
472 );
473 if (operation !== undefined) {
474 yield* waitForOperation(operation, { notFoundOk: true });
475 }
476 yield* waitUntilGone(output.name);
477 }),
478 });