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