@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 435 lines 14.3 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 { waitGlobalOperation } from "./operations.ts";
22
23 const DEFAULT_REDUNDANCY_TYPE = "TWO_IPS_REDUNDANCY";
24 const MAX_NAME_LENGTH = 63;
25
26 export type ExternalVpnGatewayInterfaceProps = {
27 /**
28 * Numeric interface id. `0` for `SINGLE_IP_INTERNALLY_REDUNDANT`,
29 * `0` and `1` for `TWO_IPS_REDUNDANCY`, `0`–`3` for
30 * `FOUR_IPS_REDUNDANCY`.
31 */
32 id?: number;
33 /**
34 * IPv4 address of the peer VPN gateway interface. Must not be a
35 * Compute Engine IP. Immutable — changing it replaces the gateway.
36 */
37 ipAddress?: string;
38 /**
39 * IPv6 address of the peer VPN gateway interface (RFC 4291). Must
40 * not be a Compute Engine IP. Immutable — changing it replaces the
41 * gateway.
42 */
43 ipv6Address?: string;
44 };
45
46 export type ExternalVpnGatewayInterface = {
47 /** Numeric interface id. */
48 id: number | undefined;
49 /** Peer IPv4 address. */
50 ipAddress: string | undefined;
51 /** Peer IPv6 address, if any. */
52 ipv6Address: string | undefined;
53 };
54
55 export type ExternalVpnGatewayProps = {
56 /**
57 * Gateway name. If omitted, a unique RFC1035 name is generated from
58 * the stack, stage, and logical id. Immutable — changing it replaces
59 * the gateway.
60 */
61 externalVpnGatewayName?: string;
62 /**
63 * Optional description. Immutable — changing it replaces the
64 * gateway.
65 */
66 description?: string;
67 /**
68 * Peer redundancy. `SINGLE_IP_INTERNALLY_REDUNDANT` (one interface),
69 * `TWO_IPS_REDUNDANCY` (two interfaces), or `FOUR_IPS_REDUNDANCY`
70 * (four interfaces, typically AWS). Immutable — changing it
71 * replaces the gateway.
72 * @default "TWO_IPS_REDUNDANCY"
73 */
74 redundancyType?: compute.ExternalVpnGatewayRedundancyTypeEnum | (string & {});
75 /**
76 * Peer interfaces. Count must match `redundancyType`. Immutable —
77 * changing them replaces the gateway.
78 */
79 interfaces?: ExternalVpnGatewayInterfaceProps[];
80 /**
81 * User labels. Alchemy ownership labels are merged in automatically
82 * and synced via `setLabels` (labels cannot be set on insert).
83 */
84 labels?: Record<string, string>;
85 };
86
87 export type ExternalVpnGateway = Resource<
88 "GCP.Compute.ExternalVpnGateway",
89 ExternalVpnGatewayProps,
90 {
91 /** Gateway name. */
92 externalVpnGatewayName: string;
93 /** Project id. */
94 project: string;
95 /** Server-assigned numeric id. */
96 externalVpnGatewayId: string | undefined;
97 /** Resource self-link. */
98 selfLink: string | undefined;
99 /** Description. */
100 description: string | undefined;
101 /** Peer redundancy type. */
102 redundancyType: string | undefined;
103 /** Peer interfaces (ids and IPs). */
104 interfaces: ReadonlyArray<ExternalVpnGatewayInterface>;
105 /** User labels (Alchemy ownership labels stripped). */
106 labels: Record<string, string>;
107 /** RFC3339 creation timestamp. */
108 creationTimestamp: string | undefined;
109 },
110 never,
111 Providers
112 >;
113
114 /**
115 * A global Compute Engine external VPN gateway — the on-premises or
116 * other-cloud peer that an HA VPN gateway connects to.
117 *
118 * Labels are the only in-place update (`externalVpnGateways.setLabels`).
119 * Name, description, redundancy type, and interfaces replace the
120 * gateway.
121 *
122 * ### Creating an ExternalVpnGateway
123 * **Example:** Generated name with two peer IPs
124 * ```typescript
125 * const peer = yield* GCP.Compute.ExternalVpnGateway("Peer", {
126 * redundancyType: "TWO_IPS_REDUNDANCY",
127 * interfaces: [
128 * { id: 0, ipAddress: "203.0.113.1" },
129 * { id: 1, ipAddress: "203.0.113.2" },
130 * ],
131 * });
132 * ```
133 *
134 * **Example:** Named gateway with labels
135 * ```typescript
136 * const peer = yield* GCP.Compute.ExternalVpnGateway("Peer", {
137 * externalVpnGatewayName: "onprem-vpn",
138 * description: "on-prem peer",
139 * redundancyType: "SINGLE_IP_INTERNALLY_REDUNDANT",
140 * interfaces: [{ id: 0, ipAddress: "203.0.113.10" }],
141 * labels: { env: "prod" },
142 * });
143 * ```
144 *
145 * @resource
146 * @category Compute
147 */
148 export const ExternalVpnGateway = Resource<ExternalVpnGateway>("GCP.Compute.ExternalVpnGateway");
149
150 export class ExternalVpnGatewayNotResolved extends Data.TaggedError(
151 "GCP.Compute.ExternalVpnGatewayNotResolved",
152 )<{
153 externalVpnGatewayName: string;
154 }> {}
155
156 export class ExternalVpnGatewayPending extends Data.TaggedError(
157 "GCP.Compute.ExternalVpnGatewayPending",
158 )<{
159 externalVpnGatewayName: string;
160 status: string;
161 }> {}
162
163 const userLabels = (
164 labels: Record<string, string | undefined> | null | undefined,
165 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
166
167 const redundancyOf = (value: string | undefined, interfaces?: ReadonlyArray<unknown>) => {
168 if (value) return value;
169 const n = interfaces?.length ?? 0;
170 if (n === 1) return "SINGLE_IP_INTERNALLY_REDUNDANT";
171 if (n === 4) return "FOUR_IPS_REDUNDANCY";
172 return DEFAULT_REDUNDANCY_TYPE;
173 };
174
175 const toName = (id: string, name: string | undefined, existing?: string) =>
176 Effect.gen(function* () {
177 if (name !== undefined) return name;
178 if (existing !== undefined) return existing;
179 const generated = yield* createPhysicalName({
180 id,
181 maxLength: MAX_NAME_LENGTH,
182 lowercase: true,
183 });
184 const rfc = generated.replace(/^[^a-z]+/, "e").replace(/-+$/g, "");
185 return rfc.slice(0, MAX_NAME_LENGTH);
186 });
187
188 const toInterfaces = (
189 interfaces: compute.ExternalVpnGatewayInterfaceList | undefined,
190 ): ExternalVpnGatewayInterface[] =>
191 (interfaces ?? []).map((iface) => ({
192 id: iface.id,
193 ipAddress: iface.ipAddress,
194 ipv6Address: iface.ipv6Address,
195 }));
196
197 const interfaceKey = (
198 interfaces: ReadonlyArray<{
199 id?: number;
200 ipAddress?: string;
201 ipv6Address?: string;
202 }>,
203 ) =>
204 interfaces
205 .map((iface) => `${iface.id ?? ""}:${iface.ipAddress ?? ""}:${iface.ipv6Address ?? ""}`)
206 .sort()
207 .join("|");
208
209 const toAttrs = (gateway: compute.ExternalVpnGateway, project: string) => ({
210 externalVpnGatewayName: gateway.name ?? "",
211 project,
212 externalVpnGatewayId: gateway.id,
213 selfLink: gateway.selfLink,
214 description: gateway.description,
215 redundancyType: gateway.redundancyType,
216 interfaces: toInterfaces(gateway.interfaces),
217 labels: userLabels(gateway.labels),
218 creationTimestamp: gateway.creationTimestamp,
219 });
220
221 const getByName = (project: string, externalVpnGateway: string) =>
222 compute
223 .getExternalVpnGateways({ project, externalVpnGateway })
224 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
225
226 const requireGateway = (project: string, externalVpnGatewayName: string) =>
227 getByName(project, externalVpnGatewayName).pipe(
228 Effect.flatMap((gateway) =>
229 gateway
230 ? Effect.succeed(gateway)
231 : Effect.fail(new ExternalVpnGatewayNotResolved({ externalVpnGatewayName })),
232 ),
233 Effect.retry({
234 while: (e) => e._tag === "GCP.Compute.ExternalVpnGatewayNotResolved",
235 schedule: Schedule.spaced("1 second"),
236 times: 8,
237 }),
238 );
239
240 const waitUntilGone = (project: string, externalVpnGatewayName: string) =>
241 getByName(project, externalVpnGatewayName).pipe(
242 Effect.flatMap((gateway) =>
243 gateway === undefined
244 ? Effect.void
245 : Effect.fail(
246 new ExternalVpnGatewayPending({
247 externalVpnGatewayName,
248 status: "EXISTS",
249 }),
250 ),
251 ),
252 Effect.retry({
253 while: (e) => e._tag === "GCP.Compute.ExternalVpnGatewayPending",
254 times: 10,
255 schedule: Schedule.spaced("2 seconds"),
256 }),
257 );
258
259 export const ExternalVpnGatewayProvider = () =>
260 Provider.succeed(ExternalVpnGateway, {
261 stables: [
262 "externalVpnGatewayName",
263 "project",
264 "externalVpnGatewayId",
265 "selfLink",
266 "redundancyType",
267 "creationTimestamp",
268 ],
269
270 diff: Effect.fn(function* ({ news, olds, output }) {
271 if (!isResolved(news)) return undefined;
272 const previousName = olds.externalVpnGatewayName ?? output?.externalVpnGatewayName;
273 const nextName = news.externalVpnGatewayName ?? previousName;
274 const nameChanged =
275 previousName !== undefined && nextName !== undefined && nextName !== previousName;
276
277 const previousDescription = olds.description ?? output?.description ?? "";
278 const previousRedundancy = redundancyOf(
279 olds.redundancyType ?? output?.redundancyType,
280 olds.interfaces ?? output?.interfaces,
281 );
282 const previousInterfaces = interfaceKey(output?.interfaces ?? olds.interfaces ?? []);
283
284 const immutableChanged =
285 (news.description !== undefined && (news.description ?? "") !== previousDescription) ||
286 (news.redundancyType !== undefined &&
287 redundancyOf(news.redundancyType, news.interfaces) !== previousRedundancy) ||
288 (news.interfaces !== undefined && interfaceKey(news.interfaces) !== previousInterfaces);
289
290 if (nameChanged) {
291 return { action: "replace" as const, deleteFirst: false };
292 }
293 if (immutableChanged) {
294 return { action: "replace" as const, deleteFirst: true };
295 }
296 return undefined;
297 }),
298
299 read: Effect.fn(function* ({ id, olds, output, previous }) {
300 const env = yield* GcpEnvironment.current;
301 const externalVpnGatewayName = yield* toName(
302 id,
303 olds?.externalVpnGatewayName,
304 output?.externalVpnGatewayName,
305 );
306 const existing = yield* getByName(env.project, externalVpnGatewayName);
307 if (existing === undefined) return undefined;
308 const attrs = toAttrs(existing, env.project);
309 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
310 ? attrs
311 : unownedUnlessPrevious(attrs, previous, "externalVpnGatewayName");
312 }),
313
314 list: () =>
315 Effect.gen(function* () {
316 const env = yield* GcpEnvironment.current;
317 return yield* compute.listExternalVpnGateways
318 .items({
319 project: env.project,
320 filter: "labels.alchemy-id:*",
321 maxResults: 500,
322 })
323 .pipe(
324 Stream.filter((gateway) =>
325 Object.keys(gateway.labels ?? {}).some((key) => key.startsWith("alchemy-")),
326 ),
327 Stream.map((gateway) => toAttrs(gateway, env.project)),
328 Stream.runCollect,
329 Effect.map((chunk) => Array.from(chunk)),
330 );
331 }),
332
333 reconcile: Effect.fn(function* ({ id, news, output }) {
334 const env = yield* GcpEnvironment.current;
335 const externalVpnGatewayName = yield* toName(
336 id,
337 news.externalVpnGatewayName,
338 output?.externalVpnGatewayName,
339 );
340 const desiredLabels = {
341 ...toLabels(news.labels),
342 ...(yield* createInternalLabels(id)),
343 };
344
345 let current = yield* getByName(env.project, externalVpnGatewayName);
346
347 if (current === undefined) {
348 const body: compute.ExternalVpnGateway = {
349 name: externalVpnGatewayName,
350 description: news.description,
351 redundancyType: redundancyOf(news.redundancyType, news.interfaces),
352 };
353 if (news.interfaces !== undefined && news.interfaces.length > 0) {
354 body.interfaces = news.interfaces.map((iface) => ({
355 id: iface.id,
356 ipAddress: iface.ipAddress,
357 ipv6Address: iface.ipv6Address,
358 }));
359 }
360 const created = yield* compute
361 .insertExternalVpnGateways({
362 project: env.project,
363 body,
364 })
365 .pipe(
366 Effect.flatMap((operation) =>
367 waitGlobalOperation(env.project, operation, {
368 ignore: ["RESOURCE_ALREADY_EXISTS"],
369 }).pipe(Effect.flatMap(() => requireGateway(env.project, externalVpnGatewayName))),
370 ),
371 Effect.catchTag("Conflict", () => getByName(env.project, externalVpnGatewayName)),
372 );
373 current = created ?? undefined;
374 }
375
376 if (current === undefined) {
377 return yield* new ExternalVpnGatewayNotResolved({
378 externalVpnGatewayName,
379 });
380 }
381
382 const resolved = current;
383 const observedLabels = tagRecord(resolved.labels);
384 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
385 if (upsert.length > 0 || removed.length > 0) {
386 yield* Effect.gen(function* () {
387 const latest = (yield* getByName(env.project, externalVpnGatewayName)) ?? resolved;
388 yield* compute
389 .setLabelsExternalVpnGateways({
390 project: env.project,
391 resource: externalVpnGatewayName,
392 body: {
393 labels: desiredLabels,
394 labelFingerprint: latest.labelFingerprint,
395 },
396 })
397 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
398 }).pipe(
399 Effect.retry({
400 while: (e) => e._tag === "Conflict",
401 times: 5,
402 schedule: Schedule.spaced("1 second"),
403 }),
404 );
405 current = (yield* getByName(env.project, externalVpnGatewayName)) ?? resolved;
406 }
407
408 return toAttrs(current ?? resolved, env.project);
409 }),
410
411 delete: Effect.fn(function* ({ output }) {
412 const env = yield* GcpEnvironment.current;
413 const project = output.project || env.project;
414 if (!output.externalVpnGatewayName) return;
415 yield* compute
416 .deleteExternalVpnGateways({
417 project,
418 externalVpnGateway: output.externalVpnGatewayName,
419 })
420 .pipe(
421 Effect.flatMap((operation) =>
422 waitGlobalOperation(project, operation, {
423 ignore: ["RESOURCE_NOT_FOUND"],
424 }),
425 ),
426 Effect.catchTag("NotFound", () => Effect.void),
427 Effect.retry({
428 while: (e) => e._tag === "Conflict",
429 times: 8,
430 schedule: Schedule.spaced("2 seconds"),
431 }),
432 );
433 yield* waitUntilGone(project, output.externalVpnGatewayName);
434 }),
435 });