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