The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Binding from "alchemy/Binding"; |
| 2 | import type { Resource } from "alchemy/Resource"; |
| 3 | import { makeFetchRpcStub, type Rpc } from "alchemy/Rpc"; |
| 4 | import { CurrentRuntimeContext, type RuntimeContext, sanitizeKey } from "alchemy/RuntimeContext"; |
| 5 | import { isYieldableEffectLike } from "alchemy/Util/effect"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import type * as HttpApi from "effect/http-api/HttpApi"; |
| 9 | import type * as HttpApiClient from "effect/http-api/HttpApiClient"; |
| 10 | import type * as HttpApiGroup from "effect/http-api/HttpApiGroup"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import type * as HttpClientError from "effect/http/HttpClientError"; |
| 13 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 14 | import type * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 15 | import type { Rpc as EffectRpc, RpcClient, RpcGroup } from "effect/rpc"; |
| 16 | import type * as RpcClientError from "effect/rpc/RpcClientError"; |
| 17 | import type { GcpHostBinding } from "../Host.ts"; |
| 18 | import type { Container } from "./Container.ts"; |
| 19 | import { makeHttpApiClient, makeRpcGroupClient } from "./EffectApis.ts"; |
| 20 | |
| 21 | /** The bound container has no port, or the caller was deployed before the binding existed. */ |
| 22 | export class BoundContainerUnavailable extends Data.TaggedError( |
| 23 | "GCP.Run.BoundContainerUnavailable", |
| 24 | )<{ |
| 25 | container: string; |
| 26 | }> { |
| 27 | override get message() { |
| 28 | return `No port for GCP.Run.Container ${this.container}. Give it a port, or redeploy the caller.`; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Client for a container bound with {@link bindContainer}: its RPC |
| 34 | * methods, plus `fetch` for its HTTP routes. |
| 35 | */ |
| 36 | export type ContainerClient<Shape> = Omit<Shape, "fetch" | "run"> & { |
| 37 | /** |
| 38 | * Send a request to the container's `fetch` handler. A relative URL such |
| 39 | * as `/health` resolves against `http://localhost:<port>`. |
| 40 | */ |
| 41 | fetch( |
| 42 | request: HttpClientRequest.HttpClientRequest, |
| 43 | ): Effect.Effect< |
| 44 | HttpClientResponse.HttpClientResponse, |
| 45 | HttpClientError.HttpClientError | BoundContainerUnavailable, |
| 46 | RuntimeContext |
| 47 | >; |
| 48 | /** |
| 49 | * An `HttpClient` whose relative requests go to the container, for an |
| 50 | * Effect RPC or HttpApi client. |
| 51 | */ |
| 52 | httpClient: HttpClient.HttpClient.With< |
| 53 | HttpClientError.HttpClientError | BoundContainerUnavailable |
| 54 | >; |
| 55 | }; |
| 56 | |
| 57 | /** A port of a container bound with {@link bindPort}. */ |
| 58 | export interface PortClient { |
| 59 | /** Always `localhost`: sidecars share the instance's network. */ |
| 60 | host: "localhost"; |
| 61 | /** The bound port. */ |
| 62 | port: number; |
| 63 | /** `http://localhost:{port}`, for a port that serves plain HTTP. */ |
| 64 | url: string; |
| 65 | /** An `HttpClient` whose relative requests go to {@link url}. */ |
| 66 | client: HttpClient.HttpClient; |
| 67 | } |
| 68 | |
| 69 | type Target<Shape> = Container & Rpc<Shape>; |
| 70 | |
| 71 | /** A container to bind: a `GCP.Run.Container` class, or an image-only declaration. */ |
| 72 | type Bindable<Shape, Req> = |
| 73 | | Target<Shape> |
| 74 | | Effect.Effect<Target<Shape>, never, Req> |
| 75 | | Effect.Effect<Container, never, Req>; |
| 76 | |
| 77 | const RUN_HOSTS = new Set(["GCP.Run.Service", "GCP.Run.Container"]); |
| 78 | |
| 79 | const isRunHost = (value: unknown): value is Resource<string, any, any, GcpHostBinding> => |
| 80 | typeof value === "object" && |
| 81 | value !== null && |
| 82 | RUN_HOSTS.has((value as { Type?: string }).Type ?? ""); |
| 83 | |
| 84 | /** Logical id without yielding the container (the runtime has no engine). */ |
| 85 | const logicalIdOf = (target: unknown): string => { |
| 86 | const id = |
| 87 | target !== null && (typeof target === "object" || typeof target === "function") |
| 88 | ? (target as { LogicalId?: unknown }).LogicalId |
| 89 | : undefined; |
| 90 | return typeof id === "string" ? id : ""; |
| 91 | }; |
| 92 | |
| 93 | const withBase = (base: string, url: string) => |
| 94 | /^[a-z]+:\/\//i.test(url) ? url : `${base}${url.startsWith("/") ? "" : "/"}${url}`; |
| 95 | |
| 96 | /** |
| 97 | * Add the container to the host's revision and record its port in the |
| 98 | * host's env. Returns a runtime accessor for that port. |
| 99 | */ |
| 100 | const bindSidecar = <Shape, Req>( |
| 101 | target: Bindable<Shape, Req>, |
| 102 | ): Effect.Effect< |
| 103 | { id: string; port: Effect.Effect<number, BoundContainerUnavailable> }, |
| 104 | never, |
| 105 | Req |
| 106 | > => |
| 107 | Effect.gen(function* () { |
| 108 | const id = logicalIdOf(target); |
| 109 | const key = sanitizeKey(`GCP_BIND_${id}_PORT`); |
| 110 | const ctx = yield* CurrentRuntimeContext; |
| 111 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 112 | // Yielding registers the container and makes the host depend on it. |
| 113 | const container = isYieldableEffectLike(target) |
| 114 | ? yield* target as Effect.Effect<Container, never, Req> |
| 115 | : target; |
| 116 | const host = yield* Binding.Host; |
| 117 | if (isRunHost(host)) { |
| 118 | yield* host.bind`GCP.Run.bindContainer(${container})`({ |
| 119 | env: { [key]: container.port }, |
| 120 | containers: [ |
| 121 | { |
| 122 | spec: container.spec, |
| 123 | iam: container.iam, |
| 124 | sidecars: container.sidecars, |
| 125 | }, |
| 126 | ], |
| 127 | } as unknown as GcpHostBinding); |
| 128 | } |
| 129 | } |
| 130 | return { |
| 131 | id, |
| 132 | port: (ctx === undefined ? Effect.undefined : ctx.get<unknown>(key)).pipe( |
| 133 | Effect.flatMap((port) => |
| 134 | port === undefined || port === null || port === "" |
| 135 | ? Effect.fail(new BoundContainerUnavailable({ container: id })) |
| 136 | : Effect.succeed(Number(port)), |
| 137 | ), |
| 138 | ), |
| 139 | }; |
| 140 | }); |
| 141 | |
| 142 | /** |
| 143 | * Run a {@link Container} as a sidecar of this Cloud Run service (or of |
| 144 | * another Container) and call it over `localhost`. |
| 145 | * |
| 146 | * At deploy time the binding adds the container to the host's revision |
| 147 | * and to the host's `dependsOn`, so the host starts only after the |
| 148 | * container passes its startup probe. The container's binding roles are |
| 149 | * granted to the revision's service account. At runtime it returns a |
| 150 | * client with the container's methods (schemaless RPC on `/__rpc__/*`) |
| 151 | * plus `fetch` for its HTTP routes. |
| 152 | * |
| 153 | * ### Calling a sidecar |
| 154 | * **Example:** Methods on the container |
| 155 | * ```typescript |
| 156 | * export default class Worker extends GCP.Run.Container<Worker>()( |
| 157 | * "Worker", |
| 158 | * { main: import.meta.url, port: 3000 }, |
| 159 | * Effect.gen(function* () { |
| 160 | * return { |
| 161 | * greet: (name: string) => Effect.succeed(`hello ${name}`), |
| 162 | * count: () => Stream.make(1, 2, 3), |
| 163 | * }; |
| 164 | * }), |
| 165 | * ) {} |
| 166 | * ``` |
| 167 | * |
| 168 | * **Example:** Bind it and call a method |
| 169 | * ```typescript |
| 170 | * export default class Api extends GCP.Run.Service<Api>()( |
| 171 | * "Api", |
| 172 | * { main: import.meta.url }, |
| 173 | * Effect.gen(function* () { |
| 174 | * const worker = yield* GCP.Run.bindContainer(Worker); |
| 175 | * return { |
| 176 | * fetch: Effect.gen(function* () { |
| 177 | * const greeting = yield* worker.greet("sam"); |
| 178 | * return HttpServerResponse.text(greeting); |
| 179 | * }), |
| 180 | * }; |
| 181 | * }), |
| 182 | * ) {} |
| 183 | * ``` |
| 184 | * |
| 185 | * ### Streams and HTTP |
| 186 | * **Example:** A method that returns a Stream |
| 187 | * ```typescript |
| 188 | * const counts = yield* worker.count().pipe(Stream.runCollect); |
| 189 | * ``` |
| 190 | * |
| 191 | * **Example:** Send a request to the container's `fetch` |
| 192 | * ```typescript |
| 193 | * const response = yield* worker.fetch(HttpClientRequest.get("/health")); |
| 194 | * ``` |
| 195 | * |
| 196 | * ### Sidecars that bind sidecars |
| 197 | * **Example:** A container that starts after another |
| 198 | * ```typescript |
| 199 | * export default class Worker extends GCP.Run.Container<Worker>()( |
| 200 | * "Worker", |
| 201 | * { main: import.meta.url, port: 3000 }, |
| 202 | * Effect.gen(function* () { |
| 203 | * const cache = yield* GCP.Run.bindPort(Cache, 6379); |
| 204 | * return { ping: () => Effect.succeed(cache.url) }; |
| 205 | * }), |
| 206 | * ) {} |
| 207 | * ``` |
| 208 | * Every sidecar a bound container binds joins the same revision. |
| 209 | * |
| 210 | * @binding |
| 211 | * @product Run |
| 212 | */ |
| 213 | /** `fetch` and `httpClient` of a bound container, alongside a typed client. */ |
| 214 | export type ContainerTransport = Pick<ContainerClient<{}>, "fetch" | "httpClient">; |
| 215 | |
| 216 | /** Options for {@link bindContainer}: the API the container serves, if typed. */ |
| 217 | export type BindContainerOptions< |
| 218 | Rpcs extends EffectRpc.Any, |
| 219 | Groups extends HttpApiGroup.Constraint, |
| 220 | > = { schema: RpcGroup.RpcGroup<Rpcs> } | { api: HttpApi.HttpApi<string, Groups> }; |
| 221 | |
| 222 | export function bindContainer<Shape = {}, Req = never>( |
| 223 | target: Bindable<Shape, Req>, |
| 224 | ): Effect.Effect<ContainerClient<Shape>, never, Req | HttpClient.HttpClient>; |
| 225 | export function bindContainer<Rpcs extends EffectRpc.Any, Req = never>( |
| 226 | target: Bindable<unknown, Req>, |
| 227 | options: { schema: RpcGroup.RpcGroup<Rpcs> }, |
| 228 | ): Effect.Effect< |
| 229 | RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError> & ContainerTransport, |
| 230 | never, |
| 231 | Req | HttpClient.HttpClient |
| 232 | >; |
| 233 | export function bindContainer<Groups extends HttpApiGroup.Constraint, Req = never>( |
| 234 | target: Bindable<unknown, Req>, |
| 235 | options: { api: HttpApi.HttpApi<string, Groups> }, |
| 236 | ): Effect.Effect< |
| 237 | HttpApiClient.Client<Groups, HttpClientError.HttpClientError | BoundContainerUnavailable> & |
| 238 | ContainerTransport, |
| 239 | never, |
| 240 | Req | HttpClient.HttpClient |
| 241 | >; |
| 242 | export function bindContainer( |
| 243 | target: Bindable<unknown, unknown>, |
| 244 | options?: BindContainerOptions<any, any>, |
| 245 | ): Effect.Effect<unknown, never, any> { |
| 246 | return Effect.gen(function* () { |
| 247 | const http = yield* HttpClient.HttpClient; |
| 248 | const bound = yield* bindSidecar(target); |
| 249 | const httpClient = HttpClient.mapRequestEffect(http, (request) => |
| 250 | bound.port.pipe( |
| 251 | Effect.map((port) => |
| 252 | HttpClientRequest.setUrl(request, withBase(`http://localhost:${port}`, request.url)), |
| 253 | ), |
| 254 | ), |
| 255 | ); |
| 256 | const send = (request: HttpClientRequest.HttpClientRequest) => httpClient.execute(request); |
| 257 | const transport = { fetch: send, httpClient }; |
| 258 | if (options !== undefined && "schema" in options) { |
| 259 | return Object.assign( |
| 260 | makeRpcGroupClient(options.schema, httpClient as unknown as HttpClient.HttpClient), |
| 261 | transport, |
| 262 | ); |
| 263 | } |
| 264 | if (options !== undefined && "api" in options) { |
| 265 | return Object.assign(yield* makeHttpApiClient(options.api, httpClient), transport); |
| 266 | } |
| 267 | return makeFetchRpcStub<ContainerClient<{}>>({ |
| 268 | // Relative RPC paths, resolved against the container's localhost port. |
| 269 | baseUrl: "", |
| 270 | fetch: send as ( |
| 271 | request: HttpClientRequest.HttpClientRequest, |
| 272 | ) => Effect.Effect<HttpClientResponse.HttpClientResponse, unknown>, |
| 273 | base: transport, |
| 274 | }); |
| 275 | }); |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Run a {@link Container} as a sidecar and reach one of its ports |
| 280 | * directly — for a protocol other than HTTP, such as Redis or Postgres. |
| 281 | * See {@link bindContainer}. |
| 282 | * |
| 283 | * ### Binding a port |
| 284 | * **Example:** A Redis sidecar |
| 285 | * ```typescript |
| 286 | * export const Cache = GCP.Run.Container("Cache", { |
| 287 | * image: "docker.io/library/redis:7", |
| 288 | * port: 6379, |
| 289 | * startupProbe: { tcpSocket: {} }, |
| 290 | * }); |
| 291 | * |
| 292 | * // inside the service's Effect |
| 293 | * const cache = yield* GCP.Run.bindPort(Cache, 6379); |
| 294 | * // cache.url === "http://localhost:6379"; connect with `redis://localhost:${cache.port}` |
| 295 | * ``` |
| 296 | * |
| 297 | * @binding |
| 298 | * @product Run |
| 299 | */ |
| 300 | export const bindPort = <Req = never>( |
| 301 | target: Bindable<unknown, Req>, |
| 302 | port: number, |
| 303 | ): Effect.Effect<PortClient, never, Req | HttpClient.HttpClient> => |
| 304 | Effect.gen(function* () { |
| 305 | const http = yield* HttpClient.HttpClient; |
| 306 | yield* bindSidecar(target); |
| 307 | const url = `http://localhost:${port}`; |
| 308 | return { |
| 309 | host: "localhost", |
| 310 | port, |
| 311 | url, |
| 312 | client: HttpClient.mapRequest(http, (request) => |
| 313 | HttpClientRequest.setUrl(request, withBase(url, request.url)), |
| 314 | ), |
| 315 | } satisfies PortClient; |
| 316 | }); |