The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as acm from "@distilled.cloud/gcp/accesscontextmanager_v1"; |
| 2 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 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 { GcpEnvironment } from "../Environment.ts"; |
| 9 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 10 | import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 11 | |
| 12 | export const MAX_TITLE_LENGTH = 256; |
| 13 | export const MAX_DESCRIPTION_LENGTH = 1024; |
| 14 | export const MAX_RESOURCE_ID_LENGTH = 50; |
| 15 | |
| 16 | export class ResourceNotResolved extends Data.TaggedError("GCP.AccessContextManager.NotResolved")<{ |
| 17 | resourceName: string; |
| 18 | }> {} |
| 19 | |
| 20 | export class ResourceStillExists extends Data.TaggedError("GCP.AccessContextManager.StillExists")<{ |
| 21 | resourceName: string; |
| 22 | }> {} |
| 23 | |
| 24 | export class OrganizationRequired extends Data.TaggedError( |
| 25 | "GCP.AccessContextManager.OrganizationRequired", |
| 26 | )<{ |
| 27 | project: string; |
| 28 | }> {} |
| 29 | |
| 30 | export const lastSegment = (value: string) => { |
| 31 | const trimmed = value.replace(/\/+$/, ""); |
| 32 | const parts = trimmed.split("/"); |
| 33 | return parts[parts.length - 1] || trimmed; |
| 34 | }; |
| 35 | |
| 36 | export const organizationParent = (value: string) => |
| 37 | value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`; |
| 38 | |
| 39 | export const policyNameOf = (policy: string) => |
| 40 | policy.startsWith("accessPolicies/") ? policy : `accessPolicies/${lastSegment(policy)}`; |
| 41 | |
| 42 | export const policyIdOf = (policy: string) => lastSegment(policyNameOf(policy)); |
| 43 | |
| 44 | export const resourceNameOf = (policy: string, collection: string, id: string) => |
| 45 | `${policyNameOf(policy)}/${collection}/${id}`; |
| 46 | |
| 47 | export const parseName = (name: string, collection: string) => { |
| 48 | const parts = name.split("/").filter((part) => part.length > 0); |
| 49 | const collectionAt = parts.lastIndexOf(collection); |
| 50 | const policiesAt = parts.lastIndexOf("accessPolicies"); |
| 51 | const orgsAt = parts.lastIndexOf("organizations"); |
| 52 | return { |
| 53 | name, |
| 54 | policyId: policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : "", |
| 55 | organization: orgsAt >= 0 && parts[orgsAt + 1] ? parts[orgsAt + 1]! : "", |
| 56 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 57 | parent: |
| 58 | collectionAt > 0 |
| 59 | ? parts.slice(0, collectionAt).join("/") |
| 60 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 61 | }; |
| 62 | }; |
| 63 | |
| 64 | export const toAcmId = ( |
| 65 | id: string, |
| 66 | requested: string | undefined, |
| 67 | existing: string | undefined, |
| 68 | maxLength = MAX_RESOURCE_ID_LENGTH, |
| 69 | ) => |
| 70 | Effect.gen(function* () { |
| 71 | if (requested !== undefined) return requested; |
| 72 | if (existing !== undefined) return existing; |
| 73 | const generated = yield* createPhysicalName({ |
| 74 | id, |
| 75 | maxLength, |
| 76 | lowercase: true, |
| 77 | delimiter: "_", |
| 78 | }); |
| 79 | let next = generated.replace(/[^a-zA-Z0-9_]/g, "_").replace(/_+/g, "_"); |
| 80 | if (!/^[a-zA-Z]/.test(next)) { |
| 81 | next = `a${next}`; |
| 82 | } |
| 83 | next = next.slice(0, maxLength).replace(/_+$/, ""); |
| 84 | return next.length > 0 ? next : "a"; |
| 85 | }); |
| 86 | |
| 87 | const parentOf = (name: string) => |
| 88 | name.startsWith("projects/") |
| 89 | ? resourcemanager.getProjects({ name }).pipe( |
| 90 | Effect.map((resource) => resource.parent), |
| 91 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 92 | ) |
| 93 | : name.startsWith("folders/") |
| 94 | ? resourcemanager.getFolders({ name }).pipe( |
| 95 | Effect.map((folder) => folder.parent), |
| 96 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 97 | ) |
| 98 | : Effect.undefined; |
| 99 | |
| 100 | export const tryResolveOrganization = () => |
| 101 | Effect.gen(function* () { |
| 102 | const env = yield* GcpEnvironment.current; |
| 103 | let current: string | undefined = `projects/${env.project}`; |
| 104 | for (let i = 0; i < 8; i++) { |
| 105 | if (current === undefined) return undefined; |
| 106 | if (current.startsWith("organizations/")) return current; |
| 107 | current = yield* parentOf(current); |
| 108 | } |
| 109 | return undefined; |
| 110 | }); |
| 111 | |
| 112 | export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) => |
| 113 | Effect.gen(function* () { |
| 114 | if (explicit !== undefined) return organizationParent(explicit); |
| 115 | if (existing !== undefined) return organizationParent(existing); |
| 116 | const resolved = yield* tryResolveOrganization(); |
| 117 | if (resolved === undefined) { |
| 118 | const env = yield* GcpEnvironment.current; |
| 119 | return yield* new OrganizationRequired({ project: env.project }); |
| 120 | } |
| 121 | return resolved; |
| 122 | }); |
| 123 | |
| 124 | export const projectNumberOf = (project: string) => |
| 125 | resourcemanager.getProjects({ name: `projects/${project}` }).pipe( |
| 126 | Effect.map((resource) => lastSegment(resource.name ?? "")), |
| 127 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 128 | ); |
| 129 | |
| 130 | export const normalizeScope = (scope: string, projectNumber?: string) => { |
| 131 | if ( |
| 132 | scope.startsWith("projects/") || |
| 133 | scope.startsWith("folders/") || |
| 134 | scope.startsWith("organizations/") |
| 135 | ) { |
| 136 | return scope; |
| 137 | } |
| 138 | if (/^\d+$/.test(scope)) return `projects/${scope}`; |
| 139 | if (projectNumber !== undefined && projectNumber.length > 0) { |
| 140 | return `projects/${projectNumber}`; |
| 141 | } |
| 142 | return `projects/${scope}`; |
| 143 | }; |
| 144 | |
| 145 | export const normalizeScopes = (scopes: readonly string[] | undefined, projectNumber?: string) => |
| 146 | (scopes ?? []).map((scope) => normalizeScope(scope, projectNumber)); |
| 147 | |
| 148 | const markerOf = (stack: string, stage: string, id: string) => |
| 149 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 150 | |
| 151 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 152 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 153 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 154 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 155 | let marker = markerOf(stack, stage, id); |
| 156 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 157 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 158 | stack = stack.slice(0, -1); |
| 159 | } else if (stage.length >= id.length) { |
| 160 | stage = stage.slice(0, -1); |
| 161 | } else { |
| 162 | id = id.slice(0, -1); |
| 163 | } |
| 164 | marker = markerOf(stack, stage, id); |
| 165 | } |
| 166 | return marker.slice(0, maxLength); |
| 167 | }; |
| 168 | |
| 169 | export const encodeOwnership = ( |
| 170 | labels: Record<string, string>, |
| 171 | text: string | undefined, |
| 172 | maxLength = MAX_DESCRIPTION_LENGTH, |
| 173 | ): string => { |
| 174 | const marker = fitMarker(labels, maxLength); |
| 175 | const trimmed = text?.trim(); |
| 176 | if (!trimmed) return marker.slice(0, maxLength); |
| 177 | return `${marker}\n${trimmed}`.slice(0, maxLength); |
| 178 | }; |
| 179 | |
| 180 | export const encodeOwnershipLine = ( |
| 181 | labels: Record<string, string>, |
| 182 | text: string | undefined, |
| 183 | maxLength = MAX_TITLE_LENGTH, |
| 184 | ): string => { |
| 185 | const trimmed = text?.replace(/[\r\n]+/g, " ").trim(); |
| 186 | const reserved = |
| 187 | trimmed && trimmed.length > 0 ? Math.min(trimmed.length + 1, Math.max(0, maxLength - 24)) : 0; |
| 188 | const marker = fitMarker(labels, Math.max(24, maxLength - reserved)); |
| 189 | if (!trimmed) return marker.slice(0, maxLength); |
| 190 | return `${marker} ${trimmed}`.slice(0, maxLength); |
| 191 | }; |
| 192 | |
| 193 | export const parseOwnership = ( |
| 194 | text: string | undefined, |
| 195 | ): { |
| 196 | labels: Record<string, string>; |
| 197 | text: string | undefined; |
| 198 | } => { |
| 199 | if (!text?.startsWith("[alchemy ")) { |
| 200 | return { labels: {}, text }; |
| 201 | } |
| 202 | const end = text.indexOf("]"); |
| 203 | if (end < 0) return { labels: {}, text }; |
| 204 | const labels: Record<string, string> = {}; |
| 205 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 206 | const eq = part.indexOf("="); |
| 207 | if (eq > 0) { |
| 208 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 209 | } |
| 210 | } |
| 211 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 212 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 213 | }; |
| 214 | |
| 215 | export const hasOwnershipMarker = (text: string | undefined) => |
| 216 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 217 | |
| 218 | const prefixMatch = (expected: string, observed: string) => |
| 219 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 220 | |
| 221 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 222 | Effect.gen(function* () { |
| 223 | const expected = yield* createInternalLabels(id); |
| 224 | const { labels } = parseOwnership(text); |
| 225 | if (!hasOwnershipMarker(text)) return false; |
| 226 | const exact = yield* hasAlchemyLabels(id, labels); |
| 227 | if (exact) return true; |
| 228 | return ( |
| 229 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 230 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 231 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 232 | ); |
| 233 | }); |
| 234 | |
| 235 | export const jsonEqual = (left: unknown, right: unknown) => |
| 236 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 237 | |
| 238 | export const sortedStrings = (values: readonly string[] | undefined) => |
| 239 | [...(values ?? [])].slice().sort(); |
| 240 | |
| 241 | export const sameStringList = ( |
| 242 | left: readonly string[] | undefined, |
| 243 | right: readonly string[] | undefined, |
| 244 | ) => JSON.stringify(sortedStrings(left)) === JSON.stringify(sortedStrings(right)); |
| 245 | |
| 246 | export const collectPages = <Page, A, E, R>( |
| 247 | pages: Stream.Stream<Page, E, R>, |
| 248 | items: (page: Page) => readonly A[] | undefined, |
| 249 | ) => |
| 250 | pages.pipe( |
| 251 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 252 | Stream.runCollect, |
| 253 | Effect.map((chunk) => Array.from(chunk)), |
| 254 | ); |
| 255 | |
| 256 | export const listAccessPolicies = (organization: string) => |
| 257 | collectPages( |
| 258 | acm.listAccessPolicies.pages({ |
| 259 | parent: organizationParent(organization), |
| 260 | pageSize: 100, |
| 261 | }), |
| 262 | (page) => page.accessPolicies, |
| 263 | ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as acm.AccessPolicy[]))); |
| 264 | |
| 265 | export const listOwnedPolicies = () => |
| 266 | Effect.gen(function* () { |
| 267 | const organization = yield* tryResolveOrganization(); |
| 268 | if (organization === undefined) return [] as acm.AccessPolicy[]; |
| 269 | const policies = yield* listAccessPolicies(organization); |
| 270 | return policies.filter((policy) => hasOwnershipMarker(policy.title)); |
| 271 | }); |
| 272 | |
| 273 | export const resourceNameFromOperation = ( |
| 274 | operation: acm.Operation, |
| 275 | prefix?: string, |
| 276 | ): string | undefined => { |
| 277 | const name = operation.response?.name; |
| 278 | if (typeof name !== "string" || name.length === 0) return undefined; |
| 279 | if (prefix !== undefined && !name.startsWith(prefix)) return undefined; |
| 280 | return name; |
| 281 | }; |
| 282 | |
| 283 | /** |
| 284 | * Wait for an Access Context Manager operation (a few minutes at most) and |
| 285 | * return the finished operation so callers can read its `response`. |
| 286 | */ |
| 287 | export const waitForOperation = (operation: acm.Operation) => |
| 288 | Effect.gen(function* () { |
| 289 | yield* waitForGcpOperation(operation, (name) => acm.getOperations({ name }), { |
| 290 | budget: "10 minutes", |
| 291 | }); |
| 292 | if (operation.done === true || !operation.name) return operation; |
| 293 | return yield* acm.getOperations({ name: operation.name }); |
| 294 | }); |
| 295 | |
| 296 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 297 | get: Effect.Effect<A | undefined, E, R>, |
| 298 | name: string, |
| 299 | ) => |
| 300 | get.pipe( |
| 301 | Effect.flatMap((value) => |
| 302 | value ? Effect.succeed(value) : Effect.fail(new ResourceNotResolved({ resourceName: name })), |
| 303 | ), |
| 304 | Effect.retry({ |
| 305 | while: (error) => error._tag === "GCP.AccessContextManager.NotResolved", |
| 306 | times: 8, |
| 307 | schedule: Schedule.spaced("1 second"), |
| 308 | }), |
| 309 | ); |
| 310 | |
| 311 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 312 | get: Effect.Effect<A | undefined, E, R>, |
| 313 | name: string, |
| 314 | ) => |
| 315 | get.pipe( |
| 316 | Effect.flatMap((value) => |
| 317 | value === undefined |
| 318 | ? Effect.void |
| 319 | : Effect.fail(new ResourceStillExists({ resourceName: name })), |
| 320 | ), |
| 321 | Effect.retry({ |
| 322 | while: (error) => error._tag === "GCP.AccessContextManager.StillExists", |
| 323 | times: 10, |
| 324 | schedule: Schedule.spaced("2 seconds"), |
| 325 | }), |
| 326 | ); |
| 327 | |
| 328 | export const replaceOnIdentity = (changed: boolean) => |
| 329 | changed ? ({ action: "replace" as const, deleteFirst: false } as const) : undefined; |