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

main
ts 352 lines 12.2 KB
Raw
1 import * as vm from "@distilled.cloud/gcp/vmmigration_v1";
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 } from "../Labels.ts";
14 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
15
16 export const GLOBAL_LOCATION = "global";
17 export const MAX_NAME_LENGTH = 63;
18 export const MAX_DISPLAY_NAME_LENGTH = 63;
19
20 export class ResourceNotResolved extends Data.TaggedError("GCP.VMMigration.ResourceNotResolved")<{
21 resourceName: string;
22 }> {}
23
24 export class ResourceStillExists extends Data.TaggedError("GCP.VMMigration.ResourceStillExists")<{
25 resourceName: string;
26 }> {}
27
28 export const lastSegment = (value: string) => {
29 const trimmed = value.replace(/\/+$/, "");
30 const parts = trimmed.split("/");
31 return parts[parts.length - 1] || trimmed;
32 };
33
34 export const rfc1035 = (name: string, fallback = "vm"): string => {
35 let next = name
36 .toLowerCase()
37 .replace(/[^a-z0-9-]/g, "-")
38 .replace(/-+/g, "-")
39 .replace(/^-+|-+$/g, "");
40 if (!/^[a-z]/.test(next)) next = `v${next}`;
41 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
42 if (next.length === 0) return fallback;
43 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
44 return next.slice(0, MAX_NAME_LENGTH);
45 };
46
47 export const normalizeLocation = (location: string | undefined, fallback: string) =>
48 lastSegment(location ?? fallback).toLowerCase();
49
50 export const locationParent = (project: string, location: string) =>
51 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
52
53 export const globalParent = (project: string) => `projects/${project}/locations/${GLOBAL_LOCATION}`;
54
55 export const parentOfName = (name: string) => {
56 const parts = name.split("/").filter((part) => part.length > 0);
57 return parts.slice(0, -2).join("/");
58 };
59
60 export const toPhysicalId = (
61 id: string,
62 explicit: string | undefined,
63 existing: string | undefined,
64 fallback = "vm",
65 ) =>
66 Effect.gen(function* () {
67 if (explicit !== undefined) return rfc1035(explicit, fallback);
68 if (existing !== undefined) return existing;
69 return rfc1035(
70 yield* createPhysicalName({
71 id,
72 maxLength: MAX_NAME_LENGTH,
73 lowercase: true,
74 }),
75 fallback,
76 );
77 });
78
79 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
80 const parts = name.split("/").filter((part) => part.length > 0);
81 const collectionAt = parts.lastIndexOf(collection);
82 const locationsAt = parts.lastIndexOf("locations");
83 const projectsAt = parts.lastIndexOf("projects");
84 return {
85 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
86 location:
87 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
88 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
89 parent:
90 collectionAt > 0
91 ? parts.slice(0, collectionAt).join("/")
92 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
93 };
94 };
95
96 export const expandParent = (
97 value: string,
98 project: string,
99 location: string,
100 collection: string,
101 ) => {
102 if (value.includes("/")) return value.replace(/\/+$/, "");
103 return `projects/${project}/locations/${location}/${collection}/${value}`;
104 };
105
106 export const sourceOf = (value: string, project: string, location: string) =>
107 expandParent(value, project, location, "sources");
108
109 export const userLabels = (
110 labels: Record<string, string | undefined> | null | undefined,
111 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
112
113 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
114 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
115
116 export const canonical = (value: unknown): unknown => {
117 if (value === undefined || value === null) return undefined;
118 if (typeof value === "boolean" || typeof value === "number") return value;
119 if (typeof value === "string") {
120 return value.length === 0 ? undefined : value;
121 }
122 if (Array.isArray(value)) {
123 const items = value.map(canonical).filter((item) => item !== undefined);
124 return items.length === 0 ? undefined : items;
125 }
126 if (typeof value === "object") {
127 const entries = Object.entries(value as Record<string, unknown>)
128 .map(([key, item]) => [key, canonical(item)] as const)
129 .filter(([, item]) => item !== undefined)
130 .sort(([left], [right]) => left.localeCompare(right));
131 if (entries.length === 0) return undefined;
132 return Object.fromEntries(entries);
133 }
134 return undefined;
135 };
136
137 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
138
139 export const fieldMask = (fields: Array<string | false | undefined>) =>
140 fields.filter((field): field is string => typeof field === "string").join(",");
141
142 export const replaceOnIdentity = (input: {
143 previousId: string | undefined;
144 nextId: string | undefined;
145 previousLocation: string;
146 nextLocation: string;
147 extra?: boolean;
148 previousParent?: string;
149 nextParent?: string;
150 }) => {
151 const parentChanged =
152 (input.previousParent ?? "") !== "" &&
153 (input.nextParent ?? "") !== "" &&
154 (input.previousParent ?? "") !== (input.nextParent ?? "");
155 const replace =
156 (input.extra ?? false) ||
157 parentChanged ||
158 (input.previousId !== undefined &&
159 input.nextId !== undefined &&
160 input.nextId !== input.previousId) ||
161 input.previousLocation !== input.nextLocation;
162 if (!replace) return undefined;
163 const samePhysical =
164 input.previousLocation === input.nextLocation &&
165 !parentChanged &&
166 input.previousId !== undefined &&
167 input.nextId === input.previousId;
168 return {
169 action: "replace" as const,
170 deleteFirst: samePhysical,
171 };
172 };
173
174 /**
175 * Wait for a Migrate to Virtual Machines long-running operation. Sources, groups, and utilization reports settle in minutes; migrating-VM and image-import operations take longer.
176 */
177 export const waitForOperation = (operation: vm.Operation) =>
178 waitForGcpOperation(operation, (name) => vm.getProjectsLocationsOperations({ name }), {
179 budget: "20 minutes",
180 });
181
182 export const waitUntilExists = <A, E, R>(
183 get: Effect.Effect<A | undefined, E, R>,
184 name: string,
185 ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> =>
186 get.pipe(
187 Effect.filterOrFail(
188 (value): value is Exclude<A, undefined> => value !== undefined,
189 () => new ResourceNotResolved({ resourceName: name }),
190 ),
191 Effect.retry({
192 while: (error) => error instanceof ResourceNotResolved,
193 times: 8,
194 schedule: Schedule.spaced("1 second"),
195 }),
196 );
197
198 export const waitUntilGone = <A, E, R>(
199 get: Effect.Effect<A | undefined, E, R>,
200 name: string,
201 ): Effect.Effect<void, E | ResourceStillExists, R> =>
202 get.pipe(
203 Effect.filterOrFail(
204 (value) => value === undefined,
205 () => new ResourceStillExists({ resourceName: name }),
206 ),
207 Effect.asVoid,
208 Effect.retry({
209 while: (error) => error instanceof ResourceStillExists,
210 times: 10,
211 schedule: Schedule.spaced("4 seconds"),
212 }),
213 );
214
215 export const collectPages = <Page, A, E, R>(
216 pages: Stream.Stream<Page, E, R>,
217 items: (page: Page) => readonly A[] | undefined,
218 ) =>
219 pages.pipe(
220 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
221 Stream.runCollect,
222 Effect.map((chunk) => Array.from(chunk)),
223 );
224
225 /** List across `locations/-`, falling back to the region if the wildcard 404s. */
226 export const listAtLocation = <A, E extends { readonly _tag: string }, R>(
227 project: string,
228 region: string,
229 list: (parent: string) => Effect.Effect<A[], E, R>,
230 ) =>
231 list(`projects/${project}/locations/-`).pipe(
232 Effect.catchIf(
233 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
234 () => list(`projects/${project}/locations/${region}`),
235 ),
236 );
237
238 export const listSources = (project: string, region: string) =>
239 collectPages(
240 vm.listProjectsLocationsSources.pages({
241 parent: `projects/${project}/locations/-`,
242 pageSize: 1000,
243 }),
244 (page) => page.sources,
245 ).pipe(
246 Effect.catchTag("NotFound", () =>
247 collectPages(
248 vm.listProjectsLocationsSources.pages({
249 parent: locationParent(project, region),
250 pageSize: 1000,
251 }),
252 (page) => page.sources,
253 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as vm.Source[]))),
254 ),
255 );
256
257 export const forEachSource = <A, E, R>(
258 project: string,
259 list: (parent: string) => Effect.Effect<A[], E, R>,
260 region: string,
261 ) =>
262 Effect.gen(function* () {
263 const sources = yield* listSources(project, region);
264 const named = sources.filter((source) => (source.name ?? "").length > 0);
265 const groups = yield* Effect.forEach(named, (source) => list(source.name!), { concurrency: 4 });
266 return groups.flat();
267 });
268
269 const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) =>
270 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
271
272 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
273 let stack = labels[alchemyLabelKeys.stack] ?? "x";
274 let stage = labels[alchemyLabelKeys.stage] ?? "x";
275 let id = labels[alchemyLabelKeys.id] ?? "x";
276 let marker = markerOf(labels, stack, stage, id);
277 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
278 if (stack.length >= stage.length && stack.length >= id.length) {
279 stack = stack.slice(0, -1);
280 } else if (stage.length >= id.length) {
281 stage = stage.slice(0, -1);
282 } else {
283 id = id.slice(0, -1);
284 }
285 marker = markerOf(labels, stack, stage, id);
286 }
287 return marker.slice(0, maxLength);
288 };
289
290 export const encodeOwnership = (
291 labels: Record<string, string>,
292 text: string | undefined,
293 ): string => {
294 const marker = fitMarker(labels, 8000);
295 const trimmed = text?.trim();
296 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
297 };
298
299 export const encodeOwnershipLine = (
300 labels: Record<string, string>,
301 text: string | undefined,
302 maxLength = MAX_DISPLAY_NAME_LENGTH,
303 ): string => {
304 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
305 if (!trimmed) return fitMarker(labels, maxLength);
306 const minMarker = 24;
307 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
308 const marker = fitMarker(labels, maxLength - reserved);
309 return `${marker} ${trimmed}`.slice(0, maxLength);
310 };
311
312 export const parseOwnership = (
313 text: string | undefined,
314 ): {
315 labels: Record<string, string>;
316 text: string | undefined;
317 } => {
318 if (!text?.startsWith("[alchemy ")) {
319 return { labels: {}, text };
320 }
321 const end = text.indexOf("]");
322 if (end < 0) return { labels: {}, text };
323 const labels: Record<string, string> = {};
324 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
325 const eq = part.indexOf("=");
326 if (eq > 0) {
327 labels[part.slice(0, eq)] = part.slice(eq + 1);
328 }
329 }
330 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
331 return { labels, text: rest.length > 0 ? rest : undefined };
332 };
333
334 export const hasOwnershipMarker = (text: string | undefined) =>
335 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
336
337 const prefixMatch = (expected: string, observed: string) =>
338 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
339
340 export const ownedByAlchemy = (id: string, text: string | undefined) =>
341 Effect.gen(function* () {
342 const expected = yield* createInternalLabels(id);
343 const { labels } = parseOwnership(text);
344 if (!hasOwnershipMarker(text)) return false;
345 const exact = yield* hasAlchemyLabels(id, labels);
346 if (exact) return true;
347 return (
348 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
349 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
350 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
351 );
352 });