Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Scope from "effect/Scope";
7import * as FetchHttpClient from "effect/http/FetchHttpClient";
8import * as HttpClient from "effect/http/HttpClient";
9
10import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
11import type {
12 ConnectionAttemptError,
13 ConnectionAttemptStage,
14 PreparedConnection,
15} from "./model.ts";
16import { ConnectionTransientError } from "./model.ts";
17import * as ConnectionResolver from "./resolver.ts";
18import {
19 connectionRoutes,
20 routeEntry,
21 routeHttpBaseUrl,
22 sendsTokenInClear,
23 usableRoutes,
24} from "./routes.ts";
25import * as RpcSession from "../rpc/session.ts";
26import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
27
28export type ConnectionDriverProgress =
29 | {
30 readonly stage: "preparing";
31 }
32 | {
33 readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
34 readonly prepared: PreparedConnection;
35 };
36
37export interface EnvironmentConnectionLease {
38 readonly prepared: PreparedConnection;
39 readonly session: RpcSession.RpcSession;
40}
41
42export type RouteCheck = "answered" | "silent" | "unchecked";
43/** "unprepared" means the route answered its check but could not be prepared. */
44export type RoutePreflight = "ready" | "unprepared" | "silent" | "unchecked";
45
46const ROUTE_CHECK_TIMEOUT_MS = 2_500;
47// Preferred direct routes share one head start, so a relay connection does not
48// wait the full probe timeout for a LAN the device has already left. A route
49// that misses it connects over relay, then upgrades with a second reconnect.
50const ROUTE_CHECK_HEAD_START_MS = 500;
51
52export class ConnectionDriver extends Context.Service<
53 ConnectionDriver,
54 {
55 readonly connect: (
56 entry: ConnectionCatalogEntry,
57 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
58 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
59 readonly preflight: (
60 entry: ConnectionCatalogEntry,
61 route: ConnectionRoute,
62 ) => Effect.Effect<RoutePreflight>;
63 /** Asks the host behind a live session to answer a fresh request on the session's own origin. */
64 readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
65 }
66>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
67
68export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
69 entry: ConnectionCatalogEntry,
70 checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
71 connectRoute: (
72 route: ConnectionRoute,
73 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
74) {
75 const routes = usableRoutes(entry);
76 const checks =
77 routes.length === 1
78 ? []
79 : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
80 const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
81 const attemptScope = yield* Scope.Scope;
82 let transient: ConnectionAttemptError | undefined;
83 let blocked: ConnectionAttemptError | undefined;
84 // Each route gets its own scope so a half-open session closes before the next try.
85 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
86 const routeScope = yield* Scope.fork(attemptScope);
87 const result = yield* connectRoute(route).pipe(
88 Scope.provide(routeScope),
89 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
90 Effect.result,
91 );
92 if (result._tag === "Failure") {
93 if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
94 else blocked ??= result.failure;
95 }
96 return result;
97 });
98 const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
99 for (const [index, route] of routes.entries()) {
100 const check =
101 checks.length === 0
102 ? "unchecked"
103 : yield* Effect.raceFirst(
104 Fiber.join(checks[index]!),
105 Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
106 );
107 if (check === "silent") {
108 silent.push({ route, index });
109 continue;
110 }
111 const result = yield* attempt(route);
112 if (result._tag === "Success") return result.success;
113 // An incompatible server is the same server on every route.
114 if (result.failure.reason === "unsupported") return yield* result.failure;
115 }
116 // A slow route that answered after the head start goes before one that is
117 // still dead, which can hold an attempt open far longer than its probe.
118 const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
119 concurrency: "unbounded",
120 });
121 const retry = [
122 ...silent.filter((_, position) => late[position] !== "silent"),
123 ...silent.filter((_, position) => late[position] === "silent"),
124 ];
125 for (const { route } of retry) {
126 const result = yield* attempt(route);
127 if (result._tag === "Success") return result.success;
128 if (result.failure.reason === "unsupported") return yield* result.failure;
129 }
130 return yield* (
131 transient ??
132 blocked ??
133 new ConnectionTransientError({
134 reason: "endpoint-unavailable",
135 detail: `${entry.target.label} did not answer on any saved route.`,
136 })
137 );
138});
139
140/** @public */
141export const make = Effect.gen(function* () {
142 const resolver = yield* ConnectionResolver.ConnectionResolver;
143 const sessions = yield* RpcSession.RpcSessionFactory;
144 const httpClient = yield* HttpClient.HttpClient;
145
146 // The descriptor is public, so this sends no credential to whatever
147 // answers at a saved LAN address on a different network.
148 const checkDescriptor = (httpBaseUrl: string, environmentId: string) =>
149 fetchRemoteEnvironmentDescriptor({
150 httpBaseUrl,
151 timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
152 }).pipe(
153 Effect.map((descriptor): RouteCheck =>
154 descriptor.environmentId === environmentId ? "answered" : "silent",
155 ),
156 Effect.orElseSucceed((): RouteCheck => "silent"),
157 // A cached descriptor would answer for a host that cannot be reached.
158 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
159 Effect.provideService(HttpClient.HttpClient, httpClient),
160 );
161
162 const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
163 const httpBaseUrl = routeHttpBaseUrl(route);
164 if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
165 return checkDescriptor(httpBaseUrl, entry.target.environmentId).pipe(
166 Effect.withSpan("ConnectionDriver.checkRoute", {
167 attributes: { "connection.target.kind": route.target._tag },
168 }),
169 );
170 };
171
172 const checkHost = (prepared: PreparedConnection) =>
173 checkDescriptor(prepared.httpBaseUrl, prepared.environmentId).pipe(
174 Effect.withSpan("ConnectionDriver.checkHost", {
175 attributes: { "connection.target.kind": prepared.target._tag },
176 }),
177 );
178
179 const connect = Effect.fn("ConnectionDriver.connect")(function* (
180 entry: ConnectionCatalogEntry,
181 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
182 ) {
183 const target = entry.target;
184 yield* Effect.annotateCurrentSpan({
185 "connection.environment.id": target.environmentId,
186 "connection.target.kind": target._tag,
187 "connection.route.count": connectionRoutes(entry).length,
188 });
189 yield* reportProgress({ stage: "preparing" });
190 return yield* connectOverRoutes(
191 entry,
192 (route) => checkRoute(entry, route),
193 Effect.fnUntraced(function* (route) {
194 const prepared = yield* resolver.prepare(routeEntry(entry, route));
195 yield* reportProgress({ stage: "opening", prepared });
196 const session = yield* sessions.connect(prepared);
197 yield* reportProgress({ stage: "synchronizing", prepared });
198 yield* session.ready;
199 return { prepared, session } satisfies EnvironmentConnectionLease;
200 }),
201 );
202 });
203
204 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
205 (sendsTokenInClear(connectionRoutes(entry), route)
206 ? Effect.succeed("silent" as const)
207 : checkRoute(entry, route)
208 ).pipe(
209 Effect.filterOrElse(
210 (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
211 () =>
212 resolver.prepare(routeEntry(entry, route)).pipe(
213 Effect.as<RoutePreflight>("ready"),
214 Effect.orElseSucceed((): RoutePreflight => "unprepared"),
215 ),
216 ),
217 Effect.withSpan("ConnectionDriver.preflight"),
218 );
219
220 return ConnectionDriver.of({ connect, preflight, checkHost });
221});
222
223export const layer = Layer.effect(ConnectionDriver, make);