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

PortScanner.test.ts

906 lines35.1 KB

1// @effect-diagnostics nodeBuiltinImport:off -- the stop test drives real server processes.
2import * as NodeChildProcess from "node:child_process";
3​
4import { it as effectIt } from "@effect/vitest";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import {
7 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
8 PREVIEW_URL_MAX_LENGTH,
9 type DiscoveredLocalServer,
10} from "@t3tools/contracts";
11import * as ProcessGroup from "@t3tools/provider-core/server/processGroup";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as PlatformError from "effect/PlatformError";
20import * as Scope from "effect/Scope";
21import * as TestClock from "effect/testing/TestClock";
22import { expect, vi } from "vite-plus/test";
23import { FetchHttpClient } from "effect/http";
24​
25import * as ProcessRunner from "../processRunner.ts";
26import * as PortScanner from "./PortScanner.ts";
27​
28vi.mock("@t3tools/provider-core/server/processGroup", { spy: true });
29​
30const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (input) =>
31 Effect.fail(
32 new ProcessRunner.ProcessSpawnError({
33 command: input.command,
34 argumentCount: input.args.length,
35 cwd: input.cwd,
36 cause: PlatformError.systemError({
37 _tag: "NotFound",
38 module: "ChildProcess",
39 method: "spawn",
40 description: "PowerShell is not installed in the test environment",
41 }),
42 }),
43 );
44​
45const layerNoProc = FileSystem.layerNoop({});
46​
47const layerProbeFailure = (
48 run: ProcessRunner.ProcessRunner["Service"]["run"],
49 fetch: typeof globalThis.fetch = globalThis.fetch,
50 fileSystem: Layer.Layer<FileSystem.FileSystem> = layerNoProc,
51) =>
52 PortScanner.layer.pipe(
53 Layer.provide(
54 Layer.mergeAll(
55 fileSystem,
56 Layer.succeed(ProcessRunner.ProcessRunner, { run }),
57 Layer.succeed(HostProcess.Platform, "linux"),
58 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))),
59 ),
60 ),
61 );
62​
63const LSOF_TEST_PORT = 43_123;
64​
65const processOutput = (stdout: string): ProcessRunner.ProcessRunOutput => ({
66 stdout,
67 stderr: "",
68 code: ChildProcessSpawner.ExitCode(0),
69 timedOut: false,
70 stdoutTruncated: false,
71 stderrTruncated: false,
72 stdoutInvalidUtf8: false,
73 stderrInvalidUtf8: false,
74});
75​
76const ownedScanner = (processIds: ReadonlyArray<number> = [1234]) =>
77 Effect.tap(PortScanner.PortDiscovery, (scanner) =>
78 scanner.registerTerminalProcesses({
79 threadId: "scanner-thread",
80 terminalId: "scanner-terminal",
81 processIds,
82 }),
83 );
84​
85const layerLsofScanner = (input: {
86 readonly pid: () => number;
87 readonly fetch: typeof globalThis.fetch;
88 readonly stdout?: () => string;
89}) =>
90 PortScanner.layer.pipe(
91 Layer.provide(
92 Layer.mergeAll(
93 layerNoProc,
94 Layer.succeed(ProcessRunner.ProcessRunner, {
95 run: () =>
96 Effect.succeed({
97 stdout: input.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(HostProcess.Platform, "linux"),
108 FetchHttpClient.layer.pipe(
109 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, input.fetch)),
110 ),
111 ),
112 ),
113 );
114​
115effectIt.effect("keeps a full configured URL when the discovered server root fails", () => {
116 const requests: string[] = [];
117 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
118 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
119 const url = String(input);
120 requests.push(url);
121 return Promise.resolve(
122 url === configuredUrl
123 ? new Response("docs", { headers: { "content-type": "text/html" } })
124 : new Response("not found", {
125 status: 404,
126 headers: { "content-type": "text/html" },
127 }),
128 );
129 }) as typeof globalThis.fetch;
130 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
131​
132 return Effect.gen(function* () {
133 const scanner = yield* PortScanner.PortDiscovery;
134 const servers = yield* scanner.scan([configuredUrl]);
135 expect(servers).toHaveLength(1);
136 expect(servers[0]?.url).toBe(configuredUrl);
137 expect(requests).toContain(configuredUrl);
138 }).pipe(Effect.provide(layer));
139});
140​
141effectIt.effect("probes configured custom ports through a canonical loopback host", () => {
142 const customPort = 43_124;
143 const configuredUrl = `http://0.0.0.0:${customPort}/docs`;
144 const expectedUrl = `http://localhost:${customPort}/docs`;
145 const requests: string[] = [];
146 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
147 requests.push(String(input));
148 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
149 }) as typeof globalThis.fetch;
150 const layer = layerProbeFailure(processProbeFailure, fetchFn);
151​
152 return Effect.gen(function* () {
153 const scanner = yield* PortScanner.PortDiscovery;
154 const servers = yield* scanner.scan([configuredUrl]);
155 expect(servers).toHaveLength(1);
156 expect(servers[0]?.host).toBe("localhost");
157 expect(servers[0]?.port).toBe(customPort);
158 expect(servers[0]?.url).toBe(expectedUrl);
159 expect(requests).toEqual([expectedUrl]);
160 }).pipe(Effect.provide(layer));
161});
162​
163effectIt.effect("preserves explicit loopback hosts and bounds wildcard rewrites", () => {
164 const ipv4Url = "https://127.0.0.1:43125/docs";
165 const ipv6Url = "http://[::1]:43126/docs";
166 const wildcardPrefix = "http://0.0.0.0/";
167 const maximumWildcardUrl = `${wildcardPrefix}${"a".repeat(
168 PREVIEW_URL_MAX_LENGTH - wildcardPrefix.length,
169 )}`;
170 const requests: string[] = [];
171 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
172 requests.push(String(input));
173 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
174 }) as typeof globalThis.fetch;
175 const layer = layerProbeFailure(processProbeFailure, fetchFn);
176​
177 return Effect.gen(function* () {
178 const scanner = yield* PortScanner.PortDiscovery;
179 const servers = yield* scanner.scan([ipv4Url, ipv6Url, maximumWildcardUrl]);
180 expect(servers.map((server) => server.url)).toEqual([ipv4Url, ipv6Url]);
181 expect(requests).toEqual([ipv4Url, ipv6Url]);
182 }).pipe(Effect.provide(layer));
183});
184​
185effectIt.effect("projects configured paths independently for simultaneous subscribers", () => {
186 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
187 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
188 let ready = true;
189 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
190 const url = String(input);
191 return Promise.resolve(
192 ready && (url === docsUrl || url === adminUrl)
193 ? new Response("app", { headers: { "content-type": "text/html" } })
194 : new Response("not found", { status: 404 }),
195 );
196 }) as typeof globalThis.fetch;
197 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
198​
199 return Effect.gen(function* () {
200 const scanner = yield* ownedScanner();
201 const docsSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
202 const adminSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
203 yield* scanner.subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, (servers) =>
204 Effect.sync(() => docsSnapshots.push(servers)),
205 );
206 yield* scanner.subscribe({ configuredUrls: [adminUrl], initialSnapshot: [] }, (servers) =>
207 Effect.sync(() => adminSnapshots.push(servers)),
208 );
209 yield* scanner.retain;
210​
211 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
212 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
213​
214 ready = false;
215 yield* TestClock.adjust(Duration.seconds(15));
216 expect(docsSnapshots.at(-1)?.[0]?.url).toBe(docsUrl);
217 expect(adminSnapshots.at(-1)?.[0]?.url).toBe(adminUrl);
218 }).pipe(Effect.scoped, Effect.provide(layer));
219});
220​
221effectIt.effect(
222 "keeps each subscriber's candidates when their combined union exceeds the per-client cap",
223 () => {
224 const firstSubscriberUrls = Array.from(
225 { length: CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS },
226 (_, index) => `http://localhost:${LSOF_TEST_PORT}/app-${index}`,
227 );
228 const secondSubscriberUrl = `http://localhost:${LSOF_TEST_PORT}/app-${CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS}`;
229 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) =>
230 Promise.resolve(
231 String(input) === secondSubscriberUrl
232 ? new Response("app", { headers: { "content-type": "text/html" } })
233 : new Response("not found", { status: 404 }),
234 )) as typeof globalThis.fetch;
235 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
236​
237 return Effect.gen(function* () {
238 const scanner = yield* PortScanner.PortDiscovery;
239 const secondSnapshots: ReadonlyArray<DiscoveredLocalServer>[] = [];
240 yield* scanner.subscribe(
241 { configuredUrls: firstSubscriberUrls, initialSnapshot: [] },
242 () => Effect.void,
243 );
244 yield* scanner.subscribe(
245 { configuredUrls: [secondSubscriberUrl], initialSnapshot: [] },
246 (servers) => Effect.sync(() => secondSnapshots.push(servers)),
247 );
248 yield* scanner.retain;
249​
250 expect(secondSnapshots.at(-1)?.[0]?.url).toBe(secondSubscriberUrl);
251 }).pipe(Effect.scoped, Effect.provide(layer));
252 },
253);
254​
255effectIt.effect("stops probing a subscriber's configured paths after its scope closes", () => {
256 const docsUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
257 const adminUrl = `http://localhost:${LSOF_TEST_PORT}/admin`;
258 const requests: string[] = [];
259 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
260 const url = String(input);
261 requests.push(url);
262 return Promise.resolve(
263 url === docsUrl || url === adminUrl
264 ? new Response("app", { headers: { "content-type": "text/html" } })
265 : new Response("not found", { status: 404 }),
266 );
267 }) as typeof globalThis.fetch;
268 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
269​
270 return Effect.gen(function* () {
271 const scanner = yield* PortScanner.PortDiscovery;
272 const docsScope = yield* Scope.make();
273 yield* scanner
274 .subscribe({ configuredUrls: [docsUrl], initialSnapshot: [] }, () => Effect.void)
275 .pipe(Effect.provideService(Scope.Scope, docsScope));
276 yield* scanner.subscribe(
277 { configuredUrls: [adminUrl], initialSnapshot: [] },
278 () => Effect.void,
279 );
280 yield* scanner.retain;
281 yield* Scope.close(docsScope, Exit.void);
282​
283 requests.length = 0;
284 yield* TestClock.adjust(Duration.seconds(15));
285 expect(requests).toContain(adminUrl);
286 expect(requests).not.toContain(docsUrl);
287 }).pipe(Effect.scoped, Effect.provide(layer));
288});
289​
290effectIt.effect("uses the current configured fragment when readiness comes from cache", () => {
291 const requests: string[] = [];
292 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
293 requests.push(String(input));
294 return Promise.resolve(new Response("docs", { headers: { "content-type": "text/html" } }));
295 }) as typeof globalThis.fetch;
296 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
297 const oldUrl = `http://localhost:${LSOF_TEST_PORT}/docs#old`;
298 const newUrl = `http://localhost:${LSOF_TEST_PORT}/docs#new`;
299​
300 return Effect.gen(function* () {
301 const scanner = yield* PortScanner.PortDiscovery;
302 expect((yield* scanner.scan([oldUrl]))[0]?.url).toBe(oldUrl);
303 const requestCount = requests.length;
304 expect((yield* scanner.scan([newUrl]))[0]?.url).toBe(newUrl);
305 expect(requests).toHaveLength(requestCount);
306 }).pipe(Effect.provide(layer));
307});
308​
309effectIt.effect(
310 "probes only a configured HTTPS URL, keeps it for an owned listener when the check fails, and does not follow redirects",
311 () => {
312 const configuredUrl = `https://localhost:${LSOF_TEST_PORT}/app`;
313 const requests: Array<readonly [string, string | undefined]> = [];
314 let respond = async () =>
315 new Response(null, { status: 302, headers: { location: "https://example.com" } });
316 const fetchFn = (async (
317 input: Parameters<typeof globalThis.fetch>[0],
318 init?: Parameters<typeof globalThis.fetch>[1],
319 ) => {
320 requests.push([String(input), init?.redirect]);
321 return respond();
322 }) as typeof globalThis.fetch;
323 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn });
324​
325 return Effect.gen(function* () {
326 const scanner = yield* ownedScanner();
327 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
328 { pid: 1234, url: configuredUrl },
329 ]);
330​
331 respond = async () => new Response("unavailable", { status: 503 });
332 yield* TestClock.adjust(Duration.seconds(15));
333 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
334 { pid: 1234, url: configuredUrl },
335 ]);
336​
337 respond = () => Promise.reject(new TypeError("fetch failed"));
338 yield* TestClock.adjust(Duration.seconds(15));
339 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
340 { pid: 1234, url: configuredUrl },
341 ]);
342 expect(requests).toEqual(Array.from({ length: 3 }, () => [configuredUrl, "manual"]));
343 }).pipe(Effect.provide(layer));
344 },
345);
346​
347effectIt.effect("discovers owned listeners without sending HTTP or TLS probes", () => {
348 const owned = `p1234\ncnode\nn[::1]:${LSOF_TEST_PORT}\n`;
349 const unowned = `p5678\ncrpc\nn127.0.0.1:${LSOF_TEST_PORT}\n`;
350 let stdout = unowned;
351 const requests: string[] = [];
352 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
353 requests.push(String(input));
354 return Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } }));
355 }) as typeof globalThis.fetch;
356 const layer = layerLsofScanner({ pid: () => 1234, fetch: fetchFn, stdout: () => stdout });
357​
358 return Effect.gen(function* () {
359 const scanner = yield* ownedScanner();
360 expect(yield* scanner.scan()).toHaveLength(0);
361 stdout = `${owned}${unowned}`;
362 expect(yield* scanner.scan()).toHaveLength(0);
363 expect(requests).toEqual([]);
364​
365 stdout = owned;
366 expect(yield* scanner.scan()).toHaveLength(1);
367 expect(requests).toEqual([]);
368​
369 yield* scanner.unregisterTerminal({
370 threadId: "scanner-thread",
371 terminalId: "scanner-terminal",
372 });
373 expect(yield* scanner.scan()).toHaveLength(0);
374 expect(requests).toEqual([]);
375 }).pipe(Effect.provide(layer));
376});
377​
378effectIt.effect(
379 "excludes configured URLs answering with HTTP errors, non-navigation responses, or non-documents",
380 () => {
381 let pid = 1;
382 let makeResponse = () =>
383 new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
384 const fetchFn = ((_input: Parameters<typeof globalThis.fetch>[0]) =>
385 Promise.resolve(makeResponse())) as typeof globalThis.fetch;
386 const layer = layerLsofScanner({ pid: () => pid, fetch: fetchFn });
387 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/`;
388​
389 return Effect.gen(function* () {
390 const scanner = yield* PortScanner.PortDiscovery;
391 const scan = () => scanner.scan([configuredUrl]);
392 expect(yield* scan()).toHaveLength(0);
393​
394 pid += 1;
395 makeResponse = () =>
396 new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
397 expect(yield* scan()).toHaveLength(0);
398​
399 pid += 1;
400 makeResponse = () =>
401 new Response("ready", { status: 200, headers: { "content-type": "text/plain" } });
402 expect(yield* scan()).toHaveLength(0);
403​
404 pid += 1;
405 makeResponse = () => new Response(null, { status: 304, headers: { location: "/cached" } });
406 expect(yield* scan()).toHaveLength(0);
407​
408 pid += 1;
409 makeResponse = () =>
410 new Response(null, { status: 204, headers: { "content-type": "text/html" } });
411 expect(yield* scan()).toHaveLength(0);
412​
413 pid += 1;
414 makeResponse = () => new Response(null, { status: 302 });
415 expect(yield* scan()).toHaveLength(0);
416​
417 pid += 1;
418 makeResponse = () =>
419 new Response("<html />", {
420 status: 200,
421 headers: { "content-type": "application/xhtml+xml; charset=utf-8" },
422 });
423 expect(yield* scan()).toHaveLength(1);
424 }).pipe(Effect.provide(layer));
425 },
426);
427​
428const PROC_NET_TCP = ` sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
429 0: 0100007F:223D 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5001 1 0000000000000000 100 0 0 10 0
430 1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5002 1 0000000000000000 100 0 0 10 0
431 2: 0100007F:223D 0100007F:C350 01 00000000:00000000 00:00000000 00000000 1000 0 5003 1 0000000000000000 20 4 30 10 -1
432 3: 0A00000F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5005 1 0000000000000000 100 0 0 10 0
433`;
434const PROC_NET_TCP6 = ` sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
435 0: 00000000000000000000000000000000:0BB9 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5004 1 0000000000000000 100 0 0 10 0
436`;
437​
438effectIt.effect(
439 "reads Linux listeners from /proc when lsof is missing, and stops spawning it",
440 () => {
441 let lsofSpawns = 0;
442 const fdWalks: string[] = [];
443 const procFiles: Record<string, string> = {
444 "/proc/net/tcp": PROC_NET_TCP,
445 "/proc/net/tcp6": PROC_NET_TCP6,
446 "/proc/4242/comm": "python3\n",
447 };
448 const procFds: Record<string, Record<string, string>> = {
449 "4242": { "0": "/dev/null", "3": "socket:[5001]" },
450 "77": { "5": "socket:[9999]" },
451 };
452 const missing = FileSystem.makeNoop({});
453 const fileSystem = FileSystem.layerNoop({
454 readFileString: (path) => {
455 const content = procFiles[path];
456 return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
457 },
458 readDirectory: (path) => {
459 if (path === "/proc") return Effect.succeed(["self", "77", "4242"]);
460 const pid = /^\/proc\/(\d+)\/fd$/.exec(path)?.[1];
461 const fds = pid === undefined ? undefined : procFds[pid];
462 if (pid === undefined || fds === undefined) return missing.readDirectory(path);
463 fdWalks.push(pid);
464 return Effect.succeed(Object.keys(fds));
465 },
466 readLink: (path) => {
467 const [, pid, fd] = /^\/proc\/(\d+)\/fd\/(\d+)$/.exec(path) ?? [];
468 const target = pid && fd ? procFds[pid]?.[fd] : undefined;
469 return target === undefined ? missing.readLink(path) : Effect.succeed(target);
470 },
471 });
472 const requests: string[] = [];
473 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
474 requests.push(String(input));
475 return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
476 }) as typeof globalThis.fetch;
477 const layer = layerProbeFailure(
478 (input) => {
479 lsofSpawns += 1;
480 return processProbeFailure(input);
481 },
482 fetchFn,
483 fileSystem,
484 );
485​
486 return Effect.gen(function* () {
487 const scanner = yield* ownedScanner([4242]);
488 const first = yield* scanner.scan();
489 expect(
490 first.map(({ port, pid, processName, url }) => ({ port, pid, processName, url })),
491 ).toEqual([{ port: 8765, pid: 4242, processName: "python3", url: "http://localhost:8765" }]);
492 yield* scanner.scan();
493 expect(lsofSpawns).toBe(1);
494 expect(fdWalks).toEqual(["77", "4242", "77", "4242"]);
495 yield* scanner.scan();
496 yield* scanner.scan();
497 expect(fdWalks).toEqual(["77", "4242", "77", "4242", "77", "4242"]);
498 expect(requests).toEqual([]);
499 }).pipe(Effect.provide(layer));
500 },
501);
502​
503effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => {
504 let ipv6Fails = true;
505 const requests: string[] = [];
506 const fetchFn = ((input: Parameters<typeof globalThis.fetch>[0]) => {
507 requests.push(String(input));
508 return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } }));
509 }) as typeof globalThis.fetch;
510 const layer = PortScanner.layer.pipe(
511 Layer.provide(
512 Layer.mergeAll(
513 layerNoProc,
514 Layer.succeed(ProcessRunner.ProcessRunner, {
515 run: (input) => {
516 if (input.command === "tasklist.exe") {
517 return Effect.succeed(
518 processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'),
519 );
520 }
521 const isIpv6 = input.args.includes("tcpv6");
522 return Effect.succeed({
523 stdout: isIpv6
524 ? ""
525 : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n",
526 stderr: "",
527 code: isIpv6 && ipv6Fails ? ChildProcessSpawner.ExitCode(1) : null,
528 timedOut: false,
529 stdoutTruncated: false,
530 stderrTruncated: false,
531 stdoutInvalidUtf8: false,
532 stderrInvalidUtf8: false,
533 });
534 },
535 }),
536 Layer.succeed(HostProcess.Platform, "win32"),
537 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
538 ),
539 ),
540 );
541​
542 return Effect.gen(function* () {
543 const scanner = yield* PortScanner.PortDiscovery;
544 yield* scanner.registerTerminalProcesses({
545 threadId: "scanner-thread",
546 terminalId: "scanner-terminal",
547 processIds: [1234],
548 });
549 expect(yield* scanner.scan()).toEqual([]);
550 ipv6Fails = false;
551 expect(yield* scanner.scan()).toMatchObject([
552 { port: 5173, pid: 1234, processName: "node", url: "http://localhost:5173" },
553 ]);
554 expect(requests).toEqual([]);
555 }).pipe(Effect.provide(layer));
556});
557​
558effectIt.effect("rechecks the socket owner before stopping a Linux server without lsof", () => {
559 let holder = "4242";
560 const missing = FileSystem.makeNoop({});
561 const layer = layerProbeFailure(
562 (input) =>
563 input.command === "lsof"
564 ? processProbeFailure(input)
565 : Effect.succeed(processOutput("4242 1 4300\n5000 1 5300\n")),
566 () => Promise.resolve(new Response("app", { headers: { "content-type": "text/html" } })),
567 FileSystem.layerNoop({
568 readFileString: (path) => {
569 if (path === "/proc/net/tcp") {
570 return Effect.succeed(PROC_NET_TCP.split("\n").slice(0, 2).join("\n"));
571 }
572 if (/^\/proc\/(4242|5000)\/comm$/.test(path)) return Effect.succeed("node\n");
573 if (/^\/proc\/(4242|5000)\/environ$/.test(path)) {
574 return Effect.succeed(`${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`);
575 }
576 return missing.readFileString(path);
577 },
578 readDirectory: (path) => {
579 if (path === "/proc") return Effect.succeed(["4242", "5000"]);
580 if (/^\/proc\/(4242|5000)\/fd$/.test(path)) {
581 return Effect.succeed(path === `/proc/${holder}/fd` ? ["3"] : []);
582 }
583 return missing.readDirectory(path);
584 },
585 readLink: (path) =>
586 path === `/proc/${holder}/fd/3` ? Effect.succeed("socket:[5001]") : missing.readLink(path),
587 }),
588 );
589​
590 return Effect.gen(function* () {
591 const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => {
592 throw Object.assign(new Error("No such process"), { code: "ESRCH" });
593 });
594 yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore()));
595 const scanner = yield* PortScanner.PortDiscovery;
596 expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, port: 8765 }]);
597​
598 // The socket outlives its original holder. Its old pid now belongs to another agent job.
599 holder = "5000";
600 const result = yield* scanner
601 .stopServer({ pid: 4242, port: 8765 })
602 .pipe(Effect.match({ onFailure: (error) => error.reason, onSuccess: () => null }));
603 expect(signal).not.toHaveBeenCalled();
604 expect(result).toBe("not-found");
605 expect(yield* scanner.scan()).toMatchObject([{ pid: 5000, port: 8765 }]);
606 yield* scanner.stopServer({ pid: 5000, port: 8765 });
607 expect(signal).toHaveBeenCalledExactlyOnceWith(5300, "SIGTERM");
608 }).pipe(Effect.provide(layer));
609});
610​
611effectIt.effect.each(["linux", "darwin", "win32"] as const)(
612 "reads no listeners on %s while T3CODE_PORT_DISCOVERY=0, and still probes configured URLs",
613 (platform) => {
614 const configuredUrl = `http://localhost:${LSOF_TEST_PORT}/docs`;
615 const commands: string[] = [];
616 const fileReads: string[] = [];
617 const requests: string[] = [];
618 const missing = FileSystem.makeNoop({});
619 const layer = PortScanner.layer.pipe(
620 Layer.provide(
621 Layer.mergeAll(
622 FileSystem.layerNoop({
623 readFileString: (path) => {
624 fileReads.push(path);
625 return missing.readFileString(path);
626 },
627 readDirectory: (path) => {
628 fileReads.push(path);
629 return missing.readDirectory(path);
630 },
631 }),
632 Layer.succeed(ProcessRunner.ProcessRunner, {
633 run: (input) => {
634 commands.push(input.command);
635 return Effect.succeed(processOutput(`p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`));
636 },
637 }),
638 Layer.succeed(HostProcess.Platform, platform),
639 Layer.succeed(HostProcess.Environment, { T3CODE_PORT_DISCOVERY: "0" }),
640 FetchHttpClient.layer.pipe(
641 Layer.provide(
642 Layer.succeed(FetchHttpClient.Fetch, (input) => {
643 requests.push(String(input));
644 return Promise.resolve(
645 new Response("docs", { headers: { "content-type": "text/html" } }),
646 );
647 }),
648 ),
649 ),
650 ),
651 ),
652 );
653​
654 return Effect.gen(function* () {
655 const scanner = yield* ownedScanner();
656 scanner.trackAgent();
657 expect(yield* scanner.scan()).toEqual([]);
658 expect(yield* scanner.scan([configuredUrl])).toMatchObject([
659 { port: LSOF_TEST_PORT, pid: null, terminal: null, url: configuredUrl },
660 ]);
661 expect(requests).toEqual([configuredUrl]);
662 expect(commands).toEqual([]);
663 expect(fileReads).toEqual([]);
664 }).pipe(Effect.provide(layer));
665 },
666);
667​
668effectIt.effect.each(["linux", "darwin"] as const)(
669 "attributes listeners to the agent thread in their environment on %s, after the agent exits",
670 (platform) => {
671 const agentPort = 43_124;
672 const otherPort = 43_125;
673 const agentListener = `p4242\ncnode\nn127.0.0.1:${agentPort}\n`;
674 const otherListener = `p5000\ncpostgres\nn127.0.0.1:${otherPort}\n`;
675 let lsofStdout = otherListener;
676 let lsofFails = false;
677 let environmentFails = false;
678 let lsofCalls = 0;
679 let environmentReads = 0;
680 const requests: string[] = [];
681 const missing = FileSystem.makeNoop({});
682 const procEnviron: Record<string, string> = {
683 "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`,
684 "/proc/5000/environ": "PATH=/usr/bin\0",
685 };
686 const layer = PortScanner.layer.pipe(
687 Layer.provide(
688 Layer.mergeAll(
689 FileSystem.layerNoop({
690 readFileString: (path) => {
691 const content = procEnviron[path];
692 if (content === undefined) return missing.readFileString(path);
693 environmentReads += 1;
694 return Effect.succeed(content);
695 },
696 }),
697 Layer.succeed(ProcessRunner.ProcessRunner, {
698 run: (input) => {
699 if (input.command === "lsof") {
700 lsofCalls += 1;
701 return lsofFails
702 ? Effect.fail(
703 new ProcessRunner.ProcessTimeoutError({
704 command: input.command,
705 argumentCount: input.args.length,
706 cwd: input.cwd,
707 timeoutMs: 5_000,
708 }),
709 )
710 : Effect.succeed(processOutput(lsofStdout));
711 }
712 // A direct child of this process, so stop refuses it without signaling anything.
713 if (input.args[0] === "-A") {
714 return Effect.succeed(processOutput(`4242 ${process.pid} 4242\n`));
715 }
716 if (environmentFails) {
717 return Effect.fail(
718 new ProcessRunner.ProcessTimeoutError({
719 command: input.command,
720 argumentCount: input.args.length,
721 timeoutMs: 5_000,
722 }),
723 );
724 }
725 environmentReads += 1;
726 return Effect.succeed(
727 processOutput(
728 ` 4242 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent HOME=/Users/dev\n` +
729 " 5000 postgres -D /data PATH=/usr/bin\n",
730 ),
731 );
732 },
733 }),
734 Layer.succeed(HostProcess.Platform, platform),
735 FetchHttpClient.layer.pipe(
736 Layer.provide(
737 Layer.succeed(FetchHttpClient.Fetch, (input) => {
738 requests.push(String(input));
739 return Promise.resolve(
740 new Response("app", { headers: { "content-type": "text/html" } }),
741 );
742 }),
743 ),
744 ),
745 ),
746 ),
747 );
748​
749 return Effect.gen(function* () {
750 const scanner = yield* PortScanner.PortDiscovery;
751 // Startup reads listeners once. With none marked, later scans stay idle.
752 expect(yield* scanner.scan()).toEqual([]);
753 expect(yield* scanner.scan()).toEqual([]);
754 expect(lsofCalls).toBe(1);
755​
756 // The agent exits before any client looks, and the first read fails; its server is still
757 // found.
758 lsofStdout = `${agentListener}${otherListener}`;
759 scanner.trackAgent()();
760 lsofFails = true;
761 expect(yield* scanner.scan()).toEqual([]);
762 lsofFails = false;
763 if (platform === "darwin") {
764 environmentFails = true;
765 expect(yield* scanner.scan()).toEqual([]);
766 environmentFails = false;
767 }
768 expect(yield* scanner.scan()).toMatchObject([
769 { port: agentPort, pid: 4242, terminal: null, agent: { threadId: "thread-agent" } },
770 ]);
771 expect(requests).toEqual([]);
772​
773 expect(yield* scanner.scan()).toHaveLength(1);
774 expect(environmentReads).toBe(2);
775​
776 // Stop reads its target's environment again rather than trust the cache, and still finds it.
777 const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: agentPort }));
778 expect(stop.reason).toBe("shared-group");
779 expect(environmentReads).toBe(3);
780​
781 lsofStdout = otherListener;
782 expect(yield* scanner.scan()).toEqual([]);
783 const lsofCallsAfterExit = lsofCalls;
784 expect(yield* scanner.scan()).toEqual([]);
785 expect(lsofCalls).toBe(lsofCallsAfterExit);
786 }).pipe(Effect.provide(layer));
787 },
788);
789​
790effectIt.effect("stops only a job's own process group", () =>
791 Effect.sync(() => {
792 const serverPid = 100;
793 const rows = [
794 { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server
795 { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job
796 { pid: serverPid, ppid: 10, pgid: 10 },
797 { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI
798 { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own
799 { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell
800 { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &`
801 { pid: 401, ppid: 400, pgid: 400 },
802 { pid: 500, ppid: serverPid, pgid: 500 }, // terminal shell
803 { pid: 600, ppid: 500, pgid: 600 }, // terminal job
804 ];
805 const table = new Map(rows.map((row) => [row.pid, row]));
806 expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400);
807 expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600);
808 for (const pid of [20, 210, 500, 999]) {
809 expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull();
810 }
811 }),
812);
813​
814const AGENT_SERVER_SCRIPT = `
815const server = require("node:http").createServer((_, response) => {
816 response.writeHead(200, { "content-type": "text/html" });
817 response.end("<html></html>");
818});
819server.listen(0, "127.0.0.1", () => {
820 process.stdout.write(process.pid + " " + server.address().port + "\\n");
821});
822`;
823​
824/**
825 * A real HTML server with an agent's environment, started the way an agent's tool shell starts a
826 * job: under a detached shell with job control, in a group of its own. Release kills only the pids
827 * it started.
828 */
829const agentServer = () =>
830 Effect.acquireRelease(
831 Effect.callback<{
832 readonly child: NodeChildProcess.ChildProcess;
833 readonly pid: number;
834 readonly port: number;
835 readonly exited: Promise<void>;
836 }>((resume) => {
837 const env = { ...process.env, [PortScanner.AGENT_THREAD_ENV]: "thread-live" };
838 // dash ignores `set -m` without a terminal; bash, like agent tool shells, honors it.
839 const child = NodeChildProcess.spawn(
840 "bash",
841 ["-c", 'set -m; "$0" -e "$1" & wait', process.execPath, AGENT_SERVER_SCRIPT],
842 { detached: true, env, stdio: ["ignore", "pipe", "ignore"] },
843 );
844 const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
845 child.once("error", (error) => resume(Effect.die(error)));
846 child.stdout?.once("data", (chunk) => {
847 const [pid, port] = String(chunk).trim().split(" ").map(Number);
848 resume(Effect.succeed({ child, pid: pid!, port: port!, exited }));
849 });
850 }),
851 ({ child, pid }) =>
852 Effect.sync(() => {
853 for (const target of [pid, child.pid]) {
854 try {
855 if (target !== undefined) process.kill(target, "SIGKILL");
856 } catch {}
857 }
858 }),
859 );
860​
861const isRunning = (pid: number): boolean => {
862 try {
863 process.kill(pid, 0);
864 return true;
865 } catch {
866 return false;
867 }
868};
869​
870effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
871 "stops an agent's server through its job's group, and only a listed server",
872 () =>
873 Effect.gen(function* () {
874 const scanner = yield* PortScanner.PortDiscovery;
875 yield* Effect.acquireRelease(Effect.sync(scanner.trackAgent), (release) =>
876 Effect.sync(release),
877 );
878 const job = yield* agentServer();
879​
880 expect(yield* scanner.scan()).toEqual(
881 expect.arrayContaining([
882 expect.objectContaining({
883 pid: job.pid,
884 port: job.port,
885 agent: { threadId: "thread-live" },
886 }),
887 ]),
888 );
889​
890 const unlisted = yield* Effect.flip(scanner.stopServer({ pid: process.pid, port: job.port }));
891 expect(unlisted.reason).toBe("not-found");
892​
893 yield* scanner.stopServer({ pid: job.pid, port: job.port });
894 // The shell waits on its job, so it exits once the job has.
895 yield* Effect.promise(() => job.exited);
896 expect(isRunning(job.pid)).toBe(false);
897 }).pipe(
898 Effect.scoped,
899 Effect.provide(
900 PortScanner.layer.pipe(
901 Layer.provide(ProcessRunner.layer),
902 Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
903 ),
904 ),
905 ),
906);