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

main
ts 384 lines 12.7 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as osconfig from "@distilled.cloud/gcp/osconfig_v2";
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 { GcpEnvironment } from "../Environment.ts";
10 import { stripInternalLabels } from "../Labels.ts";
11 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
12
13 export const MAX_ID_LENGTH = 63;
14 export const DEFAULT_ACTION = "UPSERT";
15 export const DEFAULT_STATE = "STOPPED";
16
17 export type OrchestratedResource = osconfig.GoogleCloudOsconfigV2__OrchestratedResource;
18 export type OrchestrationScope = osconfig.GoogleCloudOsconfigV2__OrchestrationScope;
19 export type PolicyOrchestratorBody = osconfig.GoogleCloudOsconfigV2__PolicyOrchestrator;
20
21 export class OsconfigNotResolved extends Data.TaggedError("GCP.OSConfig.NotResolved")<{
22 resourceName: string;
23 }> {}
24
25 export class OsconfigStillExists extends Data.TaggedError("GCP.OSConfig.StillExists")<{
26 resourceName: string;
27 }> {}
28
29 export class FolderNotResolved extends Data.TaggedError("GCP.OSConfig.FolderNotResolved")<{
30 project: string;
31 }> {}
32
33 export class OrganizationNotResolved extends Data.TaggedError(
34 "GCP.OSConfig.OrganizationNotResolved",
35 )<{
36 project: string;
37 }> {}
38
39 export const lastSegment = (value: string) => {
40 const trimmed = value.replace(/\/+$/, "");
41 const parts = trimmed.split("/");
42 return parts[parts.length - 1] || trimmed;
43 };
44
45 export const rfc1035 = (name: string, fallback = "orch"): string => {
46 let next = name
47 .toLowerCase()
48 .replace(/[^a-z0-9-]/g, "-")
49 .replace(/-+/g, "-")
50 .replace(/^-+|-+$/g, "");
51 if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "o"}${next}`;
52 next = next.slice(0, MAX_ID_LENGTH).replace(/-+$/g, "");
53 if (next.length === 0) next = fallback;
54 if (!/[a-z0-9]$/.test(next)) {
55 next = `${next.slice(0, MAX_ID_LENGTH - 1)}0`;
56 }
57 return next.slice(0, MAX_ID_LENGTH);
58 };
59
60 export const toPhysicalId = (
61 id: string,
62 explicit: string | undefined,
63 existing: string | undefined,
64 fallback = "orch",
65 ) =>
66 Effect.gen(function* () {
67 if (explicit !== undefined) return rfc1035(explicit, fallback);
68 if (existing !== undefined) return existing;
69 return rfc1035(
70 yield* createPhysicalName({
71 id,
72 maxLength: MAX_ID_LENGTH,
73 lowercase: true,
74 }),
75 fallback,
76 );
77 });
78
79 export const folderParent = (value: string) =>
80 value.startsWith("folders/") ? value : `folders/${lastSegment(value)}`;
81
82 export const organizationParent = (value: string) =>
83 value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`;
84
85 export const projectParent = (value: string) =>
86 value.startsWith("projects/") ? value : `projects/${lastSegment(value)}`;
87
88 export const globalParent = (scopeParent: string) =>
89 `${scopeParent.replace(/\/+$/, "")}/locations/global`;
90
91 export const resourceName = (parent: string, policyOrchestratorId: string) =>
92 `${parent}/policyOrchestrators/${policyOrchestratorId}`;
93
94 export const parseName = (name: string) => {
95 const parts = name.split("/").filter((part) => part.length > 0);
96 const collectionAt = parts.lastIndexOf("policyOrchestrators");
97 const locationsAt = parts.lastIndexOf("locations");
98 const projectsAt = parts.lastIndexOf("projects");
99 const orgsAt = parts.lastIndexOf("organizations");
100 const foldersAt = parts.lastIndexOf("folders");
101 return {
102 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
103 organization: orgsAt >= 0 && parts[orgsAt + 1] ? parts[orgsAt + 1]! : "",
104 folder: foldersAt >= 0 && parts[foldersAt + 1] ? parts[foldersAt + 1]! : "",
105 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "global",
106 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
107 parent:
108 collectionAt > 0
109 ? parts.slice(0, collectionAt).join("/")
110 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
111 };
112 };
113
114 export const userLabels = (
115 labels: Record<string, string | undefined> | null | undefined,
116 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
117
118 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
119 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
120
121 export const canonical = (value: unknown): unknown => {
122 if (value === undefined || value === null) return undefined;
123 if (typeof value === "boolean" || typeof value === "number") return value;
124 if (typeof value === "string") {
125 return value.length === 0 ? undefined : value;
126 }
127 if (Array.isArray(value)) {
128 const items = value.map(canonical).filter((item) => item !== undefined);
129 return items.length === 0 ? undefined : items;
130 }
131 if (typeof value === "object") {
132 const entries = Object.entries(value as Record<string, unknown>)
133 .map(([key, item]) => [key, canonical(item)] as const)
134 .filter(([, item]) => item !== undefined)
135 .sort(([left], [right]) => left.localeCompare(right));
136 if (entries.length === 0) return undefined;
137 return Object.fromEntries(entries);
138 }
139 return undefined;
140 };
141
142 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
143
144 export const fieldMask = (fields: Array<string | false | undefined>) =>
145 fields.filter((field): field is string => typeof field === "string").join(",");
146
147 const OUTPUT_ONLY_ASSIGNMENT = new Set([
148 "rolloutState",
149 "baseline",
150 "deleted",
151 "etag",
152 "uid",
153 "revisionCreateTime",
154 "reconciling",
155 "name",
156 "revisionId",
157 ]);
158
159 export const assignmentPayload = (
160 assignment: osconfig.OSPolicyAssignment | undefined,
161 ): osconfig.OSPolicyAssignment | undefined => {
162 if (assignment === undefined) return undefined;
163 const next: Record<string, unknown> = {};
164 for (const [key, value] of Object.entries(assignment)) {
165 if (!OUTPUT_ONLY_ASSIGNMENT.has(key) && value !== undefined) {
166 next[key] = value;
167 }
168 }
169 return next as osconfig.OSPolicyAssignment;
170 };
171
172 export const orchestratedPayload = (
173 resource: OrchestratedResource | undefined,
174 ): OrchestratedResource | undefined => {
175 if (resource === undefined) return undefined;
176 return {
177 id: resource.id,
178 osPolicyAssignmentV1Payload: assignmentPayload(resource.osPolicyAssignmentV1Payload),
179 };
180 };
181
182 export const defaultOrchestratedResource = (resourceId: string): OrchestratedResource => ({
183 id: resourceId,
184 osPolicyAssignmentV1Payload: {
185 instanceFilter: {
186 inventories: [{ osShortName: "debian" }],
187 },
188 osPolicies: [
189 {
190 id: "alchemy-noop",
191 mode: "VALIDATION",
192 resourceGroups: [
193 {
194 resources: [
195 {
196 id: "noop-exec",
197 exec: {
198 validate: {
199 interpreter: "SHELL",
200 script: "exit 100",
201 },
202 },
203 },
204 ],
205 },
206 ],
207 },
208 ],
209 rollout: {
210 disruptionBudget: { percent: 100 },
211 minWaitDuration: "0s",
212 },
213 },
214 });
215
216 const getOperation = (name: string) =>
217 name.startsWith("folders/")
218 ? osconfig.getFoldersLocationsOperations({ name })
219 : name.startsWith("organizations/")
220 ? osconfig.getOrganizationsLocationsOperations({ name })
221 : osconfig.getProjectsLocationsOperations({ name });
222
223 /**
224 * Wait for an OS Config policy-orchestrator operation. An operation that
225 * finished with `ALREADY_EXISTS` (6) is a lost create race; `notFoundOk`
226 * also accepts `NOT_FOUND` (5).
227 */
228 export const waitForOperation = (
229 operation: osconfig.Operation,
230 options?: { notFoundOk?: boolean },
231 ) =>
232 waitForGcpOperation(
233 operation,
234 (name) =>
235 getOperation(name).pipe(
236 Effect.catchTag("NotFound", (error) =>
237 options?.notFoundOk === true
238 ? Effect.succeed<osconfig.Operation>({ name, done: true })
239 : Effect.fail(error),
240 ),
241 ),
242 { budget: "10 minutes" },
243 ).pipe(
244 Effect.catchIf(
245 (error) =>
246 error._tag === "GCP.OperationFailed" &&
247 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
248 () => Effect.void,
249 ),
250 Effect.asVoid,
251 );
252
253 export const waitUntilExists = <A, E, R>(
254 get: Effect.Effect<A | undefined, E, R>,
255 name: string,
256 ): Effect.Effect<NonNullable<A>, E | OsconfigNotResolved, R> =>
257 get.pipe(
258 Effect.filterOrFail(
259 (value): value is NonNullable<A> => value != null,
260 () => new OsconfigNotResolved({ resourceName: name }),
261 ),
262 Effect.retry({
263 while: (error) => error instanceof OsconfigNotResolved,
264 times: 8,
265 schedule: Schedule.spaced("1 second"),
266 }),
267 );
268
269 export const waitUntilGone = <A, E, R>(
270 get: Effect.Effect<A | undefined, E, R>,
271 name: string,
272 ): Effect.Effect<void, E | OsconfigStillExists, R> =>
273 get.pipe(
274 Effect.filterOrFail(
275 (value) => value === undefined,
276 () => new OsconfigStillExists({ resourceName: name }),
277 ),
278 Effect.retry({
279 while: (error) => error instanceof OsconfigStillExists,
280 times: 10,
281 schedule: Schedule.spaced("3 seconds"),
282 }),
283 Effect.asVoid,
284 );
285
286 export const collectOrchestrators = (
287 pages: Stream.Stream<
288 osconfig.GoogleCloudOsconfigV2__ListPolicyOrchestratorsResponse,
289 osconfig.NotFound | osconfig.Forbidden | osconfig.ServiceDisabled | osconfig.GcpOpError,
290 osconfig.GcpOpContext
291 >,
292 ) =>
293 pages.pipe(
294 Stream.flatMap((page) => Stream.fromIterable(page.policyOrchestrators ?? [])),
295 Stream.runCollect,
296 Effect.map((chunk) => Array.from(chunk)),
297 Effect.catchTag(["NotFound", "Forbidden", "ServiceDisabled"], () =>
298 Effect.succeed([] as PolicyOrchestratorBody[]),
299 ),
300 );
301
302 const ancestryParent = (name: string) =>
303 name.startsWith("projects/")
304 ? resourcemanager.getProjects({ name }).pipe(
305 Effect.map((resource) => resource.parent),
306 Effect.catchTag("NotFound", () => Effect.undefined),
307 )
308 : name.startsWith("folders/")
309 ? resourcemanager.getFolders({ name }).pipe(
310 Effect.map((folder) => folder.parent),
311 Effect.catchTag("NotFound", () => Effect.undefined),
312 )
313 : Effect.undefined;
314
315 export const tryResolveFolder = () =>
316 Effect.gen(function* () {
317 const env = yield* GcpEnvironment.current;
318 let current: string | undefined = `projects/${env.project}`;
319 for (let i = 0; i < 8; i++) {
320 if (current === undefined) return undefined;
321 if (current.startsWith("folders/")) return current;
322 if (current.startsWith("organizations/")) return undefined;
323 current = yield* ancestryParent(current);
324 }
325 return undefined;
326 });
327
328 export const resolveFolder = (explicit: string | undefined, existing: string | undefined) =>
329 Effect.gen(function* () {
330 if (explicit !== undefined) return folderParent(explicit);
331 if (existing !== undefined) return folderParent(existing);
332 const resolved = yield* tryResolveFolder();
333 if (resolved === undefined) {
334 const env = yield* GcpEnvironment.current;
335 return yield* new FolderNotResolved({ project: env.project });
336 }
337 return resolved;
338 });
339
340 export const tryResolveOrganization = () =>
341 Effect.gen(function* () {
342 const env = yield* GcpEnvironment.current;
343 let current: string | undefined = `projects/${env.project}`;
344 for (let i = 0; i < 8; i++) {
345 if (current === undefined) return undefined;
346 if (current.startsWith("organizations/")) return current;
347 current = yield* ancestryParent(current);
348 }
349 return undefined;
350 });
351
352 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
353 Effect.gen(function* () {
354 if (explicit !== undefined) return organizationParent(explicit);
355 if (existing !== undefined) return organizationParent(existing);
356 const resolved = yield* tryResolveOrganization();
357 if (resolved === undefined) {
358 const env = yield* GcpEnvironment.current;
359 return yield* new OrganizationNotResolved({ project: env.project });
360 }
361 return resolved;
362 });
363
364 export const replaceOnIdentity = (input: {
365 previousId: string | undefined;
366 nextId: string | undefined;
367 previousParent: string;
368 nextParent: string;
369 }) => {
370 const idChanged =
371 input.previousId !== undefined &&
372 input.nextId !== undefined &&
373 input.nextId !== input.previousId;
374 const parentChanged =
375 input.previousParent !== "" &&
376 input.nextParent !== "" &&
377 input.previousParent !== input.nextParent;
378 if (!idChanged && !parentChanged) return undefined;
379 return {
380 action: "replace" as const,
381 deleteFirst:
382 !parentChanged && input.previousId !== undefined && input.nextId === input.previousId,
383 };
384 };