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