@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 242 lines 8.33 KB
Raw
1 import * as config from "@distilled.cloud/gcp/config_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 export class ResourceNotResolved extends Data.TaggedError("GCP.Config.ResourceNotResolved")<{
14 resourceName: string;
15 }> {}
16
17 export class ResourceStillExists extends Data.TaggedError("GCP.Config.ResourceStillExists")<{
18 resourceName: string;
19 }> {}
20
21 export const lastSegment = (value: string) => {
22 const trimmed = value.replace(/\/+$/, "");
23 const parts = trimmed.split("/");
24 return parts[parts.length - 1] || trimmed;
25 };
26
27 export const rfc1035 = (name: string, fallback = "config"): string => {
28 let next = name
29 .toLowerCase()
30 .replace(/[^a-z0-9-]/g, "-")
31 .replace(/-+/g, "-")
32 .replace(/^-+|-+$/g, "");
33 if (!/^[a-z]/.test(next)) next = `c${next}`;
34 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
35 if (next.length === 0) return fallback;
36 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
37 return next.slice(0, MAX_NAME_LENGTH);
38 };
39
40 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
41 lastSegment(location ?? defaultLocation).toLowerCase();
42
43 export const parentOf = (project: string, location: string) =>
44 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
45
46 export const toPhysicalId = (
47 id: string,
48 explicit: string | undefined,
49 existing: string | undefined,
50 fallback = "config",
51 maxLength = MAX_NAME_LENGTH,
52 ) =>
53 Effect.gen(function* () {
54 if (explicit !== undefined) return rfc1035(explicit, fallback);
55 if (existing !== undefined) return existing;
56 return rfc1035(
57 yield* createPhysicalName({
58 id,
59 maxLength,
60 lowercase: true,
61 }),
62 fallback,
63 );
64 });
65
66 export const parseName = (name: string, collection: string, defaultLocation: 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]! : defaultLocation,
75 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
76 parent:
77 collectionAt > 0
78 ? parts.slice(0, collectionAt).join("/")
79 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
80 };
81 };
82
83 export const expandNamed = (
84 value: string,
85 project: string,
86 location: string,
87 collection: string,
88 ) => {
89 if (value.includes("/")) return value.replace(/\/+$/, "");
90 return `projects/${project}/locations/${location}/${collection}/${value}`;
91 };
92
93 export const serviceAccountName = (value: string, project: string) => {
94 if (value.startsWith("projects/")) return value.replace(/\/+$/, "");
95 if (value.includes("@")) {
96 return `projects/${project}/serviceAccounts/${value}`;
97 }
98 return `projects/${project}/serviceAccounts/${value}@${project}.iam.gserviceaccount.com`;
99 };
100
101 export const userLabels = (
102 labels: Record<string, string | undefined> | null | undefined,
103 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
104
105 export const stringMap = (
106 value: Record<string, string | undefined> | null | undefined,
107 ): Record<string, string> =>
108 Object.fromEntries(
109 Object.entries(value ?? {}).filter(
110 (entry): entry is [string, string] => typeof entry[1] === "string",
111 ),
112 );
113
114 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
115 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
116
117 export const canonical = (value: unknown): unknown => {
118 if (value === undefined || value === null) return undefined;
119 if (typeof value === "boolean" || typeof value === "number") return value;
120 if (typeof value === "string") {
121 return value.length === 0 ? undefined : value;
122 }
123 if (Array.isArray(value)) {
124 const items = value.map(canonical).filter((item) => item !== undefined);
125 return items.length === 0 ? undefined : items;
126 }
127 if (typeof value === "object") {
128 const entries = Object.entries(value as Record<string, unknown>)
129 .map(([key, item]) => [key, canonical(item)] as const)
130 .filter(([, item]) => item !== undefined)
131 .sort(([left], [right]) => left.localeCompare(right));
132 if (entries.length === 0) return undefined;
133 return Object.fromEntries(entries);
134 }
135 return undefined;
136 };
137
138 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
139
140 export const fieldMask = (fields: Array<string | false | undefined>) =>
141 fields.filter((field): field is string => typeof field === "string").join(",");
142
143 export const sameText = (left: string | undefined, right: string | undefined) =>
144 (left ?? "") === (right ?? "");
145
146 export const replaceOnIdentity = (input: {
147 previousId: string | undefined;
148 nextId: string | undefined;
149 previousLocation: string;
150 nextLocation: string;
151 extra?: boolean;
152 }) => {
153 const replace =
154 (input.extra ?? false) ||
155 (input.previousId !== undefined &&
156 input.nextId !== undefined &&
157 input.nextId !== input.previousId) ||
158 input.previousLocation !== input.nextLocation;
159 if (!replace) return undefined;
160 const samePhysical =
161 input.previousLocation === input.nextLocation &&
162 input.previousId !== undefined &&
163 input.nextId === input.previousId;
164 return {
165 action: "replace" as const,
166 deleteFirst: samePhysical,
167 };
168 };
169
170 /**
171 * Wait for an Infrastructure Manager operation; previews and deployment
172 * groups run Terraform and can take several minutes. ALREADY_EXISTS
173 * (code 6) counts as success (create race); with `notFoundOk`, so does
174 * NOT_FOUND (code 5, delete race).
175 */
176 export const waitForOperation = (operation: config.Operation, options?: { notFoundOk?: boolean }) =>
177 waitForGcpOperation(operation, (name) => config.getProjectsLocationsOperations({ name }), {
178 budget: "20 minutes",
179 }).pipe(
180 Effect.catchIf(
181 (error) =>
182 error._tag === "GCP.OperationFailed" &&
183 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
184 () => Effect.succeed(operation),
185 ),
186 );
187
188 export const waitUntilExists = <A, E, R>(
189 get: Effect.Effect<A | undefined, E, R>,
190 name: string,
191 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
192 get.pipe(
193 Effect.filterOrFail(
194 (value): value is NonNullable<A> => value != null,
195 () => new ResourceNotResolved({ resourceName: name }),
196 ),
197 Effect.retry({
198 while: (error) => error instanceof ResourceNotResolved,
199 times: 8,
200 schedule: Schedule.spaced("1 second"),
201 }),
202 );
203
204 export const waitUntilGone = <A, E, R>(
205 get: Effect.Effect<A | undefined, E, R>,
206 name: string,
207 ): Effect.Effect<void, E | ResourceStillExists, R> =>
208 get.pipe(
209 Effect.filterOrFail(
210 (value) => value === undefined,
211 () => new ResourceStillExists({ resourceName: name }),
212 ),
213 Effect.retry({
214 while: (error) => error instanceof ResourceStillExists,
215 times: 10,
216 schedule: Schedule.spaced("2 seconds"),
217 }),
218 Effect.asVoid,
219 );
220
221 export const listAtLocation = <A, E, R>(
222 project: string,
223 region: string,
224 list: (parent: string) => Effect.Effect<A[], E, R>,
225 ): Effect.Effect<A[], E, R> =>
226 // Prefer the all-locations wildcard; fall back to the default region
227 // (whose error, if any, propagates).
228 list(`projects/${project}/locations/-`).pipe(
229 Effect.catch(() => list(`projects/${project}/locations/${region}`)),
230 );
231
232 export const listLabeledPages = <Page, A, E, R>(
233 pages: Stream.Stream<Page, E, R>,
234 items: (page: Page) => readonly A[] | undefined,
235 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
236 ): Effect.Effect<A[], E, R> =>
237 pages.pipe(
238 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
239 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
240 Stream.runCollect,
241 Effect.map((chunk) => Array.from(chunk)),
242 );