okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
1.6 KiB45 linesraw
1/**
2 * One long-lived PowerShell that prints a line per reading, in a loop. The monitor used to start a cold PowerShell for every sample;
3 * its WMI start cost more than the probe timeout, so every query failed and WmiPrvSE burned a core (#3939).
4 * The loop gives up after `maxStarts` early exits in a row, so a counter that cannot be read stays quiet.
5 */
6import { spawn } from 'node:child_process';
7
8export function createPowerShellLoop({ script, onLine, spawnFn = spawn, maxStarts = 3 }) {
9  let child = null, starts = 0, buffer = '';
10  function start() {
11    if (child || starts >= maxStarts) return;
12    starts++;
13    let proc;
14    try { proc = spawnFn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); }
15    catch { return; }
16    child = proc;
17    buffer = '';
18    proc.on?.('error', () => { if (child === proc) child = null; });
19    proc.on?.('exit', () => { if (child === proc) child = null; });
20    proc.stdout?.on('data', chunk => {
21      buffer += chunk;
22      let i;
23      while ((i = buffer.indexOf('\n')) >= 0) {
24        const line = buffer.slice(0, i);
25        buffer = buffer.slice(i + 1);
26        if (onLine(line)) starts = 0;
27      }
28    });
29    proc.unref?.();
30    proc.stdout?.unref?.();
31  }
32  return {
33    start,
34    stop() { try { child?.kill(); } catch { /* gone */ } child = null; },
35    get starts() { return starts; },
36  };
37}
38
39let stoppers = null;
40/** Every loop is ended with the host. */
41export function endWithHost(loop) {
42  if (!stoppers) { stoppers = new Set(); process.once('exit', () => stoppers.forEach(l => l.stop())); }
43  stoppers.add(loop);
44  return loop;
45}