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

main
ts 474 lines 15.1 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 { OperationFailed } from "../Operation.ts";
21 import type { Providers } from "../Providers.ts";
22 import { waitZoneOperation } from "./operations.ts";
23
24 const DEFAULT_ZONE = "us-central1-a";
25
26 export type InstantSnapshotProps = {
27 /**
28 * Instant snapshot name (RFC1035, 1-63 characters). If omitted, a unique
29 * name is generated from the stack, stage, and logical id. Changing the
30 * name replaces the snapshot.
31 */
32 instantSnapshotName?: string;
33 /**
34 * Zone of the snapshot and its source disk (e.g. `us-central1-a`).
35 * Immutable — changing it replaces the snapshot. Inferred from
36 * `sourceDisk` when omitted.
37 * @default "us-central1-a"
38 */
39 zone?: string;
40 /**
41 * Source disk URL or relative path
42 * (`projects/{project}/zones/{zone}/disks/{disk}`). Immutable —
43 * changing it replaces the snapshot.
44 */
45 sourceDisk: string;
46 /**
47 * Optional description. Immutable — changing it replaces the snapshot.
48 */
49 description?: string;
50 /**
51 * User labels. Alchemy ownership labels are merged in automatically
52 * and synced via `instantSnapshots.setLabels`.
53 */
54 labels?: Record<string, string>;
55 };
56
57 export type InstantSnapshot = Resource<
58 "GCP.Compute.InstantSnapshot",
59 InstantSnapshotProps,
60 {
61 /** Instant snapshot name. */
62 instantSnapshotName: string;
63 /** Server-assigned numeric id. */
64 instantSnapshotId: string | undefined;
65 /** Project id. */
66 project: string;
67 /** Zone short name (`us-central1-a`). */
68 zone: string;
69 /** Source disk URL. */
70 sourceDisk: string | undefined;
71 /** Server-assigned source disk id. */
72 sourceDiskId: string | undefined;
73 /** Optional description. */
74 description: string | undefined;
75 /** Server-reported status (`READY`, `CREATING`, …). */
76 status: string | undefined;
77 /** Size of the source disk in GB. */
78 diskSizeGb: string | undefined;
79 /** User labels (Alchemy ownership labels stripped). */
80 labels: Record<string, string>;
81 /** Compute Engine self-link. */
82 selfLink: string | undefined;
83 /** RFC3339 creation timestamp. */
84 creationTimestamp: string | undefined;
85 /** Architecture (`X86_64` or `ARM64`). */
86 architecture: string | undefined;
87 },
88 never,
89 Providers
90 >;
91
92 /**
93 * A zonal Compute Engine instant snapshot.
94 *
95 * Instant snapshots capture a disk's point-in-time state in the same zone
96 * (Hyperdisk and some persistent-disk types). Name, zone, source disk, and
97 * description are immutable — changing them replaces the snapshot. Labels
98 * update in place via `instantSnapshots.setLabels`.
99 *
100 * ### Creating an Instant Snapshot
101 * **Example:** Snapshot of a disk
102 * ```typescript
103 * const disk = yield* GCP.Compute.Disk("data", {
104 * zone: "us-central1-a",
105 * type: "pd-balanced",
106 * sizeGb: 10,
107 * });
108 * const snap = yield* GCP.Compute.InstantSnapshot("checkpoint", {
109 * sourceDisk: disk.selfLink,
110 * zone: disk.zone,
111 * });
112 * ```
113 *
114 * **Example:** Named snapshot with labels
115 * ```typescript
116 * const snap = yield* GCP.Compute.InstantSnapshot("checkpoint", {
117 * instantSnapshotName: "app-data-now",
118 * zone: "us-central1-a",
119 * sourceDisk: "zones/us-central1-a/disks/app-data",
120 * labels: { env: "prod" },
121 * });
122 * ```
123 *
124 * @resource
125 * @category Compute
126 */
127 export const InstantSnapshot = Resource<InstantSnapshot>("GCP.Compute.InstantSnapshot");
128
129 export class InstantSnapshotNotResolved extends Data.TaggedError(
130 "GCP.Compute.InstantSnapshotNotResolved",
131 )<{
132 instantSnapshotName: string;
133 zone: string;
134 }> {}
135
136 export class InstantSnapshotNotReady extends Data.TaggedError(
137 "GCP.Compute.InstantSnapshotNotReady",
138 )<{
139 instantSnapshotName: string;
140 status: string;
141 }> {}
142
143 export class InstantSnapshotFailed extends Data.TaggedError("GCP.Compute.InstantSnapshotFailed")<{
144 instantSnapshotName: string;
145 status: string;
146 }> {}
147
148 export class InstantSnapshotStillExists extends Data.TaggedError(
149 "GCP.Compute.InstantSnapshotStillExists",
150 )<{
151 instantSnapshotName: string;
152 status: string;
153 }> {}
154
155 const lastSegment = (value: string | undefined): string | undefined => {
156 if (value === undefined || value.length === 0) return undefined;
157 const parts = value.replace(/\/+$/, "").split("/");
158 return parts[parts.length - 1] || value;
159 };
160
161 const zoneFromDisk = (sourceDisk: string | undefined): string | undefined => {
162 if (!sourceDisk) return undefined;
163 const match = sourceDisk.match(/\/zones\/([^/]+)\//);
164 return match?.[1];
165 };
166
167 const canonicalizeSource = (source: string | undefined): string => {
168 if (source === undefined || source.length === 0) return "";
169 return lastSegment(source) ?? source;
170 };
171
172 const userLabels = (
173 labels: Record<string, string | undefined> | null | undefined,
174 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
175
176 const rfc1035 = (name: string): string => {
177 let next = name
178 .toLowerCase()
179 .replace(/[^a-z0-9-]/g, "-")
180 .replace(/-+/g, "-")
181 .replace(/^-+/, "")
182 .replace(/-+$/, "");
183 if (!/^[a-z]/.test(next)) {
184 next = `i${next}`;
185 }
186 next = next.slice(0, 63).replace(/-+$/, "");
187 return next.length > 0 ? next : "instantsnapshot";
188 };
189
190 const toName = (id: string, name: string | undefined, existing?: string) =>
191 Effect.gen(function* () {
192 if (name !== undefined) return name;
193 if (existing !== undefined) return existing;
194 return rfc1035(
195 yield* createPhysicalName({
196 id,
197 maxLength: 63,
198 lowercase: true,
199 }),
200 );
201 });
202
203 const toAttrs = (
204 snapshot: compute.InstantSnapshot,
205 project: string,
206 ): InstantSnapshot["Attributes"] => ({
207 instantSnapshotName: snapshot.name ?? snapshot.id ?? "",
208 instantSnapshotId: snapshot.id,
209 project,
210 zone: lastSegment(snapshot.zone) ?? DEFAULT_ZONE,
211 sourceDisk: snapshot.sourceDisk,
212 sourceDiskId: snapshot.sourceDiskId,
213 description: snapshot.description,
214 status: snapshot.status,
215 diskSizeGb: snapshot.diskSizeGb,
216 labels: userLabels(snapshot.labels),
217 selfLink: snapshot.selfLink,
218 creationTimestamp: snapshot.creationTimestamp,
219 architecture: snapshot.architecture,
220 });
221
222 const getByName = (project: string, zone: string, instantSnapshot: string) =>
223 compute
224 .getInstantSnapshots({ project, zone, instantSnapshot })
225 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
226
227 const waitReady = (project: string, zone: string, name: string) =>
228 getByName(project, zone, name).pipe(
229 Effect.flatMap((snapshot) =>
230 snapshot?.status === "FAILED"
231 ? Effect.fail(
232 new InstantSnapshotFailed({
233 instantSnapshotName: name,
234 status: "FAILED",
235 }),
236 )
237 : Effect.succeed(snapshot),
238 ),
239 Effect.filterOrFail(
240 (snapshot): snapshot is compute.InstantSnapshot =>
241 snapshot !== undefined && snapshot.status === "READY",
242 (snapshot) =>
243 new InstantSnapshotNotReady({
244 instantSnapshotName: name,
245 status: snapshot?.status ?? "MISSING",
246 }),
247 ),
248 Effect.retry({
249 while: (error) => error._tag === "GCP.Compute.InstantSnapshotNotReady",
250 times: 10,
251 schedule: Schedule.spaced("1 second"),
252 }),
253 );
254
255 const waitGone = (project: string, zone: string, name: string) =>
256 getByName(project, zone, name).pipe(
257 Effect.flatMap((snapshot) =>
258 snapshot === undefined
259 ? Effect.void
260 : Effect.fail(
261 new InstantSnapshotStillExists({
262 instantSnapshotName: name,
263 status: snapshot.status ?? "EXISTS",
264 }),
265 ),
266 ),
267 Effect.retry({
268 while: (error) => error._tag === "GCP.Compute.InstantSnapshotStillExists",
269 times: 10,
270 schedule: Schedule.spaced("2 seconds"),
271 }),
272 );
273
274 export const InstantSnapshotProvider = () =>
275 Provider.succeed(InstantSnapshot, {
276 stables: [
277 "instantSnapshotName",
278 "instantSnapshotId",
279 "project",
280 "zone",
281 "sourceDisk",
282 "sourceDiskId",
283 "selfLink",
284 "creationTimestamp",
285 ],
286
287 diff: Effect.fn(function* ({ news, olds, output }) {
288 if (!isResolved(news)) return undefined;
289 const previousName = olds?.instantSnapshotName ?? output?.instantSnapshotName;
290 const nextName = news.instantSnapshotName ?? previousName;
291 const previousZone = lastSegment(olds?.zone) ?? lastSegment(output?.zone) ?? DEFAULT_ZONE;
292 const nextZone = lastSegment(news.zone) ?? zoneFromDisk(news.sourceDisk) ?? previousZone;
293 const previousDisk = canonicalizeSource(olds?.sourceDisk ?? output?.sourceDisk);
294 const nextDisk = canonicalizeSource(news.sourceDisk);
295 const previousDescription = olds?.description ?? output?.description ?? "";
296 const nextDescription = news.description ?? "";
297
298 const replace =
299 (previousName !== undefined && nextName !== undefined && previousName !== nextName) ||
300 previousZone !== nextZone ||
301 (nextDisk.length > 0 && previousDisk.length > 0 && previousDisk !== nextDisk) ||
302 previousDescription !== nextDescription;
303
304 if (!replace) return undefined;
305 return {
306 action: "replace" as const,
307 deleteFirst:
308 previousName !== undefined &&
309 nextName !== undefined &&
310 previousName === nextName &&
311 previousZone === nextZone,
312 };
313 }),
314
315 read: Effect.fn(function* ({ id, olds, output }) {
316 const env = yield* GcpEnvironment.current;
317 const instantSnapshotName = yield* toName(
318 id,
319 olds?.instantSnapshotName,
320 output?.instantSnapshotName,
321 );
322 const zone =
323 lastSegment(olds?.zone) ??
324 lastSegment(output?.zone) ??
325 zoneFromDisk(olds?.sourceDisk ?? output?.sourceDisk) ??
326 DEFAULT_ZONE;
327 const existing = yield* getByName(env.project, zone, instantSnapshotName);
328 if (existing === undefined) return undefined;
329 const attrs = toAttrs(existing, env.project);
330 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
331 }),
332
333 list: () =>
334 Effect.gen(function* () {
335 const env = yield* GcpEnvironment.current;
336 const pages = yield* compute.aggregatedListInstantSnapshots
337 .pages({
338 project: env.project,
339 filter: "labels.alchemy-id:*",
340 returnPartialSuccess: true,
341 maxResults: 500,
342 })
343 .pipe(Stream.runCollect);
344 return Array.from(pages).flatMap((page) =>
345 Object.values(page.items ?? {}).flatMap((scoped) =>
346 (scoped?.instantSnapshots ?? [])
347 .filter((item) =>
348 Object.keys(item.labels ?? {}).some((key) => key.startsWith("alchemy-")),
349 )
350 .map((item) => toAttrs(item, env.project)),
351 ),
352 );
353 }),
354
355 reconcile: Effect.fn(function* ({ id, news, output }) {
356 const env = yield* GcpEnvironment.current;
357 const instantSnapshotName = yield* toName(
358 id,
359 news.instantSnapshotName,
360 output?.instantSnapshotName,
361 );
362 const zone =
363 lastSegment(news.zone) ??
364 lastSegment(output?.zone) ??
365 zoneFromDisk(news.sourceDisk) ??
366 DEFAULT_ZONE;
367 const desiredLabels = {
368 ...toLabels(news.labels),
369 ...(yield* createInternalLabels(id)),
370 };
371
372 let current = yield* getByName(env.project, zone, instantSnapshotName);
373 if (current?.status === "DELETING") {
374 yield* waitGone(env.project, zone, instantSnapshotName);
375 current = undefined;
376 }
377
378 if (current === undefined) {
379 // "The previous instant snapshot is too recent" — one instant snapshot
380 // per disk every 30 seconds.
381 const tooRecent = (error: { readonly _tag: string }) =>
382 error instanceof OperationFailed && error.reason === "UNSUPPORTED_OPERATION";
383 yield* compute
384 .insertInstantSnapshots({
385 project: env.project,
386 zone,
387 body: {
388 name: instantSnapshotName,
389 sourceDisk: news.sourceDisk,
390 description: news.description,
391 labels: desiredLabels,
392 },
393 })
394 .pipe(
395 Effect.catchTag("Conflict", () => Effect.undefined),
396 Effect.flatMap((inserted) =>
397 inserted === undefined
398 ? Effect.void
399 : waitZoneOperation(env.project, zone, inserted, {
400 ignore: ["RESOURCE_ALREADY_EXISTS"],
401 }),
402 ),
403 Effect.retry({
404 while: tooRecent,
405 times: 3,
406 schedule: Schedule.spaced("30 seconds"),
407 }),
408 );
409 current = yield* waitReady(env.project, zone, instantSnapshotName);
410 }
411
412 if (current === undefined) {
413 return yield* new InstantSnapshotNotResolved({
414 instantSnapshotName,
415 zone,
416 });
417 }
418
419 if (current.status !== "READY") {
420 current = yield* waitReady(env.project, zone, instantSnapshotName);
421 }
422
423 const observedLabels = tagRecord(current.labels);
424 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
425 if (upsert.length > 0 || removed.length > 0) {
426 const labeled = yield* compute.setLabelsInstantSnapshots({
427 project: env.project,
428 zone,
429 resource: instantSnapshotName,
430 body: {
431 labels: desiredLabels,
432 labelFingerprint: current.labelFingerprint,
433 },
434 });
435 yield* waitZoneOperation(env.project, zone, labeled);
436 current = yield* getByName(env.project, zone, instantSnapshotName);
437 }
438
439 if (current === undefined) {
440 return yield* new InstantSnapshotNotResolved({
441 instantSnapshotName,
442 zone,
443 });
444 }
445
446 return toAttrs(current, env.project);
447 }),
448
449 delete: Effect.fn(function* ({ output }) {
450 const env = yield* GcpEnvironment.current;
451 const project = output.project || env.project;
452 const zone = lastSegment(output.zone) ?? DEFAULT_ZONE;
453 const operation = yield* compute
454 .deleteInstantSnapshots({
455 project,
456 zone,
457 instantSnapshot: output.instantSnapshotName,
458 })
459 .pipe(
460 Effect.retry({
461 while: (error) => error._tag === "Conflict",
462 times: 8,
463 schedule: Schedule.spaced("2 seconds"),
464 }),
465 Effect.catchTag("NotFound", () => Effect.undefined),
466 );
467 if (operation !== undefined) {
468 yield* waitZoneOperation(project, zone, operation).pipe(
469 Effect.catchTag("NotFound", () => Effect.void),
470 );
471 }
472 yield* waitGone(project, zone, output.instantSnapshotName);
473 }),
474 });