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

main
ts 490 lines 16.8 KB
Raw
1 import * as apphub from "@distilled.cloud/gcp/apphub_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
9
10 export type Attributes = apphub.Attributes;
11 export type Scope = apphub.Scope;
12 export type ContactInfo = apphub.ContactInfo;
13 export type ServiceReference = apphub.ServiceReference;
14 export type ServiceProperties = apphub.ServiceProperties;
15 export type WorkloadReference = apphub.WorkloadReference;
16 export type WorkloadProperties = apphub.WorkloadProperties;
17
18 export const GLOBAL_LOCATION = "global";
19 export const MAX_NAME_LENGTH = 63;
20 export const MAX_DISPLAY_NAME_LENGTH = 63;
21 export const MAX_DESCRIPTION_LENGTH = 2048;
22
23 export class ResourceNotResolved extends Data.TaggedError("GCP.AppHub.ResourceNotResolved")<{
24 resourceName: string;
25 }> {}
26
27 export class ResourceStillExists extends Data.TaggedError("GCP.AppHub.ResourceStillExists")<{
28 resourceName: string;
29 }> {}
30
31 export class ResourceNotReady extends Data.TaggedError("GCP.AppHub.ResourceNotReady")<{
32 resourceName: string;
33 state: string;
34 }> {}
35
36 export class ResourceFailed extends Data.TaggedError("GCP.AppHub.ResourceFailed")<{
37 resourceName: string;
38 state: string;
39 }> {}
40
41 export const lastSegment = (value: string) => {
42 const trimmed = value.replace(/\/+$/, "");
43 const parts = trimmed.split("/");
44 return parts[parts.length - 1] || trimmed;
45 };
46
47 export const rfc1035 = (name: string, fallback = "apphub"): string => {
48 let next = name
49 .toLowerCase()
50 .replace(/[^a-z0-9-]/g, "-")
51 .replace(/-+/g, "-")
52 .replace(/^-+|-+$/g, "");
53 if (!/^[a-z]/.test(next)) next = `a${next}`;
54 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
55 if (next.length === 0) return fallback;
56 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
57 return next.slice(0, MAX_NAME_LENGTH);
58 };
59
60 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
61 lastSegment(location ?? defaultLocation).toLowerCase();
62
63 export const locationParent = (project: string, location: string) =>
64 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
65
66 export const toPhysicalId = (
67 id: string,
68 explicit: string | undefined,
69 existing: string | undefined,
70 fallback = "apphub",
71 ) =>
72 Effect.gen(function* () {
73 if (explicit !== undefined) return rfc1035(explicit, fallback);
74 if (existing !== undefined) return existing;
75 return rfc1035(
76 yield* createPhysicalName({
77 id,
78 maxLength: MAX_NAME_LENGTH,
79 lowercase: true,
80 }),
81 fallback,
82 );
83 });
84
85 export const parseName = (name: string, collection: string, defaultLocation: string) => {
86 const parts = name.split("/").filter((part) => part.length > 0);
87 const collectionAt = parts.lastIndexOf(collection);
88 const locationsAt = parts.lastIndexOf("locations");
89 const projectsAt = parts.lastIndexOf("projects");
90 const applicationsAt = parts.lastIndexOf("applications");
91 return {
92 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
93 location:
94 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
95 applicationId:
96 applicationsAt >= 0 && parts[applicationsAt + 1] ? parts[applicationsAt + 1]! : "",
97 application:
98 applicationsAt >= 0
99 ? parts.slice(0, applicationsAt + 2).join("/")
100 : parts.slice(0, Math.max(0, parts.length - 2)).join("/"),
101 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
102 parent:
103 collectionAt > 0
104 ? parts.slice(0, collectionAt).join("/")
105 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
106 };
107 };
108
109 export const expandApplication = (value: string, project: string, location: string) =>
110 value.includes("/applications/")
111 ? value.replace(/\/+$/, "")
112 : `${locationParent(project, location)}/applications/${value}`;
113
114 export const expandDiscovered = (
115 value: string,
116 project: string,
117 location: string,
118 collection: "discoveredServices" | "discoveredWorkloads",
119 ) => {
120 if (value.includes(`/${collection}/`)) return value.replace(/\/+$/, "");
121 if (value.includes("/") || value.startsWith("https://") || value.includes(".googleapis.com")) {
122 return value.replace(/\/+$/, "");
123 }
124 return `projects/${project}/locations/${location}/${collection}/${value}`;
125 };
126
127 export const isDiscoveredName = (
128 value: string,
129 collection: "discoveredServices" | "discoveredWorkloads",
130 ) => value.includes(`/${collection}/`);
131
132 export const projectNameOf = (value: string | undefined, project: string) => {
133 const next = (value ?? project).replace(/\/+$/, "");
134 if (next.startsWith("projects/")) return next;
135 return `projects/${next}`;
136 };
137
138 export const projectIdOf = (value: string | undefined, fallback: string) => {
139 if (value === undefined || value.length === 0) return fallback;
140 const parts = value.split("/").filter((part) => part.length > 0);
141 const at = parts.lastIndexOf("projects");
142 if (at >= 0 && parts[at + 1]) return parts[at + 1]!;
143 return lastSegment(value);
144 };
145
146 export const defaultScope = (location: string): Scope => ({
147 type: location === GLOBAL_LOCATION ? "GLOBAL" : "REGIONAL",
148 });
149
150 export const canonical = (value: unknown): unknown => {
151 if (value === undefined || value === null) return undefined;
152 if (typeof value === "boolean" || typeof value === "number") return value;
153 if (typeof value === "string") {
154 return value.length === 0 ? undefined : value;
155 }
156 if (Array.isArray(value)) {
157 const items = value.map(canonical).filter((item) => item !== undefined);
158 return items.length === 0 ? undefined : items;
159 }
160 if (typeof value === "object") {
161 const entries = Object.entries(value as Record<string, unknown>)
162 .map(([key, item]) => [key, canonical(item)] as const)
163 .filter(([, item]) => item !== undefined)
164 .sort(([left], [right]) => left.localeCompare(right));
165 if (entries.length === 0) return undefined;
166 return Object.fromEntries(entries);
167 }
168 return undefined;
169 };
170
171 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
172
173 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
174
175 export const sameText = (left: string | undefined, right: string | undefined) =>
176 (left ?? "") === (right ?? "");
177
178 export const fieldMask = (fields: Array<string | false | undefined>) =>
179 fields.filter((field): field is string => typeof field === "string").join(",");
180
181 export const replaceOnIdentity = (input: {
182 previousId: string | undefined;
183 nextId: string | undefined;
184 previousLocation: string;
185 nextLocation: string;
186 extra?: boolean;
187 previousParent?: string;
188 nextParent?: string;
189 }) => {
190 const parentChanged =
191 (input.previousParent ?? "") !== "" &&
192 (input.nextParent ?? "") !== "" &&
193 (input.previousParent ?? "") !== (input.nextParent ?? "");
194 const replace =
195 (input.extra ?? false) ||
196 parentChanged ||
197 (input.previousId !== undefined &&
198 input.nextId !== undefined &&
199 input.nextId !== input.previousId) ||
200 input.previousLocation !== input.nextLocation;
201 if (!replace) return undefined;
202 const samePhysical =
203 input.previousLocation === input.nextLocation &&
204 !parentChanged &&
205 input.previousId !== undefined &&
206 input.nextId === input.previousId;
207 return {
208 action: "replace" as const,
209 deleteFirst: samePhysical,
210 };
211 };
212
213 const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) =>
214 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
215
216 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
217 let stack = labels[alchemyLabelKeys.stack] ?? "x";
218 let stage = labels[alchemyLabelKeys.stage] ?? "x";
219 let id = labels[alchemyLabelKeys.id] ?? "x";
220 let marker = markerOf(labels, stack, stage, id);
221 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
222 if (stack.length >= stage.length && stack.length >= id.length) {
223 stack = stack.slice(0, -1);
224 } else if (stage.length >= id.length) {
225 stage = stage.slice(0, -1);
226 } else {
227 id = id.slice(0, -1);
228 }
229 marker = markerOf(labels, stack, stage, id);
230 }
231 return marker.length <= maxLength ? marker : marker.slice(0, maxLength);
232 };
233
234 export const encodeOwnership = (
235 labels: Record<string, string>,
236 text: string | undefined,
237 maxLength = MAX_DESCRIPTION_LENGTH,
238 ): string => {
239 const marker = fitMarker(labels, maxLength);
240 const trimmed = text?.trim();
241 if (!trimmed) return marker;
242 const combined = `${marker}\n${trimmed}`;
243 return combined.length <= maxLength ? combined : combined.slice(0, maxLength);
244 };
245
246 export const parseOwnership = (
247 text: string | undefined,
248 ): {
249 labels: Record<string, string>;
250 text: string | undefined;
251 } => {
252 if (!text?.includes("[alchemy ")) {
253 return { labels: {}, text };
254 }
255 const start = text.indexOf("[alchemy ");
256 const end = text.indexOf("]", start);
257 if (end < 0) return { labels: {}, text };
258 const labels: Record<string, string> = {};
259 for (const part of text.slice(start + "[alchemy ".length, end).split(/\s+/)) {
260 const eq = part.indexOf("=");
261 if (eq > 0) {
262 labels[part.slice(0, eq)] = part.slice(eq + 1);
263 }
264 }
265 const before = text.slice(0, start).trim();
266 const after = text.slice(end + 1).replace(/^[\s\n]+/, "");
267 const rest = [before, after].filter((part) => part.length > 0).join("\n");
268 return { labels, text: rest.length > 0 ? rest : undefined };
269 };
270
271 export const hasOwnershipMarker = (text: string | undefined) =>
272 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
273
274 const prefixMatch = (expected: string, observed: string) =>
275 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
276
277 export const ownedByAlchemy = (id: string, text: string | undefined) =>
278 Effect.gen(function* () {
279 const expected = yield* createInternalLabels(id);
280 const { labels } = parseOwnership(text);
281 if (!hasOwnershipMarker(text)) return false;
282 const exact = yield* hasAlchemyLabels(id, labels);
283 if (exact) return true;
284 return (
285 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
286 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
287 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
288 );
289 });
290
291 /** Wait for an operation through the shared GCP waiter. */
292 export const waitForOperation = (operation: apphub.Operation, options?: { notFoundOk?: boolean }) =>
293 waitForGcpOperation(
294 operation,
295 (name) =>
296 apphub
297 .getProjectsLocationsOperations({ name })
298 .pipe(
299 Effect.catchTag("NotFound", (error) =>
300 options?.notFoundOk === true
301 ? Effect.succeed<apphub.Operation>({ name, done: true })
302 : Effect.fail(error),
303 ),
304 ),
305 { budget: "10 minutes" },
306 ).pipe(
307 // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)
308 // is success for a delete.
309 Effect.catchIf(
310 (error) =>
311 error._tag === "GCP.OperationFailed" &&
312 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
313 () => Effect.void,
314 ),
315 );
316
317 export const waitUntilExists = <A, E, R>(
318 get: Effect.Effect<A | undefined, E, R>,
319 name: string,
320 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
321 get.pipe(
322 Effect.filterOrFail(
323 (value): value is NonNullable<A> => value !== undefined,
324 () => new ResourceNotResolved({ resourceName: name }),
325 ),
326 Effect.retry({
327 while: (error) => error instanceof ResourceNotResolved,
328 times: 8,
329 schedule: Schedule.spaced("1 second"),
330 }),
331 );
332
333 export const waitUntilGone = <A, E, R>(
334 get: Effect.Effect<A | undefined, E, R>,
335 name: string,
336 ): Effect.Effect<void, E | ResourceStillExists, R> =>
337 get.pipe(
338 Effect.flatMap((value) =>
339 value === undefined
340 ? Effect.void
341 : Effect.fail(new ResourceStillExists({ resourceName: name })),
342 ),
343 Effect.retry({
344 while: (error) => error instanceof ResourceStillExists,
345 times: 10,
346 schedule: Schedule.spaced("2 seconds"),
347 }),
348 );
349
350 const READY_STATES = new Set(["ACTIVE"]);
351 const FAILED_STATES = new Set(["FAILED", "ERROR"]);
352
353 export const waitUntilReady = <A, E, R>(
354 get: Effect.Effect<A | undefined, E, R>,
355 name: string,
356 stateOf: (value: NonNullable<A>) => string | undefined,
357 options?: {
358 times?: number;
359 interval?: `${number} seconds`;
360 },
361 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceNotReady | ResourceFailed, R> =>
362 get.pipe(
363 Effect.filterOrFail(
364 (value): value is NonNullable<A> => value !== undefined,
365 () => new ResourceNotResolved({ resourceName: name }),
366 ),
367 Effect.filterOrFail(
368 (value) => !FAILED_STATES.has((stateOf(value) ?? "").toUpperCase()),
369 (value) => new ResourceFailed({ resourceName: name, state: stateOf(value) ?? "" }),
370 ),
371 Effect.filterOrFail(
372 (value) => READY_STATES.has((stateOf(value) ?? "").toUpperCase()),
373 (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }),
374 ),
375 Effect.retry({
376 while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved,
377 times: options?.times ?? 10,
378 schedule: Schedule.spaced(options?.interval ?? "2 seconds"),
379 }),
380 );
381
382 export const collectPages = <Page, A, E, R>(
383 pages: Stream.Stream<Page, E, R>,
384 items: (page: Page) => readonly A[] | undefined,
385 ) =>
386 pages.pipe(
387 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
388 Stream.runCollect,
389 Effect.map((chunk) => Array.from(chunk)),
390 );
391
392 export const listOwnedPages = <Page, A, E, R>(
393 pages: Stream.Stream<Page, E, R>,
394 items: (page: Page) => readonly A[] | undefined,
395 textOf: (item: A) => string | undefined,
396 ) =>
397 pages.pipe(
398 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
399 Stream.filter((item) => hasOwnershipMarker(textOf(item))),
400 Stream.runCollect,
401 Effect.map((chunk) => Array.from(chunk)),
402 );
403
404 /** List at the regional and global locations (App Hub's two scopes). */
405 export const listAtLocations = <A, E, R>(
406 project: string,
407 region: string,
408 list: (parent: string) => Effect.Effect<A[], E, R>,
409 ): Effect.Effect<A[], E, R> =>
410 Effect.all(
411 [
412 list(`projects/${project}/locations/${region}`),
413 list(`projects/${project}/locations/${GLOBAL_LOCATION}`),
414 ],
415 { concurrency: 2 },
416 ).pipe(Effect.map(([regional, global]) => [...regional, ...global]));
417
418 export const listAllApplications = (project: string, region: string) =>
419 listAtLocations(project, region, (parent) =>
420 collectPages(
421 apphub.listProjectsLocationsApplications.pages({
422 parent,
423 pageSize: 1000,
424 }),
425 (page) => page.applications,
426 ),
427 );
428
429 export const listNestedOwned = <A, E, R>(
430 project: string,
431 region: string,
432 listChildren: (applicationName: string) => Effect.Effect<A[], E, R>,
433 ) =>
434 Effect.gen(function* () {
435 const apps = yield* listAllApplications(project, region);
436 const groups = yield* Effect.forEach(
437 apps,
438 (app) => {
439 const name = app.name ?? "";
440 if (name.length === 0) return Effect.succeed([] as A[]);
441 return listChildren(name);
442 },
443 { concurrency: 4 },
444 );
445 return groups.flat();
446 });
447
448 export const resolveDiscoveredService = (
449 parent: string,
450 value: string,
451 project: string,
452 location: string,
453 ) =>
454 Effect.gen(function* () {
455 const expanded = expandDiscovered(value, project, location, "discoveredServices");
456 if (isDiscoveredName(expanded, "discoveredServices")) return expanded;
457 const looked = yield* apphub
458 .lookupProjectsLocationsDiscoveredServices({
459 parent,
460 uri: expanded,
461 })
462 .pipe(
463 Effect.catchTag("NotFound", () =>
464 Effect.succeed<apphub.LookupDiscoveredServiceResponse>({}),
465 ),
466 );
467 return looked.discoveredService?.name ?? expanded;
468 });
469
470 export const resolveDiscoveredWorkload = (
471 parent: string,
472 value: string,
473 project: string,
474 location: string,
475 ) =>
476 Effect.gen(function* () {
477 const expanded = expandDiscovered(value, project, location, "discoveredWorkloads");
478 if (isDiscoveredName(expanded, "discoveredWorkloads")) return expanded;
479 const looked = yield* apphub
480 .lookupProjectsLocationsDiscoveredWorkloads({
481 parent,
482 uri: expanded,
483 })
484 .pipe(
485 Effect.catchTag("NotFound", () =>
486 Effect.succeed<apphub.LookupDiscoveredWorkloadResponse>({}),
487 ),
488 );
489 return looked.discoveredWorkload?.name ?? expanded;
490 });