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

main
ts 347 lines 11.8 KB
Raw
1 import * as apim from "@distilled.cloud/gcp/apim_v1alpha";
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 { waitForOperation as waitForLongRunning } from "../Operation.ts";
8
9 export const MAX_NAME_LENGTH = 63;
10 export const MIN_NAME_LENGTH = 4;
11 export const ALCHEMY_ID_PREFIX = "alch-";
12
13 export type PscNetworkConfig = {
14 /** VPC network `projects/{project}/global/networks/{network}`. */
15 network: string;
16 /**
17 * Subnetwork
18 * `projects/{project}/regions/{region}/subnetworks/{subnet}`.
19 */
20 subnetwork: string;
21 };
22
23 export type GclbObservationSource = {
24 /** VPC networks whose load balancers are observed. Currently one. */
25 pscNetworkConfigs: PscNetworkConfig[];
26 };
27
28 export class ResourceNotResolved extends Data.TaggedError("GCP.Apim.NotResolved")<{
29 resourceName: string;
30 }> {}
31
32 export class ResourceStillExists extends Data.TaggedError("GCP.Apim.StillExists")<{
33 resourceName: string;
34 }> {}
35
36 export class ResourceNotReady extends Data.TaggedError("GCP.Apim.NotReady")<{
37 resourceName: string;
38 state: string;
39 }> {}
40
41 export class ResourceFailed extends Data.TaggedError("GCP.Apim.Failed")<{
42 resourceName: string;
43 state: string;
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 = "apim"): 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 = `${fallback[0] ?? "a"}${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 < MIN_NAME_LENGTH) {
63 next = `${next}${"x".repeat(MIN_NAME_LENGTH)}`.slice(0, MIN_NAME_LENGTH);
64 }
65 return next.slice(0, MAX_NAME_LENGTH);
66 };
67
68 export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
69
70 export const parentOf = (project: string, location: string) =>
71 `projects/${project}/locations/${normalizeLocation(location)}`;
72
73 export const resourceName = (project: string, location: string, collection: string, id: string) =>
74 `${parentOf(project, location)}/${collection}/${id}`;
75
76 export const toPhysicalId = (
77 id: string,
78 explicit: string | undefined,
79 existing: string | undefined,
80 fallback = "apim",
81 ) =>
82 Effect.gen(function* () {
83 if (explicit !== undefined) return rfc1035(explicit, fallback);
84 if (existing !== undefined) return existing;
85 const generated = rfc1035(
86 yield* createPhysicalName({
87 id,
88 maxLength: MAX_NAME_LENGTH - ALCHEMY_ID_PREFIX.length,
89 lowercase: true,
90 }),
91 fallback,
92 );
93 const prefixed = generated.startsWith(ALCHEMY_ID_PREFIX)
94 ? generated
95 : `${ALCHEMY_ID_PREFIX}${generated}`;
96 return rfc1035(prefixed, fallback);
97 });
98
99 export const parseName = (name: string, collection: string) => {
100 const parts = name.split("/").filter((part) => part.length > 0);
101 const collectionAt = parts.lastIndexOf(collection);
102 const locationsAt = parts.lastIndexOf("locations");
103 const projectsAt = parts.lastIndexOf("projects");
104 return {
105 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
106 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
107 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
108 parent:
109 collectionAt > 0
110 ? parts.slice(0, collectionAt).join("/")
111 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
112 };
113 };
114
115 export const hasAlchemyId = (id: string | undefined) => (id ?? "").startsWith(ALCHEMY_ID_PREFIX);
116
117 export const projectIdOf = (value: string | undefined, fallback: string) => {
118 if (value === undefined || value.length === 0) return fallback;
119 const parts = value.split("/").filter((part) => part.length > 0);
120 const at = parts.lastIndexOf("projects");
121 if (at >= 0 && parts[at + 1]) return parts[at + 1]!;
122 return fallback;
123 };
124
125 export const expandNetwork = (value: string, project: string) => {
126 const trimmed = value.replace(/\/+$/, "");
127 if (trimmed.includes("/networks/")) {
128 const owner = projectIdOf(trimmed, project);
129 return `projects/${owner}/global/networks/${lastSegment(trimmed)}`;
130 }
131 return `projects/${project}/global/networks/${trimmed}`;
132 };
133
134 export const expandSubnetwork = (value: string, project: string, location: string) => {
135 const trimmed = value.replace(/\/+$/, "");
136 if (trimmed.includes("/subnetworks/")) {
137 const owner = projectIdOf(trimmed, project);
138 const parts = trimmed.split("/").filter((part) => part.length > 0);
139 const regionsAt = parts.lastIndexOf("regions");
140 const region = regionsAt >= 0 && parts[regionsAt + 1] ? parts[regionsAt + 1]! : location;
141 return `projects/${owner}/regions/${region}/subnetworks/${lastSegment(trimmed)}`;
142 }
143 return `projects/${project}/regions/${location}/subnetworks/${trimmed}`;
144 };
145
146 export const expandObservationSource = (value: string, project: string, location: string) => {
147 const trimmed = value.replace(/\/+$/, "");
148 if (trimmed.includes("/observationSources/")) return trimmed;
149 return resourceName(project, location, "observationSources", trimmed);
150 };
151
152 export const expandGclb = (
153 source: GclbObservationSource | undefined,
154 project: string,
155 location: string,
156 ): apim.GclbObservationSource | undefined => {
157 if (source === undefined) return undefined;
158 return {
159 pscNetworkConfigs: (source.pscNetworkConfigs ?? []).map((config) => ({
160 network: expandNetwork(config.network, project),
161 subnetwork: expandSubnetwork(config.subnetwork, project, location),
162 })),
163 };
164 };
165
166 export const canonical = (value: unknown): unknown => {
167 if (value === undefined || value === null) return undefined;
168 if (typeof value === "boolean" || typeof value === "number") return value;
169 if (typeof value === "string") {
170 return value.length === 0 ? undefined : value;
171 }
172 if (Array.isArray(value)) {
173 const items = value.map(canonical).filter((item) => item !== undefined);
174 return items.length === 0 ? undefined : items;
175 }
176 if (typeof value === "object") {
177 const entries = Object.entries(value as Record<string, unknown>)
178 .map(([key, item]) => [key, canonical(item)] as const)
179 .filter(([, item]) => item !== undefined)
180 .sort(([left], [right]) => left.localeCompare(right));
181 if (entries.length === 0) return undefined;
182 return Object.fromEntries(entries);
183 }
184 return undefined;
185 };
186
187 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
188
189 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
190
191 export const sameStringList = (
192 left: readonly string[] | undefined,
193 right: readonly string[] | undefined,
194 ) =>
195 fingerprint([...(left ?? [])].map(lastSegment).sort()) ===
196 fingerprint([...(right ?? [])].map(lastSegment).sort());
197
198 export const replaceOnIdentity = (input: {
199 previousId: string | undefined;
200 nextId: string | undefined;
201 previousLocation: string;
202 nextLocation: string;
203 extra?: boolean;
204 deleteFirst?: boolean;
205 }) => {
206 const replace =
207 (input.extra ?? false) ||
208 (input.previousId !== undefined &&
209 input.nextId !== undefined &&
210 input.nextId !== input.previousId) ||
211 input.previousLocation !== input.nextLocation;
212 if (!replace) return undefined;
213 const samePhysical =
214 input.previousLocation === input.nextLocation &&
215 input.previousId !== undefined &&
216 input.nextId === input.previousId;
217 return {
218 action: "replace" as const,
219 deleteFirst: input.deleteFirst ?? samePhysical,
220 };
221 };
222
223 /**
224 * Wait for a API Management long-running operation. Observation jobs and
225 * sources settle within minutes.
226 * `ALREADY_EXISTS` (a concurrent create won) always succeeds;
227 * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has
228 * already been garbage-collected (deletes).
229 */
230 export const waitForOperation = (operation: apim.Operation, options?: { notFoundOk?: boolean }) =>
231 waitForLongRunning(operation, (name) => apim.getProjectsLocationsOperations({ name }), {
232 budget: "10 minutes",
233 }).pipe(
234 Effect.catchIf(
235 (error) =>
236 error._tag === "GCP.OperationFailed" &&
237 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
238 () => Effect.void,
239 ),
240 Effect.catchIf(
241 (error) => options?.notFoundOk === true && error._tag === "NotFound",
242 () => Effect.void,
243 ),
244 );
245
246 export const waitUntilExists = <A, E, R>(
247 get: Effect.Effect<A, E, R>,
248 name: string,
249 ): Effect.Effect<A & {}, E | ResourceNotResolved, R> =>
250 get.pipe(
251 Effect.filterOrFail(
252 (value): value is A & {} => value !== undefined,
253 () => new ResourceNotResolved({ resourceName: name }),
254 ),
255 Effect.retry({
256 while: (error) => error instanceof ResourceNotResolved,
257 times: 8,
258 schedule: Schedule.spaced("1 second"),
259 }),
260 );
261
262 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A, E, R>, name: string) =>
263 get.pipe(
264 Effect.filterOrFail(
265 (value) => value === undefined,
266 () => new ResourceStillExists({ resourceName: name }),
267 ),
268 Effect.retry({
269 while: (error) => error instanceof ResourceStillExists,
270 times: 10,
271 schedule: Schedule.spaced("2 seconds"),
272 }),
273 Effect.asVoid,
274 );
275
276 const FAILED_STATES = new Set(["ERROR", "FAILED"]);
277
278 export const waitUntilReady = <A, E, R>(
279 get: Effect.Effect<A, E, R>,
280 name: string,
281 stateOf: (value: A & {}) => string | undefined,
282 ready: ReadonlySet<string>,
283 options?: {
284 times?: number;
285 interval?: `${number} seconds`;
286 },
287 ): Effect.Effect<A & {}, E | ResourceNotResolved | ResourceNotReady | ResourceFailed, R> =>
288 get.pipe(
289 Effect.filterOrFail(
290 (value): value is A & {} => value !== undefined,
291 () => new ResourceNotResolved({ resourceName: name }),
292 ),
293 Effect.filterOrFail(
294 (value) => !FAILED_STATES.has((stateOf(value) ?? "").toUpperCase()),
295 (value) =>
296 new ResourceFailed({
297 resourceName: name,
298 state: (stateOf(value) ?? "").toUpperCase(),
299 }),
300 ),
301 Effect.filterOrFail(
302 (value) => ready.has((stateOf(value) ?? "").toUpperCase()),
303 (value) =>
304 new ResourceNotReady({
305 resourceName: name,
306 state: (stateOf(value) ?? "").toUpperCase(),
307 }),
308 ),
309 Effect.retry({
310 while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved,
311 times: options?.times ?? 10,
312 schedule: Schedule.spaced(options?.interval ?? "3 seconds"),
313 }),
314 );
315
316 export const collectPages = <Page, A, E, R>(
317 pages: Stream.Stream<Page, E, R>,
318 items: (page: Page) => readonly A[] | undefined,
319 ) =>
320 pages.pipe(
321 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
322 Stream.runCollect,
323 Effect.map((chunk) => Array.from(chunk)),
324 );
325
326 /**
327 * List across every location via the `locations/-` wildcard, falling back to
328 * the default region where the API rejects the wildcard. A missing parent
329 * (`NotFound`) lists as empty; any other error fails.
330 */
331 export const listAtLocation = <A, E extends { readonly _tag: string }, R>(
332 project: string,
333 region: string,
334 list: (parent: string) => Effect.Effect<A[], E, R>,
335 ) =>
336 list(`projects/${project}/locations/-`).pipe(
337 Effect.catchIf(
338 (error) => error._tag === "NotFound" || error._tag === "BadRequest",
339 () =>
340 list(`projects/${project}/locations/${region}`).pipe(
341 Effect.catchIf(
342 (error) => error._tag === "NotFound",
343 () => Effect.succeed<A[]>([]),
344 ),
345 ),
346 ),
347 );