The best way to control Claude Code, Codex and more from any computer or phone

main
ts 183 lines 6.83 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type { Rpc } from "alchemy/Rpc";
3 import type { RuntimeContext } from "alchemy/RuntimeContext";
4 import * as Data from "effect/Data";
5 import type * as Effect from "effect/Effect";
6 import type * as HttpApi from "effect/http-api/HttpApi";
7 import type * as HttpApiClient from "effect/http-api/HttpApiClient";
8 import type * as HttpApiGroup from "effect/http-api/HttpApiGroup";
9 import type * as HttpClient from "effect/http/HttpClient";
10 import type * as HttpClientError from "effect/http/HttpClientError";
11 import type { Rpc as EffectRpc, RpcClient, RpcGroup } from "effect/rpc";
12 import type * as RpcClientError from "effect/rpc/RpcClientError";
13 import type { Service } from "./Service.ts";
14
15 /** Request options for {@link InvokeServiceClient.fetch}. */
16 export interface InvokeServiceRequestInit {
17 /** HTTP method. @default "GET" */
18 method?: string;
19 /** Extra request headers. `Authorization` is always set by the binding. */
20 headers?: Record<string, string>;
21 /** Request body; objects are not serialized — pass a string. */
22 body?: string | Uint8Array;
23 }
24
25 /** A fully buffered response from the bound service. */
26 export interface InvokeServiceResponse {
27 /** HTTP status code. */
28 readonly status: number;
29 /** Response headers (lower-cased names). */
30 readonly headers: Readonly<Record<string, string>>;
31 /** The response body as text. */
32 readonly text: Effect.Effect<string>;
33 /** The response body parsed as JSON. */
34 readonly json: Effect.Effect<unknown, InvokeServiceError>;
35 }
36
37 /**
38 * Runtime client returned by {@link InvokeService}: the target's RPC
39 * methods, `fetch` for its HTTP routes, and an `httpClient` for anything
40 * else (an Effect RPC or HttpApi client, streaming responses).
41 */
42 export type InvokeServiceClient<Shape = {}> = Omit<Shape, "fetch" | "run"> & {
43 /**
44 * Call the bound service at `path` (relative to its `uri`) with a
45 * Google-signed ID token for the host's runtime service account.
46 */
47 fetch(
48 path: string,
49 init?: InvokeServiceRequestInit,
50 ): Effect.Effect<InvokeServiceResponse, InvokeServiceError, RuntimeContext>;
51 /**
52 * An `HttpClient` that signs every request with an ID token for the
53 * service. A relative URL such as `/orders` resolves against its `uri`.
54 */
55 httpClient: HttpClient.HttpClient.With<HttpClientError.HttpClientError | InvokeServiceError>;
56 };
57
58 /** The RPC shape a Cloud Run service class declares, if any. */
59 type ShapeOf<Target> = Target extends Rpc<infer Shape> ? Shape : {};
60
61 /**
62 * Minting the ID token, reaching the service, or decoding its response
63 * failed. Non-2xx responses are not errors — inspect `status`.
64 */
65 export class InvokeServiceError extends Data.TaggedError("GCP.Run.InvokeServiceError")<{
66 message: string;
67 cause?: unknown;
68 }> {}
69
70 /**
71 * Runtime binding that calls a private Cloud Run {@link Service} from
72 * another Cloud Run host with Google-signed identity — the GCP analog of
73 * `AWS.Lambda.InvokeFunction`.
74 *
75 * At deploy time it grants `roles/run.invoker` on the target service to
76 * the host's runtime service account and binds the target's `uri` into
77 * the host. At runtime it mints an ID token (audience = the target `uri`)
78 * from the metadata server, caches it until shortly before expiry, and
79 * sends it as `Authorization: Bearer`. The target keeps
80 * `invokerIamDisabled` off, so anything without a token gets `403`.
81 *
82 * Provide {@link InvokeServiceHttp}.
83 *
84 * ### Calling a private service
85 * **Example:** Forward a request to a private backend
86 * ```typescript
87 * export default class Gateway extends GCP.Function<Gateway>()(
88 * "Gateway",
89 * { main: import.meta.url, invokerIamDisabled: true },
90 * Effect.gen(function* () {
91 * const quotes = yield* GCP.Run.InvokeService(Quotes);
92 * return {
93 * fetch: Effect.gen(function* () {
94 * const response = yield* quotes.fetch("/quote").pipe(Effect.orDie);
95 * return HttpServerResponse.text(yield* response.text, {
96 * status: response.status,
97 * });
98 * }),
99 * };
100 * }).pipe(Effect.provide(GCP.Run.InvokeServiceHttp)),
101 * ) {}
102 * ```
103 *
104 * **Example:** POST a JSON body
105 * ```typescript
106 * const response = yield* orders.fetch("/orders", {
107 * method: "POST",
108 * headers: { "content-type": "application/json" },
109 * body: JSON.stringify({ sku: "abc", quantity: 1 }),
110 * });
111 * const order = yield* response.json;
112 * ```
113 *
114 * ### Calling RPC methods
115 * **Example:** Methods on a private service
116 * ```typescript
117 * export default class Quotes extends GCP.Run.Service<Quotes>()(
118 * "Quotes",
119 * { main: import.meta.url },
120 * Effect.gen(function* () {
121 * return {
122 * quote: (symbol: string) => Effect.succeed({ symbol, price: 42 }),
123 * ticks: (symbol: string) => Stream.make(41, 42, 43),
124 * };
125 * }),
126 * ) {}
127 * ```
128 * Keep the service's IAM invoker check on: a service that returns
129 * methods and sets `invokerIamDisabled` fails to deploy with
130 * `GCP.Run.ServiceRpcPublic`.
131 *
132 * **Example:** Call them from another service
133 * ```typescript
134 * const quotes = yield* GCP.Run.InvokeService(Quotes);
135 * const { price } = yield* quotes.quote("GOOG");
136 * const ticks = yield* quotes.ticks("GOOG").pipe(Stream.take(3), Stream.runCollect);
137 * ```
138 *
139 * ### Bring your own client
140 * **Example:** `httpClient` signs every request
141 * ```typescript
142 * const response = yield* quotes.httpClient.get("/health");
143 * ```
144 *
145 * @binding
146 * @category Run
147 */
148 /** `fetch` and `httpClient` of a bound service, alongside a typed client. */
149 export type InvokeServiceTransport = Pick<InvokeServiceClient, "fetch" | "httpClient">;
150
151 /** The API a bound service serves, when it is an Effect RPC group or HttpApi. */
152 export type InvokeServiceOptions =
153 | { schema: RpcGroup.RpcGroup<EffectRpc.Any> }
154 | { api: HttpApi.HttpApi<string, HttpApiGroup.Constraint> };
155
156 export interface InvokeService extends Binding.Service<
157 InvokeService,
158 "GCP.Run.InvokeService",
159 (service: Service, options?: InvokeServiceOptions) => Effect.Effect<InvokeServiceClient>
160 > {
161 <Target extends Service, Req = never>(
162 service: Target | Effect.Effect<Target, never, Req>,
163 ): Effect.Effect<InvokeServiceClient<ShapeOf<Target>>, never, InvokeService | Req>;
164 <Rpcs extends EffectRpc.Any, Req = never>(
165 service: Service | Effect.Effect<Service, never, Req>,
166 options: { schema: RpcGroup.RpcGroup<Rpcs> },
167 ): Effect.Effect<
168 RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError> & InvokeServiceTransport,
169 never,
170 InvokeService | Req
171 >;
172 <Groups extends HttpApiGroup.Constraint, Req = never>(
173 service: Service | Effect.Effect<Service, never, Req>,
174 options: { api: HttpApi.HttpApi<string, Groups> },
175 ): Effect.Effect<
176 HttpApiClient.Client<Groups, HttpClientError.HttpClientError | InvokeServiceError> &
177 InvokeServiceTransport,
178 never,
179 InvokeService | Req
180 >;
181 }
182
183 export const InvokeService = Binding.Service<InvokeService>("GCP.Run.InvokeService");