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

main
ts 242 lines 8.46 KB
Raw
1 import * as baremetalsolution from "@distilled.cloud/gcp/baremetalsolution_v2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { hasAlchemyLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 createInternalLabels,
12 encodeOwnership,
13 hasOwnershipMarker,
14 listVolumeSnapshots,
15 normalizeLocation,
16 parseName,
17 parseOwnership,
18 replaceOnIdentity,
19 ResourceNotResolved,
20 volumeOf,
21 waitUntilGone,
22 } from "./internal.ts";
23
24 export type VolumesSnapshotProps = {
25 /**
26 * Parent boot volume. Full name
27 * `projects/{project}/locations/{location}/volumes/{volume}` or the
28 * volume id (combined with `location`). Immutable — changing it
29 * replaces the snapshot. Only boot volumes accept snapshots.
30 */
31 volume: string;
32 /**
33 * Region used when `volume` is a bare id. Immutable — changing it
34 * replaces the snapshot. `US-CENTRAL1` is accepted and normalized to
35 * `us-central1`.
36 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
37 */
38 location?: string;
39 /**
40 * Snapshot id (the `{snapshot}` segment of
41 * `{volume}/snapshots/{snapshot}`). If omitted, the API assigns an id.
42 * Immutable — changing it replaces the snapshot.
43 */
44 snapshotId?: string;
45 /**
46 * Human-readable description. Volume snapshots have no labels field, so
47 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
48 * from attributes.
49 */
50 description?: string;
51 };
52
53 export type VolumesSnapshot = Resource<
54 "GCP.BareMetalSolution.VolumesSnapshot",
55 VolumesSnapshotProps,
56 {
57 /** Full resource name. */
58 name: string;
59 /** Snapshot id (last path segment). */
60 snapshotId: string;
61 /** Parent volume resource name. */
62 volume: string;
63 /** Project id. */
64 project: string;
65 /** Location id. */
66 location: string;
67 /** User description with the Alchemy ownership prefix stripped. */
68 description: string | undefined;
69 /** Snapshot type (`AD_HOC` or `SCHEDULED`). */
70 type: string | undefined;
71 /** Backend-generated identifier. */
72 id: string | undefined;
73 /** RFC3339 creation timestamp. */
74 createTime: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Bare Metal Solution boot-volume snapshot — a point-in-time copy of a
82 * BMS boot volume.
83 *
84 * Snapshots have no labels field, so Alchemy stamps ownership into a
85 * `[alchemy …]` description prefix for `list` / nuke. The API does not
86 * expose an update method; description is set at create time. Changing
87 * `snapshotId`, `volume`, or `location` replaces the snapshot.
88 *
89 * Creating a snapshot requires an existing boot volume in a Bare Metal
90 * Solution environment. Non-boot volumes and unentitled accounts are
91 * rejected by the API (`ServiceDisabled` when the API is off).
92 *
93 * ### Creating a Volume Snapshot
94 * **Example:** Generated name
95 * ```typescript
96 * const snap = yield* GCP.BareMetalSolution.VolumesSnapshot("Nightly", {
97 * volume: volume.name,
98 * });
99 * ```
100 *
101 * **Example:** Description
102 * ```typescript
103 * const snap = yield* GCP.BareMetalSolution.VolumesSnapshot("Nightly", {
104 * volume: volume.name,
105 * description: "nightly boot snapshot",
106 * });
107 * ```
108 *
109 * @resource
110 * @category BareMetalSolution
111 */
112 export const VolumesSnapshot = Resource<VolumesSnapshot>("GCP.BareMetalSolution.VolumesSnapshot");
113
114 const resourceName = (volume: string, snapshotId: string) => `${volume}/snapshots/${snapshotId}`;
115
116 const toAttrs = (snapshot: baremetalsolution.VolumeSnapshot, project: string, region: string) => {
117 const name = snapshot.name ?? "";
118 const parsed = parseName(name, "snapshots", region);
119 const ownership = parseOwnership(snapshot.description);
120 return {
121 name,
122 snapshotId: parsed.id || snapshot.id || "",
123 volume: snapshot.storageVolume || parsed.parent,
124 project: parsed.project || project,
125 location: parsed.location,
126 description: ownership.text,
127 type: snapshot.type,
128 id: snapshot.id,
129 createTime: snapshot.createTime,
130 };
131 };
132
133 const getByName = (name: string) =>
134 Effect.gen(function* () {
135 if (name.length === 0 || name.includes("//")) {
136 return undefined;
137 }
138 return yield* baremetalsolution
139 .getProjectsLocationsVolumesSnapshots({ name })
140 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
141 });
142
143 export const VolumesSnapshotProvider = () =>
144 Provider.succeed(VolumesSnapshot, {
145 stables: ["name", "snapshotId", "volume", "project", "location", "id", "createTime"],
146
147 diff: Effect.fn(function* ({ news, olds, output }) {
148 if (!isResolved(news)) return undefined;
149 const env = yield* GcpEnvironment.current;
150 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
151 const nextLocation = normalizeLocation(
152 news.location ?? olds?.location ?? output?.location,
153 env.region,
154 );
155 const previousVolume = volumeOf(
156 olds?.volume ?? output?.volume ?? "",
157 env.project,
158 previousLocation,
159 );
160 const nextVolume = volumeOf(
161 news.volume ?? olds?.volume ?? output?.volume ?? "",
162 env.project,
163 nextLocation,
164 );
165 return replaceOnIdentity({
166 previousId: olds?.snapshotId ?? output?.snapshotId,
167 nextId: news.snapshotId ?? olds?.snapshotId ?? output?.snapshotId,
168 previousLocation,
169 nextLocation,
170 previousParent: previousVolume,
171 nextParent: nextVolume,
172 });
173 }),
174
175 read: Effect.fn(function* ({ id, olds, output }) {
176 const env = yield* GcpEnvironment.current;
177 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
178 const volumeHint = olds?.volume ?? output?.volume ?? "";
179 if (!output?.name && volumeHint.length === 0) return undefined;
180 const volume = volumeOf(volumeHint, env.project, location);
181 const snapshotId = olds?.snapshotId ?? output?.snapshotId;
182 const name =
183 output?.name ?? (snapshotId !== undefined ? resourceName(volume, snapshotId) : "");
184 if (name.length === 0) return undefined;
185 const existing = yield* getByName(name);
186 if (existing === undefined) return undefined;
187 const attrs = toAttrs(existing, env.project, env.region);
188 const { labels } = parseOwnership(existing.description);
189 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
190 }),
191
192 list: () =>
193 Effect.gen(function* () {
194 const env = yield* GcpEnvironment.current;
195 const items = yield* listVolumeSnapshots(env.project, env.region);
196 return items
197 .filter((item) => hasOwnershipMarker(item.description))
198 .map((item) => toAttrs(item, env.project, env.region));
199 }),
200
201 reconcile: Effect.fn(function* ({ id, news, output }) {
202 const env = yield* GcpEnvironment.current;
203 const locationHint = normalizeLocation(news.location ?? output?.location, env.region);
204 const volume = volumeOf(news.volume, env.project, locationHint);
205 const snapshotId = news.snapshotId ?? output?.snapshotId;
206 const name =
207 output?.name ?? (snapshotId !== undefined ? resourceName(volume, snapshotId) : "");
208 const ownership = yield* createInternalLabels(id);
209 const desiredDescription = encodeOwnership(ownership, news.description);
210
211 let current = yield* getByName(name);
212
213 if (current === undefined) {
214 const created = yield* baremetalsolution
215 .createProjectsLocationsVolumesSnapshots({
216 parent: volume,
217 body: {
218 name: name.length > 0 ? name : undefined,
219 description: desiredDescription,
220 },
221 })
222 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
223 current = created ?? undefined;
224 }
225
226 if (current === undefined) {
227 return yield* new ResourceNotResolved({
228 resourceName: name.length > 0 ? name : `${volume}/snapshots`,
229 });
230 }
231
232 return toAttrs(current, env.project, env.region);
233 }),
234
235 delete: Effect.fn(function* ({ output }) {
236 if (!output.name || output.name.includes("//")) return;
237 yield* baremetalsolution
238 .deleteProjectsLocationsVolumesSnapshots({ name: output.name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.void));
240 yield* waitUntilGone(getByName(output.name), output.name);
241 }),
242 });