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

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