The best way to control Claude Code, Codex and more from any computer or phone

main
ts 445 lines 14.7 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 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitGlobalOperation } from "./operations.ts";
22
23 export type MachineImageProps = {
24 /**
25 * Machine image name (RFC1035, 1-63 characters). If omitted, a unique
26 * name is generated from the stack, stage, and logical id. Changing the
27 * name replaces the machine image.
28 */
29 machineImageName?: string;
30 /**
31 * Source instance URL used to create the machine image
32 * (`projects/{project}/zones/{zone}/instances/{instance}` or a full
33 * self-link). Immutable — changing it replaces the machine image.
34 */
35 sourceInstance: string;
36 /**
37 * Optional description. Immutable — changing it replaces the machine
38 * image (the API has no patch).
39 */
40 description?: string;
41 /**
42 * User labels. Alchemy ownership labels are merged in automatically
43 * and synced via `machineImages.setLabels`.
44 */
45 labels?: Record<string, string>;
46 /**
47 * Cloud Storage locations for the machine image (`us-central1`, `us`,
48 * …). Immutable — changing it replaces the machine image.
49 */
50 storageLocations?: string[];
51 /**
52 * Attempt an application-consistent image by flushing the guest OS.
53 * Input-only; not persisted on the resource.
54 */
55 guestFlush?: boolean;
56 };
57
58 export type MachineImage = Resource<
59 "GCP.Compute.MachineImage",
60 MachineImageProps,
61 {
62 /** Machine image name. */
63 machineImageName: string;
64 /** Server-assigned numeric id. */
65 machineImageId: string | undefined;
66 /** Project id. */
67 project: string;
68 /** Server-reported status (`CREATING`, `READY`, `DELETING`, …). */
69 status: string | undefined;
70 /** Description. */
71 description: string | undefined;
72 /** User labels (Alchemy ownership labels stripped). */
73 labels: Record<string, string>;
74 /** Source instance URL. */
75 sourceInstance: string | undefined;
76 /** Cloud Storage locations. */
77 storageLocations: string[];
78 /** Total storage used by the machine image, in bytes. */
79 totalStorageBytes: string | undefined;
80 /** Compute Engine self-link. */
81 selfLink: string | undefined;
82 /** RFC3339 creation timestamp. */
83 creationTimestamp: string | undefined;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A Compute Engine machine image capturing a VM's disks, metadata, and
91 * configuration so it can be used to create new instances.
92 *
93 * Create from a source instance. Name, source instance, description, and
94 * storage locations replace the machine image. Labels are synced in place
95 * via `setLabels`.
96 *
97 * ### Creating a Machine Image
98 * **Example:** Machine image from an instance
99 * ```typescript
100 * const vm = yield* GCP.Compute.Instance("web", {
101 * zone: "us-central1-a",
102 * machineType: "e2-micro",
103 * });
104 * const image = yield* GCP.Compute.MachineImage("backup", {
105 * sourceInstance: vm.selfLink,
106 * labels: { env: "prod" },
107 * });
108 * ```
109 *
110 * **Example:** Explicit name and regional storage
111 * ```typescript
112 * const image = yield* GCP.Compute.MachineImage("backup", {
113 * machineImageName: "web-golden",
114 * sourceInstance:
115 * "projects/{project}/zones/us-central1-a/instances/web",
116 * description: "golden image of web",
117 * storageLocations: ["us-central1"],
118 * });
119 * ```
120 *
121 * ### Updating a Machine Image
122 * **Example:** Labels
123 * ```typescript
124 * const image = yield* GCP.Compute.MachineImage("backup", {
125 * machineImageName: "web-golden",
126 * sourceInstance:
127 * "projects/{project}/zones/us-central1-a/instances/web",
128 * labels: { env: "prod", role: "golden" },
129 * });
130 * ```
131 *
132 * @resource
133 * @category Compute
134 */
135 export const MachineImage = Resource<MachineImage>("GCP.Compute.MachineImage");
136
137 export class MachineImageNotResolved extends Data.TaggedError(
138 "GCP.Compute.MachineImageNotResolved",
139 )<{
140 machineImageName: string;
141 }> {}
142
143 export class MachineImagePending extends Data.TaggedError("GCP.Compute.MachineImagePending")<{
144 machineImageName: string;
145 status: string;
146 }> {}
147
148 export class MachineImageFailed extends Data.TaggedError("GCP.Compute.MachineImageFailed")<{
149 machineImageName: string;
150 status: string;
151 }> {}
152
153 export class MachineImageStillExists extends Data.TaggedError(
154 "GCP.Compute.MachineImageStillExists",
155 )<{
156 machineImageName: string;
157 status: string;
158 }> {}
159
160 export class MachineImageSourceRequired extends Data.TaggedError(
161 "GCP.Compute.MachineImageSourceRequired",
162 )<{
163 machineImageName: string;
164 }> {}
165
166 const MAX_NAME_LENGTH = 63;
167
168 const lastSegment = (value: string | undefined): string => {
169 if (value === undefined || value.length === 0) return "";
170 const parts = value.split("/");
171 return parts[parts.length - 1] || value;
172 };
173
174 const userLabels = (
175 labels: Record<string, string | undefined> | null | undefined,
176 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
177
178 const sameStrings = (left?: readonly string[], right?: readonly string[]) => {
179 const a = [...(left ?? [])].map((value) => value.toLowerCase()).sort();
180 const b = [...(right ?? [])].map((value) => value.toLowerCase()).sort();
181 return a.length === b.length && a.every((value, index) => value === b[index]);
182 };
183
184 const toName = (id: string, name: string | undefined, existing?: string) =>
185 Effect.gen(function* () {
186 if (name !== undefined) return name;
187 if (existing !== undefined) return existing;
188 const generated = yield* createPhysicalName({
189 id,
190 maxLength: MAX_NAME_LENGTH,
191 lowercase: true,
192 });
193 return /^[a-z]/.test(generated) ? generated : `m${generated}`.slice(0, MAX_NAME_LENGTH);
194 });
195
196 const toAttrs = (image: compute.MachineImage, project: string) => ({
197 machineImageName: image.name ?? image.id ?? "",
198 machineImageId: image.id,
199 project,
200 status: image.status,
201 description: image.description,
202 labels: userLabels(image.labels),
203 sourceInstance: image.sourceInstance,
204 storageLocations: image.storageLocations ?? [],
205 totalStorageBytes: image.totalStorageBytes,
206 selfLink: image.selfLink,
207 creationTimestamp: image.creationTimestamp,
208 });
209
210 const getByName = (project: string, machineImage: string) =>
211 compute
212 .getMachineImages({ project, machineImage })
213 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
214
215 const canonicalizeSourceInstance = (source: string | undefined): string => {
216 if (source === undefined || source.length === 0) return "";
217 const cleaned = source.split("?")[0] ?? source;
218 const full = cleaned.match(/(projects\/[^/]+\/zones\/[^/]+\/instances\/[^/]+)$/);
219 if (full?.[1] !== undefined) return full[1];
220 const zonal = cleaned.match(/(zones\/[^/]+\/instances\/[^/]+)$/);
221 if (zonal?.[1] !== undefined) return zonal[1];
222 return lastSegment(cleaned);
223 };
224
225 const waitUntilReady = (project: string, machineImageName: string) =>
226 getByName(project, machineImageName).pipe(
227 Effect.flatMap((image) =>
228 image?.status === "INVALID" || image?.status === "FAILED"
229 ? Effect.fail(
230 new MachineImageFailed({
231 machineImageName,
232 status: image.status ?? "INVALID",
233 }),
234 )
235 : Effect.succeed(image),
236 ),
237 Effect.filterOrFail(
238 (image): image is compute.MachineImage => image !== undefined && image.status === "READY",
239 (image) =>
240 new MachineImagePending({
241 machineImageName,
242 status: image?.status ?? "MISSING",
243 }),
244 ),
245 Effect.retry({
246 while: (error) => error._tag === "GCP.Compute.MachineImagePending",
247 times: 10,
248 schedule: Schedule.spaced("5 seconds"),
249 }),
250 );
251
252 const waitUntilGone = (project: string, machineImageName: string) =>
253 getByName(project, machineImageName).pipe(
254 Effect.flatMap((image) =>
255 image === undefined
256 ? Effect.void
257 : Effect.fail(
258 new MachineImageStillExists({
259 machineImageName,
260 status: image.status ?? "UNKNOWN",
261 }),
262 ),
263 ),
264 Effect.retry({
265 while: (error) => error._tag === "GCP.Compute.MachineImageStillExists",
266 times: 10,
267 schedule: Schedule.spaced("3 seconds"),
268 }),
269 );
270
271 const insertBody = (
272 machineImageName: string,
273 news: MachineImageProps,
274 labels: Record<string, string>,
275 ): compute.MachineImage => ({
276 name: machineImageName,
277 sourceInstance: news.sourceInstance,
278 description: news.description,
279 labels,
280 storageLocations: news.storageLocations,
281 guestFlush: news.guestFlush,
282 });
283
284 export const MachineImageProvider = () =>
285 Provider.succeed(MachineImage, {
286 stables: [
287 "machineImageName",
288 "machineImageId",
289 "project",
290 "selfLink",
291 "creationTimestamp",
292 "sourceInstance",
293 ],
294
295 diff: Effect.fn(function* ({ news, olds, output }) {
296 if (!isResolved(news)) return undefined;
297 const previousName = olds.machineImageName ?? output?.machineImageName;
298 const nextName = news.machineImageName ?? previousName;
299 const nameChanged =
300 previousName !== undefined && nextName !== undefined && previousName !== nextName;
301
302 const previousSource = canonicalizeSourceInstance(
303 olds.sourceInstance ?? output?.sourceInstance,
304 );
305 const nextSource = canonicalizeSourceInstance(news.sourceInstance);
306 const sourceChanged =
307 previousSource.length > 0 && nextSource.length > 0 && previousSource !== nextSource;
308
309 const previousDescription = olds.description ?? output?.description ?? "";
310 const nextDescription = news.description ?? "";
311 const descriptionChanged = previousDescription !== nextDescription;
312
313 const storageChanged =
314 news.storageLocations !== undefined &&
315 !sameStrings(news.storageLocations, olds.storageLocations ?? output?.storageLocations);
316
317 const replace = nameChanged || sourceChanged || descriptionChanged || storageChanged;
318
319 if (!replace) return undefined;
320 return {
321 action: "replace" as const,
322 deleteFirst:
323 previousName !== undefined && nextName !== undefined && nextName === previousName,
324 };
325 }),
326
327 read: Effect.fn(function* ({ id, olds, output }) {
328 const env = yield* GcpEnvironment.current;
329 const machineImageName = yield* toName(id, olds?.machineImageName, output?.machineImageName);
330 const existing = yield* getByName(env.project, machineImageName);
331 if (existing === undefined) return undefined;
332 const attrs = toAttrs(existing, env.project);
333 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
334 }),
335
336 list: () =>
337 Effect.gen(function* () {
338 const env = yield* GcpEnvironment.current;
339 return yield* compute.listMachineImages
340 .items({
341 project: env.project,
342 maxResults: 500,
343 filter: "labels.alchemy-id:*",
344 })
345 .pipe(
346 Stream.filter((image) =>
347 Object.keys(image.labels ?? {}).some((key) => key.startsWith("alchemy-")),
348 ),
349 Stream.map((image) => toAttrs(image, env.project)),
350 Stream.runCollect,
351 Effect.map((chunk) => Array.from(chunk)),
352 );
353 }),
354
355 reconcile: Effect.fn(function* ({ id, news, output }) {
356 const env = yield* GcpEnvironment.current;
357 const machineImageName = yield* toName(id, news.machineImageName, output?.machineImageName);
358 const desiredLabels = {
359 ...toLabels(news.labels),
360 ...(yield* createInternalLabels(id)),
361 };
362
363 let current = yield* getByName(env.project, machineImageName);
364 if (current?.status === "DELETING") {
365 yield* waitUntilGone(env.project, machineImageName);
366 current = undefined;
367 }
368
369 if (current === undefined) {
370 if (news.sourceInstance === undefined || news.sourceInstance.length === 0) {
371 return yield* new MachineImageSourceRequired({ machineImageName });
372 }
373 const inserted = yield* compute
374 .insertMachineImages({
375 project: env.project,
376 sourceInstance: news.sourceInstance,
377 body: insertBody(machineImageName, news, desiredLabels),
378 })
379 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
380 if (inserted !== undefined) {
381 yield* waitGlobalOperation(env.project, inserted, {
382 ignore: ["RESOURCE_ALREADY_EXISTS"],
383 });
384 }
385 current = yield* waitUntilReady(env.project, machineImageName);
386 }
387
388 if (current === undefined) {
389 return yield* new MachineImageNotResolved({ machineImageName });
390 }
391
392 if (current.status !== "READY") {
393 current = yield* waitUntilReady(env.project, machineImageName);
394 }
395
396 if (current === undefined) {
397 return yield* new MachineImageNotResolved({ machineImageName });
398 }
399
400 const observedLabels = tagRecord(current.labels);
401 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
402 if (upsert.length > 0 || removed.length > 0) {
403 yield* compute
404 .setLabelsMachineImages({
405 project: env.project,
406 resource: machineImageName,
407 body: {
408 labels: desiredLabels,
409 labelFingerprint: current.labelFingerprint,
410 },
411 })
412 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
413 current = (yield* getByName(env.project, machineImageName)) ?? current;
414 }
415
416 if (current === undefined) {
417 return yield* new MachineImageNotResolved({ machineImageName });
418 }
419
420 return toAttrs(current, env.project);
421 }),
422
423 delete: Effect.fn(function* ({ output }) {
424 const env = yield* GcpEnvironment.current;
425 const operation = yield* compute
426 .deleteMachineImages({
427 project: env.project,
428 machineImage: output.machineImageName,
429 })
430 .pipe(
431 Effect.catchTag("NotFound", () => Effect.undefined),
432 Effect.retry({
433 while: (error) => error._tag === "Conflict",
434 times: 8,
435 schedule: Schedule.spaced("2 seconds"),
436 }),
437 );
438 if (operation !== undefined) {
439 yield* waitGlobalOperation(env.project, operation, {
440 ignore: ["RESOURCE_NOT_FOUND"],
441 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
442 }
443 yield* waitUntilGone(env.project, output.machineImageName);
444 }),
445 });