@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 664 lines 23.3 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 { 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 { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
14 import type { Providers } from "../Providers.ts";
15 import { waitZoneOperation } from "./operations.ts";
16
17 const DEFAULT_ZONE = "us-central1-a";
18 const MAX_NAME_LENGTH = 63;
19
20 export type ReservationInstanceProperties =
21 compute.AllocationSpecificSKUAllocationReservedInstanceProperties;
22 export type ReservationShareSettings = compute.ShareSettings;
23 export type ReservationSharingPolicy = compute.AllocationReservationSharingPolicy;
24 export type ReservationAggregate = compute.AllocationAggregateReservation;
25 export type ReservationDuration = compute.Duration;
26 export type ReservationDeploymentType = compute.ReservationDeploymentTypeEnum | (string & {});
27 export type ReservationSchedulingType = compute.ReservationSchedulingTypeEnum | (string & {});
28 export type ReservationProtectionTier = compute.ReservationProtectionTierEnum | (string & {});
29 export type ReservationEarlyAccessMaintenance =
30 | compute.ReservationEarlyAccessMaintenanceEnum
31 | (string & {});
32 export type ReservationConfidentialComputeType =
33 | compute.ReservationConfidentialComputeTypeEnum
34 | (string & {});
35
36 export type ReservationSpecificSku = {
37 /**
38 * Number of reserved VM instances. Mutable in place via
39 * `reservations.resize`.
40 */
41 count: number | string;
42 /**
43 * Machine shape of each reserved VM. Immutable — changing it replaces
44 * the reservation. Mutually exclusive with `sourceInstanceTemplate`.
45 */
46 instanceProperties?: ReservationInstanceProperties;
47 /**
48 * Instance template URL used instead of `instanceProperties`. Immutable
49 * — changing it replaces the reservation.
50 */
51 sourceInstanceTemplate?: string;
52 };
53
54 export type ReservationProps = {
55 /**
56 * Reservation name (RFC1035, 1-63 characters). If omitted, a unique name
57 * is generated from the stack, stage, and logical id. Changing the name
58 * replaces the reservation.
59 */
60 reservationName?: string;
61 /**
62 * Zone the reservation lives in (e.g. `us-central1-a`). Immutable —
63 * changing it replaces the reservation.
64 * @default "us-central1-a"
65 */
66 zone?: string;
67 /**
68 * Optional description. Compute reservations have no labels field, so
69 * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`)
70 * is stored in a `[alchemy …]` prefix for `list` / nuke. Changing it
71 * replaces the reservation.
72 */
73 description?: string;
74 /**
75 * Specific-SKU reservation (count + machine shape or instance template).
76 * Machine shape and template are immutable; `count` resizes in place.
77 */
78 specificReservation?: ReservationSpecificSku;
79 /**
80 * When true, only VMs that target this reservation by name can consume
81 * it. Immutable — changing it replaces the reservation.
82 * @default false
83 */
84 specificReservationRequired?: boolean;
85 /**
86 * Share settings for a shared reservation.
87 */
88 shareSettings?: ReservationShareSettings;
89 /**
90 * Resource policies attached to this reservation (placement).
91 */
92 resourcePolicies?: Record<string, string>;
93 /**
94 * RFC3339 time when Compute Engine auto-deletes the reservation.
95 */
96 deleteAtTime?: string;
97 /**
98 * Duration after create when Compute Engine auto-deletes the
99 * reservation.
100 */
101 deleteAfterDuration?: ReservationDuration;
102 /**
103 * Allow unplanned (emergent) maintenance for reserved VMs.
104 */
105 enableEmergentMaintenance?: boolean;
106 /**
107 * Early-access maintenance enrollment (`NO_EARLY_ACCESS`, `WAVE1`,
108 * `WAVE2`).
109 */
110 earlyAccessMaintenance?: ReservationEarlyAccessMaintenance;
111 /**
112 * Workload protection tier.
113 */
114 protectionTier?: ReservationProtectionTier;
115 /**
116 * Deployment strategy. Immutable — changing it replaces the reservation.
117 */
118 deploymentType?: ReservationDeploymentType;
119 /**
120 * Maintenance scheduling type.
121 */
122 schedulingType?: ReservationSchedulingType;
123 /**
124 * Confidential compute type.
125 */
126 confidentialComputeType?: ReservationConfidentialComputeType;
127 /**
128 * Aggregate (accelerator) reservation. Immutable — switching between
129 * specific and aggregate replaces the reservation.
130 */
131 aggregateReservation?: ReservationAggregate;
132 /**
133 * Sharing policy with Google Cloud managed services.
134 */
135 reservationSharingPolicy?: ReservationSharingPolicy;
136 };
137
138 export type Reservation = Resource<
139 "GCP.Compute.Reservation",
140 ReservationProps,
141 {
142 /** Reservation name. */
143 reservationName: string;
144 /** Server-assigned numeric id. */
145 reservationId: string | undefined;
146 /** Project id. */
147 project: string;
148 /** Zone short name (`us-central1-a`). */
149 zone: string;
150 /** User description with the Alchemy ownership prefix stripped. */
151 description: string | undefined;
152 /** Server-reported status (`READY`, `CREATING`, `DELETING`, …). */
153 status: string | undefined;
154 /** Specific-SKU reservation, if any. */
155 specificReservation: compute.AllocationSpecificSKUReservation | undefined;
156 /** Whether consumption requires targeting this reservation by name. */
157 specificReservationRequired: boolean;
158 /** Share settings, if any. */
159 shareSettings: ReservationShareSettings | undefined;
160 /** Attached resource policies. */
161 resourcePolicies: Record<string, string>;
162 /** Parent commitment URL, if any. */
163 commitment: string | undefined;
164 /** Compute Engine self-link. */
165 selfLink: string | undefined;
166 /** RFC3339 creation timestamp. */
167 creationTimestamp: string | undefined;
168 },
169 never,
170 Providers
171 >;
172
173 /**
174 * A zonal Compute Engine capacity reservation.
175 *
176 * Reservations hold VM capacity in a zone even when the reserved VMs are
177 * not running. Compute Engine has no labels on this resource, so Alchemy
178 * stamps ownership into the description (`[alchemy alchemy-stack=…
179 * alchemy-stage=… alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find
180 * them.
181 *
182 * Name, zone, machine shape, `specificReservationRequired`, and
183 * `deploymentType` are immutable — changing them replaces the reservation.
184 * `specificReservation.count` resizes in place. Description and share
185 * settings update in place via `reservations.patch`.
186 *
187 * ### Creating a Reservation
188 * **Example:** One `n1-standard-1` in the default zone
189 * ```typescript
190 * const reserved = yield* GCP.Compute.Reservation("Burst", {
191 * specificReservation: {
192 * count: 1,
193 * instanceProperties: { machineType: "n1-standard-1" },
194 * },
195 * specificReservationRequired: true,
196 * });
197 * ```
198 *
199 * **Example:** Named reservation with a description
200 * ```typescript
201 * const reserved = yield* GCP.Compute.Reservation("Burst", {
202 * reservationName: "app-burst",
203 * zone: "us-central1-a",
204 * description: "on-demand burst capacity",
205 * specificReservation: {
206 * count: 2,
207 * instanceProperties: { machineType: "n1-standard-1" },
208 * },
209 * });
210 * ```
211 *
212 * ### Resizing a Reservation
213 * **Example:** Grow count in place
214 * ```typescript
215 * const reserved = yield* GCP.Compute.Reservation("Burst", {
216 * reservationName: "app-burst",
217 * specificReservation: {
218 * count: 4,
219 * instanceProperties: { machineType: "n1-standard-1" },
220 * },
221 * });
222 * ```
223 *
224 * @resource
225 * @category Compute
226 */
227 export const Reservation = Resource<Reservation>("GCP.Compute.Reservation");
228
229 export class ReservationNotResolved extends Data.TaggedError("GCP.Compute.ReservationNotResolved")<{
230 reservationName: string;
231 zone: string;
232 }> {}
233
234 export class ReservationNotReady extends Data.TaggedError("GCP.Compute.ReservationNotReady")<{
235 reservationName: string;
236 status: string;
237 }> {}
238
239 export class ReservationFailed extends Data.TaggedError("GCP.Compute.ReservationFailed")<{
240 reservationName: string;
241 status: string;
242 }> {}
243
244 export class ReservationStillExists extends Data.TaggedError("GCP.Compute.ReservationStillExists")<{
245 reservationName: string;
246 status: string;
247 }> {}
248
249 const lastSegment = (value: string | undefined): string => {
250 if (value === undefined || value.length === 0) return "";
251 const trimmed = value.replace(/\/+$/, "");
252 const parts = trimmed.split("/");
253 return parts[parts.length - 1] || trimmed;
254 };
255
256 const normalizeZone = (zone: string | undefined) => lastSegment(zone ?? DEFAULT_ZONE).toLowerCase();
257
258 const toName = (id: string, name: string | undefined, existing?: string) =>
259 Effect.gen(function* () {
260 if (name !== undefined) return name;
261 if (existing !== undefined) return existing;
262 const generated = yield* createPhysicalName({
263 id,
264 maxLength: MAX_NAME_LENGTH,
265 lowercase: true,
266 });
267 return /^[a-z]/.test(generated) ? generated : `r${generated}`.slice(0, MAX_NAME_LENGTH);
268 });
269
270 const encodeDescription = (
271 labels: Record<string, string>,
272 description: string | undefined,
273 ): string => {
274 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
275 return description ? `${marker}\n${description}` : marker;
276 };
277
278 const parseDescription = (
279 description: string | undefined,
280 ): {
281 labels: Record<string, string>;
282 description: string | undefined;
283 } => {
284 if (!description?.startsWith("[alchemy ")) {
285 return { labels: {}, description };
286 }
287 const end = description.indexOf("]");
288 if (end < 0) return { labels: {}, description };
289 const labels: Record<string, string> = {};
290 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
291 const eq = part.indexOf("=");
292 if (eq > 0) {
293 labels[part.slice(0, eq)] = part.slice(eq + 1);
294 }
295 }
296 const rest = description.slice(end + 1).replace(/^\n/, "");
297 return { labels, description: rest.length > 0 ? rest : undefined };
298 };
299
300 const hasOwnershipMarker = (description: string | undefined) =>
301 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
302
303 const countOf = (value: number | string | undefined): string | undefined => {
304 if (value === undefined) return undefined;
305 return String(value);
306 };
307
308 const toBody = (
309 reservationName: string,
310 props: ReservationProps,
311 ownership: Record<string, string>,
312 ): compute.Reservation => ({
313 name: reservationName,
314 description: encodeDescription(ownership, props.description),
315 specificReservation:
316 props.specificReservation !== undefined
317 ? {
318 count: countOf(props.specificReservation.count),
319 instanceProperties: props.specificReservation.instanceProperties,
320 sourceInstanceTemplate: props.specificReservation.sourceInstanceTemplate,
321 }
322 : undefined,
323 specificReservationRequired: props.specificReservationRequired === true,
324 shareSettings: props.shareSettings,
325 resourcePolicies: props.resourcePolicies,
326 deleteAtTime: props.deleteAtTime,
327 deleteAfterDuration: props.deleteAfterDuration,
328 enableEmergentMaintenance: props.enableEmergentMaintenance,
329 earlyAccessMaintenance: props.earlyAccessMaintenance,
330 protectionTier: props.protectionTier,
331 deploymentType: props.deploymentType,
332 schedulingType: props.schedulingType,
333 confidentialComputeType: props.confidentialComputeType,
334 aggregateReservation: props.aggregateReservation,
335 reservationSharingPolicy: props.reservationSharingPolicy,
336 });
337
338 const toAttrs = (reservation: compute.Reservation, project: string): Reservation["Attributes"] => {
339 const parsed = parseDescription(reservation.description);
340 return {
341 reservationName: reservation.name ?? reservation.id ?? "",
342 reservationId: reservation.id,
343 project,
344 zone: normalizeZone(reservation.zone),
345 description: parsed.description,
346 status: reservation.status,
347 specificReservation: reservation.specificReservation,
348 specificReservationRequired: reservation.specificReservationRequired === true,
349 shareSettings: reservation.shareSettings,
350 resourcePolicies: tagRecord(reservation.resourcePolicies),
351 commitment: reservation.commitment,
352 selfLink: reservation.selfLink,
353 creationTimestamp: reservation.creationTimestamp,
354 };
355 };
356
357 const sameJson = (left: unknown, right: unknown) =>
358 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
359
360 const getByName = (project: string, zone: string, reservation: string) =>
361 compute
362 .getReservations({ project, zone, reservation })
363 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
364
365 const waitReservationReady = (project: string, zone: string, reservationName: string) =>
366 getByName(project, zone, reservationName).pipe(
367 Effect.flatMap((reservation) =>
368 reservation?.status === "INVALID"
369 ? Effect.fail(
370 new ReservationFailed({
371 reservationName,
372 status: "INVALID",
373 }),
374 )
375 : Effect.succeed(reservation),
376 ),
377 Effect.filterOrFail(
378 (reservation): reservation is compute.Reservation =>
379 reservation !== undefined && reservation.status === "READY",
380 (reservation) =>
381 new ReservationNotReady({
382 reservationName,
383 status: reservation?.status ?? "MISSING",
384 }),
385 ),
386 Effect.retry({
387 while: (error) => error._tag === "GCP.Compute.ReservationNotReady",
388 times: 150,
389 schedule: Schedule.spaced("2 seconds"),
390 }),
391 );
392
393 const waitReservationGone = (project: string, zone: string, reservationName: string) =>
394 getByName(project, zone, reservationName).pipe(
395 Effect.flatMap((reservation) =>
396 reservation === undefined
397 ? Effect.void
398 : Effect.fail(
399 new ReservationStillExists({
400 reservationName,
401 status: reservation.status ?? "UNKNOWN",
402 }),
403 ),
404 ),
405 Effect.retry({
406 while: (error) => error instanceof ReservationStillExists,
407 times: 150,
408 schedule: Schedule.spaced("2 seconds"),
409 }),
410 );
411
412 export const ReservationProvider = () =>
413 Provider.succeed(Reservation, {
414 stables: [
415 "reservationName",
416 "reservationId",
417 "project",
418 "zone",
419 "selfLink",
420 "creationTimestamp",
421 ],
422
423 diff: Effect.fn(function* ({ news, olds, output }) {
424 if (!isResolved(news)) return undefined;
425
426 const previousName = olds?.reservationName ?? output?.reservationName;
427 const nextName = news.reservationName ?? previousName;
428 const nameChanged =
429 previousName !== undefined && nextName !== undefined && previousName !== nextName;
430
431 const previousZone = normalizeZone(olds?.zone ?? output?.zone);
432 const nextZone = normalizeZone(news.zone ?? output?.zone);
433 const zoneChanged = previousZone !== nextZone;
434
435 const previousRequired =
436 olds?.specificReservationRequired ?? output?.specificReservationRequired ?? false;
437 const nextRequired = news.specificReservationRequired === true;
438
439 const previousMachine =
440 olds?.specificReservation?.instanceProperties?.machineType ??
441 output?.specificReservation?.instanceProperties?.machineType;
442 const nextMachine = news.specificReservation?.instanceProperties?.machineType;
443 const machineChanged =
444 nextMachine !== undefined &&
445 previousMachine !== undefined &&
446 previousMachine !== nextMachine;
447
448 const previousTemplate =
449 olds?.specificReservation?.sourceInstanceTemplate ??
450 output?.specificReservation?.sourceInstanceTemplate;
451 const nextTemplate = news.specificReservation?.sourceInstanceTemplate;
452 const templateChanged =
453 (previousTemplate ?? "") !== (nextTemplate ?? "") &&
454 (previousTemplate !== undefined || nextTemplate !== undefined);
455
456 const previousIsAggregate = olds?.aggregateReservation !== undefined;
457 const nextIsAggregate = news.aggregateReservation !== undefined;
458 const previousIsSpecific =
459 (olds?.specificReservation ?? output?.specificReservation) !== undefined;
460 const nextIsSpecific = news.specificReservation !== undefined;
461 const kindChanged =
462 (previousIsAggregate && nextIsSpecific) || (previousIsSpecific && nextIsAggregate);
463
464 const deploymentChanged =
465 olds?.deploymentType !== undefined &&
466 news.deploymentType !== undefined &&
467 olds.deploymentType !== news.deploymentType;
468
469 // `reservations.update` accepts a description mask but leaves the
470 // stored description unchanged, so a new description replaces.
471 const descriptionChanged =
472 olds !== undefined && (olds.description ?? "") !== (news.description ?? "");
473
474 if (
475 nameChanged ||
476 zoneChanged ||
477 previousRequired !== nextRequired ||
478 machineChanged ||
479 templateChanged ||
480 kindChanged ||
481 deploymentChanged ||
482 descriptionChanged
483 ) {
484 return {
485 action: "replace" as const,
486 deleteFirst:
487 previousName !== undefined && nextName === previousName && previousZone === nextZone,
488 };
489 }
490 return undefined;
491 }),
492
493 read: Effect.fn(function* ({ id, olds, output }) {
494 const env = yield* GcpEnvironment.current;
495 const reservationName = yield* toName(id, olds?.reservationName, output?.reservationName);
496 const zone = normalizeZone(olds?.zone ?? output?.zone);
497 const existing = yield* getByName(env.project, zone, reservationName);
498 if (existing === undefined) return undefined;
499 const attrs = toAttrs(existing, env.project);
500 const { labels } = parseDescription(existing.description);
501 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
502 }),
503
504 list: () =>
505 Effect.gen(function* () {
506 const env = yield* GcpEnvironment.current;
507 const pages = yield* compute.aggregatedListReservations
508 .pages({
509 project: env.project,
510 returnPartialSuccess: true,
511 maxResults: 500,
512 })
513 .pipe(Stream.runCollect);
514 return Array.from(pages).flatMap((page) =>
515 Object.values(page.items ?? {}).flatMap((scoped) =>
516 (scoped?.reservations ?? [])
517 .filter((reservation) => hasOwnershipMarker(reservation.description))
518 .map((reservation) => toAttrs(reservation, env.project)),
519 ),
520 );
521 }),
522
523 reconcile: Effect.fn(function* ({ id, news, output }) {
524 const env = yield* GcpEnvironment.current;
525 const reservationName = yield* toName(id, news.reservationName, output?.reservationName);
526 const zone = normalizeZone(news.zone ?? output?.zone);
527 const ownership = yield* createInternalLabels(id);
528 const desired = toBody(reservationName, news, ownership);
529
530 let current = yield* getByName(env.project, zone, reservationName);
531 if (current?.status === "DELETING") {
532 yield* waitReservationGone(env.project, zone, reservationName);
533 current = undefined;
534 }
535
536 if (current === undefined) {
537 const inserted = yield* compute
538 .insertReservations({
539 project: env.project,
540 zone,
541 body: desired,
542 })
543 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
544 if (inserted !== undefined) {
545 yield* waitZoneOperation(env.project, zone, inserted, {
546 ignore: ["RESOURCE_ALREADY_EXISTS"],
547 });
548 }
549 current = yield* waitReservationReady(env.project, zone, reservationName);
550 }
551
552 if (current === undefined) {
553 return yield* new ReservationNotResolved({
554 reservationName,
555 zone,
556 });
557 }
558
559 if (current.status === "CREATING" || current.status === "UPDATING") {
560 current = yield* waitReservationReady(env.project, zone, reservationName);
561 }
562
563 if (current === undefined) {
564 return yield* new ReservationNotResolved({
565 reservationName,
566 zone,
567 });
568 }
569
570 const descriptionChanged = (current.description ?? "") !== (desired.description ?? "");
571 // Compute echoes a default `{ shareType: "LOCAL" }` when unset.
572 const shareChanged =
573 desired.shareSettings !== undefined &&
574 !sameJson(current.shareSettings, desired.shareSettings);
575 const emergentChanged =
576 (current.enableEmergentMaintenance ?? false) !==
577 (desired.enableEmergentMaintenance ?? false);
578
579 if (descriptionChanged || shareChanged || emergentChanged) {
580 const patched = yield* compute.updateReservations({
581 project: env.project,
582 zone,
583 reservation: reservationName,
584 updateMask: [
585 descriptionChanged ? "description" : undefined,
586 shareChanged ? "shareSettings" : undefined,
587 emergentChanged ? "enableEmergentMaintenance" : undefined,
588 ]
589 .filter((field): field is string => field !== undefined)
590 .join(","),
591 // `reservations.update` rejects a body without `name`.
592 body: {
593 name: reservationName,
594 description: desired.description,
595 shareSettings: desired.shareSettings,
596 enableEmergentMaintenance: desired.enableEmergentMaintenance,
597 },
598 });
599 yield* waitZoneOperation(env.project, zone, patched);
600 current =
601 (yield* getByName(env.project, zone, reservationName)) ??
602 (yield* waitReservationReady(env.project, zone, reservationName));
603 }
604
605 if (current === undefined) {
606 return yield* new ReservationNotResolved({
607 reservationName,
608 zone,
609 });
610 }
611
612 const desiredCount = desired.specificReservation?.count;
613 const observedCount = current.specificReservation?.count;
614 if (
615 desiredCount !== undefined &&
616 observedCount !== undefined &&
617 desiredCount !== observedCount
618 ) {
619 const resized = yield* compute.resizeReservations({
620 project: env.project,
621 zone,
622 reservation: reservationName,
623 body: { specificSkuCount: desiredCount },
624 });
625 yield* waitZoneOperation(env.project, zone, resized);
626 current = yield* waitReservationReady(env.project, zone, reservationName);
627 }
628
629 if (current === undefined) {
630 return yield* new ReservationNotResolved({
631 reservationName,
632 zone,
633 });
634 }
635
636 return toAttrs(current, env.project);
637 }),
638
639 delete: Effect.fn(function* ({ output }) {
640 const env = yield* GcpEnvironment.current;
641 const project = output.project || env.project;
642 const zone = normalizeZone(output.zone);
643 const deleted = yield* compute
644 .deleteReservations({
645 project,
646 zone,
647 reservation: output.reservationName,
648 })
649 .pipe(
650 Effect.catchTag("NotFound", () => Effect.undefined),
651 Effect.retry({
652 while: (error) => error._tag === "Conflict",
653 times: 8,
654 schedule: Schedule.spaced("2 seconds"),
655 }),
656 );
657 if (deleted !== undefined) {
658 yield* waitZoneOperation(project, zone, deleted, {
659 ignore: ["RESOURCE_NOT_FOUND"],
660 });
661 }
662 yield* waitReservationGone(project, zone, output.reservationName);
663 }),
664 });