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