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

main
ts 284 lines 11.3 KB
Raw
1 import { msg } from "gt-i18n";
2 import { translatableDetail } from "../errors/translatable.ts";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import * as Exit from "effect/Exit";
7 import * as Fiber from "effect/Fiber";
8 import * as Layer from "effect/Layer";
9 import * as Scope from "effect/Scope";
10 import * as FetchHttpClient from "effect/http/FetchHttpClient";
11 import * as HttpClient from "effect/http/HttpClient";
12
13 import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
14 import type {
15 ConnectionAttemptError,
16 ConnectionAttemptStage,
17 PreparedConnection,
18 } from "./model.ts";
19 import { ConnectionTransientError } from "./model.ts";
20 import { isHostCredentialRefusal } from "./errors.ts";
21 import * as ConnectionResolver from "./resolver.ts";
22 import {
23 connectionRouteId,
24 connectionRoutes,
25 routeEntry,
26 routeHttpBaseUrl,
27 routeKeepsItsHost,
28 sendsTokenInClear,
29 usableRoutes,
30 } from "./routes.ts";
31 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
32 import * as RpcSession from "../rpc/session.ts";
33 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
34
35 export type ConnectionDriverProgress =
36 | {
37 readonly stage: "preparing";
38 }
39 | {
40 readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
41 readonly prepared: PreparedConnection;
42 };
43
44 export interface RouteConnection {
45 readonly prepared: PreparedConnection;
46 readonly session: RpcSession.RpcSession;
47 }
48
49 export interface EnvironmentConnectionLease extends RouteConnection {
50 /** Saved routes whose host refused this device's credential before another route connected. */
51 readonly refusedRouteIds: ReadonlyArray<string>;
52 }
53
54 export type RouteCheck = "answered" | "silent" | "unchecked";
55 /**
56 * "unprepared" means the route answered its check but could not be prepared;
57 * "refused" means its host refused this device's credential.
58 */
59 export type RoutePreflight = "ready" | "refused" | "unprepared" | "silent" | "unchecked";
60
61 const ROUTE_CHECK_TIMEOUT_MS = 2_500;
62 // Preferred direct routes share one head start, so a relay connection does not
63 // wait the full probe timeout for a LAN the device has already left. A route
64 // that misses it connects over relay, then upgrades with a second reconnect.
65 const ROUTE_CHECK_HEAD_START_MS = 500;
66
67 export class ConnectionDriver extends Context.Service<
68 ConnectionDriver,
69 {
70 readonly connect: (
71 entry: ConnectionCatalogEntry,
72 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
73 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
74 readonly preflight: (
75 entry: ConnectionCatalogEntry,
76 route: ConnectionRoute,
77 ) => Effect.Effect<RoutePreflight>;
78 /** Asks the host behind a live session to answer a fresh request on the session's own origin. */
79 readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
80 }
81 >()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
82
83 export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
84 entry: ConnectionCatalogEntry,
85 checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
86 connectRoute: (
87 route: ConnectionRoute,
88 ) => Effect.Effect<RouteConnection, ConnectionAttemptError, R | Scope.Scope>,
89 ) {
90 const routes = usableRoutes(entry);
91 const checks =
92 routes.length === 1
93 ? []
94 : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
95 const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
96 const attemptScope = yield* Scope.Scope;
97 let transient: ConnectionAttemptError | undefined;
98 let blocked: ConnectionAttemptError | undefined;
99 const refusedRouteIds: Array<string> = [];
100 // Each route gets its own scope so a half-open session closes before the next try.
101 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
102 const routeScope = yield* Scope.fork(attemptScope);
103 const result = yield* connectRoute(route).pipe(
104 Scope.provide(routeScope),
105 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
106 Effect.result,
107 );
108 if (result._tag === "Failure") {
109 if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
110 else blocked ??= result.failure;
111 if (isHostCredentialRefusal(result.failure))
112 refusedRouteIds.push(connectionRouteId(route.target));
113 }
114 return result;
115 });
116 const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
117 for (const [index, route] of routes.entries()) {
118 const check =
119 checks.length === 0
120 ? "unchecked"
121 : yield* Effect.raceFirst(
122 Fiber.join(checks[index]!),
123 Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
124 );
125 if (check === "silent") {
126 silent.push({ route, index });
127 continue;
128 }
129 const result = yield* attempt(route);
130 if (result._tag === "Success") return { ...result.success, refusedRouteIds };
131 // An incompatible server is the same server on every route.
132 if (result.failure.reason === "unsupported") return yield* result.failure;
133 }
134 const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
135 concurrency: "unbounded",
136 });
137 const answeredLate = silent.filter((_, position) => late[position] !== "silent");
138 const stillSilent = silent.filter((_, position) => late[position] === "silent");
139 for (const { route } of [...answeredLate, ...stillSilent]) {
140 // A route still silent after its whole check can hold the attempt open far
141 // longer than the check did. Once another route failed in a way that
142 // retries, the retry reaches it sooner than waiting here would.
143 if (transient !== undefined && stillSilent.some((entry) => entry.route === route)) break;
144 const result = yield* attempt(route);
145 if (result._tag === "Success") return { ...result.success, refusedRouteIds };
146 if (result.failure.reason === "unsupported") return yield* result.failure;
147 }
148 return yield* (
149 transient ??
150 blocked ??
151 new ConnectionTransientError({
152 reason: "endpoint-unavailable",
153 ...translatableDetail(
154 msg("{host} did not answer on any saved route.", { host: entry.target.label }),
155 ),
156 })
157 );
158 });
159
160 export const preflightRoute = (
161 check: Effect.Effect<RouteCheck>,
162 prepare: Effect.Effect<unknown, ConnectionAttemptError>,
163 ): Effect.Effect<RoutePreflight> =>
164 check.pipe(
165 Effect.filterOrElse(
166 (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
167 () =>
168 prepare.pipe(
169 Effect.as<RoutePreflight>("ready"),
170 Effect.catch((error) =>
171 Effect.succeed<RoutePreflight>(
172 isHostCredentialRefusal(error) ? "refused" : "unprepared",
173 ),
174 ),
175 ),
176 ),
177 );
178
179 /** @public */
180 export const make = Effect.gen(function* () {
181 const resolver = yield* ConnectionResolver.ConnectionResolver;
182 const sessions = yield* RpcSession.RpcSessionFactory;
183 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
184 const httpClient = yield* HttpClient.HttpClient;
185
186 // The descriptor is public, so this sends no credential to whatever
187 // answers at a saved LAN address on a different network.
188 const checkDescriptor = (httpBaseUrl: string, environmentId: string, keepsItsHost: boolean) =>
189 fetchRemoteEnvironmentDescriptor({
190 httpBaseUrl,
191 timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
192 }).pipe(
193 Effect.option,
194 // The connect this check leads to skips its own read. Every answer, even a
195 // failure, replaces what an older check remembered.
196 Effect.tap((descriptor) =>
197 remote.rememberCheckedDescriptor(httpBaseUrl, descriptor, keepsItsHost),
198 ),
199 Effect.map((descriptor): RouteCheck =>
200 Option.exists(descriptor, (value) => value.environmentId === environmentId)
201 ? "answered"
202 : "silent",
203 ),
204 // A cached descriptor would answer for a host that cannot be reached.
205 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
206 Effect.provideService(HttpClient.HttpClient, httpClient),
207 );
208
209 const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
210 const httpBaseUrl = routeHttpBaseUrl(route);
211 if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
212 return checkDescriptor(httpBaseUrl, entry.target.environmentId, routeKeepsItsHost(route)).pipe(
213 Effect.withSpan("ConnectionDriver.checkRoute", {
214 attributes: { "connection.target.kind": route.target._tag },
215 }),
216 );
217 };
218
219 const checkHost = (prepared: PreparedConnection) =>
220 checkDescriptor(
221 prepared.httpBaseUrl,
222 prepared.environmentId,
223 prepared.httpBaseUrl.startsWith("https:"),
224 ).pipe(
225 Effect.withSpan("ConnectionDriver.checkHost", {
226 attributes: { "connection.target.kind": prepared.target._tag },
227 }),
228 );
229
230 const connect = Effect.fn("ConnectionDriver.connect")(function* (
231 entry: ConnectionCatalogEntry,
232 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
233 ) {
234 const target = entry.target;
235 yield* Effect.annotateCurrentSpan({
236 "connection.environment.id": target.environmentId,
237 "connection.target.kind": target._tag,
238 "connection.route.count": connectionRoutes(entry).length,
239 });
240 yield* reportProgress({ stage: "preparing" });
241 return yield* connectOverRoutes(
242 entry,
243 (route) => checkRoute(entry, route),
244 Effect.fnUntraced(function* (route) {
245 yield* reportProgress({ stage: "preparing" });
246 const prepared = yield* resolver.prepare(routeEntry(entry, route));
247 yield* reportProgress({ stage: "opening", prepared });
248 const session = yield* sessions.connect(prepared);
249 yield* reportProgress({ stage: "synchronizing", prepared });
250 yield* session.ready;
251 // The server closes a socket when its session expires, unless the same key renewed it.
252 if (prepared.httpAuthorization?._tag === "Dpop") {
253 yield* remote
254 .renewDpopBeforeExpiry({
255 expectedEnvironmentId: prepared.environmentId,
256 expiresAtEpochMs: prepared.httpAuthorization.expiresAtEpochMs,
257 ...(prepared.httpAuthorization.directConnection
258 ? { directConnection: prepared.httpAuthorization.directConnection }
259 : {}),
260 })
261 .pipe(
262 Effect.catch((error) =>
263 Effect.logWarning("Could not renew the connection's credential.", { error }),
264 ),
265 Effect.forkScoped,
266 );
267 }
268 return { prepared, session } satisfies RouteConnection;
269 }),
270 );
271 });
272
273 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
274 preflightRoute(
275 sendsTokenInClear(connectionRoutes(entry), route)
276 ? Effect.succeed("silent" as const)
277 : checkRoute(entry, route),
278 resolver.prepare(routeEntry(entry, route)),
279 ).pipe(Effect.withSpan("ConnectionDriver.preflight"));
280
281 return ConnectionDriver.of({ connect, preflight, checkHost });
282 });
283
284 export const layer = Layer.effect(ConnectionDriver, make);