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 };
43
44export interface RouteConnection {
45 readonly prepared: PreparedConnection;
46 readonly session: RpcSession.RpcSession;
47}
48
49export 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
54export 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 */
59export type RoutePreflight = "ready" | "refused" | "unprepared" | "silent" | "unchecked";
60
61const 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.
65const ROUTE_CHECK_HEAD_START_MS = 500;
66
67export 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
83export 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 // Kept when `transient` is set aside below, so a relay refusal never ends retries.
99 let firstTransient: ConnectionAttemptError | undefined;
100 let blocked: ConnectionAttemptError | undefined;
101 let relayRefused: ConnectionAttemptError | undefined;
102 const refusedRouteIds: Array<string> = [];
103 // Each route gets its own scope so a half-open session closes before the next try.
104 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
105 const routeScope = yield* Scope.fork(attemptScope);
106 const result = yield* connectRoute(route).pipe(
107 Scope.provide(routeScope),
108 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
109 Effect.result,
110 );
111 if (result._tag === "Failure") {
112 if (result.failure._tag === "ConnectionTransientError") {
113 transient ??= result.failure;
114 firstTransient ??= result.failure;
115 }
116 // A T3 Connect refusal cannot explain why a direct route failed.
117 else if (result.failure.hop === "relay" || result.failure.hop === "tunnel")
118 relayRefused ??= result.failure;
119 else blocked ??= result.failure;
120 if (isHostCredentialRefusal(result.failure))
121 refusedRouteIds.push(connectionRouteId(route.target));
122 }
123 return result;
124 });
125 const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
126 for (const [index, route] of routes.entries()) {
127 const check =
128 checks.length === 0
129 ? "unchecked"
130 : 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 late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
144 concurrency: "unbounded",
145 });
146 const answeredLate = silent.filter((_, position) => late[position] !== "silent");
147 const stillSilent = silent.filter((_, position) => late[position] === "silent");
148 for (const { route } of [...answeredLate, ...stillSilent]) {
149 // A route still silent after its whole check can hold the attempt open far
150 // longer than the check did. Once another route failed in a way that
151 // retries, the retry reaches it sooner than waiting here would.
152 const neverAnswered = stillSilent.some((entry) => entry.route === route);
153 if (transient !== undefined && neverAnswered) break;
154 const result = yield* attempt(route);
155 if (result._tag === "Success") return { ...result.success, refusedRouteIds };
156 if (result.failure.reason === "unsupported") return yield* result.failure;
157 // A route that never answered cannot explain why a host that answered refused.
158 if (neverAnswered && (blocked ?? relayRefused) !== undefined) transient = undefined;
159 }
160 return yield* (
161 transient ??
162 blocked ??
163 firstTransient ??
164 relayRefused ??
165 new ConnectionTransientError({
166 reason: "endpoint-unavailable",
167 ...translatableDetail(
168 msg("{host} did not answer on any saved route.", { host: entry.target.label }),
169 ),
170 })
171 );
172});
173
174export const preflightRoute = (
175 check: Effect.Effect<RouteCheck>,
176 prepare: Effect.Effect<unknown, ConnectionAttemptError>,
177): Effect.Effect<RoutePreflight> =>
178 check.pipe(
179 Effect.filterOrElse(
180 (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
181 () =>
182 prepare.pipe(
183 Effect.as<RoutePreflight>("ready"),
184 Effect.catch((error) =>
185 Effect.succeed<RoutePreflight>(
186 isHostCredentialRefusal(error) ? "refused" : "unprepared",
187 ),
188 ),
189 ),
190 ),
191 );
192
193/** @public */
194export const make = Effect.gen(function* () {
195 const resolver = yield* ConnectionResolver.ConnectionResolver;
196 const sessions = yield* RpcSession.RpcSessionFactory;
197 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
198 const httpClient = yield* HttpClient.HttpClient;
199
200 // The descriptor is public, so this sends no credential to whatever
201 // answers at a saved LAN address on a different network.
202 const checkDescriptor = (httpBaseUrl: string, environmentId: string, keepsItsHost: boolean) =>
203 fetchRemoteEnvironmentDescriptor({
204 httpBaseUrl,
205 timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
206 }).pipe(
207 Effect.option,
208 // The connect this check leads to skips its own read. Every answer, even a
209 // failure, replaces what an older check remembered.
210 Effect.tap((descriptor) =>
211 remote.rememberCheckedDescriptor(httpBaseUrl, descriptor, keepsItsHost),
212 ),
213 Effect.map((descriptor): RouteCheck =>
214 Option.exists(descriptor, (value) => value.environmentId === environmentId)
215 ? "answered"
216 : "silent",
217 ),
218 // A cached descriptor would answer for a host that cannot be reached.
219 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
220 Effect.provideService(HttpClient.HttpClient, httpClient),
221 );
222
223 const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
224 const httpBaseUrl = routeHttpBaseUrl(route);
225 if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
226 return checkDescriptor(httpBaseUrl, entry.target.environmentId, routeKeepsItsHost(route)).pipe(
227 Effect.withSpan("ConnectionDriver.checkRoute", {
228 attributes: { "connection.target.kind": route.target._tag },
229 }),
230 );
231 };
232
233 const checkHost = (prepared: PreparedConnection) =>
234 checkDescriptor(
235 prepared.httpBaseUrl,
236 prepared.environmentId,
237 prepared.httpBaseUrl.startsWith("https:"),
238 ).pipe(
239 Effect.withSpan("ConnectionDriver.checkHost", {
240 attributes: { "connection.target.kind": prepared.target._tag },
241 }),
242 );
243
244 const connect = Effect.fn("ConnectionDriver.connect")(function* (
245 entry: ConnectionCatalogEntry,
246 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
247 ) {
248 const target = entry.target;
249 yield* Effect.annotateCurrentSpan({
250 "connection.environment.id": target.environmentId,
251 "connection.target.kind": target._tag,
252 "connection.route.count": connectionRoutes(entry).length,
253 });
254 yield* reportProgress({ stage: "preparing" });
255 return yield* connectOverRoutes(
256 entry,
257 (route) => checkRoute(entry, route),
258 Effect.fnUntraced(function* (route) {
259 yield* reportProgress({ stage: "preparing" });
260 const prepared = yield* resolver.prepare(routeEntry(entry, route));
261 yield* reportProgress({ stage: "opening", prepared });
262 const session = yield* sessions.connect(prepared);
263 yield* reportProgress({ stage: "synchronizing", prepared });
264 yield* session.ready;
265 // The server closes a socket when its session expires, unless the same key renewed it.
266 if (prepared.httpAuthorization?._tag === "Dpop") {
267 yield* remote
268 .renewDpopBeforeExpiry({
269 expectedEnvironmentId: prepared.environmentId,
270 expiresAtEpochMs: prepared.httpAuthorization.expiresAtEpochMs,
271 ...(prepared.httpAuthorization.directConnection
272 ? { directConnection: prepared.httpAuthorization.directConnection }
273 : {}),
274 })
275 .pipe(
276 Effect.catch((error) =>
277 Effect.logWarning("Could not renew the connection's credential.", { error }),
278 ),
279 Effect.forkScoped,
280 );
281 }
282 return { prepared, session } satisfies RouteConnection;
283 }),
284 );
285 });
286
287 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
288 preflightRoute(
289 sendsTokenInClear(connectionRoutes(entry), route)
290 ? Effect.succeed("silent" as const)
291 : checkRoute(entry, route),
292 resolver.prepare(routeEntry(entry, route)),
293 ).pipe(Effect.withSpan("ConnectionDriver.preflight"));
294
295 return ConnectionDriver.of({ connect, preflight, checkHost });
296});
297
298export const layer = Layer.effect(ConnectionDriver, make);