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

driver.ts

221 lines8.4 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 preflight: (
58 entry: ConnectionCatalogEntry,
59 route: ConnectionRoute,
60 ) => Effect.Effect<boolean>;
61 /** Asks the host behind a live session to answer a fresh request on the session's own origin. */
62 readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
63 }
64>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
65​
66export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
67 entry: ConnectionCatalogEntry,
68 checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
69 connectRoute: (
70 route: ConnectionRoute,
71 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, R | Scope.Scope>,
72) {
73 const routes = usableRoutes(entry);
74 const checks =
75 routes.length === 1
76 ? []
77 : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
78 const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
79 const attemptScope = yield* Scope.Scope;
80 let transient: ConnectionAttemptError | undefined;
81 let blocked: ConnectionAttemptError | undefined;
82 // Each route gets its own scope so a half-open session closes before the next try.
83 const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
84 const routeScope = yield* Scope.fork(attemptScope);
85 const result = yield* connectRoute(route).pipe(
86 Scope.provide(routeScope),
87 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
88 Effect.result,
89 );
90 if (result._tag === "Failure") {
91 if (result.failure._tag === "ConnectionTransientError") transient ??= result.failure;
92 else blocked ??= result.failure;
93 }
94 return result;
95 });
96 const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
97 for (const [index, route] of routes.entries()) {
98 const check =
99 checks.length === 0
100 ? "unchecked"
101 : yield* Effect.raceFirst(
102 Fiber.join(checks[index]!),
103 Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
104 );
105 if (check === "silent") {
106 silent.push({ route, index });
107 continue;
108 }
109 const result = yield* attempt(route);
110 if (result._tag === "Success") return result.success;
111 // An incompatible server is the same server on every route.
112 if (result.failure.reason === "unsupported") return yield* result.failure;
113 }
114 // A slow route that answered after the head start goes before one that is
115 // still dead, which can hold an attempt open far longer than its probe.
116 const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
117 concurrency: "unbounded",
118 });
119 const retry = [
120 ...silent.filter((_, position) => late[position] !== "silent"),
121 ...silent.filter((_, position) => late[position] === "silent"),
122 ];
123 for (const { route } of retry) {
124 const result = yield* attempt(route);
125 if (result._tag === "Success") return result.success;
126 if (result.failure.reason === "unsupported") return yield* result.failure;
127 }
128 return yield* (
129 transient ??
130 blocked ??
131 new ConnectionTransientError({
132 reason: "endpoint-unavailable",
133 detail: `${entry.target.label} did not answer on any saved route.`,
134 })
135 );
136});
137​
138/** @public */
139export const make = Effect.gen(function* () {
140 const resolver = yield* ConnectionResolver.ConnectionResolver;
141 const sessions = yield* RpcSession.RpcSessionFactory;
142 const httpClient = yield* HttpClient.HttpClient;
143​
144 // The descriptor is public, so this sends no credential to whatever
145 // answers at a saved LAN address on a different network.
146 const checkDescriptor = (httpBaseUrl: string, environmentId: string) =>
147 fetchRemoteEnvironmentDescriptor({
148 httpBaseUrl,
149 timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
150 }).pipe(
151 Effect.map((descriptor): RouteCheck =>
152 descriptor.environmentId === environmentId ? "answered" : "silent",
153 ),
154 Effect.orElseSucceed((): RouteCheck => "silent"),
155 // A cached descriptor would answer for a host that cannot be reached.
156 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
157 Effect.provideService(HttpClient.HttpClient, httpClient),
158 );
159​
160 const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
161 const httpBaseUrl = routeHttpBaseUrl(route);
162 if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
163 return checkDescriptor(httpBaseUrl, entry.target.environmentId).pipe(
164 Effect.withSpan("ConnectionDriver.checkRoute", {
165 attributes: { "connection.target.kind": route.target._tag },
166 }),
167 );
168 };
169​
170 const checkHost = (prepared: PreparedConnection) =>
171 checkDescriptor(prepared.httpBaseUrl, prepared.environmentId).pipe(
172 Effect.withSpan("ConnectionDriver.checkHost", {
173 attributes: { "connection.target.kind": prepared.target._tag },
174 }),
175 );
176​
177 const connect = Effect.fn("ConnectionDriver.connect")(function* (
178 entry: ConnectionCatalogEntry,
179 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
180 ) {
181 const target = entry.target;
182 yield* Effect.annotateCurrentSpan({
183 "connection.environment.id": target.environmentId,
184 "connection.target.kind": target._tag,
185 "connection.route.count": connectionRoutes(entry).length,
186 });
187 yield* reportProgress({ stage: "preparing" });
188 return yield* connectOverRoutes(
189 entry,
190 (route) => checkRoute(entry, route),
191 Effect.fnUntraced(function* (route) {
192 const prepared = yield* resolver.prepare(routeEntry(entry, route));
193 yield* reportProgress({ stage: "opening", prepared });
194 const session = yield* sessions.connect(prepared);
195 yield* reportProgress({ stage: "synchronizing", prepared });
196 yield* session.ready;
197 return { prepared, session } satisfies EnvironmentConnectionLease;
198 }),
199 );
200 });
201​
202 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
203 (sendsTokenInClear(connectionRoutes(entry), route)
204 ? Effect.succeed("silent" as const)
205 : checkRoute(entry, route)
206 ).pipe(
207 Effect.flatMap((check) =>
208 check === "answered"
209 ? resolver.prepare(routeEntry(entry, route)).pipe(
210 Effect.as(true),
211 Effect.orElseSucceed(() => false),
212 )
213 : Effect.succeed(false),
214 ),
215 Effect.withSpan("ConnectionDriver.preflight"),
216 );
217​
218 return ConnectionDriver.of({ connect, preflight, checkHost });
219});
220​
221export const layer = Layer.effect(ConnectionDriver, make);