UNPKG

@applitools/utils

Version:
73 lines (72 loc) 2.85 kB
"use strict"; // Pure, platform-agnostic helpers for computing the resident memory of a process // tree. No Node imports — safe to use from both the Node and browser entry points. // The OS-specific data collection (reading /proc, spawning `ps`/PowerShell) lives // in `process.ts`; these functions only PARSE that data and sum the tree. Object.defineProperty(exports, "__esModule", { value: true }); exports.sumTreeRss = exports.parseWindowsCimJson = exports.parsePosixPsOutput = exports.parseLinuxStatus = void 0; /** Parse a single `/proc/<pid>/status` blob (linux). VmRSS is reported in kB. */ function parseLinuxStatus(statusText) { const ppidMatch = statusText.match(/^PPid:\s+(\d+)/m); const rssMatch = statusText.match(/^VmRSS:\s+(\d+)\s*kB/m); if (!ppidMatch) return null; return { ppid: Number(ppidMatch[1]), rss: rssMatch ? Number(rssMatch[1]) * 1024 : 0 }; } exports.parseLinuxStatus = parseLinuxStatus; /** Parse `ps -A -o pid=,ppid=,rss=` output (macOS / posix). rss is reported in kB. */ function parsePosixPsOutput(stdout) { const table = new Map(); for (const line of stdout.split('\n')) { const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/); if (!match) continue; table.set(Number(match[1]), { ppid: Number(match[2]), rss: Number(match[3]) * 1024 }); } return table; } exports.parsePosixPsOutput = parsePosixPsOutput; /** Parse `Get-CimInstance Win32_Process | ConvertTo-Json` output (windows). WorkingSetSize is bytes. */ function parseWindowsCimJson(stdout) { const parsed = JSON.parse(stdout); const rows = Array.isArray(parsed) ? parsed : [parsed]; const table = new Map(); for (const row of rows) { if (!row || row.ProcessId == null) continue; table.set(Number(row.ProcessId), { ppid: Number(row.ParentProcessId), rss: Number(row.WorkingSetSize) || 0, }); } return table; } exports.parseWindowsCimJson = parseWindowsCimJson; /** Sum rss (bytes) of `rootPid` and all transitive descendants. Cycle-safe. */ function sumTreeRss(table, rootPid) { const childrenOf = new Map(); for (const [pid, { ppid }] of table) { if (!childrenOf.has(ppid)) childrenOf.set(ppid, []); childrenOf.get(ppid).push(pid); } let total = 0; const seen = new Set(); const stack = [rootPid]; while (stack.length) { const pid = stack.pop(); if (seen.has(pid)) continue; seen.add(pid); const info = table.get(pid); if (info) total += info.rss; const kids = childrenOf.get(pid); if (kids) for (const kid of kids) if (!seen.has(kid)) stack.push(kid); } return total; } exports.sumTreeRss = sumTreeRss;