Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Ref from "effect/Ref";
8import * as FetchHttpClient from "effect/http/FetchHttpClient";
9import * as TestClock from "effect/testing/TestClock";
10
11import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
12import * as RpcSession from "../rpc/session.ts";
13import type { ConnectionCatalogEntry } from "./catalog.ts";
14import * as ConnectionDriver from "./driver.ts";
15import {
16 BearerConnectionTarget,
17 ConnectionBlockedError,
18 ConnectionTransientError,
19 RelayConnectionTarget,
20 SshConnectionTarget,
21 type PreparedConnection,
22} from "./model.ts";
23import * as ConnectionResolver from "./resolver.ts";
24
25const sshTarget = (connectionId: string) =>
26 new SshConnectionTarget({
27 environmentId: EnvironmentId.make("environment-1"),
28 label: "Test environment",
29 connectionId,
30 });
31
32const ENTRY: ConnectionCatalogEntry = {
33 target: sshTarget("ssh-first"),
34 profile: Option.none(),
35 enabled: true,
36 alternateRoutes: [{ target: sshTarget("ssh-second"), profile: Option.none() }],
37};
38
39describe("ConnectionDriver", () => {
40 it.effect("reports preparing before each route it prepares", () =>
41 Effect.gen(function* () {
42 const stages = yield* Ref.make<ReadonlyArray<string>>([]);
43 const driver = yield* ConnectionDriver.make.pipe(
44 Effect.provide(
45 Layer.mergeAll(
46 Layer.mock(ConnectionResolver.ConnectionResolver)({
47 prepare: (entry) =>
48 Effect.succeed({
49 environmentId: entry.target.environmentId,
50 label: entry.target.label,
51 httpBaseUrl: "http://127.0.0.1:1",
52 socketUrl: "ws://127.0.0.1:1/ws",
53 httpAuthorization: null,
54 target: entry.target,
55 } satisfies PreparedConnection),
56 }),
57 Layer.mock(RpcSession.RpcSessionFactory)({
58 connect: () =>
59 Effect.fail(
60 new ConnectionTransientError({ reason: "transport", detail: "Socket closed." }),
61 ),
62 }),
63 Layer.mock(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization)({}),
64 // SSH routes have no HTTP check, so the driver never sends a request.
65 FetchHttpClient.layer,
66 ),
67 ),
68 );
69
70 yield* driver
71 .connect(ENTRY, (progress) => Ref.update(stages, (all) => [...all, progress.stage]))
72 .pipe(Effect.scoped, Effect.flip);
73
74 expect(yield* Ref.get(stages)).toEqual([
75 "preparing",
76 "preparing",
77 "opening",
78 "preparing",
79 "opening",
80 ]);
81 }),
82 );
83
84 it.effect("a silent route's network failure does not hide an answered route's refusal", () =>
85 Effect.gen(function* () {
86 const refused = new ConnectionBlockedError({
87 reason: "authentication",
88 hop: "server",
89 detail: "Session token revoked.",
90 });
91 const attempted: Array<string> = [];
92 const error = yield* ConnectionDriver.connectOverRoutes(
93 ENTRY,
94 (route) =>
95 Effect.succeed<ConnectionDriver.RouteCheck>(
96 route.target === ENTRY.target ? "answered" : "silent",
97 ),
98 (route) => {
99 attempted.push(route.target.label);
100 return route.target === ENTRY.target
101 ? Effect.fail(refused)
102 : Effect.fail(
103 new ConnectionTransientError({ reason: "transport", detail: "Timed out." }),
104 );
105 },
106 ).pipe(Effect.scoped, Effect.flip);
107
108 // A refusal does not retry, so the silent route still gets its chance to connect.
109 expect(attempted).toHaveLength(2);
110 expect(error).toBe(refused);
111 }),
112 );
113
114 it.effect("connects over a late-answering route without waiting for still-silent routes", () =>
115 Effect.gen(function* () {
116 const environment = { environmentId: EnvironmentId.make("environment-1"), label: "Host" };
117 const dead = new BearerConnectionTarget({ ...environment, connectionId: "dead-tailnet" });
118 const slow = new BearerConnectionTarget({ ...environment, connectionId: "slow-lan" });
119 const connection = {
120 prepared: { target: slow } as PreparedConnection,
121 session: {} as RpcSession.RpcSession,
122 };
123 let deadCheckInterrupted = false;
124 const attempted: Array<string> = [];
125
126 const fiber = yield* ConnectionDriver.connectOverRoutes(
127 {
128 target: dead,
129 profile: Option.none(),
130 enabled: true,
131 alternateRoutes: [{ target: slow, profile: Option.none() }],
132 },
133 (route) =>
134 route.target === dead
135 ? Effect.sleep("2500 millis").pipe(
136 Effect.as<ConnectionDriver.RouteCheck>("silent"),
137 Effect.onInterrupt(() =>
138 Effect.sync(() => {
139 deadCheckInterrupted = true;
140 }),
141 ),
142 )
143 : Effect.sleep("600 millis").pipe(Effect.as<ConnectionDriver.RouteCheck>("answered")),
144 (route) => {
145 attempted.push(route.target === dead ? "dead-tailnet" : "slow-lan");
146 return Effect.succeed(connection);
147 },
148 ).pipe(Effect.scoped, Effect.forkChild);
149
150 yield* TestClock.adjust("600 millis");
151
152 const exit = fiber.pollUnsafe();
153 expect(exit && Exit.isSuccess(exit) ? exit.value.prepared : undefined).toBe(
154 connection.prepared,
155 );
156 expect(attempted).toEqual(["slow-lan"]);
157 expect(deadCheckInterrupted).toBe(true);
158 }),
159 );
160
161 it.effect.each([
162 { routeOrder: "responsive", expected: ["relay", "first-late", "second-late"] },
163 { routeOrder: "saved", expected: ["first-late", "second-late"] },
164 ] as const)(
165 "uses $routeOrder order when preferred routes answer after the head start",
166 ({ routeOrder, expected }) =>
167 Effect.gen(function* () {
168 const environment = { environmentId: EnvironmentId.make("environment-1"), label: "Host" };
169 const firstLate = new BearerConnectionTarget({
170 ...environment,
171 connectionId: "first-late",
172 });
173 const secondLate = new BearerConnectionTarget({
174 ...environment,
175 connectionId: "second-late",
176 });
177 const stillSilent = new BearerConnectionTarget({
178 ...environment,
179 connectionId: "still-silent",
180 });
181 const relay = new RelayConnectionTarget(environment);
182 const connection = {
183 prepared: { target: secondLate } as PreparedConnection,
184 session: {} as RpcSession.RpcSession,
185 };
186 const attempted: Array<string> = [];
187
188 const fiber = yield* ConnectionDriver.connectOverRoutes(
189 {
190 target: firstLate,
191 profile: Option.none(),
192 enabled: true,
193 alternateRoutes: [
194 { target: secondLate, profile: Option.none() },
195 { target: stillSilent, profile: Option.none() },
196 { target: relay, profile: Option.none() },
197 ],
198 },
199 (route) => {
200 if (route.target === relay)
201 return Effect.succeed<ConnectionDriver.RouteCheck>("unchecked");
202 if (route.target === firstLate)
203 return Effect.sleep("600 millis").pipe(
204 Effect.as<ConnectionDriver.RouteCheck>("answered"),
205 );
206 if (route.target === secondLate)
207 return Effect.sleep("550 millis").pipe(
208 Effect.as<ConnectionDriver.RouteCheck>("answered"),
209 );
210 return Effect.sleep("2500 millis").pipe(
211 Effect.as<ConnectionDriver.RouteCheck>("silent"),
212 );
213 },
214 (route) => {
215 if (route.target === relay) {
216 attempted.push("relay");
217 return Effect.sleep("300 millis").pipe(
218 Effect.andThen(
219 Effect.fail(
220 new ConnectionTransientError({
221 reason: "transport",
222 detail: "Relay unavailable.",
223 }),
224 ),
225 ),
226 );
227 }
228 if (route.target === firstLate) {
229 attempted.push("first-late");
230 return Effect.fail(
231 new ConnectionTransientError({
232 reason: "transport",
233 detail: "First route failed.",
234 }),
235 );
236 }
237 attempted.push("second-late");
238 return Effect.succeed(connection);
239 },
240 routeOrder,
241 ).pipe(Effect.scoped, Effect.forkChild);
242
243 yield* TestClock.adjust("800 millis");
244
245 const exit = fiber.pollUnsafe();
246 expect(exit && Exit.isSuccess(exit) ? exit.value.prepared : undefined).toBe(
247 connection.prepared,
248 );
249 expect(attempted).toEqual(expected);
250 }),
251 );
252
253 describe("publish-only relay", () => {
254 const environment = { environmentId: EnvironmentId.make("environment-1"), label: "Host" };
255 const relay = {
256 target: new RelayConnectionTarget(environment),
257 profile: Option.none(),
258 failure: new ConnectionBlockedError({
259 reason: "permission",
260 hop: "tunnel",
261 failureCause: "tunnel_not_enabled",
262 detail: "The host only publishes activity.",
263 }),
264 };
265 const unlinkedRelay = {
266 ...relay,
267 failure: new ConnectionBlockedError({
268 reason: "permission",
269 hop: "relay",
270 failureCause: "not_linked",
271 detail: "The host is not linked to T3 Connect.",
272 }),
273 };
274 const unreachable = {
275 target: new BearerConnectionTarget({ ...environment, connectionId: "unreachable" }),
276 profile: Option.none(),
277 failure: new ConnectionTransientError({
278 reason: "transport",
279 detail: "The host is restarting.",
280 }),
281 };
282 const refused = {
283 target: new BearerConnectionTarget({ ...environment, connectionId: "refused" }),
284 profile: Option.none(),
285 failure: new ConnectionBlockedError({
286 reason: "authentication",
287 hop: "server",
288 detail: "Session token revoked.",
289 }),
290 };
291
292 it.effect.each([
293 {
294 name: "keeps the refusal when relay is the only route",
295 primary: relay,
296 alternates: [],
297 expected: relay.failure,
298 },
299 {
300 name: "allows retries when a direct route cannot reach the host",
301 primary: unreachable,
302 alternates: [relay],
303 expected: unreachable.failure,
304 },
305 {
306 name: "allows retries when the relay refuses for another reason",
307 primary: unreachable,
308 alternates: [unlinkedRelay],
309 expected: unreachable.failure,
310 },
311 {
312 name: "keeps a direct route's host refusal when a second direct route is unreachable",
313 primary: refused,
314 alternates: [unreachable, relay],
315 expected: refused.failure,
316 },
317 ])("$name", ({ primary, alternates, expected }) =>
318 Effect.gen(function* () {
319 const routes = [primary, ...alternates];
320 const error = yield* ConnectionDriver.connectOverRoutes(
321 {
322 target: primary.target,
323 profile: primary.profile,
324 enabled: true,
325 alternateRoutes: alternates,
326 },
327 (route) =>
328 Effect.succeed<ConnectionDriver.RouteCheck>(
329 route.target === relay.target ? "unchecked" : "silent",
330 ),
331 (route) => Effect.fail(routes.find(({ target }) => target === route.target)!.failure),
332 ).pipe(Effect.scoped, Effect.flip);
333
334 expect(error).toBe(expected);
335 }),
336 );
337
338 it.effect("still tries a later silent direct route after the first one fails", () =>
339 Effect.gen(function* () {
340 const usable = new BearerConnectionTarget({ ...environment, connectionId: "usable" });
341 const connection = {
342 prepared: { target: usable } as PreparedConnection,
343 session: {} as RpcSession.RpcSession,
344 };
345 const lease = yield* ConnectionDriver.connectOverRoutes(
346 {
347 target: unreachable.target,
348 profile: Option.none(),
349 enabled: true,
350 alternateRoutes: [{ target: usable, profile: Option.none() }, relay],
351 },
352 (route) =>
353 Effect.succeed<ConnectionDriver.RouteCheck>(
354 route.target === relay.target ? "unchecked" : "silent",
355 ),
356 (route) =>
357 route.target === usable
358 ? Effect.succeed(connection)
359 : Effect.fail(route.target === relay.target ? relay.failure : unreachable.failure),
360 ).pipe(Effect.scoped);
361
362 expect(lease.prepared).toBe(connection.prepared);
363 }),
364 );
365 });
366});