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

main
ts 348 lines 11.9 KB
Raw
1 import * as clouddeploy from "@distilled.cloud/gcp/clouddeploy_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 MAX_NAME_LENGTH = 63;
13
14 export class ResourceNotResolved extends Data.TaggedError("GCP.CloudDeploy.ResourceNotResolved")<{
15 resourceName: string;
16 }> {}
17
18 export class ResourceStillExists extends Data.TaggedError("GCP.CloudDeploy.ResourceStillExists")<{
19 resourceName: string;
20 }> {}
21
22 export const lastSegment = (value: string) => {
23 const trimmed = value.replace(/\/+$/, "");
24 const parts = trimmed.split("/");
25 return parts[parts.length - 1] || trimmed;
26 };
27
28 export const rfc1035 = (name: string, fallback = "clouddeploy"): string => {
29 let next = name
30 .toLowerCase()
31 .replace(/[^a-z0-9-]/g, "-")
32 .replace(/-+/g, "-")
33 .replace(/^-+|-+$/g, "");
34 if (!/^[a-z]/.test(next)) next = `c${next}`;
35 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
36 if (next.length === 0) return fallback;
37 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
38 return next.slice(0, MAX_NAME_LENGTH);
39 };
40
41 export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
42
43 export const parentOf = (project: string, location: string) =>
44 `projects/${project}/locations/${normalizeLocation(location)}`;
45
46 export const toPhysicalId = (
47 id: string,
48 explicit: string | undefined,
49 existing: string | undefined,
50 fallback = "clouddeploy",
51 ) =>
52 Effect.gen(function* () {
53 if (explicit !== undefined) return rfc1035(explicit, fallback);
54 if (existing !== undefined) return existing;
55 return rfc1035(
56 yield* createPhysicalName({
57 id,
58 maxLength: MAX_NAME_LENGTH,
59 lowercase: true,
60 }),
61 fallback,
62 );
63 });
64
65 export const parseName = (name: string, collection: string) => {
66 const parts = name.split("/").filter((part) => part.length > 0);
67 const collectionAt = parts.lastIndexOf(collection);
68 const locationsAt = parts.lastIndexOf("locations");
69 const projectsAt = parts.lastIndexOf("projects");
70 return {
71 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
72 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
73 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
74 parent:
75 collectionAt > 0
76 ? parts.slice(0, collectionAt).join("/")
77 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
78 };
79 };
80
81 export const expandParent = (
82 value: string,
83 project: string,
84 location: string,
85 collection: string,
86 ) => {
87 if (value.includes("/")) return value.replace(/\/+$/, "");
88 return `projects/${project}/locations/${location}/${collection}/${value}`;
89 };
90
91 export const gkeClusterName = (value: string, project: string, location: string) => {
92 if (value.includes("/")) return value.replace(/\/+$/, "");
93 return `projects/${project}/locations/${location}/clusters/${value}`;
94 };
95
96 export const runLocationName = (value: string, project: string, location: string) => {
97 if (value.startsWith("projects/")) return value.replace(/\/+$/, "");
98 return `projects/${project}/locations/${lastSegment(value) || location}`;
99 };
100
101 export const membershipName = (value: string, project: string, location: string) => {
102 if (value.includes("/")) return value.replace(/\/+$/, "");
103 return `projects/${project}/locations/${location}/memberships/${value}`;
104 };
105
106 export const userLabels = (
107 labels: Record<string, string | undefined> | null | undefined,
108 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
109
110 export const stringMap = (
111 value: Record<string, string | undefined> | null | undefined,
112 ): Record<string, string> =>
113 Object.fromEntries(
114 Object.entries(value ?? {}).filter(
115 (entry): entry is [string, string] => typeof entry[1] === "string",
116 ),
117 );
118
119 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
120 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
121
122 export const canonical = (value: unknown): unknown => {
123 if (value === undefined || value === null) return undefined;
124 if (typeof value === "boolean" || typeof value === "number") return value;
125 if (typeof value === "string") {
126 return value.length === 0 ? undefined : value;
127 }
128 if (Array.isArray(value)) {
129 const items = value.map(canonical).filter((item) => item !== undefined);
130 return items.length === 0 ? undefined : items;
131 }
132 if (typeof value === "object") {
133 const entries = Object.entries(value as Record<string, unknown>)
134 .map(([key, item]) => [key, canonical(item)] as const)
135 .filter(([, item]) => item !== undefined)
136 .sort(([left], [right]) => left.localeCompare(right));
137 if (entries.length === 0) return undefined;
138 return Object.fromEntries(entries);
139 }
140 return undefined;
141 };
142
143 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
144
145 export const fieldMask = (fields: Array<string | false | undefined>) =>
146 fields.filter((field): field is string => typeof field === "string").join(",");
147
148 export const sameText = (left: string | undefined, right: string | undefined) =>
149 (left ?? "") === (right ?? "");
150
151 export const sameBool = (left: boolean | undefined, right: boolean | undefined) =>
152 (left ?? false) === (right ?? false);
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 export const stripAutomationRule = (
187 rule: clouddeploy.AutomationRule,
188 ): clouddeploy.AutomationRule => ({
189 advanceRolloutRule: rule.advanceRolloutRule
190 ? {
191 id: rule.advanceRolloutRule.id,
192 wait: rule.advanceRolloutRule.wait,
193 sourcePhases: rule.advanceRolloutRule.sourcePhases,
194 }
195 : undefined,
196 promoteReleaseRule: rule.promoteReleaseRule
197 ? {
198 id: rule.promoteReleaseRule.id,
199 destinationTargetId: rule.promoteReleaseRule.destinationTargetId,
200 destinationPhase: rule.promoteReleaseRule.destinationPhase,
201 wait: rule.promoteReleaseRule.wait,
202 }
203 : undefined,
204 repairRolloutRule: rule.repairRolloutRule
205 ? {
206 id: rule.repairRolloutRule.id,
207 phases: rule.repairRolloutRule.phases,
208 repairPhases: rule.repairRolloutRule.repairPhases,
209 jobs: rule.repairRolloutRule.jobs,
210 }
211 : undefined,
212 timedPromoteReleaseRule: rule.timedPromoteReleaseRule
213 ? {
214 id: rule.timedPromoteReleaseRule.id,
215 schedule: rule.timedPromoteReleaseRule.schedule,
216 destinationTargetId: rule.timedPromoteReleaseRule.destinationTargetId,
217 destinationPhase: rule.timedPromoteReleaseRule.destinationPhase,
218 timeZone: rule.timedPromoteReleaseRule.timeZone,
219 }
220 : undefined,
221 });
222
223 export const stripAutomationRules = (rules: readonly clouddeploy.AutomationRule[] | undefined) =>
224 (rules ?? []).map(stripAutomationRule);
225
226 /**
227 * Wait on a Cloud Deploy long-running operation (control-plane, usually under a minute).
228 * `ALREADY_EXISTS` (a create race) counts as success; so does `NOT_FOUND`
229 * when `notFoundOk` (deletes). Returns the final operation.
230 */
231 export const waitForOperation = (
232 operation: clouddeploy.Operation,
233 options?: { notFoundOk?: boolean },
234 ) =>
235 Effect.suspend(() => {
236 let latest = operation;
237 return waitForLongRunningOperation(
238 operation,
239 (name) => {
240 const get = clouddeploy.getProjectsLocationsOperations({ name }).pipe(
241 Effect.tap((current) =>
242 Effect.sync(() => {
243 latest = current;
244 }),
245 ),
246 );
247 const observe: Effect.Effect<
248 clouddeploy.Operation,
249 clouddeploy.GetProjectsLocationsOperationsError,
250 GcpOpContext
251 > =
252 options?.notFoundOk === true
253 ? get.pipe(
254 Effect.catchTag("NotFound", () =>
255 Effect.succeed<clouddeploy.Operation>({ name, done: true }),
256 ),
257 )
258 : get.pipe(
259 // A just-returned operation can briefly 404 on read.
260 Effect.retry({
261 while: (error) => error._tag === "NotFound",
262 times: 5,
263 schedule: Schedule.exponential("250 millis"),
264 }),
265 );
266 return observe;
267 },
268 { budget: "10 minutes" },
269 ).pipe(
270 Effect.map(() => latest),
271 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
272 Effect.catchTag("GCP.OperationFailed", (error) =>
273 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
274 ? Effect.succeed(latest)
275 : Effect.fail(error),
276 ),
277 );
278 });
279
280 export const waitUntilExists = <A, E, R>(
281 get: Effect.Effect<A | undefined, E, R>,
282 name: string,
283 ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> =>
284 get.pipe(
285 Effect.filterOrFail(
286 (value): value is Exclude<A, undefined> => value !== undefined,
287 () => new ResourceNotResolved({ resourceName: name }),
288 ),
289 Effect.retry({
290 while: (error) => error instanceof ResourceNotResolved,
291 times: 8,
292 schedule: Schedule.spaced("1 second"),
293 }),
294 );
295
296 export const waitUntilGone = <A, E, R>(
297 get: Effect.Effect<A | undefined, E, R>,
298 name: string,
299 ): Effect.Effect<void, E | ResourceStillExists, R> =>
300 get.pipe(
301 Effect.filterOrFail(
302 (value) => value === undefined,
303 () => new ResourceStillExists({ resourceName: name }),
304 ),
305 Effect.asVoid,
306 Effect.retry({
307 while: (error) => error instanceof ResourceStillExists,
308 times: 10,
309 schedule: Schedule.spaced("2 seconds"),
310 }),
311 );
312
313 export const listAtLocation = <A, E, R>(
314 project: string,
315 region: string,
316 list: (parent: string) => Effect.Effect<A[], E, R>,
317 ): Effect.Effect<A[], E, R> =>
318 // Some collections reject the `-` location wildcard; fall back to the
319 // region.
320 Effect.firstSuccessOf([
321 list(`projects/${project}/locations/-`),
322 list(`projects/${project}/locations/${region}`),
323 ]);
324
325 export const listAtNested = <A, E, R>(
326 project: string,
327 region: string,
328 nested: string,
329 list: (parent: string) => Effect.Effect<A[], E, R>,
330 ): Effect.Effect<A[], E, R> =>
331 // Some collections reject the `-` location wildcard; fall back to the
332 // region.
333 Effect.firstSuccessOf([
334 list(`projects/${project}/locations/-/${nested}`),
335 list(`projects/${project}/locations/${region}/${nested}`),
336 ]);
337
338 export const listLabeledPages = <Page, A, E, R>(
339 pages: Stream.Stream<Page, E, R>,
340 items: (page: Page) => readonly A[] | undefined,
341 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
342 ): Effect.Effect<A[], E, R> =>
343 pages.pipe(
344 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
345 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
346 Stream.runCollect,
347 Effect.map((chunk) => Array.from(chunk)),
348 );