@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 499 lines 16.8 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 { waitRegionOperation } from "./operations.ts";
22
23 const DEFAULT_GATEWAY_IP_VERSION = "IPV4";
24 const DEFAULT_STACK_TYPE = "IPV4_ONLY";
25 const MAX_NAME_LENGTH = 63;
26
27 export type VpnGatewayInterfaceProps = {
28 /**
29 * Interface id (`0` or `1`). Required when attaching a VLAN
30 * attachment for HA VPN over Cloud Interconnect.
31 */
32 id?: number;
33 /**
34 * VLAN attachment URL for HA VPN over Cloud Interconnect. Immutable —
35 * changing it replaces the gateway.
36 */
37 interconnectAttachment?: string;
38 };
39
40 export type VpnGatewayInterface = {
41 /** Numeric interface id (`0` or `1`). */
42 id: number | undefined;
43 /** Regional external or internal IPv4 address. */
44 ipAddress: string | undefined;
45 /** Regional external IPv6 address, if any. */
46 ipv6Address: string | undefined;
47 /** VLAN attachment URL, if this interface is over Cloud Interconnect. */
48 interconnectAttachment: string | undefined;
49 };
50
51 export type VpnGatewayProps = {
52 /**
53 * Gateway name. If omitted, a unique RFC1035 name is generated from
54 * the stack, stage, and logical id. Immutable — changing it replaces
55 * the gateway.
56 */
57 vpnGatewayName?: string;
58 /**
59 * Region the HA VPN gateway lives in. Immutable — changing it
60 * replaces the gateway. `US-CENTRAL1` is accepted and normalized to
61 * `us-central1`.
62 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
63 */
64 region?: string;
65 /**
66 * VPC network this gateway is attached to. Accepts a name
67 * (`default`), a partial URL (`global/networks/default`), or a full
68 * resource URL. Immutable — changing it replaces the gateway.
69 */
70 network: string;
71 /**
72 * Optional description. Immutable — changing it replaces the
73 * gateway.
74 */
75 description?: string;
76 /**
77 * IP family of the gateway interface addresses (`IPV4` or `IPV6`).
78 * Immutable — changing it replaces the gateway.
79 * @default "IPV4"
80 */
81 gatewayIpVersion?: compute.VpnGatewayGatewayIpVersionEnum | (string & {});
82 /**
83 * IP stack enabled on the gateway (`IPV4_ONLY`, `IPV4_IPV6`,
84 * `IPV6_ONLY`). Immutable — changing it replaces the gateway.
85 * @default "IPV4_ONLY"
86 */
87 stackType?: compute.VpnGatewayStackTypeEnum | (string & {});
88 /**
89 * VPN interfaces. Omit for a regular HA VPN (GCP allocates two
90 * regional external IPs). Set `interconnectAttachment` for HA VPN
91 * over Cloud Interconnect. Immutable — changing it replaces the
92 * gateway.
93 */
94 vpnInterfaces?: VpnGatewayInterfaceProps[];
95 /**
96 * User labels. Alchemy ownership labels are merged in automatically
97 * and synced via `setLabels` (labels cannot be set on insert).
98 */
99 labels?: Record<string, string>;
100 };
101
102 export type VpnGateway = Resource<
103 "GCP.Compute.VpnGateway",
104 VpnGatewayProps,
105 {
106 /** Gateway name. */
107 vpnGatewayName: string;
108 /** Project id. */
109 project: string;
110 /** Region short name (`us-central1`). */
111 region: string;
112 /** Network URL. */
113 network: string | undefined;
114 /** Server-assigned numeric id. */
115 vpnGatewayId: string | undefined;
116 /** Resource self-link. */
117 selfLink: string | undefined;
118 /** Description. */
119 description: string | undefined;
120 /** Gateway interface IP family. */
121 gatewayIpVersion: string | undefined;
122 /** Enabled IP stack. */
123 stackType: string | undefined;
124 /** VPN interfaces (ids, IPs, optional VLAN attachments). */
125 vpnInterfaces: ReadonlyArray<VpnGatewayInterface>;
126 /** User labels (Alchemy ownership labels stripped). */
127 labels: Record<string, string>;
128 /** RFC3339 creation timestamp. */
129 creationTimestamp: string | undefined;
130 },
131 never,
132 Providers
133 >;
134
135 /**
136 * A regional Compute Engine HA VPN gateway.
137 *
138 * HA VPN is a high-availability Cloud VPN that attaches two interfaces
139 * to a VPC in a single region. Labels are the only in-place update
140 * (`vpnGateways.setLabels`); name, region, network, description, IP
141 * version, stack type, and interconnect attachments replace the
142 * gateway.
143 *
144 * ### Creating a VpnGateway
145 * **Example:** Generated name on a custom VPC
146 * ```typescript
147 * const network = yield* GCP.Compute.Network("Vpc", {
148 * autoCreateSubnetworks: false,
149 * });
150 * const gateway = yield* GCP.Compute.VpnGateway("Gateway", {
151 * network: network.networkName,
152 * });
153 * ```
154 *
155 * **Example:** Named gateway with labels
156 * ```typescript
157 * const gateway = yield* GCP.Compute.VpnGateway("Gateway", {
158 * vpnGatewayName: "app-vpn",
159 * region: "us-central1",
160 * network: "default",
161 * description: "ha vpn",
162 * labels: { env: "prod" },
163 * });
164 * ```
165 *
166 * ### Dual-stack HA VPN
167 * **Example:** IPv4/IPv6 stack
168 * ```typescript
169 * const gateway = yield* GCP.Compute.VpnGateway("Gateway", {
170 * network: "default",
171 * stackType: "IPV4_IPV6",
172 * });
173 * ```
174 *
175 * @resource
176 * @category Compute
177 */
178 export const VpnGateway = Resource<VpnGateway>("GCP.Compute.VpnGateway");
179
180 export class VpnGatewayNotResolved extends Data.TaggedError("GCP.Compute.VpnGatewayNotResolved")<{
181 vpnGatewayName: string;
182 region: string;
183 }> {}
184
185 export class VpnGatewayPending extends Data.TaggedError("GCP.Compute.VpnGatewayPending")<{
186 vpnGatewayName: string;
187 status: string;
188 }> {}
189
190 const userLabels = (
191 labels: Record<string, string | undefined> | null | undefined,
192 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
193
194 const lastSegment = (value: string) => {
195 const trimmed = value.replace(/\/+$/, "");
196 const parts = trimmed.split("/");
197 return parts[parts.length - 1] || trimmed;
198 };
199
200 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
201 lastSegment(region ?? defaultRegion).toLowerCase();
202
203 const resourceRefOf = (value: string | undefined) => {
204 if (!value) return "";
205 return lastSegment(value);
206 };
207
208 const gatewayIpVersionOf = (value: string | undefined) => value ?? DEFAULT_GATEWAY_IP_VERSION;
209
210 const stackTypeOf = (value: string | undefined) => value ?? DEFAULT_STACK_TYPE;
211
212 const networkUrl = (project: string, network: string) => {
213 if (network.includes("/")) {
214 return network.startsWith("projects/") || network.startsWith("http")
215 ? network
216 : `projects/${project}/${network.replace(/^\//, "")}`;
217 }
218 return `projects/${project}/global/networks/${network}`;
219 };
220
221 const toName = (id: string, name: string | undefined, existing?: string) =>
222 Effect.gen(function* () {
223 if (name !== undefined) return name;
224 if (existing !== undefined) return existing;
225 const generated = yield* createPhysicalName({
226 id,
227 maxLength: MAX_NAME_LENGTH,
228 lowercase: true,
229 });
230 const rfc = generated.replace(/^[^a-z]+/, "v").replace(/-+$/g, "");
231 return rfc.slice(0, MAX_NAME_LENGTH);
232 });
233
234 const toInterfaces = (
235 interfaces: compute.VpnGatewayVpnGatewayInterfaceList | undefined,
236 ): VpnGatewayInterface[] =>
237 (interfaces ?? []).map((iface) => ({
238 id: iface.id,
239 ipAddress: iface.ipAddress,
240 ipv6Address: iface.ipv6Address,
241 interconnectAttachment: iface.interconnectAttachment,
242 }));
243
244 const attachmentKey = (
245 interfaces: ReadonlyArray<{
246 id?: number;
247 interconnectAttachment?: string;
248 }>,
249 ) =>
250 interfaces
251 .map((iface) => `${iface.id ?? ""}:${resourceRefOf(iface.interconnectAttachment)}`)
252 .sort()
253 .join("|");
254
255 const toAttrs = (gateway: compute.VpnGateway, project: string) => ({
256 vpnGatewayName: gateway.name ?? "",
257 project,
258 region: lastSegment(gateway.region ?? "").toLowerCase(),
259 network: gateway.network,
260 vpnGatewayId: gateway.id,
261 selfLink: gateway.selfLink,
262 description: gateway.description,
263 gatewayIpVersion: gateway.gatewayIpVersion,
264 stackType: gateway.stackType,
265 vpnInterfaces: toInterfaces(gateway.vpnInterfaces),
266 labels: userLabels(gateway.labels),
267 creationTimestamp: gateway.creationTimestamp,
268 });
269
270 const getByName = (project: string, region: string, vpnGateway: string) =>
271 compute
272 .getVpnGateways({ project, region, vpnGateway })
273 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
274
275 const requireGateway = (project: string, region: string, vpnGatewayName: string) =>
276 getByName(project, region, vpnGatewayName).pipe(
277 Effect.flatMap((gateway) =>
278 gateway
279 ? Effect.succeed(gateway)
280 : Effect.fail(new VpnGatewayNotResolved({ vpnGatewayName, region })),
281 ),
282 Effect.retry({
283 while: (e) => e._tag === "GCP.Compute.VpnGatewayNotResolved",
284 schedule: Schedule.spaced("1 second"),
285 times: 8,
286 }),
287 );
288
289 const waitUntilGone = (project: string, region: string, vpnGatewayName: string) =>
290 getByName(project, region, vpnGatewayName).pipe(
291 Effect.flatMap((gateway) =>
292 gateway === undefined
293 ? Effect.void
294 : Effect.fail(
295 new VpnGatewayPending({
296 vpnGatewayName,
297 status: "EXISTS",
298 }),
299 ),
300 ),
301 Effect.retry({
302 while: (e) => e._tag === "GCP.Compute.VpnGatewayPending",
303 times: 10,
304 schedule: Schedule.spaced("2 seconds"),
305 }),
306 );
307
308 export const VpnGatewayProvider = () =>
309 Provider.succeed(VpnGateway, {
310 stables: [
311 "vpnGatewayName",
312 "project",
313 "region",
314 "network",
315 "vpnGatewayId",
316 "selfLink",
317 "gatewayIpVersion",
318 "stackType",
319 "creationTimestamp",
320 ],
321
322 diff: Effect.fn(function* ({ news, olds, output }) {
323 if (!isResolved(news)) return undefined;
324 const env = yield* GcpEnvironment.current;
325 const previousName = olds.vpnGatewayName ?? output?.vpnGatewayName;
326 const nextName = news.vpnGatewayName ?? previousName;
327 const nameChanged =
328 previousName !== undefined && nextName !== undefined && nextName !== previousName;
329
330 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
331 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
332 const regionChanged = previousRegion !== nextRegion;
333
334 const previousNetwork = resourceRefOf(olds.network ?? output?.network);
335 const nextNetwork = resourceRefOf(news.network);
336 const previousDescription = olds.description ?? output?.description ?? "";
337 const previousIpVersion = gatewayIpVersionOf(
338 olds.gatewayIpVersion ?? output?.gatewayIpVersion,
339 );
340 const previousStack = stackTypeOf(olds.stackType ?? output?.stackType);
341 const previousAttachments = attachmentKey(output?.vpnInterfaces ?? olds.vpnInterfaces ?? []);
342
343 const immutableChanged =
344 nextNetwork !== previousNetwork ||
345 (news.description !== undefined && (news.description ?? "") !== previousDescription) ||
346 (news.gatewayIpVersion !== undefined &&
347 gatewayIpVersionOf(news.gatewayIpVersion) !== previousIpVersion) ||
348 (news.stackType !== undefined && stackTypeOf(news.stackType) !== previousStack) ||
349 (news.vpnInterfaces !== undefined &&
350 attachmentKey(news.vpnInterfaces) !== previousAttachments);
351
352 if (nameChanged || regionChanged) {
353 return { action: "replace" as const, deleteFirst: false };
354 }
355 if (immutableChanged) {
356 return { action: "replace" as const, deleteFirst: true };
357 }
358 return undefined;
359 }),
360
361 read: Effect.fn(function* ({ id, olds, output, previous }) {
362 const env = yield* GcpEnvironment.current;
363 const vpnGatewayName = yield* toName(id, olds?.vpnGatewayName, output?.vpnGatewayName);
364 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
365 const existing = yield* getByName(env.project, region, vpnGatewayName);
366 if (existing === undefined) return undefined;
367 const attrs = toAttrs(existing, env.project);
368 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
369 ? attrs
370 : unownedUnlessPrevious(attrs, previous, "vpnGatewayName");
371 }),
372
373 list: () =>
374 Effect.gen(function* () {
375 const env = yield* GcpEnvironment.current;
376 const pages = yield* compute.aggregatedListVpnGateways
377 .pages({
378 project: env.project,
379 filter: "labels.alchemy-id:*",
380 returnPartialSuccess: true,
381 maxResults: 500,
382 })
383 .pipe(Stream.runCollect);
384 return Array.from(pages).flatMap((page) =>
385 Object.values(page.items ?? {}).flatMap((scoped) =>
386 (scoped?.vpnGateways ?? [])
387 .filter((gateway) =>
388 Object.keys(gateway.labels ?? {}).some((key) => key.startsWith("alchemy-")),
389 )
390 .map((gateway) => toAttrs(gateway, env.project)),
391 ),
392 );
393 }),
394
395 reconcile: Effect.fn(function* ({ id, news, output }) {
396 const env = yield* GcpEnvironment.current;
397 const vpnGatewayName = yield* toName(id, news.vpnGatewayName, output?.vpnGatewayName);
398 const region = normalizeRegion(news.region ?? output?.region, env.region);
399 const desiredLabels = {
400 ...toLabels(news.labels),
401 ...(yield* createInternalLabels(id)),
402 };
403
404 let current = yield* getByName(env.project, region, vpnGatewayName);
405
406 if (current === undefined) {
407 const body: compute.VpnGateway = {
408 name: vpnGatewayName,
409 network: networkUrl(env.project, news.network),
410 description: news.description,
411 gatewayIpVersion: news.gatewayIpVersion,
412 stackType: news.stackType,
413 };
414 if (news.vpnInterfaces !== undefined && news.vpnInterfaces.length > 0) {
415 body.vpnInterfaces = news.vpnInterfaces.map((iface) => ({
416 id: iface.id,
417 interconnectAttachment: iface.interconnectAttachment,
418 }));
419 }
420 const created = yield* compute
421 .insertVpnGateways({
422 project: env.project,
423 region,
424 body,
425 })
426 .pipe(
427 Effect.flatMap((operation) =>
428 waitRegionOperation(env.project, region, operation, {
429 ignore: ["RESOURCE_ALREADY_EXISTS"],
430 }).pipe(Effect.flatMap(() => requireGateway(env.project, region, vpnGatewayName))),
431 ),
432 Effect.catchTag("Conflict", () => getByName(env.project, region, vpnGatewayName)),
433 );
434 current = created ?? undefined;
435 }
436
437 if (current === undefined) {
438 return yield* new VpnGatewayNotResolved({ vpnGatewayName, region });
439 }
440
441 const resolved = current;
442 const observedLabels = tagRecord(resolved.labels);
443 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
444 if (upsert.length > 0 || removed.length > 0) {
445 yield* Effect.gen(function* () {
446 const latest = (yield* getByName(env.project, region, vpnGatewayName)) ?? resolved;
447 yield* compute
448 .setLabelsVpnGateways({
449 project: env.project,
450 region,
451 resource: vpnGatewayName,
452 body: {
453 labels: desiredLabels,
454 labelFingerprint: latest.labelFingerprint,
455 },
456 })
457 .pipe(
458 Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)),
459 );
460 }).pipe(
461 Effect.retry({
462 while: (e) => e._tag === "Conflict",
463 times: 5,
464 schedule: Schedule.spaced("1 second"),
465 }),
466 );
467 current = (yield* getByName(env.project, region, vpnGatewayName)) ?? resolved;
468 }
469
470 return toAttrs(current ?? resolved, env.project);
471 }),
472
473 delete: Effect.fn(function* ({ output }) {
474 const env = yield* GcpEnvironment.current;
475 const project = output.project || env.project;
476 const region = normalizeRegion(output.region, env.region);
477 if (!output.vpnGatewayName) return;
478 yield* compute
479 .deleteVpnGateways({
480 project,
481 region,
482 vpnGateway: output.vpnGatewayName,
483 })
484 .pipe(
485 Effect.flatMap((operation) =>
486 waitRegionOperation(project, region, operation, {
487 ignore: ["RESOURCE_NOT_FOUND"],
488 }),
489 ),
490 Effect.catchTag("NotFound", () => Effect.void),
491 Effect.retry({
492 while: (e) => e._tag === "Conflict",
493 times: 8,
494 schedule: Schedule.spaced("2 seconds"),
495 }),
496 );
497 yield* waitUntilGone(project, region, output.vpnGatewayName);
498 }),
499 });