perf(server): replace Windows PowerShell port polling with netstat #18524
Mergedmweinbach(GitHub profile, opens in a new tab)merged 7 commits into
main fromrefs/pull/18524/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
apps/server/src/preview/PortScanner.ts line 752Resolvedby mweinbach(GitHub profile, opens in a new tab)@@ -623,10 +669,11 @@623669 }624670 }625671 if (hostPlatform === "win32") {672+ if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {673+ return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;674+ }626675 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");627- const command =628- 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';629- const listeners = yield* processRunner630- .run({631- command: "powershell.exe",632- args: ["-NoProfile", "-NonInteractive", "-Command", command],676+ const runNetstat = (protocol: "tcp" | "tcpv6") =>677+ processRunner.run({678+ command: "netstat.exe",679+ args: ["-ano", "-p", protocol],juliusmarminge added labelsmacroscope-review
- apps/server/src/preview/PortScanner.ts line 303Resolvedby mweinbach(GitHub profile, opens in a new tab)@@ -251,0 +278,21 @@278+ // `netstat.exe -ano -p tcp` / `tcpv6`:279+ // TCP 127.0.0.1:3773 0.0.0.0:0 LISTENING 34280280+ // TCP [::1]:35783 [::]:0 LISTENING 22876281+ // Foreign port `:0` identifies a listening TCP socket regardless of Windows locale.282+ const fields = trimmed.split(/\s+/);283+ if (fields.length < 4 || fields[0]?.toUpperCase() !== "TCP") return null;284+ const localEndpoint = fields[1] ?? "";285+ const foreignEndpoint = fields[2] ?? "";286+ if (!foreignEndpoint.endsWith(":0")) return null;287+ const lastColon = localEndpoint.lastIndexOf(":");288+ if (lastColon <= 0) return null;289+ const host = localEndpoint.slice(0, lastColon);290+ if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;291+ const port = Number(localEndpoint.slice(lastColon + 1));292+ if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;293+ const pid = Number(fields.at(-1));294+ return {295+ host,296+ port,297+ pid: Number.isInteger(pid) && pid > 0 ? pid : null,298+ processName: null,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/preview/PortScanner.ts line 689OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -606,0 +669,21 @@669+ ) {670+ const servers = [...snapshot.discovered, ...snapshot.configured.values()];671+ const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));672+ const cached = yield* Ref.get(windowsProcessNamesRef);673+ const fetched = yield* Effect.forEach(674+ [...pids].filter((pid) => !cached.has(pid)),675+ (pid) =>676+ processRunner677+ .run({678+ command: "tasklist.exe",679+ args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],680+ timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),681+ maxOutputBytes: 64 * 1024,682+ })683+ .pipe(684+ Effect.map((result) => [pid, parseTasklistProcessName(result.stdout, pid)] as const),685+ Effect.orElseSucceed(() => [pid, null] as const),686+ ),687+ { concurrency: "unbounded" },688+ );689+ const names = new Map([...cached, ...fetched].filter(([pid]) => pids.has(pid)));
- apps/server/src/preview/PortScanner.ts line 674OutdatedResolvedby mweinbach(GitHub profile, opens in a new tab)@@ -604,3 +663,12 @@604663 return { discovered, configured } satisfies WebProbeSnapshot;605664 });606665666+ // `tasklist` costs ~200ms per PID, so look up only visible servers and only once per PID.667+ const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (668+ snapshot: WebProbeSnapshot,669+ ) {670+ const servers = [...snapshot.discovered, ...snapshot.configured.values()];671+ const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));672+ const cached = yield* Ref.get(windowsProcessNamesRef);673+ const fetched = yield* Effect.forEach(674+ [...pids].filter((pid) => !cached.has(pid)),
- apps/server/src/preview/PortScanner.ts line 692OutdatedResolvedby mweinbach(GitHub profile, opens in a new tab)@@ -606,0 +672,21 @@672+ const cached = yield* Ref.get(windowsProcessNamesRef);673+ const fetched = yield* Effect.forEach(674+ [...pids].filter((pid) => !cached.has(pid)),675+ (pid) =>676+ processRunner677+ .run({678+ command: "tasklist.exe",679+ args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],680+ timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),681+ maxOutputBytes: 64 * 1024,682+ })683+ .pipe(684+ // Only a completed lookup is cached; failures retry on the next scan.685+ Effect.map((result) =>686+ result.code !== null && result.code !== 0687+ ? []688+ : [[pid, parseTasklistProcessName(result.stdout, pid)] as const],689+ ),690+ Effect.orElseSucceed(() => []),691+ ),692+ { concurrency: "unbounded" },apps/server/src/preview/PortScanner.ts line 727OutdatedResolvedby mweinbach(GitHub profile, opens in a new tab)@@ -623,3 +722,6 @@623722 }624723 }625724 if (hostPlatform === "win32") {725+ if (terminalByProcessId.size === 0 && configuredUrls.length === 0) {726+ // Idle scans skip the pruning in withWindowsProcessNames, and Windows may reuse a PID.727+ yield* Ref.set(windowsProcessNamesRef, new Map());
coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
apps/server/src/preview/PortScanner.ts line 775Resolvedby mweinbach(GitHub profile, opens in a new tab)@@ -645,3 +750,18 @@645- );646- if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls);647- return yield* probeWebServers([], configuredUrls);750+ maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES,751+ });752+ const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], {753+ concurrency: 2,754+ }).pipe(755+ Effect.map(([tcp4, tcp6]) =>756+ parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId),757+ ),758+ Effect.catchTags({759+ ProcessSpawnError: recoverWindowsProbeFailure,760+ ProcessStdinError: recoverWindowsProbeFailure,761+ ProcessOutputLimitError: recoverWindowsProbeFailure,762+ ProcessReadError: recoverWindowsProbeFailure,763+ ProcessTimeoutError: recoverWindowsProbeFailure,764+ }),765+ );766+ return yield* withWindowsProcessNames(767+ yield* probeWebServers(listeners ?? [], configuredUrls),coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge merged thiscde9cae
juliusmarminge closed this
Sign in to join this conversation.
Codex Review Summary#
This comment shows the latest Codex review activity on this pull request.
a6a8e0fℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.