Open History to see the last commit
1import * as NodeNet from "node:net";
2
3import { it as effectIt } from "@effect/vitest";
4import {
5 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
6 PREVIEW_URL_MAX_LENGTH,
7 type DiscoveredLocalServer,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Cause from "effect/Cause";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import * as Clock from "effect/Clock";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as PlatformError from "effect/PlatformError";
20import * as Scope from "effect/Scope";
21import * as TestClock from "effect/testing/TestClock";
22import * as Tracer from "effect/Tracer";
23import { expect } from "vite-plus/test";
24import { FetchHttpClient } from "effect/http";
25
26import * as ProcessRunner from "../processRunner.ts";
27import * as PortScanner from "./PortScanner.ts";
28const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
29 Effect.fail(
30 new ProcessRunner.ProcessSpawnError({
31 command: input.command,
32 argumentCount: input.args.length,
33 cwd: input.cwd,
34 cause: PlatformError.systemError({
35 _tag: "NotFound",
36 module: "ChildProcess",
37 method: "spawn",
38 description: "PowerShell is not installed in the test environment",
39 }),
40 }),
41 );
42
43const layerTestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
44 run: processProbeFailure,
45});
46
47/** A host without `/proc`, so a missing `lsof` leaves only configured URLs. */
48const layerNoProc = FileSystem.layerNoop({});
49
50const layerProbeFailure = (
51 run: ProcessRunner.ProcessRunner["Service"]["run"],
52 fetch: typeof globalThis.fetch = globalThis.fetch,
53 fileSystem: Layer.Layer<FileSystem.FileSystem> = layerNoProc,
54) =>
55 PortScanner.layer.pipe(
56 Layer.provide(
57 Layer.mergeAll(
58 fileSystem,
59 Layer.succeed(ProcessRunner.ProcessRunner, { run }),
60 Layer.succeed(HostProcess.Platform, "linux"),
61 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
62 ),
63 ),
64 );
65
66const layerTestPortDiscovery = PortScanner.layer.pipe(
67 Layer.provide(
68 Layer.mergeAll(
69 layerNoProc,
70 layerTestProcessRunner,
71 Layer.succeed(HostProcess.Platform, "win32"),
72 FetchHttpClient.layer,
73 ),
74 ),
75);
76
77const LSOF_TEST_PORT = 43_123;
78
79/** The scanner with `processIds` registered to a T3 terminal, so their listeners get probes. */
80const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) =>
81 Effect.tap(PortScanner.PortDiscovery, (scanner) =>
82 scanner.registerTerminalProcesses({
83 threadId: "scanner-thread",
84 terminalId: "scanner-terminal",
85 processIds,
86 }),
87 );
88
89const layerLsofScanner = (input: {
90 readonly pid: () => number;
91 readonly fetch: typeof globalThis.fetch;
92 readonly stdout?: () => string;
93}) =>
94 PortScanner.layer.pipe(
95 Layer.provide(
96 Layer.mergeAll(
97 layerNoProc,
98 Layer.succeed(ProcessRunner.ProcessRunner, {
99 run: () =>
100 Effect.succeed({
101 stdout: input.stdout?.() ?? `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
102 stderr: "",
103 code: null,
104 timedOut: false,
105 stdoutTruncated: false,
106 stderrTruncated: false,
107 stdoutInvalidUtf8: false,
108 stderrInvalidUtf8: false,
109 }),
110 }),
111 Layer.succeed(HostProcess.Platform, "linux"),
112 FetchHttpClient.layer.pipe(
113 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
114 ),
115 ),
116 ),
117 );
118
119const openServer = (
120 port: number,
121 onConnection: (socket: NodeNet.Socket) => void,
122): Effect.Effect<NodeNet.Server | null> =>
123 Effect.callback((resume) => {
124 const server = NodeNet.createServer(onConnection);
125 server.once("error", () => {
126 resume(Effect.succeed(null));
127 });
128 server.listen(port, "127.0.0.1", () => {
129 resume(Effect.succeed(server));
130 });
131 return Effect.sync(() => {
132 server.close();
133 });
134 });
135
136const closeServer = (server: NodeNet.Server): Effect.Effect<void> =>
137 Effect.callback((resume) => {
138 server.close(() => resume(Effect.void));
139 });
140
141const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
142 onConnection: (socket: NodeNet.Socket) => void,
143) {
144 const server = yield* openServer(0, onConnection);
145 const address = server?.address();
146 if (!server || !address || typeof address === "string") {
147 return yield* Effect.die(new Error("Could not open the preview scanner test listener"));
148 }
149 return { port: address.port, server };
150});
151
152const commonDevServer = Effect.acquireRelease(
153 openCommonDevServer((socket) => {
154 socket.once("data", () => {
155 socket.end("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 5\r\n\r\nhello");
156 });
157 }),
158 ({ server }) => closeServer(server),
159);
160
161const commonNonHttpServer = Effect.acquireRelease(
162 openCommonDevServer((socket) => {
163 socket.on("error", () => undefined);
164 socket.once("data", () => socket.end("MYSQL\r\n\r\n"));
165 }),
166 ({ server }) => closeServer(server),
167);
168
169/**
170 * Integration tests against a real TCP listener. We provide the Windows host
171 * platform with a failing listener probe so the tests exercise configured URLs
172 * without depending on `lsof` being installed.
173 */
174effectIt.layer(layerTestPortDiscovery)("PortDiscovery integration (configured URLs)", (it) => {
175 it.effect(
176 "scan() returns a configured HTTP server we just opened",
177 Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
178 const { port } = yield* commonDevServer;
179 const scanner = yield* PortScanner.PortDiscovery;
180 const result = yield* scanner.scan([`http://localhost:${port}`]);
181 const found = result.find((server) => server.port === port);
182 expect(found).toBeDefined();
183 expect(found?.host).toBe("localhost");
184 }),
185 );
186
187 it.effect(
188 "scan() excludes a listening port that does not speak HTTP",
189 Effect.fn("PortScannerTest.scanExcludesNonHttpServer")(function* () {
190 const { port } = yield* commonNonHttpServer;
191 const scanner = yield* PortScanner.PortDiscovery;
192 const result = yield* scanner.scan([`http://localhost:${port}`]);
193 expect(result.some((server) => server.port === port)).toBe(false);
194 }),
195 );
196
197 it.effect(
198 "retain drives an immediate broadcast to subscribers",
199 Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
200 const { port } = yield* commonDevServer;
201 const received: number[] = [];
202 const scanner = yield* PortScanner.PortDiscovery;
203 yield* scanner.subscribe(
204 { configuredUrls: [`http://localhost:${port}`], initialSnapshot: [] },
205 (servers) =>
206 Effect.sync(() => {
207 for (const server of servers) received.push(server.port);
208 }),
209 );
210 yield* scanner.retain;
211 expect(received).toContain(port);
212 }),
213 );
214});
215
216effectIt.effect("revalidates a successful HTML probe after its cache entry expires", () => {
217 let responds = true;
218 const requests: string[] = [];
219 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
220 requests.push(String(input));
221 return responds
222 ? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
223 : Promise.reject(new TypeError("not HTTP"));
224 }) as typeof globalThis.fetch;
225 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
226
227 return Effect.gen(function* () {
228 const scanner = yield* ownedScanner();
229 expect(yield* scanner.scan()).toHaveLength(1);
230 expect(yield* scanner.scan()).toHaveLength(1);
231 expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
232
233 responds = false;
234 yield* TestClock.adjust(Duration.seconds(15));
235 expect(yield* scanner.scan()).toHaveLength(0);
236 expect(requests).toEqual([
237 `http://localhost:${LSOF_TEST_PORT}/`,
238 `http://localhost:${LSOF_TEST_PORT}/`,
239 `https://localhost:${LSOF_TEST_PORT}/`,
240 ]);
241 }).pipe(Effect.provide(layer));
242});
243
244effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
245 const requests: string[] = [];
246 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
247 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
248 const url = String(input);
249 requests.push(url);
250 return Promise.resolve(
251 url === configuredUrl
252 ? new Response("docs", { headers: { "content-type": "text/html" } })
253 : new Response("not found", {
254 status: 404,
255 headers: { "content-type": "text/html" },
256 }),
257 );
258 }) as typeof globalThis.fetch;
259 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
260
261 return Effect.gen(function* () {
262 const scanner = yield* PortScanner.PortDiscovery;
263 const servers = yield* scanner.scan([configuredUrl]);
264 expect(servers).toHaveLength(1);
265 expect(servers[0]?.url).toBe(configuredUrl);
266 expect(requests).toContain(configuredUrl);
267 }).pipe(Effect.provide(layer));
268});
269
270effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
271 const customPort = 43_124;
272 const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
273 const expectedUrl = `http://localhost:${customPort}/docs`;
274 const requests: string[] = [];
275 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
276 requests.push(String(input));
277 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
278 }) as typeof globalThis.fetch;
279 const layer = layerProbeFailure(processProbeFailure, fetchFn);
280
281 return Effect.gen(function* () {
282 const scanner = yield* PortScanner.PortDiscovery;
283 const servers = yield* scanner.scan([configuredUrl]);
284 expect(servers).toHaveLength(1);
285 expect(servers[0]?.host).toBe("localhost");
286 expect(servers[0]?.port).toBe(customPort);
287 expect(servers[0]?.url).toBe(expectedUrl);
288 expect(requests).toEqual([expectedUrl]);
289 }).pipe(Effect.provide(layer));
290});
291
292effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
293 const ipv4Url = "https://127.0.0.1:43125/docs";
294 const ipv6Url = "http://[::1]:43126/docs";
295 const wildcardPrefix = "http://0.0.0.0/";
296 const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
297 PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
298 )}`;
299 const requests: string[] = [];
300 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
301 requests.push(String(input));
302 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
303 }) as typeof globalThis.fetch;
304 const layer = layerProbeFailure(processProbeFailure, fetchFn);
305
306 return Effect.gen(function* () {
307 const scanner = yield* PortScanner.PortDiscovery;
308 const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
309 expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
310 expect(requests).toEqual([ipv4Url, ipv6Url]);
311 }).pipe(Effect.provide(layer));
312});
313
314effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
315 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
316 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
317 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
318 const url = String(input);
319 return Promise.resolve(
320 url === docsUrl || url === adminUrl
321 ? new Response("app", { headers: { "content-type": "text/html" } })
322 : new Response("not found", { status: 404 }),
323 );
324 }) as typeof globalThis.fetch;
325 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
326
327 return Effect.gen(function* () {
328 const scanner = yield* PortScanner.PortDiscovery;
329 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
330 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
331 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
332 Effect.sync(() => docsSnapshots.push(servers)),
333 );
334 yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
335 Effect.sync(() => adminSnapshots.push(servers)),
336 );
337 yield* scanner.retain;
338
339 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
340 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
341 }).pipe(Effect.scoped, Effect.provide(layer));
342});
343
344effectIt.effect(
345 "keeps each subscriber's candidates when their combined union exceeds the per-client cap",
346 () => {
347 const firstSubscriberUrls = Array.from(
348 { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
349 (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
350 );
351 const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
352 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
353 Promise.resolve(
354 String(input) === secondSubscriberUrl
355 ? new Response("app", { headers: { "content-type": "text/html" } })
356 : new Response("not found", { status: 404 }),
357 )) as typeof globalThis.fetch;
358 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
359
360 return Effect.gen(function* () {
361 const scanner = yield* PortScanner.PortDiscovery;
362 const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
363 yield* scanner.subscribe(
364 { configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
365 () => Effect.void,
366 );
367 yield* scanner.subscribe(
368 { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
369 (servers) => Effect.sync(() => secondSnapshots.push(servers)),
370 );
371 yield* scanner.retain;
372
373 expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
374 }).pipe(Effect.scoped, Effect.provide(layer));
375 },
376);
377
378effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
379 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
380 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
381 const requests: string[] = [];
382 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
383 const url = String(input);
384 requests.push(url);
385 return Promise.resolve(
386 url === docsUrl || url === adminUrl
387 ? new Response("app", { headers: { "content-type": "text/html" } })
388 : new Response("not found", { status: 404 }),
389 );
390 }) as typeof globalThis.fetch;
391 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
392
393 return Effect.gen(function* () {
394 const scanner = yield* PortScanner.PortDiscovery;
395 const docsScope = yield* Scope.make();
396 yield* scanner
397 .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
398 .pipe(Effect.provideService(Scope.Scope, docsScope));
399 yield* scanner.subscribe(
400 { configuredUrls: [adminUrl], initialSnapshot: [] },
401 () => Effect.void,
402 );
403 yield* scanner.retain;
404 yield* Scope.close(docsScope, Exit.void);
405
406 requests.length = 0;
407 yield* TestClock.adjust(Duration.seconds(15));
408 expect(requests).toContain(adminUrl);
409 expect(requests).not.toContain(docsUrl);
410 }).pipe(Effect.scoped, Effect.provide(layer));
411});
412
413effectIt.effect("writes no poll span while no client retains the scanner", () => {
414 let pollSpans = 0;
415 const tracer = Tracer.make({
416 span: (options) => {
417 if (options.name === "PortDiscovery.pollTick") pollSpans += 1;
418 return new Tracer.NativeSpan(options);
419 },
420 });
421 const layer = layerProbeFailure(processProbeFailure);
422
423 return Effect.gen(function* () {
424 const scanner = yield* PortScanner.PortDiscovery;
425 yield* TestClock.adjust(Duration.seconds(15));
426 expect(pollSpans).toBe(0);
427
428 yield* scanner.retain;
429 expect(pollSpans).toBe(1);
430 }).pipe(Effect.scoped, Effect.provide(layer), Effect.withTracer(tracer));
431});
432
433effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
434 const requests: string[] = [];
435 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
436 requests.push(String(input));
437 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
438 }) as typeof globalThis.fetch;
439 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
440 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
441 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
442
443 return Effect.gen(function* () {
444 const scanner = yield* PortScanner.PortDiscovery;
445 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
446 const requestCount = requests.length;
447 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
448 expect(requests).toHaveLength(requestCount);
449 }).pipe(Effect.provide(layer));
450});
451
452effectIt.effect("shares a configured root probe with discovered-root classification", () => {
453 const requests: string[] = [];
454 const rootUrl = `http://localhost:${LSOF_TEST_PORT}/`;
455 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
456 requests.push(String(input));
457 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
458 }) as typeof globalThis.fetch;
459 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
460
461 return Effect.gen(function* () {
462 const scanner = yield* ownedScanner();
463 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
464 expect(requests).toEqual([rootUrl]);
465
466 yield* TestClock.adjust(Duration.seconds(15));
467 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
468 expect(requests).toEqual([rootUrl, rootUrl]);
469 }).pipe(Effect.provide(layer));
470});
471
472effectIt.effect("starts fresh cache entries after the probing batch completes", () =>
473 Effect.gen(function* () {
474 const baseClock = yield* Clock.Clock;
475 const times = [0, 20_000, 20_000, 20_000];
476 let timeIndex = 0;
477 const currentTimeMillis = () => times[Math.min(timeIndex++, times.length - 1)]!;
478 const clock: Clock.Clock = {
479 ...baseClock,
480 currentTimeMillisUnsafe: currentTimeMillis,
481 currentTimeMillis: Effect.sync(currentTimeMillis),
482 };
483 const requests: string[] = [];
484 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
485 requests.push(String(input));
486 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
487 }) as typeof globalThis.fetch;
488 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
489
490 yield* Effect.gen(function* () {
491 const scanner = yield* ownedScanner();
492 expect(yield* scanner.scan()).toHaveLength(1);
493 expect(yield* scanner.scan()).toHaveLength(1);
494 expect(requests).toHaveLength(1);
495 }).pipe(Effect.provide(layer), Effect.provideService(Clock.Clock, clock));
496 }),
497);
498
499effectIt.effect("caches a failed web probe until its bounded cache entry expires", () => {
500 let responds = false;
501 const requests: string[] = [];
502 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
503 requests.push(String(input));
504 return responds
505 ? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
506 : Promise.reject(new TypeError("not HTTP"));
507 }) as typeof globalThis.fetch;
508 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
509
510 return Effect.gen(function* () {
511 const scanner = yield* ownedScanner();
512 expect(yield* scanner.scan()).toHaveLength(0);
513 expect(yield* scanner.scan()).toHaveLength(0);
514 expect(requests).toHaveLength(2);
515
516 responds = true;
517 yield* TestClock.adjust(Duration.seconds(15));
518 expect(yield* scanner.scan()).toHaveLength(1);
519 expect(requests).toHaveLength(3);
520 }).pipe(Effect.provide(layer));
521});
522
523effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
524 const redirects: Array<string | undefined> = [];
525 const fetchFn = (async (
526 input: Parameters<typeof globalThis.fetch>[0],
527 init?: Parameters<typeof globalThis.fetch>[1],
528 ) => {
529 redirects.push(init?.redirect);
530 if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
531 return new Response(null, { status: 302, headers: { location: "https://example.com" } });
532 }) as typeof globalThis.fetch;
533 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
534
535 return Effect.gen(function* () {
536 const scanner = yield* ownedScanner();
537 const servers = yield* scanner.scan();
538 expect(servers).toHaveLength(1);
539 expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
540 expect(redirects).toEqual(["manual", "manual"]);
541 }).pipe(Effect.provide(layer));
542});
543
544effectIt.effect("probes a port only while T3 terminals own every listener on it", () => {
545 const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`;
546 const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`;
547 let stdout = unowned;
548 const requests: string[] = [];
549 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
550 requests.push(String(input));
551 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
552 }) as typeof globalThis.fetch;
553 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn, stdout: () => stdout });
554
555 return Effect.gen(function* () {
556 const scanner = yield* ownedScanner();
557 expect(yield* scanner.scan()).toHaveLength(0);
558 stdout = `${owned}${unowned}`;
559 expect(yield* scanner.scan()).toHaveLength(0);
560 expect(requests).toEqual([]);
561
562 stdout = owned;
563 expect(yield* scanner.scan()).toHaveLength(1);
564 expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
565
566 yield* scanner.unregisterTerminal({
567 threadId: "scanner-thread",
568 terminalId: "scanner-terminal",
569 });
570 expect(yield* scanner.scan()).toHaveLength(0);
571 expect(requests).toHaveLength(1);
572 }).pipe(Effect.provide(layer));
573});
574
575effectIt.effect(
576 "excludes HTTP errors, non-navigation responses, and successful non-documents",
577 () => {
578 let pid = 1;
579 let makeResponse = () =>
580 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
581 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
582 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
583 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
584
585 return Effect.gen(function* () {
586 const scanner = yield* ownedScanner([1, 2, 3, 4, 5, 6, 7]);
587 expect(yield* scanner.scan()).toHaveLength(0);
588
589 pid += 1;
590 makeResponse = () =>
591 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
592 expect(yield* scanner.scan()).toHaveLength(0);
593
594 pid += 1;
595 makeResponse = () =>
596 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
597 expect(yield* scanner.scan()).toHaveLength(0);
598
599 pid += 1;
600 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
601 expect(yield* scanner.scan()).toHaveLength(0);
602
603 pid += 1;
604 makeResponse = () =>
605 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
606 expect(yield* scanner.scan()).toHaveLength(0);
607
608 pid += 1;
609 makeResponse = () => new Response(null, { status: 302 });
610 expect(yield* scanner.scan()).toHaveLength(0);
611
612 pid += 1;
613 makeResponse = () =>
614 new Response("<html />", {
615 status: 200,
616 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
617 });
618 expect(yield* scanner.scan()).toHaveLength(1);
619 }).pipe(Effect.provide(layer));
620 },
621);
622
623effectIt.effect("aborts HTTP and HTTPS probes when they time out", () => {
624 const aborted: string[] = [];
625 const fetchFn = ((
626 input: Parameters<typeof globalThis.fetch>[0],
627 init?: Parameters<typeof globalThis.fetch>[1],
628 ) =>
629 new Promise<Response>((_resolve, reject) => {
630 const signal = init?.signal;
631 const onAbort = () => {
632 aborted.push(String(input));
633 reject(new DOMException("Aborted", "AbortError"));
634 };
635 if (signal?.aborted) {
636 onAbort();
637 } else {
638 signal?.addEventListener("abort", onAbort, { once: true });
639 }
640 })) as typeof globalThis.fetch;
641 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
642
643 return Effect.gen(function* () {
644 const scanner = yield* ownedScanner();
645 const scanFiber = yield* Effect.forkChild(scanner.scan());
646 yield* TestClock.adjust(Duration.seconds(2));
647 expect(yield* Fiber.join(scanFiber)).toHaveLength(0);
648 expect(aborted).toEqual([
649 `http://localhost:${LSOF_TEST_PORT}/`,
650 `https://localhost:${LSOF_TEST_PORT}/`,
651 ]);
652 }).pipe(Effect.provide(layer));
653});
654
655effectIt.effect("does not swallow process probe defects", () =>
656 Effect.gen(function* () {
657 const defect = new Error("unexpected process probe defect");
658 const layer = layerProbeFailure(() => Effect.die(defect));
659
660 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
661 Effect.provide(layer),
662 Effect.exit,
663 );
664
665 expect(Exit.isFailure(exit)).toBe(true);
666 if (Exit.isFailure(exit)) {
667 expect(Cause.hasDies(exit.cause)).toBe(true);
668 expect(Cause.squash(exit.cause)).toBe(defect);
669 }
670 }),
671);
672
673// /proc/net/tcp: 127.0.0.1:8765 and 0.0.0.0:22 listening, an established
674// connection, and a non-loopback listener; /proc/net/tcp6 adds [::]:3001.
675const PROC_NET_TCP = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
676 0: 0100007F:223D 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5001 1 0000000000000000 100 0 0 10 0
677 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5002 1 0000000000000000 100 0 0 10 0
678 2: 0100007F:223D 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 5003 1 0000000000000000 20 4 30 10 -1
679 3: 0A00000F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5005 1 0000000000000000 100 0 0 10 0
680`;
681const PROC_NET_TCP6 = ` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
682 0: 00000000000000000000000000000000:0BB9 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5004 1 0000000000000000 100 0 0 10 0
683`;
684
685effectIt.effect(
686 "reads Linux listeners from /proc when lsof is missing, and stops spawning it",
687 () => {
688 let lsofSpawns = 0;
689 const fdWalks: string[] = [];
690 const procFiles: Record<string, string> = {
691 "/proc/net/tcp": PROC_NET_TCP,
692 "/proc/net/tcp6": PROC_NET_TCP6,
693 "/proc/4242/comm": "python3\n",
694 };
695 const procFds: Record<string, Record<string, string>> = {
696 "4242": { "0": "/dev/null", "3": "socket:[5001]" },
697 "77": { "5": "socket:[9999]" },
698 };
699 const missing = FileSystem.makeNoop({});
700 const fileSystem = FileSystem.layerNoop({
701 readFileString: (path) => {
702 const content = procFiles[path];
703 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
704 },
705 readDirectory: (path) => {
706 if (path === "/proc") return Effect.succeed(["self", "77", "4242"]);
707 const pid = /^\/proc\/(\d+)\/fd$/.exec(path)?.[1];
708 const fds = pid === undefined ? undefined : procFds[pid];
709 if (pid === undefined || fds === undefined) return missing.readDirectory(path);
710 fdWalks.push(pid);
711 return Effect.succeed(Object.keys(fds));
712 },
713 readLink: (path) => {
714 const [, pid, fd] = /^\/proc\/(\d+)\/fd\/(\d+)$/.exec(path) ?? [];
715 const target = pid && fd ? procFds[pid]?.[fd] : undefined;
716 return target === undefined ? missing.readLink(path) : Effect.succeed(target);
717 },
718 });
719 const fetchFn = (() =>
720 Promise.resolve(
721 new Response("hello", { headers: { "content-type": "text/html" } }),
722 )) as typeof globalThis.fetch;
723 const layer = layerProbeFailure(
724 (input) => {
725 lsofSpawns += 1;
726 return processProbeFailure(input);
727 },
728 fetchFn,
729 fileSystem,
730 );
731
732 return Effect.gen(function* () {
733 const scanner = yield* ownedScanner([4242]);
734 const first = yield* scanner.scan();
735 // Ports 22 and 3001 have no known owner, so they never receive probes.
736 expect(first.map(({ port, pid, processName }) => ({ port, pid, processName }))).toEqual([
737 { port: 8765, pid: 4242, processName: "python3" },
738 ]);
739 yield* scanner.scan();
740 expect(lsofSpawns).toBe(1);
741 // Ports 22 and 3001 have no readable owner, so the second scan walks
742 // again; it stops at 77, which holds no listener, once nothing is left.
743 expect(fdWalks).toEqual(["77", "4242", "77", "4242"]);
744 yield* scanner.scan();
745 yield* scanner.scan();
746 // Unresolved owners are retried a bounded number of times.
747 expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]);
748 }).pipe(Effect.provide(layer));
749 },
750);
751
752effectIt.effect("keeps spawning lsof after a spawn failure that is not a missing command", () => {
753 let lsofSpawns = 0;
754 const layer = layerProbeFailure((input) => {
755 lsofSpawns += 1;
756 return Effect.fail(
757 new ProcessRunner.ProcessSpawnError({
758 command: input.command,
759 argumentCount: input.args.length,
760 cwd: input.cwd,
761 cause: PlatformError.systemError({
762 _tag: "Unknown",
763 module: "ChildProcess",
764 method: "spawn",
765 description: "EAGAIN",
766 }),
767 }),
768 );
769 });
770 return Effect.gen(function* () {
771 const scanner = yield* PortScanner.PortDiscovery;
772 yield* scanner.scan();
773 yield* scanner.scan();
774 expect(lsofSpawns).toBe(2);
775 }).pipe(Effect.provide(layer));
776});
777
778effectIt.effect("does not swallow process probe interruption", () =>
779 Effect.gen(function* () {
780 const layer = layerProbeFailure(() => Effect.interrupt);
781
782 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
783 Effect.provide(layer),
784 Effect.exit,
785 );
786
787 expect(Exit.isFailure(exit)).toBe(true);
788 if (Exit.isFailure(exit)) {
789 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
790 }
791 }),
792);
793
794effectIt.effect(
795 "parses Windows netstat listeners, names them via tasklist with retry, and skips spawns when idle",
796 () => {
797 const spawnedArgs: Array<ReadonlyArray<string>> = [];
798 let tasklistCalls = 0;
799 const fetchFn = (() =>
800 Promise.resolve(
801 new Response("hello", { headers: { "content-type": "text/html" } }),
802 )) as typeof globalThis.fetch;
803 const layer = PortScanner.layer.pipe(
804 Layer.provide(
805 Layer.mergeAll(
806 layerNoProc,
807 Layer.succeed(ProcessRunner.ProcessRunner, {
808 run: (input) => {
809 spawnedArgs.push(input.args);
810 const isIpv6 = input.args.includes("tcpv6");
811 const isTasklist = input.command === "tasklist.exe";
812 // The first lookup fails, so it must not be cached as "no name".
813 const failTasklist = isTasklist && tasklistCalls++ === 0;
814 return Effect.succeed({
815 stdout: isTasklist
816 ? '"node.exe","1234","Console","1","93,164 K"\r\n'
817 : isIpv6
818 ? " TCP [::1]:43123 [::]:0 ABHÖREN 1234\r\n TCP [::1]:43123 [::1]:52000 HERGESTELLT 1234\r\n"
819 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n TCP 127.0.0.1:5173 127.0.0.1:60123 ESTABLISHED 9999\r\n",
820 stderr: "",
821 code: failTasklist ? ChildProcessSpawner.ExitCode(1) : null,
822 timedOut: false,
823 stdoutTruncated: false,
824 stderrTruncated: false,
825 stdoutInvalidUtf8: false,
826 stderrInvalidUtf8: false,
827 });
828 },
829 }),
830 Layer.succeed(HostProcess.Platform, "win32"),
831 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
832 ),
833 ),
834 );
835
836 return Effect.gen(function* () {
837 const scanner = yield* PortScanner.PortDiscovery;
838 expect(yield* scanner.scan()).toEqual([]);
839 expect(spawnedArgs).toHaveLength(0);
840
841 yield* scanner.registerTerminalProcesses({
842 threadId: "scanner-thread",
843 terminalId: "scanner-terminal",
844 processIds: [1234],
845 });
846 const summarize = (
847 servers: ReadonlyArray<{
848 readonly port: number;
849 readonly pid: number | null;
850 readonly processName: string | null;
851 }>,
852 ) =>
853 servers.map((entry) => ({
854 port: entry.port,
855 pid: entry.pid,
856 processName: entry.processName,
857 }));
858 expect(summarize(yield* scanner.scan())).toEqual([
859 { port: 5173, pid: 1234, processName: null },
860 { port: 43123, pid: 1234, processName: null },
861 ]);
862 expect(spawnedArgs).toEqual([
863 ["-ano", "-p", "tcp"],
864 ["-ano", "-p", "tcpv6"],
865 ["/FO", "CSV", "/NH", "/FI", "PID eq 1234"],
866 ]);
867
868 // The failed lookup retries; the result is then cached, so later polls spawn only netstat.
869 expect(summarize(yield* scanner.scan())).toEqual([
870 { port: 5173, pid: 1234, processName: "node" },
871 { port: 43123, pid: 1234, processName: "node" },
872 ]);
873 yield* scanner.scan();
874 expect(tasklistCalls).toBe(2);
875
876 // Cached names expire, since Windows may hand the PID to another process.
877 yield* TestClock.adjust(Duration.seconds(61));
878 yield* scanner.scan();
879 expect(tasklistCalls).toBe(3);
880 }).pipe(Effect.provide(layer));
881 },
882);
883
884effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
885 const fetchFn = (() =>
886 Promise.resolve(
887 new Response("hello", { headers: { "content-type": "text/html" } }),
888 )) as typeof globalThis.fetch;
889 const layer = PortScanner.layer.pipe(
890 Layer.provide(
891 Layer.mergeAll(
892 layerNoProc,
893 Layer.succeed(ProcessRunner.ProcessRunner, {
894 run: (input) => {
895 const isIpv6 = input.args.includes("tcpv6");
896 return Effect.succeed({
897 stdout: isIpv6
898 ? ""
899 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
900 stderr: "",
901 code: isIpv6 ? ChildProcessSpawner.ExitCode(1) : null,
902 timedOut: false,
903 stdoutTruncated: false,
904 stderrTruncated: false,
905 stdoutInvalidUtf8: false,
906 stderrInvalidUtf8: false,
907 });
908 },
909 }),
910 Layer.succeed(HostProcess.Platform, "win32"),
911 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
912 ),
913 ),
914 );
915
916 return Effect.gen(function* () {
917 const scanner = yield* PortScanner.PortDiscovery;
918 yield* scanner.registerTerminalProcesses({
919 threadId: "scanner-thread",
920 terminalId: "scanner-terminal",
921 processIds: [1234],
922 });
923 expect(yield* scanner.scan()).toEqual([]);
924 }).pipe(Effect.provide(layer));
925});