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

ConnectReachability.test.ts

393 lines14.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, 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 = { pid: 1, readyConnections: 4, hostname: "env.example.test", protocol: "quic" };
29const notConnected = { pid: 1, readyConnections: 0, hostname: null, protocol: null };
30const facts = (overrides: Partial<ReachabilityFacts>): ReachabilityFacts => ({
31 managedTunnelConfigured: true,
32 connector: connected,
33 endpoint: null,
34 edgeReachable: null,
35 exitNode: null,
36 ...overrides,
37});
38​
39describe("classifyReachability", () => {
40 it.each([
41 [{ kind: "status", status: 502 }, "origin_unreachable"],
42 [{ kind: "status", status: 530 }, "no_connector"],
43 [{ kind: "status", status: 530, cloudflareError: "1033" }, "no_connector"],
44 [{ kind: "status", status: 530, cloudflareError: "1016" }, "unexpected_response"],
45 [{ kind: "network_error" }, "timeout"],
46 ] as const)("maps endpoint result %o to %s", (endpoint, cause) => {
47 expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject(
48 { status: "unreachable", cause },
49 );
50 });
51​
52 it("keeps the endpoint cause when the TCP edge test cannot explain it", () => {
53 // QUIC (UDP) can connect while TCP 7844 is blocked.
54 expect(
55 classifyReachability(
56 facts({ endpoint: { kind: "status", status: 502 }, edgeReachable: false }),
57 checkedAt,
58 ),
59 ).toMatchObject({ cause: "origin_unreachable" });
60 expect(
61 classifyReachability(
62 facts({
63 connector: {
64 pid: 1,
65 readyConnections: null,
66 hostname: "env.example.test",
67 protocol: null,
68 },
69 endpoint: { kind: "status", status: 502 },
70 edgeReachable: false,
71 }),
72 checkedAt,
73 ),
74 ).toMatchObject({ cause: "origin_unreachable" });
75 // Failed DNS also fails the edge lookups.
76 expect(
77 classifyReachability(
78 facts({
79 connector: {
80 pid: 1,
81 readyConnections: null,
82 hostname: "env.example.test",
83 protocol: null,
84 },
85 endpoint: { kind: "dns_failed" },
86 edgeReachable: false,
87 }),
88 checkedAt,
89 ),
90 ).toMatchObject({ cause: "dns_failed" });
91 });
92​
93 it("waits on a connector that has not connected while the edge answers", () => {
94 expect(
95 classifyReachability(facts({ connector: notConnected, edgeReachable: true }), checkedAt),
96 ).toMatchObject({ cause: "connector_not_ready" });
97 });
98});
99​
100interface ServedResponse {
101 readonly status: number;
102 readonly body: string | ReadableStream<Uint8Array> | { readonly cloudflareError: number };
104​
105// What Cloudflare serves for its 530 page: HTML unless the client accepts JSON.
106const cloudflareErrorPage = (request: HttpClientRequest.HttpClientRequest, code: number) =>
107 request.headers.accept === "application/json"
108 ? JSON.stringify({ status: 530, error_code: code, error_name: "tunnel_error" })
109 : `<!doctype html><h1><span>Error</span> <span>${code}</span></h1>`;
110​
111const reachabilityLayer = (
112 respond: Effect.Effect<ServedResponse>,
113 restartConnector: (pid: number, stillDead: Effect.Effect<boolean>) => Effect.Effect<boolean>,
114) =>
115 ConnectReachability.layer.pipe(
116 Layer.provide(
117 Layer.mergeAll(
118 Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
119 inspectConnector: Effect.succeed(connected),
120 readinessChanged: Stream.never,
121 restartConnector,
122 }),
123 Layer.mock(ServerSecretStore.ServerSecretStore)({
124 get: () => Effect.succeedSome(new Uint8Array()),
125 }),
126 Layer.succeed(
127 HttpClient.HttpClient,
128 HttpClient.make((request) =>
129 respond.pipe(
130 Effect.map(({ status, body }) =>
131 HttpClientResponse.fromWeb(
132 request,
133 new Response(
134 typeof body === "object" && "cloudflareError" in body
135 ? cloudflareErrorPage(request, body.cloudflareError)
136 : body,
137 { status },
138 ),
139 ),
140 ),
141 ),
142 ),
143 ),
144 Layer.succeed(
145 ChildProcessSpawner.ChildProcessSpawner,
146 ChildProcessSpawner.make(() => Effect.die("no tailscale")),
147 ),
148 ),
149 ),
150 );
151​
152const mockEdgeConnect = () =>
153 vi.spyOn(NodeNet, "connect").mockImplementation(() => {
154 const socket = new NodeNet.Socket();
155 queueMicrotask(() => socket.emit("connect"));
156 return socket;
157 });
158​
159describe("ConnectReachability stale connector recovery", () => {
160 it.effect("restarts cloudflared when Cloudflare has no connector but it reports ready", () =>
161 Effect.gen(function* () {
162 using _connect = mockEdgeConnect();
163 const restarts = yield* Queue.unbounded<number>();
164 // Cloudflare answers 530 while cloudflared still reports four ready connections.
165 let status = 530;
166 let body = { cloudflareError: 1033 };
167 const layer = reachabilityLayer(
168 Effect.sync(() => ({ status, body })),
169 (pid, stillDead) =>
170 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
171 );
172 // The scheduled checks run in the layer's scope, so the assertions run inside it.
173 yield* Effect.gen(function* () {
174 const reachability = yield* ConnectReachability.ConnectReachability;
175​
176 // The first sighting schedules its own confirming check two minutes later.
177 expect(yield* reachability.check).toMatchObject({ cause: "no_connector" });
178 yield* TestClock.adjust(Duration.minutes(1));
179 expect(yield* Queue.size(restarts)).toBe(0);
180 yield* TestClock.adjust(Duration.minutes(1));
181 expect(yield* Queue.take(restarts)).toBe(connected.pid);
182​
183 // A restart that did not help doubles the wait.
184 yield* reachability.check;
185 yield* TestClock.adjust(Duration.minutes(2));
186 expect(yield* Queue.size(restarts)).toBe(0);
187 yield* TestClock.adjust(Duration.minutes(2));
188 expect(yield* Queue.take(restarts)).toBe(connected.pid);
189​
190 // Reaching the endpoint resets the wait, and a 530 for a broken DNS record is left alone.
191 status = 200;
192 expect(yield* reachability.check).toMatchObject({ status: "reachable" });
193 status = 530;
194 body = { cloudflareError: 1016 };
195 expect(yield* reachability.check).toMatchObject({ cause: "unexpected_response" });
196 yield* TestClock.adjust(Duration.minutes(2));
197 expect(yield* Queue.size(restarts)).toBe(0);
198​
199 body = { cloudflareError: 1033 };
200 yield* reachability.check;
201 yield* TestClock.adjust(Duration.minutes(2));
202 expect(yield* Queue.take(restarts)).toBe(connected.pid);
203 }).pipe(Effect.provide(layer));
204 }),
205 );
206​
207 it.effect("starts a new streak after a healthy check that a newer check overtook", () =>
208 Effect.gen(function* () {
209 using _connect = mockEdgeConnect();
210 const restartTimes = yield* Queue.unbounded<number>();
211 const healthyRequested = yield* Deferred.make<void>();
212 const healthyAnswer = yield* Deferred.make<void>();
213 let status = 530;
214 const layer = reachabilityLayer(
215 Effect.gen(function* () {
216 const served = status;
217 if (served === 200) {
218 yield* Deferred.succeed(healthyRequested, undefined);
219 yield* Deferred.await(healthyAnswer);
220 }
221 return { status: served, body: { cloudflareError: 1033 } };
222 }),
223 (_pid, stillDead) =>
224 stillDead.pipe(
225 Effect.tap((dead) =>
226 dead
227 ? Clock.currentTimeMillis.pipe(
228 Effect.flatMap((now) => Queue.offer(restartTimes, now)),
229 )
230 : Effect.void,
231 ),
232 ),
233 );
234 yield* Effect.gen(function* () {
235 const reachability = yield* ConnectReachability.ConnectReachability;
236 const startedAt = yield* Clock.currentTimeMillis;
237 yield* reachability.check;
238 yield* TestClock.adjust(Duration.minutes(1));
239​
240 // The healthy answer arrives after a newer check already reported the tunnel dead.
241 status = 200;
242 const healthy = yield* Effect.forkChild(reachability.check);
243 yield* Deferred.await(healthyRequested);
244 status = 530;
245 yield* reachability.check;
246 yield* Deferred.succeed(healthyAnswer, undefined);
247 expect(yield* Fiber.join(healthy)).toMatchObject({ status: "reachable" });
248​
249 // The grace period starts again at the next dead check, a minute after the first one.
250 yield* reachability.check;
251 yield* TestClock.adjust(Duration.minutes(2));
252 expect((yield* Queue.take(restartTimes)) - startedAt).toBe(
253 Duration.toMillis(Duration.minutes(3)),
254 );
255 }).pipe(Effect.provide(layer));
256 }),
257 );
258​
259 it.effect("rejects a restart when an overtaken healthy check finishes while it waits", () =>
260 Effect.gen(function* () {
261 using _connect = mockEdgeConnect();
262 const healthyRequested = yield* Deferred.make<void>();
263 const healthyAnswer = yield* Deferred.make<void>();
264 const restartRequested = yield* Deferred.make<void>();
265 const releaseRestart = yield* Deferred.make<void>();
266 const guardChecks = yield* Queue.unbounded<boolean>();
267 let status = 530;
268 const layer = reachabilityLayer(
269 Effect.gen(function* () {
270 const served = status;
271 if (served === 200) {
272 yield* Deferred.succeed(healthyRequested, undefined);
273 yield* Deferred.await(healthyAnswer);
274 }
275 return { status: served, body: { cloudflareError: 1033 } };
276 }),
277 (_pid, stillDead) =>
278 Effect.gen(function* () {
279 yield* Deferred.succeed(restartRequested, undefined);
280 yield* Deferred.await(releaseRestart);
281 const accepted = yield* stillDead;
282 yield* Queue.offer(guardChecks, accepted);
283 return accepted;
284 }),
285 );
286 yield* Effect.gen(function* () {
287 const reachability = yield* ConnectReachability.ConnectReachability;
288 yield* reachability.check;
289 yield* TestClock.adjust(Duration.seconds(119));
290​
291 status = 200;
292 const healthy = yield* Effect.forkChild(reachability.check);
293 yield* Deferred.await(healthyRequested);
294 status = 530;
295 yield* TestClock.adjust(Duration.seconds(1));
296 yield* Deferred.await(restartRequested);
297​
298 yield* Deferred.succeed(healthyAnswer, undefined);
299 expect(yield* Fiber.join(healthy)).toMatchObject({ status: "reachable" });
300 yield* Deferred.succeed(releaseRestart, undefined);
301 expect(yield* Queue.take(guardChecks)).toBe(false);
302​
303 yield* reachability.check;
304 yield* TestClock.adjust(Duration.minutes(1));
305 expect(yield* Queue.size(guardChecks)).toBe(0);
306 yield* TestClock.adjust(Duration.minutes(1));
307 expect(yield* Queue.take(guardChecks)).toBe(true);
308 }).pipe(Effect.provide(layer));
309 }),
310 );
311​
312 it.effect("drops the confirming check of a streak that already ended", () =>
313 Effect.gen(function* () {
314 using _connect = mockEdgeConnect();
315 const restarts = yield* Queue.unbounded<number>();
316 let status = 530;
317 let requests = 0;
318 const layer = reachabilityLayer(
319 Effect.sync(() => {
320 requests += 1;
321 return { status, body: { cloudflareError: 1033 } };
322 }),
323 (pid, stillDead) =>
324 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
325 );
326 yield* Effect.gen(function* () {
327 const reachability = yield* ConnectReachability.ConnectReachability;
328 yield* reachability.check;
329 yield* TestClock.adjust(Duration.minutes(1));
330 status = 200;
331 yield* reachability.check;
332 status = 530;
333 yield* reachability.check;
334​
335 const before = requests;
336 yield* TestClock.adjust(Duration.minutes(1));
337 expect(requests).toBe(before);
338 yield* TestClock.adjust(Duration.minutes(1));
339 expect(yield* Queue.take(restarts)).toBe(connected.pid);
340 }).pipe(Effect.provide(layer));
341 }),
342 );
343​
344 it.effect("keeps a 530 whose error body never finishes", () =>
345 Effect.gen(function* () {
346 using _connect = mockEdgeConnect();
347 let markBodyRead = () => {};
348 const bodyRead = new Promise<void>((resolve) => {
349 markBodyRead = resolve;
350 });
351 const layer = reachabilityLayer(
352 Effect.sync(() => ({
353 status: 530,
354 body: new ReadableStream({
355 pull: () => {
356 markBodyRead();
357 return new Promise<void>(() => {});
358 },
359 }),
360 })),
361 () => Effect.succeed(false),
362 );
363 yield* Effect.gen(function* () {
364 const reachability = yield* ConnectReachability.ConnectReachability;
365 const check = yield* Effect.forkChild(reachability.check);
366 yield* Effect.promise(() => bodyRead);
367 yield* TestClock.adjust(Duration.seconds(2));
368 expect(yield* Fiber.join(check)).toMatchObject({ cause: "no_connector" });
369 }).pipe(Effect.provide(layer));
370 }),
371 );
372});
373​
374describe("T3 Connect troubleshooting links", () => {
375 it("each section names a heading in the user guide", () => {
376 const guide = NodeFS.readFileSync(
377 new URL("../../../../docs/user/t3-connect-troubleshooting.md", import.meta.url),
378 "utf8",
379 );
380 // GitHub's heading anchors: lowercase, drop punctuation, spaces become hyphens.
381 const anchors = new Set(
382 [...guide.matchAll(/^#{2,3} (.+)$/gm)].map(([, heading]) =>
383 heading!
384 .toLowerCase()
385 .replace(/[^\p{L}\p{N} _-]/gu, "")
386 .replace(/ /g, "-"),
387 ),
388 );
389 for (const section of T3_CONNECT_TROUBLESHOOTING_SECTIONS) {
390 expect(anchors, section).toContain(section);
391 }
392 });
393});