The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as assuredworkloads from "@distilled.cloud/gcp/assuredworkloads_v1"; |
| 2 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 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_DISPLAY_NAME_LENGTH = 30; |
| 14 | export const MIN_DISPLAY_NAME_LENGTH = 4; |
| 15 | |
| 16 | export type ApiWorkload = assuredworkloads.GoogleCloudAssuredworkloadsV1Workload; |
| 17 | export type ApiOperation = assuredworkloads.GoogleLongrunningOperation; |
| 18 | |
| 19 | export class AssuredworkloadsNotResolved extends Data.TaggedError( |
| 20 | "GCP.AssuredWorkloads.NotResolved", |
| 21 | )<{ |
| 22 | resourceName: string; |
| 23 | }> {} |
| 24 | |
| 25 | export class AssuredworkloadsStillExists extends Data.TaggedError( |
| 26 | "GCP.AssuredWorkloads.StillExists", |
| 27 | )<{ |
| 28 | resourceName: string; |
| 29 | }> {} |
| 30 | |
| 31 | export class OrganizationNotResolved extends Data.TaggedError( |
| 32 | "GCP.AssuredWorkloads.OrganizationNotResolved", |
| 33 | )<{ |
| 34 | project: string; |
| 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 organizationParent = (value: string) => |
| 44 | value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`; |
| 45 | |
| 46 | export const organizationIdOf = (value: string) => lastSegment(value); |
| 47 | |
| 48 | export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase(); |
| 49 | |
| 50 | export const locationParent = (organization: string, location: string) => |
| 51 | `${organizationParent(organization)}/locations/${normalizeLocation(location)}`; |
| 52 | |
| 53 | export const parseName = (name: string, defaultLocation: string) => { |
| 54 | const parts = name.split("/").filter((part) => part.length > 0); |
| 55 | const workloadsAt = parts.lastIndexOf("workloads"); |
| 56 | const locationsAt = parts.lastIndexOf("locations"); |
| 57 | const orgsAt = parts.lastIndexOf("organizations"); |
| 58 | return { |
| 59 | organization: orgsAt >= 0 && parts[orgsAt + 1] ? parts[orgsAt + 1]! : "", |
| 60 | location: |
| 61 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, |
| 62 | id: workloadsAt >= 0 && parts[workloadsAt + 1] ? parts[workloadsAt + 1]! : lastSegment(name), |
| 63 | parent: |
| 64 | workloadsAt > 0 |
| 65 | ? parts.slice(0, workloadsAt).join("/") |
| 66 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 67 | }; |
| 68 | }; |
| 69 | |
| 70 | export const sanitizeDisplayName = (name: string): string => { |
| 71 | let next = name |
| 72 | .replace(/[^A-Za-z0-9 -]/g, " ") |
| 73 | .replace(/\s+/g, " ") |
| 74 | .trim(); |
| 75 | if (next.length === 0) next = "Work"; |
| 76 | if (next.length > MAX_DISPLAY_NAME_LENGTH) { |
| 77 | next = next.slice(0, MAX_DISPLAY_NAME_LENGTH).trim(); |
| 78 | } |
| 79 | if (next.length < MIN_DISPLAY_NAME_LENGTH) { |
| 80 | next = `${next} Load`.slice(0, MAX_DISPLAY_NAME_LENGTH); |
| 81 | } |
| 82 | return next; |
| 83 | }; |
| 84 | |
| 85 | export const toDisplayName = ( |
| 86 | id: string, |
| 87 | requested: string | undefined, |
| 88 | existing: string | undefined, |
| 89 | ) => |
| 90 | Effect.gen(function* () { |
| 91 | if (requested !== undefined) return requested; |
| 92 | if (existing !== undefined) return existing; |
| 93 | return sanitizeDisplayName( |
| 94 | yield* createPhysicalName({ |
| 95 | id, |
| 96 | maxLength: MAX_DISPLAY_NAME_LENGTH, |
| 97 | lowercase: true, |
| 98 | }), |
| 99 | ); |
| 100 | }); |
| 101 | |
| 102 | export const userLabels = ( |
| 103 | labels: Record<string, string | undefined> | null | undefined, |
| 104 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 105 | |
| 106 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 107 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 108 | |
| 109 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 110 | (left ?? "") === (right ?? ""); |
| 111 | |
| 112 | export const sameBool = (left: boolean | undefined, right: boolean | undefined) => |
| 113 | (left ?? true) === (right ?? true); |
| 114 | |
| 115 | export const canonical = (value: unknown): unknown => { |
| 116 | if (value === undefined || value === null) return undefined; |
| 117 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 118 | if (typeof value === "string") { |
| 119 | return value.length === 0 ? undefined : value; |
| 120 | } |
| 121 | if (Array.isArray(value)) { |
| 122 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 123 | return items.length === 0 ? undefined : items; |
| 124 | } |
| 125 | if (typeof value === "object") { |
| 126 | const entries = Object.entries(value as Record<string, unknown>) |
| 127 | .map(([key, item]) => [key, canonical(item)] as const) |
| 128 | .filter(([, item]) => item !== undefined) |
| 129 | .sort(([left], [right]) => left.localeCompare(right)); |
| 130 | if (entries.length === 0) return undefined; |
| 131 | return Object.fromEntries(entries); |
| 132 | } |
| 133 | return undefined; |
| 134 | }; |
| 135 | |
| 136 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 137 | |
| 138 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 139 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 140 | |
| 141 | export const replaceOnIdentity = (changed: boolean) => |
| 142 | changed ? ({ action: "replace" as const, deleteFirst: false } as const) : undefined; |
| 143 | |
| 144 | export const collectPages = <Page, A, E, R>( |
| 145 | pages: Stream.Stream<Page, E, R>, |
| 146 | items: (page: Page) => readonly A[] | undefined, |
| 147 | ) => |
| 148 | pages.pipe( |
| 149 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 150 | Stream.runCollect, |
| 151 | Effect.map((chunk) => Array.from(chunk)), |
| 152 | ); |
| 153 | |
| 154 | export const listWorkloads = (organization: string, location: string) => |
| 155 | collectPages( |
| 156 | assuredworkloads.listOrganizationsLocationsWorkloads.pages({ |
| 157 | parent: locationParent(organization, location), |
| 158 | pageSize: 100, |
| 159 | }), |
| 160 | (page) => page.workloads, |
| 161 | ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as ApiWorkload[]))); |
| 162 | |
| 163 | export const listOwnedWorkloads = (organization: string, region: string) => |
| 164 | Effect.gen(function* () { |
| 165 | const wildcard = yield* listWorkloads(organization, "-"); |
| 166 | const regional = yield* listWorkloads(organization, region); |
| 167 | const byName = new Map<string, ApiWorkload>(); |
| 168 | for (const workload of [...wildcard, ...regional]) { |
| 169 | if (workload.name) byName.set(workload.name, workload); |
| 170 | } |
| 171 | return Array.from(byName.values()).filter((workload) => hasAlchemyLabelMap(workload.labels)); |
| 172 | }); |
| 173 | |
| 174 | export const resourceNameFromOperation = (operation: ApiOperation): string | undefined => { |
| 175 | const response = operation.response; |
| 176 | if (response && typeof response.name === "string" && response.name.includes("/workloads/")) { |
| 177 | return response.name; |
| 178 | } |
| 179 | const metadata = operation.metadata; |
| 180 | if (metadata && typeof metadata.target === "string") { |
| 181 | return metadata.target; |
| 182 | } |
| 183 | if (metadata && typeof metadata.name === "string" && metadata.name.includes("/workloads/")) { |
| 184 | return metadata.name; |
| 185 | } |
| 186 | return undefined; |
| 187 | }; |
| 188 | |
| 189 | /** Workload creation settles within a few minutes. */ |
| 190 | export const waitForOperation = (operation: ApiOperation) => |
| 191 | waitForGcpOperation( |
| 192 | operation, |
| 193 | (name) => assuredworkloads.getOrganizationsLocationsOperations({ name }), |
| 194 | { budget: "10 minutes" }, |
| 195 | ); |
| 196 | |
| 197 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 198 | get: Effect.Effect<A | undefined, E, R>, |
| 199 | name: string, |
| 200 | ) => |
| 201 | get.pipe( |
| 202 | Effect.filterOrFail( |
| 203 | (value): value is NonNullable<A> => value !== undefined, |
| 204 | () => new AssuredworkloadsNotResolved({ resourceName: name }), |
| 205 | ), |
| 206 | Effect.retry({ |
| 207 | while: (error) => error._tag === "GCP.AssuredWorkloads.NotResolved", |
| 208 | times: 8, |
| 209 | schedule: Schedule.spaced("2 seconds"), |
| 210 | }), |
| 211 | ); |
| 212 | |
| 213 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 214 | get: Effect.Effect<A | undefined, E, R>, |
| 215 | name: string, |
| 216 | ) => |
| 217 | get.pipe( |
| 218 | Effect.filterOrFail( |
| 219 | (value) => value === undefined, |
| 220 | () => new AssuredworkloadsStillExists({ resourceName: name }), |
| 221 | ), |
| 222 | Effect.retry({ |
| 223 | while: (error) => error._tag === "GCP.AssuredWorkloads.StillExists", |
| 224 | times: 10, |
| 225 | schedule: Schedule.spaced("2 seconds"), |
| 226 | }), |
| 227 | Effect.asVoid, |
| 228 | ); |
| 229 | |
| 230 | const ancestryParent = (name: string) => |
| 231 | name.startsWith("projects/") |
| 232 | ? resourcemanager.getProjects({ name }).pipe( |
| 233 | Effect.map((resource) => resource.parent), |
| 234 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 235 | ) |
| 236 | : name.startsWith("folders/") |
| 237 | ? resourcemanager.getFolders({ name }).pipe( |
| 238 | Effect.map((folder) => folder.parent), |
| 239 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 240 | ) |
| 241 | : Effect.undefined; |
| 242 | |
| 243 | export const tryResolveOrganization = () => |
| 244 | Effect.gen(function* () { |
| 245 | const env = yield* GcpEnvironment.current; |
| 246 | let current: string | undefined = `projects/${env.project}`; |
| 247 | for (let i = 0; i < 8; i++) { |
| 248 | if (current === undefined) return undefined; |
| 249 | if (current.startsWith("organizations/")) return current; |
| 250 | current = yield* ancestryParent(current); |
| 251 | } |
| 252 | return undefined; |
| 253 | }); |
| 254 | |
| 255 | export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) => |
| 256 | Effect.gen(function* () { |
| 257 | if (explicit !== undefined) return organizationParent(explicit); |
| 258 | if (existing !== undefined) return organizationParent(existing); |
| 259 | const resolved = yield* tryResolveOrganization(); |
| 260 | if (resolved === undefined) { |
| 261 | const env = yield* GcpEnvironment.current; |
| 262 | return yield* new OrganizationNotResolved({ project: env.project }); |
| 263 | } |
| 264 | return resolved; |
| 265 | }); |
| 266 | |
| 267 | export const deleteChildResources = (workload: ApiWorkload) => |
| 268 | Effect.gen(function* () { |
| 269 | const resources = workload.resources ?? []; |
| 270 | const projects = resources.filter( |
| 271 | (resource) => |
| 272 | resource.resourceType === "CONSUMER_PROJECT" || |
| 273 | resource.resourceType === "ENCRYPTION_KEYS_PROJECT", |
| 274 | ); |
| 275 | const folders = resources.filter((resource) => resource.resourceType === "CONSUMER_FOLDER"); |
| 276 | |
| 277 | yield* Effect.forEach( |
| 278 | projects, |
| 279 | (resource) => { |
| 280 | const id = resource.resourceId; |
| 281 | if (id === undefined || id.length === 0) return Effect.void; |
| 282 | return resourcemanager |
| 283 | .deleteProjects({ name: `projects/${id}` }) |
| 284 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 285 | }, |
| 286 | { concurrency: 4 }, |
| 287 | ); |
| 288 | |
| 289 | yield* Effect.forEach( |
| 290 | folders, |
| 291 | (resource) => { |
| 292 | const id = resource.resourceId; |
| 293 | if (id === undefined || id.length === 0) return Effect.void; |
| 294 | return resourcemanager |
| 295 | .deleteFolders({ name: `folders/${id}` }) |
| 296 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 297 | }, |
| 298 | { concurrency: 4 }, |
| 299 | ); |
| 300 | }); |