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 Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { waitGlobalOperation } from "./operations.ts"; |
| 15 | |
| 16 | const DEFAULT_PRIORITY = 1000; |
| 17 | const DEFAULT_INTERNET_GATEWAY = "default-internet-gateway"; |
| 18 | |
| 19 | export type RouteProps = { |
| 20 | /** |
| 21 | * Route name (RFC1035, 1-63 chars). If omitted, a unique name is generated |
| 22 | * from the stack, stage, and logical id. Immutable — changing it replaces |
| 23 | * the route. |
| 24 | */ |
| 25 | routeName?: string; |
| 26 | /** |
| 27 | * Destination range of outgoing packets this route applies to (IPv4 or |
| 28 | * IPv6 CIDR). Immutable — changing it replaces the route. |
| 29 | */ |
| 30 | destRange: string; |
| 31 | /** |
| 32 | * VPC network this route belongs to. Accepts a name (`default`), a |
| 33 | * partial URL (`global/networks/default`), or a full resource URL. |
| 34 | * Immutable — changing it replaces the route. |
| 35 | */ |
| 36 | network: string; |
| 37 | /** |
| 38 | * Optional description. Compute routes have no labels field, so Alchemy |
| 39 | * ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is stored |
| 40 | * in a `[alchemy …]` prefix for `list` / nuke. Immutable — changing the |
| 41 | * user-facing description replaces the route. |
| 42 | */ |
| 43 | description?: string; |
| 44 | /** |
| 45 | * Priority used to break ties among equal-prefix matches. Lower wins. |
| 46 | * Range `0`–`65535`. |
| 47 | * @default 1000 |
| 48 | */ |
| 49 | priority?: number; |
| 50 | /** |
| 51 | * Instance tags this route applies to. Empty means every instance. |
| 52 | * Immutable — changing it replaces the route. |
| 53 | */ |
| 54 | tags?: string[]; |
| 55 | /** |
| 56 | * Next hop gateway URL or `default-internet-gateway`. Exactly one next |
| 57 | * hop must be set. Immutable. |
| 58 | */ |
| 59 | nextHopGateway?: string; |
| 60 | /** |
| 61 | * Next hop IP address (IPv4 or IPv6). Exactly one next hop must be set. |
| 62 | * Immutable. |
| 63 | */ |
| 64 | nextHopIp?: string; |
| 65 | /** |
| 66 | * Next hop instance URL. Exactly one next hop must be set. Immutable. |
| 67 | */ |
| 68 | nextHopInstance?: string; |
| 69 | /** |
| 70 | * Next hop VPN tunnel URL. Exactly one next hop must be set. Immutable. |
| 71 | */ |
| 72 | nextHopVpnTunnel?: string; |
| 73 | /** |
| 74 | * Next hop internal load balancer forwarding rule URL or IP. Exactly one |
| 75 | * next hop must be set. Immutable. |
| 76 | */ |
| 77 | nextHopIlb?: string; |
| 78 | }; |
| 79 | |
| 80 | export type Route = Resource< |
| 81 | "GCP.Compute.Route", |
| 82 | RouteProps, |
| 83 | { |
| 84 | /** Route name. */ |
| 85 | routeName: string; |
| 86 | /** Project id. */ |
| 87 | project: string; |
| 88 | /** Destination CIDR. */ |
| 89 | destRange: string; |
| 90 | /** Network URL. */ |
| 91 | network: string; |
| 92 | /** User description with the Alchemy ownership prefix stripped. */ |
| 93 | description: string | undefined; |
| 94 | /** Route priority. */ |
| 95 | priority: number; |
| 96 | /** Instance tags this route applies to. */ |
| 97 | tags: string[]; |
| 98 | /** Next hop gateway URL, if set. */ |
| 99 | nextHopGateway: string | undefined; |
| 100 | /** Next hop IP, if set. */ |
| 101 | nextHopIp: string | undefined; |
| 102 | /** Next hop instance URL, if set. */ |
| 103 | nextHopInstance: string | undefined; |
| 104 | /** Next hop VPN tunnel URL, if set. */ |
| 105 | nextHopVpnTunnel: string | undefined; |
| 106 | /** Next hop internal load balancer, if set. */ |
| 107 | nextHopIlb: string | undefined; |
| 108 | /** Next hop network URL (output-only, typically subnet routes). */ |
| 109 | nextHopNetwork: string | undefined; |
| 110 | /** Server-defined URL. */ |
| 111 | selfLink: string | undefined; |
| 112 | /** Server-assigned numeric id. */ |
| 113 | id: string | undefined; |
| 114 | /** RFC3339 creation timestamp. */ |
| 115 | creationTimestamp: string | undefined; |
| 116 | /** Route type (`STATIC`, `SUBNET`, `BGP`, `TRANSIT`). */ |
| 117 | routeType: string | undefined; |
| 118 | /** Route status. */ |
| 119 | routeStatus: string | undefined; |
| 120 | }, |
| 121 | never, |
| 122 | Providers |
| 123 | >; |
| 124 | |
| 125 | /** |
| 126 | * A VPC static route. |
| 127 | * |
| 128 | * Routes tell instances where to send packets whose destination matches |
| 129 | * `destRange`. Compute Engine has no update API for routes — every |
| 130 | * user-facing field is immutable and changing it replaces the resource. |
| 131 | * Ownership is stamped into the description because routes have no labels. |
| 132 | * |
| 133 | * ### Creating a Route |
| 134 | * **Example:** Default internet route on the default network |
| 135 | * ```typescript |
| 136 | * const route = yield* GCP.Compute.Route("internet", { |
| 137 | * destRange: "0.0.0.0/0", |
| 138 | * network: "default", |
| 139 | * nextHopGateway: "default-internet-gateway", |
| 140 | * }); |
| 141 | * ``` |
| 142 | * |
| 143 | * **Example:** Named route with priority and tags |
| 144 | * ```typescript |
| 145 | * const route = yield* GCP.Compute.Route("tagged", { |
| 146 | * routeName: "app-egress", |
| 147 | * destRange: "192.0.2.0/24", |
| 148 | * network: "default", |
| 149 | * nextHopGateway: "default-internet-gateway", |
| 150 | * priority: 100, |
| 151 | * tags: ["egress"], |
| 152 | * description: "test-net egress", |
| 153 | * }); |
| 154 | * ``` |
| 155 | * |
| 156 | * **Example:** Next hop IP |
| 157 | * ```typescript |
| 158 | * const route = yield* GCP.Compute.Route("appliance", { |
| 159 | * destRange: "10.200.0.0/16", |
| 160 | * network: "default", |
| 161 | * nextHopIp: "10.128.0.5", |
| 162 | * }); |
| 163 | * ``` |
| 164 | * |
| 165 | * @resource |
| 166 | * @category Compute |
| 167 | */ |
| 168 | export const Route = Resource<Route>("GCP.Compute.Route"); |
| 169 | |
| 170 | export class RouteNotResolved extends Data.TaggedError("GCP.Compute.RouteNotResolved")<{ |
| 171 | routeName: string; |
| 172 | }> {} |
| 173 | |
| 174 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 175 | Effect.gen(function* () { |
| 176 | if (name !== undefined) return name; |
| 177 | if (existing !== undefined) return existing; |
| 178 | const generated = yield* createPhysicalName({ |
| 179 | id, |
| 180 | maxLength: 63, |
| 181 | lowercase: true, |
| 182 | }); |
| 183 | const rfc = generated.replace(/^[^a-z]+/, "r").replace(/-+$/g, ""); |
| 184 | return rfc.slice(0, 63); |
| 185 | }); |
| 186 | |
| 187 | const encodeDescription = ( |
| 188 | labels: Record<string, string>, |
| 189 | description: string | undefined, |
| 190 | ): string => { |
| 191 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 192 | return description ? `${marker}\n${description}` : marker; |
| 193 | }; |
| 194 | |
| 195 | const parseDescription = ( |
| 196 | description: string | undefined, |
| 197 | ): { |
| 198 | labels: Record<string, string>; |
| 199 | description: string | undefined; |
| 200 | } => { |
| 201 | if (!description?.startsWith("[alchemy ")) { |
| 202 | return { labels: {}, description }; |
| 203 | } |
| 204 | const end = description.indexOf("]"); |
| 205 | if (end < 0) return { labels: {}, description }; |
| 206 | const labels: Record<string, string> = {}; |
| 207 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 208 | const eq = part.indexOf("="); |
| 209 | if (eq > 0) { |
| 210 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 211 | } |
| 212 | } |
| 213 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 214 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 215 | }; |
| 216 | |
| 217 | const lastToken = (value: string | undefined) => { |
| 218 | if (!value) return ""; |
| 219 | const parts = value.split("/").filter((part) => part.length > 0); |
| 220 | return parts[parts.length - 1] ?? ""; |
| 221 | }; |
| 222 | |
| 223 | const sameRef = (left: string | undefined, right: string | undefined) => |
| 224 | lastToken(left) === lastToken(right); |
| 225 | |
| 226 | const sameTags = (left: string[] | undefined, right: string[] | undefined) => |
| 227 | [...(left ?? [])].sort().join("\0") === [...(right ?? [])].sort().join("\0"); |
| 228 | |
| 229 | const networkUrl = (project: string, network: string) => { |
| 230 | if (network.includes("/")) { |
| 231 | return network.startsWith("projects/") || network.startsWith("http") |
| 232 | ? network |
| 233 | : `projects/${project}/${network.replace(/^\//, "")}`; |
| 234 | } |
| 235 | return `projects/${project}/global/networks/${network}`; |
| 236 | }; |
| 237 | |
| 238 | const gatewayUrl = (project: string, gateway: string) => { |
| 239 | if (gateway.includes("/")) return gateway; |
| 240 | if (gateway === DEFAULT_INTERNET_GATEWAY) { |
| 241 | return `projects/${project}/global/gateways/${DEFAULT_INTERNET_GATEWAY}`; |
| 242 | } |
| 243 | return gateway; |
| 244 | }; |
| 245 | |
| 246 | const hopOf = (props: { |
| 247 | nextHopGateway?: string; |
| 248 | nextHopIp?: string; |
| 249 | nextHopInstance?: string; |
| 250 | nextHopVpnTunnel?: string; |
| 251 | nextHopIlb?: string; |
| 252 | }) => { |
| 253 | if (props.nextHopGateway) |
| 254 | return { kind: "gateway" as const, value: lastToken(props.nextHopGateway) }; |
| 255 | if (props.nextHopIp) return { kind: "ip" as const, value: props.nextHopIp }; |
| 256 | if (props.nextHopInstance) |
| 257 | return { |
| 258 | kind: "instance" as const, |
| 259 | value: lastToken(props.nextHopInstance), |
| 260 | }; |
| 261 | if (props.nextHopVpnTunnel) |
| 262 | return { |
| 263 | kind: "vpn" as const, |
| 264 | value: lastToken(props.nextHopVpnTunnel), |
| 265 | }; |
| 266 | if (props.nextHopIlb) return { kind: "ilb" as const, value: lastToken(props.nextHopIlb) }; |
| 267 | return undefined; |
| 268 | }; |
| 269 | |
| 270 | const toBody = ( |
| 271 | project: string, |
| 272 | routeName: string, |
| 273 | props: RouteProps, |
| 274 | ownership: Record<string, string>, |
| 275 | ): compute.Route => ({ |
| 276 | name: routeName, |
| 277 | destRange: props.destRange, |
| 278 | network: networkUrl(project, props.network), |
| 279 | description: encodeDescription(ownership, props.description), |
| 280 | priority: props.priority ?? DEFAULT_PRIORITY, |
| 281 | tags: props.tags, |
| 282 | nextHopGateway: props.nextHopGateway ? gatewayUrl(project, props.nextHopGateway) : undefined, |
| 283 | nextHopIp: props.nextHopIp, |
| 284 | nextHopInstance: props.nextHopInstance, |
| 285 | nextHopVpnTunnel: props.nextHopVpnTunnel, |
| 286 | nextHopIlb: props.nextHopIlb, |
| 287 | }); |
| 288 | |
| 289 | const toAttrs = (route: compute.Route, project: string) => { |
| 290 | const parsed = parseDescription(route.description); |
| 291 | return { |
| 292 | routeName: route.name ?? "", |
| 293 | project, |
| 294 | destRange: route.destRange ?? "", |
| 295 | network: route.network ?? "", |
| 296 | description: parsed.description, |
| 297 | priority: route.priority ?? DEFAULT_PRIORITY, |
| 298 | tags: route.tags ?? [], |
| 299 | nextHopGateway: route.nextHopGateway, |
| 300 | nextHopIp: route.nextHopIp, |
| 301 | nextHopInstance: route.nextHopInstance, |
| 302 | nextHopVpnTunnel: route.nextHopVpnTunnel, |
| 303 | nextHopIlb: route.nextHopIlb, |
| 304 | nextHopNetwork: route.nextHopNetwork, |
| 305 | selfLink: route.selfLink, |
| 306 | id: route.id, |
| 307 | creationTimestamp: route.creationTimestamp, |
| 308 | routeType: route.routeType, |
| 309 | routeStatus: route.routeStatus, |
| 310 | }; |
| 311 | }; |
| 312 | |
| 313 | const getByName = (project: string, route: string) => |
| 314 | compute.getRoutes({ project, route }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 315 | |
| 316 | const requireRoute = (project: string, routeName: string) => |
| 317 | getByName(project, routeName).pipe( |
| 318 | Effect.flatMap((route) => |
| 319 | route ? Effect.succeed(route) : Effect.fail(new RouteNotResolved({ routeName })), |
| 320 | ), |
| 321 | Effect.retry({ |
| 322 | while: (error) => error._tag === "GCP.Compute.RouteNotResolved", |
| 323 | schedule: Schedule.spaced("1 second"), |
| 324 | times: 8, |
| 325 | }), |
| 326 | ); |
| 327 | |
| 328 | const removeRoute = (project: string, routeName: string) => |
| 329 | Effect.gen(function* () { |
| 330 | const operation = yield* compute |
| 331 | .deleteRoutes({ |
| 332 | project, |
| 333 | route: routeName, |
| 334 | }) |
| 335 | .pipe( |
| 336 | Effect.retry({ |
| 337 | while: (error) => error._tag === "Conflict", |
| 338 | times: 8, |
| 339 | schedule: Schedule.spaced("1 second"), |
| 340 | }), |
| 341 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 342 | ); |
| 343 | if (operation !== undefined) { |
| 344 | yield* waitGlobalOperation(project, operation, { |
| 345 | ignore: ["RESOURCE_NOT_FOUND"], |
| 346 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 347 | } |
| 348 | }); |
| 349 | |
| 350 | const matchesDesired = (route: compute.Route, news: RouteProps) => { |
| 351 | if ((route.destRange ?? "") !== news.destRange) return false; |
| 352 | if (!sameRef(route.network, news.network)) return false; |
| 353 | if ((route.priority ?? DEFAULT_PRIORITY) !== (news.priority ?? DEFAULT_PRIORITY)) { |
| 354 | return false; |
| 355 | } |
| 356 | const parsed = parseDescription(route.description); |
| 357 | if ((parsed.description ?? "") !== (news.description ?? "")) return false; |
| 358 | if (!sameTags(route.tags, news.tags)) return false; |
| 359 | const previousHop = hopOf({ |
| 360 | nextHopGateway: route.nextHopGateway, |
| 361 | nextHopIp: route.nextHopIp, |
| 362 | nextHopInstance: route.nextHopInstance, |
| 363 | nextHopVpnTunnel: route.nextHopVpnTunnel, |
| 364 | nextHopIlb: route.nextHopIlb, |
| 365 | }); |
| 366 | const nextHop = hopOf(news); |
| 367 | if (nextHop === undefined) return previousHop === undefined; |
| 368 | return ( |
| 369 | previousHop !== undefined && |
| 370 | previousHop.kind === nextHop.kind && |
| 371 | previousHop.value === nextHop.value |
| 372 | ); |
| 373 | }; |
| 374 | |
| 375 | const immutableChanged = ( |
| 376 | news: RouteProps, |
| 377 | olds: Partial<RouteProps> | undefined, |
| 378 | output: Route["Attributes"] | undefined, |
| 379 | ) => { |
| 380 | const previousDest = olds?.destRange ?? output?.destRange; |
| 381 | if (previousDest !== undefined && news.destRange !== previousDest) { |
| 382 | return true; |
| 383 | } |
| 384 | const previousNetwork = olds?.network ?? output?.network; |
| 385 | if (previousNetwork !== undefined && !sameRef(news.network, previousNetwork)) { |
| 386 | return true; |
| 387 | } |
| 388 | const previousPriority = olds?.priority ?? output?.priority ?? DEFAULT_PRIORITY; |
| 389 | if ((news.priority ?? DEFAULT_PRIORITY) !== previousPriority) { |
| 390 | return true; |
| 391 | } |
| 392 | const previousDescription = olds?.description ?? output?.description ?? ""; |
| 393 | if ((news.description ?? "") !== previousDescription) { |
| 394 | return true; |
| 395 | } |
| 396 | if (!sameTags(news.tags, olds?.tags ?? output?.tags)) { |
| 397 | return true; |
| 398 | } |
| 399 | const previousHop = hopOf(olds ?? {}) ?? hopOf(output ?? {}); |
| 400 | const nextHop = hopOf(news); |
| 401 | if ( |
| 402 | nextHop !== undefined && |
| 403 | (previousHop === undefined || |
| 404 | previousHop.kind !== nextHop.kind || |
| 405 | previousHop.value !== nextHop.value) |
| 406 | ) { |
| 407 | return true; |
| 408 | } |
| 409 | return false; |
| 410 | }; |
| 411 | |
| 412 | export const RouteProvider = () => |
| 413 | Provider.succeed(Route, { |
| 414 | stables: [ |
| 415 | "routeName", |
| 416 | "project", |
| 417 | "id", |
| 418 | "selfLink", |
| 419 | "creationTimestamp", |
| 420 | "network", |
| 421 | "destRange", |
| 422 | ], |
| 423 | |
| 424 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 425 | if (!isResolved(news)) return undefined; |
| 426 | const previousName = olds?.routeName ?? output?.routeName; |
| 427 | const nextName = news.routeName ?? previousName; |
| 428 | if (previousName === undefined && output === undefined) { |
| 429 | return undefined; |
| 430 | } |
| 431 | const nameChanged = |
| 432 | news.routeName !== undefined && |
| 433 | previousName !== undefined && |
| 434 | news.routeName !== previousName; |
| 435 | if (nameChanged || immutableChanged(news, olds, output)) { |
| 436 | return { |
| 437 | action: "replace" as const, |
| 438 | deleteFirst: nextName !== undefined && nextName === previousName, |
| 439 | }; |
| 440 | } |
| 441 | return undefined; |
| 442 | }), |
| 443 | |
| 444 | read: Effect.fn(function* ({ id, olds, output }) { |
| 445 | const env = yield* GcpEnvironment.current; |
| 446 | const routeName = yield* toName(id, olds?.routeName, output?.routeName); |
| 447 | const existing = yield* getByName(env.project, routeName); |
| 448 | if (existing === undefined) return undefined; |
| 449 | const attrs = toAttrs(existing, env.project); |
| 450 | const { labels } = parseDescription(existing.description); |
| 451 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 452 | }), |
| 453 | |
| 454 | list: () => |
| 455 | Effect.gen(function* () { |
| 456 | const env = yield* GcpEnvironment.current; |
| 457 | return yield* compute.listRoutes.items({ project: env.project }).pipe( |
| 458 | Stream.filter((route) => { |
| 459 | const { labels } = parseDescription(route.description); |
| 460 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 461 | }), |
| 462 | Stream.map((route) => toAttrs(route, env.project)), |
| 463 | Stream.runCollect, |
| 464 | Effect.map((chunk) => Array.from(chunk)), |
| 465 | ); |
| 466 | }), |
| 467 | |
| 468 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 469 | const env = yield* GcpEnvironment.current; |
| 470 | const routeName = yield* toName(id, news.routeName, output?.routeName); |
| 471 | const ownership = yield* createInternalLabels(id); |
| 472 | const desired = toBody(env.project, routeName, news, ownership); |
| 473 | |
| 474 | let current = yield* getByName(env.project, routeName); |
| 475 | |
| 476 | if (current !== undefined && !matchesDesired(current, news)) { |
| 477 | yield* removeRoute(env.project, routeName); |
| 478 | current = undefined; |
| 479 | } |
| 480 | |
| 481 | if (current === undefined) { |
| 482 | yield* compute |
| 483 | .insertRoutes({ |
| 484 | project: env.project, |
| 485 | body: desired, |
| 486 | }) |
| 487 | .pipe( |
| 488 | Effect.flatMap((operation) => |
| 489 | waitGlobalOperation(env.project, operation, { |
| 490 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 491 | }), |
| 492 | ), |
| 493 | Effect.catchTag("Conflict", () => Effect.void), |
| 494 | ); |
| 495 | current = yield* requireRoute(env.project, routeName); |
| 496 | } |
| 497 | |
| 498 | return toAttrs(current, env.project); |
| 499 | }), |
| 500 | |
| 501 | delete: Effect.fn(function* ({ output }) { |
| 502 | if (!output.routeName) return; |
| 503 | const env = yield* GcpEnvironment.current; |
| 504 | yield* removeRoute(env.project, output.routeName); |
| 505 | }), |
| 506 | }); |