Repository navigation
Expand file tree
/
Copy pathdriver.ts
More file actions
300 lines (283 loc) · 11.9 KB
/
Copy pathdriver.ts
File metadata and controls
300 lines (283 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { msg } from "gt-i18n";
import { translatableDetail } from "../errors/translatable.ts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
import type {
ConnectionAttemptError,
ConnectionAttemptStage,
PreparedConnection,
} from "./model.ts";
import { ConnectionTransientError } from "./model.ts";
import { isHostCredentialRefusal } from "./errors.ts";
import * as ConnectionResolver from "./resolver.ts";
import {
connectionRoutes,
connectionRouteId,
credentialConnectionId,
routeEntry,
routeHttpBaseUrl,
routeKeepsItsHost,
sendsTokenInClear,
usableRoutes,
} from "./routes.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as RpcSession from "../rpc/session.ts";
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
export type ConnectionDriverProgress =
| {
readonly stage: "preparing";
}
| {
readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
readonly prepared: PreparedConnection;
};
export interface RouteConnection {
readonly prepared: PreparedConnection;
readonly session: RpcSession.RpcSession;
}
export interface EnvironmentConnectionLease extends RouteConnection {
/** Saved routes whose host refused this device's credential before another route connected. */
readonly refusedRouteIds: ReadonlyArray<string>;
}
export type RouteCheck = "answered" | "silent" | "unchecked";
/**
* "unprepared" means the route answered its check but could not be prepared;
* "refused" means its host refused this device's credential.
*/
export type RoutePreflight = "ready" | "refused" | "unprepared" | "silent" | "unchecked";
const ROUTE_CHECK_TIMEOUT_MS = 2_500;
// Preferred direct routes share one head start, so a relay connection does not
// wait the full probe timeout for a LAN the device has already left. A route
// that misses it connects over relay, then upgrades with a second reconnect.
const ROUTE_CHECK_HEAD_START_MS = 500;
export class ConnectionDriver extends Context.Service<
ConnectionDriver,
{
readonly connect: (
entry: ConnectionCatalogEntry,
reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
readonly preflight: (
entry: ConnectionCatalogEntry,
route: ConnectionRoute,
) => Effect.Effect<RoutePreflight>;
readonly mintLanCredential: (input: {
readonly httpBaseUrl: string;
readonly bearerToken: string;
}) => Effect.Effect<string, ConnectionAttemptError>;
/** Asks the host behind a live session to answer a fresh request on the session's own origin. */
readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;
}
>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")(function* <R>(
entry: ConnectionCatalogEntry,
checkRoute: (route: ConnectionRoute) => Effect.Effect<RouteCheck>,
connectRoute: (
route: ConnectionRoute,
) => Effect.Effect<RouteConnection, ConnectionAttemptError, R | Scope.Scope>,
) {
const routes = usableRoutes(entry);
const checks =
routes.length === 1
? []
: yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
const attemptScope = yield* Scope.Scope;
const transient = new Map<string, ConnectionAttemptError>();
const rejectedCredentials = new Set<string>();
let blocked: ConnectionAttemptError | undefined;
const refusedRouteIds: Array<string> = [];
// Each route gets its own scope so a half-open session closes before the next try.
const attempt = Effect.fnUntraced(function* (route: ConnectionRoute) {
const routeScope = yield* Scope.fork(attemptScope);
const result = yield* connectRoute(route).pipe(
Scope.provide(routeScope),
Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : Scope.close(routeScope, exit))),
Effect.result,
);
if (result._tag === "Failure") {
const credentialId = credentialConnectionId(connectionRouteId(route.target));
if (result.failure._tag === "ConnectionTransientError") {
if (!transient.has(credentialId)) transient.set(credentialId, result.failure);
} else {
blocked ??= result.failure;
if (result.failure.reason === "authentication") rejectedCredentials.add(credentialId);
}
if (isHostCredentialRefusal(result.failure))
refusedRouteIds.push(connectionRouteId(route.target));
}
return result;
});
const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
for (const [index, route] of routes.entries()) {
const check =
checks.length === 0
? "unchecked"
: yield* Effect.raceFirst(
Fiber.join(checks[index]!),
Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
);
if (check === "silent") {
silent.push({ route, index });
continue;
}
const result = yield* attempt(route);
if (result._tag === "Success") return { ...result.success, refusedRouteIds };
// An incompatible server is the same server on every route.
if (result.failure.reason === "unsupported") return yield* result.failure;
}
const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
concurrency: "unbounded",
});
const answeredLate = silent.filter((_, position) => late[position] !== "silent");
const stillSilent = silent.filter((_, position) => late[position] === "silent");
for (const { route } of [...answeredLate, ...stillSilent]) {
// A route still silent after its whole check can hold the attempt open far
// longer than the check did. Once another route failed in a way that
// retries, the retry reaches it sooner than waiting here would.
if (transient.size > 0 && stillSilent.some((entry) => entry.route === route)) break;
const result = yield* attempt(route);
if (result._tag === "Success") return { ...result.success, refusedRouteIds };
if (result.failure.reason === "unsupported") return yield* result.failure;
}
return yield* (
[...transient].find(([credentialId]) => !rejectedCredentials.has(credentialId))?.[1] ??
blocked ??
new ConnectionTransientError({
reason: "endpoint-unavailable",
...translatableDetail(
msg("{host} did not answer on any saved route.", { host: entry.target.label }),
),
})
);
});
export const preflightRoute = (
check: Effect.Effect<RouteCheck>,
prepare: Effect.Effect<unknown, ConnectionAttemptError>,
): Effect.Effect<RoutePreflight> =>
check.pipe(
Effect.filterOrElse(
(check): check is Exclude<RouteCheck, "answered"> => check !== "answered",
() =>
prepare.pipe(
Effect.as<RoutePreflight>("ready"),
Effect.catch((error) =>
Effect.succeed<RoutePreflight>(
isHostCredentialRefusal(error) ? "refused" : "unprepared",
),
),
),
),
);
/** @public */
export const make = Effect.gen(function* () {
const resolver = yield* ConnectionResolver.ConnectionResolver;
const sessions = yield* RpcSession.RpcSessionFactory;
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
const httpClient = yield* HttpClient.HttpClient;
// The descriptor is public, so this sends no credential to whatever
// answers at a saved LAN address on a different network.
const checkDescriptor = (httpBaseUrl: string, environmentId: string, keepsItsHost: boolean) =>
fetchRemoteEnvironmentDescriptor({
httpBaseUrl,
timeoutMs: ROUTE_CHECK_TIMEOUT_MS,
}).pipe(
Effect.option,
// The connect this check leads to skips its own read. Every answer, even a
// failure, replaces what an older check remembered.
Effect.tap((descriptor) =>
remote.rememberCheckedDescriptor(httpBaseUrl, descriptor, keepsItsHost),
),
Effect.map((descriptor): RouteCheck =>
Option.exists(descriptor, (value) => value.environmentId === environmentId)
? "answered"
: "silent",
),
// A cached descriptor would answer for a host that cannot be reached.
Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => {
const httpBaseUrl = routeHttpBaseUrl(route);
if (httpBaseUrl === null) return Effect.succeed<RouteCheck>("unchecked");
return checkDescriptor(httpBaseUrl, entry.target.environmentId, routeKeepsItsHost(route)).pipe(
Effect.withSpan("ConnectionDriver.checkRoute", {
attributes: { "connection.target.kind": route.target._tag },
}),
);
};
const checkHost = (prepared: PreparedConnection) =>
checkDescriptor(
prepared.httpBaseUrl,
prepared.environmentId,
prepared.httpBaseUrl.startsWith("https:"),
).pipe(
Effect.withSpan("ConnectionDriver.checkHost", {
attributes: { "connection.target.kind": prepared.target._tag },
}),
);
const connect = Effect.fn("ConnectionDriver.connect")(function* (
entry: ConnectionCatalogEntry,
reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
) {
const target = entry.target;
yield* Effect.annotateCurrentSpan({
"connection.environment.id": target.environmentId,
"connection.target.kind": target._tag,
"connection.route.count": connectionRoutes(entry).length,
});
yield* reportProgress({ stage: "preparing" });
return yield* connectOverRoutes(
entry,
(route) => checkRoute(entry, route),
Effect.fnUntraced(function* (route) {
yield* reportProgress({ stage: "preparing" });
const prepared = yield* resolver.prepare(routeEntry(entry, route));
yield* reportProgress({ stage: "opening", prepared });
const session = yield* sessions.connect(prepared);
yield* reportProgress({ stage: "synchronizing", prepared });
yield* session.ready;
// The server closes a socket when its session expires, unless the same key renewed it.
if (prepared.httpAuthorization?._tag === "Dpop") {
yield* remote
.renewDpopBeforeExpiry({
expectedEnvironmentId: prepared.environmentId,
expiresAtEpochMs: prepared.httpAuthorization.expiresAtEpochMs,
...(prepared.httpAuthorization.directConnection
? { directConnection: prepared.httpAuthorization.directConnection }
: {}),
})
.pipe(
Effect.catch((error) =>
Effect.logWarning("Could not renew the connection's credential.", { error }),
),
Effect.forkScoped,
);
}
return { prepared, session } satisfies RouteConnection;
}),
);
});
const preflight = (entry: ConnectionCatalogEntry, route: ConnectionRoute) =>
preflightRoute(
sendsTokenInClear(connectionRoutes(entry), route)
? Effect.succeed("silent" as const)
: checkRoute(entry, route),
resolver.prepare(routeEntry(entry, route)),
).pipe(Effect.withSpan("ConnectionDriver.preflight"));
return ConnectionDriver.of({
connect,
preflight,
checkHost,
mintLanCredential: remote.mintLanCredential,
});
});
export const layer = Layer.effect(ConnectionDriver, make);