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

PortScanner.test.ts

705 lines26.1 KB

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 Layer from "effect/Layer";
18import * as PlatformError from "effect/PlatformError";
19import * as Scope from "effect/Scope";
20import * as TestClock from "effect/testing/TestClock";
21import * as Tracer from "effect/Tracer";
22import { expect } from "vite-plus/test";
23import { FetchHttpClient } from "effect/unstable/http";
24​
25import * as ProcessRunner from "../processRunner.ts";
26import * as PortScanner from "./PortScanner.ts";
27const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
28 Effect.fail(
29 new ProcessRunner.ProcessSpawnError({
30 command: input.command,
31 argumentCount: input.args.length,
32 cwd: input.cwd,
33 cause: PlatformError.systemError({
34 _tag: "NotFound",
35 module: "ChildProcess",
36 method: "spawn",
37 description: "PowerShell is not installed in the test environment",
38 }),
39 }),
40 );
41​
42const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
43 run: processProbeFailure,
44});
45​
46let integrationListeningPort: number | null = null;
47​
48const TestIntegrationNet = Layer.succeed(Net.NetService, {
49 canListenOnHost: () => Effect.succeed(true),
50 isPortAvailableOnLoopback: (port) => Effect.sync(() => port !== integrationListeningPort),
51 hasListenerOnHost: (port) => Effect.sync(() => port === integrationListeningPort),
52 reserveLoopbackPort: () => Effect.succeed(40_000),
53 findAvailablePort: (preferred) => Effect.succeed(preferred),
54});
55​
56const makeProbeFailureLayer = (
57 run: ProcessRunner.ProcessRunner["Service"]["run"],
58 fetch: typeof globalThis.fetch = globalThis.fetch,
59) =>
60 PortScanner.layer.pipe(
61 Layer.provide(
62 Layer.mergeAll(
63 Layer.succeed(ProcessRunner.ProcessRunner, { run }),
64 Layer.succeed(Net.NetService, {
65 canListenOnHost: () => Effect.succeed(true),
66 isPortAvailableOnLoopback: () => Effect.succeed(true),
67 hasListenerOnHost: () => Effect.succeed(false),
68 reserveLoopbackPort: () => Effect.succeed(40_000),
69 findAvailablePort: (preferred) => Effect.succeed(preferred),
70 }),
71 Layer.succeed(HostProcessPlatform, "linux"),
72 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
73 ),
74 ),
75 );
76​
77const TestPortDiscoveryLive = PortScanner.layer.pipe(
78 Layer.provide(
79 Layer.mergeAll(
80 TestProcessRunner,
81 TestIntegrationNet,
82 Layer.succeed(HostProcessPlatform, "win32"),
83 FetchHttpClient.layer,
84 ),
85 ),
86);
87​
88const LSOF_TEST_PORT = 43_123;
89​
90const makeLsofScannerLayer = (input: {
91 readonly pid: () => number;
92 readonly fetch: typeof globalThis.fetch;
93}) =>
94 PortScanner.layer.pipe(
95 Layer.provide(
96 Layer.mergeAll(
97 Layer.succeed(ProcessRunner.ProcessRunner, {
98 run: () =>
99 Effect.succeed({
100 stdout: `p${input.pid()}\ncnode\nn*:${LSOF_TEST_PORT}\n`,
101 stderr: "",
102 code: null,
103 timedOut: false,
104 stdoutTruncated: false,
105 stderrTruncated: false,
106 stdoutInvalidUtf8: false,
107 stderrInvalidUtf8: false,
108 }),
109 }),
110 Layer.succeed(Net.NetService, {
111 canListenOnHost: () => Effect.succeed(true),
112 isPortAvailableOnLoopback: () => Effect.succeed(true),
113 hasListenerOnHost: () => Effect.succeed(false),
114 reserveLoopbackPort: () => Effect.succeed(40_000),
115 findAvailablePort: (preferred) => Effect.succeed(preferred),
116 }),
117 Layer.succeed(HostProcessPlatform, "linux"),
118 FetchHttpClient.layer.pipe(
119 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
120 ),
121 ),
122 ),
123 );
124​
125const openServer = (
126 port: number,
127 onConnection: (socket: NodeNet.Socket) => void,
128): Effect.Effect<NodeNet.Server | null> =>
129 Effect.callback((resume) => {
130 const server = NodeNet.createServer(onConnection);
131 server.once("error", () => {
132 resume(Effect.succeed(null));
133 });
134 server.listen(port, "127.0.0.1", () => {
135 resume(Effect.succeed(server));
136 });
137 return Effect.sync(() => {
138 server.close();
139 });
140 });
141​
142const closeServer = (server: NodeNet.Server): Effect.Effect<void> =>
143 Effect.callback((resume) => {
144 server.close(() => resume(Effect.void));
145 });
146​
147const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
148 ports: ReadonlyArray<number>,
149 onConnection: (socket: NodeNet.Socket) => void,
150) {
151 for (const port of ports) {
152 const server = yield* openServer(port, onConnection);
153 if (server !== null) return { port, server };
154 }
155 return yield* Effect.die(
156 new Error("No common development port was available for the preview scanner test"),
157 );
158});
159​
160const commonDevServer = Effect.acquireRelease(
161 openCommonDevServer(PortScanner.COMMON_DEV_PORTS, (socket) => {
162 socket.once("data", () => {
163 socket.end("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 5\r\n\r\nhello");
164 });
165 }).pipe(
166 Effect.tap(({ port }) =>
167 Effect.sync(() => {
168 integrationListeningPort = port;
169 }),
170 ),
171 ),
172 ({ server }) =>
173 closeServer(server).pipe(
174 Effect.ensuring(
175 Effect.sync(() => {
176 integrationListeningPort = null;
177 }),
178 ),
179 ),
180);
181​
182const commonNonHttpServer = Effect.acquireRelease(
183 openCommonDevServer(PortScanner.COMMON_DEV_PORTS.toReversed(), (socket) => {
184 socket.on("error", () => undefined);
185 socket.once("data", () => socket.end("MYSQL\r\n\r\n"));
186 }).pipe(
187 Effect.tap(({ port }) =>
188 Effect.sync(() => {
189 integrationListeningPort = port;
190 }),
191 ),
192 ),
193 ({ server }) =>
194 closeServer(server).pipe(
195 Effect.ensuring(
196 Effect.sync(() => {
197 integrationListeningPort = null;
198 }),
199 ),
200 ),
201);
202​
203/**
204 * Integration tests against a real TCP listener. We provide the Windows host
205 * platform so the tests exercise the TCP-probe fallback without depending on
206 * `lsof` being installed.
207 */
208effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
209 it.effect(
210 "scan() returns an HTTP server we just opened on a curated dev port",
211 Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
212 const { port } = yield* commonDevServer;
213 const scanner = yield* PortScanner.PortDiscovery;
214 const result = yield* scanner.scan();
215 const found = result.find((server) => server.port === port);
216 expect(found).toBeDefined();
217 expect(found?.host).toBe("localhost");
218 }),
219 );
220​
221 it.effect(
222 "scan() excludes a listening port that does not speak HTTP",
223 Effect.fn("PortScannerTest.scanExcludesNonHttpServer")(function* () {
224 const { port } = yield* commonNonHttpServer;
225 const scanner = yield* PortScanner.PortDiscovery;
226 const result = yield* scanner.scan();
227 expect(result.some((server) => server.port === port)).toBe(false);
228 }),
229 );
230​
231 it.effect(
232 "retain drives an immediate broadcast to subscribers",
233 Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
234 const { port } = yield* commonDevServer;
235 const received: number[] = [];
236 const scanner = yield* PortScanner.PortDiscovery;
237 yield* scanner.subscribe({ configuredUrls: [], initialSnapshot: [] }, (servers) =>
238 Effect.sync(() => {
239 for (const server of servers) received.push(server.port);
240 }),
241 );
242 yield* scanner.retain;
243 expect(received).toContain(port);
244 }),
245 );
246});
247​
248effectIt.effect("revalidates a successful HTML probe after its cache entry expires", () => {
249 let responds = true;
250 const requests: string[] = [];
251 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
252 requests.push(String(input));
253 return responds
254 ? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
255 : Promise.reject(new TypeError("not HTTP"));
256 }) as typeof globalThis.fetch;
257 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
258​
259 return Effect.gen(function* () {
260 const scanner = yield* PortScanner.PortDiscovery;
261 expect(yield* scanner.scan()).toHaveLength(1);
262 expect(yield* scanner.scan()).toHaveLength(1);
263 expect(requests).toEqual([`http://localhost:${LSOF_TEST_PORT}/`]);
264​
265 responds = false;
266 yield* TestClock.adjust(Duration.seconds(15));
267 expect(yield* scanner.scan()).toHaveLength(0);
268 expect(requests).toEqual([
269 `http://localhost:${LSOF_TEST_PORT}/`,
270 `http://localhost:${LSOF_TEST_PORT}/`,
271 `https://localhost:${LSOF_TEST_PORT}/`,
272 ]);
273 }).pipe(Effect.provide(layer));
274});
275​
276effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
277 const requests: string[] = [];
278 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
279 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
280 const url = String(input);
281 requests.push(url);
282 return Promise.resolve(
283 url === configuredUrl
284 ? new Response("docs", { headers: { "content-type": "text/html" } })
285 : new Response("not found", {
286 status: 404,
287 headers: { "content-type": "text/html" },
288 }),
289 );
290 }) as typeof globalThis.fetch;
291 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
292​
293 return Effect.gen(function* () {
294 const scanner = yield* PortScanner.PortDiscovery;
295 const servers = yield* scanner.scan([configuredUrl]);
296 expect(servers).toHaveLength(1);
297 expect(servers[0]?.url).toBe(configuredUrl);
298 expect(requests).toContain(configuredUrl);
299 }).pipe(Effect.provide(layer));
300});
301​
302effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
303 const customPort = 43_124;
304 const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
305 const expectedUrl = `http://localhost:${customPort}/docs`;
306 const requests: string[] = [];
307 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
308 requests.push(String(input));
309 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
310 }) as typeof globalThis.fetch;
311 const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
312​
313 return Effect.gen(function* () {
314 const scanner = yield* PortScanner.PortDiscovery;
315 const servers = yield* scanner.scan([configuredUrl]);
316 expect(servers).toHaveLength(1);
317 expect(servers[0]?.host).toBe("localhost");
318 expect(servers[0]?.port).toBe(customPort);
319 expect(servers[0]?.url).toBe(expectedUrl);
320 expect(requests).toEqual([expectedUrl]);
321 }).pipe(Effect.provide(layer));
322});
323​
324effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
325 const ipv4Url = "https://127.0.0.1:43125/docs";
326 const ipv6Url = "http://[::1]:43126/docs";
327 const wildcardPrefix = "http://0.0.0.0/";
328 const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
329 PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
330 )}`;
331 const requests: string[] = [];
332 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
333 requests.push(String(input));
334 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
335 }) as typeof globalThis.fetch;
336 const layer = makeProbeFailureLayer(processProbeFailure, fetchFn);
337​
338 return Effect.gen(function* () {
339 const scanner = yield* PortScanner.PortDiscovery;
340 const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
341 expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
342 expect(requests).toEqual([ipv4Url, ipv6Url]);
343 }).pipe(Effect.provide(layer));
344});
345​
346effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
347 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
348 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
349 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
350 const url = String(input);
351 return Promise.resolve(
352 url === docsUrl || url === adminUrl
353 ? new Response("app", { headers: { "content-type": "text/html" } })
354 : new Response("not found", { status: 404 }),
355 );
356 }) as typeof globalThis.fetch;
357 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
358​
359 return Effect.gen(function* () {
360 const scanner = yield* PortScanner.PortDiscovery;
361 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
362 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
363 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
364 Effect.sync(() => docsSnapshots.push(servers)),
365 );
366 yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
367 Effect.sync(() => adminSnapshots.push(servers)),
368 );
369 yield* scanner.retain;
370​
371 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
372 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
373 }).pipe(Effect.scoped, Effect.provide(layer));
374});
375​
376effectIt.effect(
377 "keeps each subscriber's candidates when their combined union exceeds the per-client cap",
378 () => {
379 const firstSubscriberUrls = Array.from(
380 { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
381 (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
382 );
383 const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
384 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
385 Promise.resolve(
386 String(input) === secondSubscriberUrl
387 ? new Response("app", { headers: { "content-type": "text/html" } })
388 : new Response("not found", { status: 404 }),
389 )) as typeof globalThis.fetch;
390 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
391​
392 return Effect.gen(function* () {
393 const scanner = yield* PortScanner.PortDiscovery;
394 const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
395 yield* scanner.subscribe(
396 { configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
397 () => Effect.void,
398 );
399 yield* scanner.subscribe(
400 { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
401 (servers) => Effect.sync(() => secondSnapshots.push(servers)),
402 );
403 yield* scanner.retain;
404​
405 expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
406 }).pipe(Effect.scoped, Effect.provide(layer));
407 },
408);
409​
410effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
411 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
412 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
413 const requests: string[] = [];
414 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
415 const url = String(input);
416 requests.push(url);
417 return Promise.resolve(
418 url === docsUrl || url === adminUrl
419 ? new Response("app", { headers: { "content-type": "text/html" } })
420 : new Response("not found", { status: 404 }),
421 );
422 }) as typeof globalThis.fetch;
423 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
424​
425 return Effect.gen(function* () {
426 const scanner = yield* PortScanner.PortDiscovery;
427 const docsScope = yield* Scope.make();
428 yield* scanner
429 .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
430 .pipe(Effect.provideService(Scope.Scope, docsScope));
431 yield* scanner.subscribe(
432 { configuredUrls: [adminUrl], initialSnapshot: [] },
433 () => Effect.void,
434 );
435 yield* scanner.retain;
436 yield* Scope.close(docsScope, Exit.void);
437​
438 requests.length = 0;
439 yield* TestClock.adjust(Duration.seconds(15));
440 expect(requests).toContain(adminUrl);
441 expect(requests).not.toContain(docsUrl);
442 }).pipe(Effect.scoped, Effect.provide(layer));
443});
444​
445effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
446 const requests: string[] = [];
447 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
448 requests.push(String(input));
449 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
450 }) as typeof globalThis.fetch;
451 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
452 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
453 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
454​
455 return Effect.gen(function* () {
456 const scanner = yield* PortScanner.PortDiscovery;
457 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
458 const requestCount = requests.length;
459 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
460 expect(requests).toHaveLength(requestCount);
461 }).pipe(Effect.provide(layer));
462});
463​
464effectIt.effect("shares a configured root probe with discovered-root classification", () => {
465 const requests: string[] = [];
466 const rootUrl = `http://localhost:${LSOF_TEST_PORT}/`;
467 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
468 requests.push(String(input));
469 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
470 }) as typeof globalThis.fetch;
471 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
472​
473 return Effect.gen(function* () {
474 const scanner = yield* PortScanner.PortDiscovery;
475 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
476 expect(requests).toEqual([rootUrl]);
477​
478 yield* TestClock.adjust(Duration.seconds(15));
479 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
480 expect(requests).toEqual([rootUrl, rootUrl]);
481 }).pipe(Effect.provide(layer));
482});
483​
484effectIt.effect("starts fresh cache entries after the probing batch completes", () =>
485 Effect.gen(function* () {
486 const baseClock = yield* Clock.Clock;
487 const times = [0, 20_000, 20_000, 20_000];
488 let timeIndex = 0;
489 const currentTimeMillis = () => times[Math.min(timeIndex++, times.length - 1)]!;
490 const clock: Clock.Clock = {
491 ...baseClock,
492 currentTimeMillisUnsafe: currentTimeMillis,
493 currentTimeMillis: Effect.sync(currentTimeMillis),
494 };
495 const requests: string[] = [];
496 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
497 requests.push(String(input));
498 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
499 }) as typeof globalThis.fetch;
500 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
501​
502 yield* Effect.gen(function* () {
503 const scanner = yield* PortScanner.PortDiscovery;
504 expect(yield* scanner.scan()).toHaveLength(1);
505 expect(yield* scanner.scan()).toHaveLength(1);
506 expect(requests).toHaveLength(1);
507 }).pipe(Effect.provide(layer), Effect.provideService(Clock.Clock, clock));
508 }),
509);
510​
511effectIt.effect("caches a failed web probe until its bounded cache entry expires", () => {
512 let responds = false;
513 const requests: string[] = [];
514 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
515 requests.push(String(input));
516 return responds
517 ? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
518 : Promise.reject(new TypeError("not HTTP"));
519 }) as typeof globalThis.fetch;
520 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
521​
522 return Effect.gen(function* () {
523 const scanner = yield* PortScanner.PortDiscovery;
524 expect(yield* scanner.scan()).toHaveLength(0);
525 expect(yield* scanner.scan()).toHaveLength(0);
526 expect(requests).toHaveLength(2);
527​
528 responds = true;
529 yield* TestClock.adjust(Duration.seconds(15));
530 expect(yield* scanner.scan()).toHaveLength(1);
531 expect(requests).toHaveLength(3);
532 }).pipe(Effect.provide(layer));
533});
534​
535effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
536 const redirects: Array<string | undefined> = [];
537 const fetchFn = (async (
538 input: Parameters<typeof globalThis.fetch>[0],
539 init?: Parameters<typeof globalThis.fetch>[1],
540 ) => {
541 redirects.push(init?.redirect);
542 if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
543 return new Response(null, { status: 302, headers: { location: "https://example.com" } });
544 }) as typeof globalThis.fetch;
545 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
546​
547 return Effect.gen(function* () {
548 const scanner = yield* PortScanner.PortDiscovery;
549 const servers = yield* scanner.scan();
550 expect(servers).toHaveLength(1);
551 expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
552 expect(redirects).toEqual(["manual", "manual"]);
553 }).pipe(Effect.provide(layer));
554});
555​
556effectIt.effect(
557 "excludes HTTP errors, non-navigation responses, and successful non-documents",
558 () => {
559 let pid = 1;
560 let makeResponse = () =>
561 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
562 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
563 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
564 const layer = makeLsofScannerLayer({ pid: () => pid, fetch: fetchFn });
565​
566 return Effect.gen(function* () {
567 const scanner = yield* PortScanner.PortDiscovery;
568 expect(yield* scanner.scan()).toHaveLength(0);
569​
570 pid += 1;
571 makeResponse = () =>
572 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
573 expect(yield* scanner.scan()).toHaveLength(0);
574​
575 pid += 1;
576 makeResponse = () =>
577 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
578 expect(yield* scanner.scan()).toHaveLength(0);
579​
580 pid += 1;
581 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
582 expect(yield* scanner.scan()).toHaveLength(0);
583​
584 pid += 1;
585 makeResponse = () =>
586 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
587 expect(yield* scanner.scan()).toHaveLength(0);
588​
589 pid += 1;
590 makeResponse = () => new Response(null, { status: 302 });
591 expect(yield* scanner.scan()).toHaveLength(0);
592​
593 pid += 1;
594 makeResponse = () =>
595 new Response("<html />", {
596 status: 200,
597 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
598 });
599 expect(yield* scanner.scan()).toHaveLength(1);
600 }).pipe(Effect.provide(layer));
601 },
602);
603​
604effectIt.effect("aborts HTTP and HTTPS probes when they time out", () => {
605 const aborted: string[] = [];
606 const fetchFn = ((
607 input: Parameters<typeof globalThis.fetch>[0],
608 init?: Parameters<typeof globalThis.fetch>[1],
609 ) =>
610 new Promise<Response>((_resolve, reject) => {
611 const signal = init?.signal;
612 const onAbort = () => {
613 aborted.push(String(input));
614 reject(new DOMException("Aborted", "AbortError"));
615 };
616 if (signal?.aborted) {
617 onAbort();
618 } else {
619 signal?.addEventListener("abort", onAbort, { once: true });
620 }
621 })) as typeof globalThis.fetch;
622 const layer = makeLsofScannerLayer({ pid: () => 1234, fetch: fetchFn });
623​
624 return Effect.gen(function* () {
625 const scanner = yield* PortScanner.PortDiscovery;
626 const scanFiber = yield* Effect.forkChild(scanner.scan());
627 yield* TestClock.adjust(Duration.seconds(2));
628 expect(yield* Fiber.join(scanFiber)).toHaveLength(0);
629 expect(aborted).toEqual([
630 `http://localhost:${LSOF_TEST_PORT}/`,
631 `https://localhost:${LSOF_TEST_PORT}/`,
632 ]);
633 }).pipe(Effect.provide(layer));
634});
635​
636effectIt.effect("does not swallow process probe defects", () =>
637 Effect.gen(function* () {
638 const defect = new Error("unexpected process probe defect");
639 const layer = makeProbeFailureLayer(() => Effect.die(defect));
640​
641 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
642 Effect.provide(layer),
643 Effect.exit,
644 );
645​
646 expect(Exit.isFailure(exit)).toBe(true);
647 if (Exit.isFailure(exit)) {
648 expect(Cause.hasDies(exit.cause)).toBe(true);
649 expect(Cause.squash(exit.cause)).toBe(defect);
650 }
651 }),
652);
653​
654effectIt.effect("does not swallow process probe interruption", () =>
655 Effect.gen(function* () {
656 const layer = makeProbeFailureLayer(() => Effect.interrupt);
657​
658 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (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.hasInterruptsOnly(exit.cause)).toBe(true);
666 }
667 }),
668);
669​
670effectIt.effect("idle poll ticks create no spans under the ambient parent", () => {
671 const spanNames: Array<string> = [];
672 const tracer = Tracer.make({
673 span: (options) => {
674 const span = new Tracer.NativeSpan(options);
675 const end = span.end.bind(span);
676 span.end = (endTime, exit) => {
677 end(endTime, exit);
678 spanNames.push(span.name);
679 };
680 return span;
681 },
682 });
683 // No retain call, so every tick takes the idle early-return path.
684 const layer = makeProbeFailureLayer(processProbeFailure);
685​
686 const idlePolls = Effect.gen(function* () {
687 yield* PortScanner.PortDiscovery;
688 yield* TestClock.adjust(Duration.seconds(30));
689 });
690​
691 // Nesting matters: the recording tracer must already be installed when the
692 // ambient span is created, and the layer (which forks the poll fiber) must
693 // build inside that ambient span so a leaked ParentSpan would be observed.
694 // Assertions run after the scope closes so the ambient span has ended.
695 return Effect.gen(function* () {
696 yield* Effect.scoped(
697 Effect.withTracer(
698 Effect.withSpan("PortScannerTest.idlePollTick")(Effect.provide(idlePolls, layer)),
699 tracer,
700 ),
701 );
702 expect(spanNames).toContain("PortScannerTest.idlePollTick");
703 expect(spanNames.filter((name) => name === "PortDiscovery.pollTick")).toHaveLength(0);
704 });
705});