Skip to content

Commit a78e13b

Browse files
RioPlayRioPlay
authored andcommitted
perf(server): stop Windows port discovery thrashing WMI
1 parent 560d4a4 commit a78e13b

2 files changed

Lines changed: 129 additions & 6 deletions

File tree

‎apps/server/src/preview/PortScanner.test.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,101 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
122122
);
123123
});
124124

125+
effectIt("Windows listener probe builds the process-name map once", () =>
126+
Effect.gen(function* () {
127+
let seenCommand: string | undefined;
128+
const layer = PortScanner.layer.pipe(
129+
Layer.provide(
130+
Layer.mergeAll(
131+
Layer.succeed(ProcessRunner.ProcessRunner, {
132+
run: (input) => {
133+
seenCommand = input.args.at(-1);
134+
return Effect.succeed({
135+
stdout: "127.0.0.1|5173|4242|node\n",
136+
stderr: "",
137+
code: 0,
138+
timedOut: false,
139+
stdoutTruncated: false,
140+
stderrTruncated: false,
141+
stdoutInvalidUtf8: false,
142+
stderrInvalidUtf8: false,
143+
});
144+
},
145+
}),
146+
Layer.succeed(Net.NetService, {
147+
canListenOnHost: () => Effect.succeed(true),
148+
isPortAvailableOnLoopback: () => Effect.succeed(true),
149+
reserveLoopbackPort: () => Effect.succeed(40_000),
150+
findAvailablePort: (preferred) => Effect.succeed(preferred),
151+
}),
152+
Layer.succeed(HostProcessPlatform, "win32"),
153+
),
154+
),
155+
);
156+
157+
const servers = yield* Effect.gen(function* () {
158+
const scanner = yield* PortScanner.PortDiscovery;
159+
return yield* scanner.scan();
160+
}).pipe(Effect.provide(layer), Effect.scoped);
161+
162+
expect(seenCommand).toBe(PortScanner.WINDOWS_LISTENER_COMMAND);
163+
// Regression for #5900: never call Get-Process -Id per listener.
164+
expect(seenCommand).toContain("$m = @{}");
165+
expect(seenCommand).not.toMatch(/Get-Process\s+-Id/);
166+
expect(servers).toEqual([
167+
{
168+
host: "localhost",
169+
port: 5173,
170+
url: "http://localhost:5173",
171+
processName: "node",
172+
pid: 4242,
173+
terminal: null,
174+
},
175+
]);
176+
}),
177+
);
178+
179+
effectIt("Windows listener probe cools down after a timeout", () =>
180+
Effect.gen(function* () {
181+
let probeRuns = 0;
182+
const layer = PortScanner.layer.pipe(
183+
Layer.provide(
184+
Layer.mergeAll(
185+
Layer.succeed(ProcessRunner.ProcessRunner, {
186+
run: () => {
187+
probeRuns += 1;
188+
return Effect.fail(
189+
new ProcessRunner.ProcessTimeoutError({
190+
command: "powershell.exe",
191+
argumentCount: 4,
192+
timeoutMs: 5_000,
193+
}),
194+
);
195+
},
196+
}),
197+
Layer.succeed(Net.NetService, {
198+
canListenOnHost: () => Effect.succeed(true),
199+
isPortAvailableOnLoopback: () => Effect.succeed(true),
200+
reserveLoopbackPort: () => Effect.succeed(40_000),
201+
findAvailablePort: (preferred) => Effect.succeed(preferred),
202+
}),
203+
Layer.succeed(HostProcessPlatform, "win32"),
204+
),
205+
),
206+
);
207+
208+
yield* Effect.gen(function* () {
209+
const scanner = yield* PortScanner.PortDiscovery;
210+
// First scan hits the probe and records a cooldown.
211+
yield* scanner.scan();
212+
expect(probeRuns).toBe(1);
213+
// Immediate re-scan must use the common-port fallback, not re-spawn PowerShell.
214+
yield* scanner.scan();
215+
expect(probeRuns).toBe(1);
216+
}).pipe(Effect.provide(layer), Effect.scoped);
217+
}),
218+
);
219+
125220
effectIt("does not swallow process probe defects", () =>
126221
Effect.gen(function* () {
127222
const defect = new Error("unexpected process probe defect");

‎apps/server/src/preview/PortScanner.ts‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
* stable line-prefixed field format; this is the only `lsof` flag set we rely
66
* on).
77
*
8-
* Windows / lsof missing: checks a curated list of common dev ports through
9-
* the shared Net service.
8+
* Windows: PowerShell lists listening sockets (one PID→name map per probe).
9+
* On timeout, fall back to the curated common-port list and cool the probe
10+
* briefly so a doomed WMI query is not re-spawned every poll (#5900).
11+
*
12+
* lsof missing / probe failed: checks a curated list of common dev ports
13+
* through the shared Net service.
1014
*
1115
* Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
1216
* polls forever, but each tick is a no-op when the retain count is zero.
@@ -53,6 +57,15 @@ export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
5357
const POLL_INTERVAL = Duration.seconds(3);
5458
const LSOF_TIMEOUT_MS = 5_000;
5559
const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
60+
/** After a timeout, skip the expensive probe for this many poll ticks (~60s). */
61+
const WINDOWS_LISTENER_TIMEOUT_COOLDOWN_TICKS = 20;
62+
63+
/**
64+
* Windows listener probe command. Builds the process-name map once; per-listener
65+
* `Get-Process -Id` was the cost that made this miss its 5s timeout (#5900).
66+
*/
67+
export const WINDOWS_LISTENER_COMMAND =
68+
'$m = @{}; Get-Process | ForEach-Object { $m[$_.Id] = $_.ProcessName }; Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$($m[[int]$_.OwningProcess])" }';
5669

5770
type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
5871

@@ -67,6 +80,8 @@ interface ScannerState {
6780
}
6881
>;
6982
readonly retainCount: number;
83+
/** Poll ticks remaining before the Windows listener probe is tried again. */
84+
readonly windowsListenerCooldownTicks: number;
7085
}
7186

7287
interface TerminalProcessOwner {
@@ -195,6 +210,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
195210
listeners: new Set(),
196211
terminalProcesses: new Map(),
197212
retainCount: 0,
213+
windowsListenerCooldownTicks: 0,
198214
});
199215

200216
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
@@ -238,13 +254,21 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
238254
}
239255
}
240256
if (hostPlatform === "win32") {
257+
// A probe that just timed out will time out again until the machine
258+
// cools off; skip it for a while and use the cheap common-port path.
259+
if (state.windowsListenerCooldownTicks > 0) {
260+
yield* Ref.update(stateRef, (current) => ({
261+
...current,
262+
windowsListenerCooldownTicks: Math.max(0, current.windowsListenerCooldownTicks - 1),
263+
}));
264+
return yield* probeCommonPorts();
265+
}
266+
241267
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" }';
244268
const listeners = yield* processRunner
245269
.run({
246270
command: "powershell.exe",
247-
args: ["-NoProfile", "-NonInteractive", "-Command", command],
271+
args: ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTENER_COMMAND],
248272
timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
249273
maxOutputBytes: 1024 * 1024,
250274
outputMode: "truncate",
@@ -256,7 +280,11 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
256280
ProcessStdinError: recoverWindowsProbeFailure,
257281
ProcessOutputLimitError: recoverWindowsProbeFailure,
258282
ProcessReadError: recoverWindowsProbeFailure,
259-
ProcessTimeoutError: recoverWindowsProbeFailure,
283+
ProcessTimeoutError: (error) =>
284+
Ref.update(stateRef, (current) => ({
285+
...current,
286+
windowsListenerCooldownTicks: WINDOWS_LISTENER_TIMEOUT_COOLDOWN_TICKS,
287+
})).pipe(Effect.zipRight(recoverWindowsProbeFailure(error))),
260288
}),
261289
);
262290
if (listeners !== null) return listeners;

0 commit comments

Comments
 (0)