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

main
ts 416 lines 14.3 KB
Raw
1 import * as beyondcorp from "@distilled.cloud/gcp/beyondcorp_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 waitForLongRunning, type LongRunningOperation } from "../Operation.ts";
15
16 export const DEFAULT_GLOBAL = "global";
17 export const MAX_NAME_LENGTH = 63;
18 export const MAX_DISPLAY_NAME_LENGTH = 64;
19 export const DEFAULT_CONNECTION_TYPE = "TCP_PROXY";
20 export const DEFAULT_GATEWAY_TYPE = "TCP_PROXY";
21 export const DEFAULT_HOST_TYPE = "GCP_REGIONAL_MIG";
22 export const DEFAULT_GATEWAY_KIND = "GCP_REGIONAL_MIG";
23
24 export class ResourceNotResolved extends Data.TaggedError("GCP.BeyondCorp.ResourceNotResolved")<{
25 resourceName: string;
26 }> {}
27
28 export class ResourceStillExists extends Data.TaggedError("GCP.BeyondCorp.ResourceStillExists")<{
29 resourceName: string;
30 }> {}
31
32 export class ResourceFailed extends Data.TaggedError("GCP.BeyondCorp.ResourceFailed")<{
33 resourceName: string;
34 state: string | undefined;
35 }> {}
36
37 export class ResourceNotReady extends Data.TaggedError("GCP.BeyondCorp.ResourceNotReady")<{
38 resourceName: string;
39 state: string | undefined;
40 }> {}
41
42 export const lastSegment = (value: string) => {
43 const trimmed = value.replace(/\/+$/, "");
44 const parts = trimmed.split("/");
45 return parts[parts.length - 1] || trimmed;
46 };
47
48 export const rfc1035 = (name: string, fallback = "beyondcorp"): string => {
49 let next = name
50 .toLowerCase()
51 .replace(/[^a-z0-9-]/g, "-")
52 .replace(/-+/g, "-")
53 .replace(/^-+|-+$/g, "");
54 if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "b"}${next}`;
55 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
56 if (next.length === 0) next = fallback;
57 if (next.length < 4) next = `${next}${fallback}xxxx`.slice(0, MAX_NAME_LENGTH);
58 if (!/[a-z0-9]$/.test(next)) {
59 next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
60 }
61 return next.slice(0, MAX_NAME_LENGTH);
62 };
63
64 export const normalizeLocation = (location: string | undefined, fallback: string) =>
65 lastSegment(location ?? fallback).toLowerCase();
66
67 export const parentOf = (project: string, location: string) =>
68 `projects/${project}/locations/${location}`;
69
70 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
71 const parts = name.split("/").filter((part) => part.length > 0);
72 const collectionAt = parts.lastIndexOf(collection);
73 const locationsAt = parts.lastIndexOf("locations");
74 const projectsAt = parts.lastIndexOf("projects");
75 return {
76 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
77 location:
78 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
79 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
80 parent:
81 collectionAt > 0
82 ? parts.slice(0, collectionAt).join("/")
83 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
84 };
85 };
86
87 export const expandName = (
88 value: string,
89 project: string,
90 location: string,
91 collection: string,
92 ) => {
93 const next = value.replace(/\/+$/, "");
94 if (next.includes("/")) return next;
95 return `projects/${project}/locations/${location}/${collection}/${next}`;
96 };
97
98 export const toPhysicalId = (
99 id: string,
100 explicit: string | undefined,
101 existing: string | undefined,
102 fallback = "beyondcorp",
103 ) =>
104 Effect.gen(function* () {
105 if (explicit !== undefined) return rfc1035(explicit, fallback);
106 if (existing !== undefined) return existing;
107 return rfc1035(
108 yield* createPhysicalName({
109 id,
110 maxLength: MAX_NAME_LENGTH,
111 lowercase: true,
112 }),
113 fallback,
114 );
115 });
116
117 export const userLabels = (
118 labels: Record<string, string | undefined> | null | undefined,
119 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
120
121 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
122 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
123
124 const markerOf = (stack: string, stage: string, id: string) =>
125 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
126
127 const compactMarkerOf = (stack: string, stage: string, id: string) =>
128 `[alc ${stack} ${stage} ${id}]`;
129
130 const shrinkMarker = (
131 labels: Record<string, string>,
132 maxLength: number,
133 build: (stack: string, stage: string, id: string) => string,
134 ) => {
135 let stack = labels[alchemyLabelKeys.stack] ?? "x";
136 let stage = labels[alchemyLabelKeys.stage] ?? "x";
137 let id = labels[alchemyLabelKeys.id] ?? "x";
138 let marker = build(stack, stage, id);
139 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
140 if (stack.length >= stage.length && stack.length >= id.length) {
141 stack = stack.slice(0, -1);
142 } else if (stage.length >= id.length) {
143 stage = stage.slice(0, -1);
144 } else {
145 id = id.slice(0, -1);
146 }
147 marker = build(stack, stage, id);
148 }
149 return marker.slice(0, maxLength);
150 };
151
152 export const encodeOwnershipLine = (
153 labels: Record<string, string>,
154 text: string | undefined,
155 maxLength = MAX_DISPLAY_NAME_LENGTH,
156 ): string => {
157 const marker =
158 maxLength < 54
159 ? shrinkMarker(labels, maxLength, compactMarkerOf)
160 : shrinkMarker(labels, maxLength, markerOf);
161 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
162 if (!trimmed) return marker;
163 return `${marker} ${trimmed}`.slice(0, maxLength);
164 };
165
166 export const parseOwnership = (
167 text: string | undefined,
168 ): {
169 labels: Record<string, string>;
170 text: string | undefined;
171 } => {
172 if (text?.startsWith("[alc ")) {
173 const end = text.indexOf("]");
174 if (end < 0) return { labels: {}, text };
175 const parts = text.slice("[alc ".length, end).trim().split(/\s+/);
176 const labels: Record<string, string> = {};
177 if (parts[0]) labels[alchemyLabelKeys.stack] = parts[0]!;
178 if (parts[1]) labels[alchemyLabelKeys.stage] = parts[1]!;
179 if (parts[2]) labels[alchemyLabelKeys.id] = parts[2]!;
180 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
181 return { labels, text: rest.length > 0 ? rest : undefined };
182 }
183 if (!text?.startsWith("[alchemy ")) {
184 return { labels: {}, text };
185 }
186 const end = text.indexOf("]");
187 if (end < 0) return { labels: {}, text };
188 const labels: Record<string, string> = {};
189 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
190 const eq = part.indexOf("=");
191 if (eq > 0) {
192 labels[part.slice(0, eq)] = part.slice(eq + 1);
193 }
194 }
195 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
196 return { labels, text: rest.length > 0 ? rest : undefined };
197 };
198
199 export const hasOwnershipMarker = (text: string | undefined) =>
200 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
201
202 const prefixMatch = (expected: string, observed: string) =>
203 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
204
205 export const ownedByAlchemy = (id: string, text: string | undefined) =>
206 Effect.gen(function* () {
207 const expected = yield* createInternalLabels(id);
208 const { labels } = parseOwnership(text);
209 if (!hasOwnershipMarker(text)) return false;
210 const exact = yield* hasAlchemyLabels(id, labels);
211 if (exact) return true;
212 return (
213 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
214 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
215 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
216 );
217 });
218
219 export const canonical = (value: unknown): unknown => {
220 if (value === undefined || value === null) return undefined;
221 if (typeof value === "boolean" || typeof value === "number") return value;
222 if (typeof value === "string") {
223 return value.length === 0 ? undefined : value;
224 }
225 if (Array.isArray(value)) {
226 const items = value.map(canonical).filter((item) => item !== undefined);
227 return items.length === 0 ? undefined : items;
228 }
229 if (typeof value === "object") {
230 const entries = Object.entries(value as Record<string, unknown>)
231 .map(([key, item]) => [key, canonical(item)] as const)
232 .filter(([, item]) => item !== undefined)
233 .sort(([left], [right]) => left.localeCompare(right));
234 if (entries.length === 0) return undefined;
235 return Object.fromEntries(entries);
236 }
237 return undefined;
238 };
239
240 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
241
242 export const sameText = (left: string | undefined, right: string | undefined) =>
243 (left ?? "") === (right ?? "");
244
245 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
246
247 export const sameStringList = (
248 left: readonly string[] | undefined,
249 right: readonly string[] | undefined,
250 ) =>
251 JSON.stringify([...(left ?? [])].map(lastSegment).sort()) ===
252 JSON.stringify([...(right ?? [])].map(lastSegment).sort());
253
254 export const fieldMask = (fields: Array<string | false | undefined>) =>
255 fields.filter((field): field is string => typeof field === "string").join(",");
256
257 export const replaceOnIdentity = (input: {
258 previousId: string | undefined;
259 nextId: string | undefined;
260 previousLocation: string;
261 nextLocation: string;
262 extra?: boolean;
263 previousParent?: string;
264 nextParent?: string;
265 }) => {
266 const parentChanged =
267 (input.previousParent ?? "") !== "" &&
268 (input.nextParent ?? "") !== "" &&
269 lastSegment(input.previousParent ?? "") !== lastSegment(input.nextParent ?? "");
270 const replace =
271 (input.extra ?? false) ||
272 parentChanged ||
273 (input.previousId !== undefined &&
274 input.nextId !== undefined &&
275 input.nextId !== input.previousId) ||
276 input.previousLocation !== input.nextLocation;
277 if (!replace) return undefined;
278 const samePhysical =
279 input.previousLocation === input.nextLocation &&
280 !parentChanged &&
281 input.previousId !== undefined &&
282 input.nextId === input.previousId;
283 return {
284 action: "replace" as const,
285 deleteFirst: samePhysical,
286 };
287 };
288
289 const READY_STATES = new Set(["CREATED", "RUNNING"]);
290 const FAILED_STATES = new Set(["ERROR"]);
291
292 export const isReadyState = (state: string | undefined) => {
293 const value = (state ?? "").toUpperCase();
294 return value.length === 0 || READY_STATES.has(value);
295 };
296
297 export const isFailedState = (state: string | undefined) =>
298 FAILED_STATES.has((state ?? "").toUpperCase());
299
300 export const waitUntilExists = <A, E extends { readonly _tag: string }, R>(
301 get: Effect.Effect<A, E, R>,
302 name: string,
303 ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> =>
304 get.pipe(
305 Effect.filterOrFail(
306 (value): value is Exclude<A, undefined> => value !== undefined,
307 () => new ResourceNotResolved({ resourceName: name }),
308 ),
309 Effect.retry({
310 while: (error) => error._tag === "GCP.BeyondCorp.ResourceNotResolved",
311 times: 8,
312 schedule: Schedule.spaced("1 second"),
313 }),
314 );
315
316 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
317 get: Effect.Effect<A, E, R>,
318 name: string,
319 ): Effect.Effect<void, E | ResourceStillExists, R> =>
320 get.pipe(
321 Effect.filterOrFail(
322 (value) => value === undefined,
323 () => new ResourceStillExists({ resourceName: name }),
324 ),
325 Effect.asVoid,
326 Effect.retry({
327 while: (error) => error._tag === "GCP.BeyondCorp.ResourceStillExists",
328 times: 10,
329 schedule: Schedule.spaced("2 seconds"),
330 }),
331 );
332
333 export const waitUntilReady = <A, E extends { readonly _tag: string }, R>(
334 get: Effect.Effect<A, E, R>,
335 name: string,
336 stateOf: (value: Exclude<A, undefined>) => string | undefined,
337 ): Effect.Effect<
338 Exclude<A, undefined>,
339 E | ResourceNotResolved | ResourceFailed | ResourceNotReady,
340 R
341 > =>
342 get.pipe(
343 Effect.filterOrFail(
344 (value): value is Exclude<A, undefined> => value !== undefined,
345 () => new ResourceNotResolved({ resourceName: name }),
346 ),
347 Effect.filterOrFail(
348 (value) => !isFailedState(stateOf(value)),
349 (value) => new ResourceFailed({ resourceName: name, state: stateOf(value) }),
350 ),
351 Effect.filterOrFail(
352 (value) => {
353 const state = stateOf(value);
354 return isReadyState(state) || (state ?? "").toUpperCase() === "DOWN";
355 },
356 (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) }),
357 ),
358 Effect.retry({
359 while: (error) =>
360 error._tag === "GCP.BeyondCorp.ResourceNotReady" ||
361 error._tag === "GCP.BeyondCorp.ResourceNotResolved",
362 times: 8,
363 schedule: Schedule.spaced("3 seconds"),
364 }),
365 );
366
367 export const collectPages = <Page, Item, E, R>(
368 stream: Stream.Stream<Page, E, R>,
369 pick: (page: Page) => readonly Item[] | undefined,
370 ) =>
371 stream.pipe(
372 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
373 Stream.runFold(
374 (): Item[] => [],
375 (acc, item) => {
376 acc.push(item);
377 return acc;
378 },
379 ),
380 );
381
382 /** Every location at once: the API accepts the `locations/-` wildcard. */
383 export const listAtLocation = <A, E, R>(
384 project: string,
385 list: (parent: string) => Effect.Effect<A[], E, R>,
386 ) => list(`projects/${project}/locations/-`);
387
388 /** App connector and security gateway provisioning takes several minutes. */
389 const OPERATION_BUDGET = "15 minutes";
390
391 /**
392 * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a
393 * concurrent create won the race; reconcile observes the resource next.
394 */
395 export const waitForOperation = (operation: LongRunningOperation) =>
396 waitForLongRunning(operation, (name) => beyondcorp.getProjectsLocationsOperations({ name }), {
397 budget: OPERATION_BUDGET,
398 }).pipe(
399 Effect.catchIf(
400 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
401 () => Effect.succeed(operation),
402 ),
403 );
404
405 /**
406 * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5)
407 * means the resource is already gone.
408 */
409 export const waitForDeleteOperation = (operation: LongRunningOperation) =>
410 waitForOperation(operation).pipe(
411 Effect.catchIf(
412 (error) =>
413 error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5),
414 () => Effect.succeed(operation),
415 ),
416 );