@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 338 lines 11.1 KB
Raw
1 import type { GcpOpContext } from "@distilled.cloud/gcp/Protocol";
2 import * as vmwareengine from "@distilled.cloud/gcp/vmwareengine_v1";
3 import { createPhysicalName } from "alchemy/PhysicalName";
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, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9 import { waitForOperation as waitForLongRunningOperation } from "../Operation.ts";
10
11 export const DEFAULT_GLOBAL = "global";
12 // Zonal default for private clouds: a zone can't be derived from the stack
13 // region (not every region has an `-a` zone), so this stays fixed.
14 export const DEFAULT_ZONE = "us-central1-a";
15 export const MAX_NAME_LENGTH = 63;
16
17 export { createInternalLabels, hasAlchemyLabels };
18
19 export class VmwareengineNotResolved extends Data.TaggedError("GCP.VMwareEngine.NotResolved")<{
20 resourceName: string;
21 }> {}
22
23 export class VmwareengineStillExists extends Data.TaggedError("GCP.VMwareEngine.StillExists")<{
24 resourceName: string;
25 }> {}
26
27 export class VmwareengineFailed extends Data.TaggedError("GCP.VMwareEngine.Failed")<{
28 resourceName: string;
29 state: string | undefined;
30 }> {}
31
32 export const lastSegment = (value: string) => {
33 const trimmed = value.replace(/\/+$/, "");
34 const parts = trimmed.split("/");
35 return parts[parts.length - 1] || trimmed;
36 };
37
38 export const rfc1035 = (name: string, fallback = "resource"): string => {
39 let next = name
40 .toLowerCase()
41 .replace(/[^a-z0-9-]/g, "-")
42 .replace(/-+/g, "-")
43 .replace(/^-+/, "")
44 .replace(/-+$/, "");
45 if (!/^[a-z]/.test(next)) {
46 next = `v${next}`;
47 }
48 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
49 return next.length > 0 ? next : fallback;
50 };
51
52 export const normalizeLocation = (location: string | undefined, fallback: string) =>
53 lastSegment(location ?? fallback).toLowerCase();
54
55 export const parentOf = (project: string, location: string) =>
56 `projects/${project}/locations/${location}`;
57
58 export const canonicalizeLink = (value: string | undefined) => {
59 if (value === undefined || value.length === 0) return "";
60 return value
61 .replace(/^https?:\/\/[^/]+\//, "")
62 .replace(/^\/+/, "")
63 .replace(/\/+$/, "");
64 };
65
66 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
67 const parts = name.split("/").filter((part) => part.length > 0);
68 const collectionAt = parts.lastIndexOf(collection);
69 const locationsAt = parts.lastIndexOf("locations");
70 const projectsAt = parts.lastIndexOf("projects");
71 return {
72 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
73 location:
74 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
75 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
76 parent: collectionAt > 0 ? parts.slice(0, collectionAt).join("/") : "",
77 };
78 };
79
80 export const locationFromName = (name: string, fallback: string) => {
81 const canonical = canonicalizeLink(name);
82 if (!canonical.includes("/locations/")) return fallback;
83 return parseName(canonical, "locations", fallback).location;
84 };
85
86 export const expandName = (
87 value: string,
88 project: string,
89 location: string,
90 collection: string,
91 ) => {
92 const canonical = canonicalizeLink(value);
93 if (canonical.includes(`/${collection}/`) || canonical.includes("/locations/")) {
94 return canonical;
95 }
96 return `${parentOf(project, location)}/${collection}/${rfc1035(canonical, collection)}`;
97 };
98
99 export const toPhysicalId = (
100 id: string,
101 explicit: string | undefined,
102 existing: string | undefined,
103 fallback = "resource",
104 ) =>
105 Effect.gen(function* () {
106 if (explicit !== undefined) return rfc1035(explicit, fallback);
107 if (existing !== undefined) return existing;
108 return rfc1035(
109 yield* createPhysicalName({
110 id,
111 maxLength: MAX_NAME_LENGTH,
112 lowercase: true,
113 }),
114 fallback,
115 );
116 });
117
118 export const encodeOwnership = (
119 labels: Record<string, string>,
120 text: string | undefined,
121 ): string => {
122 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
123 const trimmed = text?.trim();
124 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
125 };
126
127 export const parseOwnership = (
128 text: string | undefined,
129 ): {
130 labels: Record<string, string>;
131 text: string | undefined;
132 } => {
133 if (!text?.startsWith("[alchemy ")) {
134 return { labels: {}, text };
135 }
136 const end = text.indexOf("]");
137 if (end < 0) return { labels: {}, text };
138 const labels: Record<string, string> = {};
139 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
140 const eq = part.indexOf("=");
141 if (eq > 0) {
142 labels[part.slice(0, eq)] = part.slice(eq + 1);
143 }
144 }
145 const rest = text.slice(end + 1).replace(/^\s+/, "");
146 return { labels, text: rest.length > 0 ? rest : undefined };
147 };
148
149 export const hasOwnershipMarker = (text: string | undefined) =>
150 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
151
152 export const sameJson = (left: unknown, right: unknown) =>
153 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
154
155 export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) =>
156 pairs.filter(([, changed]) => changed).map(([field]) => field);
157
158 export const replaceOnIdentity = (input: {
159 previousId: string | undefined;
160 nextId: string | undefined;
161 previousLocation: string;
162 nextLocation: string;
163 extra?: boolean;
164 previousParent?: string;
165 nextParent?: string;
166 }) => {
167 const parentChanged =
168 (input.previousParent ?? "") !== "" &&
169 (input.nextParent ?? "") !== "" &&
170 canonicalizeLink(input.previousParent) !== canonicalizeLink(input.nextParent);
171 const replace =
172 (input.extra ?? false) ||
173 parentChanged ||
174 (input.previousId !== undefined &&
175 input.nextId !== undefined &&
176 input.nextId !== input.previousId) ||
177 input.previousLocation !== input.nextLocation;
178 if (!replace) return undefined;
179 const samePhysical =
180 input.previousLocation === input.nextLocation &&
181 !parentChanged &&
182 input.previousId !== undefined &&
183 input.nextId === input.previousId;
184 return {
185 action: "replace" as const,
186 deleteFirst: samePhysical,
187 };
188 };
189
190 /**
191 * Wait on a VMware Engine long-running operation. Private clouds take 1–2 hours; networks and policies minutes.
192 * `ALREADY_EXISTS` (a create race) counts as success; so does `NOT_FOUND`
193 * when `notFoundOk` (deletes). Returns the final operation.
194 */
195 export const waitForOperation = (
196 operation: vmwareengine.Operation,
197 options?: { notFoundOk?: boolean },
198 ) =>
199 Effect.suspend(() => {
200 let latest = operation;
201 return waitForLongRunningOperation(
202 operation,
203 (name) => {
204 const get = vmwareengine.getProjectsLocationsOperations({ name }).pipe(
205 Effect.tap((current) =>
206 Effect.sync(() => {
207 latest = current;
208 }),
209 ),
210 );
211 const observe: Effect.Effect<
212 vmwareengine.Operation,
213 vmwareengine.GetProjectsLocationsOperationsError,
214 GcpOpContext
215 > =
216 options?.notFoundOk === true
217 ? get.pipe(
218 Effect.catchTag("NotFound", () =>
219 Effect.succeed<vmwareengine.Operation>({ name, done: true }),
220 ),
221 )
222 : get.pipe(
223 // A just-returned operation can briefly 404 on read.
224 Effect.retry({
225 while: (error) => error._tag === "NotFound",
226 times: 5,
227 schedule: Schedule.exponential("250 millis"),
228 }),
229 );
230 return observe;
231 },
232 { budget: "3 hours", interval: "30 seconds" },
233 ).pipe(
234 Effect.map(() => latest),
235 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
236 Effect.catchTag("GCP.OperationFailed", (error) =>
237 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
238 ? Effect.succeed(latest)
239 : Effect.fail(error),
240 ),
241 );
242 });
243
244 export const waitUntilPresent = <A extends object, E, R>(
245 get: Effect.Effect<A | undefined, E, R>,
246 name: string,
247 ): Effect.Effect<A, E | VmwareengineNotResolved, R> =>
248 get.pipe(
249 Effect.filterOrFail(
250 (value): value is A => value !== undefined,
251 () => new VmwareengineNotResolved({ resourceName: name }),
252 ),
253 Effect.retry({
254 while: (error) => error instanceof VmwareengineNotResolved,
255 times: 8,
256 schedule: Schedule.spaced("1 second"),
257 }),
258 );
259
260 export const waitUntilGone = <A, E, R>(
261 get: Effect.Effect<A | undefined, E, R>,
262 name: string,
263 ): Effect.Effect<void, E | VmwareengineStillExists, R> =>
264 get.pipe(
265 Effect.filterOrFail(
266 (value): value is undefined => value === undefined,
267 () => new VmwareengineStillExists({ resourceName: name }),
268 ),
269 Effect.as(undefined as void),
270 Effect.retry({
271 while: (error) => error instanceof VmwareengineStillExists,
272 times: 10,
273 schedule: Schedule.spaced("2 seconds"),
274 }),
275 );
276
277 const PENDING_STATES = new Set([
278 "STATE_UNSPECIFIED",
279 "CREATING",
280 "UPDATING",
281 "DELETING",
282 "PURGING",
283 "REPAIRING",
284 "RECONCILING",
285 ]);
286
287 const FAILED_STATES = new Set(["FAILED", "DELETE_FAILED"]);
288
289 export const waitUntilReady = <A extends object, E, R>(
290 get: Effect.Effect<A | undefined, E, R>,
291 name: string,
292 stateOf: (value: A) => string | undefined,
293 ): Effect.Effect<A, E | VmwareengineNotResolved | VmwareengineFailed, R> =>
294 get.pipe(
295 Effect.filterOrFail(
296 (value): value is A => {
297 if (value === undefined) return false;
298 return !PENDING_STATES.has(stateOf(value) ?? "");
299 },
300 () => new VmwareengineNotResolved({ resourceName: name }),
301 ),
302 Effect.filterOrFail(
303 (value) => !FAILED_STATES.has(stateOf(value) ?? ""),
304 (value) => new VmwareengineFailed({ resourceName: name, state: stateOf(value) }),
305 ),
306 Effect.retry({
307 while: (error) => error instanceof VmwareengineNotResolved,
308 // Private clouds and clusters take 1–2 hours to provision.
309 times: 360,
310 schedule: Schedule.spaced("30 seconds"),
311 }),
312 );
313
314 export const collectPages = <Page, Item, E, R>(
315 stream: Stream.Stream<Page, E, R>,
316 pick: (page: Page) => readonly Item[] | undefined,
317 ): Effect.Effect<Item[], E, R> =>
318 stream.pipe(
319 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? ([] as readonly Item[]))),
320 Stream.runCollect,
321 Effect.map((chunk) => Array.from(chunk)),
322 );
323
324 export const listAcrossLocations = <A, E, R>(
325 project: string,
326 region: string,
327 list: (parent: string) => Effect.Effect<A[], E, R>,
328 ): Effect.Effect<A[], E, R> =>
329 // Some collections reject the `-` location wildcard; fall back to the
330 // well-known locations.
331 Effect.firstSuccessOf([
332 list(parentOf(project, "-")),
333 Effect.forEach(
334 [...new Set<string>([DEFAULT_GLOBAL, region, DEFAULT_ZONE])],
335 (location) => list(parentOf(project, location)),
336 { concurrency: 3 },
337 ).pipe(Effect.map((chunks) => chunks.flat())),
338 ]);