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 resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import * as networkmanagement from "@distilled.cloud/gcp/networkmanagement_v1"; |
| 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 waitForLongRunning } from "../Operation.ts"; |
| 12 | |
| 13 | export const DEFAULT_GLOBAL = "global"; |
| 14 | export const MAX_NAME_LENGTH = 63; |
| 15 | export const MAX_CONNECTIVITY_TEST_ID_LENGTH = 40; |
| 16 | |
| 17 | export class NetworkmanagementNotResolved extends Data.TaggedError( |
| 18 | "GCP.NetworkManagement.NotResolved", |
| 19 | )<{ |
| 20 | resourceName: string; |
| 21 | }> {} |
| 22 | |
| 23 | export class NetworkmanagementStillExists extends Data.TaggedError( |
| 24 | "GCP.NetworkManagement.StillExists", |
| 25 | )<{ |
| 26 | resourceName: string; |
| 27 | }> {} |
| 28 | |
| 29 | export class NetworkmanagementFailed extends Data.TaggedError("GCP.NetworkManagement.Failed")<{ |
| 30 | resourceName: string; |
| 31 | state: string | undefined; |
| 32 | }> {} |
| 33 | |
| 34 | export class OrganizationRequired extends Data.TaggedError( |
| 35 | "GCP.NetworkManagement.OrganizationRequired", |
| 36 | )<{ |
| 37 | project: string; |
| 38 | }> {} |
| 39 | |
| 40 | export const lastSegment = (value: string) => { |
| 41 | const trimmed = value.replace(/\/+$/, ""); |
| 42 | const parts = trimmed.split("/"); |
| 43 | return parts[parts.length - 1] || trimmed; |
| 44 | }; |
| 45 | |
| 46 | export const rfc1035 = ( |
| 47 | name: string, |
| 48 | fallback = "resource", |
| 49 | maxLength = MAX_NAME_LENGTH, |
| 50 | ): string => { |
| 51 | let next = name |
| 52 | .toLowerCase() |
| 53 | .replace(/[^a-z0-9-]/g, "-") |
| 54 | .replace(/-+/g, "-") |
| 55 | .replace(/^-+/, "") |
| 56 | .replace(/-+$/, ""); |
| 57 | if (!/^[a-z]/.test(next)) { |
| 58 | next = `${fallback[0] ?? "n"}${next}`; |
| 59 | } |
| 60 | next = next.slice(0, maxLength).replace(/-+$/, ""); |
| 61 | if (next.length > 0 && !/[a-z0-9]$/.test(next)) { |
| 62 | next = next.slice(0, -1); |
| 63 | } |
| 64 | return next.length > 0 ? next : fallback; |
| 65 | }; |
| 66 | |
| 67 | export const normalizeLocation = (location: string | undefined, fallback: string) => |
| 68 | lastSegment(location ?? fallback).toLowerCase(); |
| 69 | |
| 70 | export const parentOf = (project: string, location: string) => |
| 71 | `projects/${project}/locations/${location}`; |
| 72 | |
| 73 | export const organizationParent = (organization: string, location: string) => |
| 74 | `organizations/${lastSegment(organization)}/locations/${location}`; |
| 75 | |
| 76 | export const organizationIdOf = (value: string) => lastSegment(value); |
| 77 | |
| 78 | export const resourceName = (project: string, location: string, collection: string, id: string) => |
| 79 | `projects/${project}/locations/${location}/${collection}/${id}`; |
| 80 | |
| 81 | export const organizationResourceName = ( |
| 82 | organization: string, |
| 83 | location: string, |
| 84 | collection: string, |
| 85 | id: string, |
| 86 | ) => `organizations/${lastSegment(organization)}/locations/${location}/${collection}/${id}`; |
| 87 | |
| 88 | export const parseName = (name: string, collection: string, fallbackLocation: string) => { |
| 89 | const parts = name.split("/").filter((part) => part.length > 0); |
| 90 | const collectionAt = parts.lastIndexOf(collection); |
| 91 | const locationsAt = parts.lastIndexOf("locations"); |
| 92 | const projectsAt = parts.lastIndexOf("projects"); |
| 93 | const organizationsAt = parts.lastIndexOf("organizations"); |
| 94 | return { |
| 95 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 96 | organization: |
| 97 | organizationsAt >= 0 && parts[organizationsAt + 1] ? parts[organizationsAt + 1]! : "", |
| 98 | location: |
| 99 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 100 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 101 | }; |
| 102 | }; |
| 103 | |
| 104 | export const toPhysicalId = ( |
| 105 | id: string, |
| 106 | explicit: string | undefined, |
| 107 | existing: string | undefined, |
| 108 | fallback = "resource", |
| 109 | maxLength = MAX_NAME_LENGTH, |
| 110 | ) => |
| 111 | Effect.gen(function* () { |
| 112 | if (explicit !== undefined) return rfc1035(explicit, fallback, maxLength); |
| 113 | if (existing !== undefined) return existing; |
| 114 | return rfc1035( |
| 115 | yield* createPhysicalName({ |
| 116 | id, |
| 117 | maxLength, |
| 118 | lowercase: true, |
| 119 | }), |
| 120 | fallback, |
| 121 | maxLength, |
| 122 | ); |
| 123 | }); |
| 124 | |
| 125 | export const userLabels = ( |
| 126 | labels: Record<string, string | undefined> | null | undefined, |
| 127 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 128 | |
| 129 | export const hasAlchemyLabelKeys = ( |
| 130 | labels: Record<string, string | undefined> | null | undefined, |
| 131 | ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 132 | |
| 133 | export const sameJson = (left: unknown, right: unknown) => |
| 134 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 135 | |
| 136 | export const canonicalizeLink = (value: string | undefined) => { |
| 137 | if (value === undefined || value.length === 0) return ""; |
| 138 | return value |
| 139 | .replace(/^https?:\/\/[^/]+\//, "") |
| 140 | .replace(/^compute\/v1\//, "") |
| 141 | .replace(/\/+$/, ""); |
| 142 | }; |
| 143 | |
| 144 | export const sameStringList = ( |
| 145 | left: readonly string[] | undefined, |
| 146 | right: readonly string[] | undefined, |
| 147 | ) => |
| 148 | JSON.stringify([...(left ?? [])].map(canonicalizeLink).sort()) === |
| 149 | JSON.stringify([...(right ?? [])].map(canonicalizeLink).sort()); |
| 150 | |
| 151 | export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) => |
| 152 | pairs.filter(([, changed]) => changed).map(([field]) => field); |
| 153 | |
| 154 | export const toNetworkResource = (project: string, network: string) => { |
| 155 | const trimmed = canonicalizeLink(network); |
| 156 | const id = lastSegment(trimmed); |
| 157 | const parts = trimmed.split("/").filter((part) => part.length > 0); |
| 158 | const projectsAt = parts.lastIndexOf("projects"); |
| 159 | const proj = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project; |
| 160 | return `projects/${proj}/global/networks/${id || trimmed}`; |
| 161 | }; |
| 162 | |
| 163 | export const toSubnetworkResource = (project: string, region: string, subnetwork: string) => { |
| 164 | const trimmed = canonicalizeLink(subnetwork); |
| 165 | if (trimmed.includes("/subnetworks/") || trimmed.includes("/subNetworks/")) { |
| 166 | const parts = trimmed.split("/").filter((part) => part.length > 0); |
| 167 | const projectsAt = parts.lastIndexOf("projects"); |
| 168 | const regionsAt = parts.lastIndexOf("regions"); |
| 169 | const proj = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project; |
| 170 | const loc = regionsAt >= 0 && parts[regionsAt + 1] ? parts[regionsAt + 1]! : region; |
| 171 | return `projects/${proj}/regions/${loc}/subnetworks/${lastSegment(trimmed)}`; |
| 172 | } |
| 173 | return `projects/${project}/regions/${region}/subnetworks/${lastSegment(trimmed)}`; |
| 174 | }; |
| 175 | |
| 176 | export const toRegionalComputeResource = ( |
| 177 | project: string, |
| 178 | region: string, |
| 179 | collection: string, |
| 180 | value: string, |
| 181 | ) => { |
| 182 | const trimmed = canonicalizeLink(value); |
| 183 | if (trimmed.includes(`/${collection}/`)) { |
| 184 | const parts = trimmed.split("/").filter((part) => part.length > 0); |
| 185 | const projectsAt = parts.lastIndexOf("projects"); |
| 186 | const regionsAt = parts.lastIndexOf("regions"); |
| 187 | const proj = projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : project; |
| 188 | const loc = regionsAt >= 0 && parts[regionsAt + 1] ? parts[regionsAt + 1]! : region; |
| 189 | return `projects/${proj}/regions/${loc}/${collection}/${lastSegment(trimmed)}`; |
| 190 | } |
| 191 | return `projects/${project}/regions/${region}/${collection}/${lastSegment(trimmed)}`; |
| 192 | }; |
| 193 | |
| 194 | const getOperation = (name: string) => |
| 195 | name.startsWith("organizations/") |
| 196 | ? networkmanagement.getOrganizationsLocationsGlobalOperations({ name }) |
| 197 | : networkmanagement.getProjectsLocationsGlobalOperations({ name }); |
| 198 | |
| 199 | /** |
| 200 | * Wait for a Network Management long-running operation. Connectivity tests |
| 201 | * and flow-log configs settle within minutes. |
| 202 | * `ALREADY_EXISTS` (a concurrent create won) always succeeds; |
| 203 | * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has |
| 204 | * already been garbage-collected (deletes). |
| 205 | */ |
| 206 | export const waitForOperation = ( |
| 207 | operation: networkmanagement.Operation, |
| 208 | options?: { notFoundOk?: boolean }, |
| 209 | ) => |
| 210 | waitForLongRunning(operation, getOperation, { budget: "10 minutes" }).pipe( |
| 211 | Effect.catchIf( |
| 212 | (error) => |
| 213 | error._tag === "GCP.OperationFailed" && |
| 214 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), |
| 215 | () => Effect.void, |
| 216 | ), |
| 217 | Effect.catchIf( |
| 218 | (error) => options?.notFoundOk === true && error._tag === "NotFound", |
| 219 | () => Effect.void, |
| 220 | ), |
| 221 | ); |
| 222 | |
| 223 | export const waitUntilPresent = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) => |
| 224 | get.pipe( |
| 225 | Effect.flatMap((value) => |
| 226 | value |
| 227 | ? Effect.succeed(value) |
| 228 | : Effect.fail(new NetworkmanagementNotResolved({ resourceName: name })), |
| 229 | ), |
| 230 | Effect.retry({ |
| 231 | while: (error) => error instanceof NetworkmanagementNotResolved, |
| 232 | times: 8, |
| 233 | schedule: Schedule.spaced("1 second"), |
| 234 | }), |
| 235 | ); |
| 236 | |
| 237 | export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) => |
| 238 | get.pipe( |
| 239 | Effect.flatMap((value) => |
| 240 | value === undefined |
| 241 | ? Effect.void |
| 242 | : Effect.fail(new NetworkmanagementStillExists({ resourceName: name })), |
| 243 | ), |
| 244 | Effect.retry({ |
| 245 | while: (error) => error instanceof NetworkmanagementStillExists, |
| 246 | times: 10, |
| 247 | schedule: Schedule.spaced("2 seconds"), |
| 248 | }), |
| 249 | ); |
| 250 | |
| 251 | const PENDING_STATES = new Set(["STATE_UNSPECIFIED", "ACTIVATING", "SUSPENDING", "DELETING"]); |
| 252 | |
| 253 | const FAILED_STATES = new Set(["DELETED"]); |
| 254 | |
| 255 | export const waitUntilReady = <A extends { state?: string }, E, R>( |
| 256 | get: Effect.Effect<A | undefined, E, R>, |
| 257 | name: string, |
| 258 | ) => |
| 259 | get.pipe( |
| 260 | Effect.filterOrFail( |
| 261 | (value): value is A => value !== undefined, |
| 262 | () => new NetworkmanagementNotResolved({ resourceName: name }), |
| 263 | ), |
| 264 | Effect.filterOrFail( |
| 265 | (value) => !FAILED_STATES.has(value.state ?? ""), |
| 266 | (value) => new NetworkmanagementFailed({ resourceName: name, state: value.state }), |
| 267 | ), |
| 268 | Effect.filterOrFail( |
| 269 | (value) => !PENDING_STATES.has(value.state ?? ""), |
| 270 | () => new NetworkmanagementNotResolved({ resourceName: name }), |
| 271 | ), |
| 272 | Effect.retry({ |
| 273 | while: (error) => error instanceof NetworkmanagementNotResolved, |
| 274 | times: 10, |
| 275 | schedule: Schedule.spaced("4 seconds"), |
| 276 | }), |
| 277 | ); |
| 278 | |
| 279 | /** Collect every page; a missing parent (`NotFound`) lists as empty. */ |
| 280 | export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>( |
| 281 | stream: Stream.Stream<Page, E, R>, |
| 282 | pick: (page: Page) => readonly Item[] | undefined, |
| 283 | ) => |
| 284 | stream.pipe( |
| 285 | Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])), |
| 286 | Stream.runCollect, |
| 287 | Effect.map((chunk): Item[] => Array.from(chunk)), |
| 288 | Effect.catchIf( |
| 289 | (error) => error._tag === "NotFound", |
| 290 | () => Effect.succeed<Item[]>([]), |
| 291 | ), |
| 292 | ); |
| 293 | |
| 294 | const parentOfResource = (name: string) => |
| 295 | name.startsWith("projects/") |
| 296 | ? resourcemanager.getProjects({ name }).pipe( |
| 297 | Effect.map((resource) => resource.parent), |
| 298 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 299 | ) |
| 300 | : name.startsWith("folders/") |
| 301 | ? resourcemanager.getFolders({ name }).pipe( |
| 302 | Effect.map((folder) => folder.parent), |
| 303 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 304 | ) |
| 305 | : Effect.undefined; |
| 306 | |
| 307 | const tryResolveOrganizationId = (project: string) => |
| 308 | Effect.gen(function* () { |
| 309 | let current: string | undefined = `projects/${project}`; |
| 310 | for (let i = 0; i < 8; i++) { |
| 311 | if (current === undefined) return undefined; |
| 312 | if (current.startsWith("organizations/")) return lastSegment(current); |
| 313 | current = yield* parentOfResource(current); |
| 314 | } |
| 315 | return undefined; |
| 316 | }); |
| 317 | |
| 318 | export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) => |
| 319 | Effect.gen(function* () { |
| 320 | if (explicit !== undefined) return lastSegment(explicit); |
| 321 | if (existing !== undefined) return lastSegment(existing); |
| 322 | const env = yield* GcpEnvironment.current; |
| 323 | const resolved = yield* tryResolveOrganizationId(env.project); |
| 324 | if (resolved === undefined) { |
| 325 | return yield* new OrganizationRequired({ project: env.project }); |
| 326 | } |
| 327 | return resolved; |
| 328 | }); |
| 329 | |
| 330 | export const listOrganizations = (project: string) => |
| 331 | Effect.gen(function* () { |
| 332 | const resolved = yield* tryResolveOrganizationId(project); |
| 333 | return resolved === undefined ? [] : [resolved]; |
| 334 | }); |