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

PortScanner.test.ts

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