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

main
ts 308 lines 10.5 KB
Raw
1 import * as networkservices from "@distilled.cloud/gcp/networkservices_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 { alchemyLabelKeys, stripInternalLabels } from "../Labels.ts";
9 import { waitForOperation as waitForLongRunning } from "../Operation.ts";
10
11 export const DEFAULT_GLOBAL = "global";
12 // Multicast resources are zonal; a zone cannot be derived from the stack
13 // region (not every region has an `-a` zone), so this default stays fixed.
14 export const DEFAULT_ZONE = "us-central1-a";
15 export const MAX_NAME_LENGTH = 63;
16 export const MAX_MULTICAST_NAME_LENGTH = 48;
17
18 export class NetworkservicesNotResolved extends Data.TaggedError(
19 "GCP.NetworkServices.NotResolved",
20 )<{
21 resourceName: string;
22 }> {}
23
24 export class NetworkservicesStillExists extends Data.TaggedError(
25 "GCP.NetworkServices.StillExists",
26 )<{
27 resourceName: string;
28 }> {}
29
30 export class NetworkservicesFailed extends Data.TaggedError("GCP.NetworkServices.Failed")<{
31 resourceName: string;
32 state: string | undefined;
33 }> {}
34
35 export const lastSegment = (value: string) => {
36 const trimmed = value.replace(/\/+$/, "");
37 const parts = trimmed.split("/");
38 return parts[parts.length - 1] || trimmed;
39 };
40
41 export const rfc1035 = (
42 name: string,
43 fallback = "resource",
44 maxLength = MAX_NAME_LENGTH,
45 ): string => {
46 let next = name
47 .toLowerCase()
48 .replace(/[^a-z0-9-]/g, "-")
49 .replace(/-+/g, "-")
50 .replace(/^-+/, "")
51 .replace(/-+$/, "");
52 if (!/^[a-z]/.test(next)) {
53 next = `n${next}`;
54 }
55 next = next.slice(0, maxLength).replace(/-+$/, "");
56 return next.length > 0 ? next : fallback;
57 };
58
59 export const normalizeLocation = (location: string | undefined, fallback: string) =>
60 lastSegment(location ?? fallback).toLowerCase();
61
62 export const parentOf = (project: string, location: string) =>
63 `projects/${project}/locations/${location}`;
64
65 export const resourceName = (project: string, location: string, collection: string, id: string) =>
66 `projects/${project}/locations/${location}/${collection}/${id}`;
67
68 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
69 const parts = name.split("/").filter((part) => part.length > 0);
70 const collectionAt = parts.lastIndexOf(collection);
71 const locationsAt = parts.lastIndexOf("locations");
72 const projectsAt = parts.lastIndexOf("projects");
73 return {
74 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
75 location:
76 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
77 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
78 };
79 };
80
81 export const toPhysicalId = (
82 id: string,
83 explicit: string | undefined,
84 existing: string | undefined,
85 fallback = "resource",
86 maxLength = MAX_NAME_LENGTH,
87 ) =>
88 Effect.gen(function* () {
89 if (explicit !== undefined) return rfc1035(explicit, fallback, maxLength);
90 if (existing !== undefined) return existing;
91 return rfc1035(
92 yield* createPhysicalName({
93 id,
94 maxLength,
95 lowercase: true,
96 }),
97 fallback,
98 maxLength,
99 );
100 });
101
102 export const userLabels = (
103 labels: Record<string, string | undefined> | null | undefined,
104 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
105
106 export const hasAlchemyLabelKeys = (
107 labels: Record<string, string | undefined> | null | undefined,
108 ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
109
110 export const encodeOwnership = (
111 labels: Record<string, string>,
112 text: string | undefined,
113 ): string => {
114 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
115 const trimmed = text?.trim();
116 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
117 };
118
119 export const parseOwnership = (
120 text: string | undefined,
121 ): {
122 labels: Record<string, string>;
123 text: string | undefined;
124 } => {
125 if (!text?.startsWith("[alchemy ")) {
126 return { labels: {}, text };
127 }
128 const end = text.indexOf("]");
129 if (end < 0) return { labels: {}, text };
130 const labels: Record<string, string> = {};
131 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
132 const eq = part.indexOf("=");
133 if (eq > 0) {
134 labels[part.slice(0, eq)] = part.slice(eq + 1);
135 }
136 }
137 const rest = text.slice(end + 1).replace(/^\s+/, "");
138 return { labels, text: rest.length > 0 ? rest : undefined };
139 };
140
141 export const hasOwnershipMarker = (text: string | undefined) =>
142 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
143
144 export const sameJson = (left: unknown, right: unknown) =>
145 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
146
147 export const canonicalizeLink = (value: string | undefined) => {
148 if (value === undefined || value.length === 0) return "";
149 return value
150 .replace(/^https?:\/\/[^/]+\//, "")
151 .replace(/^compute\/v1\//, "")
152 .replace(/\/+$/, "");
153 };
154
155 export const sameStringList = (
156 left: readonly string[] | undefined,
157 right: readonly string[] | undefined,
158 ) =>
159 JSON.stringify([...(left ?? [])].map(canonicalizeLink).sort()) ===
160 JSON.stringify([...(right ?? [])].map(canonicalizeLink).sort());
161
162 export const sameNumberList = (
163 left: readonly number[] | undefined,
164 right: readonly number[] | undefined,
165 ) => JSON.stringify([...(left ?? [])]) === JSON.stringify([...(right ?? [])]);
166
167 export const linkKey = (value: string | undefined) =>
168 lastSegment(canonicalizeLink(value)).toLowerCase();
169
170 export const toMulticastNetwork = (project: string, network: string) => {
171 const trimmed = canonicalizeLink(network);
172 const parts = trimmed.split("/").filter((part) => part.length > 0);
173 const projectsAt = parts.lastIndexOf("projects");
174 const proj = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project;
175 const id = lastSegment(trimmed);
176 return `projects/${proj}/locations/global/networks/${id || trimmed}`;
177 };
178
179 export const toBackendServiceResource = (project: string, service: string) => {
180 const trimmed = canonicalizeLink(service);
181 if (trimmed.includes("/backendServices/") || trimmed.includes("/backendservices/")) {
182 if (trimmed.includes("/locations/")) return trimmed;
183 const parts = trimmed.split("/").filter((part) => part.length > 0);
184 const projectsAt = parts.lastIndexOf("projects");
185 const proj = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project;
186 return `projects/${proj}/locations/global/backendServices/${lastSegment(trimmed)}`;
187 }
188 return `projects/${project}/locations/global/backendServices/${lastSegment(trimmed)}`;
189 };
190
191 export const toNamedResource = (
192 project: string,
193 location: string,
194 collection: string,
195 value: string,
196 ) => {
197 const trimmed = canonicalizeLink(value);
198 if (trimmed.includes(`/${collection}/`)) return trimmed;
199 return resourceName(project, location, collection, lastSegment(trimmed));
200 };
201
202 export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) =>
203 pairs.filter(([, changed]) => changed).map(([field]) => field);
204
205 /**
206 * Wait for a Network Services long-running operation. Agent gateways and
207 * multicast resources take several minutes.
208 * `ALREADY_EXISTS` (a concurrent create won) always succeeds;
209 * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has
210 * already been garbage-collected (deletes).
211 */
212 export const waitForOperation = (
213 operation: networkservices.Operation,
214 options?: { notFoundOk?: boolean },
215 ) =>
216 waitForLongRunning(
217 operation,
218 (name) => networkservices.getProjectsLocationsOperations({ name }),
219 { budget: "20 minutes" },
220 ).pipe(
221 Effect.catchIf(
222 (error) =>
223 error._tag === "GCP.OperationFailed" &&
224 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
225 () => Effect.void,
226 ),
227 Effect.catchIf(
228 (error) => options?.notFoundOk === true && error._tag === "NotFound",
229 () => Effect.void,
230 ),
231 );
232
233 export const waitUntilPresent = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
234 get.pipe(
235 Effect.flatMap((value) =>
236 value
237 ? Effect.succeed(value)
238 : Effect.fail(new NetworkservicesNotResolved({ resourceName: name })),
239 ),
240 Effect.retry({
241 while: (error) => error instanceof NetworkservicesNotResolved,
242 times: 8,
243 schedule: Schedule.spaced("1 second"),
244 }),
245 );
246
247 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
248 get.pipe(
249 Effect.flatMap((value) =>
250 value === undefined
251 ? Effect.void
252 : Effect.fail(new NetworkservicesStillExists({ resourceName: name })),
253 ),
254 Effect.retry({
255 while: (error) => error instanceof NetworkservicesStillExists,
256 times: 10,
257 schedule: Schedule.spaced("2 seconds"),
258 }),
259 );
260
261 const PENDING_STATES = new Set([
262 "STATE_UNSPECIFIED",
263 "STATE_ENUM_UNSPECIFIED",
264 "CREATING",
265 "UPDATING",
266 "DELETING",
267 ]);
268
269 const FAILED_STATES = new Set(["FAILED", "DELETE_FAILED", "UPDATE_FAILED", "OBSOLETE"]);
270
271 export const waitUntilReady = <A extends { state?: string }, E, R>(
272 get: Effect.Effect<A | undefined, E, R>,
273 name: string,
274 ) =>
275 get.pipe(
276 Effect.filterOrFail(
277 (value): value is A => value !== undefined,
278 () => new NetworkservicesNotResolved({ resourceName: name }),
279 ),
280 Effect.filterOrFail(
281 (value) => !FAILED_STATES.has(value.state ?? ""),
282 (value) => new NetworkservicesFailed({ resourceName: name, state: value.state }),
283 ),
284 Effect.filterOrFail(
285 (value) => !PENDING_STATES.has(value.state ?? ""),
286 () => new NetworkservicesNotResolved({ resourceName: name }),
287 ),
288 Effect.retry({
289 while: (error) => error instanceof NetworkservicesNotResolved,
290 times: 10,
291 schedule: Schedule.spaced("4 seconds"),
292 }),
293 );
294
295 /** Collect every page; a missing parent (`NotFound`) lists as empty. */
296 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
297 stream: Stream.Stream<Page, E, R>,
298 pick: (page: Page) => readonly Item[] | undefined,
299 ) =>
300 stream.pipe(
301 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
302 Stream.runCollect,
303 Effect.map((chunk): Item[] => Array.from(chunk)),
304 Effect.catchIf(
305 (error) => error._tag === "NotFound",
306 () => Effect.succeed<Item[]>([]),
307 ),
308 );