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