|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import fs from "node:fs"; |
| 4 | +import path from "node:path"; |
| 5 | + |
| 6 | +function printUsage() { |
| 7 | + console.error( |
| 8 | + "Usage: node heapsnapshot-delta.mjs <before.heapsnapshot> <after.heapsnapshot> [--top N] [--min-kb N]", |
| 9 | + ); |
| 10 | + console.error( |
| 11 | + " or: node heapsnapshot-delta.mjs --lane-dir <dir> [--pid PID] [--top N] [--min-kb N]", |
| 12 | + ); |
| 13 | +} |
| 14 | + |
| 15 | +function fail(message) { |
| 16 | + console.error(message); |
| 17 | + process.exit(1); |
| 18 | +} |
| 19 | + |
| 20 | +function parseArgs(argv) { |
| 21 | + const options = { |
| 22 | + top: 30, |
| 23 | + minKb: 64, |
| 24 | + laneDir: null, |
| 25 | + pid: null, |
| 26 | + files: [], |
| 27 | + }; |
| 28 | + |
| 29 | + for (let index = 0; index < argv.length; index += 1) { |
| 30 | + const arg = argv[index]; |
| 31 | + if (arg === "--top") { |
| 32 | + options.top = Number.parseInt(argv[index + 1] ?? "", 10); |
| 33 | + index += 1; |
| 34 | + continue; |
| 35 | + } |
| 36 | + if (arg === "--min-kb") { |
| 37 | + options.minKb = Number.parseInt(argv[index + 1] ?? "", 10); |
| 38 | + index += 1; |
| 39 | + continue; |
| 40 | + } |
| 41 | + if (arg === "--lane-dir") { |
| 42 | + options.laneDir = argv[index + 1] ?? null; |
| 43 | + index += 1; |
| 44 | + continue; |
| 45 | + } |
| 46 | + if (arg === "--pid") { |
| 47 | + options.pid = Number.parseInt(argv[index + 1] ?? "", 10); |
| 48 | + index += 1; |
| 49 | + continue; |
| 50 | + } |
| 51 | + options.files.push(arg); |
| 52 | + } |
| 53 | + |
| 54 | + if (!Number.isFinite(options.top) || options.top <= 0) { |
| 55 | + fail("--top must be a positive integer"); |
| 56 | + } |
| 57 | + if (!Number.isFinite(options.minKb) || options.minKb < 0) { |
| 58 | + fail("--min-kb must be a non-negative integer"); |
| 59 | + } |
| 60 | + if (options.pid !== null && (!Number.isInteger(options.pid) || options.pid <= 0)) { |
| 61 | + fail("--pid must be a positive integer"); |
| 62 | + } |
| 63 | + |
| 64 | + return options; |
| 65 | +} |
| 66 | + |
| 67 | +function parseHeapFilename(filePath) { |
| 68 | + const base = path.basename(filePath); |
| 69 | + const match = base.match( |
| 70 | + /^Heap\.(?<stamp>\d{8}\.\d{6})\.(?<pid>\d+)\.0\.(?<seq>\d+)\.heapsnapshot$/u, |
| 71 | + ); |
| 72 | + if (!match?.groups) { |
| 73 | + return null; |
| 74 | + } |
| 75 | + return { |
| 76 | + filePath, |
| 77 | + pid: Number.parseInt(match.groups.pid, 10), |
| 78 | + stamp: match.groups.stamp, |
| 79 | + sequence: Number.parseInt(match.groups.seq, 10), |
| 80 | + }; |
| 81 | +} |
| 82 | + |
| 83 | +function resolvePair(options) { |
| 84 | + if (options.laneDir) { |
| 85 | + const entries = fs |
| 86 | + .readdirSync(options.laneDir) |
| 87 | + .map((name) => parseHeapFilename(path.join(options.laneDir, name))) |
| 88 | + .filter((entry) => entry !== null) |
| 89 | + .filter((entry) => options.pid === null || entry.pid === options.pid) |
| 90 | + .toSorted((left, right) => { |
| 91 | + if (left.pid !== right.pid) { |
| 92 | + return left.pid - right.pid; |
| 93 | + } |
| 94 | + if (left.stamp !== right.stamp) { |
| 95 | + return left.stamp.localeCompare(right.stamp); |
| 96 | + } |
| 97 | + return left.sequence - right.sequence; |
| 98 | + }); |
| 99 | + |
| 100 | + if (entries.length === 0) { |
| 101 | + fail(`No matching heap snapshots found in ${options.laneDir}`); |
| 102 | + } |
| 103 | + |
| 104 | + const groups = new Map(); |
| 105 | + for (const entry of entries) { |
| 106 | + const group = groups.get(entry.pid) ?? []; |
| 107 | + group.push(entry); |
| 108 | + groups.set(entry.pid, group); |
| 109 | + } |
| 110 | + |
| 111 | + const candidates = Array.from(groups.values()) |
| 112 | + .map((group) => ({ |
| 113 | + pid: group[0].pid, |
| 114 | + before: group[0], |
| 115 | + after: group.at(-1), |
| 116 | + count: group.length, |
| 117 | + })) |
| 118 | + .filter((entry) => entry.count >= 2); |
| 119 | + |
| 120 | + if (candidates.length === 0) { |
| 121 | + fail(`Need at least two snapshots for one PID in ${options.laneDir}`); |
| 122 | + } |
| 123 | + |
| 124 | + const chosen = |
| 125 | + options.pid !== null |
| 126 | + ? (candidates.find((entry) => entry.pid === options.pid) ?? null) |
| 127 | + : candidates.toSorted((left, right) => right.count - left.count || left.pid - right.pid)[0]; |
| 128 | + |
| 129 | + if (!chosen) { |
| 130 | + fail(`No PID with at least two snapshots matched in ${options.laneDir}`); |
| 131 | + } |
| 132 | + |
| 133 | + return { |
| 134 | + before: chosen.before.filePath, |
| 135 | + after: chosen.after.filePath, |
| 136 | + pid: chosen.pid, |
| 137 | + snapshotCount: chosen.count, |
| 138 | + }; |
| 139 | + } |
| 140 | + |
| 141 | + if (options.files.length !== 2) { |
| 142 | + printUsage(); |
| 143 | + process.exit(1); |
| 144 | + } |
| 145 | + |
| 146 | + return { |
| 147 | + before: options.files[0], |
| 148 | + after: options.files[1], |
| 149 | + pid: null, |
| 150 | + snapshotCount: 2, |
| 151 | + }; |
| 152 | +} |
| 153 | + |
| 154 | +function loadSummary(filePath) { |
| 155 | + const data = JSON.parse(fs.readFileSync(filePath, "utf8")); |
| 156 | + const meta = data.snapshot?.meta; |
| 157 | + if (!meta) { |
| 158 | + fail(`Invalid heap snapshot: ${filePath}`); |
| 159 | + } |
| 160 | + |
| 161 | + const nodeFieldCount = meta.node_fields.length; |
| 162 | + const typeNames = meta.node_types[0]; |
| 163 | + const strings = data.strings; |
| 164 | + const typeIndex = meta.node_fields.indexOf("type"); |
| 165 | + const nameIndex = meta.node_fields.indexOf("name"); |
| 166 | + const selfSizeIndex = meta.node_fields.indexOf("self_size"); |
| 167 | + |
| 168 | + const summary = new Map(); |
| 169 | + for (let offset = 0; offset < data.nodes.length; offset += nodeFieldCount) { |
| 170 | + const type = typeNames[data.nodes[offset + typeIndex]]; |
| 171 | + const name = strings[data.nodes[offset + nameIndex]]; |
| 172 | + const selfSize = data.nodes[offset + selfSizeIndex]; |
| 173 | + const key = `${type}\t${name}`; |
| 174 | + const current = summary.get(key) ?? { |
| 175 | + type, |
| 176 | + name, |
| 177 | + selfSize: 0, |
| 178 | + count: 0, |
| 179 | + }; |
| 180 | + current.selfSize += selfSize; |
| 181 | + current.count += 1; |
| 182 | + summary.set(key, current); |
| 183 | + } |
| 184 | + return { |
| 185 | + nodeCount: data.snapshot.node_count, |
| 186 | + summary, |
| 187 | + }; |
| 188 | +} |
| 189 | + |
| 190 | +function formatBytes(bytes) { |
| 191 | + if (Math.abs(bytes) >= 1024 ** 2) { |
| 192 | + return `${(bytes / 1024 ** 2).toFixed(2)} MiB`; |
| 193 | + } |
| 194 | + if (Math.abs(bytes) >= 1024) { |
| 195 | + return `${(bytes / 1024).toFixed(1)} KiB`; |
| 196 | + } |
| 197 | + return `${bytes} B`; |
| 198 | +} |
| 199 | + |
| 200 | +function formatDelta(bytes) { |
| 201 | + return `${bytes >= 0 ? "+" : "-"}${formatBytes(Math.abs(bytes))}`; |
| 202 | +} |
| 203 | + |
| 204 | +function truncate(text, maxLength) { |
| 205 | + return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`; |
| 206 | +} |
| 207 | + |
| 208 | +function main() { |
| 209 | + const options = parseArgs(process.argv.slice(2)); |
| 210 | + const pair = resolvePair(options); |
| 211 | + const before = loadSummary(pair.before); |
| 212 | + const after = loadSummary(pair.after); |
| 213 | + const minBytes = options.minKb * 1024; |
| 214 | + |
| 215 | + const rows = []; |
| 216 | + for (const [key, next] of after.summary) { |
| 217 | + const previous = before.summary.get(key) ?? { selfSize: 0, count: 0 }; |
| 218 | + const sizeDelta = next.selfSize - previous.selfSize; |
| 219 | + const countDelta = next.count - previous.count; |
| 220 | + if (sizeDelta < minBytes) { |
| 221 | + continue; |
| 222 | + } |
| 223 | + rows.push({ |
| 224 | + type: next.type, |
| 225 | + name: next.name, |
| 226 | + sizeDelta, |
| 227 | + countDelta, |
| 228 | + afterSize: next.selfSize, |
| 229 | + afterCount: next.count, |
| 230 | + }); |
| 231 | + } |
| 232 | + |
| 233 | + rows.sort( |
| 234 | + (left, right) => right.sizeDelta - left.sizeDelta || right.countDelta - left.countDelta, |
| 235 | + ); |
| 236 | + |
| 237 | + console.log(`before: ${pair.before}`); |
| 238 | + console.log(`after: ${pair.after}`); |
| 239 | + if (pair.pid !== null) { |
| 240 | + console.log(`pid: ${pair.pid} (${pair.snapshotCount} snapshots found)`); |
| 241 | + } |
| 242 | + console.log( |
| 243 | + `nodes: ${before.nodeCount} -> ${after.nodeCount} (${after.nodeCount - before.nodeCount >= 0 ? "+" : ""}${after.nodeCount - before.nodeCount})`, |
| 244 | + ); |
| 245 | + console.log(`filter: top=${options.top} min=${options.minKb} KiB`); |
| 246 | + console.log(""); |
| 247 | + |
| 248 | + if (rows.length === 0) { |
| 249 | + console.log("No entries exceeded the minimum delta."); |
| 250 | + return; |
| 251 | + } |
| 252 | + |
| 253 | + for (const row of rows.slice(0, options.top)) { |
| 254 | + console.log( |
| 255 | + [ |
| 256 | + formatDelta(row.sizeDelta).padStart(11), |
| 257 | + `count ${row.countDelta >= 0 ? "+" : ""}${row.countDelta}`.padStart(10), |
| 258 | + row.type.padEnd(16), |
| 259 | + truncate(row.name || "(empty)", 96), |
| 260 | + ].join(" "), |
| 261 | + ); |
| 262 | + } |
| 263 | +} |
| 264 | + |
| 265 | +main(); |
0 commit comments