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

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