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

main
ts 321 lines 10.9 KB
Raw
1 import * as gkebackup from "@distilled.cloud/gcp/gkebackup_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 waitForLongRunning, type LongRunningOperation } from "../Operation.ts";
10
11 export const MAX_NAME_LENGTH = 63;
12
13 export class ResourceNotResolved extends Data.TaggedError("GCP.GKEBackup.ResourceNotResolved")<{
14 resourceName: string;
15 }> {}
16
17 export class ResourceStillExists extends Data.TaggedError("GCP.GKEBackup.ResourceStillExists")<{
18 resourceName: string;
19 }> {}
20
21 export class ResourceNotReady extends Data.TaggedError("GCP.GKEBackup.ResourceNotReady")<{
22 resourceName: string;
23 state: string;
24 }> {}
25
26 export class ResourceFailed extends Data.TaggedError("GCP.GKEBackup.ResourceFailed")<{
27 resourceName: string;
28 state: string;
29 details: 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 = "gkebackup"): string => {
39 let next = name
40 .toLowerCase()
41 .replace(/[^a-z0-9-]/g, "-")
42 .replace(/-+/g, "-")
43 .replace(/^-+|-+$/g, "");
44 if (!/^[a-z]/.test(next)) next = `g${next}`;
45 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
46 if (next.length === 0) return fallback;
47 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
48 return next.slice(0, MAX_NAME_LENGTH);
49 };
50
51 export const normalizeLocation = (location: string | undefined, fallback: string) =>
52 lastSegment(location ?? fallback).toLowerCase();
53
54 export const parentOf = (project: string, location: string) =>
55 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
56
57 export const toPhysicalId = (
58 id: string,
59 explicit: string | undefined,
60 existing: string | undefined,
61 fallback = "gkebackup",
62 ) =>
63 Effect.gen(function* () {
64 if (explicit !== undefined) return rfc1035(explicit, fallback);
65 if (existing !== undefined) return existing;
66 return rfc1035(
67 yield* createPhysicalName({
68 id,
69 maxLength: MAX_NAME_LENGTH,
70 lowercase: true,
71 }),
72 fallback,
73 );
74 });
75
76 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
77 const parts = name.split("/").filter((part) => part.length > 0);
78 const collectionAt = parts.lastIndexOf(collection);
79 const locationsAt = parts.lastIndexOf("locations");
80 const projectsAt = parts.lastIndexOf("projects");
81 return {
82 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
83 location:
84 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
85 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
86 parent:
87 collectionAt > 0
88 ? parts.slice(0, collectionAt).join("/")
89 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
90 };
91 };
92
93 export const expandParent = (
94 value: string,
95 project: string,
96 location: string,
97 collection: string,
98 ) => {
99 if (value.includes("/")) return value.replace(/\/+$/, "");
100 return `projects/${project}/locations/${location}/${collection}/${value}`;
101 };
102
103 export const projectName = (value: string | undefined, project: string) => {
104 const next = (value ?? project).replace(/\/+$/, "");
105 if (next.startsWith("projects/")) return next;
106 return `projects/${next}`;
107 };
108
109 export const clusterName = (value: string, project: string, location: string) => {
110 if (value.includes("/")) return value.replace(/\/+$/, "");
111 return `projects/${project}/locations/${location}/clusters/${value}`;
112 };
113
114 export const userLabels = (
115 labels: Record<string, string | undefined> | null | undefined,
116 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
117
118 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
119 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
120
121 export const canonical = (value: unknown): unknown => {
122 if (value === undefined || value === null) return undefined;
123 if (typeof value === "boolean" || typeof value === "number") return value;
124 if (typeof value === "string") {
125 return value.length === 0 ? undefined : value;
126 }
127 if (Array.isArray(value)) {
128 const items = value.map(canonical).filter((item) => item !== undefined);
129 return items.length === 0 ? undefined : items;
130 }
131 if (typeof value === "object") {
132 const entries = Object.entries(value as Record<string, unknown>)
133 .map(([key, item]) => [key, canonical(item)] as const)
134 .filter(([, item]) => item !== undefined)
135 .sort(([left], [right]) => left.localeCompare(right));
136 if (entries.length === 0) return undefined;
137 return Object.fromEntries(entries);
138 }
139 return undefined;
140 };
141
142 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
143
144 export const fieldMask = (fields: Array<string | false | undefined>) =>
145 fields.filter((field): field is string => typeof field === "string").join(",");
146
147 export const sameText = (left: string | undefined, right: string | undefined) =>
148 (left ?? "") === (right ?? "");
149
150 export const replaceOnIdentity = (input: {
151 previousId: string | undefined;
152 nextId: string | undefined;
153 previousLocation: string;
154 nextLocation: string;
155 extra?: boolean;
156 previousParent?: string;
157 nextParent?: string;
158 }) => {
159 const parentChanged =
160 (input.previousParent ?? "") !== "" &&
161 (input.nextParent ?? "") !== "" &&
162 (input.previousParent ?? "") !== (input.nextParent ?? "");
163 const replace =
164 (input.extra ?? false) ||
165 parentChanged ||
166 (input.previousId !== undefined &&
167 input.nextId !== undefined &&
168 input.nextId !== input.previousId) ||
169 input.previousLocation !== input.nextLocation;
170 if (!replace) return undefined;
171 const samePhysical =
172 input.previousLocation === input.nextLocation &&
173 !parentChanged &&
174 input.previousId !== undefined &&
175 input.nextId === input.previousId;
176 return {
177 action: "replace" as const,
178 deleteFirst: samePhysical,
179 };
180 };
181
182 const READY_STATES = new Set(["READY", "SUCCEEDED", "DEACTIVATED", "IN_USE"]);
183 const FAILED_STATES = new Set(["FAILED", "ERROR"]);
184
185 export const isReadyState = (state: string | undefined) =>
186 READY_STATES.has((state ?? "").toUpperCase());
187
188 export const isFailedState = (state: string | undefined) =>
189 FAILED_STATES.has((state ?? "").toUpperCase());
190
191 export const waitUntilExists = <A, E extends { readonly _tag: string }, R>(
192 get: Effect.Effect<A, E, R>,
193 name: string,
194 ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> =>
195 get.pipe(
196 Effect.filterOrFail(
197 (value): value is Exclude<A, undefined> => value !== undefined,
198 () => new ResourceNotResolved({ resourceName: name }),
199 ),
200 Effect.retry({
201 while: (error) => error._tag === "GCP.GKEBackup.ResourceNotResolved",
202 times: 8,
203 schedule: Schedule.spaced("1 second"),
204 }),
205 );
206
207 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
208 get: Effect.Effect<A, E, R>,
209 name: string,
210 ): Effect.Effect<void, E | ResourceStillExists, R> =>
211 get.pipe(
212 Effect.filterOrFail(
213 (value) => value === undefined,
214 () => new ResourceStillExists({ resourceName: name }),
215 ),
216 Effect.asVoid,
217 Effect.retry({
218 while: (error) => error._tag === "GCP.GKEBackup.ResourceStillExists",
219 times: 10,
220 schedule: Schedule.spaced("2 seconds"),
221 }),
222 );
223
224 export const waitUntilReady = <A, E extends { readonly _tag: string }, R>(
225 get: Effect.Effect<A, E, R>,
226 name: string,
227 stateOf: (value: Exclude<A, undefined>) => string | undefined,
228 detailsOf?: (value: Exclude<A, undefined>) => string | undefined,
229 options?: {
230 times?: number;
231 interval?: `${number} seconds`;
232 },
233 ): Effect.Effect<
234 Exclude<A, undefined>,
235 E | ResourceNotResolved | ResourceFailed | ResourceNotReady,
236 R
237 > =>
238 get.pipe(
239 Effect.filterOrFail(
240 (value): value is Exclude<A, undefined> => value !== undefined,
241 () => new ResourceNotResolved({ resourceName: name }),
242 ),
243 Effect.filterOrFail(
244 (value) => !isFailedState(stateOf(value)),
245 (value) =>
246 new ResourceFailed({
247 resourceName: name,
248 state: stateOf(value) ?? "",
249 details: detailsOf?.(value),
250 }),
251 ),
252 Effect.filterOrFail(
253 (value) => {
254 const state = stateOf(value) ?? "";
255 return isReadyState(state) || state.length === 0;
256 },
257 (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }),
258 ),
259 Effect.retry({
260 while: (error) =>
261 error._tag === "GCP.GKEBackup.ResourceNotReady" ||
262 error._tag === "GCP.GKEBackup.ResourceNotResolved",
263 times: options?.times ?? 10,
264 schedule: Schedule.spaced(options?.interval ?? "3 seconds"),
265 }),
266 );
267
268 /** Every location at once: the API accepts the `locations/-` wildcard. */
269 export const listAtLocation = <A, E, R>(
270 project: string,
271 list: (parent: string) => Effect.Effect<A[], E, R>,
272 ) => list(`projects/${project}/locations/-`);
273
274 /** Children of every parent in every location (`locations/-/{nested}`). */
275 export const listAtNested = <A, E, R>(
276 project: string,
277 nested: string,
278 list: (parent: string) => Effect.Effect<A[], E, R>,
279 ) => list(`projects/${project}/locations/-/${nested}`);
280
281 export const listLabeledPages = <Page, A, E, R>(
282 pages: Stream.Stream<Page, E, R>,
283 items: (page: Page) => readonly A[] | undefined,
284 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
285 ) =>
286 pages.pipe(
287 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
288 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
289 Stream.runCollect,
290 Effect.map((chunk) => Array.from(chunk)),
291 );
292
293 /** Backups and restores of cluster workloads take up to ~20 minutes. */
294 const OPERATION_BUDGET = "30 minutes";
295
296 /**
297 * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a
298 * concurrent create won the race; reconcile observes the resource next.
299 */
300 export const waitForOperation = (operation: LongRunningOperation) =>
301 waitForLongRunning(operation, (name) => gkebackup.getProjectsLocationsOperations({ name }), {
302 budget: OPERATION_BUDGET,
303 }).pipe(
304 Effect.catchIf(
305 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
306 () => Effect.succeed(operation),
307 ),
308 );
309
310 /**
311 * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5)
312 * means the resource is already gone.
313 */
314 export const waitForDeleteOperation = (operation: LongRunningOperation) =>
315 waitForOperation(operation).pipe(
316 Effect.catchIf(
317 (error) =>
318 error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5),
319 () => Effect.succeed(operation),
320 ),
321 );