Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

driver.ts

328 lines13.0 KB

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