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

ConnectReachability.test.ts

470 lines17.9 KB

1// @effect-diagnostics nodeBuiltinImport:off - reads the user guide to check its anchors.
2import * as NodeFS from "node:fs";
3import * as NodeNet from "node:net";
4​
5import { T3_CONNECT_TROUBLESHOOTING_SECTIONS } from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Clock from "effect/Clock";
8import * as Deferred from "effect/Deferred";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Queue from "effect/Queue";
14import * as Stream from "effect/Stream";
15import * as TestClock from "effect/testing/TestClock";
16import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
17import { ChildProcessSpawner } from "effect/process";
18import { vi } from "vite-plus/test";
19​
20import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
21import * as ConnectReachability from "./ConnectReachability.ts";
22import { classifyReachability, type ReachabilityFacts } from "./ConnectReachability.ts";
23import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
24​
25vi.mock("node:net", { spy: true });
26​
27const checkedAt = "2026-10-19T00:00:00.000Z";
28const connected = {
29 pid: 1,
30 readyConnections: 4,
31 hostname: "env.example.test",
32 origin: null,
33 protocol: "quic",
34};
35const notConnected = { pid: 1, readyConnections: 0, hostname: null, origin: null, protocol: null };
36const facts = (overrides: Partial<ReachabilityFacts>): ReachabilityFacts => ({
37 managedTunnelConfigured: true,
38 connector: connected,
39 endpoint: null,
40 edgeReachable: null,
41 exitNode: null,
42 ...overrides,
43});
44​
45describe("classifyReachability", () => {
46 it.each([
47 [{ kind: "status", status: 502 }, "origin_unreachable"],
48 [{ kind: "status", status: 530 }, "no_connector"],
49 [{ kind: "status", status: 530, cloudflareError: "1033" }, "no_connector"],
50 [{ kind: "status", status: 530, cloudflareError: "1016" }, "unexpected_response"],
51 [{ kind: "network_error" }, "timeout"],
52 ] as const)("maps endpoint result %o to %s", (endpoint, cause) => {
53 expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject(
54 { status: "unreachable", cause },
55 );
56 });
57​
58 it("keeps the endpoint cause when the TCP edge test cannot explain it", () => {
59 // QUIC (UDP) can connect while TCP 7844 is blocked.
60 expect(
61 classifyReachability(
62 facts({ endpoint: { kind: "status", status: 502 }, edgeReachable: false }),
63 checkedAt,
64 ),
65 ).toMatchObject({ cause: "origin_unreachable" });
66 expect(
67 classifyReachability(
68 facts({
69 connector: {
70 pid: 1,
71 readyConnections: null,
72 hostname: "env.example.test",
73 origin: null,
74 protocol: null,
75 },
76 endpoint: { kind: "status", status: 502 },
77 edgeReachable: false,
78 }),
79 checkedAt,
80 ),
81 ).toMatchObject({ cause: "origin_unreachable" });
82 // Failed DNS also fails the edge lookups.
83 expect(
84 classifyReachability(
85 facts({
86 connector: {
87 pid: 1,
88 readyConnections: null,
89 hostname: "env.example.test",
90 origin: null,
91 protocol: null,
92 },
93 endpoint: { kind: "dns_failed" },
94 edgeReachable: false,
95 }),
96 checkedAt,
97 ),
98 ).toMatchObject({ cause: "dns_failed" });
99 });
100​
101 it("waits on a connector that has not connected while the edge answers", () => {
102 expect(
103 classifyReachability(facts({ connector: notConnected, edgeReachable: true }), checkedAt),
104 ).toMatchObject({ cause: "connector_not_ready" });
105 });
106​
107 it("does not point an unlinked server at a background service it may not have", () => {
108 // Desktop and `t3 serve` run the server without a background service.
109 const result = classifyReachability(facts({ managedTunnelConfigured: false }), checkedAt);
110 expect(result).toMatchObject({ cause: "not_linked" });
111 expect(result.status === "unreachable" && result.fix).not.toContain("t3 service");
112 });
113});
114​
115interface ServedResponse {
116 readonly status: number;
117 readonly body: string | ReadableStream<Uint8Array> | { readonly cloudflareError: number };
119​
120// What Cloudflare serves for its 530 page: HTML unless the client accepts JSON.
121const cloudflareErrorPage = (request: HttpClientRequest.HttpClientRequest, code: number) =>
122 request.headers.accept === "application/json"
123 ? JSON.stringify({ status: 530, error_code: code, error_name: "tunnel_error" })
124 : `<!doctype html><h1><span>Error</span> <span>${code}</span></h1>`;
125​
126type Served = Effect.Effect<ServedResponse, HttpClientError.HttpClientError>;
127​
128const reachabilityLayer = (
129 respond: Served | ((request: HttpClientRequest.HttpClientRequest) => Served),
130 restartConnector: (pid: number, stillDead: Effect.Effect<boolean>) => Effect.Effect<boolean>,
131) =>
132 ConnectReachability.layer.pipe(
133 Layer.provide(
134 Layer.mergeAll(
135 Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
136 inspectConnector: Effect.succeed(connected),
137 readinessChanged: Stream.never,
138 restartConnector,
139 }),
140 Layer.mock(ServerSecretStore.ServerSecretStore)({
141 get: () => Effect.succeedSome(new Uint8Array()),
142 }),
143 Layer.succeed(
144 HttpClient.HttpClient,
145 HttpClient.make((request) =>
146 (Effect.isEffect(respond) ? respond : respond(request)).pipe(
147 Effect.map(({ status, body }) =>
148 HttpClientResponse.fromWeb(
149 request,
150 new Response(
151 typeof body === "object" && "cloudflareError" in body
152 ? cloudflareErrorPage(request, body.cloudflareError)
153 : body,
154 { status },
155 ),
156 ),
157 ),
158 ),
159 ),
160 ),
161 Layer.succeed(
162 ChildProcessSpawner.ChildProcessSpawner,
163 ChildProcessSpawner.make(() => Effect.die("no tailscale")),
164 ),
165 ),
166 ),
167 );
168​
169const mockEdgeConnect = () =>
170 vi.spyOn(NodeNet, "connect").mockImplementation(() => {
171 const socket = new NodeNet.Socket();
172 queueMicrotask(() => socket.emit("connect"));
173 return socket;
174 });
175​
176describe("ConnectReachability stale connector recovery", () => {
177 it.effect("restarts cloudflared when Cloudflare has no connector but it reports ready", () =>
178 Effect.gen(function* () {
179 using _connect = mockEdgeConnect();
180 const restarts = yield* Queue.unbounded<number>();
181 // Cloudflare answers 530 while cloudflared still reports four ready connections.
182 let status = 530;
183 let body = { cloudflareError: 1033 };
184 const layer = reachabilityLayer(
185 Effect.sync(() => ({ status, body })),
186 (pid, stillDead) =>
187 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
188 );
189 // The scheduled checks run in the layer's scope, so the assertions run inside it.
190 yield* Effect.gen(function* () {
191 const reachability = yield* ConnectReachability.ConnectReachability;
192​
193 // The first sighting schedules its own confirming check two minutes later.
194 expect(yield* reachability.check).toMatchObject({ cause: "no_connector" });
195 yield* TestClock.adjust(Duration.minutes(1));
196 expect(yield* Queue.size(restarts)).toBe(0);
197 yield* TestClock.adjust(Duration.minutes(1));
198 expect(yield* Queue.take(restarts)).toBe(connected.pid);
199​
200 // A restart that did not help doubles the wait.
201 yield* reachability.check;
202 yield* TestClock.adjust(Duration.minutes(2));
203 expect(yield* Queue.size(restarts)).toBe(0);
204 yield* TestClock.adjust(Duration.minutes(2));
205 expect(yield* Queue.take(restarts)).toBe(connected.pid);
206​
207 // Reaching the endpoint resets the wait, and a 530 for a broken DNS record is left alone.
208 status = 200;
209 expect(yield* reachability.check).toMatchObject({ status: "reachable" });
210 status = 530;
211 body = { cloudflareError: 1016 };
212 expect(yield* reachability.check).toMatchObject({ cause: "unexpected_response" });
213 yield* TestClock.adjust(Duration.minutes(2));
214 expect(yield* Queue.size(restarts)).toBe(0);
215​
216 body = { cloudflareError: 1033 };
217 yield* reachability.check;
218 yield* TestClock.adjust(Duration.minutes(2));
219 expect(yield* Queue.take(restarts)).toBe(connected.pid);
220 }).pipe(Effect.provide(layer));
221 }),
222 );
223​
224 it.effect("starts a new streak after a healthy check that a newer check overtook", () =>
225 Effect.gen(function* () {
226 using _connect = mockEdgeConnect();
227 const restartTimes = yield* Queue.unbounded<number>();
228 const healthyRequested = yield* Deferred.make<void>();
229 const healthyAnswer = yield* Deferred.make<void>();
230 let status = 530;
231 const layer = reachabilityLayer(
232 Effect.gen(function* () {
233 const served = status;
234 if (served === 200) {
235 yield* Deferred.succeed(healthyRequested, undefined);
236 yield* Deferred.await(healthyAnswer);
237 }
238 return { status: served, body: { cloudflareError: 1033 } };
239 }),
240 (_pid, stillDead) =>
241 stillDead.pipe(
242 Effect.tap((dead) =>
243 dead
244 ? Clock.currentTimeMillis.pipe(
245 Effect.flatMap((now) => Queue.offer(restartTimes, now)),
246 )
247 : Effect.void,
248 ),
249 ),
250 );
251 yield* Effect.gen(function* () {
252 const reachability = yield* ConnectReachability.ConnectReachability;
253 const startedAt = yield* Clock.currentTimeMillis;
254 yield* reachability.check;
255 yield* TestClock.adjust(Duration.minutes(1));
256​
257 // The healthy answer arrives after a newer check already reported the tunnel dead.
258 status = 200;
259 const healthy = yield* Effect.forkChild(reachability.check);
260 yield* Deferred.await(healthyRequested);
261 status = 530;
262 yield* reachability.check;
263 yield* Deferred.succeed(healthyAnswer, undefined);
264 expect(yield* Fiber.join(healthy)).toMatchObject({ status: "reachable" });
265​
266 // The grace period starts again at the next dead check, a minute after the first one.
267 yield* reachability.check;
268 yield* TestClock.adjust(Duration.minutes(2));
269 expect((yield* Queue.take(restartTimes)) - startedAt).toBe(
270 Duration.toMillis(Duration.minutes(3)),
271 );
272 }).pipe(Effect.provide(layer));
273 }),
274 );
275​
276 it.effect("rejects a restart when an overtaken healthy check finishes while it waits", () =>
277 Effect.gen(function* () {
278 using _connect = mockEdgeConnect();
279 const healthyRequested = yield* Deferred.make<void>();
280 const healthyAnswer = yield* Deferred.make<void>();
281 const restartRequested = yield* Deferred.make<void>();
282 const releaseRestart = yield* Deferred.make<void>();
283 const guardChecks = yield* Queue.unbounded<boolean>();
284 let status = 530;
285 const layer = reachabilityLayer(
286 Effect.gen(function* () {
287 const served = status;
288 if (served === 200) {
289 yield* Deferred.succeed(healthyRequested, undefined);
290 yield* Deferred.await(healthyAnswer);
291 }
292 return { status: served, body: { cloudflareError: 1033 } };
293 }),
294 (_pid, stillDead) =>
295 Effect.gen(function* () {
296 yield* Deferred.succeed(restartRequested, undefined);
297 yield* Deferred.await(releaseRestart);
298 const accepted = yield* stillDead;
299 yield* Queue.offer(guardChecks, accepted);
300 return accepted;
301 }),
302 );
303 yield* Effect.gen(function* () {
304 const reachability = yield* ConnectReachability.ConnectReachability;
305 yield* reachability.check;
306 yield* TestClock.adjust(Duration.seconds(119));
307​
308 status = 200;
309 const healthy = yield* Effect.forkChild(reachability.check);
310 yield* Deferred.await(healthyRequested);
311 status = 530;
312 yield* TestClock.adjust(Duration.seconds(1));
313 yield* Deferred.await(restartRequested);
314​
315 yield* Deferred.succeed(healthyAnswer, undefined);
316 expect(yield* Fiber.join(healthy)).toMatchObject({ status: "reachable" });
317 yield* Deferred.succeed(releaseRestart, undefined);
318 expect(yield* Queue.take(guardChecks)).toBe(false);
319​
320 yield* reachability.check;
321 yield* TestClock.adjust(Duration.minutes(1));
322 expect(yield* Queue.size(guardChecks)).toBe(0);
323 yield* TestClock.adjust(Duration.minutes(1));
324 expect(yield* Queue.take(guardChecks)).toBe(true);
325 }).pipe(Effect.provide(layer));
326 }),
327 );
328​
329 it.effect("drops the confirming check of a streak that already ended", () =>
330 Effect.gen(function* () {
331 using _connect = mockEdgeConnect();
332 const restarts = yield* Queue.unbounded<number>();
333 let status = 530;
334 let requests = 0;
335 const layer = reachabilityLayer(
336 Effect.sync(() => {
337 requests += 1;
338 return { status, body: { cloudflareError: 1033 } };
339 }),
340 (pid, stillDead) =>
341 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
342 );
343 yield* Effect.gen(function* () {
344 const reachability = yield* ConnectReachability.ConnectReachability;
345 yield* reachability.check;
346 yield* TestClock.adjust(Duration.minutes(1));
347 status = 200;
348 yield* reachability.check;
349 status = 530;
350 yield* reachability.check;
351​
352 const before = requests;
353 yield* TestClock.adjust(Duration.minutes(1));
354 expect(requests).toBe(before);
355 yield* TestClock.adjust(Duration.minutes(1));
356 expect(yield* Queue.take(restarts)).toBe(connected.pid);
357 }).pipe(Effect.provide(layer));
358 }),
359 );
360​
361 it.effect("keeps a 530 whose error body never finishes", () =>
362 Effect.gen(function* () {
363 using _connect = mockEdgeConnect();
364 let markBodyRead = () => {};
365 const bodyRead = new Promise<void>((resolve) => {
366 markBodyRead = resolve;
367 });
368 const layer = reachabilityLayer(
369 Effect.sync(() => ({
370 status: 530,
371 body: new ReadableStream({
372 pull: () => {
373 markBodyRead();
374 return new Promise<void>(() => {});
375 },
376 }),
377 })),
378 () => Effect.succeed(false),
379 );
380 yield* Effect.gen(function* () {
381 const reachability = yield* ConnectReachability.ConnectReachability;
382 const check = yield* Effect.forkChild(reachability.check);
383 yield* Effect.promise(() => bodyRead);
384 yield* TestClock.adjust(Duration.seconds(2));
385 expect(yield* Fiber.join(check)).toMatchObject({ cause: "no_connector" });
386 }).pipe(Effect.provide(layer));
387 }),
388 );
389});
390​
391describe("ConnectReachability DNS failures", () => {
392 // undici wraps getaddrinfo's error in `TypeError: fetch failed`. glibc behind
393 // systemd-resolved can report an NXDOMAIN as EBUSY rather than ENOTFOUND.
394 const lookupFailed = (code: string) =>
395 Effect.fail(
396 new HttpClientError.HttpClientError({
397 reason: new HttpClientError.TransportError({
398 request: HttpClientRequest.get("https://env.example.test"),
399 cause: new TypeError("fetch failed", {
400 cause: Object.assign(new Error(`getaddrinfo ${code} env.example.test`), {
401 code,
402 syscall: "getaddrinfo",
403 hostname: "env.example.test",
404 }),
405 }),
406 }),
407 }),
408 );
409​
410 it.effect("reports a getaddrinfo EBUSY as a DNS failure", () =>
411 Effect.gen(function* () {
412 using _connect = mockEdgeConnect();
413 const layer = reachabilityLayer(lookupFailed("EBUSY"), () => Effect.succeed(false));
414 const result = yield* ConnectReachability.ConnectReachability.use(
415 (reachability) => reachability.check,
416 ).pipe(Effect.provide(layer));
417 expect(result).toMatchObject({ status: "unreachable", cause: "dns_failed" });
418 }),
419 );
420​
421 // A local "not found" cached before the relay published the record looks like a missing
422 // record. Public DNS tells them apart.
423 it.effect("says whether the name exists in public DNS", () =>
424 Effect.gen(function* () {
425 using _connect = mockEdgeConnect();
426 for (const [lookupCode, dnsStatus, reason] of [
427 ["ENOTFOUND", 0, "old cached answer"],
428 ["ENOTFOUND", 3, "missing from public DNS"],
429 // The local resolver did not answer, so nothing it cached is to blame.
430 ["EAI_AGAIN", 0, "does not resolve from this machine"],
431 ] as const) {
432 const layer = reachabilityLayer(
433 (request) =>
434 request.url.startsWith("https://1.1.1.1/dns-query")
435 ? Effect.succeed({ status: 200, body: JSON.stringify({ Status: dnsStatus }) })
436 : lookupFailed(lookupCode),
437 () => Effect.succeed(false),
438 );
439 const result = yield* ConnectReachability.ConnectReachability.use(
440 (reachability) => reachability.check,
441 ).pipe(Effect.provide(layer));
442 expect(result).toMatchObject({
443 cause: "dns_failed",
444 reason: expect.stringContaining(reason),
445 });
446 }
447 }),
448 );
449});
450​
451describe("T3 Connect troubleshooting links", () => {
452 it("each section names a heading in the user guide", () => {
453 const guide = NodeFS.readFileSync(
454 new URL("../../../../docs/user/t3-connect-troubleshooting.md", import.meta.url),
455 "utf8",
456 );
457 // GitHub's heading anchors: lowercase, drop punctuation, spaces become hyphens.
458 const anchors = new Set(
459 [...guide.matchAll(/^#{2,3} (.+)$/gm)].map(([, heading]) =>
460 heading!
461 .toLowerCase()
462 .replace(/[^\p{L}\p{N} _-]/gu, "")
463 .replace(/ /g, "-"),
464 ),
465 );
466 for (const section of T3_CONNECT_TROUBLESHOOTING_SECTIONS) {
467 expect(anchors, section).toContain(section);
468 }
469 });
470});