The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as compute from "@distilled.cloud/gcp/compute_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { waitRegionOperation } from "./operations.ts"; |
| 14 | |
| 15 | export type RegionTargetHttpProxyProps = { |
| 16 | /** |
| 17 | * TargetHttpProxy name (RFC1035, 1-63 characters). If omitted, a unique |
| 18 | * name is generated from the stack, stage, and logical id. Changing it |
| 19 | * replaces the resource. |
| 20 | */ |
| 21 | targetHttpProxyName?: string; |
| 22 | /** |
| 23 | * Region the proxy lives in (e.g. `us-central1`). Immutable — changing |
| 24 | * it replaces the resource. `US-CENTRAL1` is accepted and normalized to |
| 25 | * `us-central1`. |
| 26 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 27 | */ |
| 28 | region?: string; |
| 29 | /** |
| 30 | * Optional description. Alchemy ownership is stored in a `[alchemy …]` |
| 31 | * prefix so `list` / nuke can find resources (Compute |
| 32 | * RegionTargetHttpProxy has no labels field and no patch API, so |
| 33 | * changing the description replaces the proxy). |
| 34 | */ |
| 35 | description?: string; |
| 36 | /** |
| 37 | * Regional URL map this proxy routes to. Accepts a RegionUrlMap |
| 38 | * self-link, a `projects/{project}/regions/{region}/urlMaps/{name}` |
| 39 | * path, or the UrlMap name. |
| 40 | */ |
| 41 | urlMap: string; |
| 42 | /** |
| 43 | * Bind inbound traffic to the forwarding-rule address. Only applies when |
| 44 | * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`. |
| 45 | * Immutable — changing it replaces the proxy. |
| 46 | * @default false |
| 47 | */ |
| 48 | proxyBind?: boolean; |
| 49 | /** |
| 50 | * Idle keep-alive timeout in seconds after a response completes with no |
| 51 | * matching traffic. Regional Application Load Balancers allow 5–600 |
| 52 | * (default 610). Immutable — changing it replaces the proxy. |
| 53 | */ |
| 54 | httpKeepAliveTimeoutSec?: number; |
| 55 | }; |
| 56 | |
| 57 | export type RegionTargetHttpProxy = Resource< |
| 58 | "GCP.Compute.RegionTargetHttpProxy", |
| 59 | RegionTargetHttpProxyProps, |
| 60 | { |
| 61 | /** TargetHttpProxy name. */ |
| 62 | targetHttpProxyName: string; |
| 63 | /** Project id. */ |
| 64 | project: string; |
| 65 | /** Region short name (`us-central1`). */ |
| 66 | region: string; |
| 67 | /** User description with the Alchemy ownership prefix stripped. */ |
| 68 | description: string | undefined; |
| 69 | /** URL of the attached regional UrlMap. */ |
| 70 | urlMap: string; |
| 71 | /** Whether Envoy inbound bind is enabled. */ |
| 72 | proxyBind: boolean; |
| 73 | /** HTTP keep-alive timeout in seconds, if set. */ |
| 74 | httpKeepAliveTimeoutSec: number | undefined; |
| 75 | /** Server-defined URL. */ |
| 76 | selfLink: string | undefined; |
| 77 | /** Server-assigned numeric id. */ |
| 78 | targetHttpProxyId: string | undefined; |
| 79 | /** Optimistic-locking fingerprint. */ |
| 80 | fingerprint: string | undefined; |
| 81 | /** RFC3339 creation timestamp. */ |
| 82 | creationTimestamp: string | undefined; |
| 83 | /** Resource kind. */ |
| 84 | kind: string | undefined; |
| 85 | }, |
| 86 | never, |
| 87 | Providers |
| 88 | >; |
| 89 | |
| 90 | /** |
| 91 | * A regional Compute Engine target HTTP proxy. |
| 92 | * |
| 93 | * Regional target HTTP proxies are referenced by regional forwarding rules |
| 94 | * and point at a regional URL map that routes host/path to a backend |
| 95 | * service or redirect. This resource maps to the `regionTargetHttpProxies` |
| 96 | * collection (`targetHttpProxies` is `GCP.Compute.TargetHttpProxy`). |
| 97 | * Compute RegionTargetHttpProxy has no labels field — Alchemy ownership is |
| 98 | * stored in the description so nuke can find leaked proxies. The only |
| 99 | * in-place mutation is `setUrlMap`; name, region, description, |
| 100 | * `proxyBind`, and `httpKeepAliveTimeoutSec` replace the proxy. |
| 101 | * |
| 102 | * ### Creating a Regional Target HTTP Proxy |
| 103 | * **Example:** Generated name in front of a regional URL map |
| 104 | * ```typescript |
| 105 | * const map = yield* GCP.Compute.RegionUrlMap("web", { |
| 106 | * region: "us-central1", |
| 107 | * defaultUrlRedirect: { |
| 108 | * httpsRedirect: true, |
| 109 | * hostRedirect: "example.com", |
| 110 | * stripQuery: false, |
| 111 | * }, |
| 112 | * }); |
| 113 | * const proxy = yield* GCP.Compute.RegionTargetHttpProxy("http", { |
| 114 | * region: "us-central1", |
| 115 | * urlMap: map.urlMapName, |
| 116 | * }); |
| 117 | * ``` |
| 118 | * |
| 119 | * **Example:** Explicit name and description |
| 120 | * ```typescript |
| 121 | * const proxy = yield* GCP.Compute.RegionTargetHttpProxy("http", { |
| 122 | * targetHttpProxyName: "app-http", |
| 123 | * region: "us-central1", |
| 124 | * description: "public http frontend", |
| 125 | * urlMap: map.selfLink, |
| 126 | * }); |
| 127 | * ``` |
| 128 | * |
| 129 | * @resource |
| 130 | * @category Compute |
| 131 | */ |
| 132 | export const RegionTargetHttpProxy = Resource<RegionTargetHttpProxy>( |
| 133 | "GCP.Compute.RegionTargetHttpProxy", |
| 134 | ); |
| 135 | |
| 136 | export class RegionTargetHttpProxyNotResolved extends Data.TaggedError( |
| 137 | "GCP.Compute.RegionTargetHttpProxyNotResolved", |
| 138 | )<{ |
| 139 | targetHttpProxyName: string; |
| 140 | region: string; |
| 141 | }> {} |
| 142 | |
| 143 | const lastSegment = (value: string) => { |
| 144 | const trimmed = value.replace(/\/+$/, ""); |
| 145 | const parts = trimmed.split("/"); |
| 146 | return parts[parts.length - 1] || trimmed; |
| 147 | }; |
| 148 | |
| 149 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 150 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 151 | |
| 152 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 153 | Effect.gen(function* () { |
| 154 | if (name !== undefined) return name; |
| 155 | if (existing !== undefined) return existing; |
| 156 | const generated = yield* createPhysicalName({ |
| 157 | id, |
| 158 | maxLength: 63, |
| 159 | lowercase: true, |
| 160 | }); |
| 161 | return /^[a-z]/.test(generated) ? generated : `p${generated}`.slice(0, 63); |
| 162 | }); |
| 163 | |
| 164 | const encodeDescription = ( |
| 165 | labels: Record<string, string>, |
| 166 | description: string | undefined, |
| 167 | ): string => { |
| 168 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 169 | return description ? `${marker}\n${description}` : marker; |
| 170 | }; |
| 171 | |
| 172 | const parseDescription = ( |
| 173 | description: string | undefined, |
| 174 | ): { |
| 175 | labels: Record<string, string>; |
| 176 | description: string | undefined; |
| 177 | } => { |
| 178 | if (!description?.startsWith("[alchemy ")) { |
| 179 | return { labels: {}, description }; |
| 180 | } |
| 181 | const end = description.indexOf("]"); |
| 182 | if (end < 0) return { labels: {}, description }; |
| 183 | const labels: Record<string, string> = {}; |
| 184 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 185 | const eq = part.indexOf("="); |
| 186 | if (eq > 0) { |
| 187 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 188 | } |
| 189 | } |
| 190 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 191 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 192 | }; |
| 193 | |
| 194 | const hasOwnershipMarker = (description: string | undefined) => |
| 195 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 196 | |
| 197 | const resourceTail = (value: string | undefined): string => { |
| 198 | if (value === undefined || value.length === 0) return ""; |
| 199 | return lastSegment(value); |
| 200 | }; |
| 201 | |
| 202 | const toUrlMapRef = (project: string, region: string, urlMap: string): string => { |
| 203 | if (urlMap.includes("/")) return urlMap; |
| 204 | return `projects/${project}/regions/${region}/urlMaps/${urlMap}`; |
| 205 | }; |
| 206 | |
| 207 | const toAttrs = (proxy: compute.TargetHttpProxy, project: string) => { |
| 208 | const parsed = parseDescription(proxy.description); |
| 209 | return { |
| 210 | targetHttpProxyName: proxy.name ?? proxy.id ?? "", |
| 211 | project, |
| 212 | region: lastSegment(proxy.region ?? "").toLowerCase(), |
| 213 | description: parsed.description, |
| 214 | urlMap: proxy.urlMap ?? "", |
| 215 | proxyBind: proxy.proxyBind === true, |
| 216 | httpKeepAliveTimeoutSec: proxy.httpKeepAliveTimeoutSec, |
| 217 | selfLink: proxy.selfLink, |
| 218 | targetHttpProxyId: proxy.id, |
| 219 | fingerprint: proxy.fingerprint, |
| 220 | creationTimestamp: proxy.creationTimestamp, |
| 221 | kind: proxy.kind, |
| 222 | }; |
| 223 | }; |
| 224 | |
| 225 | const getByName = (project: string, region: string, targetHttpProxy: string) => |
| 226 | compute |
| 227 | .getRegionTargetHttpProxies({ project, region, targetHttpProxy }) |
| 228 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 229 | |
| 230 | const immutableChanged = ( |
| 231 | news: RegionTargetHttpProxyProps, |
| 232 | olds: RegionTargetHttpProxyProps | undefined, |
| 233 | output: RegionTargetHttpProxy["Attributes"] | undefined, |
| 234 | ) => { |
| 235 | const previousDescription = olds?.description ?? output?.description; |
| 236 | if (news.description !== undefined && news.description !== previousDescription) { |
| 237 | return true; |
| 238 | } |
| 239 | const previousBind = olds?.proxyBind ?? output?.proxyBind; |
| 240 | if (news.proxyBind !== undefined && news.proxyBind !== previousBind) { |
| 241 | return true; |
| 242 | } |
| 243 | const previousKeepAlive = olds?.httpKeepAliveTimeoutSec ?? output?.httpKeepAliveTimeoutSec; |
| 244 | if ( |
| 245 | news.httpKeepAliveTimeoutSec !== undefined && |
| 246 | news.httpKeepAliveTimeoutSec !== previousKeepAlive |
| 247 | ) { |
| 248 | return true; |
| 249 | } |
| 250 | return false; |
| 251 | }; |
| 252 | |
| 253 | export const RegionTargetHttpProxyProvider = () => |
| 254 | Provider.succeed(RegionTargetHttpProxy, { |
| 255 | stables: [ |
| 256 | "targetHttpProxyName", |
| 257 | "project", |
| 258 | "region", |
| 259 | "targetHttpProxyId", |
| 260 | "selfLink", |
| 261 | "creationTimestamp", |
| 262 | ], |
| 263 | |
| 264 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 265 | if (!isResolved(news)) return undefined; |
| 266 | const env = yield* GcpEnvironment.current; |
| 267 | const previousName = olds?.targetHttpProxyName ?? output?.targetHttpProxyName; |
| 268 | const nextName = news.targetHttpProxyName ?? previousName; |
| 269 | const nameChanged = |
| 270 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 271 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 272 | const nextRegion = normalizeRegion(news.region ?? output?.region, env.region); |
| 273 | const regionChanged = previousRegion !== nextRegion; |
| 274 | if (nameChanged || regionChanged || immutableChanged(news, olds, output)) { |
| 275 | return { |
| 276 | action: "replace" as const, |
| 277 | deleteFirst: !regionChanged, |
| 278 | }; |
| 279 | } |
| 280 | return undefined; |
| 281 | }), |
| 282 | |
| 283 | read: Effect.fn(function* ({ id, olds, output }) { |
| 284 | const env = yield* GcpEnvironment.current; |
| 285 | const targetHttpProxyName = yield* toName( |
| 286 | id, |
| 287 | olds?.targetHttpProxyName, |
| 288 | output?.targetHttpProxyName, |
| 289 | ); |
| 290 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 291 | const existing = yield* getByName(env.project, region, targetHttpProxyName); |
| 292 | if (existing === undefined) return undefined; |
| 293 | const attrs = toAttrs(existing, env.project); |
| 294 | const { labels } = parseDescription(existing.description); |
| 295 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 296 | }), |
| 297 | |
| 298 | list: () => |
| 299 | Effect.gen(function* () { |
| 300 | const env = yield* GcpEnvironment.current; |
| 301 | const pages = yield* compute.aggregatedListTargetHttpProxies |
| 302 | .pages({ |
| 303 | project: env.project, |
| 304 | returnPartialSuccess: true, |
| 305 | maxResults: 500, |
| 306 | }) |
| 307 | .pipe(Stream.runCollect); |
| 308 | return Array.from(pages).flatMap((page) => |
| 309 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 310 | (scoped?.targetHttpProxies ?? []) |
| 311 | .filter((proxy) => (proxy.region ?? "").length > 0) |
| 312 | .filter((proxy) => hasOwnershipMarker(proxy.description)) |
| 313 | .map((proxy) => toAttrs(proxy, env.project)), |
| 314 | ), |
| 315 | ); |
| 316 | }), |
| 317 | |
| 318 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 319 | const env = yield* GcpEnvironment.current; |
| 320 | const targetHttpProxyName = yield* toName( |
| 321 | id, |
| 322 | news.targetHttpProxyName, |
| 323 | output?.targetHttpProxyName, |
| 324 | ); |
| 325 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 326 | const ownership = yield* createInternalLabels(id); |
| 327 | const desiredDescription = encodeDescription(ownership, news.description); |
| 328 | const desiredUrlMap = toUrlMapRef(env.project, region, news.urlMap); |
| 329 | |
| 330 | let current = yield* getByName(env.project, region, targetHttpProxyName); |
| 331 | |
| 332 | if (current === undefined) { |
| 333 | const body: compute.TargetHttpProxy = { |
| 334 | name: targetHttpProxyName, |
| 335 | description: desiredDescription, |
| 336 | urlMap: desiredUrlMap, |
| 337 | }; |
| 338 | if (news.proxyBind !== undefined) { |
| 339 | body.proxyBind = news.proxyBind; |
| 340 | } |
| 341 | if (news.httpKeepAliveTimeoutSec !== undefined) { |
| 342 | body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec; |
| 343 | } |
| 344 | yield* compute |
| 345 | .insertRegionTargetHttpProxies({ |
| 346 | project: env.project, |
| 347 | region, |
| 348 | body, |
| 349 | }) |
| 350 | .pipe( |
| 351 | Effect.flatMap((operation) => |
| 352 | waitRegionOperation(env.project, region, operation, { |
| 353 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 354 | }), |
| 355 | ), |
| 356 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 357 | ); |
| 358 | current = yield* getByName(env.project, region, targetHttpProxyName); |
| 359 | } |
| 360 | |
| 361 | if (current === undefined) { |
| 362 | return yield* new RegionTargetHttpProxyNotResolved({ |
| 363 | targetHttpProxyName, |
| 364 | region, |
| 365 | }); |
| 366 | } |
| 367 | |
| 368 | if (resourceTail(current.urlMap) !== resourceTail(desiredUrlMap)) { |
| 369 | yield* compute |
| 370 | .setUrlMapRegionTargetHttpProxies({ |
| 371 | project: env.project, |
| 372 | region, |
| 373 | targetHttpProxy: targetHttpProxyName, |
| 374 | body: { urlMap: desiredUrlMap }, |
| 375 | }) |
| 376 | .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation))); |
| 377 | current = yield* getByName(env.project, region, targetHttpProxyName); |
| 378 | if (current === undefined) { |
| 379 | return yield* new RegionTargetHttpProxyNotResolved({ |
| 380 | targetHttpProxyName, |
| 381 | region, |
| 382 | }); |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | return toAttrs(current, env.project); |
| 387 | }), |
| 388 | |
| 389 | delete: Effect.fn(function* ({ output }) { |
| 390 | const env = yield* GcpEnvironment.current; |
| 391 | const region = normalizeRegion(output.region, env.region); |
| 392 | const operation = yield* compute |
| 393 | .deleteRegionTargetHttpProxies({ |
| 394 | project: env.project, |
| 395 | region, |
| 396 | targetHttpProxy: output.targetHttpProxyName, |
| 397 | }) |
| 398 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 399 | if (operation !== undefined) { |
| 400 | yield* waitRegionOperation(env.project, region, operation).pipe( |
| 401 | Effect.catchTag("NotFound", () => Effect.void), |
| 402 | ); |
| 403 | } |
| 404 | }), |
| 405 | }); |