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

PortScanner.test.ts

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