@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 568 lines 18.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 {
14 createInternalLabels,
15 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20 import { waitGlobalOperation } from "./operations.ts";
21
22 const DEFAULT_MACHINE_TYPE = "e2-micro";
23 const DEFAULT_SOURCE_IMAGE = "projects/debian-cloud/global/images/family/debian-12";
24 const DEFAULT_DISK_SIZE_GB = "10";
25 const DEFAULT_NETWORK = "global/networks/default";
26 const MAX_NAME_LENGTH = 63;
27
28 export type InstanceTemplateAccessConfig = {
29 /** Access config type. @default "ONE_TO_ONE_NAT" */
30 type?: string;
31 /** Access config name. */
32 name?: string;
33 /** Network tier (`PREMIUM` or `STANDARD`). */
34 networkTier?: string;
35 /** External IPv4 address. */
36 natIP?: string;
37 };
38
39 export type InstanceTemplateNetworkInterface = {
40 /**
41 * VPC network URL or name.
42 * @default "global/networks/default"
43 */
44 network?: string;
45 /** Subnetwork URL. */
46 subnetwork?: string;
47 /** Internal IPv4 address. */
48 networkIP?: string;
49 /** NIC type (`GVNIC` or `VIRTIO_NET`). */
50 nicType?: string;
51 /** Stack type (`IPV4_ONLY` or `IPV4_IPV6`). */
52 stackType?: string;
53 /** External access configs. Omit for no external IP. */
54 accessConfigs?: InstanceTemplateAccessConfig[];
55 };
56
57 export type InstanceTemplateDisk = {
58 /** Whether this is the boot disk. */
59 boot?: boolean;
60 /** Delete the disk when the instance is deleted. */
61 autoDelete?: boolean;
62 /** Device name visible to the guest OS. */
63 deviceName?: string;
64 /** Disk type (`PERSISTENT` or `SCRATCH`). @default "PERSISTENT" */
65 type?: string;
66 /** Attach mode (`READ_WRITE` or `READ_ONLY`). */
67 mode?: string;
68 /** Disk interface (`SCSI` or `NVME`). */
69 diskInterface?: string;
70 /** Disk size in GB. */
71 diskSizeGb?: string | number;
72 /** Persistent disk type (`pd-standard`, `pd-balanced`, `pd-ssd`). */
73 diskType?: string;
74 /** Source image URL or family. */
75 sourceImage?: string;
76 /** Source snapshot URL. */
77 sourceSnapshot?: string;
78 /** Existing disk to attach (name for zonal, URL for regional). */
79 source?: string;
80 /** Disk resource name. */
81 diskName?: string;
82 /** Disk labels. */
83 labels?: Record<string, string>;
84 };
85
86 export type InstanceTemplateServiceAccount = {
87 /** Service account email. */
88 email?: string;
89 /** OAuth scopes granted to the service account. */
90 scopes?: string[];
91 };
92
93 export type InstanceTemplateScheduling = {
94 /** Restart the VM if Compute Engine terminates it. */
95 automaticRestart?: boolean;
96 /** Host maintenance behavior (`MIGRATE` or `TERMINATE`). */
97 onHostMaintenance?: string;
98 /** Whether the VM is preemptible. */
99 preemptible?: boolean;
100 /** Provisioning model (`STANDARD` or `SPOT`). */
101 provisioningModel?: string;
102 };
103
104 export type InstanceTemplateProps = {
105 /**
106 * Template name. If omitted, a unique RFC1035 name is generated from the
107 * stack, stage, and logical id. Must be 1-63 characters matching
108 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Changing it replaces the template.
109 */
110 templateName?: string;
111 /**
112 * Optional description. Changing it replaces the template.
113 */
114 description?: string;
115 /**
116 * Machine type name (not a URL), e.g. `e2-micro`. Instance templates are
117 * immutable — changing this replaces the template.
118 * @default "e2-micro"
119 */
120 machineType?: string;
121 /**
122 * Allow sending/receiving packets with non-instance IPs.
123 * @default false
124 */
125 canIpForward?: boolean;
126 /**
127 * Labels applied to instances created from this template. Alchemy
128 * ownership labels are merged in automatically. Changing labels replaces
129 * the template (no in-place update API).
130 */
131 labels?: Record<string, string>;
132 /**
133 * Network tags applied to instances created from this template.
134 */
135 networkTags?: string[];
136 /**
137 * Instance metadata key/value pairs.
138 */
139 metadata?: Record<string, string>;
140 /**
141 * Attached disks. If omitted, a 10 GB Debian 12 boot disk is used.
142 */
143 disks?: InstanceTemplateDisk[];
144 /**
145 * Network interfaces.
146 * @default [{ network: "global/networks/default" }]
147 */
148 networkInterfaces?: InstanceTemplateNetworkInterface[];
149 /**
150 * Service accounts and scopes for created instances.
151 */
152 serviceAccounts?: InstanceTemplateServiceAccount[];
153 /**
154 * Scheduling options for created instances.
155 */
156 scheduling?: InstanceTemplateScheduling;
157 };
158
159 export type InstanceTemplate = Resource<
160 "GCP.Compute.InstanceTemplate",
161 InstanceTemplateProps,
162 {
163 /** Template name. */
164 templateName: string;
165 /** Project id. */
166 project: string;
167 /** Description. */
168 description: string | undefined;
169 /** Machine type name. */
170 machineType: string | undefined;
171 /** User labels (Alchemy ownership labels stripped). */
172 labels: Record<string, string>;
173 /** Network tags. */
174 networkTags: string[];
175 /** Whether IP forwarding is enabled. */
176 canIpForward: boolean;
177 /** Boot-disk source image, if set. */
178 sourceImage: string | undefined;
179 /** Server-defined URL. */
180 selfLink: string | undefined;
181 /** Server-assigned numeric id. */
182 templateId: string | undefined;
183 /** RFC3339 creation timestamp. */
184 creationTimestamp: string | undefined;
185 },
186 never,
187 Providers
188 >;
189
190 /**
191 * A global Compute Engine instance template.
192 *
193 * Instance templates are immutable. Changing machine type, disks, labels,
194 * network interfaces, or other properties replaces the template. Use the
195 * template to create VMs, managed instance groups, and reservations.
196 *
197 * ### Creating a Template
198 * **Example:** Generated name with defaults
199 * ```typescript
200 * const template = yield* GCP.Compute.InstanceTemplate("web", {});
201 * ```
202 *
203 * **Example:** Explicit machine type, disk, and labels
204 * ```typescript
205 * const template = yield* GCP.Compute.InstanceTemplate("web", {
206 * machineType: "e2-micro",
207 * labels: { env: "prod" },
208 * disks: [
209 * {
210 * boot: true,
211 * autoDelete: true,
212 * sourceImage:
213 * "projects/debian-cloud/global/images/family/debian-12",
214 * diskSizeGb: 10,
215 * },
216 * ],
217 * networkInterfaces: [{ network: "global/networks/default" }],
218 * });
219 * ```
220 *
221 * @resource
222 * @category Compute
223 */
224 export const InstanceTemplate = Resource<InstanceTemplate>("GCP.Compute.InstanceTemplate");
225
226 export class InstanceTemplateNotResolved extends Data.TaggedError(
227 "GCP.Compute.InstanceTemplateNotResolved",
228 )<{
229 templateName: string;
230 }> {}
231
232 export class InstanceTemplateStillExists extends Data.TaggedError(
233 "GCP.Compute.InstanceTemplateStillExists",
234 )<{
235 templateName: string;
236 }> {}
237
238 const DEFAULT_DISKS: InstanceTemplateDisk[] = [
239 {
240 boot: true,
241 autoDelete: true,
242 type: "PERSISTENT",
243 sourceImage: DEFAULT_SOURCE_IMAGE,
244 diskSizeGb: DEFAULT_DISK_SIZE_GB,
245 },
246 ];
247
248 const DEFAULT_NICS: InstanceTemplateNetworkInterface[] = [{ network: DEFAULT_NETWORK }];
249
250 const userLabels = (
251 labels: Record<string, string | undefined> | null | undefined,
252 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
253
254 const rfc1035Name = (name: string) => {
255 let next = name.toLowerCase().replace(/[^a-z0-9-]/g, "-");
256 if (!/^[a-z]/.test(next)) next = `t${next}`;
257 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
258 return next.length > 0 ? next : "template";
259 };
260
261 const toName = (id: string, name: string | undefined, existing?: string) =>
262 Effect.gen(function* () {
263 if (name !== undefined) return name;
264 if (existing !== undefined) return existing;
265 return rfc1035Name(
266 yield* createPhysicalName({
267 id,
268 maxLength: MAX_NAME_LENGTH,
269 lowercase: true,
270 }),
271 );
272 });
273
274 const sortedRecord = (labels: Record<string, string> | undefined): Record<string, string> =>
275 Object.fromEntries(
276 Object.entries(labels ?? {}).sort(([left], [right]) => left.localeCompare(right)),
277 );
278
279 const resolvedDisks = (props: InstanceTemplateProps) =>
280 props.disks !== undefined && props.disks.length > 0 ? props.disks : DEFAULT_DISKS;
281
282 const resolvedNics = (props: InstanceTemplateProps) =>
283 props.networkInterfaces !== undefined && props.networkInterfaces.length > 0
284 ? props.networkInterfaces
285 : DEFAULT_NICS;
286
287 const fingerprint = (props: InstanceTemplateProps): string =>
288 JSON.stringify({
289 templateName: props.templateName ?? "",
290 description: props.description ?? "",
291 machineType: props.machineType ?? DEFAULT_MACHINE_TYPE,
292 canIpForward: props.canIpForward === true,
293 labels: sortedRecord(props.labels),
294 networkTags: [...(props.networkTags ?? [])].sort(),
295 metadata: sortedRecord(props.metadata),
296 disks: resolvedDisks(props).map((disk) => ({
297 boot: disk.boot === true,
298 autoDelete: disk.autoDelete,
299 deviceName: disk.deviceName ?? "",
300 type: disk.type ?? "",
301 mode: disk.mode ?? "",
302 diskInterface: disk.diskInterface ?? "",
303 diskSizeGb: disk.diskSizeGb !== undefined ? String(disk.diskSizeGb) : "",
304 diskType: disk.diskType ?? "",
305 sourceImage: disk.sourceImage ?? "",
306 sourceSnapshot: disk.sourceSnapshot ?? "",
307 source: disk.source ?? "",
308 diskName: disk.diskName ?? "",
309 labels: sortedRecord(disk.labels),
310 })),
311 networkInterfaces: resolvedNics(props).map((nic) => ({
312 network: nic.network ?? "",
313 subnetwork: nic.subnetwork ?? "",
314 networkIP: nic.networkIP ?? "",
315 nicType: nic.nicType ?? "",
316 stackType: nic.stackType ?? "",
317 accessConfigs: nic.accessConfigs ?? [],
318 })),
319 serviceAccounts: props.serviceAccounts ?? [],
320 scheduling: props.scheduling ?? {},
321 });
322
323 const initializeParamsOf = (
324 disk: InstanceTemplateDisk,
325 ): compute.AttachedDiskInitializeParams | undefined => {
326 if (
327 disk.sourceImage === undefined &&
328 disk.sourceSnapshot === undefined &&
329 disk.diskType === undefined &&
330 disk.diskName === undefined &&
331 disk.labels === undefined &&
332 disk.diskSizeGb === undefined
333 ) {
334 return undefined;
335 }
336 return {
337 sourceImage: disk.sourceImage,
338 sourceSnapshot: disk.sourceSnapshot,
339 diskType: disk.diskType,
340 diskName: disk.diskName,
341 labels: disk.labels,
342 diskSizeGb: disk.diskSizeGb !== undefined ? String(disk.diskSizeGb) : undefined,
343 };
344 };
345
346 const toDisks = (disks: InstanceTemplateDisk[]): compute.AttachedDisk[] =>
347 disks.map((disk) => ({
348 boot: disk.boot,
349 autoDelete: disk.autoDelete,
350 deviceName: disk.deviceName,
351 type: disk.type,
352 mode: disk.mode,
353 interface: disk.diskInterface,
354 source: disk.source,
355 initializeParams: disk.source ? undefined : initializeParamsOf(disk),
356 }));
357
358 const toNics = (nics: InstanceTemplateNetworkInterface[]): compute.NetworkInterface[] =>
359 nics.map((nic) => ({
360 network: nic.network,
361 subnetwork: nic.subnetwork,
362 networkIP: nic.networkIP,
363 nicType: nic.nicType,
364 stackType: nic.stackType,
365 accessConfigs: nic.accessConfigs,
366 }));
367
368 const toProperties = (
369 news: InstanceTemplateProps,
370 labels: Record<string, string>,
371 ): compute.InstanceProperties => ({
372 machineType: news.machineType ?? DEFAULT_MACHINE_TYPE,
373 canIpForward: news.canIpForward,
374 labels,
375 tags: news.networkTags !== undefined ? { items: news.networkTags } : undefined,
376 metadata:
377 news.metadata !== undefined
378 ? {
379 items: Object.entries(news.metadata).map(([key, value]) => ({
380 key,
381 value,
382 })),
383 }
384 : undefined,
385 disks: toDisks(resolvedDisks(news)),
386 networkInterfaces: toNics(resolvedNics(news)),
387 serviceAccounts: news.serviceAccounts,
388 scheduling: news.scheduling,
389 });
390
391 const bootSourceImage = (template: compute.InstanceTemplate) => {
392 const boot = (template.properties?.disks ?? []).find((disk) => disk.boot === true);
393 return boot?.initializeParams?.sourceImage;
394 };
395
396 const toAttrs = (template: compute.InstanceTemplate, project: string) => ({
397 templateName: template.name ?? "",
398 project,
399 description: template.description,
400 machineType: template.properties?.machineType,
401 labels: userLabels(template.properties?.labels),
402 networkTags: template.properties?.tags?.items ?? [],
403 canIpForward: template.properties?.canIpForward === true,
404 sourceImage: bootSourceImage(template),
405 selfLink: template.selfLink,
406 templateId: template.id,
407 creationTimestamp: template.creationTimestamp,
408 });
409
410 const getByName = (project: string, instanceTemplate: string) =>
411 compute
412 .getInstanceTemplates({ project, instanceTemplate })
413 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
414
415 const waitUntilPresent = (project: string, templateName: string) =>
416 getByName(project, templateName).pipe(
417 Effect.flatMap((template) =>
418 template !== undefined
419 ? Effect.succeed(template)
420 : Effect.fail(new InstanceTemplateNotResolved({ templateName })),
421 ),
422 Effect.retry({
423 while: (error) => error._tag === "GCP.Compute.InstanceTemplateNotResolved",
424 times: 8,
425 schedule: Schedule.spaced("1 second"),
426 }),
427 Effect.catchTag("GCP.Compute.InstanceTemplateNotResolved", () => Effect.undefined),
428 );
429
430 const waitUntilGone = (project: string, templateName: string) =>
431 getByName(project, templateName).pipe(
432 Effect.flatMap((template) =>
433 template === undefined
434 ? Effect.void
435 : Effect.fail(new InstanceTemplateStillExists({ templateName })),
436 ),
437 Effect.retry({
438 while: (error) => error._tag === "GCP.Compute.InstanceTemplateStillExists",
439 times: 10,
440 schedule: Schedule.spaced("1 second"),
441 }),
442 Effect.catchTag("GCP.Compute.InstanceTemplateStillExists", () => Effect.void),
443 );
444
445 export const InstanceTemplateProvider = () =>
446 Provider.succeed(InstanceTemplate, {
447 stables: ["templateName", "project", "templateId", "selfLink", "creationTimestamp"],
448
449 diff: Effect.fn(function* ({ news, olds, output }) {
450 if (!isResolved(news)) return undefined;
451 const previousName = olds?.templateName ?? output?.templateName;
452 const nextName = news.templateName ?? previousName;
453 if (previousName === undefined && output === undefined) {
454 return undefined;
455 }
456 const nameChanged =
457 news.templateName !== undefined &&
458 previousName !== undefined &&
459 news.templateName !== previousName;
460 const propsChanged = olds !== undefined && fingerprint(news) !== fingerprint(olds);
461 const adoptedChanged =
462 olds === undefined &&
463 output !== undefined &&
464 ((news.machineType ?? DEFAULT_MACHINE_TYPE) !==
465 (output.machineType ?? DEFAULT_MACHINE_TYPE) ||
466 (news.description ?? "") !== (output.description ?? "") ||
467 (news.canIpForward === true) !== output.canIpForward ||
468 JSON.stringify(sortedRecord(news.labels)) !==
469 JSON.stringify(sortedRecord(output.labels)));
470 if (!nameChanged && !propsChanged && !adoptedChanged) {
471 return undefined;
472 }
473 return {
474 action: "replace" as const,
475 deleteFirst:
476 previousName !== undefined && nextName !== undefined && nextName === previousName,
477 };
478 }),
479
480 read: Effect.fn(function* ({ id, olds, output }) {
481 const env = yield* GcpEnvironment.current;
482 const templateName = yield* toName(id, olds?.templateName, output?.templateName);
483 const existing = yield* getByName(env.project, templateName);
484 if (existing === undefined) return undefined;
485 const attrs = toAttrs(existing, env.project);
486 return (yield* hasAlchemyLabels(id, tagRecord(existing.properties?.labels)))
487 ? attrs
488 : Unowned(attrs);
489 }),
490
491 list: () =>
492 Effect.gen(function* () {
493 const env = yield* GcpEnvironment.current;
494 return yield* compute.listInstanceTemplates
495 .items({ project: env.project, maxResults: 500 })
496 .pipe(
497 Stream.filter((template) =>
498 Object.keys(template.properties?.labels ?? {}).some((key) =>
499 key.startsWith("alchemy-"),
500 ),
501 ),
502 Stream.map((template) => toAttrs(template, env.project)),
503 Stream.runCollect,
504 Effect.map((chunk) => Array.from(chunk)),
505 );
506 }),
507
508 reconcile: Effect.fn(function* ({ id, news, output }) {
509 const env = yield* GcpEnvironment.current;
510 const templateName = yield* toName(id, news.templateName, output?.templateName);
511 const desiredLabels = {
512 ...toLabels(news.labels),
513 ...(yield* createInternalLabels(id)),
514 };
515
516 let current = yield* getByName(env.project, templateName);
517
518 if (current === undefined) {
519 yield* compute
520 .insertInstanceTemplates({
521 project: env.project,
522 body: {
523 name: templateName,
524 description: news.description,
525 properties: toProperties(news, desiredLabels),
526 },
527 })
528 .pipe(
529 Effect.flatMap((operation) =>
530 waitGlobalOperation(env.project, operation, {
531 ignore: ["RESOURCE_ALREADY_EXISTS"],
532 }),
533 ),
534 Effect.catchTag("Conflict", () => Effect.void),
535 );
536 current = yield* waitUntilPresent(env.project, templateName);
537 }
538
539 if (current === undefined) {
540 return yield* new InstanceTemplateNotResolved({ templateName });
541 }
542
543 return toAttrs(current, env.project);
544 }),
545
546 delete: Effect.fn(function* ({ output }) {
547 const env = yield* GcpEnvironment.current;
548 const operation = yield* compute
549 .deleteInstanceTemplates({
550 project: env.project,
551 instanceTemplate: output.templateName,
552 })
553 .pipe(
554 Effect.catchTag("NotFound", () => Effect.undefined),
555 Effect.retry({
556 while: (error) => error._tag === "Conflict",
557 times: 8,
558 schedule: Schedule.spaced("2 seconds"),
559 }),
560 );
561 if (operation !== undefined) {
562 yield* waitGlobalOperation(env.project, operation, {
563 ignore: ["RESOURCE_NOT_FOUND"],
564 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
565 }
566 yield* waitUntilGone(env.project, output.templateName);
567 }),
568 });