@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 618 lines 21.6 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 { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitRegionOperation } from "./operations.ts";
15
16 const DEFAULT_SESSION_AFFINITY = "NONE";
17 const MAX_NAME_LENGTH = 63;
18
19 export type TargetPoolSessionAffinity = "NONE" | "CLIENT_IP" | "CLIENT_IP_PROTO" | (string & {});
20
21 export type TargetPoolProps = {
22 /**
23 * Target pool name (RFC1035, 1-63 characters). If omitted, a unique
24 * name is generated from the stack, stage, and logical id. Immutable —
25 * changing it replaces the pool.
26 */
27 targetPoolName?: string;
28 /**
29 * Region the pool lives in. Immutable — changing it replaces the pool.
30 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
31 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
32 */
33 region?: string;
34 /**
35 * Optional description. Compute target pools have no labels field, so
36 * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`)
37 * is stored in a `[alchemy …]` prefix for `list` / nuke. Immutable —
38 * changing the user-facing description replaces the pool.
39 */
40 description?: string;
41 /**
42 * Session affinity. Immutable — changing it replaces the pool.
43 * `NONE` spreads connections. `CLIENT_IP` pins by client IP.
44 * `CLIENT_IP_PROTO` pins by client IP and protocol.
45 * @default "NONE"
46 */
47 sessionAffinity?: TargetPoolSessionAffinity;
48 /**
49 * Backup target pool URL or name in the same region. Used with
50 * `failoverRatio` when this pool is the primary for a forwarding rule.
51 * Updated in place via `setBackup`.
52 */
53 backupPool?: string;
54 /**
55 * Failover threshold in `[0, 1]`. Required when `backupPool` is set.
56 * Traffic fails over when the ratio of healthy instances in this pool
57 * is at or below this value. Updated in place via `setBackup`.
58 */
59 failoverRatio?: number;
60 /**
61 * Legacy HttpHealthCheck URLs or names (at most one). Only the
62 * `httpHealthChecks` collection is supported — modern HealthCheck
63 * resources cannot be attached. When omitted, existing checks are
64 * left as-is; pass `[]` to detach.
65 */
66 healthChecks?: string[];
67 /**
68 * Member instance URLs (`projects/{project}/zones/{zone}/instances/{name}`)
69 * or `zone/name` shorthand. Instances must be in this pool's region.
70 * When omitted, membership is left as-is (managed instance groups may
71 * add members). Pass `[]` to detach every instance.
72 */
73 instances?: string[];
74 /**
75 * Cloud Armor security policy URL. When omitted, the current policy is
76 * left as-is. Pass `""` to detach. Updated in place via
77 * `setSecurityPolicy`.
78 */
79 securityPolicy?: string;
80 };
81
82 export type TargetPool = Resource<
83 "GCP.Compute.TargetPool",
84 TargetPoolProps,
85 {
86 /** Target pool name. */
87 targetPoolName: string;
88 /** Project id. */
89 project: string;
90 /** Region short name (`us-central1`). */
91 region: string;
92 /** User description with the Alchemy ownership prefix stripped. */
93 description: string | undefined;
94 /** Session affinity. */
95 sessionAffinity: string | undefined;
96 /** Backup pool URL, if set. */
97 backupPool: string | undefined;
98 /** Failover ratio, if set. */
99 failoverRatio: number | undefined;
100 /** Legacy HttpHealthCheck URLs. */
101 healthChecks: ReadonlyArray<string>;
102 /** Member instance URLs. */
103 instances: ReadonlyArray<string>;
104 /** Attached Cloud Armor policy URL, if any. */
105 securityPolicy: string | undefined;
106 /** Server-defined URL. */
107 selfLink: string | undefined;
108 /** Server-assigned numeric id. */
109 targetPoolId: string | undefined;
110 /** RFC3339 creation timestamp. */
111 creationTimestamp: string | undefined;
112 /** Resource kind. */
113 kind: string | undefined;
114 },
115 never,
116 Providers
117 >;
118
119 /**
120 * A regional Compute Engine target pool.
121 *
122 * Target pools are the backend for external network load balancers
123 * (target-pool forwarding rules). Members are zonal instances in the
124 * same region. Health checking uses legacy HttpHealthCheck resources
125 * only. Compute TargetPool has no labels field — Alchemy ownership is
126 * stored in the description so nuke can find leaked pools.
127 *
128 * ### Creating a Target Pool
129 * **Example:** Generated name
130 * ```typescript
131 * const pool = yield* GCP.Compute.TargetPool("backends", {});
132 * ```
133 *
134 * **Example:** Named pool with session affinity
135 * ```typescript
136 * const pool = yield* GCP.Compute.TargetPool("backends", {
137 * targetPoolName: "app-nlb",
138 * region: "us-central1",
139 * sessionAffinity: "CLIENT_IP",
140 * description: "network load balancer",
141 * });
142 * ```
143 *
144 * ### Failover
145 * **Example:** Primary pool with a backup
146 * ```typescript
147 * const backup = yield* GCP.Compute.TargetPool("failover", {});
148 * const primary = yield* GCP.Compute.TargetPool("backends", {
149 * backupPool: backup.selfLink,
150 * failoverRatio: 0.5,
151 * });
152 * ```
153 *
154 * ### Instances
155 * **Example:** Pin specific VMs
156 * ```typescript
157 * const pool = yield* GCP.Compute.TargetPool("backends", {
158 * instances: [
159 * "projects/{project}/zones/us-central1-a/instances/web-1",
160 * "us-central1-b/web-2",
161 * ],
162 * });
163 * ```
164 *
165 * @resource
166 * @category Compute
167 */
168 export const TargetPool = Resource<TargetPool>("GCP.Compute.TargetPool");
169
170 export class TargetPoolNotResolved extends Data.TaggedError("GCP.Compute.TargetPoolNotResolved")<{
171 targetPoolName: string;
172 region: string;
173 }> {}
174
175 export class TargetPoolPending extends Data.TaggedError("GCP.Compute.TargetPoolPending")<{
176 targetPoolName: string;
177 status: string;
178 }> {}
179
180 const lastSegment = (value: string | undefined) => {
181 if (!value) return "";
182 const trimmed = value.replace(/\/+$/, "");
183 const parts = trimmed.split("/");
184 return parts[parts.length - 1] || trimmed;
185 };
186
187 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
188 lastSegment(region ?? defaultRegion).toLowerCase();
189
190 const sessionAffinityOf = (value: string | undefined) =>
191 value && value.length > 0 ? value : DEFAULT_SESSION_AFFINITY;
192
193 const encodeDescription = (
194 labels: Record<string, string>,
195 description: string | undefined,
196 ): string => {
197 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
198 return description ? `${marker}\n${description}` : marker;
199 };
200
201 const parseDescription = (
202 description: string | undefined,
203 ): {
204 labels: Record<string, string>;
205 description: string | undefined;
206 } => {
207 if (!description?.startsWith("[alchemy ")) {
208 return { labels: {}, description };
209 }
210 const end = description.indexOf("]");
211 if (end < 0) return { labels: {}, description };
212 const labels: Record<string, string> = {};
213 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
214 const eq = part.indexOf("=");
215 if (eq > 0) {
216 labels[part.slice(0, eq)] = part.slice(eq + 1);
217 }
218 }
219 const rest = description.slice(end + 1).replace(/^\n/, "");
220 return { labels, description: rest.length > 0 ? rest : undefined };
221 };
222
223 const toName = (id: string, name: string | undefined, existing?: string) =>
224 Effect.gen(function* () {
225 if (name !== undefined) return name;
226 if (existing !== undefined) return existing;
227 const generated = yield* createPhysicalName({
228 id,
229 maxLength: MAX_NAME_LENGTH,
230 lowercase: true,
231 });
232 const rfc = generated.replace(/^[^a-z]+/, "t").replace(/-+$/g, "");
233 return rfc.slice(0, MAX_NAME_LENGTH);
234 });
235
236 const toPoolUrl = (project: string, region: string, pool: string) => {
237 if (pool.includes("/")) return pool;
238 return `projects/${project}/regions/${region}/targetPools/${pool}`;
239 };
240
241 const toHealthCheckUrl = (project: string, healthCheck: string) => {
242 if (healthCheck.includes("/")) return healthCheck;
243 return `projects/${project}/global/httpHealthChecks/${healthCheck}`;
244 };
245
246 const toInstanceUrl = (project: string, instance: string) => {
247 if (instance.startsWith("http") || instance.startsWith("projects/")) {
248 return instance;
249 }
250 const parts = instance.split("/").filter((part) => part.length > 0);
251 if (parts.length === 2 && parts[0] !== "zones") {
252 return `projects/${project}/zones/${parts[0]}/instances/${parts[1]}`;
253 }
254 if (parts[0] === "zones") {
255 return `projects/${project}/${parts.join("/")}`;
256 }
257 return instance;
258 };
259
260 const instanceKey = (value: string) => {
261 const parts = value.replace(/\/+$/, "").split("/").filter(Boolean);
262 const index = parts.lastIndexOf("instances");
263 if (index >= 1 && parts[index + 1]) {
264 return `${parts[index - 1]}/${parts[index + 1]}`.toLowerCase();
265 }
266 if (parts.length === 2) {
267 return `${parts[0]}/${parts[1]}`.toLowerCase();
268 }
269 return lastSegment(value).toLowerCase();
270 };
271
272 const toAttrs = (pool: compute.TargetPool, project: string): TargetPool["Attributes"] => {
273 const parsed = parseDescription(pool.description);
274 return {
275 targetPoolName: pool.name ?? "",
276 project,
277 region: lastSegment(pool.region).toLowerCase(),
278 description: parsed.description,
279 sessionAffinity: sessionAffinityOf(pool.sessionAffinity),
280 backupPool: pool.backupPool,
281 failoverRatio: pool.failoverRatio,
282 healthChecks: pool.healthChecks ?? [],
283 instances: pool.instances ?? [],
284 securityPolicy: pool.securityPolicy,
285 selfLink: pool.selfLink,
286 targetPoolId: pool.id,
287 creationTimestamp: pool.creationTimestamp,
288 kind: pool.kind,
289 };
290 };
291
292 const getByName = (project: string, region: string, targetPool: string) =>
293 compute
294 .getTargetPools({ project, region, targetPool })
295 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
296
297 const runOp = <E, R>(
298 project: string,
299 region: string,
300 targetPoolName: string,
301 start: Effect.Effect<compute.Operation, E, R>,
302 ) => start.pipe(Effect.flatMap((operation) => waitRegionOperation(project, region, operation)));
303
304 const requirePool = (project: string, region: string, targetPoolName: string) =>
305 getByName(project, region, targetPoolName).pipe(
306 Effect.flatMap((pool) =>
307 pool
308 ? Effect.succeed(pool)
309 : Effect.fail(new TargetPoolNotResolved({ targetPoolName, region })),
310 ),
311 Effect.retry({
312 while: (error) => error._tag === "GCP.Compute.TargetPoolNotResolved",
313 schedule: Schedule.spaced("1 second"),
314 times: 8,
315 }),
316 );
317
318 const waitUntilGone = (project: string, region: string, targetPoolName: string) =>
319 getByName(project, region, targetPoolName).pipe(
320 Effect.flatMap((pool) =>
321 pool === undefined
322 ? Effect.void
323 : Effect.fail(
324 new TargetPoolPending({
325 targetPoolName,
326 status: "EXISTS",
327 }),
328 ),
329 ),
330 Effect.retry({
331 while: (error) => error._tag === "GCP.Compute.TargetPoolPending",
332 times: 10,
333 schedule: Schedule.spaced("2 seconds"),
334 }),
335 );
336
337 const sameRef = (left: string | undefined, right: string | undefined) =>
338 lastSegment(left).toLowerCase() === lastSegment(right).toLowerCase();
339
340 export const TargetPoolProvider = () =>
341 Provider.succeed(TargetPool, {
342 stables: [
343 "targetPoolName",
344 "project",
345 "region",
346 "targetPoolId",
347 "selfLink",
348 "sessionAffinity",
349 "creationTimestamp",
350 ],
351
352 diff: Effect.fn(function* ({ news, olds, output }) {
353 if (!isResolved(news)) return undefined;
354 const env = yield* GcpEnvironment.current;
355 const previousName = olds?.targetPoolName ?? output?.targetPoolName;
356 const nextName = news.targetPoolName ?? previousName;
357 const nameChanged =
358 previousName !== undefined && nextName !== undefined && nextName !== previousName;
359
360 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
361 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
362 const regionChanged = previousRegion !== nextRegion;
363
364 const affinityChanged =
365 news.sessionAffinity !== undefined &&
366 sessionAffinityOf(news.sessionAffinity) !==
367 sessionAffinityOf(olds?.sessionAffinity ?? output?.sessionAffinity);
368
369 const previousDescription = olds?.description ?? output?.description ?? "";
370 const descriptionChanged =
371 news.description !== undefined && (news.description ?? "") !== previousDescription;
372
373 if (nameChanged || regionChanged) {
374 return { action: "replace" as const, deleteFirst: false };
375 }
376 if (affinityChanged || descriptionChanged) {
377 return {
378 action: "replace" as const,
379 deleteFirst:
380 previousName !== undefined &&
381 (news.targetPoolName === undefined || news.targetPoolName === previousName),
382 };
383 }
384 return undefined;
385 }),
386
387 read: Effect.fn(function* ({ id, olds, output }) {
388 const env = yield* GcpEnvironment.current;
389 const targetPoolName = yield* toName(id, olds?.targetPoolName, output?.targetPoolName);
390 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
391 const existing = yield* getByName(env.project, region, targetPoolName);
392 if (existing === undefined) return undefined;
393 const attrs = toAttrs(existing, env.project);
394 const { labels } = parseDescription(existing.description);
395 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
396 }),
397
398 list: () =>
399 Effect.gen(function* () {
400 const env = yield* GcpEnvironment.current;
401 const pages = yield* compute.aggregatedListTargetPools
402 .pages({
403 project: env.project,
404 returnPartialSuccess: true,
405 maxResults: 500,
406 })
407 .pipe(Stream.runCollect);
408 return Array.from(pages).flatMap((page) =>
409 Object.values(page.items ?? {}).flatMap((scoped) =>
410 (scoped?.targetPools ?? [])
411 .filter((item) => {
412 const { labels } = parseDescription(item.description);
413 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
414 })
415 .map((item) => toAttrs(item, env.project)),
416 ),
417 );
418 }),
419
420 reconcile: Effect.fn(function* ({ id, news, output }) {
421 const env = yield* GcpEnvironment.current;
422 const targetPoolName = yield* toName(id, news.targetPoolName, output?.targetPoolName);
423 const region = normalizeRegion(news.region ?? output?.region, env.region);
424 const ownership = yield* createInternalLabels(id);
425 const desiredDescription = encodeDescription(ownership, news.description);
426 const sessionAffinity = sessionAffinityOf(news.sessionAffinity);
427 const backupPool =
428 news.backupPool !== undefined && news.backupPool.length > 0
429 ? toPoolUrl(env.project, region, news.backupPool)
430 : undefined;
431 const healthChecks = news.healthChecks?.map((check) => toHealthCheckUrl(env.project, check));
432 const instances = news.instances?.map((instance) => toInstanceUrl(env.project, instance));
433
434 let current = yield* getByName(env.project, region, targetPoolName);
435
436 if (current === undefined) {
437 const created = yield* compute
438 .insertTargetPools({
439 project: env.project,
440 region,
441 body: {
442 name: targetPoolName,
443 description: desiredDescription,
444 sessionAffinity,
445 backupPool,
446 failoverRatio: news.failoverRatio,
447 healthChecks,
448 instances,
449 },
450 })
451 .pipe(
452 Effect.flatMap((operation) =>
453 waitRegionOperation(env.project, region, operation, {
454 ignore: ["RESOURCE_ALREADY_EXISTS"],
455 }).pipe(Effect.flatMap(() => requirePool(env.project, region, targetPoolName))),
456 ),
457 Effect.catchTag("Conflict", () => getByName(env.project, region, targetPoolName)),
458 );
459 current = created ?? undefined;
460 }
461
462 if (current === undefined) {
463 return yield* new TargetPoolNotResolved({ targetPoolName, region });
464 }
465
466 if (news.backupPool !== undefined || news.failoverRatio !== undefined) {
467 const desiredBackup =
468 news.backupPool !== undefined
469 ? news.backupPool.length > 0
470 ? toPoolUrl(env.project, region, news.backupPool)
471 : ""
472 : (current.backupPool ?? "");
473 const desiredFailover = news.failoverRatio ?? current.failoverRatio ?? 0;
474 if (
475 !sameRef(desiredBackup, current.backupPool) ||
476 desiredFailover !== (current.failoverRatio ?? 0)
477 ) {
478 yield* runOp(
479 env.project,
480 region,
481 targetPoolName,
482 compute.setBackupTargetPools({
483 project: env.project,
484 region,
485 targetPool: targetPoolName,
486 failoverRatio: desiredFailover,
487 body: { target: desiredBackup },
488 }),
489 ).pipe(Effect.catchTag("Conflict", () => Effect.void));
490 current = (yield* getByName(env.project, region, targetPoolName)) ?? current;
491 }
492 }
493
494 if (healthChecks !== undefined) {
495 const observed = current.healthChecks ?? [];
496 const observedKeys = new Set(observed.map((url) => lastSegment(url)));
497 const desiredKeys = new Set(healthChecks.map((url) => lastSegment(url)));
498 const toAdd = healthChecks.filter((url) => !observedKeys.has(lastSegment(url)));
499 const toRemove = observed.filter((url) => !desiredKeys.has(lastSegment(url)));
500 if (toAdd.length > 0) {
501 yield* runOp(
502 env.project,
503 region,
504 targetPoolName,
505 compute.addHealthCheckTargetPools({
506 project: env.project,
507 region,
508 targetPool: targetPoolName,
509 body: {
510 healthChecks: toAdd.map((healthCheck) => ({ healthCheck })),
511 },
512 }),
513 );
514 }
515 if (toRemove.length > 0) {
516 yield* runOp(
517 env.project,
518 region,
519 targetPoolName,
520 compute.removeHealthCheckTargetPools({
521 project: env.project,
522 region,
523 targetPool: targetPoolName,
524 body: {
525 healthChecks: toRemove.map((healthCheck) => ({ healthCheck })),
526 },
527 }),
528 );
529 }
530 current = (yield* getByName(env.project, region, targetPoolName)) ?? current;
531 }
532
533 if (instances !== undefined) {
534 const observed = current.instances ?? [];
535 const observedKeys = new Set(observed.map(instanceKey));
536 const desiredKeys = new Set(instances.map(instanceKey));
537 const toAdd = instances.filter((url) => !observedKeys.has(instanceKey(url)));
538 const toRemove = observed.filter((url) => !desiredKeys.has(instanceKey(url)));
539 if (toAdd.length > 0) {
540 yield* runOp(
541 env.project,
542 region,
543 targetPoolName,
544 compute.addInstanceTargetPools({
545 project: env.project,
546 region,
547 targetPool: targetPoolName,
548 body: {
549 instances: toAdd.map((instance) => ({ instance })),
550 },
551 }),
552 );
553 }
554 if (toRemove.length > 0) {
555 yield* runOp(
556 env.project,
557 region,
558 targetPoolName,
559 compute.removeInstanceTargetPools({
560 project: env.project,
561 region,
562 targetPool: targetPoolName,
563 body: {
564 instances: toRemove.map((instance) => ({ instance })),
565 },
566 }),
567 );
568 }
569 current = (yield* getByName(env.project, region, targetPoolName)) ?? current;
570 }
571
572 if (news.securityPolicy !== undefined) {
573 const desiredPolicy = news.securityPolicy;
574 if (!sameRef(desiredPolicy, current.securityPolicy ?? "")) {
575 yield* runOp(
576 env.project,
577 region,
578 targetPoolName,
579 compute.setSecurityPolicyTargetPools({
580 project: env.project,
581 region,
582 targetPool: targetPoolName,
583 body: { securityPolicy: desiredPolicy },
584 }),
585 );
586 current = (yield* getByName(env.project, region, targetPoolName)) ?? current;
587 }
588 }
589
590 return toAttrs(current, env.project);
591 }),
592
593 delete: Effect.fn(function* ({ output }) {
594 const env = yield* GcpEnvironment.current;
595 const project = output.project || env.project;
596 const region = normalizeRegion(output.region, env.region);
597 yield* compute
598 .deleteTargetPools({
599 project,
600 region,
601 targetPool: output.targetPoolName,
602 })
603 .pipe(
604 Effect.flatMap((operation) =>
605 waitRegionOperation(project, region, operation, {
606 ignore: ["RESOURCE_NOT_FOUND"],
607 }),
608 ),
609 Effect.catchTag("NotFound", () => Effect.void),
610 Effect.retry({
611 while: (error) => error._tag === "Conflict",
612 times: 8,
613 schedule: Schedule.spaced("2 seconds"),
614 }),
615 );
616 yield* waitUntilGone(project, region, output.targetPoolName);
617 }),
618 });