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

PortScanner.test.ts

498 lines19.6 KB

1import { it as effectIt } from "@effect/vitest";
2import {
3 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
4 PREVIEW_URL_MAX_LENGTH,
5 type DiscoveredLocalServer,
6} from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as PlatformError from "effect/PlatformError";
15import * as Scope from "effect/Scope";
16import * as TestClock from "effect/testing/TestClock";
17import { expect } from "vite-plus/test";
18import { FetchHttpClient } from "effect/http";
19​
20import * as ProcessRunner from "../processRunner.ts";
21import * as PortScanner from "./PortScanner.ts";
22const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
23 Effect.fail(
24 new ProcessRunner.ProcessSpawnError({
25 command: input.command,
26 argumentCount: input.args.length,
27 cwd: input.cwd,
28 cause: PlatformError.systemError({
29 _tag: "NotFound",
30 module: "ChildProcess",
31 method: "spawn",
32 description: "PowerShell is not installed in the test environment",
33 }),
34 }),
35 );
36​
37const layerNoProc = FileSystem.layerNoop({});
38​
39const layerProbeFailure = (
40 run: ProcessRunner.ProcessRunner["Service"]["run"],
41 fetch: typeof globalThis.fetch = globalThis.fetch,
42 fileSystem: Layer.Layer<FileSystem.FileSystem> = layerNoProc,
43) =>
44 PortScanner.layer.pipe(
45 Layer.provide(
46 Layer.mergeAll(
47 fileSystem,
48 Layer.succeed(ProcessRunner.ProcessRunner, { run }),
49 Layer.succeed(HostProcess.Platform, "linux"),
50 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
51 ),
52 ),
53 );
54​
55const LSOF_TEST_PORT = 43_123;
56​
57const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) =>
58 Effect.tap(PortScanner.PortDiscovery, (scanner) =>
59 scanner.registerTerminalProcesses({
60 threadId: "scanner-thread",
61 terminalId: "scanner-terminal",
62 processIds,
63 }),
64 );
65​
66const layerLsofScanner = (input: {
67 readonly pid: () => number;
68 readonly fetch: typeof globalThis.fetch;
69 readonly stdout?: () => string;
70}) =>
71 PortScanner.layer.pipe(
72 Layer.provide(
73 Layer.mergeAll(
74 layerNoProc,
75 Layer.succeed(ProcessRunner.ProcessRunner, {
76 run: () =>
77 Effect.succeed({
78 stdout: input.stdout?.() ?? `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
79 stderr: "",
80 code: null,
81 timedOut: false,
82 stdoutTruncated: false,
83 stderrTruncated: false,
84 stdoutInvalidUtf8: false,
85 stderrInvalidUtf8: false,
86 }),
87 }),
88 Layer.succeed(HostProcess.Platform, "linux"),
89 FetchHttpClient.layer.pipe(
90 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
91 ),
92 ),
93 ),
94 );
95​
96effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
97 const requests: string[] = [];
98 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
99 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
100 const url = String(input);
101 requests.push(url);
102 return Promise.resolve(
103 url === configuredUrl
104 ? new Response("docs", { headers: { "content-type": "text/html" } })
105 : new Response("not found", {
106 status: 404,
107 headers: { "content-type": "text/html" },
108 }),
109 );
110 }) as typeof globalThis.fetch;
111 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
112​
113 return Effect.gen(function* () {
114 const scanner = yield* PortScanner.PortDiscovery;
115 const servers = yield* scanner.scan([configuredUrl]);
116 expect(servers).toHaveLength(1);
117 expect(servers[0]?.url).toBe(configuredUrl);
118 expect(requests).toContain(configuredUrl);
119 }).pipe(Effect.provide(layer));
120});
121​
122effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
123 const customPort = 43_124;
124 const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
125 const expectedUrl = `http://localhost:${customPort}/docs`;
126 const requests: string[] = [];
127 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
128 requests.push(String(input));
129 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
130 }) as typeof globalThis.fetch;
131 const layer = layerProbeFailure(processProbeFailure, fetchFn);
132​
133 return Effect.gen(function* () {
134 const scanner = yield* PortScanner.PortDiscovery;
135 const servers = yield* scanner.scan([configuredUrl]);
136 expect(servers).toHaveLength(1);
137 expect(servers[0]?.host).toBe("localhost");
138 expect(servers[0]?.port).toBe(customPort);
139 expect(servers[0]?.url).toBe(expectedUrl);
140 expect(requests).toEqual([expectedUrl]);
141 }).pipe(Effect.provide(layer));
142});
143​
144effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
145 const ipv4Url = "https://127.0.0.1:43125/docs";
146 const ipv6Url = "http://[::1]:43126/docs";
147 const wildcardPrefix = "http://0.0.0.0/";
148 const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
149 PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
150 )}`;
151 const requests: string[] = [];
152 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
153 requests.push(String(input));
154 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
155 }) as typeof globalThis.fetch;
156 const layer = layerProbeFailure(processProbeFailure, fetchFn);
157​
158 return Effect.gen(function* () {
159 const scanner = yield* PortScanner.PortDiscovery;
160 const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
161 expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
162 expect(requests).toEqual([ipv4Url, ipv6Url]);
163 }).pipe(Effect.provide(layer));
164});
165​
166effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
167 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
168 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
169 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
170 const url = String(input);
171 return Promise.resolve(
172 url === docsUrl || url === adminUrl
173 ? new Response("app", { headers: { "content-type": "text/html" } })
174 : new Response("not found", { status: 404 }),
175 );
176 }) as typeof globalThis.fetch;
177 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
178​
179 return Effect.gen(function* () {
180 const scanner = yield* PortScanner.PortDiscovery;
181 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
182 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
183 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
184 Effect.sync(() => docsSnapshots.push(servers)),
185 );
186 yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
187 Effect.sync(() => adminSnapshots.push(servers)),
188 );
189 yield* scanner.retain;
190​
191 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
192 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
193 }).pipe(Effect.scoped, Effect.provide(layer));
194});
195​
196effectIt.effect(
197 "keeps each subscriber's candidates when their combined union exceeds the per-client cap",
198 () => {
199 const firstSubscriberUrls = Array.from(
200 { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
201 (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
202 );
203 const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
204 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
205 Promise.resolve(
206 String(input) === secondSubscriberUrl
207 ? new Response("app", { headers: { "content-type": "text/html" } })
208 : new Response("not found", { status: 404 }),
209 )) as typeof globalThis.fetch;
210 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
211​
212 return Effect.gen(function* () {
213 const scanner = yield* PortScanner.PortDiscovery;
214 const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
215 yield* scanner.subscribe(
216 { configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
217 () => Effect.void,
218 );
219 yield* scanner.subscribe(
220 { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
221 (servers) => Effect.sync(() => secondSnapshots.push(servers)),
222 );
223 yield* scanner.retain;
224​
225 expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
226 }).pipe(Effect.scoped, Effect.provide(layer));
227 },
228);
229​
230effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
231 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
232 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
233 const requests: string[] = [];
234 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
235 const url = String(input);
236 requests.push(url);
237 return Promise.resolve(
238 url === docsUrl || url === adminUrl
239 ? new Response("app", { headers: { "content-type": "text/html" } })
240 : new Response("not found", { status: 404 }),
241 );
242 }) as typeof globalThis.fetch;
243 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
244​
245 return Effect.gen(function* () {
246 const scanner = yield* PortScanner.PortDiscovery;
247 const docsScope = yield* Scope.make();
248 yield* scanner
249 .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
250 .pipe(Effect.provideService(Scope.Scope, docsScope));
251 yield* scanner.subscribe(
252 { configuredUrls: [adminUrl], initialSnapshot: [] },
253 () => Effect.void,
254 );
255 yield* scanner.retain;
256 yield* Scope.close(docsScope, Exit.void);
257​
258 requests.length = 0;
259 yield* TestClock.adjust(Duration.seconds(15));
260 expect(requests).toContain(adminUrl);
261 expect(requests).not.toContain(docsUrl);
262 }).pipe(Effect.scoped, Effect.provide(layer));
263});
264​
265effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
266 const requests: string[] = [];
267 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
268 requests.push(String(input));
269 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
270 }) as typeof globalThis.fetch;
271 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
272 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
273 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
274​
275 return Effect.gen(function* () {
276 const scanner = yield* PortScanner.PortDiscovery;
277 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
278 const requestCount = requests.length;
279 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
280 expect(requests).toHaveLength(requestCount);
281 }).pipe(Effect.provide(layer));
282});
283​
284effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
285 const redirects: Array<string | undefined> = [];
286 const fetchFn = (async (
287 input: Parameters<typeof globalThis.fetch>[0],
288 init?: Parameters<typeof globalThis.fetch>[1],
289 ) => {
290 redirects.push(init?.redirect);
291 if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
292 return new Response(null, { status: 302, headers: { location: "https://example.com" } });
293 }) as typeof globalThis.fetch;
294 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
295​
296 return Effect.gen(function* () {
297 const scanner = yield* ownedScanner();
298 const servers = yield* scanner.scan();
299 expect(servers).toHaveLength(1);
300 expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
301 expect(redirects).toEqual(["manual", "manual"]);
302 }).pipe(Effect.provide(layer));
303});
304​
305effectIt.effect("probes a port only while T3 terminals own every listener on it", () => {
306 const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`;
307 const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`;
308 let stdout = unowned;
309 const requests: string[] = [];
310 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
311 requests.push(String(input));
312 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
313 }) as typeof globalThis.fetch;
314 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn, stdout: () => stdout });
315​
316 return Effect.gen(function* () {
317 const scanner = yield* ownedScanner();
318 expect(yield* scanner.scan()).toHaveLength(0);
319 stdout = `${owned}${unowned}`;
320 expect(yield* scanner.scan()).toHaveLength(0);
321 expect(requests).toEqual([]);
322​
323 stdout = owned;
324 expect(yield* scanner.scan()).toHaveLength(1);
325 expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
326​
327 yield* scanner.unregisterTerminal({
328 threadId: "scanner-thread",
329 terminalId: "scanner-terminal",
330 });
331 expect(yield* scanner.scan()).toHaveLength(0);
332 expect(requests).toHaveLength(1);
333 }).pipe(Effect.provide(layer));
334});
335​
336effectIt.effect(
337 "excludes HTTP errors, non-navigation responses, and successful non-documents",
338 () => {
339 let pid = 1;
340 let makeResponse = () =>
341 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
342 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
343 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
344 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
345​
346 return Effect.gen(function* () {
347 const scanner = yield* ownedScanner([1, 2, 3, 4, 5, 6, 7]);
348 expect(yield* scanner.scan()).toHaveLength(0);
349​
350 pid += 1;
351 makeResponse = () =>
352 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
353 expect(yield* scanner.scan()).toHaveLength(0);
354​
355 pid += 1;
356 makeResponse = () =>
357 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
358 expect(yield* scanner.scan()).toHaveLength(0);
359​
360 pid += 1;
361 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
362 expect(yield* scanner.scan()).toHaveLength(0);
363​
364 pid += 1;
365 makeResponse = () =>
366 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
367 expect(yield* scanner.scan()).toHaveLength(0);
368​
369 pid += 1;
370 makeResponse = () => new Response(null, { status: 302 });
371 expect(yield* scanner.scan()).toHaveLength(0);
372​
373 pid += 1;
374 makeResponse = () =>
375 new Response("<html />", {
376 status: 200,
377 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
378 });
379 expect(yield* scanner.scan()).toHaveLength(1);
380 }).pipe(Effect.provide(layer));
381 },
382);
383​
384const PROC_NET_TCP = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
385 0: 0100007F:223D 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5001 1 0000000000000000 100 0 0 10 0
386 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5002 1 0000000000000000 100 0 0 10 0
387 2: 0100007F:223D 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 5003 1 0000000000000000 20 4 30 10 -1
388 3: 0A00000F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5005 1 0000000000000000 100 0 0 10 0
389`;
390const PROC_NET_TCP6 = ` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
391 0: 00000000000000000000000000000000:0BB9 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5004 1 0000000000000000 100 0 0 10 0
392`;
393​
394effectIt.effect(
395 "reads Linux listeners from /proc when lsof is missing, and stops spawning it",
396 () => {
397 let lsofSpawns = 0;
398 const fdWalks: string[] = [];
399 const procFiles: Record<string, string> = {
400 "/proc/net/tcp": PROC_NET_TCP,
401 "/proc/net/tcp6": PROC_NET_TCP6,
402 "/proc/4242/comm": "python3\n",
403 };
404 const procFds: Record<string, Record<string, string>> = {
405 "4242": { "0": "/dev/null", "3": "socket:[5001]" },
406 "77": { "5": "socket:[9999]" },
407 };
408 const missing = FileSystem.makeNoop({});
409 const fileSystem = FileSystem.layerNoop({
410 readFileString: (path) => {
411 const content = procFiles[path];
412 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
413 },
414 readDirectory: (path) => {
415 if (path === "/proc") return Effect.succeed(["self", "77", "4242"]);
416 const pid = /^\/proc\/(\d+)\/fd$/.exec(path)?.[1];
417 const fds = pid === undefined ? undefined : procFds[pid];
418 if (pid === undefined || fds === undefined) return missing.readDirectory(path);
419 fdWalks.push(pid);
420 return Effect.succeed(Object.keys(fds));
421 },
422 readLink: (path) => {
423 const [, pid, fd] = /^\/proc\/(\d+)\/fd\/(\d+)$/.exec(path) ?? [];
424 const target = pid && fd ? procFds[pid]?.[fd] : undefined;
425 return target === undefined ? missing.readLink(path) : Effect.succeed(target);
426 },
427 });
428 const fetchFn = (() =>
429 Promise.resolve(
430 new Response("hello", { headers: { "content-type": "text/html" } }),
431 )) as typeof globalThis.fetch;
432 const layer = layerProbeFailure(
433 (input) => {
434 lsofSpawns += 1;
435 return processProbeFailure(input);
436 },
437 fetchFn,
438 fileSystem,
439 );
440​
441 return Effect.gen(function* () {
442 const scanner = yield* ownedScanner([4242]);
443 const first = yield* scanner.scan();
444 expect(first.map(({ port, pid, processName }) => ({ port, pid, processName }))).toEqual([
445 { port: 8765, pid: 4242, processName: "python3" },
446 ]);
447 yield* scanner.scan();
448 expect(lsofSpawns).toBe(1);
449 expect(fdWalks).toEqual(["77", "4242", "77", "4242"]);
450 yield* scanner.scan();
451 yield* scanner.scan();
452 expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]);
453 }).pipe(Effect.provide(layer));
454 },
455);
456​
457effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
458 const fetchFn = (() =>
459 Promise.resolve(
460 new Response("hello", { headers: { "content-type": "text/html" } }),
461 )) as typeof globalThis.fetch;
462 const layer = PortScanner.layer.pipe(
463 Layer.provide(
464 Layer.mergeAll(
465 layerNoProc,
466 Layer.succeed(ProcessRunner.ProcessRunner, {
467 run: (input) => {
468 const isIpv6 = input.args.includes("tcpv6");
469 return Effect.succeed({
470 stdout: isIpv6
471 ? ""
472 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
473 stderr: "",
474 code: isIpv6 ? ChildProcessSpawner.ExitCode(1) : null,
475 timedOut: false,
476 stdoutTruncated: false,
477 stderrTruncated: false,
478 stdoutInvalidUtf8: false,
479 stderrInvalidUtf8: false,
480 });
481 },
482 }),
483 Layer.succeed(HostProcess.Platform, "win32"),
484 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
485 ),
486 ),
487 );
488​
489 return Effect.gen(function* () {
490 const scanner = yield* PortScanner.PortDiscovery;
491 yield* scanner.registerTerminalProcesses({
492 threadId: "scanner-thread",
493 terminalId: "scanner-terminal",
494 processIds: [1234],
495 });
496 expect(yield* scanner.scan()).toEqual([]);
497 }).pipe(Effect.provide(layer));
498});