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

main
ts 275 lines 9.24 KB
Raw
1 import * as eventarc from "@distilled.cloud/gcp/eventarc_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 {
11 type LongRunningOperation,
12 waitForOperation as waitForLongRunningOperation,
13 } from "../Operation.ts";
14
15 export const MAX_NAME_LENGTH = 63;
16
17 export class EventarcNotResolved extends Data.TaggedError("GCP.Eventarc.NotResolved")<{
18 resourceName: string;
19 }> {}
20
21 export class EventarcStillExists extends Data.TaggedError("GCP.Eventarc.StillExists")<{
22 resourceName: string;
23 }> {}
24
25 export type LoggingConfig = {
26 /**
27 * Minimum log severity sent to Cloud Logging (`NONE`, `DEBUG`,
28 * `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`,
29 * `EMERGENCY`).
30 */
31 logSeverity?: eventarc.LoggingConfigLogSeverityEnum | (string & {});
32 };
33
34 export const lastSegment = (value: string) => {
35 const trimmed = value.replace(/\/+$/, "");
36 const parts = trimmed.split("/");
37 return parts[parts.length - 1] || trimmed;
38 };
39
40 export const rfc1035 = (
41 name: string,
42 fallback = "resource",
43 maxLength = MAX_NAME_LENGTH,
44 ): string => {
45 let next = name
46 .toLowerCase()
47 .replace(/[^a-z0-9-]/g, "-")
48 .replace(/-+/g, "-")
49 .replace(/^-+/, "")
50 .replace(/-+$/, "");
51 if (!/^[a-z]/.test(next)) {
52 next = `e${next}`;
53 }
54 next = next.slice(0, maxLength).replace(/-+$/, "");
55 return next.length > 0 ? next : fallback;
56 };
57
58 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
59 lastSegment(location ?? defaultLocation).toLowerCase();
60
61 export const parentOf = (project: string, location: string) =>
62 `projects/${project}/locations/${location}`;
63
64 export const resourceName = (project: string, location: string, collection: string, id: string) =>
65 `projects/${project}/locations/${location}/${collection}/${id}`;
66
67 export const parseName = (name: string, collection: string, defaultLocation: string) => {
68 const parts = name.split("/").filter((part) => part.length > 0);
69 const collectionAt = parts.lastIndexOf(collection);
70 const locationsAt = parts.lastIndexOf("locations");
71 const projectsAt = parts.lastIndexOf("projects");
72 return {
73 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
74 location:
75 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
76 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
77 };
78 };
79
80 export const toPhysicalId = (
81 id: string,
82 explicit: string | undefined,
83 existing: string | undefined,
84 fallback = "resource",
85 maxLength = MAX_NAME_LENGTH,
86 ) =>
87 Effect.gen(function* () {
88 if (explicit !== undefined) return rfc1035(explicit, fallback, maxLength);
89 if (existing !== undefined) return existing;
90 return rfc1035(
91 yield* createPhysicalName({
92 id,
93 maxLength,
94 lowercase: true,
95 }),
96 fallback,
97 maxLength,
98 );
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 userAnnotations = (
106 annotations: Record<string, string | undefined> | null | undefined,
107 ): Record<string, string> => tagRecord(annotations);
108
109 export const hasAlchemyLabelKeys = (
110 labels: Record<string, string | undefined> | null | undefined,
111 ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
112
113 export const expandResource = (
114 value: string,
115 project: string,
116 location: string,
117 collection: string,
118 ) => {
119 const trimmed = value.replace(/\/+$/, "");
120 if (trimmed.includes(`/${collection}/`)) return trimmed;
121 return resourceName(project, location, collection, lastSegment(trimmed));
122 };
123
124 export const expandTopic = (value: string, project: string) => {
125 const trimmed = value.replace(/\/+$/, "");
126 if (trimmed.includes("/topics/")) return trimmed;
127 return `projects/${project}/topics/${lastSegment(trimmed)}`;
128 };
129
130 export const toLoggingConfig = (
131 config: LoggingConfig | eventarc.LoggingConfig | undefined,
132 ): LoggingConfig | undefined => {
133 const logSeverity = config?.logSeverity;
134 if (logSeverity === undefined || logSeverity.length === 0) return undefined;
135 return { logSeverity };
136 };
137
138 export const loggingKey = (config: LoggingConfig | eventarc.LoggingConfig | undefined) =>
139 toLoggingConfig(config)?.logSeverity ?? "";
140
141 export const cryptoKeyKey = (name: string | undefined) =>
142 name === undefined || name.length === 0 ? "" : name;
143
144 export const textKey = (value: string | undefined) => value ?? "";
145
146 export const sameJson = (left: unknown, right: unknown) =>
147 JSON.stringify(canonical(left) ?? null) === JSON.stringify(canonical(right) ?? null);
148
149 export const canonical = (value: unknown): unknown => {
150 if (value === undefined || value === null) return undefined;
151 if (typeof value === "boolean" || typeof value === "number") return value;
152 if (typeof value === "string") {
153 return value.length === 0 ? undefined : value;
154 }
155 if (Array.isArray(value)) {
156 const items = value.map(canonical).filter((item) => item !== undefined);
157 return items.length === 0 ? undefined : items;
158 }
159 if (typeof value === "object") {
160 const entries = Object.entries(value as Record<string, unknown>)
161 .map(([key, item]) => [key, canonical(item)] as const)
162 .filter(([, item]) => item !== undefined)
163 .sort(([left], [right]) => left.localeCompare(right));
164 if (entries.length === 0) return undefined;
165 return Object.fromEntries(entries);
166 }
167 return undefined;
168 };
169
170 export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) =>
171 pairs.filter(([, changed]) => changed).map(([field]) => field);
172
173 export const compact = <T extends Record<string, unknown>>(value: T): T => {
174 const next: Record<string, unknown> = {};
175 for (const [key, entry] of Object.entries(value)) {
176 if (entry !== undefined && entry !== "") next[key] = entry;
177 }
178 return next as T;
179 };
180
181 /**
182 * Wait on an Eventarc long-running operation. Pipelines and enrollments
183 * routinely take ~4 minutes. `ALREADY_EXISTS` (a create race) counts as
184 * success; `NOT_FOUND` does too when `notFoundOk` (deletes).
185 */
186 export const waitForOperation = (
187 operation: eventarc.GoogleLongrunningOperation,
188 options?: { notFoundOk?: boolean },
189 ) =>
190 waitForLongRunningOperation(
191 operation,
192 (name) => {
193 const get = eventarc.getProjectsLocationsOperations({ name });
194 const observe: Effect.Effect<
195 LongRunningOperation,
196 eventarc.GetProjectsLocationsOperationsError,
197 GcpOpContext
198 > =
199 options?.notFoundOk === true
200 ? get.pipe(
201 Effect.catchTag("NotFound", () =>
202 Effect.succeed<LongRunningOperation>({ name, done: true }),
203 ),
204 )
205 : get.pipe(
206 // A just-returned operation can briefly 404 on read.
207 Effect.retry({
208 while: (error) => error._tag === "NotFound",
209 times: 5,
210 schedule: Schedule.exponential("250 millis"),
211 }),
212 );
213 return observe;
214 },
215 { budget: "15 minutes" },
216 ).pipe(
217 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
218 Effect.catchTag("GCP.OperationFailed", (error) =>
219 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
220 ? Effect.succeed<LongRunningOperation>(operation)
221 : Effect.fail(error),
222 ),
223 );
224
225 export const retryOnTransient = <A, E extends { readonly _tag: string }, R>(
226 effect: Effect.Effect<A, E, R>,
227 ) =>
228 effect.pipe(
229 Effect.retry({
230 while: (error) => error._tag === "Conflict" || error._tag === "GCP.OperationFailed",
231 times: 8,
232 schedule: Schedule.spaced("3 seconds"),
233 }),
234 );
235
236 export const waitUntilPresent = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
237 get.pipe(
238 Effect.flatMap((value) =>
239 value ? Effect.succeed(value) : Effect.fail(new EventarcNotResolved({ resourceName: name })),
240 ),
241 Effect.retry({
242 while: (error) => error instanceof EventarcNotResolved,
243 times: 8,
244 schedule: Schedule.spaced("1 second"),
245 }),
246 );
247
248 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
249 get.pipe(
250 Effect.flatMap((value) =>
251 value === undefined
252 ? Effect.void
253 : Effect.fail(new EventarcStillExists({ resourceName: name })),
254 ),
255 Effect.retry({
256 while: (error) => error instanceof EventarcStillExists,
257 times: 10,
258 schedule: Schedule.spaced("2 seconds"),
259 }),
260 );
261
262 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
263 stream: Stream.Stream<Page, E, R>,
264 pick: (page: Page) => readonly Item[] | undefined,
265 ) =>
266 stream.pipe(
267 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
268 Stream.runCollect,
269 Effect.map((chunk) => Array.from(chunk)),
270 // A missing parent location lists as empty.
271 Effect.catchIf(
272 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
273 () => Effect.succeed<Item[]>([]),
274 ),
275 );