@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, 06:00 UTC

main
ts 299 lines 10.4 KB
Raw
1 import * as workstations from "@distilled.cloud/gcp/workstations_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 { stripInternalLabels } from "../Labels.ts";
9 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
10
11 export const MAX_NAME_LENGTH = 63;
12
13 /**
14 * Generated ids are shorter than the 63-character id limit: GCP rejects a
15 * workstation's full resource name as "Malformed name" once it passes ~280
16 * characters, which three 63-character ids (cluster, config, workstation)
17 * exceed.
18 */
19 const GENERATED_NAME_LENGTH = 50;
20 export const DEFAULT_NETWORK = "default";
21 export const DEFAULT_SUBNETWORK = "default";
22
23 export class ResourceNotResolved extends Data.TaggedError("GCP.Workstations.ResourceNotResolved")<{
24 resourceName: string;
25 }> {}
26
27 export class ResourceStillExists extends Data.TaggedError("GCP.Workstations.ResourceStillExists")<{
28 resourceName: string;
29 }> {}
30
31 export class ResourceNotReady extends Data.TaggedError("GCP.Workstations.ResourceNotReady")<{
32 resourceName: string;
33 state: string;
34 }> {}
35
36 export const lastSegment = (value: string) => {
37 const trimmed = value.replace(/\/+$/, "");
38 const parts = trimmed.split("/");
39 return parts[parts.length - 1] || trimmed;
40 };
41
42 export const rfc1035 = (name: string, fallback = "workstation"): string => {
43 let next = name
44 .toLowerCase()
45 .replace(/[^a-z0-9-]/g, "-")
46 .replace(/-+/g, "-")
47 .replace(/^-+|-+$/g, "");
48 if (!/^[a-z]/.test(next)) next = `w${next}`;
49 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
50 if (next.length === 0) return fallback;
51 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
52 return next.slice(0, MAX_NAME_LENGTH);
53 };
54
55 export const normalizeLocation = (location: string | undefined, fallback: string) =>
56 lastSegment(location ?? fallback).toLowerCase();
57
58 export const parentOf = (project: string, location: string) =>
59 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
60
61 export const toPhysicalId = (
62 id: string,
63 explicit: string | undefined,
64 existing: string | undefined,
65 fallback = "workstation",
66 ) =>
67 Effect.gen(function* () {
68 if (explicit !== undefined) return rfc1035(explicit, fallback);
69 if (existing !== undefined) return existing;
70 return rfc1035(
71 yield* createPhysicalName({
72 id,
73 maxLength: GENERATED_NAME_LENGTH,
74 lowercase: true,
75 }),
76 fallback,
77 );
78 });
79
80 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
81 const parts = name.split("/").filter((part) => part.length > 0);
82 const collectionAt = parts.lastIndexOf(collection);
83 const locationsAt = parts.lastIndexOf("locations");
84 const projectsAt = parts.lastIndexOf("projects");
85 return {
86 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
87 location:
88 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
89 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
90 parent:
91 collectionAt > 0
92 ? parts.slice(0, collectionAt).join("/")
93 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
94 };
95 };
96
97 export const expandParent = (
98 value: string,
99 project: string,
100 location: string,
101 collection: string,
102 ) => {
103 if (value.includes("/")) return value.replace(/\/+$/, "");
104 return `projects/${project}/locations/${location}/${collection}/${value}`;
105 };
106
107 export const networkName = (value: string | undefined, project: string) => {
108 const next = (value ?? DEFAULT_NETWORK).replace(/\/+$/, "");
109 if (next.includes("/")) return next;
110 return `projects/${project}/global/networks/${next}`;
111 };
112
113 export const subnetworkName = (value: string | undefined, project: string, location: string) => {
114 const next = (value ?? DEFAULT_SUBNETWORK).replace(/\/+$/, "");
115 if (next.includes("/")) return next;
116 return `projects/${project}/regions/${location}/subnetworks/${next}`;
117 };
118
119 export const sameResource = (left: string | undefined, right: string | undefined) => {
120 if ((left ?? "") === (right ?? "")) return true;
121 if (left === undefined || right === undefined) return false;
122 return lastSegment(left) === lastSegment(right);
123 };
124
125 export const userLabels = (
126 labels: Record<string, string | undefined> | null | undefined,
127 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
128
129 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
130 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
131
132 export const canonical = (value: unknown): unknown => {
133 if (value === undefined || value === null) return undefined;
134 if (typeof value === "boolean" || typeof value === "number") return value;
135 if (typeof value === "string") {
136 return value.length === 0 ? undefined : value;
137 }
138 if (Array.isArray(value)) {
139 const items = value.map(canonical).filter((item) => item !== undefined);
140 return items.length === 0 ? undefined : items;
141 }
142 if (typeof value === "object") {
143 const entries = Object.entries(value as Record<string, unknown>)
144 .map(([key, item]) => [key, canonical(item)] as const)
145 .filter(([, item]) => item !== undefined)
146 .sort(([left], [right]) => left.localeCompare(right));
147 if (entries.length === 0) return undefined;
148 return Object.fromEntries(entries);
149 }
150 return undefined;
151 };
152
153 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
154
155 export const fieldMask = (fields: Array<string | false | undefined>) =>
156 fields.filter((field): field is string => typeof field === "string").join(",");
157
158 export const sameText = (left: string | undefined, right: string | undefined) =>
159 (left ?? "") === (right ?? "");
160
161 export const sameBool = (left: boolean | undefined, right: boolean | undefined) =>
162 (left === true) === (right === true);
163
164 export const sameNumber = (left: number | undefined, right: number | undefined) =>
165 (left ?? 0) === (right ?? 0);
166
167 export const replaceOnIdentity = (input: {
168 previousId: string | undefined;
169 nextId: string | undefined;
170 previousLocation: string;
171 nextLocation: string;
172 extra?: boolean;
173 previousParent?: string;
174 nextParent?: string;
175 }) => {
176 const parentChanged =
177 (input.previousParent ?? "") !== "" &&
178 (input.nextParent ?? "") !== "" &&
179 (input.previousParent ?? "") !== (input.nextParent ?? "") &&
180 lastSegment(input.previousParent ?? "") !== lastSegment(input.nextParent ?? "");
181 const replace =
182 (input.extra ?? false) ||
183 parentChanged ||
184 (input.previousId !== undefined &&
185 input.nextId !== undefined &&
186 input.nextId !== input.previousId) ||
187 input.previousLocation !== input.nextLocation;
188 if (!replace) return undefined;
189 const samePhysical =
190 input.previousLocation === input.nextLocation &&
191 !parentChanged &&
192 input.previousId !== undefined &&
193 input.nextId === input.previousId;
194 return {
195 action: "replace" as const,
196 deleteFirst: samePhysical,
197 };
198 };
199
200 /**
201 * Wait for a Cloud Workstations long-running operation. Cluster creates and deletes take up to ~20 minutes.
202 */
203 export const waitForOperation = (operation: workstations.Operation) =>
204 waitForGcpOperation(operation, (name) => workstations.getProjectsLocationsOperations({ name }), {
205 budget: "30 minutes",
206 });
207
208 export const waitUntilExists = <A, E extends object, R>(
209 get: Effect.Effect<A | undefined, E, R>,
210 name: string,
211 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
212 get.pipe(
213 Effect.filterOrFail(
214 (value): value is NonNullable<A> => value != null,
215 () => new ResourceNotResolved({ resourceName: name }),
216 ),
217 Effect.retry({
218 while: (error) => error instanceof ResourceNotResolved,
219 times: 8,
220 schedule: Schedule.spaced("1 second"),
221 }),
222 );
223
224 export const waitUntilGone = <A, E extends object, R>(
225 get: Effect.Effect<A | undefined, E, R>,
226 name: string,
227 ): Effect.Effect<void, E | ResourceStillExists, R> =>
228 get.pipe(
229 Effect.filterOrFail(
230 (value) => value === undefined,
231 () => new ResourceStillExists({ resourceName: name }),
232 ),
233 Effect.retry({
234 while: (error) => error instanceof ResourceStillExists,
235 times: 10,
236 schedule: Schedule.spaced("2 seconds"),
237 }),
238 Effect.asVoid,
239 );
240
241 export const listAtLocation = <A, E extends { readonly _tag: string }, R>(
242 project: string,
243 region: string,
244 list: (parent: string) => Effect.Effect<A[], E, R>,
245 ) =>
246 list(`projects/${project}/locations/-`).pipe(
247 Effect.catchIf(
248 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
249 () =>
250 list(`projects/${project}/locations/${region}`).pipe(
251 Effect.catchIf(
252 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
253 () => Effect.succeed([] as A[]),
254 ),
255 ),
256 ),
257 );
258
259 export const listAtNested = <A, E extends { readonly _tag: string }, R>(
260 project: string,
261 region: string,
262 nested: string,
263 list: (parent: string) => Effect.Effect<A[], E, R>,
264 ) =>
265 list(`projects/${project}/locations/-/${nested}`).pipe(
266 Effect.catchIf(
267 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
268 () =>
269 list(`projects/${project}/locations/${region}/${nested}`).pipe(
270 Effect.catchIf(
271 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
272 () => Effect.succeed([] as A[]),
273 ),
274 ),
275 ),
276 );
277
278 export const listLabeledPages = <Page, A, E, R>(
279 pages: Stream.Stream<Page, E, R>,
280 items: (page: Page) => readonly A[] | undefined,
281 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
282 ) =>
283 pages.pipe(
284 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
285 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
286 Stream.runCollect,
287 Effect.map((chunk) => Array.from(chunk)),
288 );
289
290 export const stringMap = (
291 value: Record<string, string | undefined> | null | undefined,
292 ): Record<string, string> | undefined => {
293 const next = Object.fromEntries(
294 Object.entries(value ?? {}).filter(
295 (entry): entry is [string, string] => entry[1] !== undefined,
296 ),
297 );
298 return Object.keys(next).length === 0 ? undefined : next;
299 };