node-server-lens 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/metrics.js ADDED
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+ const os = require('os');
3
+ const { monitorEventLoopDelay } = require('perf_hooks');
4
+
5
+ const MIN = 60 * 1000;
6
+ const HOUR = 60 * MIN;
7
+ const RANGES = ['1h', '24h', '7d', '30d', '1y'];
8
+ const offMs = (t) => -new Date(t).getTimezoneOffset() * MIN;
9
+ const hourKey = (t) => Math.floor((t + offMs(t)) / HOUR); // local-time hour index (handles +5:30 etc.)
10
+
11
+ // Collapse ids so /users/42 and /users/43 count as one endpoint.
12
+ function normalizePath(p) {
13
+ const out = String(p || '/').split('?')[0].slice(0, 200).split('/').map((s) =>
14
+ /^\d+$/.test(s) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s) || /^[0-9a-f]{16,}$/i.test(s)
15
+ ? ':id' : s).join('/');
16
+ return out || '/';
17
+ }
18
+
19
+ function percentile(arr, p) {
20
+ if (!arr.length) return 0;
21
+ const s = [...arr].sort((a, b) => a - b);
22
+ return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
23
+ }
24
+
25
+ const add = (map, k, ms, isErr, n = 1) => {
26
+ const b = map.get(k) || { c: 0, e: 0, t: 0 };
27
+ b.c += n; b.t += ms; if (isErr) b.e += n;
28
+ map.set(k, b);
29
+ };
30
+
31
+ class Metrics {
32
+ /** sample=false: no local process sampling (used for remote servers whose samples are pushed in). */
33
+ constructor({ maxRoutes = 500, maxRecent = 100, sampleEvery = 2000, sample = true } = {}) {
34
+ this.maxRoutes = maxRoutes;
35
+ this.maxRecent = maxRecent;
36
+ this.routes = new Map();
37
+ this.minutes = new Map(); // minute index -> { c, e, t } (last ~25h)
38
+ this.hours = new Map(); // local hour index -> { c, e, t } (last ~400d)
39
+ this.status = { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0 };
40
+ this.recent = [];
41
+ this.total = 0;
42
+ this.errors = 0;
43
+ this.totalMs = 0;
44
+ this.samples = [];
45
+ this.startedAt = Date.now();
46
+
47
+ if (sample) {
48
+ this._loop = monitorEventLoopDelay({ resolution: 20 });
49
+ this._loop.enable();
50
+ this._cpu = process.cpuUsage();
51
+ this._cpuAt = process.hrtime.bigint();
52
+ this._sys = sysCpuTimes();
53
+ this.sample();
54
+ this._timer = setInterval(() => this.sample(), sampleEvery);
55
+ } else {
56
+ this._timer = setInterval(() => this.prune(), MIN);
57
+ }
58
+ this._timer.unref();
59
+ }
60
+
61
+ record({ method, route, status, ms, ip = '', path = route, now = Date.now() }) {
62
+ let key = `${method} ${route}`;
63
+ if (!this.routes.has(key) && this.routes.size >= this.maxRoutes) key = `${method} *`; // cardinality guard vs. URL scanners
64
+ let r = this.routes.get(key);
65
+ if (!r) {
66
+ r = { method, route: key.slice(method.length + 1), count: 0, errors: 0, totalMs: 0, max: 0, durations: [], lastAt: 0, lastStatus: 0 };
67
+ this.routes.set(key, r);
68
+ }
69
+ const isErr = status >= 500;
70
+ r.count++; r.totalMs += ms; r.max = Math.max(r.max, ms); r.lastAt = Math.max(r.lastAt, now); r.lastStatus = status;
71
+ if (status >= 400) r.errors++;
72
+ r.durations.push(ms);
73
+ if (r.durations.length > 200) r.durations.shift();
74
+
75
+ const cls = `${Math.floor(status / 100)}xx`;
76
+ if (cls in this.status) this.status[cls]++;
77
+ this.total++; this.totalMs += ms;
78
+ if (isErr) this.errors++;
79
+ add(this.minutes, Math.floor(now / MIN), ms, isErr);
80
+ add(this.hours, hourKey(now), ms, isErr);
81
+
82
+ this.recent.unshift({ ts: now, method, path: String(path).slice(0, 300), route: r.route, status, ms, ip });
83
+ if (this.recent.length > this.maxRecent) this.recent.pop();
84
+ }
85
+
86
+ pushSample(s) {
87
+ this.samples.push({ ...s, ts: s.ts || Date.now() });
88
+ if (this.samples.length > 60) this.samples.shift();
89
+ }
90
+
91
+ sample() {
92
+ const now = process.hrtime.bigint();
93
+ const elapsedUs = Number(now - this._cpuAt) / 1000;
94
+ const cpu = process.cpuUsage(this._cpu);
95
+ this._cpu = process.cpuUsage(); this._cpuAt = now;
96
+ const sys = sysCpuTimes();
97
+ const idle = sys.idle - this._sys.idle, tot = sys.total - this._sys.total;
98
+ this._sys = sys;
99
+ const mem = process.memoryUsage();
100
+ const lag = this._loop.mean / 1e6;
101
+ this._loop.reset();
102
+ this.pushSample({
103
+ cpu: elapsedUs ? Math.min(100 * os.cpus().length, ((cpu.user + cpu.system) / elapsedUs) * 100) : 0,
104
+ sysCpu: tot ? (1 - idle / tot) * 100 : 0,
105
+ rss: mem.rss, heapUsed: mem.heapUsed, heapTotal: mem.heapTotal,
106
+ freeMem: os.freemem(),
107
+ lag: Number.isFinite(lag) ? lag : 0,
108
+ load: os.loadavg(),
109
+ });
110
+ this.prune();
111
+ }
112
+
113
+ prune(now = Date.now()) {
114
+ const m = Math.floor(now / MIN) - 1500, h = hourKey(now) - 24 * 400;
115
+ for (const k of this.minutes.keys()) if (k < m) this.minutes.delete(k);
116
+ for (const k of this.hours.keys()) if (k < h) this.hours.delete(k);
117
+ }
118
+
119
+ window(fromMin, toMin) { return sum(this.minutes, fromMin, toMin); }
120
+
121
+ traffic(range, now = Date.now()) {
122
+ const out = [];
123
+ if (range === '1h' || range === '24h') {
124
+ const [bars, minutes] = range === '1h' ? [12, 5] : [24, 60];
125
+ const nowMin = Math.floor(now / MIN), off = offMs(now) / MIN;
126
+ const endMin = Math.ceil((nowMin + 1 + off) / minutes) * minutes - off; // align to clean local boundaries
127
+ for (let i = bars; i > 0; i--) {
128
+ const to = endMin - (i - 1) * minutes, from = to - minutes;
129
+ out.push({ start: from * MIN, ...sum(this.minutes, from, to) });
130
+ }
131
+ } else if (range === '7d' || range === '30d') {
132
+ const days = range === '7d' ? 7 : 30, today = Math.floor(hourKey(now) / 24);
133
+ for (let d = today - days + 1; d <= today; d++) {
134
+ out.push({ start: d * 24 * HOUR - offMs(now), ...sum(this.hours, d * 24, d * 24 + 24) });
135
+ }
136
+ } else if (range === '1y') {
137
+ const d = new Date(now);
138
+ for (let i = 11; i >= 0; i--) {
139
+ const s = new Date(d.getFullYear(), d.getMonth() - i, 1).getTime();
140
+ const e = new Date(d.getFullYear(), d.getMonth() - i + 1, 1).getTime();
141
+ out.push({ start: s, ...sum(this.hours, hourKey(s), hourKey(e)) });
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+
147
+ health() {
148
+ const s = this.samples[this.samples.length - 1];
149
+ const nowMin = Math.floor(Date.now() / MIN);
150
+ const w = this.window(nowMin - 4, nowMin + 1);
151
+ return (w.count && w.errors / w.count > 0.05) || (s && s.lag > 100) ? 'degraded' : 'healthy';
152
+ }
153
+
154
+ snapshot() {
155
+ const nowMin = Math.floor(Date.now() / MIN);
156
+ const routes = [...this.routes.values()].map((r) => ({
157
+ method: r.method, route: r.route, count: r.count, errors: r.errors,
158
+ avgMs: r.totalMs / r.count, p95: r.durations.length ? percentile(r.durations, 95) : r.totalMs / r.count, max: r.max,
159
+ lastAt: r.lastAt, lastStatus: r.lastStatus,
160
+ }));
161
+ return {
162
+ totals: { requests: this.total, errors: this.errors, avgMs: this.total ? this.totalMs / this.total : 0 },
163
+ lastHour: this.window(nowMin - 59, nowMin + 1),
164
+ prevHour: this.window(nowMin - 119, nowMin - 59),
165
+ status: this.status,
166
+ traffic: Object.fromEntries(RANGES.map((k) => [k, this.traffic(k)])),
167
+ routes,
168
+ recent: this.recent,
169
+ samples: this.samples,
170
+ };
171
+ }
172
+
173
+ toJSON() {
174
+ return {
175
+ v: 1, startedAt: this.startedAt, total: this.total, errors: this.errors, totalMs: this.totalMs, status: this.status,
176
+ minutes: [...this.minutes], hours: [...this.hours], recent: this.recent,
177
+ routes: [...this.routes].map(([k, { durations, ...r }]) => [k, r]),
178
+ };
179
+ }
180
+
181
+ load(o) {
182
+ if (!o || o.v !== 1) return this;
183
+ Object.assign(this, { total: o.total, errors: o.errors, totalMs: o.totalMs, status: { ...this.status, ...o.status }, recent: o.recent || [] });
184
+ this.minutes = new Map(o.minutes);
185
+ this.hours = new Map(o.hours);
186
+ this.routes = new Map(o.routes.map(([k, r]) => [k, { ...r, durations: [] }]));
187
+ this.prune();
188
+ return this;
189
+ }
190
+
191
+ stop() { clearInterval(this._timer); if (this._loop) this._loop.disable(); }
192
+ }
193
+
194
+ function sum(map, from, to) {
195
+ let c = 0, e = 0, t = 0;
196
+ for (let k = from; k < to; k++) {
197
+ const b = map.get(k);
198
+ if (b) { c += b.c; e += b.e; t += b.t; }
199
+ }
200
+ return { count: c, errors: e, avgMs: c ? t / c : 0 };
201
+ }
202
+
203
+ function sysCpuTimes() {
204
+ let idle = 0, total = 0;
205
+ for (const c of os.cpus()) {
206
+ for (const v of Object.values(c.times)) total += v;
207
+ idle += c.times.idle;
208
+ }
209
+ return { idle, total };
210
+ }
211
+
212
+ module.exports = { Metrics, normalizePath, percentile, hourKey, RANGES, MIN, HOUR };
package/src/source.js ADDED
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+ // A "source" is one monitored server: this process (local), a remote agent, or a URL check.
3
+ const os = require('os');
4
+ const { Metrics } = require('./metrics');
5
+ const { LogStore } = require('./logs');
6
+
7
+ const OFFLINE_AFTER = 20 * 1000;
8
+
9
+ function processInfo(httpServer, startedAt) {
10
+ const ips = [];
11
+ for (const [name, list] of Object.entries(os.networkInterfaces())) {
12
+ for (const i of list || []) if (!i.internal && !/^fe80:/i.test(i.address)) ips.push({ name, address: i.address, family: String(i.family).replace(/^(4|6)$/, 'IPv$1') });
13
+ }
14
+ ips.sort((a, b) => a.family.localeCompare(b.family)); // IPv4 first
15
+ ips.splice(6);
16
+ const addr = httpServer && httpServer.address && httpServer.address();
17
+ const cpus = os.cpus();
18
+ return {
19
+ hostname: os.hostname(),
20
+ ips,
21
+ port: addr && typeof addr === 'object' ? addr.port : Number(process.env.PORT) || null,
22
+ pid: process.pid,
23
+ runtime: `Node.js ${process.version}`,
24
+ platform: `${os.type()} ${os.release()}`,
25
+ arch: process.arch,
26
+ cpuModel: cpus[0] ? cpus[0].model.trim() : 'unknown',
27
+ cpus: cpus.length,
28
+ totalMem: os.totalmem(),
29
+ env: process.env.NODE_ENV || 'development',
30
+ startedAt,
31
+ uptime: process.uptime(),
32
+ osUptime: os.uptime(),
33
+ };
34
+ }
35
+
36
+ function localSource({ id = 'local', name = os.hostname(), captureConsole = true, maxLogs, maxRoutes, maxRecent } = {}) {
37
+ const metrics = new Metrics({ maxRoutes, maxRecent });
38
+ const logs = new LogStore({ max: maxLogs });
39
+ if (captureConsole) logs.captureConsole();
40
+ const src = {
41
+ id, name, kind: 'agent', metrics, logs, httpServer: null, lastSeen: null,
42
+ info: () => processInfo(src.httpServer, metrics.startedAt),
43
+ health: () => metrics.health(),
44
+ close: () => { metrics.stop(); if (logs.restore) logs.restore(); },
45
+ };
46
+ return src;
47
+ }
48
+
49
+ function remoteSource({ id, name, saved }) {
50
+ const metrics = new Metrics({ sample: false }).load(saved && saved.metrics);
51
+ const logs = new LogStore();
52
+ const src = {
53
+ id, name, kind: 'agent', metrics, logs,
54
+ data: (saved && saved.info) || { hostname: name, ips: [] },
55
+ lastSeen: (saved && saved.lastSeen) || 0,
56
+ info() {
57
+ const age = (Date.now() - src.lastSeen) / 1000;
58
+ return { ...src.data, uptime: src.lastSeen && age * 1000 < OFFLINE_AFTER ? (src.data.uptime || 0) + age : src.data.uptime };
59
+ },
60
+ health: () => (Date.now() - src.lastSeen > OFFLINE_AFTER ? 'offline' : metrics.health()),
61
+ toJSON: () => ({ id, name: src.name, kind: 'agent', info: src.data, lastSeen: src.lastSeen, metrics: metrics.toJSON() }),
62
+ close: () => metrics.stop(),
63
+ };
64
+ return src;
65
+ }
66
+
67
+ function urlSource({ id, name, url, interval = 30000, saved }) {
68
+ const metrics = new Metrics({ sample: false }).load(saved && saved.metrics);
69
+ const logs = new LogStore();
70
+ const u = new URL(url);
71
+ const route = u.pathname || '/';
72
+ let last = (saved && saved.last) || null; // { ok, status, ms, ts, error }
73
+ let checks = (saved && saved.checks) || { ok: 0, total: 0 };
74
+
75
+ async function check() {
76
+ const t = Date.now();
77
+ let status = 0, error = null;
78
+ try {
79
+ const res = await fetch(url, { signal: AbortSignal.timeout(10000), headers: { 'user-agent': 'server-lens-monitor' } });
80
+ status = res.status;
81
+ res.body && res.body.cancel().catch(() => {});
82
+ } catch (e) { error = (e && (e.cause && e.cause.code)) || (e && e.name) || 'error'; }
83
+ const ms = Date.now() - t;
84
+ const ok = status > 0 && status < 400;
85
+ if (last && last.ok !== ok) logs.addAt(t, ok ? 'info' : 'error', ok ? `Recovered: ${url} → ${status} in ${ms} ms` : `Down: ${url} → ${error || status}`);
86
+ else if (!last) logs.addAt(t, ok ? 'info' : 'error', `First check: ${url} → ${error || status} in ${ms} ms`);
87
+ else if (!ok) logs.addAt(t, 'warn', `Still down: ${url} → ${error || status}`);
88
+ last = { ok, status, ms, ts: t, error };
89
+ checks = { ok: checks.ok + (ok ? 1 : 0), total: checks.total + 1 };
90
+ metrics.record({ method: 'GET', route, path: url, status: status || 599, ms, ip: 'monitor', now: t });
91
+ metrics.pushSample({ ts: t, responseMs: ms });
92
+ }
93
+
94
+ const timer = setInterval(check, interval);
95
+ timer.unref();
96
+ setTimeout(check, 100).unref();
97
+
98
+ return {
99
+ id, name, kind: 'url', url, metrics, logs,
100
+ get lastSeen() { return last ? last.ts : 0; },
101
+ info: () => ({
102
+ hostname: u.host, url, ips: [], interval: interval / 1000,
103
+ lastStatus: last ? last.error || last.status : '–', lastMs: last ? last.ms : null,
104
+ uptimePct: checks.total ? (checks.ok / checks.total) * 100 : null, checks: checks.total,
105
+ }),
106
+ health: () => (!last ? 'pending' : !last.ok ? 'down' : last.ms > 2000 ? 'degraded' : 'healthy'),
107
+ toJSON() { return { id, name: this.name, kind: 'url', url, last, checks, metrics: metrics.toJSON() }; },
108
+ close: () => { clearInterval(timer); metrics.stop(); },
109
+ };
110
+ }
111
+
112
+ module.exports = { localSource, remoteSource, urlSource, processInfo, OFFLINE_AFTER };