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 { unownedUnlessPrevious } 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 { waitGlobalOperation } from "./operations.ts"; |
| 14 | |
| 15 | export type TargetHttpProxyProps = { |
| 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 | * Optional description. Alchemy ownership is stored in a `[alchemy …]` |
| 24 | * prefix so `list` / nuke can find resources (Compute TargetHttpProxy has |
| 25 | * no labels field). |
| 26 | */ |
| 27 | description?: string; |
| 28 | /** |
| 29 | * URL map this proxy routes to. Accepts a UrlMap self-link, a |
| 30 | * `projects/{project}/global/urlMaps/{name}` path, or the UrlMap name. |
| 31 | */ |
| 32 | urlMap: string; |
| 33 | /** |
| 34 | * Bind inbound traffic to the forwarding-rule address. Only applies when |
| 35 | * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`. |
| 36 | * @default false |
| 37 | */ |
| 38 | proxyBind?: boolean; |
| 39 | /** |
| 40 | * Idle keep-alive timeout in seconds after a response completes with no |
| 41 | * matching traffic. Global external Application Load Balancers allow |
| 42 | * 5–1200 (default 610). Not supported on classic Application Load |
| 43 | * Balancers. |
| 44 | */ |
| 45 | httpKeepAliveTimeoutSec?: number; |
| 46 | }; |
| 47 | |
| 48 | export type TargetHttpProxy = Resource< |
| 49 | "GCP.Compute.TargetHttpProxy", |
| 50 | TargetHttpProxyProps, |
| 51 | { |
| 52 | /** TargetHttpProxy name. */ |
| 53 | targetHttpProxyName: string; |
| 54 | /** Project id. */ |
| 55 | project: string; |
| 56 | /** User description with the Alchemy ownership prefix stripped. */ |
| 57 | description: string | undefined; |
| 58 | /** URL of the attached UrlMap. */ |
| 59 | urlMap: string; |
| 60 | /** Whether Envoy inbound bind is enabled. */ |
| 61 | proxyBind: boolean; |
| 62 | /** HTTP keep-alive timeout in seconds, if set. */ |
| 63 | httpKeepAliveTimeoutSec: number | undefined; |
| 64 | /** Server-defined URL. */ |
| 65 | selfLink: string | undefined; |
| 66 | /** Server-assigned numeric id. */ |
| 67 | targetHttpProxyId: string | undefined; |
| 68 | /** Optimistic-locking fingerprint. */ |
| 69 | fingerprint: string | undefined; |
| 70 | /** RFC3339 creation timestamp. */ |
| 71 | creationTimestamp: string | undefined; |
| 72 | /** Resource kind. */ |
| 73 | kind: string | undefined; |
| 74 | }, |
| 75 | never, |
| 76 | Providers |
| 77 | >; |
| 78 | |
| 79 | /** |
| 80 | * A global Compute Engine target HTTP proxy. |
| 81 | * |
| 82 | * Target HTTP proxies are referenced by global forwarding rules and point |
| 83 | * at a URL map that routes host/path to a backend service, backend bucket, |
| 84 | * or redirect. This resource maps to the global `targetHttpProxies` |
| 85 | * collection (`regionTargetHttpProxies` is a separate resource). Compute |
| 86 | * TargetHttpProxy has no labels field — Alchemy ownership is stored in the |
| 87 | * description so nuke can find leaked proxies. |
| 88 | * |
| 89 | * ### Creating a Target HTTP Proxy |
| 90 | * **Example:** Generated name in front of a URL map |
| 91 | * ```typescript |
| 92 | * const map = yield* GCP.Compute.UrlMap("web", { |
| 93 | * defaultUrlRedirect: { |
| 94 | * httpsRedirect: true, |
| 95 | * hostRedirect: "example.com", |
| 96 | * stripQuery: false, |
| 97 | * }, |
| 98 | * }); |
| 99 | * const proxy = yield* GCP.Compute.TargetHttpProxy("http", { |
| 100 | * urlMap: map.urlMapName, |
| 101 | * }); |
| 102 | * ``` |
| 103 | * |
| 104 | * **Example:** Explicit name and description |
| 105 | * ```typescript |
| 106 | * const proxy = yield* GCP.Compute.TargetHttpProxy("http", { |
| 107 | * targetHttpProxyName: "app-http", |
| 108 | * description: "public http frontend", |
| 109 | * urlMap: map.selfLink, |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * @resource |
| 114 | * @category Compute |
| 115 | */ |
| 116 | export const TargetHttpProxy = Resource<TargetHttpProxy>("GCP.Compute.TargetHttpProxy"); |
| 117 | |
| 118 | export class TargetHttpProxyNotResolved extends Data.TaggedError( |
| 119 | "GCP.Compute.TargetHttpProxyNotResolved", |
| 120 | )<{ |
| 121 | targetHttpProxyName: string; |
| 122 | }> {} |
| 123 | |
| 124 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 125 | Effect.gen(function* () { |
| 126 | if (name !== undefined) return name; |
| 127 | if (existing !== undefined) return existing; |
| 128 | const generated = yield* createPhysicalName({ |
| 129 | id, |
| 130 | maxLength: 63, |
| 131 | lowercase: true, |
| 132 | }); |
| 133 | return /^[a-z]/.test(generated) ? generated : `p${generated}`.slice(0, 63); |
| 134 | }); |
| 135 | |
| 136 | const encodeDescription = ( |
| 137 | labels: Record<string, string>, |
| 138 | description: string | undefined, |
| 139 | ): string => { |
| 140 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 141 | return description ? `${marker}\n${description}` : marker; |
| 142 | }; |
| 143 | |
| 144 | const parseDescription = ( |
| 145 | description: string | undefined, |
| 146 | ): { |
| 147 | labels: Record<string, string>; |
| 148 | description: string | undefined; |
| 149 | } => { |
| 150 | if (!description?.startsWith("[alchemy ")) { |
| 151 | return { labels: {}, description }; |
| 152 | } |
| 153 | const end = description.indexOf("]"); |
| 154 | if (end < 0) return { labels: {}, description }; |
| 155 | const labels: Record<string, string> = {}; |
| 156 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 157 | const eq = part.indexOf("="); |
| 158 | if (eq > 0) { |
| 159 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 160 | } |
| 161 | } |
| 162 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 163 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 164 | }; |
| 165 | |
| 166 | const resourceTail = (value: string | undefined): string => { |
| 167 | if (value === undefined || value.length === 0) return ""; |
| 168 | const parts = value.split("/").filter((part) => part.length > 0); |
| 169 | return parts[parts.length - 1] ?? ""; |
| 170 | }; |
| 171 | |
| 172 | const toUrlMapRef = (project: string, urlMap: string): string => { |
| 173 | if (urlMap.includes("/")) return urlMap; |
| 174 | return `projects/${project}/global/urlMaps/${urlMap}`; |
| 175 | }; |
| 176 | |
| 177 | const toAttrs = (proxy: compute.TargetHttpProxy, project: string) => { |
| 178 | const parsed = parseDescription(proxy.description); |
| 179 | return { |
| 180 | targetHttpProxyName: proxy.name ?? proxy.id ?? "", |
| 181 | project, |
| 182 | description: parsed.description, |
| 183 | urlMap: proxy.urlMap ?? "", |
| 184 | proxyBind: proxy.proxyBind === true, |
| 185 | httpKeepAliveTimeoutSec: proxy.httpKeepAliveTimeoutSec, |
| 186 | selfLink: proxy.selfLink, |
| 187 | targetHttpProxyId: proxy.id, |
| 188 | fingerprint: proxy.fingerprint, |
| 189 | creationTimestamp: proxy.creationTimestamp, |
| 190 | kind: proxy.kind, |
| 191 | }; |
| 192 | }; |
| 193 | |
| 194 | const getByName = (project: string, targetHttpProxy: string) => |
| 195 | compute |
| 196 | .getTargetHttpProxies({ project, targetHttpProxy }) |
| 197 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 198 | |
| 199 | export const TargetHttpProxyProvider = () => |
| 200 | Provider.succeed(TargetHttpProxy, { |
| 201 | nuke: { |
| 202 | dependsOn: ["GCP.Compute.UrlMap"], |
| 203 | }, |
| 204 | stables: [ |
| 205 | "targetHttpProxyName", |
| 206 | "project", |
| 207 | "targetHttpProxyId", |
| 208 | "selfLink", |
| 209 | "creationTimestamp", |
| 210 | ], |
| 211 | |
| 212 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 213 | if (!isResolved(news)) return undefined; |
| 214 | const previous = olds?.targetHttpProxyName ?? output?.targetHttpProxyName; |
| 215 | const next = news.targetHttpProxyName; |
| 216 | if (previous !== undefined && next !== undefined && previous !== next) { |
| 217 | return { action: "replace" as const, deleteFirst: true }; |
| 218 | } |
| 219 | return undefined; |
| 220 | }), |
| 221 | |
| 222 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 223 | const env = yield* GcpEnvironment.current; |
| 224 | const targetHttpProxyName = yield* toName( |
| 225 | id, |
| 226 | olds?.targetHttpProxyName, |
| 227 | output?.targetHttpProxyName, |
| 228 | ); |
| 229 | const existing = yield* getByName(env.project, targetHttpProxyName); |
| 230 | if (existing === undefined) return undefined; |
| 231 | const attrs = toAttrs(existing, env.project); |
| 232 | const { labels } = parseDescription(existing.description); |
| 233 | return (yield* hasAlchemyLabels(id, labels)) |
| 234 | ? attrs |
| 235 | : unownedUnlessPrevious(attrs, previous, "targetHttpProxyName"); |
| 236 | }), |
| 237 | |
| 238 | list: () => |
| 239 | Effect.gen(function* () { |
| 240 | const env = yield* GcpEnvironment.current; |
| 241 | return yield* compute.listTargetHttpProxies |
| 242 | .items({ project: env.project, maxResults: 500 }) |
| 243 | .pipe( |
| 244 | Stream.filter((proxy) => { |
| 245 | const { labels } = parseDescription(proxy.description); |
| 246 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 247 | }), |
| 248 | Stream.map((proxy) => toAttrs(proxy, env.project)), |
| 249 | Stream.runCollect, |
| 250 | Effect.map((chunk) => Array.from(chunk)), |
| 251 | ); |
| 252 | }), |
| 253 | |
| 254 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 255 | const env = yield* GcpEnvironment.current; |
| 256 | const targetHttpProxyName = yield* toName( |
| 257 | id, |
| 258 | news.targetHttpProxyName, |
| 259 | output?.targetHttpProxyName, |
| 260 | ); |
| 261 | const ownership = yield* createInternalLabels(id); |
| 262 | const desiredDescription = encodeDescription(ownership, news.description); |
| 263 | const desiredUrlMap = toUrlMapRef(env.project, news.urlMap); |
| 264 | |
| 265 | let current = yield* getByName(env.project, targetHttpProxyName); |
| 266 | |
| 267 | if (current === undefined) { |
| 268 | const body: compute.TargetHttpProxy = { |
| 269 | name: targetHttpProxyName, |
| 270 | description: desiredDescription, |
| 271 | urlMap: desiredUrlMap, |
| 272 | }; |
| 273 | if (news.proxyBind !== undefined) { |
| 274 | body.proxyBind = news.proxyBind; |
| 275 | } |
| 276 | if (news.httpKeepAliveTimeoutSec !== undefined) { |
| 277 | body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec; |
| 278 | } |
| 279 | yield* compute |
| 280 | .insertTargetHttpProxies({ |
| 281 | project: env.project, |
| 282 | body, |
| 283 | }) |
| 284 | .pipe( |
| 285 | Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)), |
| 286 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 287 | ); |
| 288 | current = yield* getByName(env.project, targetHttpProxyName); |
| 289 | } |
| 290 | |
| 291 | if (current === undefined) { |
| 292 | return yield* new TargetHttpProxyNotResolved({ targetHttpProxyName }); |
| 293 | } |
| 294 | |
| 295 | if (resourceTail(current.urlMap) !== resourceTail(desiredUrlMap)) { |
| 296 | yield* compute |
| 297 | .setUrlMapTargetHttpProxies({ |
| 298 | project: env.project, |
| 299 | targetHttpProxy: targetHttpProxyName, |
| 300 | body: { urlMap: desiredUrlMap }, |
| 301 | }) |
| 302 | .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation))); |
| 303 | current = yield* getByName(env.project, targetHttpProxyName); |
| 304 | if (current === undefined) { |
| 305 | return yield* new TargetHttpProxyNotResolved({ |
| 306 | targetHttpProxyName, |
| 307 | }); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 312 | const proxyBindChanged = |
| 313 | news.proxyBind !== undefined && (current.proxyBind === true) !== news.proxyBind; |
| 314 | const keepAliveChanged = |
| 315 | news.httpKeepAliveTimeoutSec !== undefined && |
| 316 | current.httpKeepAliveTimeoutSec !== news.httpKeepAliveTimeoutSec; |
| 317 | |
| 318 | if (descriptionChanged || proxyBindChanged || keepAliveChanged) { |
| 319 | const body: compute.TargetHttpProxy = { |
| 320 | fingerprint: current.fingerprint, |
| 321 | description: desiredDescription, |
| 322 | }; |
| 323 | if (news.proxyBind !== undefined) { |
| 324 | body.proxyBind = news.proxyBind; |
| 325 | } |
| 326 | if (news.httpKeepAliveTimeoutSec !== undefined) { |
| 327 | body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec; |
| 328 | } |
| 329 | yield* compute |
| 330 | .patchTargetHttpProxies({ |
| 331 | project: env.project, |
| 332 | targetHttpProxy: targetHttpProxyName, |
| 333 | body, |
| 334 | }) |
| 335 | .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation))); |
| 336 | current = yield* getByName(env.project, targetHttpProxyName); |
| 337 | if (current === undefined) { |
| 338 | return yield* new TargetHttpProxyNotResolved({ |
| 339 | targetHttpProxyName, |
| 340 | }); |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | return toAttrs(current, env.project); |
| 345 | }), |
| 346 | |
| 347 | delete: Effect.fn(function* ({ output }) { |
| 348 | const env = yield* GcpEnvironment.current; |
| 349 | const operation = yield* compute |
| 350 | .deleteTargetHttpProxies({ |
| 351 | project: env.project, |
| 352 | targetHttpProxy: output.targetHttpProxyName, |
| 353 | }) |
| 354 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 355 | if (operation !== undefined) { |
| 356 | yield* waitGlobalOperation(env.project, operation).pipe( |
| 357 | Effect.catchTag("NotFound", () => Effect.void), |
| 358 | ); |
| 359 | } |
| 360 | }), |
| 361 | }); |