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

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