The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as workloadmanager from "@distilled.cloud/gcp/workloadmanager_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 waitForGcpOperation } from "../Operation.ts"; |
| 10 | |
| 11 | export const MAX_NAME_LENGTH = 63; |
| 12 | export const ACTUATION_ID_PREFIX = "alch-"; |
| 13 | |
| 14 | export class ResourceNotResolved extends Data.TaggedError( |
| 15 | "GCP.WorkloadManager.ResourceNotResolved", |
| 16 | )<{ |
| 17 | resourceName: string; |
| 18 | }> {} |
| 19 | |
| 20 | export class ResourceStillExists extends Data.TaggedError( |
| 21 | "GCP.WorkloadManager.ResourceStillExists", |
| 22 | )<{ |
| 23 | resourceName: string; |
| 24 | }> {} |
| 25 | |
| 26 | export class ResourceNotReady extends Data.TaggedError("GCP.WorkloadManager.ResourceNotReady")<{ |
| 27 | resourceName: string; |
| 28 | state: string; |
| 29 | }> {} |
| 30 | |
| 31 | export class ResourceFailed extends Data.TaggedError("GCP.WorkloadManager.ResourceFailed")<{ |
| 32 | resourceName: string; |
| 33 | state: string; |
| 34 | details: string | undefined; |
| 35 | }> {} |
| 36 | |
| 37 | export const lastSegment = (value: string) => { |
| 38 | const trimmed = value.replace(/\/+$/, ""); |
| 39 | const parts = trimmed.split("/"); |
| 40 | return parts[parts.length - 1] || trimmed; |
| 41 | }; |
| 42 | |
| 43 | export const rfc1035 = (name: string, fallback = "workloadmanager"): string => { |
| 44 | let next = name |
| 45 | .toLowerCase() |
| 46 | .replace(/[^a-z0-9-]/g, "-") |
| 47 | .replace(/-+/g, "-") |
| 48 | .replace(/^-+|-+$/g, ""); |
| 49 | if (!/^[a-z]/.test(next)) next = `w${next}`; |
| 50 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 51 | if (next.length === 0) return fallback; |
| 52 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 53 | return next.slice(0, MAX_NAME_LENGTH); |
| 54 | }; |
| 55 | |
| 56 | export const normalizeLocation = (location: string | undefined, fallback: string) => |
| 57 | lastSegment(location ?? fallback).toLowerCase(); |
| 58 | |
| 59 | export const parentOf = (project: string, location: string) => |
| 60 | `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; |
| 61 | |
| 62 | export const toPhysicalId = ( |
| 63 | id: string, |
| 64 | explicit: string | undefined, |
| 65 | existing: string | undefined, |
| 66 | fallback = "workloadmanager", |
| 67 | ) => |
| 68 | Effect.gen(function* () { |
| 69 | if (explicit !== undefined) return rfc1035(explicit, fallback); |
| 70 | if (existing !== undefined) return existing; |
| 71 | return rfc1035( |
| 72 | yield* createPhysicalName({ |
| 73 | id, |
| 74 | maxLength: MAX_NAME_LENGTH, |
| 75 | lowercase: true, |
| 76 | }), |
| 77 | fallback, |
| 78 | ); |
| 79 | }); |
| 80 | |
| 81 | /** |
| 82 | * Actuations have no labels or description. Generated ids are prefixed |
| 83 | * `alch-` so `list` / nuke can find Alchemy-owned rows. |
| 84 | */ |
| 85 | export const toActuationId = ( |
| 86 | id: string, |
| 87 | explicit: string | undefined, |
| 88 | existing: string | undefined, |
| 89 | ) => |
| 90 | Effect.gen(function* () { |
| 91 | if (explicit !== undefined) return rfc1035(explicit, "alch"); |
| 92 | if (existing !== undefined) return existing; |
| 93 | const generated = rfc1035( |
| 94 | yield* createPhysicalName({ |
| 95 | id, |
| 96 | maxLength: MAX_NAME_LENGTH - ACTUATION_ID_PREFIX.length, |
| 97 | lowercase: true, |
| 98 | }), |
| 99 | "actuation", |
| 100 | ); |
| 101 | const prefixed = generated.startsWith(ACTUATION_ID_PREFIX) |
| 102 | ? generated |
| 103 | : `${ACTUATION_ID_PREFIX}${generated}`; |
| 104 | return prefixed.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 105 | }); |
| 106 | |
| 107 | export const hasAlchemyActuationId = (actuationId: string) => |
| 108 | actuationId.startsWith(ACTUATION_ID_PREFIX); |
| 109 | |
| 110 | export const parseName = (name: string, collection: string, fallbackLocation: string) => { |
| 111 | const parts = name.split("/").filter((part) => part.length > 0); |
| 112 | const collectionAt = parts.lastIndexOf(collection); |
| 113 | const locationsAt = parts.lastIndexOf("locations"); |
| 114 | const projectsAt = parts.lastIndexOf("projects"); |
| 115 | return { |
| 116 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 117 | location: |
| 118 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 119 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 120 | parent: |
| 121 | collectionAt > 0 |
| 122 | ? parts.slice(0, collectionAt).join("/") |
| 123 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 124 | }; |
| 125 | }; |
| 126 | |
| 127 | export const expandNamed = ( |
| 128 | value: string, |
| 129 | project: string, |
| 130 | location: string, |
| 131 | collection: string, |
| 132 | ) => { |
| 133 | if (value.includes("/")) return value.replace(/\/+$/, ""); |
| 134 | return `projects/${project}/locations/${location}/${collection}/${value}`; |
| 135 | }; |
| 136 | |
| 137 | export const userLabels = ( |
| 138 | labels: Record<string, string | undefined> | null | undefined, |
| 139 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 140 | |
| 141 | export const stringMap = ( |
| 142 | value: Record<string, string | undefined> | null | undefined, |
| 143 | ): Record<string, string> => |
| 144 | Object.fromEntries( |
| 145 | Object.entries(value ?? {}).filter( |
| 146 | (entry): entry is [string, string] => typeof entry[1] === "string", |
| 147 | ), |
| 148 | ); |
| 149 | |
| 150 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 151 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 152 | |
| 153 | export const canonical = (value: unknown): unknown => { |
| 154 | if (value === undefined || value === null) return undefined; |
| 155 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 156 | if (typeof value === "string") { |
| 157 | return value.length === 0 ? undefined : value; |
| 158 | } |
| 159 | if (Array.isArray(value)) { |
| 160 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 161 | return items.length === 0 ? undefined : items; |
| 162 | } |
| 163 | if (typeof value === "object") { |
| 164 | const entries = Object.entries(value as Record<string, unknown>) |
| 165 | .map(([key, item]) => [key, canonical(item)] as const) |
| 166 | .filter(([, item]) => item !== undefined) |
| 167 | .sort(([left], [right]) => left.localeCompare(right)); |
| 168 | if (entries.length === 0) return undefined; |
| 169 | return Object.fromEntries(entries); |
| 170 | } |
| 171 | return undefined; |
| 172 | }; |
| 173 | |
| 174 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 175 | |
| 176 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 177 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 178 | |
| 179 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 180 | (left ?? "") === (right ?? ""); |
| 181 | |
| 182 | export const sameStringList = ( |
| 183 | left: readonly string[] | undefined, |
| 184 | right: readonly string[] | undefined, |
| 185 | ) => |
| 186 | fingerprint([...(left ?? [])].slice().sort()) === fingerprint([...(right ?? [])].slice().sort()); |
| 187 | |
| 188 | export const replaceOnIdentity = (input: { |
| 189 | previousId: string | undefined; |
| 190 | nextId: string | undefined; |
| 191 | previousLocation: string; |
| 192 | nextLocation: string; |
| 193 | extra?: boolean; |
| 194 | previousParent?: string; |
| 195 | nextParent?: string; |
| 196 | }) => { |
| 197 | const parentChanged = |
| 198 | (input.previousParent ?? "") !== "" && |
| 199 | (input.nextParent ?? "") !== "" && |
| 200 | (input.previousParent ?? "") !== (input.nextParent ?? ""); |
| 201 | const replace = |
| 202 | (input.extra ?? false) || |
| 203 | parentChanged || |
| 204 | (input.previousId !== undefined && |
| 205 | input.nextId !== undefined && |
| 206 | input.nextId !== input.previousId) || |
| 207 | input.previousLocation !== input.nextLocation; |
| 208 | if (!replace) return undefined; |
| 209 | const samePhysical = |
| 210 | input.previousLocation === input.nextLocation && |
| 211 | !parentChanged && |
| 212 | input.previousId !== undefined && |
| 213 | input.nextId === input.previousId; |
| 214 | return { |
| 215 | action: "replace" as const, |
| 216 | deleteFirst: samePhysical, |
| 217 | }; |
| 218 | }; |
| 219 | |
| 220 | const READY_STATES = new Set(["READY", "SUCCEEDED", "ACTIVE"]); |
| 221 | const FAILED_STATES = new Set(["FAILED", "ERROR", "TIMEOUT"]); |
| 222 | |
| 223 | export const isReadyState = (state: string | undefined) => |
| 224 | READY_STATES.has((state ?? "").toUpperCase()); |
| 225 | |
| 226 | export const isFailedState = (state: string | undefined) => |
| 227 | FAILED_STATES.has((state ?? "").toUpperCase()); |
| 228 | |
| 229 | export const resourceNameFromOperation = ( |
| 230 | operation: workloadmanager.Operation, |
| 231 | ): string | undefined => { |
| 232 | const response = operation.response; |
| 233 | if (response && typeof response.name === "string" && response.name.length > 0) { |
| 234 | return response.name; |
| 235 | } |
| 236 | const metadata = operation.metadata; |
| 237 | if (metadata && typeof metadata.target === "string" && metadata.target.length > 0) { |
| 238 | return metadata.target; |
| 239 | } |
| 240 | if (metadata && typeof metadata.name === "string" && metadata.name.length > 0) { |
| 241 | return metadata.name; |
| 242 | } |
| 243 | return undefined; |
| 244 | }; |
| 245 | |
| 246 | /** |
| 247 | * Wait for a Workload Manager long-running operation (evaluations settle in minutes; deployment actuations run infrastructure changes). |
| 248 | */ |
| 249 | export const waitForOperation = (operation: workloadmanager.Operation) => |
| 250 | waitForGcpOperation( |
| 251 | operation, |
| 252 | (name) => workloadmanager.getProjectsLocationsOperations({ name }), |
| 253 | { budget: "20 minutes" }, |
| 254 | ); |
| 255 | |
| 256 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 257 | get: Effect.Effect<A, E, R>, |
| 258 | name: string, |
| 259 | ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> => |
| 260 | get.pipe( |
| 261 | Effect.filterOrFail( |
| 262 | (value): value is Exclude<A, undefined> => value !== undefined, |
| 263 | () => new ResourceNotResolved({ resourceName: name }), |
| 264 | ), |
| 265 | Effect.retry({ |
| 266 | while: (error) => error._tag === "GCP.WorkloadManager.ResourceNotResolved", |
| 267 | times: 8, |
| 268 | schedule: Schedule.spaced("1 second"), |
| 269 | }), |
| 270 | ); |
| 271 | |
| 272 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 273 | get: Effect.Effect<A, E, R>, |
| 274 | name: string, |
| 275 | ): Effect.Effect<void, E | ResourceStillExists, R> => |
| 276 | get.pipe( |
| 277 | Effect.filterOrFail( |
| 278 | (value) => value === undefined, |
| 279 | () => new ResourceStillExists({ resourceName: name }), |
| 280 | ), |
| 281 | Effect.retry({ |
| 282 | while: (error) => error._tag === "GCP.WorkloadManager.ResourceStillExists", |
| 283 | times: 10, |
| 284 | schedule: Schedule.spaced("2 seconds"), |
| 285 | }), |
| 286 | Effect.asVoid, |
| 287 | ); |
| 288 | |
| 289 | export const waitUntilReady = <A, E extends { readonly _tag: string }, R>( |
| 290 | get: Effect.Effect<A, E, R>, |
| 291 | name: string, |
| 292 | stateOf: (value: Exclude<A, undefined>) => string | undefined, |
| 293 | detailsOf?: (value: Exclude<A, undefined>) => string | undefined, |
| 294 | options?: { |
| 295 | times?: number; |
| 296 | interval?: `${number} seconds`; |
| 297 | }, |
| 298 | ): Effect.Effect< |
| 299 | Exclude<A, undefined>, |
| 300 | E | ResourceNotResolved | ResourceFailed | ResourceNotReady, |
| 301 | R |
| 302 | > => |
| 303 | get.pipe( |
| 304 | Effect.filterOrFail( |
| 305 | (value): value is Exclude<A, undefined> => value !== undefined, |
| 306 | () => new ResourceNotResolved({ resourceName: name }), |
| 307 | ), |
| 308 | Effect.filterOrFail( |
| 309 | (value) => !isFailedState(stateOf(value)), |
| 310 | (value) => |
| 311 | new ResourceFailed({ |
| 312 | resourceName: name, |
| 313 | state: stateOf(value) ?? "", |
| 314 | details: detailsOf?.(value), |
| 315 | }), |
| 316 | ), |
| 317 | Effect.filterOrFail( |
| 318 | (value) => { |
| 319 | const state = stateOf(value) ?? ""; |
| 320 | return isReadyState(state) || state.length === 0; |
| 321 | }, |
| 322 | (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }), |
| 323 | ), |
| 324 | Effect.retry({ |
| 325 | while: (error) => |
| 326 | error._tag === "GCP.WorkloadManager.ResourceNotReady" || |
| 327 | error._tag === "GCP.WorkloadManager.ResourceNotResolved", |
| 328 | times: options?.times ?? 10, |
| 329 | schedule: Schedule.spaced(options?.interval ?? "2 seconds"), |
| 330 | }), |
| 331 | ); |
| 332 | |
| 333 | const isNotFound = <E extends { readonly _tag: string }>( |
| 334 | error: E, |
| 335 | ): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound"; |
| 336 | |
| 337 | /** List across `locations/-`, falling back to the region if the wildcard 404s. */ |
| 338 | export const listAtLocation = <A, E extends { readonly _tag: string }, R>( |
| 339 | project: string, |
| 340 | region: string, |
| 341 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 342 | ) => |
| 343 | list(`projects/${project}/locations/-`).pipe( |
| 344 | Effect.catchIf(isNotFound, () => list(`projects/${project}/locations/${region}`)), |
| 345 | ); |
| 346 | |
| 347 | export const listAtNested = <A, E extends { readonly _tag: string }, R>( |
| 348 | project: string, |
| 349 | region: string, |
| 350 | nested: string, |
| 351 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 352 | ) => |
| 353 | list(`projects/${project}/locations/-/${nested}`).pipe( |
| 354 | Effect.catchIf(isNotFound, () => list(`projects/${project}/locations/${region}/${nested}`)), |
| 355 | ); |
| 356 | |
| 357 | export const listLabeledPages = <Page, A, E, R>( |
| 358 | pages: Stream.Stream<Page, E, R>, |
| 359 | items: (page: Page) => readonly A[] | undefined, |
| 360 | labelsOf: (item: A) => Record<string, string | undefined> | null | undefined, |
| 361 | ): Effect.Effect<A[], E, R> => |
| 362 | pages.pipe( |
| 363 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 364 | Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))), |
| 365 | Stream.runCollect, |
| 366 | Effect.map((chunk) => Array.from(chunk)), |
| 367 | ); |
| 368 | |
| 369 | export const listPages = <Page, A, E, R>( |
| 370 | pages: Stream.Stream<Page, E, R>, |
| 371 | items: (page: Page) => readonly A[] | undefined, |
| 372 | keep: (item: A) => boolean, |
| 373 | ): Effect.Effect<A[], E, R> => |
| 374 | pages.pipe( |
| 375 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 376 | Stream.filter(keep), |
| 377 | Stream.runCollect, |
| 378 | Effect.map((chunk) => Array.from(chunk)), |
| 379 | ); |