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

ConnectReachability.test.ts

351 lines13.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - reads the user guide to check its anchors.
2import * as NodeNet from "node:net";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { SpawnExecutableResolution, type SpawnExecutableResolver } from "@t3tools/shared/shell";
5import { describe, expect, it } from "@effect/vitest";
6import * as Clock from "effect/Clock";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Queue from "effect/Queue";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14import {
15 FetchHttpClient,
16 HttpClient,
17 HttpClientError,
18 HttpClientRequest,
19 HttpClientResponse,
20} from "effect/http";
21import { ChildProcessSpawner } from "effect/process";
22import { vi } from "vite-plus/test";
23​
24import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
25import * as ConnectReachability from "./ConnectReachability.ts";
26import { classifyReachability, type ReachabilityFacts } from "./ConnectReachability.ts";
27import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
28​
29vi.mock("node:net", { spy: true });
30​
31const checkedAt = "2026-10-19T00:00:00.000Z";
32const connected = {
33 pid: 1,
34 readyConnections: 4,
35 hostname: "env.example.test",
36 origin: null,
37 protocol: "quic",
38};
39const notConnected = { pid: 1, readyConnections: 0, hostname: null, origin: null, protocol: null };
40const facts = (overrides: Partial<ReachabilityFacts>): ReachabilityFacts => ({
41 managedTunnelConfigured: true,
42 connector: connected,
43 endpoint: null,
44 edgeReachable: null,
45 exitNode: null,
46 ...overrides,
47});
48​
49describe("classifyReachability", () => {
50 it.each([
51 [{ kind: "status", status: 502 }, "origin_unreachable"],
52 [{ kind: "network_error" }, "timeout"],
53 ] as const)("maps endpoint result %o to %s", (endpoint, cause) => {
54 expect(classifyReachability(facts({ endpoint, edgeReachable: true }), checkedAt)).toMatchObject(
55 { status: "unreachable", cause },
56 );
57 });
58});
59​
60interface ServedResponse {
61 readonly status: number;
62 readonly body: string | ReadableStream<Uint8Array> | { readonly cloudflareError: number };
64​
65// What Cloudflare serves for its 530 page: HTML unless the client accepts JSON.
66const cloudflareErrorPage = (request: HttpClientRequest.HttpClientRequest, code: number) =>
67 request.headers.accept === "application/json"
68 ? JSON.stringify({ status: 530, error_code: code, error_name: "tunnel_error" })
69 : `<!doctype html><h1><span>Error</span> <span>${code}</span></h1>`;
70​
71type Served = Effect.Effect<ServedResponse, HttpClientError.HttpClientError>;
72​
73const reachabilityLayer = (
74 respond: Served | ((request: HttpClientRequest.HttpClientRequest) => Served),
75 restartConnector: (pid: number, stillDead: Effect.Effect<boolean>) => Effect.Effect<boolean>,
76 options: {
77 readonly connector?: ManagedEndpointRuntime.ConnectorFacts;
78 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
79 readonly resolveExecutable?: SpawnExecutableResolver;
80 readonly httpClient?: Layer.Layer<HttpClient.HttpClient>;
81 } = {},
82) =>
83 ConnectReachability.layer.pipe(
84 Layer.provide(
85 Layer.mergeAll(
86 Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
87 inspectConnector: Effect.succeed(options.connector ?? connected),
88 readinessChanged: Stream.never,
89 restartConnector,
90 }),
91 Layer.mock(ServerSecretStore.ServerSecretStore)({
92 get: () => Effect.succeedSome(new Uint8Array()),
93 }),
94 options.httpClient ??
95 Layer.succeed(
96 HttpClient.HttpClient,
97 HttpClient.make((request) =>
98 (Effect.isEffect(respond) ? respond : respond(request)).pipe(
99 Effect.map(({ status, body }) =>
100 HttpClientResponse.fromWeb(
101 request,
102 new Response(
103 typeof body === "object" && "cloudflareError" in body
104 ? cloudflareErrorPage(request, body.cloudflareError)
105 : body,
106 { status },
107 ),
108 ),
109 ),
110 ),
111 ),
112 ),
113 Layer.succeed(
114 ChildProcessSpawner.ChildProcessSpawner,
115 options.spawner ?? ChildProcessSpawner.make(() => Effect.die("no tailscale")),
116 ),
117 Layer.succeed(SpawnExecutableResolution, options.resolveExecutable ?? (() => undefined)),
118 Layer.succeed(HostProcess.Platform, "linux"),
119 ),
120 ),
121 );
122​
123const mockEdgeConnect = () =>
124 vi.spyOn(NodeNet, "connect").mockImplementation(() => {
125 const socket = new NodeNet.Socket();
126 queueMicrotask(() => socket.emit("connect"));
127 return socket;
128 });
129​
130describe("ConnectReachability stale connector recovery", () => {
131 it.effect("restarts cloudflared when Cloudflare has no connector but it reports ready", () =>
132 Effect.gen(function* () {
133 using _connect = mockEdgeConnect();
134 const restarts = yield* Queue.unbounded<number>();
135 // Cloudflare answers 530 while cloudflared still reports four ready connections.
136 let status = 530;
137 let body = { cloudflareError: 1033 };
138 const layer = reachabilityLayer(
139 Effect.sync(() => ({ status, body })),
140 (pid, stillDead) =>
141 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
142 );
143 // The scheduled checks run in the layer's scope, so the assertions run inside it.
144 yield* Effect.gen(function* () {
145 const reachability = yield* ConnectReachability.ConnectReachability;
146​
147 // The first sighting schedules its own confirming check two minutes later.
148 expect(yield* reachability.check).toMatchObject({ cause: "no_connector" });
149 yield* TestClock.adjust(Duration.minutes(1));
150 expect(yield* Queue.size(restarts)).toBe(0);
151 yield* TestClock.adjust(Duration.minutes(1));
152 expect(yield* Queue.take(restarts)).toBe(connected.pid);
153​
154 // A restart that did not help doubles the wait.
155 yield* reachability.check;
156 yield* TestClock.adjust(Duration.minutes(2));
157 expect(yield* Queue.size(restarts)).toBe(0);
158 yield* TestClock.adjust(Duration.minutes(2));
159 expect(yield* Queue.take(restarts)).toBe(connected.pid);
160​
161 // Reaching the endpoint resets the wait, and a 530 for a broken DNS record is left alone.
162 status = 200;
163 expect(yield* reachability.check).toMatchObject({ status: "reachable" });
164 status = 530;
165 body = { cloudflareError: 1016 };
166 expect(yield* reachability.check).toMatchObject({ cause: "dns_failed" });
167 yield* TestClock.adjust(Duration.minutes(2));
168 expect(yield* Queue.size(restarts)).toBe(0);
169​
170 body = { cloudflareError: 1033 };
171 yield* reachability.check;
172 yield* TestClock.adjust(Duration.minutes(2));
173 expect(yield* Queue.take(restarts)).toBe(connected.pid);
174 }).pipe(Effect.provide(layer));
175 }),
176 );
177​
178 it.effect("restarts a stale cloudflared soon after the host wakes from sleep", () =>
179 Effect.gen(function* () {
180 const restarts = yield* Queue.unbounded<number>();
181 const testClock = yield* TestClock.testClockWith(Effect.succeed);
182 // A suspend moves the wall clock without running timers.
183 let sleptMillis = 0;
184 const wallMillis = () => testClock.currentTimeMillisUnsafe() + sleptMillis;
185 const layer = reachabilityLayer(
186 Effect.succeed({ status: 530, body: { cloudflareError: 1033 } }),
187 (pid, stillDead) =>
188 stillDead.pipe(Effect.tap((dead) => (dead ? Queue.offer(restarts, pid) : Effect.void))),
189 ).pipe(
190 Layer.provide(
191 Layer.succeed(Clock.Clock, {
192 ...testClock,
193 currentTimeMillisUnsafe: wallMillis,
194 currentTimeMillis: Effect.sync(wallMillis),
195 }),
196 ),
197 );
198 yield* Effect.gen(function* () {
199 yield* ConnectReachability.ConnectReachability;
200 yield* TestClock.adjust(Duration.seconds(5));
201 sleptMillis = Duration.toMillis(Duration.minutes(5));
202 yield* TestClock.adjust(Duration.seconds(10));
203 // The network gets a moment to come back before the check.
204 expect(yield* Queue.size(restarts)).toBe(0);
205 yield* TestClock.adjust(Duration.seconds(10));
206 expect(yield* Queue.take(restarts)).toBe(connected.pid);
207 }).pipe(Effect.provide(layer));
208 }),
209 );
210});
211​
212// undici wraps getaddrinfo's error in `TypeError: fetch failed`. glibc behind
213// systemd-resolved can report an NXDOMAIN as EBUSY rather than ENOTFOUND.
214const lookupFailed = (code: string) =>
215 Effect.fail(
216 new HttpClientError.HttpClientError({
217 reason: new HttpClientError.TransportError({
218 request: HttpClientRequest.get("https://env.example.test"),
219 cause: new TypeError("fetch failed", {
220 cause: Object.assign(new Error(`getaddrinfo ${code} env.example.test`), {
221 code,
222 syscall: "getaddrinfo",
223 hostname: "env.example.test",
224 }),
225 }),
226 }),
227 }),
228 );
229​
230describe("ConnectReachability DNS failures", () => {
231 // A local "not found" cached before the relay published the record looks like a missing
232 // record. Public DNS tells them apart.
233 it.effect("says whether the name exists in public DNS", () =>
234 Effect.gen(function* () {
235 using _connect = mockEdgeConnect();
236 for (const [lookupCode, dnsStatus, reason] of [
237 ["ENOTFOUND", 0, "old cached answer"],
238 ["ENOTFOUND", 3, "missing from public DNS"],
239 // The local resolver did not answer, so nothing it cached is to blame.
240 ["EAI_AGAIN", 0, "does not resolve from this machine"],
241 ] as const) {
242 const layer = reachabilityLayer(
243 (request) =>
244 request.url.startsWith("https://1.1.1.1/dns-query")
245 ? Effect.succeed({ status: 200, body: JSON.stringify({ Status: dnsStatus }) })
246 : lookupFailed(lookupCode),
247 () => Effect.succeed(false),
248 );
249 const result = yield* ConnectReachability.ConnectReachability.use(
250 (reachability) => reachability.check,
251 ).pipe(Effect.provide(layer));
252 expect(result).toMatchObject({
253 cause: "dns_failed",
254 reason: expect.stringContaining(reason),
255 });
256 }
257 }),
258 );
259});
260​
261describe("ConnectReachability endpoint probe", () => {
262 it.effect("reports a redirect as the endpoint's answer without following it", () =>
263 Effect.gen(function* () {
264 using _connect = mockEdgeConnect();
265 const redirectModes: Array<RequestInit["redirect"]> = [];
266 // Following the redirect would reach a host that answers 200.
267 const fetch: typeof globalThis.fetch = async (_url, init) => {
268 redirectModes.push(init?.redirect);
269 return init?.redirect === "manual"
270 ? new Response(null, { status: 302, headers: { location: "https://elsewhere.test/" } })
271 : new Response("{}", { status: 200 });
272 };
273 const result = yield* ConnectReachability.ConnectReachability.use(
274 (reachability) => reachability.check,
275 ).pipe(
276 Effect.provide(
277 reachabilityLayer(Effect.die("unused"), () => Effect.succeed(false), {
278 httpClient: FetchHttpClient.layer,
279 }),
280 ),
281 Effect.provideService(FetchHttpClient.Fetch, fetch),
282 );
283 expect(redirectModes).toEqual(["manual"]);
284 expect(result.status).not.toBe("reachable");
285 }),
286 );
287});
288​
289describe("ConnectReachability tailscale and edge probes", () => {
290 const exitNodeStatusJson = JSON.stringify({
291 ExitNodeStatus: { Online: true },
292 Peer: { peer1: { ExitNode: true, DNSName: "exit-box.tail.ts.net." } },
293 });
294 const exitNodeHint =
295 'Tailscale exit node "exit-box" is on. Traffic to Cloudflare goes through it.';
296 const tailscaleOnPath: SpawnExecutableResolver = (command) =>
297 command === "tailscale" ? "/usr/bin/tailscale" : undefined;
298​
299 const countingSpawner = () => {
300 const counter = { spawns: 0 };
301 const spawner = ChildProcessSpawner.make(() => {
302 counter.spawns += 1;
303 return Effect.succeed(
304 ChildProcessSpawner.makeHandle({
305 pid: ChildProcessSpawner.ProcessId(1),
306 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
307 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
308 isRunning: Effect.succeed(false),
309 kill: () => Effect.void,
310 unref: Effect.succeed(Effect.void),
311 stdin: Sink.drain,
312 stdout: Stream.make(new TextEncoder().encode(exitNodeStatusJson)),
313 stderr: Stream.empty,
314 all: Stream.empty,
315 getInputFd: () => Sink.drain,
316 getOutputFd: () => Stream.empty,
317 }),
318 );
319 });
320 return { counter, spawner };
321 };
322​
323 const mockEdgeTimeout = () =>
324 vi.spyOn(NodeNet, "connect").mockImplementation(() => {
325 const socket = new NodeNet.Socket();
326 queueMicrotask(() => socket.emit("error", new Error("ETIMEDOUT")));
327 return socket;
328 });
329​
330 const runCheck = (layer: ReturnType<typeof reachabilityLayer>) =>
331 ConnectReachability.ConnectReachability.use((reachability) => reachability.check).pipe(
332 Effect.provide(layer),
333 );
334 const noRestart = () => Effect.succeed(false);
335​
336 it.effect("names the exit node when the edge is unreachable", () =>
337 Effect.gen(function* () {
338 using _connect = mockEdgeTimeout();
339 const { counter, spawner } = countingSpawner();
340 const result = yield* runCheck(
341 reachabilityLayer(Effect.succeed({ status: 200, body: "" }), noRestart, {
342 connector: notConnected,
343 spawner,
344 resolveExecutable: tailscaleOnPath,
345 }),
346 );
347 expect(result).toMatchObject({ cause: "edge_unreachable", hint: exitNodeHint });
348 expect(counter.spawns).toBe(1);
349 }),
350 );
351});