Open History to see the last commit
1import {
2 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
3 PREVIEW_URL_MAX_LENGTH,
4 ThreadId,
5 type DiscoveredLocalServer,
6} from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
9import * as Cause from "effect/Cause";
10import * as Clock from "effect/Clock";
11import * as Context from "effect/Context";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PlatformError from "effect/PlatformError";
18import * as Ref from "effect/Ref";
19import * as Schedule from "effect/Schedule";
20import * as Scope from "effect/Scope";
21import * as Semaphore from "effect/Semaphore";
22import { FetchHttpClient, HttpClient } from "effect/http";
23
24import * as ProcessRunner from "../processRunner.ts";
25
26export class PortDiscovery extends Context.Service<
27 PortDiscovery,
28 {
29 readonly scan: (
30 configuredUrls?: ReadonlyArray<string>,
31 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
32 readonly subscribe: (
33 input: {
34 readonly configuredUrls: ReadonlyArray<string>;
35 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
36 },
37 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
38 ) => Effect.Effect<void, never, Scope.Scope>;
39 readonly retain: Effect.Effect<void, never, Scope.Scope>;
40 readonly registerTerminalProcesses: (input: {
41 readonly threadId: string;
42 readonly terminalId: string;
43 readonly processIds: ReadonlyArray<number>;
44 }) => Effect.Effect<void>;
45 readonly unregisterTerminal: (input: {
46 readonly threadId: string;
47 readonly terminalId: string;
48 }) => Effect.Effect<void>;
49 }
50>()("t3/preview/PortScanner/PortDiscovery") {}
51
52const POLL_INTERVAL = Duration.seconds(3);
53const LSOF_TIMEOUT_MS = 5_000;
54const PROC_FD_WALK_LIMIT = 50_000;
55const SOCKET_OWNER_ATTEMPTS = 3;
56const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
57/** `netstat -ano` lists every connection, not just listeners; ~80 bytes per row, sized for ~200k rows. */
58const WINDOWS_NETSTAT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
59const WEB_PROBE_TIMEOUT = Duration.seconds(1);
60const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
61/** Bounds how long a cached Windows image name can outlive its process if Windows reuses the PID. */
62const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
63const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
64const WEB_PROBE_CONCURRENCY = 16;
65const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
66
67type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
68
69interface ListenerSubscription {
70 readonly configuredUrls: ReadonlyArray<string>;
71 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
72}
73
74interface ScannerState {
75 readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
76 readonly terminalProcesses: ReadonlyMap<
77 string,
78 {
79 readonly owner: TerminalProcessOwner;
80 readonly processIds: ReadonlySet<number>;
81 }
82 >;
83 readonly retainCount: number;
84}
85
86interface TerminalProcessOwner {
87 readonly threadId: ThreadId;
88 readonly terminalId: string;
89}
90
91interface WebProbeCacheEntry {
92 readonly pid: number | null;
93 readonly isWeb: boolean;
94 readonly expiresAtMillis: number;
95}
96
97interface WebProbeGroup {
98 readonly server: DiscoveredLocalServer;
99 readonly urls: ReadonlyArray<string>;
100 readonly configuredKey: string | null;
101}
102
103interface WebProbeSnapshot {
104 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
105 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
106}
107
108const terminalOwnerKey = (owner: {
109 readonly threadId: string;
110 readonly terminalId: string;
111}): string => `${owner.threadId}\u0000${owner.terminalId}`;
112
113const parseConfiguredUrl = (raw: string): URL | null => {
114 try {
115 const url = new URL(raw);
116 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
117 if (!isLoopbackHost(url.hostname)) return null;
118 return url;
119 } catch {
120 return null;
121 }
122};
123
124const localServerKey = (host: string, port: number): string =>
125 `${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
126
127const urlPort = (url: URL): number =>
128 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
129
130const webProbeCacheKey = (raw: string): string => {
131 const url = new URL(raw);
132 url.hash = "";
133 return url.href;
134};
135
136const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
137 ...new Set(
138 urls
139 .slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
140 .filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
141 .map(parseConfiguredUrl)
142 .filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
143 .map((url) => {
144 if (url.hostname === "0.0.0.0") url.hostname = "localhost";
145 return url.href;
146 })
147 .filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
148 ),
149];
150
151const projectWebProbeSnapshot = (
152 snapshot: WebProbeSnapshot,
153 configuredUrls: ReadonlyArray<string>,
154): ReadonlyArray<DiscoveredLocalServer> => {
155 const visibleByServer = new Map<string, DiscoveredLocalServer>();
156 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
157 const url = new URL(raw);
158 const port = urlPort(url);
159 const serverKey = localServerKey(url.hostname, port);
160 if (visibleByServer.has(serverKey)) continue;
161 const configured = snapshot.configured.get(webProbeCacheKey(raw));
162 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
163 }
164 for (const server of snapshot.discovered) {
165 const key = localServerKey(server.host, server.port);
166 if (!visibleByServer.has(key)) visibleByServer.set(key, server);
167 }
168 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
169};
170
171const parseLsofOutput = (
172 raw: string,
173 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
174): ReadonlyArray<DiscoveredLocalServer> => {
175 const seen = new Map<string, DiscoveredLocalServer>();
176 let pid: number | null = null;
177 let processName: string | null = null;
178
179 for (const line of raw.split("\n")) {
180 if (line.length === 0) continue;
181 const tag = line.charAt(0);
182 const value = line.slice(1);
183 if (tag === "p") {
184 const parsed = Number.parseInt(value, 10);
185 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
186 processName = null;
187 continue;
188 }
189 if (tag === "c") {
190 processName = value.trim() || null;
191 continue;
192 }
193 if (tag === "n") {
194 const portMatch = parsePortFromLsofName(value);
195 if (portMatch == null) continue;
196 const url = `http://localhost:${portMatch}`;
197 const key = `localhost:${portMatch}`;
198 const terminal = pid === null ? null : (terminalByProcessId.get(pid) ?? null);
199 const existing = seen.get(key);
200 if (existing) {
201 if (terminal === null) seen.set(key, { ...existing, terminal: null });
202 continue;
203 }
204 seen.set(key, {
205 host: "localhost",
206 port: portMatch,
207 url,
208 processName,
209 pid,
210 terminal,
211 });
212 }
213 }
214
215 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
216};
217
218const parsePortFromLsofName = (name: string): number | null => {
219 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
220 if (trimmed.length === 0) return null;
221 const lastColon = trimmed.lastIndexOf(":");
222 if (lastColon < 0) return null;
223 const hostPart = trimmed.slice(0, lastColon);
224 const portPart = trimmed.slice(lastColon + 1);
225 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
226 const port = Number.parseInt(portPart, 10);
227 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
228 return port;
229};
230
231const parseWindowsListenerLine = (
232 line: string,
233): {
234 readonly host: string;
235 readonly port: number;
236 readonly pid: number | null;
237 readonly processName: string | null;
238} | null => {
239 const trimmed = line.trim();
240 if (trimmed.length === 0) return null;
241
242 if (trimmed.includes("|")) {
243 const [hostRaw, portRaw, pidRaw, processNameRaw] = trimmed.split("|", 4);
244 const host = hostRaw?.trim() ?? "";
245 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
246 const port = Number(portRaw);
247 const pid = Number(pidRaw);
248 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
249 return {
250 host,
251 port,
252 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
253 processName: processNameRaw?.trim() || null,
254 };
255 }
256
257 // Foreign port `:0` identifies a listening TCP socket regardless of Windows locale.
258 const fields = trimmed.split(/\s+/);
259 if (fields.length < 4 || fields[0]?.toUpperCase() !== "TCP") return null;
260 const localEndpoint = fields[1] ?? "";
261 const foreignEndpoint = fields[2] ?? "";
262 if (!foreignEndpoint.endsWith(":0")) return null;
263 const lastColon = localEndpoint.lastIndexOf(":");
264 if (lastColon <= 0) return null;
265 const host = localEndpoint.slice(0, lastColon);
266 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
267 const port = Number(localEndpoint.slice(lastColon + 1));
268 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
269 const pid = Number(fields.at(-1));
270 return {
271 host,
272 port,
273 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
274 processName: null,
275 };
276};
277
278const exitedWithError = (result: ProcessRunner.ProcessRunOutput): boolean =>
279 result.code !== null && result.code !== 0;
280
281const parseTasklistProcessName = (raw: string, pid: number): string | null => {
282 for (const line of raw.split(/\r?\n/g)) {
283 const match = /^"([^"]*)","(\d+)"/.exec(line.trim());
284 if (match && Number(match[2]) === pid) return match[1]!.replace(/\.exe$/i, "") || null;
285 }
286 return null;
287};
288
289const parseWindowsListenerOutput = (
290 raw: string,
291 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
292): ReadonlyArray<DiscoveredLocalServer> => {
293 const seen = new Map<number, DiscoveredLocalServer>();
294 for (const line of raw.split(/\r?\n/g)) {
295 const parsed = parseWindowsListenerLine(line);
296 if (!parsed) continue;
297 const { port, pid: normalizedPid, processName } = parsed;
298 const terminal =
299 normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null);
300 const existing = seen.get(port);
301 if (existing) {
302 if (terminal === null) seen.set(port, { ...existing, terminal: null });
303 continue;
304 }
305 seen.set(port, {
306 host: "localhost",
307 port,
308 url: `http://localhost:${port}`,
309 processName,
310 pid: normalizedPid,
311 terminal,
312 });
313 }
314 return [...seen.values()].toSorted((left, right) => left.port - right.port);
315};
316
317const PROC_TCP_LISTEN = "0A";
318
319/** Each 32-bit word of the hex address is little-endian. */
320const procLocalAddress = (hex: string): boolean => {
321 if (hex.length === 8) {
322 return hex === "00000000" || hex.endsWith("7F");
323 }
324 if (hex.length !== 32) return false;
325 if (hex === "0".repeat(32) || hex === `${"0".repeat(24)}01000000`) return true;
326 return hex.startsWith(`${"0".repeat(16)}FFFF0000`) && procLocalAddress(hex.slice(24));
327};
328
329const parseProcNetTcp = (
330 raw: string,
331): ReadonlyArray<{ readonly port: number; readonly inode: string }> => {
332 const listeners: Array<{ port: number; inode: string }> = [];
333 for (const line of raw.split("\n").slice(1)) {
334 const fields = line.trim().split(/\s+/);
335 const [address, portHex] = fields[1]?.split(":") ?? [];
336 if (fields[3] !== PROC_TCP_LISTEN || !address || !portHex) continue;
337 if (!procLocalAddress(address.toUpperCase())) continue;
338 const port = Number.parseInt(portHex, 16);
339 const inode = fields[9];
340 if (!Number.isInteger(port) || port <= 0 || port >= 65536 || !inode) continue;
341 listeners.push({ port, inode });
342 }
343 return listeners;
344};
345
346const serversEqual = (
347 left: ReadonlyArray<DiscoveredLocalServer>,
348 right: ReadonlyArray<DiscoveredLocalServer>,
349): boolean => {
350 if (left.length !== right.length) return false;
351 for (let i = 0; i < left.length; i += 1) {
352 const a = left[i];
353 const b = right[i];
354 if (!a || !b) return false;
355 if (
356 a.host !== b.host ||
357 a.port !== b.port ||
358 a.url !== b.url ||
359 a.processName !== b.processName ||
360 a.pid !== b.pid ||
361 a.terminal?.threadId !== b.terminal?.threadId ||
362 a.terminal?.terminalId !== b.terminal?.terminalId
363 ) {
364 return false;
365 }
366 }
367 return true;
368};
369
370const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
371 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
372
373/** @public */
374export const make = Effect.gen(function* PortDiscoveryMake() {
375 const processRunner = yield* ProcessRunner.ProcessRunner;
376 const fileSystem = yield* FileSystem.FileSystem;
377 const hostPlatform = yield* HostProcess.Platform;
378 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
379 const stateRef = yield* Ref.make<ScannerState>({
380 listeners: new Map(),
381 terminalProcesses: new Map(),
382 retainCount: 0,
383 });
384 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
385 const scanSemaphore = yield* Semaphore.make(1);
386 const lsofMissingRef = yield* Ref.make(false);
387 const windowsProcessNamesRef = yield* Ref.make<
388 ReadonlyMap<number, { readonly name: string | null; readonly expiresAtMillis: number }>
389 >(new Map());
390 const socketOwnersRef = yield* Ref.make<
391 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
392 >(new Map());
393 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
394
395 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
396 inodes: ReadonlySet<string>,
397 ) {
398 const owners = new Map<string, { pid: number; processName: string | null }>();
399 const pids = (yield* fileSystem
400 .readDirectory("/proc")
401 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>
402 /^\d+$/.test(entry),
403 );
404 let budget = PROC_FD_WALK_LIMIT;
405 for (const pidText of pids) {
406 if (owners.size === inodes.size || budget <= 0) break;
407 const fds = yield* fileSystem
408 .readDirectory(`/proc/${pidText}/fd`)
409 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
410 const walked = fds.slice(0, budget);
411 budget -= walked.length;
412 const links = yield* Effect.forEach(
413 walked,
414 (fd) =>
415 fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),
416 { concurrency: 16 },
417 );
418 const held = links.flatMap((link) => /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? []);
419 const matched = held.filter((inode) => inodes.has(inode) && !owners.has(inode));
420 if (matched.length === 0) continue;
421 const processName = yield* fileSystem.readFileString(`/proc/${pidText}/comm`).pipe(
422 Effect.map((name) => name.trim() || null),
423 Effect.orElseSucceed(() => null),
424 );
425 for (const inode of matched) owners.set(inode, { pid: Number(pidText), processName });
426 }
427 return owners;
428 });
429
430 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
431 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner>,
432 ) {
433 if (hostPlatform !== "linux") return null;
434 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
435 fileSystem.readFileString(path).pipe(Effect.option),
436 );
437 if (tables.every(Option.isNone)) return null;
438 const listeners = tables.flatMap((table) =>
439 Option.isSome(table) ? parseProcNetTcp(table.value) : [],
440 );
441 const known = yield* Ref.get(socketOwnersRef);
442 const knownMisses = yield* Ref.get(socketOwnerMissesRef);
443 const inodes = new Set(listeners.map((listener) => listener.inode));
444 // Walk fds only for unowned sockets; stop after repeated misses for inaccessible or exited processes.
445 const unseen = new Set(
446 [...inodes].filter(
447 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
448 ),
449 );
450 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
451 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
452 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
453 for (const inode of unseen) {
454 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
455 }
456 yield* Ref.set(socketOwnersRef, owners);
457 yield* Ref.set(socketOwnerMissesRef, misses);
458 const seen = new Map<number, DiscoveredLocalServer>();
459 for (const { port, inode } of listeners) {
460 const owner = owners.get(inode) ?? null;
461 const terminal = owner === null ? null : (terminalByProcessId.get(owner.pid) ?? null);
462 const existing = seen.get(port);
463 if (existing && (existing.pid !== null || owner === null)) {
464 if (terminal === null) seen.set(port, { ...existing, terminal: null });
465 continue;
466 }
467 seen.set(port, {
468 host: "localhost",
469 port,
470 url: `http://localhost:${port}`,
471 processName: owner?.processName ?? null,
472 pid: owner?.pid ?? null,
473 terminal: existing ? null : terminal,
474 });
475 }
476 return [...seen.values()].toSorted((left, right) => left.port - right.port);
477 });
478
479 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
480 httpClient.get(url).pipe(
481 Effect.map((response) => {
482 const location = response.headers.location?.trim();
483 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
484 if (response.status < 200 || response.status >= 300) return null;
485 if (response.status === 204 || response.status === 205) return null;
486 const contentType = response.headers["content-type"]
487 ?.split(";", 1)[0]
488 ?.trim()
489 .toLowerCase();
490 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
491 }),
492 Effect.scoped,
493 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
494 Effect.map(Option.getOrNull),
495 Effect.orElseSucceed(() => null),
496 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
497 ),
498 );
499
500 const makeWebProbeGroups = (
501 servers: ReadonlyArray<DiscoveredLocalServer>,
502 configuredUrls: ReadonlyArray<string>,
503 ): ReadonlyArray<WebProbeGroup> => {
504 const serversByKey = new Map(
505 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
506 );
507 const groups: WebProbeGroup[] = [];
508 const configuredResources = new Set<string>();
509
510 for (const raw of configuredUrls) {
511 const url = new URL(raw);
512 const port = urlPort(url);
513 const key = localServerKey(url.hostname, port);
514 const resourceKey = webProbeCacheKey(raw);
515 if (configuredResources.has(resourceKey)) continue;
516 configuredResources.add(resourceKey);
517 groups.push({
518 server: serversByKey.get(key) ?? {
519 host: url.hostname,
520 port,
521 url: raw,
522 processName: null,
523 pid: null,
524 terminal: null,
525 },
526 urls: [raw],
527 configuredKey: resourceKey,
528 });
529 }
530
531 for (const server of servers) {
532 // Never probe an unidentified listener with HTTP or TLS; binary RPC servers can crash on it.
533 if (server.terminal === null) continue;
534 groups.push({
535 server,
536 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
537 configuredKey: null,
538 });
539 }
540
541 return groups;
542 };
543
544 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
545 servers: ReadonlyArray<DiscoveredLocalServer>,
546 configuredUrls: ReadonlyArray<string>,
547 ) {
548 const nowMillis = yield* Clock.currentTimeMillis;
549 const cached = yield* Ref.get(webProbeCacheRef);
550 const groups = makeWebProbeGroups(servers, configuredUrls);
551 const batchProbes = new Map<
552 string,
553 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
554 >();
555 const batchProbeSemaphore = yield* Semaphore.make(1);
556 const getProbe = (url: string, pid: number | null) => {
557 const key = webProbeCacheKey(url);
558 const identity = `${key}\u0000${pid ?? ""}`;
559 return batchProbeSemaphore
560 .withPermits(1)(
561 Effect.gen(function* () {
562 const existing = batchProbes.get(identity);
563 if (existing) return [existing] as const;
564 const cachedProbe = cached.get(key);
565 const cachedIsCurrent =
566 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
567 const memoized = yield* Effect.cached(
568 cachedIsCurrent
569 ? Effect.succeed({ probe: cachedProbe, fresh: false })
570 : probeWebUrl(url).pipe(
571 Effect.map((result) => ({
572 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
573 fresh: true,
574 })),
575 ),
576 );
577 batchProbes.set(identity, memoized);
578 return [memoized] as const;
579 }),
580 )
581 .pipe(Effect.flatMap(([probe]) => probe));
582 };
583 const probed = yield* Effect.forEach(
584 groups,
585 (group) =>
586 Effect.gen(function* () {
587 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
588 let visibleUrl: string | null = null;
589 for (const url of group.urls) {
590 const key = webProbeCacheKey(url);
591 const { probe, fresh } = yield* getProbe(url, group.server.pid);
592 probes.push([key, probe, fresh]);
593 if (probe.isWeb) {
594 visibleUrl = url;
595 break;
596 }
597 }
598 return { group, probes, visibleUrl };
599 }),
600 { concurrency: WEB_PROBE_CONCURRENCY },
601 );
602 const completedAtMillis = yield* Clock.currentTimeMillis;
603 const nextCache = new Map(
604 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
605 );
606 const discovered: DiscoveredLocalServer[] = [];
607 const configured = new Map<string, DiscoveredLocalServer>();
608 for (const { group, probes, visibleUrl } of probed) {
609 for (const [key, probe, fresh] of probes) {
610 nextCache.set(
611 key,
612 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
613 );
614 }
615 if (visibleUrl === null) continue;
616 const server = { ...group.server, url: visibleUrl };
617 if (group.configuredKey === null) discovered.push(server);
618 else configured.set(group.configuredKey, server);
619 }
620 yield* Ref.set(webProbeCacheRef, nextCache);
621 return { discovered, configured } satisfies WebProbeSnapshot;
622 });
623
624 // tasklist costs 200-300ms per PID; query visible servers with bounded concurrency and cache names.
625 const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (
626 snapshot: WebProbeSnapshot,
627 ) {
628 const servers = [...snapshot.discovered, ...snapshot.configured.values()];
629 const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));
630 const nowMillis = yield* Clock.currentTimeMillis;
631 const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter(
632 ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis,
633 );
634 const cachedPids = new Set(cached.map(([pid]) => pid));
635 const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS;
636 const fetched = yield* Effect.forEach(
637 [...pids].filter((pid) => !cachedPids.has(pid)),
638 (pid) =>
639 processRunner
640 .run({
641 command: "tasklist.exe",
642 args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
643 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
644 maxOutputBytes: 64 * 1024,
645 })
646 .pipe(
647 Effect.map((result) =>
648 exitedWithError(result)
649 ? []
650 : [
651 [
652 pid,
653 { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis },
654 ] as const,
655 ],
656 ),
657 Effect.orElseSucceed(() => []),
658 ),
659 { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY },
660 );
661 const names = new Map([...cached, ...fetched.flat()]);
662 yield* Ref.set(windowsProcessNamesRef, names);
663 const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer =>
664 server.pid === null || server.processName !== null
665 ? server
666 : { ...server, processName: names.get(server.pid)?.name ?? null };
667 return {
668 discovered: snapshot.discovered.map(withName),
669 configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])),
670 } satisfies WebProbeSnapshot;
671 });
672
673 const recoverProcessProbeFailure =
674 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
675 Effect.logDebug("preview port process probe failed; probing configured URLs only", {
676 cause: error,
677 probe,
678 platform: hostPlatform,
679 }).pipe(Effect.as(null));
680
681 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
682 configuredUrls: ReadonlyArray<string>,
683 ) {
684 const state = yield* Ref.get(stateRef);
685 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
686 for (const registration of state.terminalProcesses.values()) {
687 for (const processId of registration.processIds) {
688 terminalByProcessId.set(processId, registration.owner);
689 }
690 }
691 if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {
692 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
693 }
694 if (hostPlatform === "win32") {
695 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
696 const runNetstat = (protocol: "tcp" | "tcpv6") =>
697 processRunner.run({
698 command: "netstat.exe",
699 args: ["-ano", "-p", protocol],
700 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
701 maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES,
702 });
703 const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], {
704 concurrency: 2,
705 }).pipe(
706 // Failed queries can hide other IPv4/IPv6 listeners on the port; fall back to configured URLs.
707 Effect.map(([tcp4, tcp6]) =>
708 exitedWithError(tcp4) || exitedWithError(tcp6)
709 ? null
710 : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId),
711 ),
712 Effect.catchTags({
713 ProcessSpawnError: recoverWindowsProbeFailure,
714 ProcessStdinError: recoverWindowsProbeFailure,
715 ProcessOutputLimitError: recoverWindowsProbeFailure,
716 ProcessReadError: recoverWindowsProbeFailure,
717 ProcessTimeoutError: recoverWindowsProbeFailure,
718 }),
719 );
720 return yield* withWindowsProcessNames(
721 yield* probeWebServers(listeners ?? [], configuredUrls),
722 );
723 }
724 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
725 if (yield* Ref.get(lsofMissingRef)) {
726 const fromProc = yield* scanProcListeners(terminalByProcessId);
727 return yield* probeWebServers(fromProc ?? [], configuredUrls);
728 }
729 const lsofResult = yield* processRunner
730 .run({
731 command: "lsof",
732 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
733 timeout: Duration.millis(LSOF_TIMEOUT_MS),
734 // Partial output could hide another app's listener on an owned port.
735 maxOutputBytes: 1024 * 1024,
736 })
737 .pipe(
738 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
739 Effect.catchTags({
740 ProcessSpawnError: (error) =>
741 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
742 Effect.andThen(recoverLsofProbeFailure(error)),
743 ),
744 ProcessStdinError: recoverLsofProbeFailure,
745 ProcessOutputLimitError: recoverLsofProbeFailure,
746 ProcessReadError: recoverLsofProbeFailure,
747 ProcessTimeoutError: recoverLsofProbeFailure,
748 }),
749 );
750 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
751 const fromProc = yield* scanProcListeners(terminalByProcessId);
752 return yield* probeWebServers(fromProc ?? [], configuredUrls);
753 });
754
755 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
756 (configuredUrls: ReadonlyArray<string>) =>
757 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
758 );
759
760 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
761 const normalized = normalizeConfiguredUrls(configuredUrls);
762 return scanSnapshot(normalized).pipe(
763 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
764 );
765 };
766
767 const pollTick = Effect.fn("PortDiscovery.pollTick")(
768 function* () {
769 const configuredUrls = [
770 ...new Set(
771 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
772 (subscription) => subscription.configuredUrls,
773 ),
774 ),
775 ];
776 const snapshot = yield* scanSnapshot(configuredUrls);
777 const notifications = yield* Ref.modify(stateRef, (state) => {
778 const listeners = new Map(state.listeners);
779 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
780 for (const [listener, subscription] of listeners) {
781 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
782 if (serversEqual(subscription.lastSnapshot, next)) continue;
783 listeners.set(listener, { ...subscription, lastSnapshot: next });
784 changed.push([listener, next]);
785 }
786 return [changed, { ...state, listeners }];
787 });
788 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
789 discard: true,
790 });
791 },
792 Effect.catchCause((cause: Cause.Cause<never>) =>
793 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
794 ),
795 );
796
797 const pollIfRetained = Ref.get(stateRef).pipe(
798 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
799 );
800 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
801
802 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
803 const wasIdle = yield* Ref.modify(stateRef, (state) => [
804 state.retainCount === 0,
805 { ...state, retainCount: state.retainCount + 1 },
806 ]);
807 if (wasIdle) {
808 yield* pollTick();
809 }
810 });
811
812 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
813 Ref.update(stateRef, (state) => ({
814 ...state,
815 retainCount: Math.max(0, state.retainCount - 1),
816 })),
817 );
818
819 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
820 (input, listener) =>
821 Effect.acquireRelease(
822 Ref.update(stateRef, (state) => {
823 const listeners = new Map(state.listeners);
824 listeners.set(listener, {
825 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
826 lastSnapshot: input.initialSnapshot,
827 });
828 return { ...state, listeners };
829 }),
830 () =>
831 Ref.update(stateRef, (state) => {
832 const listeners = new Map(state.listeners);
833 listeners.delete(listener);
834 return { ...state, listeners };
835 }),
836 ),
837 );
838
839 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
840 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
841 const owner = {
842 threadId: ThreadId.make(input.threadId),
843 terminalId: input.terminalId,
844 };
845 const processIds = new Set(
846 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
847 );
848 yield* Ref.update(stateRef, (state) => {
849 const terminalProcesses = new Map(state.terminalProcesses);
850 const key = terminalOwnerKey(owner);
851 if (processIds.size === 0) {
852 terminalProcesses.delete(key);
853 } else {
854 terminalProcesses.set(key, { owner, processIds });
855 }
856 return { ...state, terminalProcesses };
857 });
858 });
859
860 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
861 "PortDiscovery.unregisterTerminal",
862 )(function* (input) {
863 yield* Ref.update(stateRef, (state) => {
864 const terminalProcesses = new Map(state.terminalProcesses);
865 terminalProcesses.delete(terminalOwnerKey(input));
866 return { ...state, terminalProcesses };
867 });
868 });
869
870 return PortDiscovery.of({
871 scan: scanOnce,
872 subscribe,
873 retain,
874 registerTerminalProcesses,
875 unregisterTerminal,
876 });
877}).pipe(Effect.withSpan("PortDiscovery.make"));
878
879export const layer = Layer.effect(PortDiscovery, make);