Open History to see the last commit
1/**
2 * In-process PortScanner implementation.
3 *
4 * macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
5 * stable line-prefixed field format; this is the only `lsof` flag set we rely
6 * on).
7 *
8 * Windows / lsof missing: checks a curated list of common dev ports through
9 * the shared Net service.
10 *
11 * Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
12 * polls forever, but each tick is a no-op when the retain count is zero.
13 */
14import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
15import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
16import * as Net from "@t3tools/shared/Net";
17import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
18import * as Cause from "effect/Cause";
19import * as Context from "effect/Context";
20import * as Duration from "effect/Duration";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Ref from "effect/Ref";
24import * as Schedule from "effect/Schedule";
25import * as Scope from "effect/Scope";
26
27import * as ProcessRunner from "../processRunner.ts";
28
29export class PortDiscovery extends Context.Service<
30 PortDiscovery,
31 {
32 readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
33 readonly subscribe: (
34 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
35 ) => Effect.Effect<void, never, Scope.Scope>;
36 readonly retain: Effect.Effect<void, never, Scope.Scope>;
37 readonly registerTerminalProcesses: (input: {
38 readonly threadId: string;
39 readonly terminalId: string;
40 readonly processIds: ReadonlyArray<number>;
41 }) => Effect.Effect<void>;
42 readonly unregisterTerminal: (input: {
43 readonly threadId: string;
44 readonly terminalId: string;
45 }) => Effect.Effect<void>;
46 }
47>()("t3/preview/PortScanner/PortDiscovery") {}
48
49export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
50 3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
51]);
52
53const POLL_INTERVAL = Duration.seconds(3);
54const LSOF_TIMEOUT_MS = 5_000;
55const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
56
57type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
58
59interface ScannerState {
60 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
61 readonly listeners: ReadonlySet<Listener>;
62 readonly terminalProcesses: ReadonlyMap<
63 string,
64 {
65 readonly owner: TerminalProcessOwner;
66 readonly processIds: ReadonlySet<number>;
67 }
68 >;
69 readonly retainCount: number;
70}
71
72interface TerminalProcessOwner {
73 readonly threadId: ThreadId;
74 readonly terminalId: string;
75}
76
77const terminalOwnerKey = (owner: {
78 readonly threadId: string;
79 readonly terminalId: string;
80}): string => `${owner.threadId}\u0000${owner.terminalId}`;
81
82const parseLsofOutput = (
83 raw: string,
84 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
85): ReadonlyArray<DiscoveredLocalServer> => {
86 const seen = new Map<string, DiscoveredLocalServer>();
87 let pid: number | null = null;
88 let processName: string | null = null;
89
90 for (const line of raw.split("\n")) {
91 if (line.length === 0) continue;
92 const tag = line.charAt(0);
93 const value = line.slice(1);
94 if (tag === "p") {
95 const parsed = Number.parseInt(value, 10);
96 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
97 processName = null;
98 continue;
99 }
100 if (tag === "c") {
101 processName = value.trim() || null;
102 continue;
103 }
104 if (tag === "n") {
105 const portMatch = parsePortFromLsofName(value);
106 if (portMatch == null) continue;
107 const url = `http://localhost:${portMatch}`;
108 const key = `localhost:${portMatch}`;
109 if (seen.has(key)) continue;
110 seen.set(key, {
111 host: "localhost",
112 port: portMatch,
113 url,
114 processName,
115 pid,
116 terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
117 });
118 }
119 }
120
121 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
122};
123
124const parsePortFromLsofName = (name: string): number | null => {
125 // Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
126 // "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
127 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
128 if (trimmed.length === 0) return null;
129 const lastColon = trimmed.lastIndexOf(":");
130 if (lastColon < 0) return null;
131 const hostPart = trimmed.slice(0, lastColon);
132 const portPart = trimmed.slice(lastColon + 1);
133 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
134 const port = Number.parseInt(portPart, 10);
135 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
136 return port;
137};
138
139const parseWindowsListenerOutput = (
140 raw: string,
141 terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
142): ReadonlyArray<DiscoveredLocalServer> => {
143 const seen = new Map<number, DiscoveredLocalServer>();
144 for (const line of raw.split(/\r?\n/g)) {
145 const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
146 const host = hostRaw?.trim() ?? "";
147 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
148 const port = Number(portRaw);
149 const pid = Number(pidRaw);
150 if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
151 const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
152 if (seen.has(port)) continue;
153 seen.set(port, {
154 host: "localhost",
155 port,
156 url: `http://localhost:${port}`,
157 processName: processNameRaw?.trim() || null,
158 pid: normalizedPid,
159 terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
160 });
161 }
162 return [...seen.values()].toSorted((left, right) => left.port - right.port);
163};
164
165const serversEqual = (
166 left: ReadonlyArray<DiscoveredLocalServer>,
167 right: ReadonlyArray<DiscoveredLocalServer>,
168): boolean => {
169 if (left.length !== right.length) return false;
170 for (let i = 0; i < left.length; i += 1) {
171 const a = left[i];
172 const b = right[i];
173 if (!a || !b) return false;
174 if (
175 a.host !== b.host ||
176 a.port !== b.port ||
177 a.url !== b.url ||
178 a.processName !== b.processName ||
179 a.pid !== b.pid ||
180 a.terminal?.threadId !== b.terminal?.threadId ||
181 a.terminal?.terminalId !== b.terminal?.terminalId
182 ) {
183 return false;
184 }
185 }
186 return true;
187};
188
189export const make = Effect.gen(function* PortDiscoveryMake() {
190 const net = yield* Net.NetService;
191 const processRunner = yield* ProcessRunner.ProcessRunner;
192 const hostPlatform = yield* HostProcessPlatform;
193 const stateRef = yield* Ref.make<ScannerState>({
194 lastSnapshot: [],
195 listeners: new Set(),
196 terminalProcesses: new Map(),
197 retainCount: 0,
198 });
199
200 const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
201 const results = yield* Effect.forEach(
202 COMMON_DEV_PORTS,
203 (port) =>
204 net.isPortAvailableOnLoopback(port).pipe(
205 Effect.map((available) => ({
206 port,
207 listening: !available,
208 })),
209 ),
210 { concurrency: "unbounded" },
211 );
212 return results
213 .filter((result) => result.listening)
214 .map<DiscoveredLocalServer>((result) => ({
215 host: "localhost",
216 port: result.port,
217 url: `http://localhost:${result.port}`,
218 processName: null,
219 pid: null,
220 terminal: null,
221 }));
222 });
223
224 const recoverProcessProbeFailure =
225 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
226 Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
227 cause: error,
228 probe,
229 platform: hostPlatform,
230 }).pipe(Effect.as(null));
231
232 const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
233 const state = yield* Ref.get(stateRef);
234 const terminalByProcessId = new Map<number, TerminalProcessOwner>();
235 for (const registration of state.terminalProcesses.values()) {
236 for (const processId of registration.processIds) {
237 terminalByProcessId.set(processId, registration.owner);
238 }
239 }
240 if (hostPlatform === "win32") {
241 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
242 const command =
243 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
244 const listeners = yield* processRunner
245 .run({
246 command: "powershell.exe",
247 args: ["-NoProfile", "-NonInteractive", "-Command", command],
248 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
249 maxOutputBytes: 1024 * 1024,
250 outputMode: "truncate",
251 })
252 .pipe(
253 Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
254 Effect.catchTags({
255 ProcessSpawnError: recoverWindowsProbeFailure,
256 ProcessStdinError: recoverWindowsProbeFailure,
257 ProcessOutputLimitError: recoverWindowsProbeFailure,
258 ProcessReadError: recoverWindowsProbeFailure,
259 ProcessTimeoutError: recoverWindowsProbeFailure,
260 }),
261 );
262 if (listeners !== null) return listeners;
263 return yield* probeCommonPorts();
264 }
265 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
266 const lsofResult = yield* processRunner
267 .run({
268 command: "lsof",
269 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
270 timeout: Duration.millis(LSOF_TIMEOUT_MS),
271 maxOutputBytes: 1024 * 1024,
272 outputMode: "truncate",
273 })
274 .pipe(
275 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
276 Effect.catchTags({
277 ProcessSpawnError: recoverLsofProbeFailure,
278 ProcessStdinError: recoverLsofProbeFailure,
279 ProcessOutputLimitError: recoverLsofProbeFailure,
280 ProcessReadError: recoverLsofProbeFailure,
281 ProcessTimeoutError: recoverLsofProbeFailure,
282 }),
283 );
284 if (lsofResult !== null) return lsofResult;
285 return yield* probeCommonPorts();
286 });
287
288 const broadcast = Effect.fn("PortDiscovery.broadcast")(function* (
289 servers: ReadonlyArray<DiscoveredLocalServer>,
290 ) {
291 const listeners = (yield* Ref.get(stateRef)).listeners;
292 yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });
293 });
294
295 const pollTick = Effect.fn("PortDiscovery.pollTick")(
296 function* () {
297 if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
298 const next = yield* scanOnce();
299 const changed = yield* Ref.modify(stateRef, (state) =>
300 serversEqual(state.lastSnapshot, next)
301 ? [false, state]
302 : [true, { ...state, lastSnapshot: next }],
303 );
304 if (changed) yield* broadcast(next);
305 },
306 Effect.catchCause((cause: Cause.Cause<never>) =>
307 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
308 ),
309 );
310
311 // Single layer-scoped polling fiber. Ticks are no-ops when no client is
312 // currently retained, so the cost is one Ref.get every POLL_INTERVAL.
313 yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
314
315 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
316 const wasIdle = yield* Ref.modify(stateRef, (state) => [
317 state.retainCount === 0,
318 { ...state, retainCount: state.retainCount + 1 },
319 ]);
320 if (wasIdle) {
321 // Run an immediate scan + broadcast so the new retainer doesn't have
322 // to wait up to POLL_INTERVAL for the first emission.
323 yield* pollTick();
324 }
325 });
326
327 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
328 Ref.update(stateRef, (state) => ({
329 ...state,
330 retainCount: Math.max(0, state.retainCount - 1),
331 })),
332 );
333
334 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
335 (listener) =>
336 Effect.acquireRelease(
337 Ref.update(stateRef, (state) => ({
338 ...state,
339 listeners: new Set([...state.listeners, listener]),
340 })),
341 () =>
342 Ref.update(stateRef, (state) => {
343 const listeners = new Set(state.listeners);
344 listeners.delete(listener);
345 return { ...state, listeners };
346 }),
347 ),
348 );
349
350 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
351 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
352 const owner = {
353 threadId: ThreadId.make(input.threadId),
354 terminalId: input.terminalId,
355 };
356 const processIds = new Set(
357 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
358 );
359 yield* Ref.update(stateRef, (state) => {
360 const terminalProcesses = new Map(state.terminalProcesses);
361 const key = terminalOwnerKey(owner);
362 if (processIds.size === 0) {
363 terminalProcesses.delete(key);
364 } else {
365 terminalProcesses.set(key, { owner, processIds });
366 }
367 return { ...state, terminalProcesses };
368 });
369 });
370
371 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
372 "PortDiscovery.unregisterTerminal",
373 )(function* (input) {
374 yield* Ref.update(stateRef, (state) => {
375 const terminalProcesses = new Map(state.terminalProcesses);
376 terminalProcesses.delete(terminalOwnerKey(input));
377 return { ...state, terminalProcesses };
378 });
379 });
380
381 return PortDiscovery.of({
382 scan: scanOnce,
383 subscribe,
384 retain,
385 registerTerminalProcesses,
386 unregisterTerminal,
387 });
388}).pipe(Effect.withSpan("PortDiscovery.make"));
389
390export const layer = Layer.effect(PortDiscovery, make);