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 Service construction is part of the canonical Effect module API. */
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 // Listeners rarely change, so the fd walk runs only for sockets without a
445 // confirmed owner, and gives up on one after a few walks miss it (another
446 // user's process, or one that exited mid-walk).
447 const unseen = new Set(
448 [...inodes].filter(
449 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
450 ),
451 );
452 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
453 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
454 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
455 for (const inode of unseen) {
456 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
457 }
458 yield* Ref.set(socketOwnersRef, owners);
459 yield* Ref.set(socketOwnerMissesRef, misses);
460 const seen = new Map<number, DiscoveredLocalServer>();
461 for (const { port, inode } of listeners) {
462 const owner = owners.get(inode) ?? null;
463 const terminal = owner === null ? null : (terminalByProcessId.get(owner.pid) ?? null);
464 const existing = seen.get(port);
465 if (existing && (existing.pid !== null || owner === null)) {
466 if (terminal === null) seen.set(port, { ...existing, terminal: null });
467 continue;
468 }
469 seen.set(port, {
470 host: "localhost",
471 port,
472 url: `http://localhost:${port}`,
473 processName: owner?.processName ?? null,
474 pid: owner?.pid ?? null,
475 terminal: existing ? null : terminal,
476 });
477 }
478 return [...seen.values()].toSorted((left, right) => left.port - right.port);
479 });
480
481 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
482 httpClient.get(url).pipe(
483 Effect.map((response) => {
484 const location = response.headers.location?.trim();
485 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
486 if (response.status < 200 || response.status >= 300) return null;
487 if (response.status === 204 || response.status === 205) return null;
488 const contentType = response.headers["content-type"]
489 ?.split(";", 1)[0]
490 ?.trim()
491 .toLowerCase();
492 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
493 }),
494 Effect.scoped,
495 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
496 Effect.map(Option.getOrNull),
497 Effect.orElseSucceed(() => null),
498 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
499 ),
500 );
501
502 const makeWebProbeGroups = (
503 servers: ReadonlyArray<DiscoveredLocalServer>,
504 configuredUrls: ReadonlyArray<string>,
505 ): ReadonlyArray<WebProbeGroup> => {
506 const serversByKey = new Map(
507 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
508 );
509 const groups: WebProbeGroup[] = [];
510 const configuredResources = new Set<string>();
511
512 for (const raw of configuredUrls) {
513 const url = new URL(raw);
514 const port = urlPort(url);
515 const key = localServerKey(url.hostname, port);
516 const resourceKey = webProbeCacheKey(raw);
517 if (configuredResources.has(resourceKey)) continue;
518 configuredResources.add(resourceKey);
519 groups.push({
520 server: serversByKey.get(key) ?? {
521 host: url.hostname,
522 port,
523 url: raw,
524 processName: null,
525 pid: null,
526 terminal: null,
527 },
528 urls: [raw],
529 configuredKey: resourceKey,
530 });
531 }
532
533 for (const server of servers) {
534 // A listener alone does not identify its protocol. Sending HTTP or TLS to
535 // another app's binary RPC listener can crash it before classification.
536 if (server.terminal === null) continue;
537 groups.push({
538 server,
539 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
540 configuredKey: null,
541 });
542 }
543
544 return groups;
545 };
546
547 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
548 servers: ReadonlyArray<DiscoveredLocalServer>,
549 configuredUrls: ReadonlyArray<string>,
550 ) {
551 const nowMillis = yield* Clock.currentTimeMillis;
552 const cached = yield* Ref.get(webProbeCacheRef);
553 const groups = makeWebProbeGroups(servers, configuredUrls);
554 const batchProbes = new Map<
555 string,
556 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
557 >();
558 const batchProbeSemaphore = yield* Semaphore.make(1);
559 const getProbe = (url: string, pid: number | null) => {
560 const key = webProbeCacheKey(url);
561 const identity = `${key}\u0000${pid ?? ""}`;
562 return batchProbeSemaphore
563 .withPermits(1)(
564 Effect.gen(function* () {
565 const existing = batchProbes.get(identity);
566 if (existing) return [existing] as const;
567 const cachedProbe = cached.get(key);
568 const cachedIsCurrent =
569 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
570 const memoized = yield* Effect.cached(
571 cachedIsCurrent
572 ? Effect.succeed({ probe: cachedProbe, fresh: false })
573 : probeWebUrl(url).pipe(
574 Effect.map((result) => ({
575 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
576 fresh: true,
577 })),
578 ),
579 );
580 batchProbes.set(identity, memoized);
581 return [memoized] as const;
582 }),
583 )
584 .pipe(Effect.flatMap(([probe]) => probe));
585 };
586 const probed = yield* Effect.forEach(
587 groups,
588 (group) =>
589 Effect.gen(function* () {
590 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
591 let visibleUrl: string | null = null;
592 for (const url of group.urls) {
593 const key = webProbeCacheKey(url);
594 const { probe, fresh } = yield* getProbe(url, group.server.pid);
595 probes.push([key, probe, fresh]);
596 if (probe.isWeb) {
597 visibleUrl = url;
598 break;
599 }
600 }
601 return { group, probes, visibleUrl };
602 }),
603 { concurrency: WEB_PROBE_CONCURRENCY },
604 );
605 const completedAtMillis = yield* Clock.currentTimeMillis;
606 const nextCache = new Map(
607 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
608 );
609 const discovered: DiscoveredLocalServer[] = [];
610 const configured = new Map<string, DiscoveredLocalServer>();
611 for (const { group, probes, visibleUrl } of probed) {
612 for (const [key, probe, fresh] of probes) {
613 nextCache.set(
614 key,
615 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
616 );
617 }
618 if (visibleUrl === null) continue;
619 const server = { ...group.server, url: visibleUrl };
620 if (group.configuredKey === null) discovered.push(server);
621 else configured.set(group.configuredKey, server);
622 }
623 yield* Ref.set(webProbeCacheRef, nextCache);
624 return { discovered, configured } satisfies WebProbeSnapshot;
625 });
626
627 // `tasklist` costs ~200-300ms per PID, so look up only visible servers, a few at a time, and
628 // reuse each name until its TTL expires.
629 const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (
630 snapshot: WebProbeSnapshot,
631 ) {
632 const servers = [...snapshot.discovered, ...snapshot.configured.values()];
633 const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));
634 const nowMillis = yield* Clock.currentTimeMillis;
635 const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter(
636 ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis,
637 );
638 const cachedPids = new Set(cached.map(([pid]) => pid));
639 const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS;
640 const fetched = yield* Effect.forEach(
641 [...pids].filter((pid) => !cachedPids.has(pid)),
642 (pid) =>
643 processRunner
644 .run({
645 command: "tasklist.exe",
646 args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
647 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
648 maxOutputBytes: 64 * 1024,
649 })
650 .pipe(
651 Effect.map((result) =>
652 exitedWithError(result)
653 ? []
654 : [
655 [
656 pid,
657 { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis },
658 ] as const,
659 ],
660 ),
661 Effect.orElseSucceed(() => []),
662 ),
663 { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY },
664 );
665 const names = new Map([...cached, ...fetched.flat()]);
666 yield* Ref.set(windowsProcessNamesRef, names);
667 const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer =>
668 server.pid === null || server.processName !== null
669 ? server
670 : { ...server, processName: names.get(server.pid)?.name ?? null };
671 return {
672 discovered: snapshot.discovered.map(withName),
673 configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])),
674 } satisfies WebProbeSnapshot;
675 });
676
677 const recoverProcessProbeFailure =
678 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
679 Effect.logDebug("preview port process probe failed; probing configured URLs only", {
680 cause: error,
681 probe,
682 platform: hostPlatform,
683 }).pipe(Effect.as(null));
684
685 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
686 configuredUrls: ReadonlyArray<string>,
687 ) {
688 const state = yield* Ref.get(stateRef);
689 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
690 for (const registration of state.terminalProcesses.values()) {
691 for (const processId of registration.processIds) {
692 terminalByProcessId.set(processId, registration.owner);
693 }
694 }
695 if (hostPlatform === "win32") {
696 if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {
697 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
698 }
699 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
700 const runNetstat = (protocol: "tcp" | "tcpv6") =>
701 processRunner.run({
702 command: "netstat.exe",
703 args: ["-ano", "-p", protocol],
704 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
705 maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES,
706 });
707 const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], {
708 concurrency: 2,
709 }).pipe(
710 // One failed query leaves a partial snapshot that could hide another process sharing a
711 // port across IPv4/IPv6, so fall back to configured URLs instead.
712 Effect.map(([tcp4, tcp6]) =>
713 exitedWithError(tcp4) || exitedWithError(tcp6)
714 ? null
715 : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId),
716 ),
717 Effect.catchTags({
718 ProcessSpawnError: recoverWindowsProbeFailure,
719 ProcessStdinError: recoverWindowsProbeFailure,
720 ProcessOutputLimitError: recoverWindowsProbeFailure,
721 ProcessReadError: recoverWindowsProbeFailure,
722 ProcessTimeoutError: recoverWindowsProbeFailure,
723 }),
724 );
725 return yield* withWindowsProcessNames(
726 yield* probeWebServers(listeners ?? [], configuredUrls),
727 );
728 }
729 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
730 if (yield* Ref.get(lsofMissingRef)) {
731 const fromProc = yield* scanProcListeners(terminalByProcessId);
732 return yield* probeWebServers(fromProc ?? [], configuredUrls);
733 }
734 const lsofResult = yield* processRunner
735 .run({
736 command: "lsof",
737 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
738 timeout: Duration.millis(LSOF_TIMEOUT_MS),
739 // Partial output could hide another app's listener on an owned port.
740 maxOutputBytes: 1024 * 1024,
741 })
742 .pipe(
743 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
744 Effect.catchTags({
745 ProcessSpawnError: (error) =>
746 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
747 Effect.andThen(recoverLsofProbeFailure(error)),
748 ),
749 ProcessStdinError: recoverLsofProbeFailure,
750 ProcessOutputLimitError: recoverLsofProbeFailure,
751 ProcessReadError: recoverLsofProbeFailure,
752 ProcessTimeoutError: recoverLsofProbeFailure,
753 }),
754 );
755 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
756 const fromProc = yield* scanProcListeners(terminalByProcessId);
757 return yield* probeWebServers(fromProc ?? [], configuredUrls);
758 });
759
760 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
761 (configuredUrls: ReadonlyArray<string>) =>
762 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
763 );
764
765 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
766 const normalized = normalizeConfiguredUrls(configuredUrls);
767 return scanSnapshot(normalized).pipe(
768 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
769 );
770 };
771
772 const pollTick = Effect.fn("PortDiscovery.pollTick")(
773 function* () {
774 const configuredUrls = [
775 ...new Set(
776 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
777 (subscription) => subscription.configuredUrls,
778 ),
779 ),
780 ];
781 const snapshot = yield* scanSnapshot(configuredUrls);
782 const notifications = yield* Ref.modify(stateRef, (state) => {
783 const listeners = new Map(state.listeners);
784 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
785 for (const [listener, subscription] of listeners) {
786 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
787 if (serversEqual(subscription.lastSnapshot, next)) continue;
788 listeners.set(listener, { ...subscription, lastSnapshot: next });
789 changed.push([listener, next]);
790 }
791 return [changed, { ...state, listeners }];
792 });
793 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
794 discard: true,
795 });
796 },
797 Effect.catchCause((cause: Cause.Cause<never>) =>
798 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
799 ),
800 );
801
802 const pollIfRetained = Ref.get(stateRef).pipe(
803 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
804 );
805 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
806
807 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
808 const wasIdle = yield* Ref.modify(stateRef, (state) => [
809 state.retainCount === 0,
810 { ...state, retainCount: state.retainCount + 1 },
811 ]);
812 if (wasIdle) {
813 yield* pollTick();
814 }
815 });
816
817 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
818 Ref.update(stateRef, (state) => ({
819 ...state,
820 retainCount: Math.max(0, state.retainCount - 1),
821 })),
822 );
823
824 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
825 (input, listener) =>
826 Effect.acquireRelease(
827 Ref.update(stateRef, (state) => {
828 const listeners = new Map(state.listeners);
829 listeners.set(listener, {
830 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
831 lastSnapshot: input.initialSnapshot,
832 });
833 return { ...state, listeners };
834 }),
835 () =>
836 Ref.update(stateRef, (state) => {
837 const listeners = new Map(state.listeners);
838 listeners.delete(listener);
839 return { ...state, listeners };
840 }),
841 ),
842 );
843
844 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
845 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
846 const owner = {
847 threadId: ThreadId.make(input.threadId),
848 terminalId: input.terminalId,
849 };
850 const processIds = new Set(
851 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
852 );
853 yield* Ref.update(stateRef, (state) => {
854 const terminalProcesses = new Map(state.terminalProcesses);
855 const key = terminalOwnerKey(owner);
856 if (processIds.size === 0) {
857 terminalProcesses.delete(key);
858 } else {
859 terminalProcesses.set(key, { owner, processIds });
860 }
861 return { ...state, terminalProcesses };
862 });
863 });
864
865 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
866 "PortDiscovery.unregisterTerminal",
867 )(function* (input) {
868 yield* Ref.update(stateRef, (state) => {
869 const terminalProcesses = new Map(state.terminalProcesses);
870 terminalProcesses.delete(terminalOwnerKey(input));
871 return { ...state, terminalProcesses };
872 });
873 });
874
875 return PortDiscovery.of({
876 scan: scanOnce,
877 subscribe,
878 retain,
879 registerTerminalProcesses,
880 unregisterTerminal,
881 });
882}).pipe(Effect.withSpan("PortDiscovery.make"));
883
884export const layer = Layer.effect(PortDiscovery, make);