The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cnr from "@distilled.cloud/gcp/cloudnumberregistry_v1alpha"; |
| 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 waitForLongRunning, type LongRunningOperation } from "../Operation.ts"; |
| 10 | |
| 11 | export const DEFAULT_LOCATION = "global"; |
| 12 | export const MAX_NAME_LENGTH = 63; |
| 13 | |
| 14 | export class ResourceNotResolved extends Data.TaggedError("GCP.CloudNumberRegistry.NotResolved")<{ |
| 15 | resourceName: string; |
| 16 | }> {} |
| 17 | |
| 18 | export class ResourceStillExists extends Data.TaggedError("GCP.CloudNumberRegistry.StillExists")<{ |
| 19 | resourceName: string; |
| 20 | }> {} |
| 21 | |
| 22 | export const lastSegment = (value: string) => { |
| 23 | const trimmed = value.replace(/\/+$/, ""); |
| 24 | const parts = trimmed.split("/"); |
| 25 | return parts[parts.length - 1] || trimmed; |
| 26 | }; |
| 27 | |
| 28 | export const rfc1035 = (name: string, fallback = "cnr"): string => { |
| 29 | let next = name |
| 30 | .toLowerCase() |
| 31 | .replace(/[^a-z0-9-]/g, "-") |
| 32 | .replace(/-+/g, "-") |
| 33 | .replace(/^-+|-+$/g, ""); |
| 34 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "c"}${next}`; |
| 35 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 36 | if (next.length === 0) return fallback; |
| 37 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 38 | if (next.length < 3) next = `${next}xxx`.slice(0, 3); |
| 39 | return next.slice(0, MAX_NAME_LENGTH); |
| 40 | }; |
| 41 | |
| 42 | export const normalizeLocation = (location: string | undefined) => |
| 43 | lastSegment(location ?? DEFAULT_LOCATION).toLowerCase(); |
| 44 | |
| 45 | export const parentOf = (project: string, location: string | undefined) => |
| 46 | `projects/${project}/locations/${normalizeLocation(location)}`; |
| 47 | |
| 48 | export const resourceName = (project: string, location: string, collection: string, id: string) => |
| 49 | `${parentOf(project, location)}/${collection}/${id}`; |
| 50 | |
| 51 | export const toPhysicalId = ( |
| 52 | id: string, |
| 53 | explicit: string | undefined, |
| 54 | existing: string | undefined, |
| 55 | fallback = "cnr", |
| 56 | ) => |
| 57 | Effect.gen(function* () { |
| 58 | if (explicit !== undefined) return rfc1035(explicit, fallback); |
| 59 | if (existing !== undefined) return existing; |
| 60 | return rfc1035( |
| 61 | yield* createPhysicalName({ |
| 62 | id, |
| 63 | maxLength: MAX_NAME_LENGTH, |
| 64 | lowercase: true, |
| 65 | }), |
| 66 | fallback, |
| 67 | ); |
| 68 | }); |
| 69 | |
| 70 | export const parseName = (name: string, collection: string) => { |
| 71 | const parts = name.split("/").filter((part) => part.length > 0); |
| 72 | const collectionAt = parts.lastIndexOf(collection); |
| 73 | const locationsAt = parts.lastIndexOf("locations"); |
| 74 | const projectsAt = parts.lastIndexOf("projects"); |
| 75 | return { |
| 76 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 77 | location: |
| 78 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 79 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 80 | parent: |
| 81 | collectionAt > 0 |
| 82 | ? parts.slice(0, collectionAt).join("/") |
| 83 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 84 | }; |
| 85 | }; |
| 86 | |
| 87 | export const expandName = ( |
| 88 | value: string, |
| 89 | project: string, |
| 90 | location: string, |
| 91 | collection: string, |
| 92 | ) => { |
| 93 | const trimmed = value.replace(/\/+$/, ""); |
| 94 | if (trimmed.includes("/")) return trimmed; |
| 95 | return resourceName(project, location, collection, trimmed); |
| 96 | }; |
| 97 | |
| 98 | export const userLabels = ( |
| 99 | labels: Record<string, string | undefined> | null | undefined, |
| 100 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 101 | |
| 102 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 103 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 104 | |
| 105 | export const canonical = (value: unknown): unknown => { |
| 106 | if (value === undefined || value === null) return undefined; |
| 107 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 108 | if (typeof value === "string") { |
| 109 | return value.length === 0 ? undefined : value; |
| 110 | } |
| 111 | if (Array.isArray(value)) { |
| 112 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 113 | return items.length === 0 ? undefined : items; |
| 114 | } |
| 115 | if (typeof value === "object") { |
| 116 | const entries = Object.entries(value as Record<string, unknown>) |
| 117 | .map(([key, item]) => [key, canonical(item)] as const) |
| 118 | .filter(([, item]) => item !== undefined) |
| 119 | .sort(([left], [right]) => left.localeCompare(right)); |
| 120 | if (entries.length === 0) return undefined; |
| 121 | return Object.fromEntries(entries); |
| 122 | } |
| 123 | return undefined; |
| 124 | }; |
| 125 | |
| 126 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 127 | |
| 128 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 129 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 130 | |
| 131 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 132 | (left ?? "") === (right ?? ""); |
| 133 | |
| 134 | export const sameRef = (left: string | undefined, right: string | undefined) => |
| 135 | lastSegment(left ?? "") === lastSegment(right ?? ""); |
| 136 | |
| 137 | export const sameStringList = ( |
| 138 | left: readonly string[] | undefined, |
| 139 | right: readonly string[] | undefined, |
| 140 | ) => fingerprint([...(left ?? [])].sort()) === fingerprint([...(right ?? [])].sort()); |
| 141 | |
| 142 | export const replaceOnIdentity = (input: { |
| 143 | previousId: string | undefined; |
| 144 | nextId: string | undefined; |
| 145 | previousLocation: string; |
| 146 | nextLocation: string; |
| 147 | extra?: boolean; |
| 148 | }) => { |
| 149 | const replace = |
| 150 | (input.extra ?? false) || |
| 151 | (input.previousId !== undefined && |
| 152 | input.nextId !== undefined && |
| 153 | input.nextId !== input.previousId) || |
| 154 | input.previousLocation !== input.nextLocation; |
| 155 | if (!replace) return undefined; |
| 156 | const samePhysical = |
| 157 | input.previousLocation === input.nextLocation && |
| 158 | input.previousId !== undefined && |
| 159 | input.nextId === input.previousId; |
| 160 | return { |
| 161 | action: "replace" as const, |
| 162 | deleteFirst: samePhysical, |
| 163 | }; |
| 164 | }; |
| 165 | |
| 166 | export const waitUntilExists = <A, E, R>( |
| 167 | get: Effect.Effect<A | undefined, E, R>, |
| 168 | name: string, |
| 169 | ): Effect.Effect<Exclude<A, undefined>, E | ResourceNotResolved, R> => |
| 170 | get.pipe( |
| 171 | Effect.filterOrFail( |
| 172 | (value): value is Exclude<A, undefined> => value !== undefined, |
| 173 | () => new ResourceNotResolved({ resourceName: name }), |
| 174 | ), |
| 175 | Effect.retry({ |
| 176 | while: (error) => error instanceof ResourceNotResolved, |
| 177 | times: 8, |
| 178 | schedule: Schedule.spaced("1 second"), |
| 179 | }), |
| 180 | ); |
| 181 | |
| 182 | export const waitUntilGone = <A, E, R>( |
| 183 | get: Effect.Effect<A | undefined, E, R>, |
| 184 | name: string, |
| 185 | ): Effect.Effect<void, E | ResourceStillExists, R> => |
| 186 | get.pipe( |
| 187 | Effect.filterOrFail( |
| 188 | (value) => value === undefined, |
| 189 | () => new ResourceStillExists({ resourceName: name }), |
| 190 | ), |
| 191 | Effect.asVoid, |
| 192 | Effect.retry({ |
| 193 | while: (error) => error instanceof ResourceStillExists, |
| 194 | times: 10, |
| 195 | schedule: Schedule.spaced("2 seconds"), |
| 196 | }), |
| 197 | ); |
| 198 | |
| 199 | /** The API rejects the `locations/-` wildcard; resources live in `global`. */ |
| 200 | export const listAtLocation = <A, E, R>( |
| 201 | project: string, |
| 202 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 203 | ) => list(`projects/${project}/locations/${DEFAULT_LOCATION}`); |
| 204 | |
| 205 | export const listLabeledPages = <Page, A, E, R>( |
| 206 | pages: Stream.Stream<Page, E, R>, |
| 207 | items: (page: Page) => readonly A[] | undefined, |
| 208 | labelsOf: (item: A) => Record<string, string | undefined> | null | undefined, |
| 209 | ) => |
| 210 | pages.pipe( |
| 211 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 212 | Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))), |
| 213 | Stream.runCollect, |
| 214 | Effect.map((chunk) => Array.from(chunk)), |
| 215 | ); |
| 216 | |
| 217 | /** Registry and IPAM scope operations finish within a few minutes. */ |
| 218 | const OPERATION_BUDGET = "10 minutes"; |
| 219 | |
| 220 | /** |
| 221 | * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a |
| 222 | * concurrent create won the race; reconcile observes the resource next. |
| 223 | */ |
| 224 | export const waitForOperation = (operation: LongRunningOperation) => |
| 225 | waitForLongRunning(operation, (name) => cnr.getProjectsLocationsOperations({ name }), { |
| 226 | budget: OPERATION_BUDGET, |
| 227 | }).pipe( |
| 228 | Effect.catchIf( |
| 229 | (error) => error._tag === "GCP.OperationFailed" && error.code === 6, |
| 230 | () => Effect.succeed(operation), |
| 231 | ), |
| 232 | ); |
| 233 | |
| 234 | /** |
| 235 | * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5) |
| 236 | * means the resource is already gone. |
| 237 | */ |
| 238 | export const waitForDeleteOperation = (operation: LongRunningOperation) => |
| 239 | waitForOperation(operation).pipe( |
| 240 | Effect.catchIf( |
| 241 | (error) => |
| 242 | error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5), |
| 243 | () => Effect.succeed(operation), |
| 244 | ), |
| 245 | ); |