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 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/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 layerTestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
43 run: processProbeFailure,
44});
45
46let integrationListeningPort: number | null = null;
47
48const layerTestIntegrationNet = 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 layerProbeFailure = (
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 layerTestPortDiscovery = PortScanner.layer.pipe(
78 Layer.provide(
79 Layer.mergeAll(
80 layerTestProcessRunner,
81 layerTestIntegrationNet,
82 Layer.succeed(HostProcessPlatform, "win32"),
83 FetchHttpClient.layer,
84 ),
85 ),
86);
87
88const LSOF_TEST_PORT = 43_123;
89
90const layerLsofScanner = (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(layerTestPortDiscovery)("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 = layerLsofScanner({ 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 = layerLsofScanner({ 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 = layerProbeFailure(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 = layerProbeFailure(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 = layerLsofScanner({ 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 = layerLsofScanner({ 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 = layerLsofScanner({ 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("writes no poll span while no client retains the scanner", () => {
446 let pollSpans = 0;
447 const tracer = Tracer.make({
448 span: (options) => {
449 if (options.name === "PortDiscovery.pollTick") pollSpans += 1;
450 return new Tracer.NativeSpan(options);
451 },
452 });
453 const layer = layerProbeFailure(processProbeFailure);
454
455 return Effect.gen(function* () {
456 const scanner = yield* PortScanner.PortDiscovery;
457 yield* TestClock.adjust(Duration.seconds(15));
458 expect(pollSpans).toBe(0);
459
460 yield* scanner.retain;
461 expect(pollSpans).toBe(1);
462 }).pipe(Effect.scoped, Effect.provide(layer), Effect.withTracer(tracer));
463});
464
465effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
466 const requests: string[] = [];
467 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
468 requests.push(String(input));
469 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
470 }) as typeof globalThis.fetch;
471 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
472 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
473 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
474
475 return Effect.gen(function* () {
476 const scanner = yield* PortScanner.PortDiscovery;
477 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
478 const requestCount = requests.length;
479 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
480 expect(requests).toHaveLength(requestCount);
481 }).pipe(Effect.provide(layer));
482});
483
484effectIt.effect("shares a configured root probe with discovered-root classification", () => {
485 const requests: string[] = [];
486 const rootUrl = `http://localhost:${LSOF_TEST_PORT}/`;
487 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
488 requests.push(String(input));
489 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
490 }) as typeof globalThis.fetch;
491 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
492
493 return Effect.gen(function* () {
494 const scanner = yield* PortScanner.PortDiscovery;
495 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
496 expect(requests).toEqual([rootUrl]);
497
498 yield* TestClock.adjust(Duration.seconds(15));
499 expect(yield* scanner.scan([rootUrl])).toHaveLength(1);
500 expect(requests).toEqual([rootUrl, rootUrl]);
501 }).pipe(Effect.provide(layer));
502});
503
504effectIt.effect("starts fresh cache entries after the probing batch completes", () =>
505 Effect.gen(function* () {
506 const baseClock = yield* Clock.Clock;
507 const times = [0, 20_000, 20_000, 20_000];
508 let timeIndex = 0;
509 const currentTimeMillis = () => times[Math.min(timeIndex++, times.length - 1)]!;
510 const clock: Clock.Clock = {
511 ...baseClock,
512 currentTimeMillisUnsafe: currentTimeMillis,
513 currentTimeMillis: Effect.sync(currentTimeMillis),
514 };
515 const requests: string[] = [];
516 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
517 requests.push(String(input));
518 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
519 }) as typeof globalThis.fetch;
520 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
521
522 yield* Effect.gen(function* () {
523 const scanner = yield* PortScanner.PortDiscovery;
524 expect(yield* scanner.scan()).toHaveLength(1);
525 expect(yield* scanner.scan()).toHaveLength(1);
526 expect(requests).toHaveLength(1);
527 }).pipe(Effect.provide(layer), Effect.provideService(Clock.Clock, clock));
528 }),
529);
530
531effectIt.effect("caches a failed web probe until its bounded cache entry expires", () => {
532 let responds = false;
533 const requests: string[] = [];
534 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
535 requests.push(String(input));
536 return responds
537 ? Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }))
538 : Promise.reject(new TypeError("not HTTP"));
539 }) as typeof globalThis.fetch;
540 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
541
542 return Effect.gen(function* () {
543 const scanner = yield* PortScanner.PortDiscovery;
544 expect(yield* scanner.scan()).toHaveLength(0);
545 expect(yield* scanner.scan()).toHaveLength(0);
546 expect(requests).toHaveLength(2);
547
548 responds = true;
549 yield* TestClock.adjust(Duration.seconds(15));
550 expect(yield* scanner.scan()).toHaveLength(1);
551 expect(requests).toHaveLength(3);
552 }).pipe(Effect.provide(layer));
553});
554
555effectIt.effect("falls back to HTTPS and does not follow redirects while probing", () => {
556 const redirects: Array<string | undefined> = [];
557 const fetchFn = (async (
558 input: Parameters<typeof globalThis.fetch>[0],
559 init?: Parameters<typeof globalThis.fetch>[1],
560 ) => {
561 redirects.push(init?.redirect);
562 if (String(input).startsWith("http:")) throw new TypeError("TLS listener");
563 return new Response(null, { status: 302, headers: { location: "https://example.com" } });
564 }) as typeof globalThis.fetch;
565 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
566
567 return Effect.gen(function* () {
568 const scanner = yield* PortScanner.PortDiscovery;
569 const servers = yield* scanner.scan();
570 expect(servers).toHaveLength(1);
571 expect(servers[0]?.url).toBe(`https://localhost:${LSOF_TEST_PORT}`);
572 expect(redirects).toEqual(["manual", "manual"]);
573 }).pipe(Effect.provide(layer));
574});
575
576effectIt.effect(
577 "excludes HTTP errors, non-navigation responses, and successful non-documents",
578 () => {
579 let pid = 1;
580 let makeResponse = () =>
581 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
582 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
583 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
584 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
585
586 return Effect.gen(function* () {
587 const scanner = yield* PortScanner.PortDiscovery;
588 expect(yield* scanner.scan()).toHaveLength(0);
589
590 pid += 1;
591 makeResponse = () =>
592 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
593 expect(yield* scanner.scan()).toHaveLength(0);
594
595 pid += 1;
596 makeResponse = () =>
597 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
598 expect(yield* scanner.scan()).toHaveLength(0);
599
600 pid += 1;
601 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
602 expect(yield* scanner.scan()).toHaveLength(0);
603
604 pid += 1;
605 makeResponse = () =>
606 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
607 expect(yield* scanner.scan()).toHaveLength(0);
608
609 pid += 1;
610 makeResponse = () => new Response(null, { status: 302 });
611 expect(yield* scanner.scan()).toHaveLength(0);
612
613 pid += 1;
614 makeResponse = () =>
615 new Response("<html />", {
616 status: 200,
617 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
618 });
619 expect(yield* scanner.scan()).toHaveLength(1);
620 }).pipe(Effect.provide(layer));
621 },
622);
623
624effectIt.effect("aborts HTTP and HTTPS probes when they time out", () => {
625 const aborted: string[] = [];
626 const fetchFn = ((
627 input: Parameters<typeof globalThis.fetch>[0],
628 init?: Parameters<typeof globalThis.fetch>[1],
629 ) =>
630 new Promise<Response>((_resolve, reject) => {
631 const signal = init?.signal;
632 const onAbort = () => {
633 aborted.push(String(input));
634 reject(new DOMException("Aborted", "AbortError"));
635 };
636 if (signal?.aborted) {
637 onAbort();
638 } else {
639 signal?.addEventListener("abort", onAbort, { once: true });
640 }
641 })) as typeof globalThis.fetch;
642 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
643
644 return Effect.gen(function* () {
645 const scanner = yield* PortScanner.PortDiscovery;
646 const scanFiber = yield* Effect.forkChild(scanner.scan());
647 yield* TestClock.adjust(Duration.seconds(2));
648 expect(yield* Fiber.join(scanFiber)).toHaveLength(0);
649 expect(aborted).toEqual([
650 `http://localhost:${LSOF_TEST_PORT}/`,
651 `https://localhost:${LSOF_TEST_PORT}/`,
652 ]);
653 }).pipe(Effect.provide(layer));
654});
655
656effectIt.effect("does not swallow process probe defects", () =>
657 Effect.gen(function* () {
658 const defect = new Error("unexpected process probe defect");
659 const layer = layerProbeFailure(() => Effect.die(defect));
660
661 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
662 Effect.provide(layer),
663 Effect.exit,
664 );
665
666 expect(Exit.isFailure(exit)).toBe(true);
667 if (Exit.isFailure(exit)) {
668 expect(Cause.hasDies(exit.cause)).toBe(true);
669 expect(Cause.squash(exit.cause)).toBe(defect);
670 }
671 }),
672);
673
674effectIt.effect("does not swallow process probe interruption", () =>
675 Effect.gen(function* () {
676 const layer = layerProbeFailure(() => Effect.interrupt);
677
678 const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
679 Effect.provide(layer),
680 Effect.exit,
681 );
682
683 expect(Exit.isFailure(exit)).toBe(true);
684 if (Exit.isFailure(exit)) {
685 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
686 }
687 }),
688);