The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apigateway from "@distilled.cloud/gcp/apigateway_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 DEFAULT_LOCATION = "global"; |
| 12 | export const MAX_NAME_LENGTH = 63; |
| 13 | export const MIN_NAME_LENGTH = 4; |
| 14 | |
| 15 | export type ApiConfigFile = { |
| 16 | /** File path (for example `openapi.yaml`). */ |
| 17 | path: string; |
| 18 | /** |
| 19 | * UTF-8 file contents. Alchemy base64-encodes them for the API Gateway |
| 20 | * wire format. |
| 21 | */ |
| 22 | contents: string; |
| 23 | }; |
| 24 | |
| 25 | export type ApiConfigOpenApiDocument = { |
| 26 | /** OpenAPI Specification document file. */ |
| 27 | document: ApiConfigFile; |
| 28 | }; |
| 29 | |
| 30 | export type ApiConfigGrpcServiceDefinition = { |
| 31 | /** Uncompiled proto sources associated with the descriptor set. */ |
| 32 | source?: readonly ApiConfigFile[]; |
| 33 | /** File descriptor set generated by protoc. */ |
| 34 | fileDescriptorSet?: ApiConfigFile; |
| 35 | }; |
| 36 | |
| 37 | export class ResourceNotResolved extends Data.TaggedError("GCP.ApiGateway.NotResolved")<{ |
| 38 | resourceName: string; |
| 39 | }> {} |
| 40 | |
| 41 | export class ResourceStillExists extends Data.TaggedError("GCP.ApiGateway.StillExists")<{ |
| 42 | resourceName: string; |
| 43 | }> {} |
| 44 | |
| 45 | export class ResourceNotReady extends Data.TaggedError("GCP.ApiGateway.NotReady")<{ |
| 46 | resourceName: string; |
| 47 | state: string; |
| 48 | }> {} |
| 49 | |
| 50 | export class ResourceFailed extends Data.TaggedError("GCP.ApiGateway.Failed")<{ |
| 51 | resourceName: string; |
| 52 | state: string; |
| 53 | }> {} |
| 54 | |
| 55 | export const lastSegment = (value: string) => { |
| 56 | const trimmed = value.replace(/\/+$/, ""); |
| 57 | const parts = trimmed.split("/"); |
| 58 | return parts[parts.length - 1] || trimmed; |
| 59 | }; |
| 60 | |
| 61 | export const rfc1035 = (name: string, fallback = "apigw"): string => { |
| 62 | let next = name |
| 63 | .toLowerCase() |
| 64 | .replace(/[^a-z0-9-]/g, "-") |
| 65 | .replace(/-+/g, "-") |
| 66 | .replace(/^-+|-+$/g, ""); |
| 67 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "a"}${next}`; |
| 68 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 69 | if (next.length === 0) return fallback; |
| 70 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 71 | if (next.length < MIN_NAME_LENGTH) { |
| 72 | next = `${next}${"x".repeat(MIN_NAME_LENGTH)}`.slice(0, MIN_NAME_LENGTH); |
| 73 | } |
| 74 | return next.slice(0, MAX_NAME_LENGTH); |
| 75 | }; |
| 76 | |
| 77 | export const locationParent = (project: string) => |
| 78 | `projects/${project}/locations/${DEFAULT_LOCATION}`; |
| 79 | |
| 80 | export const expandApi = (value: string, project: string) => { |
| 81 | const trimmed = value.replace(/\/+$/, ""); |
| 82 | if (trimmed.includes("/apis/")) return trimmed; |
| 83 | return `${locationParent(project)}/apis/${trimmed}`; |
| 84 | }; |
| 85 | |
| 86 | export const resourceName = (api: string, apiConfigId: string) => `${api}/configs/${apiConfigId}`; |
| 87 | |
| 88 | export const toPhysicalId = ( |
| 89 | id: string, |
| 90 | explicit: string | undefined, |
| 91 | existing: string | undefined, |
| 92 | fallback = "apigw", |
| 93 | ) => |
| 94 | Effect.gen(function* () { |
| 95 | if (explicit !== undefined) return explicit; |
| 96 | if (existing !== undefined) return existing; |
| 97 | return rfc1035( |
| 98 | yield* createPhysicalName({ |
| 99 | id, |
| 100 | maxLength: MAX_NAME_LENGTH, |
| 101 | lowercase: true, |
| 102 | }), |
| 103 | fallback, |
| 104 | ); |
| 105 | }); |
| 106 | |
| 107 | export const parseName = (name: string, collection: string) => { |
| 108 | const parts = name.split("/").filter((part) => part.length > 0); |
| 109 | const collectionAt = parts.lastIndexOf(collection); |
| 110 | const locationsAt = parts.lastIndexOf("locations"); |
| 111 | const projectsAt = parts.lastIndexOf("projects"); |
| 112 | return { |
| 113 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 114 | location: |
| 115 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 116 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 117 | parent: |
| 118 | collectionAt > 0 |
| 119 | ? parts.slice(0, collectionAt).join("/") |
| 120 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 121 | }; |
| 122 | }; |
| 123 | |
| 124 | export const userLabels = ( |
| 125 | labels: Record<string, string | undefined> | null | undefined, |
| 126 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 127 | |
| 128 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 129 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 130 | |
| 131 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 132 | (left ?? "") === (right ?? ""); |
| 133 | |
| 134 | export const canonical = (value: unknown): unknown => { |
| 135 | if (value === undefined || value === null) return undefined; |
| 136 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 137 | if (typeof value === "string") { |
| 138 | return value.length === 0 ? undefined : value; |
| 139 | } |
| 140 | if (Array.isArray(value)) { |
| 141 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 142 | return items.length === 0 ? undefined : items; |
| 143 | } |
| 144 | if (typeof value === "object") { |
| 145 | const entries = Object.entries(value as Record<string, unknown>) |
| 146 | .map(([key, item]) => [key, canonical(item)] as const) |
| 147 | .filter(([, item]) => item !== undefined) |
| 148 | .sort(([left], [right]) => left.localeCompare(right)); |
| 149 | if (entries.length === 0) return undefined; |
| 150 | return Object.fromEntries(entries); |
| 151 | } |
| 152 | return undefined; |
| 153 | }; |
| 154 | |
| 155 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 156 | |
| 157 | export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right); |
| 158 | |
| 159 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 160 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 161 | |
| 162 | export const replaceOnIdentity = (input: { |
| 163 | previousId: string | undefined; |
| 164 | nextId: string | undefined; |
| 165 | previousParent?: string; |
| 166 | nextParent?: string; |
| 167 | extra?: boolean; |
| 168 | }) => { |
| 169 | const parentChanged = |
| 170 | (input.previousParent ?? "") !== "" && |
| 171 | (input.nextParent ?? "") !== "" && |
| 172 | (input.previousParent ?? "") !== (input.nextParent ?? ""); |
| 173 | const replace = |
| 174 | (input.extra ?? false) || |
| 175 | parentChanged || |
| 176 | (input.previousId !== undefined && |
| 177 | input.nextId !== undefined && |
| 178 | input.nextId !== input.previousId); |
| 179 | if (!replace) return undefined; |
| 180 | const samePhysical = |
| 181 | !parentChanged && input.previousId !== undefined && input.nextId === input.previousId; |
| 182 | return { |
| 183 | action: "replace" as const, |
| 184 | deleteFirst: samePhysical, |
| 185 | }; |
| 186 | }; |
| 187 | |
| 188 | export const encodeContents = (contents: string) => |
| 189 | Effect.sync(() => Buffer.from(contents, "utf8").toString("base64")); |
| 190 | |
| 191 | export const encodeFile = (file: ApiConfigFile) => |
| 192 | Effect.gen(function* () { |
| 193 | return { |
| 194 | path: file.path, |
| 195 | contents: yield* encodeContents(file.contents), |
| 196 | }; |
| 197 | }); |
| 198 | |
| 199 | export const encodeOpenApiDocuments = ( |
| 200 | documents: readonly ApiConfigOpenApiDocument[] | undefined, |
| 201 | ) => |
| 202 | documents === undefined |
| 203 | ? Effect.undefined |
| 204 | : Effect.forEach(documents, (document) => |
| 205 | Effect.gen(function* () { |
| 206 | return { document: yield* encodeFile(document.document) }; |
| 207 | }), |
| 208 | ); |
| 209 | |
| 210 | export const encodeFiles = (files: readonly ApiConfigFile[] | undefined) => |
| 211 | files === undefined ? Effect.undefined : Effect.forEach(files, encodeFile); |
| 212 | |
| 213 | export const encodeGrpcServices = ( |
| 214 | services: readonly ApiConfigGrpcServiceDefinition[] | undefined, |
| 215 | ) => |
| 216 | services === undefined |
| 217 | ? Effect.undefined |
| 218 | : Effect.forEach(services, (service) => |
| 219 | Effect.gen(function* () { |
| 220 | return { |
| 221 | source: yield* encodeFiles(service.source), |
| 222 | fileDescriptorSet: service.fileDescriptorSet |
| 223 | ? yield* encodeFile(service.fileDescriptorSet) |
| 224 | : undefined, |
| 225 | }; |
| 226 | }), |
| 227 | ); |
| 228 | |
| 229 | /** |
| 230 | * Wait for an API Gateway long-running operation. API configs take several |
| 231 | * minutes to roll out. An operation that finished with `ALREADY_EXISTS` (6) |
| 232 | * is a lost create race; `notFoundOk` also accepts `NOT_FOUND` (5). |
| 233 | */ |
| 234 | export const waitForOperation = ( |
| 235 | operation: apigateway.ApigatewayOperation, |
| 236 | options?: { notFoundOk?: boolean }, |
| 237 | ) => |
| 238 | waitForGcpOperation( |
| 239 | operation, |
| 240 | (name) => |
| 241 | apigateway.getProjectsLocationsOperations({ name }).pipe( |
| 242 | Effect.catchTag("NotFound", (error) => |
| 243 | options?.notFoundOk === true |
| 244 | ? Effect.succeed<apigateway.ApigatewayOperation>({ |
| 245 | name, |
| 246 | done: true, |
| 247 | }) |
| 248 | : Effect.fail(error), |
| 249 | ), |
| 250 | ), |
| 251 | { budget: "20 minutes" }, |
| 252 | ).pipe( |
| 253 | Effect.catchIf( |
| 254 | (error) => |
| 255 | error._tag === "GCP.OperationFailed" && |
| 256 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), |
| 257 | () => Effect.void, |
| 258 | ), |
| 259 | Effect.asVoid, |
| 260 | ); |
| 261 | |
| 262 | export const waitUntilExists = <A, E, R>( |
| 263 | get: Effect.Effect<A | undefined, E, R>, |
| 264 | name: string, |
| 265 | ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> => |
| 266 | get.pipe( |
| 267 | Effect.filterOrFail( |
| 268 | (value): value is NonNullable<A> => value != null, |
| 269 | () => new ResourceNotResolved({ resourceName: name }), |
| 270 | ), |
| 271 | Effect.retry({ |
| 272 | while: (error) => error instanceof ResourceNotResolved, |
| 273 | times: 8, |
| 274 | schedule: Schedule.spaced("1 second"), |
| 275 | }), |
| 276 | ); |
| 277 | |
| 278 | export const waitUntilGone = <A, E, R>( |
| 279 | get: Effect.Effect<A | undefined, E, R>, |
| 280 | name: string, |
| 281 | ): Effect.Effect<void, E | ResourceStillExists, R> => |
| 282 | get.pipe( |
| 283 | Effect.filterOrFail( |
| 284 | (value) => value === undefined, |
| 285 | () => new ResourceStillExists({ resourceName: name }), |
| 286 | ), |
| 287 | Effect.retry({ |
| 288 | while: (error) => error instanceof ResourceStillExists, |
| 289 | times: 10, |
| 290 | schedule: Schedule.spaced("3 seconds"), |
| 291 | }), |
| 292 | Effect.asVoid, |
| 293 | ); |
| 294 | |
| 295 | const FAILED_STATES = new Set(["FAILED"]); |
| 296 | const READY_STATES = new Set(["ACTIVE"]); |
| 297 | |
| 298 | export const waitUntilReady = <A, E, R>( |
| 299 | get: Effect.Effect<A | undefined, E, R>, |
| 300 | name: string, |
| 301 | stateOf: (value: NonNullable<A>) => string | undefined, |
| 302 | options?: { |
| 303 | times?: number; |
| 304 | interval?: `${number} seconds`; |
| 305 | }, |
| 306 | ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceFailed | ResourceNotReady, R> => |
| 307 | get.pipe( |
| 308 | Effect.filterOrFail( |
| 309 | (value): value is NonNullable<A> => value != null, |
| 310 | () => new ResourceNotResolved({ resourceName: name }), |
| 311 | ), |
| 312 | Effect.filterOrFail( |
| 313 | (value) => !FAILED_STATES.has((stateOf(value) ?? "").toUpperCase()), |
| 314 | (value) => |
| 315 | new ResourceFailed({ |
| 316 | resourceName: name, |
| 317 | state: (stateOf(value) ?? "").toUpperCase(), |
| 318 | }), |
| 319 | ), |
| 320 | Effect.filterOrFail( |
| 321 | (value) => READY_STATES.has((stateOf(value) ?? "").toUpperCase()), |
| 322 | (value) => |
| 323 | new ResourceNotReady({ |
| 324 | resourceName: name, |
| 325 | state: (stateOf(value) ?? "").toUpperCase(), |
| 326 | }), |
| 327 | ), |
| 328 | Effect.retry({ |
| 329 | while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved, |
| 330 | times: options?.times ?? 10, |
| 331 | schedule: Schedule.spaced(options?.interval ?? "8 seconds"), |
| 332 | }), |
| 333 | ); |
| 334 | |
| 335 | const emptyList = <A>() => Effect.succeed<A[]>([]); |
| 336 | |
| 337 | export const collectPages = <Page, Item, E, R>( |
| 338 | pages: Stream.Stream<Page, E, R>, |
| 339 | items: (page: Page) => readonly Item[] | null | undefined, |
| 340 | ) => |
| 341 | pages.pipe( |
| 342 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 343 | Stream.runCollect, |
| 344 | Effect.map((chunk) => Array.from(chunk)), |
| 345 | ); |
| 346 | |
| 347 | export const listApis = (parent: string) => |
| 348 | parent.length === 0 |
| 349 | ? emptyList<apigateway.ApigatewayApi>() |
| 350 | : collectPages( |
| 351 | apigateway.listProjectsLocationsApis.pages({ |
| 352 | parent, |
| 353 | pageSize: 1000, |
| 354 | }), |
| 355 | (page) => page.apis, |
| 356 | ).pipe(Effect.catchTag("NotFound", () => emptyList<apigateway.ApigatewayApi>())); |
| 357 | |
| 358 | export const listConfigs = (parent: string) => |
| 359 | parent.length === 0 |
| 360 | ? emptyList<apigateway.ApigatewayApiConfig>() |
| 361 | : collectPages( |
| 362 | apigateway.listProjectsLocationsApisConfigs.pages({ |
| 363 | parent, |
| 364 | pageSize: 1000, |
| 365 | }), |
| 366 | (page) => page.apiConfigs, |
| 367 | ).pipe(Effect.catchTag("NotFound", () => emptyList<apigateway.ApigatewayApiConfig>())); |
| 368 | |
| 369 | export const listChildResources = <A, E, R>( |
| 370 | parents: readonly { name?: string }[], |
| 371 | list: (name: string) => Effect.Effect<A[], E, R>, |
| 372 | ) => |
| 373 | Effect.forEach( |
| 374 | parents.filter((parent) => (parent.name ?? "").length > 0), |
| 375 | (parent) => list(parent.name!), |
| 376 | { concurrency: 4 }, |
| 377 | ).pipe(Effect.map((groups) => groups.flat())); |