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

main
ts 600 lines 21 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { ignoredCodes } from "./internal.ts";
22 import { waitGlobalOperation } from "./operations.ts";
23
24 const MAX_NAME_LENGTH = 63;
25 const DEFAULT_TYPE = "DEDICATED";
26 const DEFAULT_LINK_TYPE = "LINK_TYPE_ETHERNET_10G_LR";
27
28 export type InterconnectType = compute.InterconnectInterconnectTypeEnum | (string & {});
29 export type InterconnectLinkType = compute.InterconnectLinkTypeEnum | (string & {});
30 export type InterconnectMacsec = compute.InterconnectMacsec;
31 export type InterconnectApplicationAware = compute.InterconnectApplicationAwareInterconnect;
32
33 export type InterconnectProps = {
34 /**
35 * Interconnect name (RFC1035, 1-63 characters). If omitted, a unique
36 * name is generated from the stack, stage, and logical id. Immutable —
37 * changing it replaces the interconnect.
38 */
39 interconnectName?: string;
40 /**
41 * URL or name of the InterconnectLocation (for example
42 * `iad-zone1-1`). Immutable — changing it replaces the interconnect.
43 */
44 location: string;
45 /**
46 * Dedicated physical interconnection or partner-managed. Immutable —
47 * changing it replaces the interconnect.
48 * @default "DEDICATED"
49 */
50 interconnectType?: InterconnectType;
51 /**
52 * Speed of each physical link in the bundle. Immutable — changing it
53 * replaces the interconnect.
54 * @default "LINK_TYPE_ETHERNET_10G_LR"
55 */
56 linkType?: InterconnectLinkType;
57 /**
58 * Target number of physical links in the bundle. Updated in place.
59 * @default 1
60 */
61 requestedLinkCount?: number;
62 /**
63 * Customer name for the Letter of Authorization. Immutable — changing
64 * it replaces the interconnect.
65 */
66 customerName?: string;
67 /**
68 * Optional description. Updated in place via `interconnects.patch`.
69 */
70 description?: string;
71 /**
72 * NOC contact email for operations notifications. Updated in place.
73 */
74 nocContactEmail?: string;
75 /**
76 * Administrative status. When `false`, the interconnect carries no
77 * packets. Updated in place.
78 * @default true
79 */
80 adminEnabled?: boolean;
81 /**
82 * Cross-Cloud Interconnect remote location URL. Immutable — changing
83 * it replaces the interconnect.
84 */
85 remoteLocation?: string;
86 /**
87 * Enable MACsec on this interconnect. Updated in place.
88 * @default false
89 */
90 macsecEnabled?: boolean;
91 /**
92 * MACsec pre-shared keys and configuration. Updated in place.
93 */
94 macsec?: InterconnectMacsec;
95 /**
96 * Features requested at create time (`IF_MACSEC`,
97 * `IF_CROSS_SITE_NETWORK`). Immutable — changing them replaces the
98 * interconnect.
99 */
100 requestedFeatures?: string[];
101 /**
102 * Enable application-aware interconnect. Updated in place.
103 */
104 aaiEnabled?: boolean;
105 /**
106 * Application-aware interconnect configuration. Updated in place.
107 */
108 applicationAwareInterconnect?: InterconnectApplicationAware;
109 /**
110 * User labels. Alchemy ownership labels are merged in automatically
111 * and synced via `setLabels` (labels cannot be set on insert).
112 */
113 labels?: Record<string, string>;
114 };
115
116 export type Interconnect = Resource<
117 "GCP.Compute.Interconnect",
118 InterconnectProps,
119 {
120 /** Interconnect name. */
121 interconnectName: string;
122 /** Project id. */
123 project: string;
124 /** Interconnect location URL. */
125 location: string | undefined;
126 /** Interconnect type (`DEDICATED` or `PARTNER`). */
127 interconnectType: string | undefined;
128 /** Link type. */
129 linkType: string | undefined;
130 /** Requested number of physical links. */
131 requestedLinkCount: number | undefined;
132 /** Provisioned number of physical links. */
133 provisionedLinkCount: number | undefined;
134 /** Customer name on the LOA. */
135 customerName: string | undefined;
136 /** Description. */
137 description: string | undefined;
138 /** NOC contact email. */
139 nocContactEmail: string | undefined;
140 /** Administrative status. */
141 adminEnabled: boolean;
142 /** Remote location URL for Cross-Cloud Interconnect. */
143 remoteLocation: string | undefined;
144 /** Whether MACsec is enabled. */
145 macsecEnabled: boolean;
146 /** MACsec configuration. */
147 macsec: InterconnectMacsec | undefined;
148 /** Requested features. */
149 requestedFeatures: ReadonlyArray<string>;
150 /** Available features. */
151 availableFeatures: ReadonlyArray<string>;
152 /** Application-aware interconnect enabled. */
153 aaiEnabled: boolean;
154 /** Application-aware interconnect config. */
155 applicationAwareInterconnect: InterconnectApplicationAware | undefined;
156 /** User labels (Alchemy ownership labels stripped). */
157 labels: Record<string, string>;
158 /** Google reference id. */
159 googleReferenceId: string | undefined;
160 /** Operational status. */
161 operationalStatus: string | undefined;
162 /** Resource state. */
163 state: string | undefined;
164 /** Google-side ping IP. */
165 googleIpAddress: string | undefined;
166 /** Customer-side ping IP. */
167 peerIpAddress: string | undefined;
168 /** Attachment URLs using this interconnect. */
169 interconnectAttachments: ReadonlyArray<string>;
170 /** Interconnect group URLs. */
171 interconnectGroups: ReadonlyArray<string>;
172 /** Server-assigned numeric id. */
173 interconnectId: string | undefined;
174 /** Resource self-link. */
175 selfLink: string | undefined;
176 /** Label fingerprint for `setLabels`. */
177 labelFingerprint: 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 global Compute Engine Dedicated Interconnect.
189 *
190 * Dedicated Interconnect is a physical connection between your on-premises
191 * network and Google's network at a colocation facility. Name, location,
192 * interconnect type, link type, customer name, remote location, and
193 * requested features are immutable. Description, admin status, link count,
194 * NOC email, and MACsec update in place via `interconnects.patch`. Labels
195 * are applied with `setLabels` after the interconnect exists.
196 *
197 * ### Creating an Interconnect
198 * **Example:** Dedicated 10G interconnect
199 * ```typescript
200 * const interconnect = yield* GCP.Compute.Interconnect("OnPrem", {
201 * location: "iad-zone1-1",
202 * interconnectType: "DEDICATED",
203 * linkType: "LINK_TYPE_ETHERNET_10G_LR",
204 * requestedLinkCount: 1,
205 * customerName: "Example Corp",
206 * description: "prod interconnect",
207 * });
208 * ```
209 *
210 * **Example:** Named interconnect with labels
211 * ```typescript
212 * const interconnect = yield* GCP.Compute.Interconnect("OnPrem", {
213 * interconnectName: "app-ix",
214 * location: "iad-zone1-1",
215 * customerName: "Example Corp",
216 * labels: { env: "prod" },
217 * });
218 * ```
219 *
220 * @resource
221 * @category Compute
222 */
223 export const Interconnect = Resource<Interconnect>("GCP.Compute.Interconnect");
224
225 export class InterconnectNotResolved extends Data.TaggedError(
226 "GCP.Compute.InterconnectNotResolved",
227 )<{
228 interconnectName: string;
229 }> {}
230
231 export class InterconnectStillExists extends Data.TaggedError(
232 "GCP.Compute.InterconnectStillExists",
233 )<{
234 interconnectName: string;
235 }> {}
236
237 const lastSegment = (value: string | undefined): string => {
238 if (value === undefined || value.length === 0) return "";
239 const trimmed = value.replace(/\/+$/, "");
240 const parts = trimmed.split("/");
241 return parts[parts.length - 1] || trimmed;
242 };
243
244 const rfc1035 = (name: string): string => {
245 let next = name
246 .toLowerCase()
247 .replace(/[^a-z0-9-]/g, "-")
248 .replace(/-+/g, "-")
249 .replace(/^-+/, "")
250 .replace(/-+$/, "");
251 if (!/^[a-z]/.test(next)) next = `i${next}`;
252 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
253 return next.length > 0 ? next : "interconnect";
254 };
255
256 const toName = (id: string, name: string | undefined, existing?: string) =>
257 Effect.gen(function* () {
258 if (name !== undefined) return name;
259 if (existing !== undefined) return existing;
260 return rfc1035(
261 yield* createPhysicalName({
262 id,
263 maxLength: MAX_NAME_LENGTH,
264 lowercase: true,
265 }),
266 );
267 });
268
269 const locationUrl = (project: string, location: string) => {
270 if (location.includes("/")) return location;
271 return `projects/${project}/global/interconnectLocations/${location}`;
272 };
273
274 const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase();
275
276 const linkTypeOf = (value: string | undefined) => value ?? DEFAULT_LINK_TYPE;
277
278 const featuresKey = (values: ReadonlyArray<string> | undefined) =>
279 [...(values ?? [])]
280 .map((value) => value.toUpperCase())
281 .sort()
282 .join(",");
283
284 const userLabels = (
285 labels: Record<string, string | undefined> | null | undefined,
286 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
287
288 const toAttrs = (
289 interconnect: compute.Interconnect,
290 project: string,
291 ): Interconnect["Attributes"] => ({
292 interconnectName: interconnect.name ?? "",
293 project,
294 location: interconnect.location,
295 interconnectType: interconnect.interconnectType,
296 linkType: interconnect.linkType,
297 requestedLinkCount: interconnect.requestedLinkCount,
298 provisionedLinkCount: interconnect.provisionedLinkCount,
299 customerName: interconnect.customerName,
300 description: interconnect.description,
301 nocContactEmail: interconnect.nocContactEmail,
302 adminEnabled: interconnect.adminEnabled !== false,
303 remoteLocation: interconnect.remoteLocation,
304 macsecEnabled: interconnect.macsecEnabled === true,
305 macsec: interconnect.macsec,
306 requestedFeatures: interconnect.requestedFeatures ?? [],
307 availableFeatures: interconnect.availableFeatures ?? [],
308 aaiEnabled: interconnect.aaiEnabled === true,
309 applicationAwareInterconnect: interconnect.applicationAwareInterconnect,
310 labels: userLabels(interconnect.labels),
311 googleReferenceId: interconnect.googleReferenceId,
312 operationalStatus: interconnect.operationalStatus,
313 state: interconnect.state,
314 googleIpAddress: interconnect.googleIpAddress,
315 peerIpAddress: interconnect.peerIpAddress,
316 interconnectAttachments: interconnect.interconnectAttachments ?? [],
317 interconnectGroups: interconnect.interconnectGroups ?? [],
318 interconnectId: interconnect.id,
319 selfLink: interconnect.selfLink,
320 labelFingerprint: interconnect.labelFingerprint,
321 creationTimestamp: interconnect.creationTimestamp,
322 kind: interconnect.kind,
323 });
324
325 const getByName = (project: string, interconnect: string) =>
326 compute
327 .getInterconnects({ project, interconnect })
328 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
329
330 const awaitResource = (project: string, interconnectName: string) =>
331 getByName(project, interconnectName).pipe(
332 Effect.flatMap((resource) =>
333 resource !== undefined
334 ? Effect.succeed(resource)
335 : Effect.fail(new InterconnectNotResolved({ interconnectName })),
336 ),
337 Effect.retry({
338 while: (error) => error._tag === "GCP.Compute.InterconnectNotResolved",
339 times: 8,
340 schedule: Schedule.spaced("1 second"),
341 }),
342 );
343
344 const waitUntilGone = (project: string, interconnectName: string) =>
345 getByName(project, interconnectName).pipe(
346 Effect.flatMap((resource) =>
347 resource === undefined
348 ? Effect.void
349 : Effect.fail(new InterconnectStillExists({ interconnectName })),
350 ),
351 Effect.retry({
352 while: (error) => error._tag === "GCP.Compute.InterconnectStillExists",
353 times: 10,
354 schedule: Schedule.spaced("2 seconds"),
355 }),
356 Effect.catchTag("GCP.Compute.InterconnectStillExists", () => Effect.void),
357 );
358
359 const runOp = <E extends { readonly _tag: string }, R>(
360 project: string,
361 interconnectName: string,
362 start: Effect.Effect<compute.Operation, E, R>,
363 options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean },
364 ) =>
365 start.pipe(
366 Effect.flatMap((operation) =>
367 waitGlobalOperation(project, operation, {
368 ignore: ignoredCodes(options),
369 }),
370 ),
371 Effect.retry({
372 while: (error) => error._tag === "Conflict",
373 times: 5,
374 schedule: Schedule.spaced("1 second"),
375 }),
376 );
377
378 export const InterconnectProvider = () =>
379 Provider.succeed(Interconnect, {
380 stables: [
381 "interconnectName",
382 "project",
383 "interconnectId",
384 "selfLink",
385 "location",
386 "interconnectType",
387 "linkType",
388 "creationTimestamp",
389 ],
390
391 diff: Effect.fn(function* ({ news, olds, output }) {
392 if (!isResolved(news)) return undefined;
393 const previousName = olds?.interconnectName ?? output?.interconnectName;
394 const nextName = news.interconnectName ?? previousName;
395 const nameChanged =
396 previousName !== undefined && nextName !== undefined && previousName !== nextName;
397
398 const previousLocation = lastSegment(olds?.location ?? output?.location);
399 const nextLocation = lastSegment(news.location ?? previousLocation);
400 const previousType = typeOf(olds?.interconnectType ?? output?.interconnectType);
401 const nextType = typeOf(news.interconnectType ?? previousType);
402 const previousLink = linkTypeOf(olds?.linkType ?? output?.linkType);
403 const nextLink = linkTypeOf(news.linkType ?? previousLink);
404 const previousCustomer = olds?.customerName ?? output?.customerName ?? "";
405 const nextCustomer = news.customerName ?? previousCustomer;
406 const previousRemote = lastSegment(olds?.remoteLocation ?? output?.remoteLocation);
407 const nextRemote = lastSegment(news.remoteLocation ?? previousRemote);
408 const previousFeatures = featuresKey(olds?.requestedFeatures ?? output?.requestedFeatures);
409 const nextFeatures = featuresKey(
410 news.requestedFeatures ?? olds?.requestedFeatures ?? output?.requestedFeatures,
411 );
412
413 const immutableChanged =
414 previousLocation !== nextLocation ||
415 previousType !== nextType ||
416 previousLink !== nextLink ||
417 previousCustomer !== nextCustomer ||
418 previousRemote !== nextRemote ||
419 (news.requestedFeatures !== undefined && previousFeatures !== nextFeatures);
420
421 if (nameChanged) {
422 return { action: "replace" as const, deleteFirst: false };
423 }
424 if (immutableChanged) {
425 return { action: "replace" as const, deleteFirst: true };
426 }
427 return undefined;
428 }),
429
430 read: Effect.fn(function* ({ id, olds, output, previous }) {
431 const env = yield* GcpEnvironment.current;
432 const interconnectName = yield* toName(id, olds?.interconnectName, output?.interconnectName);
433 const existing = yield* getByName(env.project, interconnectName);
434 if (existing === undefined) return undefined;
435 const attrs = toAttrs(existing, env.project);
436 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
437 ? attrs
438 : unownedUnlessPrevious(attrs, previous, "interconnectName");
439 }),
440
441 list: () =>
442 Effect.gen(function* () {
443 const env = yield* GcpEnvironment.current;
444 return yield* compute.listInterconnects
445 .items({
446 project: env.project,
447 filter: "labels.alchemy-id:*",
448 maxResults: 500,
449 returnPartialSuccess: true,
450 })
451 .pipe(
452 Stream.filter((item) =>
453 Object.keys(item.labels ?? {}).some((key) => key.startsWith("alchemy-")),
454 ),
455 Stream.map((item) => toAttrs(item, env.project)),
456 Stream.runCollect,
457 Effect.map((items) => Array.from(items)),
458 Effect.catchTag("NotFound", () => Effect.succeed([] as Interconnect["Attributes"][])),
459 );
460 }),
461
462 reconcile: Effect.fn(function* ({ id, news, output }) {
463 const env = yield* GcpEnvironment.current;
464 const interconnectName = yield* toName(id, news.interconnectName, output?.interconnectName);
465 const desiredLabels = {
466 ...toLabels(news.labels),
467 ...(yield* createInternalLabels(id)),
468 };
469 const location = locationUrl(env.project, news.location);
470 const interconnectType = typeOf(news.interconnectType);
471 const linkType = linkTypeOf(news.linkType);
472 const requestedLinkCount = news.requestedLinkCount ?? 1;
473 const adminEnabled = news.adminEnabled !== false;
474
475 let current = yield* getByName(env.project, interconnectName);
476
477 if (current === undefined) {
478 yield* compute
479 .insertInterconnects({
480 project: env.project,
481 body: {
482 name: interconnectName,
483 location,
484 interconnectType,
485 linkType,
486 requestedLinkCount,
487 customerName: news.customerName,
488 description: news.description,
489 nocContactEmail: news.nocContactEmail,
490 adminEnabled,
491 remoteLocation: news.remoteLocation,
492 macsecEnabled: news.macsecEnabled,
493 macsec: news.macsec,
494 requestedFeatures: news.requestedFeatures,
495 aaiEnabled: news.aaiEnabled,
496 applicationAwareInterconnect: news.applicationAwareInterconnect,
497 },
498 })
499 .pipe(
500 Effect.flatMap((operation) =>
501 waitGlobalOperation(env.project, operation, {
502 ignore: ["RESOURCE_ALREADY_EXISTS"],
503 }),
504 ),
505 Effect.catchTag("Conflict", () => Effect.void),
506 );
507 current = yield* awaitResource(env.project, interconnectName);
508 }
509
510 const needsPatch =
511 (current.description ?? "") !== (news.description ?? "") ||
512 (current.nocContactEmail ?? "") !== (news.nocContactEmail ?? "") ||
513 (current.adminEnabled !== false) !== adminEnabled ||
514 (news.requestedLinkCount !== undefined &&
515 (current.requestedLinkCount ?? 1) !== requestedLinkCount) ||
516 (current.macsecEnabled === true) !== (news.macsecEnabled === true) ||
517 (news.macsec !== undefined &&
518 JSON.stringify(current.macsec ?? null) !== JSON.stringify(news.macsec ?? null)) ||
519 (news.aaiEnabled !== undefined && (current.aaiEnabled === true) !== news.aaiEnabled);
520
521 if (needsPatch) {
522 yield* runOp(
523 env.project,
524 interconnectName,
525 compute.patchInterconnects({
526 project: env.project,
527 interconnect: interconnectName,
528 body: {
529 description: news.description,
530 nocContactEmail: news.nocContactEmail,
531 adminEnabled,
532 requestedLinkCount,
533 macsecEnabled: news.macsecEnabled,
534 macsec: news.macsec,
535 aaiEnabled: news.aaiEnabled,
536 applicationAwareInterconnect: news.applicationAwareInterconnect,
537 },
538 }),
539 );
540 current = (yield* getByName(env.project, interconnectName)) ?? current;
541 }
542
543 const observedLabels = tagRecord(current.labels);
544 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
545 if (upsert.length > 0 || removed.length > 0) {
546 yield* Effect.gen(function* () {
547 const latest = (yield* getByName(env.project, interconnectName)) ?? current;
548 if (latest === undefined) {
549 return yield* new InterconnectNotResolved({ interconnectName });
550 }
551 yield* runOp(
552 env.project,
553 interconnectName,
554 compute.setLabelsInterconnects({
555 project: env.project,
556 resource: interconnectName,
557 body: {
558 labels: desiredLabels,
559 labelFingerprint: latest.labelFingerprint,
560 },
561 }),
562 );
563 }).pipe(
564 Effect.retry({
565 while: (error) => error._tag === "Conflict",
566 times: 5,
567 schedule: Schedule.spaced("1 second"),
568 }),
569 );
570 current = (yield* getByName(env.project, interconnectName)) ?? current;
571 }
572
573 return toAttrs(current, env.project);
574 }),
575
576 delete: Effect.fn(function* ({ output }) {
577 if (!output.interconnectName) return;
578 const env = yield* GcpEnvironment.current;
579 const project = output.project || env.project;
580 yield* compute
581 .deleteInterconnects({
582 project,
583 interconnect: output.interconnectName,
584 })
585 .pipe(
586 Effect.flatMap((operation) =>
587 waitGlobalOperation(project, operation, {
588 ignore: ["RESOURCE_NOT_FOUND"],
589 }),
590 ),
591 Effect.catchTag("NotFound", () => Effect.void),
592 Effect.retry({
593 while: (error) => error._tag === "Conflict",
594 times: 8,
595 schedule: Schedule.spaced("2 seconds"),
596 }),
597 );
598 yield* waitUntilGone(project, output.interconnectName);
599 }),
600 });