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

driver.ts

225 lines8.6 KB

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;
41​
42export type RouteCheck = "answered" | "silent" | "unchecked";
43​
44const ROUTE_CHECK_TIMEOUT_MS = 2_500;
45// Preferred direct routes share one head start, so a relay connection does not
46// wait the full probe timeout for a LAN the device has already left. A route
47// that misses it connects over relay, then upgrades with a second reconnect.
48const ROUTE_CHECK_HEAD_START_MS = 500;
49​
50export class ConnectionDriver extends Context.Service<
51 ConnectionDriver,
52 {
53 readonly connect: (
54 entry: ConnectionCatalogEntry,
55 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
56 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
57 readonly checkRoute: (
58 entry: ConnectionCatalogEntry,
59 route: ConnectionRoute,
60 ) => Effect.Effect<RouteCheck>;
61 readonly preflight: (
62 entry: ConnectionCatalogEntry,
63 route: ConnectionRoute,
64 ) => Effect.Effect<boolean>;
65 /** Asks the host behind a live session to answer a fresh request on the session's own origin. */
66 readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
67 }
68>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
69​
70export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
71 entry: ConnectionCatalogEntry,
72 checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
73 connectRoute: (
74 route: ConnectionRoute,
75 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
76) {
77 const routes = usableRoutes(entry);
78 const checks =
79 routes.length === 1
80 ? []
81 : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
82 const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
83 const attemptScope = yield* Scope.Scope;
84 let transient: ConnectionAttemptError | undefined;
85 let blocked: ConnectionAttemptError | undefined;
86 // Each route gets its own scope so a half-open session closes before the next try.
87 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
88 const routeScope = yield* Scope.fork(attemptScope);
89 const result = yield* connectRoute(route).pipe(
90 Scope.provide(routeScope),
91 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
92 Effect.result,
93 );
94 if (result._tag === "Failure") {
95 if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
96 else blocked ??= result.failure;
97 }
98 return result;
99 });
100 const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
101 for (const [index, route] of routes.entries()) {
102 const check =
103 checks.length === 0
104 ? "unchecked"
105 : yield* Effect.raceFirst(
106 Fiber.join(checks[index]!),
107 Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
108 );
109 if (check === "silent") {
110 silent.push({ route, index });
111 continue;
112 }
113 const result = yield* attempt(route);
114 if (result._tag === "Success") return result.success;
115 // An incompatible server is the same server on every route.
116 if (result.failure.reason === "unsupported") return yield* result.failure;
117 }
118 // A slow route that answered after the head start goes before one that is
119 // still dead, which can hold an attempt open far longer than its probe.
120 const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
121 concurrency: "unbounded",
122 });
123 const retry = [
124 ...silent.filter((_, position) => late[position] !== "silent"),
125 ...silent.filter((_, position) => late[position] === "silent"),
126 ];
127 for (const { route } of retry) {
128 const result = yield* attempt(route);
129 if (result._tag === "Success") return result.success;
130 if (result.failure.reason === "unsupported") return yield* result.failure;
131 }
132 return yield* (
133 transient ??
134 blocked ??
135 new ConnectionTransientError({
136 reason: "endpoint-unavailable",
137 detail: `${entry.target.label} did not answer on any saved route.`,
138 })
139 );
140});
141​
142/** @public */
143export const make = Effect.gen(function* () {
144 const resolver = yield* ConnectionResolver.ConnectionResolver;
145 const sessions = yield* RpcSession.RpcSessionFactory;
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 return { prepared, session } satisfies EnvironmentConnectionLease;
202 }),
203 );
204 });
205​
206 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
207 (sendsTokenInClear(connectionRoutes(entry), route)
208 ? Effect.succeed("silent" as const)
209 : checkRoute(entry, route)
210 ).pipe(
211 Effect.flatMap((check) =>
212 check === "answered"
213 ? resolver.prepare(routeEntry(entry, route)).pipe(
214 Effect.as(true),
215 Effect.orElseSucceed(() => false),
216 )
217 : Effect.succeed(false),
218 ),
219 Effect.withSpan("ConnectionDriver.preflight"),
220 );
221​
222 return ConnectionDriver.of({ connect, checkRoute, preflight, checkHost });
223});
224​
225export const layer = Layer.effect(ConnectionDriver, make);