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

main
ts 443 lines 14.5 KB
Raw
1 import * as baremetalsolution from "@distilled.cloud/gcp/baremetalsolution_v2";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import { tagRecord } from "alchemy/Tags";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Stream from "effect/Stream";
8 import {
9 alchemyLabelKeys,
10 createInternalLabels,
11 hasAlchemyLabels,
12 stripInternalLabels,
13 toLabels,
14 } from "../Labels.ts";
15 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
16
17 export const MAX_NAME_LENGTH = 63;
18 export const DEFAULT_SIZE_GIB = "100";
19 export const DEFAULT_STORAGE_TYPE = "SSD";
20
21 export { createInternalLabels, hasAlchemyLabels, stripInternalLabels, toLabels };
22
23 export class ResourceNotResolved extends Data.TaggedError(
24 "GCP.BareMetalSolution.ResourceNotResolved",
25 )<{
26 resourceName: string;
27 }> {}
28
29 export class ResourceStillExists extends Data.TaggedError(
30 "GCP.BareMetalSolution.ResourceStillExists",
31 )<{
32 resourceName: string;
33 }> {}
34
35 export class ResourceNotReady extends Data.TaggedError("GCP.BareMetalSolution.ResourceNotReady")<{
36 resourceName: string;
37 state: string;
38 }> {}
39
40 export class ResourceFailed extends Data.TaggedError("GCP.BareMetalSolution.ResourceFailed")<{
41 resourceName: string;
42 state: string;
43 details: string | undefined;
44 }> {}
45
46 export const lastSegment = (value: string) => {
47 const trimmed = value.replace(/\/+$/, "");
48 const parts = trimmed.split("/");
49 return parts[parts.length - 1] || trimmed;
50 };
51
52 export const rfc1035 = (name: string, fallback = "baremetal"): string => {
53 let next = name
54 .toLowerCase()
55 .replace(/[^a-z0-9-]/g, "-")
56 .replace(/-+/g, "-")
57 .replace(/^-+|-+$/g, "");
58 if (!/^[a-z]/.test(next)) next = `b${next}`;
59 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
60 if (next.length === 0) return fallback;
61 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
62 if (next.length < 3) next = `${next}xxx`.slice(0, 3);
63 return next.slice(0, MAX_NAME_LENGTH);
64 };
65
66 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
67 lastSegment(location ?? defaultLocation).toLowerCase();
68
69 export const parentOf = (project: string, location: string) =>
70 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
71
72 export const toPhysicalId = (
73 id: string,
74 explicit: string | undefined,
75 existing: string | undefined,
76 fallback = "baremetal",
77 ) =>
78 Effect.gen(function* () {
79 if (explicit !== undefined) return rfc1035(explicit, fallback);
80 if (existing !== undefined) return existing;
81 return rfc1035(
82 yield* createPhysicalName({
83 id,
84 maxLength: MAX_NAME_LENGTH,
85 lowercase: true,
86 }),
87 fallback,
88 );
89 });
90
91 export const parseName = (name: string, collection: string, defaultLocation: string) => {
92 const parts = name.split("/").filter((part) => part.length > 0);
93 const collectionAt = parts.lastIndexOf(collection);
94 const locationsAt = parts.lastIndexOf("locations");
95 const projectsAt = parts.lastIndexOf("projects");
96 return {
97 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
98 location:
99 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
100 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
101 parent:
102 collectionAt > 0
103 ? parts.slice(0, collectionAt).join("/")
104 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
105 };
106 };
107
108 export const expandParent = (
109 value: string,
110 project: string,
111 location: string,
112 collection: string,
113 ) => {
114 if (value.includes("/")) return value.replace(/\/+$/, "");
115 return `projects/${project}/locations/${location}/${collection}/${rfc1035(value, collection)}`;
116 };
117
118 export const volumeOf = (value: string, project: string, location: string) =>
119 expandParent(value, project, location, "volumes");
120
121 export const networkOf = (value: string, project: string, location: string) => {
122 const next = value.replace(/\/+$/, "");
123 if (next.includes("/")) return next;
124 return `projects/${project}/locations/${location}/networks/${rfc1035(next, "network")}`;
125 };
126
127 export const gibOf = (value: number | string | undefined): string | undefined =>
128 value === undefined ? undefined : String(value);
129
130 export const userLabels = (
131 labels: Record<string, string | undefined> | null | undefined,
132 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
133
134 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
135 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
136
137 export const encodeOwnership = (
138 labels: Record<string, string>,
139 text: string | undefined,
140 ): string => {
141 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
142 const trimmed = text?.trim();
143 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
144 };
145
146 export const parseOwnership = (
147 text: string | undefined,
148 ): {
149 labels: Record<string, string>;
150 text: string | undefined;
151 } => {
152 if (!text?.startsWith("[alchemy ")) {
153 return { labels: {}, text };
154 }
155 const end = text.indexOf("]");
156 if (end < 0) return { labels: {}, text };
157 const labels: Record<string, string> = {};
158 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
159 const eq = part.indexOf("=");
160 if (eq > 0) {
161 labels[part.slice(0, eq)] = part.slice(eq + 1);
162 }
163 }
164 const rest = text.slice(end + 1).replace(/^\s+/, "");
165 return { labels, text: rest.length > 0 ? rest : undefined };
166 };
167
168 export const hasOwnershipMarker = (text: string | undefined) =>
169 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
170
171 export const canonical = (value: unknown): unknown => {
172 if (value === undefined || value === null) return undefined;
173 if (typeof value === "boolean" || typeof value === "number") return value;
174 if (typeof value === "string") {
175 return value.length === 0 ? undefined : value;
176 }
177 if (Array.isArray(value)) {
178 const items = value.map(canonical).filter((item) => item !== undefined);
179 return items.length === 0 ? undefined : items;
180 }
181 if (typeof value === "object") {
182 const entries = Object.entries(value as Record<string, unknown>)
183 .map(([key, item]) => [key, canonical(item)] as const)
184 .filter(([, item]) => item !== undefined)
185 .sort(([left], [right]) => left.localeCompare(right));
186 if (entries.length === 0) return undefined;
187 return Object.fromEntries(entries);
188 }
189 return undefined;
190 };
191
192 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
193
194 const pickDefined = (observed: unknown, desired: unknown): unknown => {
195 if (desired === undefined || desired === null) return undefined;
196 if (Array.isArray(desired)) {
197 if (!Array.isArray(observed)) return observed;
198 return desired.map((item, index) => pickDefined(observed[index], item));
199 }
200 if (typeof desired === "object") {
201 if (typeof observed !== "object" || observed === null) return observed;
202 const rec = observed as Record<string, unknown>;
203 return Object.fromEntries(
204 Object.entries(desired as Record<string, unknown>).map(([key, item]) => [
205 key,
206 pickDefined(rec[key], item),
207 ]),
208 );
209 }
210 return observed;
211 };
212
213 export const differs = (observed: unknown, desired: unknown): boolean => {
214 if (desired === undefined) return false;
215 return fingerprint(pickDefined(observed, desired)) !== fingerprint(desired);
216 };
217
218 export const fieldMask = (fields: Array<string | false | undefined>) =>
219 fields.filter((field): field is string => typeof field === "string").join(",");
220
221 export const sameText = (left: string | undefined, right: string | undefined) =>
222 (left ?? "") === (right ?? "");
223
224 export const replaceOnIdentity = (input: {
225 previousId: string | undefined;
226 nextId: string | undefined;
227 previousLocation: string;
228 nextLocation: string;
229 extra?: boolean;
230 previousParent?: string;
231 nextParent?: string;
232 }) => {
233 const parentChanged =
234 (input.previousParent ?? "") !== "" &&
235 (input.nextParent ?? "") !== "" &&
236 (input.previousParent ?? "") !== (input.nextParent ?? "");
237 const replace =
238 (input.extra ?? false) ||
239 parentChanged ||
240 (input.previousId !== undefined &&
241 input.nextId !== undefined &&
242 input.nextId !== input.previousId) ||
243 input.previousLocation !== input.nextLocation;
244 if (!replace) return undefined;
245 const samePhysical =
246 input.previousLocation === input.nextLocation &&
247 !parentChanged &&
248 input.previousId !== undefined &&
249 input.nextId === input.previousId;
250 return {
251 action: "replace" as const,
252 deleteFirst: samePhysical,
253 };
254 };
255
256 const READY_STATES = new Set(["PROVISIONED", "READY"]);
257 const FAILED_STATES = new Set(["ERROR", "FAILED"]);
258
259 export const isReadyState = (state: string | undefined) =>
260 READY_STATES.has((state ?? "").toUpperCase());
261
262 export const isFailedState = (state: string | undefined) =>
263 FAILED_STATES.has((state ?? "").toUpperCase());
264
265 export const isDeletingState = (state: string | undefined) =>
266 (state ?? "").toUpperCase() === "DELETING";
267
268 /**
269 * Wait for a Bare Metal Solution operation. NFS shares and volumes take
270 * several minutes to provision. An operation that finished with
271 * `ALREADY_EXISTS` (6) is a lost create race; `notFoundOk` also accepts
272 * `NOT_FOUND` (5).
273 */
274 export const waitForOperation = (
275 operation: baremetalsolution.Operation,
276 options?: { notFoundOk?: boolean },
277 ) =>
278 waitForGcpOperation(
279 operation,
280 (name) =>
281 baremetalsolution.getProjectsLocationsOperations({ name }).pipe(
282 Effect.catchTag("NotFound", (error) =>
283 options?.notFoundOk === true
284 ? Effect.succeed<baremetalsolution.Operation>({
285 name,
286 done: true,
287 })
288 : Effect.fail(error),
289 ),
290 ),
291 { budget: "30 minutes" },
292 ).pipe(
293 Effect.catchIf(
294 (error) =>
295 error._tag === "GCP.OperationFailed" &&
296 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
297 () => Effect.void,
298 ),
299 Effect.asVoid,
300 );
301
302 export const waitUntilExists = <A, E, R>(
303 get: Effect.Effect<A, E, R>,
304 name: string,
305 ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> =>
306 get.pipe(
307 Effect.filterOrFail(
308 (value): value is Exclude<A, undefined> => value !== undefined,
309 () => new ResourceNotResolved({ resourceName: name }),
310 ),
311 Effect.retry({
312 while: (error) => error instanceof ResourceNotResolved,
313 times: 8,
314 schedule: Schedule.spaced("1 second"),
315 }),
316 );
317
318 export const waitUntilGone = <A, E, R>(
319 get: Effect.Effect<A, E, R>,
320 name: string,
321 ): Effect.Effect<void, E | ResourceStillExists, R> =>
322 get.pipe(
323 Effect.filterOrFail(
324 (value) => value === undefined,
325 () => new ResourceStillExists({ resourceName: name }),
326 ),
327 Effect.asVoid,
328 Effect.retry({
329 while: (error) => error instanceof ResourceStillExists,
330 times: 10,
331 schedule: Schedule.spaced("2 seconds"),
332 }),
333 );
334
335 export const waitUntilReady = <A, E, R>(
336 get: Effect.Effect<A, E, R>,
337 name: string,
338 stateOf: (value: Exclude<A, undefined>) => string | undefined,
339 detailsOf?: (value: Exclude<A, undefined>) => string | undefined,
340 options?: {
341 times?: number;
342 interval?: `${number} seconds`;
343 },
344 ): Effect.Effect<
345 Exclude<A, undefined>,
346 E | ResourceNotResolved | ResourceNotReady | ResourceFailed,
347 R
348 > =>
349 get.pipe(
350 Effect.filterOrFail(
351 (value): value is Exclude<A, undefined> => value !== undefined,
352 () => new ResourceNotResolved({ resourceName: name }),
353 ),
354 Effect.filterOrFail(
355 (value) => !isFailedState(stateOf(value)),
356 (value) =>
357 new ResourceFailed({
358 resourceName: name,
359 state: stateOf(value) ?? "",
360 details: detailsOf?.(value),
361 }),
362 ),
363 Effect.filterOrFail(
364 (value) => {
365 const state = stateOf(value) ?? "";
366 return isReadyState(state) || state.length === 0;
367 },
368 (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }),
369 ),
370 Effect.retry({
371 while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved,
372 times: options?.times ?? 10,
373 schedule: Schedule.spaced(options?.interval ?? "5 seconds"),
374 }),
375 );
376
377 export const collectPages = <Page, A, E, R>(
378 pages: Stream.Stream<Page, E, R>,
379 items: (page: Page) => readonly A[] | undefined,
380 ): Effect.Effect<A[], E, R> =>
381 pages.pipe(
382 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
383 Stream.runCollect,
384 Effect.map((chunk) => Array.from(chunk)),
385 );
386
387 export const listAtLocation = <A, E extends { readonly _tag: string }, R>(
388 project: string,
389 region: string,
390 list: (parent: string) => Effect.Effect<A[], E, R>,
391 ) =>
392 list(`projects/${project}/locations/${region}`).pipe(
393 Effect.catchIf(
394 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
395 (): Effect.Effect<A[]> => Effect.succeed([]),
396 ),
397 );
398
399 export const listLabeledPages = <Page, A, E, R>(
400 pages: Stream.Stream<Page, E, R>,
401 items: (page: Page) => readonly A[] | undefined,
402 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
403 ): Effect.Effect<A[], E, R> =>
404 pages.pipe(
405 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
406 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
407 Stream.runCollect,
408 Effect.map((chunk) => Array.from(chunk)),
409 );
410
411 export const listVolumes = (project: string, region: string) =>
412 listAtLocation(project, region, (parent) =>
413 collectPages(
414 baremetalsolution.listProjectsLocationsVolumes.pages({
415 parent,
416 pageSize: 1000,
417 }),
418 (page) => page.volumes,
419 ),
420 );
421
422 export const listVolumeSnapshots = (project: string, region: string) =>
423 listVolumes(project, region).pipe(
424 Effect.flatMap((volumes) =>
425 Effect.forEach(
426 volumes.filter((volume) => (volume.name ?? "").length > 0),
427 (volume) =>
428 collectPages(
429 baremetalsolution.listProjectsLocationsVolumesSnapshots.pages({
430 parent: volume.name ?? "",
431 pageSize: 1000,
432 }),
433 (page) => page.volumeSnapshots,
434 ).pipe(
435 Effect.catchTag("NotFound", () =>
436 Effect.succeed([] as baremetalsolution.VolumeSnapshot[]),
437 ),
438 ),
439 { concurrency: 4 },
440 ),
441 ),
442 Effect.map((groups) => groups.flat()),
443 );