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