import { parentPort, workerData } from 'node:worker_threads' import { killAll, treeOf, treeRss } from './proc.mjs' import { SAMPLE_INTERVAL_MS, SLOT } from './watchdog.mjs' /** Sampler thread of lib/watchdog.mjs; writes the shared slots only. */ const { rootPid, ceilingBytes, shared } = workerData const stats = new Int32Array(shared) const toKib = (bytes) => Math.round(bytes / 1024) const PEAKS = [ [SLOT.currentKib, SLOT.peakKib], [SLOT.currentMaxKib, SLOT.peakMaxKib], [SLOT.currentContentKib, SLOT.peakContentKib], ] /** Current values, then each peak (restarted when the main thread asked). */ function record(values) { for (const [slot, value] of values) Atomics.store(stats, slot, value) const reset = Atomics.load(stats, SLOT.resetRequested) === 1 for (const [current, peak] of PEAKS) { const value = Atomics.load(stats, current) if (reset || value > Atomics.load(stats, peak)) { Atomics.store(stats, peak, value) } } if (reset) Atomics.store(stats, SLOT.resetRequested, 0) Atomics.add(stats, SLOT.samples, 1) } /** A fresh walk at kill time: children forked since the sample are included. */ function stopBrowser(timer, totalBytes) { clearInterval(timer) killAll(treeOf(rootPid)) Atomics.store(stats, SLOT.stoppedAtKib, toKib(totalBytes)) Atomics.store(stats, SLOT.stopped, 1) parentPort.postMessage({ type: 'ceiling', totalBytes }) } function sample(timer) { const rss = treeRss(rootPid) record([ [SLOT.currentKib, toKib(rss.totalBytes)], [SLOT.currentMaxKib, toKib(rss.maxProcessBytes)], [SLOT.currentContentKib, toKib(rss.contentBytes)], ]) if (rss.totalBytes > ceilingBytes) stopBrowser(timer, rss.totalBytes) } const timer = setInterval(() => sample(timer), SAMPLE_INTERVAL_MS) sample(timer)