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

driver.ts

246 lines9.8 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Exit from "effect/Exit";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Scope from "effect/Scope";
8import * as FetchHttpClient from "effect/http/FetchHttpClient";
9import * as HttpClient from "effect/http/HttpClient";
10​
11import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
12import type {
13 ConnectionAttemptError,
14 ConnectionAttemptStage,
15 PreparedConnection,
16} from "./model.ts";
17import { ConnectionTransientError } from "./model.ts";
18import * as ConnectionResolver from "./resolver.ts";
19import {
20 connectionRoutes,
21 routeEntry,
22 routeHttpBaseUrl,
23 sendsTokenInClear,
24 usableRoutes,
25} from "./routes.ts";
26import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
27import * as RpcSession from "../rpc/session.ts";
28import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
29​
30export type ConnectionDriverProgress =
31 | {
32 readonly stage: "preparing";
33 }
34 | {
35 readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
36 readonly prepared: PreparedConnection;
37 };
38​
39export interface EnvironmentConnectionLease {
40 readonly prepared: PreparedConnection;
41 readonly session: RpcSession.RpcSession;
43​
44export type RouteCheck = "answered" | "silent" | "unchecked";
45/** "unprepared" means the route answered its check but could not be prepared. */
46export type RoutePreflight = "ready" | "unprepared" | "silent" | "unchecked";
47​
48const ROUTE_CHECK_TIMEOUT_MS = 2_500;
49// Preferred direct routes share one head start, so a relay connection does not
50// wait the full probe timeout for a LAN the device has already left. A route
51// that misses it connects over relay, then upgrades with a second reconnect.
52const ROUTE_CHECK_HEAD_START_MS = 500;
53​
54export class ConnectionDriver extends Context.Service<
55 ConnectionDriver,
56 {
57 readonly connect: (
58 entry: ConnectionCatalogEntry,
59 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
60 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
61 readonly preflight: (
62 entry: ConnectionCatalogEntry,
63 route: ConnectionRoute,
64 ) => Effect.Effect<RoutePreflight>;
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 remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
147 const httpClient = yield* HttpClient.HttpClient;
148​
149 // The descriptor is public, so this sends no credential to whatever
150 // answers at a saved LAN address on a different network.
151 const checkDescriptor = (httpBaseUrl: string, environmentId: string) =>
152 fetchRemoteEnvironmentDescriptor({
153 httpBaseUrl,
154 timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
155 }).pipe(
156 Effect.option,
157 // The connect this check leads to skips its own read. Every answer, even a
158 // failure, replaces what an older check remembered.
159 Effect.tap((descriptor) => remote.rememberCheckedDescriptor(httpBaseUrl, descriptor)),
160 Effect.map((descriptor): RouteCheck =>
161 Option.exists(descriptor, (value) => value.environmentId === environmentId)
162 ? "answered"
163 : "silent",
164 ),
165 // A cached descriptor would answer for a host that cannot be reached.
166 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
167 Effect.provideService(HttpClient.HttpClient, httpClient),
168 );
169​
170 const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
171 const httpBaseUrl = routeHttpBaseUrl(route);
172 if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
173 return checkDescriptor(httpBaseUrl, entry.target.environmentId).pipe(
174 Effect.withSpan("ConnectionDriver.checkRoute", {
175 attributes: { "connection.target.kind": route.target._tag },
176 }),
177 );
178 };
179​
180 const checkHost = (prepared: PreparedConnection) =>
181 checkDescriptor(prepared.httpBaseUrl, prepared.environmentId).pipe(
182 Effect.withSpan("ConnectionDriver.checkHost", {
183 attributes: { "connection.target.kind": prepared.target._tag },
184 }),
185 );
186​
187 const connect = Effect.fn("ConnectionDriver.connect")(function* (
188 entry: ConnectionCatalogEntry,
189 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
190 ) {
191 const target = entry.target;
192 yield* Effect.annotateCurrentSpan({
193 "connection.environment.id": target.environmentId,
194 "connection.target.kind": target._tag,
195 "connection.route.count": connectionRoutes(entry).length,
196 });
197 yield* reportProgress({ stage: "preparing" });
198 return yield* connectOverRoutes(
199 entry,
200 (route) => checkRoute(entry, route),
201 Effect.fnUntraced(function* (route) {
202 yield* reportProgress({ stage: "preparing" });
203 const prepared = yield* resolver.prepare(routeEntry(entry, route));
204 yield* reportProgress({ stage: "opening", prepared });
205 const session = yield* sessions.connect(prepared);
206 yield* reportProgress({ stage: "synchronizing", prepared });
207 yield* session.ready;
208 // The server closes a socket when its session expires, unless the same key renewed it.
209 if (prepared.httpAuthorization?._tag === "Dpop") {
210 yield* remote
211 .renewDpopBeforeExpiry({
212 expectedEnvironmentId: prepared.environmentId,
213 expiresAtEpochMs: prepared.httpAuthorization.expiresAtEpochMs,
214 })
215 .pipe(
216 Effect.catch((error) =>
217 Effect.logWarning("Could not renew the connection's credential.", { error }),
218 ),
219 Effect.forkScoped,
220 );
221 }
222 return { prepared, session } satisfies EnvironmentConnectionLease;
223 }),
224 );
225 });
226​
227 const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
228 (sendsTokenInClear(connectionRoutes(entry), route)
229 ? Effect.succeed("silent" as const)
230 : checkRoute(entry, route)
231 ).pipe(
232 Effect.filterOrElse(
233 (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
234 () =>
235 resolver.prepare(routeEntry(entry, route)).pipe(
236 Effect.as<RoutePreflight>("ready"),
237 Effect.orElseSucceed((): RoutePreflight => "unprepared"),
238 ),
239 ),
240 Effect.withSpan("ConnectionDriver.preflight"),
241 );
242​
243 return ConnectionDriver.of({ connect, preflight, checkHost });
244});
245​
246export const layer = Layer.effect(ConnectionDriver, make);