@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, 04:45 UTC

main
ts 500 lines 17.9 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitGlobalOperation } from "./operations.ts";
15
16 export type NetworkProps = {
17 /**
18 * Network name. If omitted, a unique RFC1035 name is generated from the
19 * stack, stage, and logical id. Must be 1-63 characters and match
20 * `[a-z]([-a-z0-9]*[a-z0-9])?`.
21 */
22 networkName?: string;
23 /**
24 * User description. Immutable — changing it replaces the network.
25 * Alchemy ownership labels are stamped into the description (VPC networks
26 * have no `labels` field) so `list` / nuke can find the resource.
27 */
28 description?: string;
29 /**
30 * When `true`, GCP creates a subnet in every region (auto mode). When
31 * `false`, the VPC is custom mode and you add subnets yourself. Immutable
32 * — changing it replaces the network.
33 * @default false
34 */
35 autoCreateSubnetworks?: boolean;
36 /**
37 * Maximum transmission unit in bytes (1300–8896).
38 * @default 1460
39 */
40 mtu?: number;
41 /**
42 * Network-wide Cloud Router advertisement mode.
43 * @default "REGIONAL"
44 */
45 routingMode?: compute.NetworkRoutingConfigRoutingModeEnum;
46 /**
47 * BGP best-path selection algorithm (`LEGACY` or `STANDARD`).
48 */
49 bgpBestPathSelectionMode?: compute.NetworkRoutingConfigBgpBestPathSelectionModeEnum;
50 /**
51 * Compare MED across routes with different neighbor ASNs (STANDARD BGP).
52 */
53 bgpAlwaysCompareMed?: boolean;
54 /**
55 * Inter-region cost handling for STANDARD BGP (`DEFAULT` or
56 * `ADD_COST_TO_MED`).
57 */
58 bgpInterRegionCost?: compute.NetworkRoutingConfigBgpInterRegionCostEnum;
59 /**
60 * When to enforce hierarchical firewall policies relative to classic
61 * VPC firewall rules.
62 * @default "AFTER_CLASSIC_FIREWALL"
63 */
64 networkFirewallPolicyEnforcementOrder?: compute.NetworkNetworkFirewallPolicyEnforcementOrderEnum;
65 /**
66 * Enable ULA internal IPv6 (`fd20::/20`). Immutable — changing it
67 * replaces the network.
68 * @default false
69 */
70 enableUlaInternalIpv6?: boolean;
71 /**
72 * Optional `/48` from `fd20::/20` used when ULA IPv6 is enabled.
73 * Immutable — changing it replaces the network.
74 */
75 internalIpv6Range?: string;
76 /**
77 * Full or partial URL of a network profile. Set only at create time.
78 * Immutable — changing it replaces the network.
79 */
80 networkProfile?: string;
81 };
82
83 export type Network = Resource<
84 "GCP.Compute.Network",
85 NetworkProps,
86 {
87 /** RFC1035 network name. */
88 networkName: string;
89 /** Server-assigned numeric id. */
90 networkId: string | undefined;
91 /** Project id. */
92 project: string;
93 /** Server-defined resource URL. */
94 selfLink: string | undefined;
95 /** Server-defined URL including the numeric id. */
96 selfLinkWithId: string | undefined;
97 /** RFC3339 creation timestamp. */
98 creationTimestamp: string | undefined;
99 /** Whether auto-mode subnets were created. */
100 autoCreateSubnetworks: boolean;
101 /** User description (Alchemy ownership marker stripped). */
102 description: string | undefined;
103 /** Configured MTU in bytes. */
104 mtu: number | undefined;
105 /** Network-wide routing mode. */
106 routingMode: string | undefined;
107 /** BGP best-path selection mode. */
108 bgpBestPathSelectionMode: string | undefined;
109 /** Whether MED is compared across neighbor ASNs. */
110 bgpAlwaysCompareMed: boolean | undefined;
111 /** Inter-region cost handling for STANDARD BGP. */
112 bgpInterRegionCost: string | undefined;
113 /** Hierarchical firewall policy enforcement order. */
114 networkFirewallPolicyEnforcementOrder: string | undefined;
115 /** Whether ULA internal IPv6 is enabled. */
116 enableUlaInternalIpv6: boolean;
117 /** Allocated ULA `/48`, if any. */
118 internalIpv6Range: string | undefined;
119 /** Network profile URL, if any. */
120 networkProfile: string | undefined;
121 /** Gateway address selected by Google Cloud. */
122 gatewayIPv4: string | undefined;
123 /** Associated firewall policy URL, if any. */
124 firewallPolicy: string | undefined;
125 /** Subnetwork self-links. */
126 subnetworks: ReadonlyArray<string> | undefined;
127 },
128 never,
129 Providers
130 >;
131
132 /**
133 * A Google Compute Engine VPC network.
134 *
135 * VPC networks have no `labels` field. Alchemy stamps
136 * `alchemy-stack` / `alchemy-stage` / `alchemy-id` into the description so
137 * `list` and `pnpm nuke:gcp` can still identify owned networks.
138 *
139 * ### Creating a Network
140 * **Example:** Custom-mode VPC (generated name)
141 * ```typescript
142 * const network = yield* GCP.Compute.Network("Vpc", {});
143 * ```
144 *
145 * **Example:** Explicit name, MTU, and routing mode
146 * ```typescript
147 * const network = yield* GCP.Compute.Network("Vpc", {
148 * networkName: "app-vpc",
149 * description: "application vpc",
150 * autoCreateSubnetworks: false,
151 * mtu: 1500,
152 * routingMode: "GLOBAL",
153 * });
154 * ```
155 *
156 * ### Auto-mode VPC
157 * **Example:** Auto-create a subnet in every region
158 * ```typescript
159 * const network = yield* GCP.Compute.Network("Vpc", {
160 * autoCreateSubnetworks: true,
161 * });
162 * ```
163 *
164 * Auto mode is slower to create and delete (one subnet per region). Prefer
165 * custom mode (`autoCreateSubnetworks: false`, the default) unless you
166 * specifically want the pre-created ranges.
167 *
168 * @resource
169 * @category Compute
170 */
171 export const Network = Resource<Network>("GCP.Compute.Network");
172
173 export class NetworkNotResolved extends Data.TaggedError("GCP.Compute.NetworkNotResolved")<{
174 networkName: string;
175 }> {}
176
177 const DEFAULT_AUTO_CREATE = false;
178 const DEFAULT_MTU = 1460;
179 const DEFAULT_ROUTING_MODE = "REGIONAL";
180 const DEFAULT_ENFORCEMENT = "AFTER_CLASSIC_FIREWALL";
181
182 const OWNERSHIP_KEYS = ["alchemy-stack", "alchemy-stage", "alchemy-id"] as const;
183
184 const encodeDescription = (internal: Record<string, string>, user?: string): string => {
185 const marker = OWNERSHIP_KEYS.map((key) => `${key}=${internal[key] ?? ""}`).join(" ");
186 return user && user.length > 0 ? `${marker}\n${user}` : marker;
187 };
188
189 const parseDescription = (description: string | undefined) => {
190 if (!description) {
191 return { labels: {} as Record<string, string>, description: undefined };
192 }
193 const newline = description.indexOf("\n");
194 const first = newline === -1 ? description : description.slice(0, newline);
195 const rest = newline === -1 ? undefined : description.slice(newline + 1);
196 if (!first.includes("alchemy-id=") || !first.includes("alchemy-stack=")) {
197 return { labels: {} as Record<string, string>, description };
198 }
199 const labels: Record<string, string> = {};
200 for (const part of first.split(/\s+/)) {
201 const eq = part.indexOf("=");
202 if (eq > 0) {
203 labels[part.slice(0, eq)] = part.slice(eq + 1);
204 }
205 }
206 return {
207 labels,
208 description: rest && rest.length > 0 ? rest : undefined,
209 };
210 };
211
212 const hasAlchemyMarker = (description: string | undefined) =>
213 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
214
215 const toNetworkName = (id: string, name: string | undefined, existing?: string) =>
216 Effect.gen(function* () {
217 if (name !== undefined) return name;
218 if (existing !== undefined) return existing;
219 const generated = yield* createPhysicalName({
220 id,
221 maxLength: 63,
222 lowercase: true,
223 });
224 const rfc = generated
225 .replace(/^[^a-z]+/, "n")
226 .slice(0, 63)
227 .replace(/-+$/g, "");
228 return rfc.length > 0 ? rfc : "n";
229 });
230
231 const toAttrs = (network: compute.Network, project: string): Network["Attributes"] => {
232 const parsed = parseDescription(network.description);
233 return {
234 networkName: network.name ?? "",
235 networkId: network.id,
236 project,
237 selfLink: network.selfLink,
238 selfLinkWithId: network.selfLinkWithId,
239 creationTimestamp: network.creationTimestamp,
240 autoCreateSubnetworks: network.autoCreateSubnetworks === true,
241 description: parsed.description,
242 mtu: network.mtu,
243 routingMode: network.routingConfig?.routingMode,
244 bgpBestPathSelectionMode: network.routingConfig?.bgpBestPathSelectionMode,
245 bgpAlwaysCompareMed: network.routingConfig?.bgpAlwaysCompareMed,
246 bgpInterRegionCost: network.routingConfig?.bgpInterRegionCost,
247 networkFirewallPolicyEnforcementOrder: network.networkFirewallPolicyEnforcementOrder,
248 enableUlaInternalIpv6: network.enableUlaInternalIpv6 === true,
249 internalIpv6Range: network.internalIpv6Range,
250 networkProfile: network.networkProfile,
251 gatewayIPv4: network.gatewayIPv4,
252 firewallPolicy: network.firewallPolicy,
253 subnetworks: network.subnetworks,
254 };
255 };
256
257 const getByName = (project: string, networkName: string) =>
258 compute
259 .getNetworks({ project, network: networkName })
260 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
261
262 const waitInsertedNetwork = (
263 project: string,
264 networkName: string,
265 operation: compute.Operation | undefined,
266 ) =>
267 Effect.gen(function* () {
268 if (operation === undefined) return;
269 yield* waitGlobalOperation(project, operation, {
270 ignore: ["RESOURCE_NOT_FOUND"],
271 }).pipe(
272 Effect.catchTag("GCP.OperationFailed", (error) =>
273 getByName(project, networkName).pipe(
274 Effect.flatMap((network) => (network !== undefined ? Effect.void : Effect.fail(error))),
275 ),
276 ),
277 );
278 });
279
280 const requireNetwork = (project: string, networkName: string) =>
281 getByName(project, networkName).pipe(
282 Effect.flatMap((network) =>
283 network ? Effect.succeed(network) : Effect.fail(new NetworkNotResolved({ networkName })),
284 ),
285 Effect.retry({
286 while: (e) => e._tag === "GCP.Compute.NetworkNotResolved",
287 schedule: Schedule.spaced("1 second"),
288 times: 8,
289 }),
290 );
291
292 export const NetworkProvider = () =>
293 Provider.succeed(Network, {
294 stables: [
295 "networkName",
296 "networkId",
297 "project",
298 "selfLink",
299 "selfLinkWithId",
300 "creationTimestamp",
301 "autoCreateSubnetworks",
302 "enableUlaInternalIpv6",
303 "internalIpv6Range",
304 "networkProfile",
305 "gatewayIPv4",
306 "description",
307 ],
308
309 diff: Effect.fn(function* ({ news, olds, output }) {
310 if (!isResolved(news)) return undefined;
311 const previousName = olds?.networkName ?? output?.networkName;
312 const nextName = news.networkName ?? previousName;
313 const replace =
314 (previousName !== undefined &&
315 news.networkName !== undefined &&
316 news.networkName !== previousName) ||
317 (olds?.autoCreateSubnetworks ?? output?.autoCreateSubnetworks ?? DEFAULT_AUTO_CREATE) !==
318 (news.autoCreateSubnetworks ?? DEFAULT_AUTO_CREATE) ||
319 (olds?.enableUlaInternalIpv6 ?? output?.enableUlaInternalIpv6 ?? false) !==
320 (news.enableUlaInternalIpv6 ?? false) ||
321 (news.internalIpv6Range !== undefined &&
322 (olds?.internalIpv6Range ?? output?.internalIpv6Range) !== news.internalIpv6Range) ||
323 (news.networkProfile !== undefined &&
324 (olds?.networkProfile ?? output?.networkProfile) !== news.networkProfile) ||
325 (news.description !== undefined &&
326 (olds?.description ?? output?.description ?? "") !== news.description);
327 if (!replace) return undefined;
328 return {
329 action: "replace" as const,
330 deleteFirst:
331 nextName !== undefined && previousName !== undefined && nextName === previousName,
332 };
333 }),
334
335 read: Effect.fn(function* ({ id, olds, output }) {
336 const env = yield* GcpEnvironment.current;
337 const networkName = yield* toNetworkName(id, olds?.networkName, output?.networkName);
338 const existing = yield* getByName(env.project, networkName);
339 if (existing === undefined) return undefined;
340 const attrs = toAttrs(existing, env.project);
341 const parsed = parseDescription(existing.description);
342 return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs);
343 }),
344
345 list: () =>
346 Effect.gen(function* () {
347 const env = yield* GcpEnvironment.current;
348 return yield* compute.listNetworks.items({ project: env.project, maxResults: 500 }).pipe(
349 Stream.filter((network) => hasAlchemyMarker(network.description)),
350 Stream.map((network) => toAttrs(network, env.project)),
351 Stream.runCollect,
352 Effect.map((chunk) => Array.from(chunk)),
353 );
354 }),
355
356 reconcile: Effect.fn(function* ({ id, news, output }) {
357 const env = yield* GcpEnvironment.current;
358 const networkName = yield* toNetworkName(id, news.networkName, output?.networkName);
359 const autoCreateSubnetworks = news.autoCreateSubnetworks ?? DEFAULT_AUTO_CREATE;
360 const mtu = news.mtu ?? DEFAULT_MTU;
361 const routingMode = news.routingMode ?? DEFAULT_ROUTING_MODE;
362 const enforcement = news.networkFirewallPolicyEnforcementOrder ?? DEFAULT_ENFORCEMENT;
363 const enableUlaInternalIpv6 = news.enableUlaInternalIpv6 === true;
364 const internal = yield* createInternalLabels(id);
365 const desiredDescription = encodeDescription(internal, news.description);
366
367 let current = yield* getByName(env.project, networkName);
368
369 if (current === undefined) {
370 const routingConfig: compute.NetworkRoutingConfig = {
371 routingMode,
372 };
373 if (news.bgpBestPathSelectionMode !== undefined) {
374 routingConfig.bgpBestPathSelectionMode = news.bgpBestPathSelectionMode;
375 }
376 if (news.bgpAlwaysCompareMed !== undefined) {
377 routingConfig.bgpAlwaysCompareMed = news.bgpAlwaysCompareMed;
378 }
379 if (news.bgpInterRegionCost !== undefined) {
380 routingConfig.bgpInterRegionCost = news.bgpInterRegionCost;
381 }
382 const body: compute.Network = {
383 name: networkName,
384 autoCreateSubnetworks,
385 description: desiredDescription,
386 mtu,
387 routingConfig,
388 networkFirewallPolicyEnforcementOrder: enforcement,
389 };
390 if (enableUlaInternalIpv6) {
391 body.enableUlaInternalIpv6 = true;
392 }
393 if (news.internalIpv6Range !== undefined) {
394 body.internalIpv6Range = news.internalIpv6Range;
395 }
396 if (news.networkProfile !== undefined) {
397 body.networkProfile = news.networkProfile;
398 }
399 yield* compute
400 .insertNetworks({
401 project: env.project,
402 body,
403 })
404 .pipe(
405 Effect.catchTag("Conflict", () => Effect.undefined),
406 Effect.flatMap((inserted) => waitInsertedNetwork(env.project, networkName, inserted)),
407 Effect.retry({
408 while: (error) => error._tag === "NotFound" || error._tag === "GCP.OperationFailed",
409 times: 6,
410 schedule: Schedule.spaced("5 seconds"),
411 }),
412 );
413 current = yield* requireNetwork(env.project, networkName);
414 }
415
416 if (current === undefined) {
417 return yield* new NetworkNotResolved({ networkName });
418 }
419
420 const applyPatch = (body: compute.Network) =>
421 Effect.gen(function* () {
422 const patched = yield* compute.patchNetworks({
423 project: env.project,
424 network: networkName,
425 body,
426 });
427 yield* waitGlobalOperation(env.project, patched);
428 return yield* requireNetwork(env.project, networkName);
429 });
430
431 // GCP rejects PATCH bodies that combine an MTU change with any other
432 // field ("Other fields cannot be modified when changing MTU").
433 if ((current.mtu ?? DEFAULT_MTU) !== mtu) {
434 current = yield* applyPatch({ mtu });
435 }
436
437 const patchBody: compute.Network = {};
438 if ((current.networkFirewallPolicyEnforcementOrder ?? DEFAULT_ENFORCEMENT) !== enforcement) {
439 patchBody.networkFirewallPolicyEnforcementOrder = enforcement;
440 }
441 const routingPatch: compute.NetworkRoutingConfig = {};
442 if ((current.routingConfig?.routingMode ?? DEFAULT_ROUTING_MODE) !== routingMode) {
443 routingPatch.routingMode = routingMode;
444 }
445 if (
446 news.bgpBestPathSelectionMode !== undefined &&
447 current.routingConfig?.bgpBestPathSelectionMode !== news.bgpBestPathSelectionMode
448 ) {
449 routingPatch.bgpBestPathSelectionMode = news.bgpBestPathSelectionMode;
450 }
451 if (
452 news.bgpAlwaysCompareMed !== undefined &&
453 current.routingConfig?.bgpAlwaysCompareMed !== news.bgpAlwaysCompareMed
454 ) {
455 routingPatch.bgpAlwaysCompareMed = news.bgpAlwaysCompareMed;
456 }
457 if (
458 news.bgpInterRegionCost !== undefined &&
459 current.routingConfig?.bgpInterRegionCost !== news.bgpInterRegionCost
460 ) {
461 routingPatch.bgpInterRegionCost = news.bgpInterRegionCost;
462 }
463 if (Object.keys(routingPatch).length > 0) {
464 patchBody.routingConfig = routingPatch;
465 }
466
467 if (Object.keys(patchBody).length > 0) {
468 current = yield* applyPatch(patchBody);
469 }
470
471 return toAttrs(current, env.project);
472 }),
473
474 delete: Effect.fn(function* ({ output }) {
475 const env = yield* GcpEnvironment.current;
476 if (!output.networkName) return;
477 yield* compute
478 .deleteNetworks({
479 project: env.project,
480 network: output.networkName,
481 })
482 .pipe(
483 Effect.flatMap((operation) =>
484 waitGlobalOperation(env.project, operation, {
485 ignore: ["RESOURCE_NOT_FOUND"],
486 }),
487 ),
488 Effect.catchTag("NotFound", () => Effect.void),
489 Effect.retry({
490 while: (error) =>
491 error._tag === "Conflict" ||
492 (error._tag === "GCP.OperationFailed" &&
493 (error.reason === "RESOURCE_IN_USE_BY_ANOTHER_RESOURCE" ||
494 error.reason === "RESOURCE_NOT_READY")),
495 times: 20,
496 schedule: Schedule.spaced("3 seconds"),
497 }),
498 );
499 }),
500 });