Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

node-metrics-collector.ts

133 lines3.7 KB

1#!/usr/bin/env bun
2/**
3 * node-metrics-collector.ts — V8/Node metrics collector for baseline comparison.
4 *
5 * Collects: process.memoryUsage(), event loop lag, active session count.
6 * Writes JSON lines to stdout at 1-second intervals.
7 *
8 * STRUCTURAL LIMITATION: Node's shared V8 heap means per-session memory
9 * attribution is impossible. This IS the key difference we're measuring.
10 *
11 * Usage:
12 * bun run scripts/node-metrics-collector.ts [duration_seconds=30] [output_file]
13 *
14 * Output format (one JSON object per line):
15 * {
16 * timestamp: number,
17 * memory: { heapUsed, heapTotal, rss, external, arrayBuffers },
18 * eventLoopLag_ms: number,
19 * v8Heap: { totalHeapSize, usedHeapSize, heapSizeLimit, mallocedMemory },
20 * gc: { note: "per-session GC not available in V8 — shared heap" }
21 * }
22 */
23​
24import v8 from "node:v8";
25import { writeFileSync, appendFileSync } from "node:fs";
26​
27const durationSeconds = Number(process.argv[2] || 30);
28if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) {
29 console.error(`Invalid duration: ${process.argv[2]} — must be a positive number`);
30 process.exit(1);
32const outputFile = process.argv[3] || null;
33​
34interface MetricsSample {
35 timestamp: number;
36 elapsed_ms: number;
37 memory: {
38 heapUsed: number;
39 heapTotal: number;
40 rss: number;
41 external: number;
42 arrayBuffers: number;
43 };
44 eventLoopLag_ms: number;
45 v8Heap: {
46 totalHeapSize: number;
47 usedHeapSize: number;
48 heapSizeLimit: number;
49 mallocedMemory: number;
50 };
51 gc: {
52 note: string;
53 perSessionAvailable: false;
54 };
56​
57// --- Event loop lag measurement ---
58// Uses hrtime to measure how long a setTimeout(0) actually takes
59​
60function measureEventLoopLag(): Promise<number> {
61 return new Promise((resolve) => {
62 const start = process.hrtime.bigint();
63 setTimeout(() => {
64 const elapsed = Number(process.hrtime.bigint() - start) / 1e6; // ns → ms
65 // Subtract the expected 1ms setTimeout minimum
66 resolve(Math.max(0, elapsed - 1));
67 }, 1);
68 });
70​
71// --- Collector ---
72​
73const t0 = Date.now();
74const samples: MetricsSample[] = [];
75​
76if (outputFile) {
77 writeFileSync(outputFile, ""); // truncate
79​
80console.error(`[node-metrics] Collecting for ${durationSeconds}s...`);
81​
82async function collectSample(): Promise<MetricsSample> {
83 const mem = process.memoryUsage();
84 const heapStats = v8.getHeapStatistics();
85 const lag = await measureEventLoopLag();
86​
87 return {
88 timestamp: Date.now(),
89 elapsed_ms: Date.now() - t0,
90 memory: {
91 heapUsed: mem.heapUsed,
92 heapTotal: mem.heapTotal,
93 rss: mem.rss,
94 external: mem.external,
95 arrayBuffers: mem.arrayBuffers,
96 },
97 eventLoopLag_ms: Math.round(lag * 100) / 100,
98 v8Heap: {
99 totalHeapSize: heapStats.total_heap_size,
100 usedHeapSize: heapStats.used_heap_size,
101 heapSizeLimit: heapStats.heap_size_limit,
102 mallocedMemory: heapStats.malloced_memory,
103 },
104 gc: {
105 note: "per-session GC not available in V8 — shared heap",
106 perSessionAvailable: false,
107 },
108 };
110​
111let elapsed = 0;
112const interval = setInterval(async () => {
113 elapsed += 1;
114 const sample = await collectSample();
115 samples.push(sample);
116​
117 const line = JSON.stringify(sample);
118​
119 if (outputFile) {
120 appendFileSync(outputFile, line + "\n");
121 } else {
122 console.log(line);
123 }
124​
125 if (elapsed >= durationSeconds) {
126 clearInterval(interval);
127 console.error(
128 `[node-metrics] Done. ${samples.length} samples collected. ` +
129 `Peak RSS: ${(Math.max(...samples.map((s) => s.memory.rss)) / 1024 / 1024).toFixed(1)}MB, ` +
130 `Peak heap: ${(Math.max(...samples.map((s) => s.memory.heapUsed)) / 1024 / 1024).toFixed(1)}MB`,
131 );
132 }
133}, 1000);