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

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