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

main
ts 303 lines 11 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type { Resource } from "alchemy/Resource";
3 import { makeFetchRpcStub, RPC_PATH_PREFIX, 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 * as HttpClient from "effect/http/HttpClient";
9 import type * as HttpClientError from "effect/http/HttpClientError";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
12 import * as Redacted from "effect/Redacted";
13 import type { BoundTarget, ServiceBinding } from "./MountVolume.ts";
14 import { RPC_TOKEN_HEADER } from "./rpc.ts";
15 import type { Service } from "./Service.ts";
16
17 /** The deployed caller has no address for the bound Service. */
18 export class BoundServiceUnavailable extends Data.TaggedError("Fly.BoundServiceUnavailable")<{
19 service: string;
20 }> {
21 get message() {
22 return `No private address for Fly Service ${this.service}. It publishes no ports, or the caller was deployed before the binding existed.`;
23 }
24 }
25
26 /**
27 * Client for a Service bound with {@link bindService}: its RPC methods,
28 * plus `fetch` for its HTTP routes.
29 */
30 export type ServiceClient<Shape> = Omit<Shape, "fetch" | "run"> & {
31 /**
32 * Send a request to the Service's `fetch` handler over Fly's private
33 * network. A relative URL such as `/users/u1` resolves against the
34 * Service's private address.
35 */
36 fetch(
37 request: HttpClientRequest.HttpClientRequest,
38 ): Effect.Effect<
39 HttpClientResponse.HttpClientResponse,
40 HttpClientError.HttpClientError | BoundServiceUnavailable,
41 RuntimeContext
42 >;
43 };
44
45 /** A published port of a Service bound with {@link bindEndpoint}. */
46 export interface EndpointClient {
47 /** `{appName}.flycast`, the bound Service's private hostname. */
48 host: Effect.Effect<string, BoundServiceUnavailable, RuntimeContext>;
49 /** The published port. */
50 port: number;
51 /** `http://{appName}.flycast:{port}`, for a port that serves plain HTTP. */
52 url: Effect.Effect<string, BoundServiceUnavailable, RuntimeContext>;
53 /** An `HttpClient` whose relative requests go to {@link url}. */
54 client: HttpClient.HttpClient.With<HttpClientError.HttpClientError | BoundServiceUnavailable>;
55 }
56
57 type Target<Shape> = Service & Rpc<Shape>;
58
59 const isFlyHost = (value: unknown): value is Resource<string, any, any, ServiceBinding> =>
60 typeof value === "object" &&
61 value !== null &&
62 ((value as { Type?: string }).Type === "Fly.Service" ||
63 (value as { Type?: string }).Type === "Fly.Machine");
64
65 /** Logical id without yielding the Service (the runtime has no engine). */
66 const logicalIdOf = (target: unknown): string => {
67 const id =
68 target !== null && (typeof target === "object" || typeof target === "function")
69 ? (target as { LogicalId?: unknown }).LogicalId
70 : undefined;
71 return typeof id === "string" ? id : "";
72 };
73
74 /** Machine env vars the caller's reconcile writes for a bound Service. */
75 export const boundTargetEnvKeys = (id: string) => ({
76 appName: sanitizeKey(`FLY_BIND_${id}_APP`),
77 url: sanitizeKey(`FLY_BIND_${id}_URL`),
78 token: sanitizeKey(`FLY_BIND_${id}_TOKEN`),
79 });
80
81 /**
82 * Record the binding on the caller and transport the target's private
83 * address and caller token as Outputs. Returns runtime accessors for them.
84 */
85 const bindTarget = Effect.fn(function* <Shape, Req>(
86 target: Target<Shape> | Effect.Effect<Target<Shape>, never, Req>,
87 port: number | undefined,
88 ) {
89 const id = logicalIdOf(target);
90 const keys = boundTargetEnvKeys(id);
91 const ctx = yield* CurrentRuntimeContext;
92 if (!globalThis.__ALCHEMY_RUNTIME__) {
93 // Yielding registers the target and makes the caller depend on it.
94 const service = isYieldableEffectLike(target)
95 ? yield* target as Effect.Effect<Target<Shape>, never, Req>
96 : target;
97 // The binding carries the target's Outputs. Unlike props, binding
98 // data may stay unresolved between cycle peers, so two Services can
99 // bind each other; the caller's reconcile writes them onto its Machines.
100 const host = yield* Binding.Host;
101 if (isFlyHost(host)) {
102 yield* host.bind`${service}`({
103 target: {
104 service: id,
105 appName: service.appName,
106 network: service.network,
107 privateUrl: service.privateUrl,
108 rpcToken: service.rpcToken,
109 port,
110 endpoints: service.endpoints,
111 } as unknown as BoundTarget,
112 });
113 }
114 }
115 // Captured at bind time: the host's runtime context reads the values
116 // transported onto the Machine.
117 const read = (key: string) => (ctx === undefined ? Effect.undefined : ctx.get<unknown>(key));
118 const required = (key: string) =>
119 read(key).pipe(
120 Effect.flatMap((value) =>
121 typeof value === "string" && value.length > 0
122 ? Effect.succeed(value)
123 : Effect.fail(new BoundServiceUnavailable({ service: id })),
124 ),
125 );
126 return {
127 appName: required(keys.appName),
128 url: required(keys.url),
129 token: read(keys.token).pipe(
130 Effect.map((value) =>
131 Redacted.isRedacted(value)
132 ? String(Redacted.value(value))
133 : typeof value === "string"
134 ? value
135 : "",
136 ),
137 ),
138 };
139 });
140
141 /** Resolve `path` (relative or placeholder-based) against `base`. */
142 const withBase = (base: string, url: string) => {
143 const path = url.replace(/^https?:\/\/[^/]+/, "");
144 return `${base.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
145 };
146
147 /**
148 * Bind another {@link Service} and get a typed client for it. The client
149 * calls the Service's methods (everything its program returns besides
150 * `fetch` and `run`) and forwards `fetch` requests, over Fly's private
151 * network.
152 *
153 * Binding makes the caller deploy after the Service and hands it the
154 * Service's private address and caller token. Only callers that bind a
155 * Service receive its token, so other Services on the same network cannot
156 * call its methods. Every call must also carry Fly's signed `Fly-Src`
157 * header from the same organization, so the public internet cannot call
158 * them. Calls are plain HTTP inside Fly's WireGuard-encrypted network.
159 *
160 * ### Call a private Service
161 * **Example:** Methods on the target
162 * ```typescript
163 * export default class Users extends Fly.Service<Users>()(
164 * "Users",
165 * { main: import.meta.url, public: false },
166 * Effect.gen(function* () {
167 * return {
168 * list: () => Effect.succeed(USERS),
169 * get: (id: string) =>
170 * Effect.succeed(USERS.find((user) => user.id === id)),
171 * };
172 * }),
173 * ) {}
174 * ```
175 *
176 * **Example:** Bind it and call a method
177 * ```typescript
178 * export default class Orders extends Fly.Service<Orders>()(
179 * "Orders",
180 * { main: import.meta.url, public: false },
181 * Effect.gen(function* () {
182 * const users = yield* Fly.bindService(Users);
183 * return {
184 * list: () =>
185 * Effect.forEach(ORDERS, (order) =>
186 * users
187 * .get(order.userId)
188 * .pipe(Effect.map((user) => ({ ...order, user }))),
189 * ),
190 * };
191 * }),
192 * ) {}
193 * ```
194 *
195 * ### Stream and forward HTTP
196 * **Example:** A method that returns a Stream
197 * ```typescript
198 * const all = yield* users.streamAll().pipe(Stream.runCollect);
199 * ```
200 *
201 * **Example:** Send a request to the Service's `fetch`
202 * ```typescript
203 * const response = yield* users.fetch(HttpClientRequest.get("/users/u1"));
204 * ```
205 *
206 * ### Bind one port
207 * {@link bindEndpoint} targets one published port, such as an admin API
208 * or a raw TCP protocol. Deploy fails with `Fly.EndpointNotPublished`
209 * when the Service does not publish it.
210 *
211 * **Example:** An admin API on port 9000
212 * ```typescript
213 * const admin = yield* Fly.bindEndpoint(Users, { port: 9000 });
214 * const stats = yield* admin.client.get("/stats");
215 * const host = yield* admin.host; // "{appName}.flycast"
216 * ```
217 *
218 * ### Two Services that bind each other
219 * Declare each as a tag class with its method shape, and implement each
220 * in its own file as the default export of `.make`.
221 *
222 * **Example:** Ping and Pong
223 * ```typescript
224 * // src/services.ts
225 * export class Ping extends Fly.Service<Ping, Named>()("Ping") {}
226 * export class Pong extends Fly.Service<Pong, Named>()("Pong") {}
227 *
228 * // src/ping.ts
229 * export default Ping.make(
230 * { main: import.meta.url },
231 * Effect.gen(function* () {
232 * const pong = yield* Fly.bindService(Pong);
233 * return { name: () => Effect.succeed("ping") };
234 * }),
235 * );
236 * ```
237 *
238 * ### Errors
239 * Each fails the caller's deploy before the caller is created:
240 * `Fly.ServiceUnreachable` when the caller and the Service are on
241 * different networks, `Fly.ServiceNotBindable` when the Service publishes
242 * no ports, and `Fly.EndpointNotPublished` for a port it does not publish.
243 *
244 * @binding
245 * @product Service
246 */
247 export const bindService = <Shape, Req = never>(
248 target: Target<Shape> | Effect.Effect<Target<Shape>, never, Req>,
249 ): Effect.Effect<ServiceClient<Shape>, never, Req | HttpClient.HttpClient> =>
250 Effect.gen(function* () {
251 const http = yield* HttpClient.HttpClient;
252 const bound = yield* bindTarget(target, undefined);
253 const send = (request: HttpClientRequest.HttpClientRequest, isRpc: boolean) =>
254 Effect.gen(function* () {
255 const base = yield* bound.url;
256 let next = HttpClientRequest.setUrl(request, withBase(base, request.url));
257 if (isRpc) {
258 next = HttpClientRequest.setHeader(next, RPC_TOKEN_HEADER, yield* bound.token);
259 }
260 return yield* http.execute(next);
261 });
262 return makeFetchRpcStub<ServiceClient<Shape>>({
263 fetch: (request) =>
264 send(request, request.url.includes(RPC_PATH_PREFIX)) as Effect.Effect<
265 HttpClientResponse.HttpClientResponse,
266 unknown
267 >,
268 base: {
269 fetch: (request: HttpClientRequest.HttpClientRequest) => send(request, false),
270 },
271 });
272 });
273
274 /**
275 * Bind one published port of another {@link Service}: an admin API on
276 * its own port, or a raw TCP protocol. Returns the port's private host,
277 * its URL when it serves plain HTTP, and an `HttpClient` whose relative
278 * requests go there. See {@link bindService}.
279 */
280 export const bindEndpoint = <Shape, Req = never>(
281 target: Target<Shape> | Effect.Effect<Target<Shape>, never, Req>,
282 options: { port: number },
283 ): Effect.Effect<EndpointClient, never, Req | HttpClient.HttpClient> =>
284 Effect.gen(function* () {
285 const http = yield* HttpClient.HttpClient;
286 const bound = yield* bindTarget(target, options.port);
287 const host = bound.appName.pipe(Effect.map((app) => `${app}.flycast`));
288 const url = host.pipe(
289 Effect.map((name) =>
290 options.port === 80 ? `http://${name}` : `http://${name}:${options.port}`,
291 ),
292 );
293 return {
294 host,
295 port: options.port,
296 url,
297 client: HttpClient.mapRequestEffect(http, (request) =>
298 url.pipe(
299 Effect.map((base) => HttpClientRequest.setUrl(request, withBase(base, request.url))),
300 ),
301 ),
302 } satisfies EndpointClient;
303 });