@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 474 lines 15.9 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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
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 {
15 encodeDescription,
16 hasOwnershipMarker,
17 lastSegment,
18 parseDescription,
19 runGlobalOp,
20 toPhysicalName,
21 } from "./internal.ts";
22
23 const DEFAULT_NETWORK_ENDPOINT_TYPE = "INTERNET_FQDN_PORT";
24
25 export type GlobalNetworkEndpointType = "INTERNET_FQDN_PORT" | "INTERNET_IP_PORT" | (string & {});
26
27 export type GlobalNetworkEndpointSpec = {
28 /** Fully qualified domain name. Required for `INTERNET_FQDN_PORT`. */
29 fqdn?: string;
30 /** IPv4 address. Required for `INTERNET_IP_PORT`. */
31 ipAddress?: string;
32 /** IPv6 address. */
33 ipv6Address?: string;
34 /** Port. Omitted endpoints use the group's `defaultPort`. */
35 port?: number;
36 };
37
38 export type GlobalNetworkEndpointGroupProps = {
39 /**
40 * NEG name (RFC1035, 1–63 characters). If omitted, a unique name is
41 * generated from the stack, stage, and logical id. Immutable —
42 * changing it replaces the group.
43 */
44 networkEndpointGroupName?: string;
45 /**
46 * Optional description. Global internet NEGs have no labels field and
47 * no update API, so Alchemy ownership (`alchemy-stack` /
48 * `alchemy-stage` / `alchemy-id`) is stored in a `[alchemy …]` prefix
49 * for `list` / nuke. Immutable — changing the user-facing description
50 * replaces the group.
51 */
52 description?: string;
53 /**
54 * Endpoint type. Global NEGs are internet NEGs:
55 * `INTERNET_FQDN_PORT` or `INTERNET_IP_PORT`. Immutable — changing
56 * it replaces the group.
57 * @default "INTERNET_FQDN_PORT"
58 */
59 networkEndpointType?: GlobalNetworkEndpointType;
60 /**
61 * Default port used when an endpoint omits `port`. Immutable —
62 * changing it replaces the group.
63 */
64 defaultPort?: number;
65 /**
66 * User annotations. Immutable — changing them replaces the group.
67 */
68 annotations?: Record<string, string>;
69 /**
70 * Member endpoints. A global internet NEG accepts at most one
71 * endpoint. When omitted, membership is left as-is. When set
72 * (including `[]`), observed endpoints are attached/detached to match.
73 */
74 networkEndpoints?: GlobalNetworkEndpointSpec[];
75 };
76
77 export type GlobalNetworkEndpointGroup = Resource<
78 "GCP.Compute.GlobalNetworkEndpointGroup",
79 GlobalNetworkEndpointGroupProps,
80 {
81 /** NEG name. */
82 networkEndpointGroupName: string;
83 /** Project id. */
84 project: string;
85 /** Endpoint type. */
86 networkEndpointType: string | undefined;
87 /** User description with the Alchemy ownership prefix stripped. */
88 description: string | undefined;
89 /** Default port, if any. */
90 defaultPort: number | undefined;
91 /** User annotations. */
92 annotations: Record<string, string>;
93 /** Number of endpoints in the group. */
94 size: number | undefined;
95 /** Server-assigned numeric id. */
96 networkEndpointGroupId: string | undefined;
97 /** Resource self-link. */
98 selfLink: string | undefined;
99 /** RFC3339 creation timestamp. */
100 creationTimestamp: string | undefined;
101 /** Resource kind. */
102 kind: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * A global Compute Engine internet network endpoint group.
110 *
111 * Global NEGs back internet (`INTERNET_FQDN_PORT` / `INTERNET_IP_PORT`)
112 * backends for global external Application Load Balancers. They live in
113 * the `global/networkEndpointGroups` collection (zonal VM NEGs and
114 * regional serverless/PSC NEGs are separate resources). The collection
115 * has no labels field and no update API — Alchemy stamps ownership into
116 * the description so `list` / nuke can find leaked groups. Name, type,
117 * default port, annotations, and description are immutable (changing any
118 * of them replaces the group). Endpoints attach and detach in place.
119 *
120 * ### Creating a GlobalNetworkEndpointGroup
121 * **Example:** FQDN internet NEG
122 * ```typescript
123 * const neg = yield* GCP.Compute.GlobalNetworkEndpointGroup("Internet", {
124 * networkEndpointType: "INTERNET_FQDN_PORT",
125 * defaultPort: 443,
126 * });
127 * ```
128 *
129 * **Example:** Explicit name and a single FQDN endpoint
130 * ```typescript
131 * const neg = yield* GCP.Compute.GlobalNetworkEndpointGroup("Internet", {
132 * networkEndpointGroupName: "www-neg",
133 * networkEndpointType: "INTERNET_FQDN_PORT",
134 * defaultPort: 443,
135 * networkEndpoints: [{ fqdn: "www.example.com", port: 443 }],
136 * });
137 * ```
138 *
139 * ### IP internet NEGs
140 * **Example:** Global internet IP:port NEG
141 * ```typescript
142 * const neg = yield* GCP.Compute.GlobalNetworkEndpointGroup("IpNeg", {
143 * networkEndpointType: "INTERNET_IP_PORT",
144 * defaultPort: 443,
145 * networkEndpoints: [{ ipAddress: "203.0.113.10", port: 443 }],
146 * });
147 * ```
148 *
149 * @resource
150 * @category Compute
151 */
152 export const GlobalNetworkEndpointGroup = Resource<GlobalNetworkEndpointGroup>(
153 "GCP.Compute.GlobalNetworkEndpointGroup",
154 );
155
156 export class GlobalNetworkEndpointGroupNotResolved extends Data.TaggedError(
157 "GCP.Compute.GlobalNetworkEndpointGroupNotResolved",
158 )<{
159 networkEndpointGroupName: string;
160 }> {}
161
162 export class GlobalNetworkEndpointGroupStillExists extends Data.TaggedError(
163 "GCP.Compute.GlobalNetworkEndpointGroupStillExists",
164 )<{
165 networkEndpointGroupName: string;
166 }> {}
167
168 const annotationsOf = (
169 annotations: Record<string, string | undefined> | null | undefined,
170 ): Record<string, string> => tagRecord(annotations);
171
172 const sameAnnotations = (
173 left: Record<string, string> | undefined,
174 right: Record<string, string> | undefined,
175 ) => {
176 const a = annotationsOf(left);
177 const b = annotationsOf(right);
178 const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
179 for (const key of keys) {
180 if (a[key] !== b[key]) return false;
181 }
182 return true;
183 };
184
185 const asType = (value: string | undefined) =>
186 value && value.length > 0 ? value : DEFAULT_NETWORK_ENDPOINT_TYPE;
187
188 const toAttrs = (
189 group: compute.NetworkEndpointGroup,
190 project: string,
191 ): GlobalNetworkEndpointGroup["Attributes"] => {
192 const parsed = parseDescription(group.description);
193 return {
194 networkEndpointGroupName: group.name ?? lastSegment(group.selfLink),
195 project,
196 networkEndpointType: group.networkEndpointType,
197 description: parsed.description,
198 defaultPort: group.defaultPort,
199 annotations: annotationsOf(group.annotations),
200 size: group.size,
201 networkEndpointGroupId: group.id,
202 selfLink: group.selfLink,
203 creationTimestamp: group.creationTimestamp,
204 kind: group.kind,
205 };
206 };
207
208 const toBody = (
209 networkEndpointGroupName: string,
210 props: GlobalNetworkEndpointGroupProps,
211 ownership: Record<string, string>,
212 ): compute.NetworkEndpointGroup => ({
213 name: networkEndpointGroupName,
214 description: encodeDescription(ownership, props.description),
215 networkEndpointType: asType(props.networkEndpointType),
216 defaultPort: props.defaultPort,
217 annotations:
218 props.annotations !== undefined && Object.keys(props.annotations).length > 0
219 ? props.annotations
220 : undefined,
221 });
222
223 const toApiEndpoint = (endpoint: GlobalNetworkEndpointSpec): compute.NetworkEndpoint => ({
224 fqdn: endpoint.fqdn,
225 ipAddress: endpoint.ipAddress,
226 ipv6Address: endpoint.ipv6Address,
227 port: endpoint.port,
228 });
229
230 const endpointKey = (endpoint: {
231 fqdn?: string;
232 ipAddress?: string;
233 ipv6Address?: string;
234 port?: number;
235 }) =>
236 [
237 endpoint.fqdn ?? "",
238 endpoint.ipAddress ?? "",
239 endpoint.ipv6Address ?? "",
240 endpoint.port ?? "",
241 ].join("|");
242
243 const getByName = (project: string, networkEndpointGroup: string) =>
244 compute
245 .getGlobalNetworkEndpointGroups({ project, networkEndpointGroup })
246 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
247
248 const awaitResource = (project: string, networkEndpointGroupName: string) =>
249 getByName(project, networkEndpointGroupName).pipe(
250 Effect.flatMap((group) =>
251 group !== undefined
252 ? Effect.succeed(group)
253 : Effect.fail(
254 new GlobalNetworkEndpointGroupNotResolved({
255 networkEndpointGroupName,
256 }),
257 ),
258 ),
259 Effect.retry({
260 while: (error) => error._tag === "GCP.Compute.GlobalNetworkEndpointGroupNotResolved",
261 times: 8,
262 schedule: Schedule.spaced("1 second"),
263 }),
264 );
265
266 const waitUntilGone = (project: string, networkEndpointGroupName: string) =>
267 getByName(project, networkEndpointGroupName).pipe(
268 Effect.flatMap((group) =>
269 group === undefined
270 ? Effect.void
271 : Effect.fail(
272 new GlobalNetworkEndpointGroupStillExists({
273 networkEndpointGroupName,
274 }),
275 ),
276 ),
277 Effect.retry({
278 while: (error) => error._tag === "GCP.Compute.GlobalNetworkEndpointGroupStillExists",
279 times: 10,
280 schedule: Schedule.spaced("1 second"),
281 }),
282 Effect.catchTag("GCP.Compute.GlobalNetworkEndpointGroupStillExists", () => Effect.void),
283 );
284
285 const listEndpoints = (project: string, networkEndpointGroup: string) =>
286 compute.listNetworkEndpointsGlobalNetworkEndpointGroups
287 .items({
288 project,
289 networkEndpointGroup,
290 maxResults: 500,
291 })
292 .pipe(
293 Stream.runCollect,
294 Effect.map((chunk) =>
295 Array.from(chunk)
296 .map((item) => item.networkEndpoint)
297 .filter((endpoint): endpoint is compute.NetworkEndpoint => endpoint !== undefined),
298 ),
299 Effect.catchTag(["NotFound", "BadRequest"], () =>
300 Effect.succeed([] as compute.NetworkEndpoint[]),
301 ),
302 );
303
304 const immutableChanged = (
305 news: GlobalNetworkEndpointGroupProps,
306 olds: Partial<GlobalNetworkEndpointGroupProps> | undefined,
307 output: GlobalNetworkEndpointGroup["Attributes"] | undefined,
308 ) => {
309 const previousType = asType(olds?.networkEndpointType ?? output?.networkEndpointType);
310 if (asType(news.networkEndpointType) !== previousType) return true;
311
312 const previousDescription = olds?.description ?? output?.description ?? "";
313 if ((news.description ?? "") !== previousDescription) return true;
314
315 if (
316 news.defaultPort !== undefined &&
317 news.defaultPort !== (olds?.defaultPort ?? output?.defaultPort)
318 ) {
319 return true;
320 }
321
322 if (
323 news.annotations !== undefined &&
324 !sameAnnotations(news.annotations, olds?.annotations ?? output?.annotations)
325 ) {
326 return true;
327 }
328 return false;
329 };
330
331 export const GlobalNetworkEndpointGroupProvider = () =>
332 Provider.succeed(GlobalNetworkEndpointGroup, {
333 stables: [
334 "networkEndpointGroupName",
335 "project",
336 "networkEndpointType",
337 "networkEndpointGroupId",
338 "selfLink",
339 "creationTimestamp",
340 ],
341
342 diff: Effect.fn(function* ({ news, olds, output }) {
343 if (!isResolved(news)) return undefined;
344 const previousName = olds.networkEndpointGroupName ?? output?.networkEndpointGroupName;
345 const nextName = news.networkEndpointGroupName ?? previousName;
346 const nameChanged =
347 previousName !== undefined && nextName !== undefined && nextName !== previousName;
348 if (nameChanged) {
349 return { action: "replace" as const, deleteFirst: false };
350 }
351 if (immutableChanged(news, olds, output)) {
352 return { action: "replace" as const, deleteFirst: true };
353 }
354 return undefined;
355 }),
356
357 read: Effect.fn(function* ({ id, olds, output, previous }) {
358 const env = yield* GcpEnvironment.current;
359 const networkEndpointGroupName = yield* toPhysicalName(
360 id,
361 olds?.networkEndpointGroupName,
362 output?.networkEndpointGroupName,
363 "neg",
364 );
365 const existing = yield* getByName(env.project, networkEndpointGroupName);
366 if (existing === undefined) return undefined;
367 const attrs = toAttrs(existing, env.project);
368 const { labels } = parseDescription(existing.description);
369 return (yield* hasAlchemyLabels(id, labels))
370 ? attrs
371 : unownedUnlessPrevious(attrs, previous, "networkEndpointGroupName");
372 }),
373
374 list: () =>
375 Effect.gen(function* () {
376 const env = yield* GcpEnvironment.current;
377 return yield* compute.listGlobalNetworkEndpointGroups
378 .items({
379 project: env.project,
380 maxResults: 500,
381 returnPartialSuccess: true,
382 })
383 .pipe(
384 Stream.filter((item) => hasOwnershipMarker(item.description)),
385 Stream.map((item) => toAttrs(item, env.project)),
386 Stream.runCollect,
387 Effect.map((chunk) => Array.from(chunk)),
388 Effect.catchTag("NotFound", () =>
389 Effect.succeed([] as GlobalNetworkEndpointGroup["Attributes"][]),
390 ),
391 );
392 }),
393
394 reconcile: Effect.fn(function* ({ id, news, output }) {
395 const env = yield* GcpEnvironment.current;
396 const networkEndpointGroupName = yield* toPhysicalName(
397 id,
398 news.networkEndpointGroupName,
399 output?.networkEndpointGroupName,
400 "neg",
401 );
402 const ownership = yield* createInternalLabels(id);
403 const desired = toBody(networkEndpointGroupName, news, ownership);
404
405 let current = yield* getByName(env.project, networkEndpointGroupName);
406
407 if (current === undefined) {
408 yield* runGlobalOp(
409 env.project,
410 compute.insertGlobalNetworkEndpointGroups({
411 project: env.project,
412 body: desired,
413 }),
414 { ignoreAlreadyExists: true },
415 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
416 current = yield* awaitResource(env.project, networkEndpointGroupName);
417 }
418
419 if (current === undefined) {
420 return yield* new GlobalNetworkEndpointGroupNotResolved({
421 networkEndpointGroupName,
422 });
423 }
424
425 if (news.networkEndpoints !== undefined) {
426 const observed = yield* listEndpoints(env.project, networkEndpointGroupName);
427 const wanted = news.networkEndpoints.map(toApiEndpoint);
428 const observedKeys = new Set(observed.map(endpointKey));
429 const wantedKeys = new Set(wanted.map(endpointKey));
430 const toAdd = wanted.filter((endpoint) => !observedKeys.has(endpointKey(endpoint)));
431 const toRemove = observed.filter((endpoint) => !wantedKeys.has(endpointKey(endpoint)));
432 if (toAdd.length > 0) {
433 yield* runGlobalOp(
434 env.project,
435 compute.attachNetworkEndpointsGlobalNetworkEndpointGroups({
436 project: env.project,
437 networkEndpointGroup: networkEndpointGroupName,
438 body: { networkEndpoints: toAdd },
439 }),
440 { ignoreAlreadyExists: true },
441 ).pipe(Effect.catchTag(["Conflict", "NotFound"], () => Effect.void));
442 }
443 if (toRemove.length > 0) {
444 yield* runGlobalOp(
445 env.project,
446 compute.detachNetworkEndpointsGlobalNetworkEndpointGroups({
447 project: env.project,
448 networkEndpointGroup: networkEndpointGroupName,
449 body: { networkEndpoints: toRemove },
450 }),
451 { ignoreNotFound: true },
452 ).pipe(Effect.catchTag(["Conflict", "NotFound"], () => Effect.void));
453 }
454 current = (yield* getByName(env.project, networkEndpointGroupName)) ?? current;
455 }
456
457 return toAttrs(current, env.project);
458 }),
459
460 delete: Effect.fn(function* ({ output }) {
461 const env = yield* GcpEnvironment.current;
462 const project = output.project || env.project;
463 if (!output.networkEndpointGroupName) return;
464 yield* runGlobalOp(
465 project,
466 compute.deleteGlobalNetworkEndpointGroups({
467 project,
468 networkEndpointGroup: output.networkEndpointGroupName,
469 }),
470 { ignoreNotFound: true },
471 ).pipe(Effect.catchTag(["NotFound", "Conflict"], () => Effect.undefined));
472 yield* waitUntilGone(project, output.networkEndpointGroupName);
473 }),
474 });