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

main
ts 296 lines 9.96 KB
Raw
1 import * as file from "@distilled.cloud/gcp/file_v1";
2 import type { GcpOpContext } from "@distilled.cloud/gcp/Protocol";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import { tagRecord } from "alchemy/Tags";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { stripInternalLabels } from "../Labels.ts";
10 import { waitForOperation as waitForLongRunningOperation } from "../Operation.ts";
11
12 export const DEFAULT_ZONE = "us-central1-a";
13 export const DEFAULT_SHARE_NAME = "share1";
14 export const MAX_NAME_LENGTH = 63;
15
16 export class ResourceNotResolved extends Data.TaggedError("GCP.Filestore.ResourceNotResolved")<{
17 resourceName: string;
18 }> {}
19
20 export class ResourceStillExists extends Data.TaggedError("GCP.Filestore.ResourceStillExists")<{
21 resourceName: string;
22 }> {}
23
24 export class ResourceNotReady extends Data.TaggedError("GCP.Filestore.ResourceNotReady")<{
25 resourceName: string;
26 state: string;
27 }> {}
28
29 export class ResourceFailed extends Data.TaggedError("GCP.Filestore.ResourceFailed")<{
30 resourceName: string;
31 state: string;
32 }> {}
33
34 export const lastSegment = (value: string | undefined) => {
35 if (value === undefined || value.length === 0) return "";
36 const trimmed = value.replace(/\/+$/, "");
37 const parts = trimmed.split("/");
38 return parts[parts.length - 1] || trimmed;
39 };
40
41 export const rfc1035 = (name: string, fallback = "filestore"): string => {
42 let next = name
43 .toLowerCase()
44 .replace(/[^a-z0-9-]/g, "-")
45 .replace(/-+/g, "-")
46 .replace(/^-+|-+$/g, "");
47 if (!/^[a-z]/.test(next)) next = `f${next}`;
48 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
49 if (next.length === 0) return fallback;
50 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
51 return next.slice(0, MAX_NAME_LENGTH);
52 };
53
54 export const normalizeLocation = (location: string | undefined, fallback: string) =>
55 lastSegment(location ?? fallback).toLowerCase();
56
57 export const regionOf = (location: string) => {
58 const parts = location.split("-");
59 const last = parts[parts.length - 1];
60 if (last !== undefined && last.length === 1) {
61 return parts.slice(0, -1).join("-");
62 }
63 return location;
64 };
65
66 export const toPhysicalId = (
67 id: string,
68 explicit: string | undefined,
69 existing: string | undefined,
70 fallback = "filestore",
71 ) =>
72 Effect.gen(function* () {
73 if (explicit !== undefined) return rfc1035(explicit, fallback);
74 if (existing !== undefined) return existing;
75 return rfc1035(
76 yield* createPhysicalName({
77 id,
78 maxLength: MAX_NAME_LENGTH,
79 lowercase: true,
80 }),
81 fallback,
82 );
83 });
84
85 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
86 const parts = name.split("/").filter((part) => part.length > 0);
87 const collectionAt = parts.lastIndexOf(collection);
88 const locationsAt = parts.lastIndexOf("locations");
89 const projectsAt = parts.lastIndexOf("projects");
90 return {
91 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
92 location:
93 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
94 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
95 parent:
96 collectionAt > 0
97 ? parts.slice(0, collectionAt).join("/")
98 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
99 };
100 };
101
102 export const expandParent = (
103 value: string,
104 project: string,
105 location: string,
106 collection: string,
107 ) => {
108 if (value.includes("/")) return value.replace(/\/+$/, "");
109 return `projects/${project}/locations/${location}/${collection}/${value}`;
110 };
111
112 export const userLabels = (
113 labels: Record<string, string | undefined> | null | undefined,
114 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
115
116 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
117 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
118
119 export const fieldMask = (fields: Array<string | false | undefined>) =>
120 fields.filter((field): field is string => typeof field === "string").join(",");
121
122 export const replaceOnIdentity = (input: {
123 previousId: string | undefined;
124 nextId: string | undefined;
125 previousLocation: string;
126 nextLocation: string;
127 extra?: boolean;
128 previousParent?: string;
129 nextParent?: string;
130 }) => {
131 const parentChanged =
132 (input.previousParent ?? "") !== "" &&
133 (input.nextParent ?? "") !== "" &&
134 (input.previousParent ?? "") !== (input.nextParent ?? "");
135 const replace =
136 (input.extra ?? false) ||
137 parentChanged ||
138 (input.previousId !== undefined &&
139 input.nextId !== undefined &&
140 input.nextId !== input.previousId) ||
141 input.previousLocation !== input.nextLocation;
142 if (!replace) return undefined;
143 const samePhysical =
144 input.previousLocation === input.nextLocation &&
145 !parentChanged &&
146 input.previousId !== undefined &&
147 input.nextId === input.previousId;
148 return {
149 action: "replace" as const,
150 deleteFirst: samePhysical,
151 };
152 };
153
154 const READY_STATES = new Set(["READY"]);
155 const FAILED_STATES = new Set(["INVALID", "ERROR"]);
156
157 export const isReadyState = (state: string | undefined) =>
158 READY_STATES.has((state ?? "").toUpperCase());
159
160 export const isFailedState = (state: string | undefined) =>
161 FAILED_STATES.has((state ?? "").toUpperCase());
162
163 export const isDeletingState = (state: string | undefined) =>
164 (state ?? "").toUpperCase() === "DELETING";
165
166 /**
167 * Wait on a Filestore long-running operation. Instances, backups, and snapshots take 5–20 minutes.
168 * `ALREADY_EXISTS` (a create race) counts as success; so does `NOT_FOUND`
169 * when `notFoundOk` (deletes). Returns the final operation.
170 */
171 export const waitForOperation = (operation: file.Operation, options?: { notFoundOk?: boolean }) =>
172 Effect.suspend(() => {
173 let latest = operation;
174 return waitForLongRunningOperation(
175 operation,
176 (name) => {
177 const get = file.getProjectsLocationsOperations({ name }).pipe(
178 Effect.tap((current) =>
179 Effect.sync(() => {
180 latest = current;
181 }),
182 ),
183 );
184 const observe: Effect.Effect<
185 file.Operation,
186 file.GetProjectsLocationsOperationsError,
187 GcpOpContext
188 > =
189 options?.notFoundOk === true
190 ? get.pipe(
191 Effect.catchTag("NotFound", () =>
192 Effect.succeed<file.Operation>({ name, done: true }),
193 ),
194 )
195 : get.pipe(
196 // A just-returned operation can briefly 404 on read.
197 Effect.retry({
198 while: (error) => error._tag === "NotFound",
199 times: 5,
200 schedule: Schedule.exponential("250 millis"),
201 }),
202 );
203 return observe;
204 },
205 { budget: "30 minutes", interval: "10 seconds" },
206 ).pipe(
207 Effect.map(() => latest),
208 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
209 Effect.catchTag("GCP.OperationFailed", (error) =>
210 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
211 ? Effect.succeed(latest)
212 : Effect.fail(error),
213 ),
214 );
215 });
216
217 export const waitUntilExists = <A, E extends { readonly _tag: string }, R>(
218 get: Effect.Effect<A | undefined, E, R>,
219 name: string,
220 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
221 get.pipe(
222 Effect.filterOrFail(
223 (value): value is NonNullable<A> => value != null,
224 () => new ResourceNotResolved({ resourceName: name }),
225 ),
226 Effect.retry({
227 while: (error) => error._tag === "GCP.Filestore.ResourceNotResolved",
228 times: 8,
229 schedule: Schedule.spaced("1 second"),
230 }),
231 );
232
233 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
234 get: Effect.Effect<A | undefined, E, R>,
235 name: string,
236 ): Effect.Effect<void, E | ResourceStillExists, R> =>
237 get.pipe(
238 Effect.filterOrFail(
239 (value) => value === undefined,
240 () => new ResourceStillExists({ resourceName: name }),
241 ),
242 Effect.retry({
243 while: (error) => error._tag === "GCP.Filestore.ResourceStillExists",
244 // Backup and snapshot deletion takes several minutes.
245 times: 120,
246 schedule: Schedule.spaced("10 seconds"),
247 }),
248 Effect.asVoid,
249 );
250
251 export const waitUntilReady = <A, E extends { readonly _tag: string }, R>(
252 get: Effect.Effect<A | undefined, E, R>,
253 name: string,
254 stateOf: (value: NonNullable<A>) => string | undefined,
255 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceFailed | ResourceNotReady, R> =>
256 get.pipe(
257 Effect.filterOrFail(
258 (value): value is NonNullable<A> => value != null,
259 () => new ResourceNotResolved({ resourceName: name }),
260 ),
261 Effect.filterOrFail(
262 (value) => !isFailedState(stateOf(value)),
263 (value) =>
264 new ResourceFailed({
265 resourceName: name,
266 state: stateOf(value) ?? "",
267 }),
268 ),
269 Effect.filterOrFail(
270 (value) => {
271 const state = stateOf(value) ?? "";
272 return isReadyState(state) || state.length === 0;
273 },
274 (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }),
275 ),
276 Effect.retry({
277 while: (error) =>
278 error._tag === "GCP.Filestore.ResourceNotReady" ||
279 error._tag === "GCP.Filestore.ResourceNotResolved",
280 // Backups and snapshots take several minutes to become READY.
281 times: 120,
282 schedule: Schedule.spaced("10 seconds"),
283 }),
284 );
285
286 export const listLabeledPages = <Page, A, E, R>(
287 pages: Stream.Stream<Page, E, R>,
288 items: (page: Page) => readonly A[] | undefined,
289 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
290 ) =>
291 pages.pipe(
292 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
293 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
294 Stream.runCollect,
295 Effect.map((chunk) => Array.from(chunk)),
296 );