The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as appengine from "@distilled.cloud/gcp/appengine_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Data from "effect/Data"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Stream from "effect/Stream"; |
| 6 | import { GcpEnvironment } from "../Environment.ts"; |
| 7 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 8 | |
| 9 | // App Engine location ids (`us-central`, `europe-west`) are not Compute regions, and the app's own locationId wins. |
| 10 | export const DEFAULT_LOCATION = "us-central"; |
| 11 | export const DEFAULT_SERVICE = "default"; |
| 12 | export const DEFAULT_ACTION = "ALLOW"; |
| 13 | export const DEFAULT_SOURCE_RANGE = "*"; |
| 14 | export const DEFAULT_SSL_MANAGEMENT = "AUTOMATIC"; |
| 15 | export const MAX_DISPLAY_NAME_LENGTH = 100; |
| 16 | export const MAX_DESCRIPTION_LENGTH = 400; |
| 17 | export const MAX_VERSION_ID_LENGTH = 63; |
| 18 | export const OWNERSHIP_ENV = "ALCHEMY_OWNERSHIP"; |
| 19 | export const CATCH_ALL_PRIORITY = 2147483647; |
| 20 | |
| 21 | export class ApplicationNotResolved extends Data.TaggedError( |
| 22 | "GCP.AppEngine.ApplicationNotResolved", |
| 23 | )<{ |
| 24 | appsId: string; |
| 25 | }> {} |
| 26 | |
| 27 | export const lastSegment = (value: string) => { |
| 28 | const trimmed = value.replace(/\/+$/, ""); |
| 29 | const parts = trimmed.split("/"); |
| 30 | return parts[parts.length - 1] || trimmed; |
| 31 | }; |
| 32 | |
| 33 | export const jsonEqual = (left: unknown, right: unknown) => |
| 34 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 35 | |
| 36 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 37 | (left ?? "") === (right ?? ""); |
| 38 | |
| 39 | export const updateMaskOf = (...fields: Array<string | undefined>) => |
| 40 | fields.filter((field): field is string => field !== undefined).join(","); |
| 41 | |
| 42 | const markerOf = (_labels: Record<string, string>, stack: string, stage: string, id: string) => |
| 43 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 44 | |
| 45 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 46 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 47 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 48 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 49 | let marker = markerOf(labels, stack, stage, id); |
| 50 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 51 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 52 | stack = stack.slice(0, -1); |
| 53 | } else if (stage.length >= id.length) { |
| 54 | stage = stage.slice(0, -1); |
| 55 | } else { |
| 56 | id = id.slice(0, -1); |
| 57 | } |
| 58 | marker = markerOf(labels, stack, stage, id); |
| 59 | } |
| 60 | return marker.slice(0, maxLength); |
| 61 | }; |
| 62 | |
| 63 | export const encodeOwnership = ( |
| 64 | labels: Record<string, string>, |
| 65 | text: string | undefined, |
| 66 | maxLength = 8000, |
| 67 | ): string => { |
| 68 | const trimmed = text?.trim(); |
| 69 | if (!trimmed) return fitMarker(labels, maxLength); |
| 70 | const minMarker = 24; |
| 71 | const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker)); |
| 72 | const marker = fitMarker(labels, maxLength - reserved); |
| 73 | return `${marker} ${trimmed}`.slice(0, maxLength); |
| 74 | }; |
| 75 | |
| 76 | export const parseOwnership = ( |
| 77 | text: string | undefined, |
| 78 | ): { |
| 79 | labels: Record<string, string>; |
| 80 | text: string | undefined; |
| 81 | } => { |
| 82 | if (!text?.startsWith("[alchemy ")) { |
| 83 | return { labels: {}, text }; |
| 84 | } |
| 85 | const end = text.indexOf("]"); |
| 86 | if (end < 0) return { labels: {}, text }; |
| 87 | const labels: Record<string, string> = {}; |
| 88 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 89 | const eq = part.indexOf("="); |
| 90 | if (eq > 0) { |
| 91 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 92 | } |
| 93 | } |
| 94 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 95 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 96 | }; |
| 97 | |
| 98 | export const hasOwnershipMarker = (text: string | undefined) => |
| 99 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 100 | |
| 101 | const prefixMatch = (expected: string, observed: string) => |
| 102 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 103 | |
| 104 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 105 | Effect.gen(function* () { |
| 106 | const expected = yield* createInternalLabels(id); |
| 107 | const { labels } = parseOwnership(text); |
| 108 | if (!hasOwnershipMarker(text)) return false; |
| 109 | const exact = yield* hasAlchemyLabels(id, labels); |
| 110 | if (exact) return true; |
| 111 | return ( |
| 112 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 113 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 114 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 115 | ); |
| 116 | }); |
| 117 | |
| 118 | export const ownershipLabels = (id: string) => createInternalLabels(id); |
| 119 | |
| 120 | export const rfc1035 = (name: string, maxLength: number): string => { |
| 121 | let next = name |
| 122 | .toLowerCase() |
| 123 | .replace(/[^a-z0-9-]/g, "-") |
| 124 | .replace(/-+/g, "-") |
| 125 | .replace(/^-+/, "") |
| 126 | .replace(/-+$/, ""); |
| 127 | if (!/^[a-z]/.test(next)) next = `v${next}`; |
| 128 | if (next.startsWith("ah-") || next === "default" || next === "latest") { |
| 129 | next = `v-${next}`; |
| 130 | } |
| 131 | next = next.slice(0, maxLength).replace(/-+$/, ""); |
| 132 | return next.length > 0 ? next : "version"; |
| 133 | }; |
| 134 | |
| 135 | export const toResourceId = ( |
| 136 | id: string, |
| 137 | requested: string | undefined, |
| 138 | existing: string | undefined, |
| 139 | maxLength = MAX_VERSION_ID_LENGTH, |
| 140 | ) => |
| 141 | Effect.gen(function* () { |
| 142 | if (requested !== undefined && requested.length > 0) return requested; |
| 143 | if (existing !== undefined && existing.length > 0) return existing; |
| 144 | return rfc1035( |
| 145 | yield* createPhysicalName({ |
| 146 | id, |
| 147 | maxLength, |
| 148 | lowercase: true, |
| 149 | }), |
| 150 | maxLength, |
| 151 | ); |
| 152 | }); |
| 153 | |
| 154 | export const toDisplayName = ( |
| 155 | id: string, |
| 156 | requested: string | undefined, |
| 157 | existing: string | undefined, |
| 158 | ) => |
| 159 | Effect.gen(function* () { |
| 160 | if (requested !== undefined && requested.length > 0) { |
| 161 | return requested.slice(0, MAX_DISPLAY_NAME_LENGTH); |
| 162 | } |
| 163 | if (existing !== undefined && existing.length > 0) { |
| 164 | return existing.slice(0, MAX_DISPLAY_NAME_LENGTH); |
| 165 | } |
| 166 | return yield* toResourceId(id, undefined, undefined, 40); |
| 167 | }); |
| 168 | |
| 169 | export const toPriority = ( |
| 170 | id: string, |
| 171 | requested: number | undefined, |
| 172 | existing: number | undefined, |
| 173 | ) => |
| 174 | Effect.gen(function* () { |
| 175 | if (requested !== undefined) return requested; |
| 176 | if (existing !== undefined) return existing; |
| 177 | const name = yield* createPhysicalName({ |
| 178 | id, |
| 179 | maxLength: 32, |
| 180 | lowercase: true, |
| 181 | }); |
| 182 | let hash = 2166136261; |
| 183 | for (const ch of name) { |
| 184 | hash ^= ch.charCodeAt(0); |
| 185 | hash = Math.imul(hash, 16777619); |
| 186 | } |
| 187 | const priority = 10000 + ((hash >>> 0) % 900000); |
| 188 | return priority === CATCH_ALL_PRIORITY ? priority - 1 : priority; |
| 189 | }); |
| 190 | |
| 191 | export const resolveAppsId = (requested: string | undefined, existing: string | undefined) => |
| 192 | Effect.gen(function* () { |
| 193 | if (requested !== undefined && requested.length > 0) return requested; |
| 194 | if (existing !== undefined && existing.length > 0) return existing; |
| 195 | const env = yield* GcpEnvironment.current; |
| 196 | return env.project; |
| 197 | }); |
| 198 | |
| 199 | export const getApplication = (appsId: string) => |
| 200 | appsId.length === 0 |
| 201 | ? Effect.undefined |
| 202 | : appengine.getApps({ appsId }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 203 | |
| 204 | export const resolveLocation = ( |
| 205 | requested: string | undefined, |
| 206 | existing: string | undefined, |
| 207 | appsId: string, |
| 208 | ) => |
| 209 | Effect.gen(function* () { |
| 210 | if (requested !== undefined && requested.length > 0) { |
| 211 | return lastSegment(requested); |
| 212 | } |
| 213 | if (existing !== undefined && existing.length > 0) { |
| 214 | return lastSegment(existing); |
| 215 | } |
| 216 | const app = yield* getApplication(appsId); |
| 217 | return app?.locationId ?? DEFAULT_LOCATION; |
| 218 | }); |
| 219 | |
| 220 | export const catchMissing = <A, E extends { readonly _tag: string }, R>( |
| 221 | effect: Effect.Effect<A, E, R>, |
| 222 | ) => |
| 223 | effect.pipe( |
| 224 | Effect.catchIf( |
| 225 | (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound", |
| 226 | () => Effect.undefined, |
| 227 | ), |
| 228 | ); |
| 229 | |
| 230 | export const ignoreMissing = <E extends { readonly _tag: string }, R>( |
| 231 | effect: Effect.Effect<unknown, E, R>, |
| 232 | ) => |
| 233 | effect.pipe( |
| 234 | Effect.catchIf( |
| 235 | (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound", |
| 236 | () => Effect.void, |
| 237 | ), |
| 238 | ); |
| 239 | |
| 240 | const emptyList = <A>() => Effect.succeed([] as A[]); |
| 241 | |
| 242 | export const listAuthorizedCertificates = (appsId: string) => |
| 243 | appsId.length === 0 |
| 244 | ? emptyList<appengine.AuthorizedCertificate>() |
| 245 | : appengine.listAppsAuthorizedCertificates |
| 246 | .pages({ appsId, pageSize: 100, view: "BASIC_CERTIFICATE" }) |
| 247 | .pipe( |
| 248 | Stream.flatMap((page) => Stream.fromIterable(page.certificates ?? [])), |
| 249 | Stream.runCollect, |
| 250 | Effect.map((chunk) => Array.from(chunk)), |
| 251 | Effect.catchTag("NotFound", () => emptyList<appengine.AuthorizedCertificate>()), |
| 252 | ); |
| 253 | |
| 254 | export const listApplicationsAuthorizedCertificates = ( |
| 255 | projectsId: string, |
| 256 | locationsId: string, |
| 257 | applicationsId: string, |
| 258 | ) => |
| 259 | projectsId.length === 0 || applicationsId.length === 0 |
| 260 | ? emptyList<appengine.AuthorizedCertificate>() |
| 261 | : appengine.listProjectsLocationsApplicationsAuthorizedCertificates |
| 262 | .pages({ |
| 263 | projectsId, |
| 264 | locationsId, |
| 265 | applicationsId, |
| 266 | pageSize: 100, |
| 267 | view: "BASIC_CERTIFICATE", |
| 268 | }) |
| 269 | .pipe( |
| 270 | Stream.flatMap((page) => Stream.fromIterable(page.certificates ?? [])), |
| 271 | Stream.runCollect, |
| 272 | Effect.map((chunk) => Array.from(chunk)), |
| 273 | Effect.catchTag("NotFound", () => emptyList<appengine.AuthorizedCertificate>()), |
| 274 | ); |
| 275 | |
| 276 | export const listDomainMappings = (appsId: string) => |
| 277 | appsId.length === 0 |
| 278 | ? emptyList<appengine.DomainMapping>() |
| 279 | : appengine.listAppsDomainMappings.pages({ appsId, pageSize: 100 }).pipe( |
| 280 | Stream.flatMap((page) => Stream.fromIterable(page.domainMappings ?? [])), |
| 281 | Stream.runCollect, |
| 282 | Effect.map((chunk) => Array.from(chunk)), |
| 283 | Effect.catchTag("NotFound", () => emptyList<appengine.DomainMapping>()), |
| 284 | ); |
| 285 | |
| 286 | export const listApplicationsDomainMappings = ( |
| 287 | projectsId: string, |
| 288 | locationsId: string, |
| 289 | applicationsId: string, |
| 290 | ) => |
| 291 | projectsId.length === 0 || applicationsId.length === 0 |
| 292 | ? emptyList<appengine.DomainMapping>() |
| 293 | : appengine.listProjectsLocationsApplicationsDomainMappings |
| 294 | .pages({ |
| 295 | projectsId, |
| 296 | locationsId, |
| 297 | applicationsId, |
| 298 | pageSize: 100, |
| 299 | }) |
| 300 | .pipe( |
| 301 | Stream.flatMap((page) => Stream.fromIterable(page.domainMappings ?? [])), |
| 302 | Stream.runCollect, |
| 303 | Effect.map((chunk) => Array.from(chunk)), |
| 304 | Effect.catchTag("NotFound", () => emptyList<appengine.DomainMapping>()), |
| 305 | ); |
| 306 | |
| 307 | export const listFirewallRules = (appsId: string) => |
| 308 | appsId.length === 0 |
| 309 | ? emptyList<appengine.FirewallRule>() |
| 310 | : appengine.listAppsFirewallIngressRules.pages({ appsId, pageSize: 100 }).pipe( |
| 311 | Stream.flatMap((page) => Stream.fromIterable(page.ingressRules ?? [])), |
| 312 | Stream.runCollect, |
| 313 | Effect.map((chunk) => Array.from(chunk)), |
| 314 | Effect.catchTag("NotFound", () => emptyList<appengine.FirewallRule>()), |
| 315 | ); |
| 316 | |
| 317 | export const listServices = (appsId: string) => |
| 318 | appsId.length === 0 |
| 319 | ? emptyList<appengine.Service>() |
| 320 | : appengine.listAppsServices.pages({ appsId, pageSize: 100 }).pipe( |
| 321 | Stream.flatMap((page) => Stream.fromIterable(page.services ?? [])), |
| 322 | Stream.runCollect, |
| 323 | Effect.map((chunk) => Array.from(chunk)), |
| 324 | Effect.catchTag("NotFound", () => emptyList<appengine.Service>()), |
| 325 | ); |
| 326 | |
| 327 | export const listVersions = (appsId: string, servicesId: string) => |
| 328 | appsId.length === 0 || servicesId.length === 0 |
| 329 | ? emptyList<appengine.Version>() |
| 330 | : appengine.listAppsServicesVersions |
| 331 | .pages({ |
| 332 | appsId, |
| 333 | servicesId, |
| 334 | pageSize: 100, |
| 335 | view: "FULL", |
| 336 | }) |
| 337 | .pipe( |
| 338 | Stream.flatMap((page) => Stream.fromIterable(page.versions ?? [])), |
| 339 | Stream.runCollect, |
| 340 | Effect.map((chunk) => Array.from(chunk)), |
| 341 | Effect.catchTag("NotFound", () => emptyList<appengine.Version>()), |
| 342 | ); |
| 343 | |
| 344 | export const findOwnedCertificate = ( |
| 345 | id: string, |
| 346 | certificates: readonly appengine.AuthorizedCertificate[], |
| 347 | ) => |
| 348 | Effect.gen(function* () { |
| 349 | for (const certificate of certificates) { |
| 350 | if (yield* ownedByAlchemy(id, certificate.displayName)) { |
| 351 | return certificate; |
| 352 | } |
| 353 | } |
| 354 | return undefined; |
| 355 | }); |
| 356 | |
| 357 | export const findOwnedFirewallRule = (id: string, rules: readonly appengine.FirewallRule[]) => |
| 358 | Effect.gen(function* () { |
| 359 | for (const rule of rules) { |
| 360 | if (yield* ownedByAlchemy(id, rule.description)) { |
| 361 | return rule; |
| 362 | } |
| 363 | } |
| 364 | return undefined; |
| 365 | }); |
| 366 | |
| 367 | export const envVariablesOf = (env: appengine.StringMap | undefined): Record<string, string> => { |
| 368 | const result: Record<string, string> = {}; |
| 369 | for (const [key, value] of Object.entries(env ?? {})) { |
| 370 | if (key === OWNERSHIP_ENV) continue; |
| 371 | if (value !== undefined) result[key] = value; |
| 372 | } |
| 373 | return result; |
| 374 | }; |
| 375 | |
| 376 | export const stampEnvVariables = ( |
| 377 | labels: Record<string, string>, |
| 378 | env: Record<string, string | undefined> | undefined, |
| 379 | ): Record<string, string | undefined> => ({ |
| 380 | ...env, |
| 381 | [OWNERSHIP_ENV]: fitMarker(labels, 200), |
| 382 | }); |
| 383 | |
| 384 | export const versionOwnershipText = (version: appengine.Version) => |
| 385 | version.envVariables?.[OWNERSHIP_ENV]; |
| 386 | |
| 387 | export const domainIsOwned = ( |
| 388 | domain: string | undefined, |
| 389 | ownedCertificateIds: ReadonlySet<string>, |
| 390 | mapping: appengine.DomainMapping, |
| 391 | ) => { |
| 392 | if (hasOwnershipMarker(domain)) return true; |
| 393 | const id = (mapping.id ?? domain ?? "").toLowerCase(); |
| 394 | if (id.startsWith("alchemy-") || id.includes(".alchemy-")) return true; |
| 395 | const certificateId = mapping.sslSettings?.certificateId; |
| 396 | return certificateId !== undefined && ownedCertificateIds.has(certificateId); |
| 397 | }; |
| 398 | |
| 399 | export const ownedCertificateIds = (certificates: readonly appengine.AuthorizedCertificate[]) => |
| 400 | new Set( |
| 401 | certificates |
| 402 | .filter((certificate) => hasOwnershipMarker(certificate.displayName)) |
| 403 | .map((certificate) => certificate.id) |
| 404 | .filter((id): id is string => id !== undefined && id.length > 0), |
| 405 | ); |
| 406 | |
| 407 | export const parseCertificateName = (name: string) => { |
| 408 | const parts = name.split("/").filter((part) => part.length > 0); |
| 409 | const appsAt = parts.indexOf("apps"); |
| 410 | const projectsAt = parts.indexOf("projects"); |
| 411 | const locationsAt = parts.indexOf("locations"); |
| 412 | const applicationsAt = parts.indexOf("applications"); |
| 413 | const certsAt = parts.lastIndexOf("authorizedCertificates"); |
| 414 | const certificateId = |
| 415 | certsAt >= 0 && parts[certsAt + 1] ? parts[certsAt + 1]! : lastSegment(name); |
| 416 | const appsId = |
| 417 | appsAt >= 0 && parts[appsAt + 1] |
| 418 | ? parts[appsAt + 1] |
| 419 | : applicationsAt >= 0 |
| 420 | ? parts[applicationsAt + 1] |
| 421 | : undefined; |
| 422 | return { |
| 423 | appsId, |
| 424 | project: projectsAt >= 0 ? parts[projectsAt + 1] : appsId, |
| 425 | location: locationsAt >= 0 ? parts[locationsAt + 1] : undefined, |
| 426 | applicationsId: applicationsAt >= 0 ? parts[applicationsAt + 1] : appsId, |
| 427 | certificateId, |
| 428 | }; |
| 429 | }; |
| 430 | |
| 431 | export const parseDomainMappingName = (name: string) => { |
| 432 | const parts = name.split("/").filter((part) => part.length > 0); |
| 433 | const appsAt = parts.indexOf("apps"); |
| 434 | const projectsAt = parts.indexOf("projects"); |
| 435 | const locationsAt = parts.indexOf("locations"); |
| 436 | const applicationsAt = parts.indexOf("applications"); |
| 437 | const mappingsAt = parts.lastIndexOf("domainMappings"); |
| 438 | const domain = mappingsAt >= 0 ? parts.slice(mappingsAt + 1).join("/") : lastSegment(name); |
| 439 | const appsId = |
| 440 | appsAt >= 0 && parts[appsAt + 1] |
| 441 | ? parts[appsAt + 1] |
| 442 | : applicationsAt >= 0 |
| 443 | ? parts[applicationsAt + 1] |
| 444 | : undefined; |
| 445 | return { |
| 446 | appsId, |
| 447 | project: projectsAt >= 0 ? parts[projectsAt + 1] : appsId, |
| 448 | location: locationsAt >= 0 ? parts[locationsAt + 1] : undefined, |
| 449 | applicationsId: applicationsAt >= 0 ? parts[applicationsAt + 1] : appsId, |
| 450 | domain, |
| 451 | }; |
| 452 | }; |
| 453 | |
| 454 | export const parseVersionName = (name: string) => { |
| 455 | const parts = name.split("/").filter((part) => part.length > 0); |
| 456 | const appsAt = parts.indexOf("apps"); |
| 457 | const servicesAt = parts.indexOf("services"); |
| 458 | const versionsAt = parts.indexOf("versions"); |
| 459 | return { |
| 460 | appsId: appsAt >= 0 ? parts[appsAt + 1] : undefined, |
| 461 | servicesId: servicesAt >= 0 ? parts[servicesAt + 1] : undefined, |
| 462 | versionsId: versionsAt >= 0 ? parts[versionsAt + 1] : lastSegment(name), |
| 463 | }; |
| 464 | }; |
| 465 | |
| 466 | export const stringMapOf = ( |
| 467 | map: Record<string, string | undefined> | undefined, |
| 468 | ): Record<string, string> => { |
| 469 | const result: Record<string, string> = {}; |
| 470 | for (const [key, value] of Object.entries(map ?? {})) { |
| 471 | if (value !== undefined) result[key] = value; |
| 472 | } |
| 473 | return result; |
| 474 | }; |