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/LICENSE +21 -0
- package/README.md +445 -2
- package/bin/server-lens.js +44 -0
- package/package.json +52 -4
- package/public/index.html +929 -0
- package/src/dashboard.js +143 -0
- package/src/hub.js +153 -0
- package/src/index.d.ts +80 -0
- package/src/index.js +145 -0
- package/src/logs.js +46 -0
- package/src/metrics.js +212 -0
- package/src/source.js +112 -0
package/src/dashboard.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Serves the UI, the JSON API and the live WebSocket for a set of sources.
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { WebSocketServer } = require('ws');
|
|
7
|
+
|
|
8
|
+
const HTML = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
|
|
9
|
+
const hash = (s) => crypto.createHash('sha256').update(String(s)).digest();
|
|
10
|
+
const safeEqual = (a, b) => crypto.timingSafeEqual(hash(a), hash(b));
|
|
11
|
+
|
|
12
|
+
function normBase(p) {
|
|
13
|
+
const s = String(p == null ? '/server-lens' : p).replace(/^\/+|\/+$/g, '');
|
|
14
|
+
return s ? '/' + s : '';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {object} o
|
|
19
|
+
* @param {string} o.base mount path ('' for root)
|
|
20
|
+
* @param {object} o.sources { list(): Source[], get(id): Source|undefined }
|
|
21
|
+
* @param {boolean} [o.hub] multi-server mode
|
|
22
|
+
*/
|
|
23
|
+
function createDashboard({ base, title = 'Server Lens', auth, interval = 2000, hub = false, sources }) {
|
|
24
|
+
const token = crypto.randomBytes(24).toString('hex'); // per-process key for the dashboard socket
|
|
25
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 4096 });
|
|
26
|
+
const clients = new Set();
|
|
27
|
+
const watched = new WeakSet();
|
|
28
|
+
|
|
29
|
+
const send = (ws, msg) => { try { ws.send(JSON.stringify(msg)); } catch { /* socket gone */ } };
|
|
30
|
+
|
|
31
|
+
function authorized(req) {
|
|
32
|
+
if (!auth) return true;
|
|
33
|
+
if (typeof auth === 'function') return !!auth(req);
|
|
34
|
+
const h = req.headers.authorization || '';
|
|
35
|
+
if (!h.startsWith('Basic ')) return false;
|
|
36
|
+
return safeEqual(Buffer.from(h.slice(6), 'base64').toString(), `${auth.username}:${auth.password}`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function summary(src) {
|
|
40
|
+
const nowMin = Math.floor(Date.now() / 60000);
|
|
41
|
+
const lh = src.metrics.window(nowMin - 59, nowMin + 1);
|
|
42
|
+
const info = src.info();
|
|
43
|
+
return { id: src.id, name: src.name, kind: src.kind, health: src.health(), lastSeen: src.lastSeen, host: info.hostname, url: src.url, count: lh.count, errors: lh.errors, avgMs: lh.avgMs, total: src.metrics.total };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function snapshot(src) {
|
|
47
|
+
const s = src.metrics.snapshot();
|
|
48
|
+
s.id = src.id; s.name = src.name; s.kind = src.kind;
|
|
49
|
+
s.server = src.info();
|
|
50
|
+
s.health = src.health();
|
|
51
|
+
s.servers = hub ? sources.list().map(summary) : null;
|
|
52
|
+
s.clients = clients.size;
|
|
53
|
+
return s;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function watch(src) {
|
|
57
|
+
if (watched.has(src.logs)) return;
|
|
58
|
+
watched.add(src.logs);
|
|
59
|
+
src.logs.on('log', (entry) => {
|
|
60
|
+
for (const ws of clients) if (ws.srcId === src.id) send(ws, { type: 'log', data: entry });
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function subscribe(ws, id) {
|
|
65
|
+
const src = sources.get(id) || sources.list()[0];
|
|
66
|
+
if (!src) return;
|
|
67
|
+
ws.srcId = src.id;
|
|
68
|
+
send(ws, { type: 'init', data: { snapshot: snapshot(src), logs: src.logs.entries } });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const ticker = setInterval(() => {
|
|
72
|
+
if (!clients.size) return;
|
|
73
|
+
const cache = new Map();
|
|
74
|
+
for (const ws of clients) {
|
|
75
|
+
const src = sources.get(ws.srcId);
|
|
76
|
+
if (!src) { subscribe(ws); continue; } // server was removed
|
|
77
|
+
if (!cache.has(src.id)) cache.set(src.id, snapshot(src));
|
|
78
|
+
send(ws, { type: 'snapshot', data: cache.get(src.id) });
|
|
79
|
+
}
|
|
80
|
+
}, interval);
|
|
81
|
+
ticker.unref();
|
|
82
|
+
|
|
83
|
+
const isWs = (req) => (req.url || '').split('?')[0] === `${base}/ws`;
|
|
84
|
+
|
|
85
|
+
function handleUpgrade(req, socket, head) {
|
|
86
|
+
const url = new URL(req.url, 'http://localhost');
|
|
87
|
+
if (!safeEqual(url.searchParams.get('token') || '', token)) { socket.destroy(); return; }
|
|
88
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
89
|
+
clients.add(ws);
|
|
90
|
+
ws.on('close', () => clients.delete(ws));
|
|
91
|
+
ws.on('error', () => clients.delete(ws));
|
|
92
|
+
ws.on('message', (raw) => {
|
|
93
|
+
let m; try { m = JSON.parse(raw); } catch { return; }
|
|
94
|
+
if (m && m.type === 'subscribe' && typeof m.id === 'string') subscribe(ws, m.id);
|
|
95
|
+
});
|
|
96
|
+
subscribe(ws, url.searchParams.get('server') || undefined);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Returns true if the request was handled. */
|
|
101
|
+
function handle(req, res, pathname) {
|
|
102
|
+
const sub = pathname.slice(base.length) || '/';
|
|
103
|
+
const q = new URL(req.url, 'http://localhost').searchParams;
|
|
104
|
+
if (sub === '/health') { // public & minimal, for load balancers / uptime checks
|
|
105
|
+
const src = sources.list()[0];
|
|
106
|
+
return json(res, 200, { status: src ? src.health() : 'unknown', uptime: process.uptime(), timestamp: Date.now() });
|
|
107
|
+
}
|
|
108
|
+
if (!authorized(req)) {
|
|
109
|
+
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Server Lens"', 'Content-Type': 'text/plain' });
|
|
110
|
+
return res.end('Authentication required');
|
|
111
|
+
}
|
|
112
|
+
if (sub === '/' && req.method === 'GET') {
|
|
113
|
+
const cfg = JSON.stringify({ base, ws: `${base}/ws`, token, title, interval, hub }).replace(/</g, '\\u003c');
|
|
114
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff' });
|
|
115
|
+
return res.end(HTML.replace('__SL_CONFIG__', cfg));
|
|
116
|
+
}
|
|
117
|
+
if (sub === '/api/snapshot') {
|
|
118
|
+
const src = sources.get(q.get('server')) || sources.list()[0];
|
|
119
|
+
return src ? json(res, 200, snapshot(src)) : json(res, 404, { error: 'no servers' });
|
|
120
|
+
}
|
|
121
|
+
if (sub === '/api/servers' && req.method === 'GET') return json(res, 200, sources.list().map(summary));
|
|
122
|
+
if (sub === '/api/logs') {
|
|
123
|
+
const src = sources.get(q.get('server')) || sources.list()[0];
|
|
124
|
+
return json(res, 200, src ? src.logs.entries : []);
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function close() {
|
|
130
|
+
clearInterval(ticker);
|
|
131
|
+
for (const ws of clients) ws.terminate();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { handle, handleUpgrade, isWs, authorized, watch, snapshot, close, base };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function json(res, code, body) {
|
|
138
|
+
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
139
|
+
res.end(JSON.stringify(body));
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = { createDashboard, normBase, json, safeEqual };
|
package/src/hub.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Standalone hub: one dashboard for many servers (agents push in, URLs are polled).
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const http = require('http');
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
const { localSource, remoteSource, urlSource } = require('./source');
|
|
8
|
+
const { createDashboard, normBase, json, safeEqual } = require('./dashboard');
|
|
9
|
+
const { normalizePath } = require('./metrics');
|
|
10
|
+
|
|
11
|
+
const MAX_SERVERS = 200;
|
|
12
|
+
const ID_RE = /^[\w.-]{1,64}$/;
|
|
13
|
+
const str = (v, max) => String(v == null ? '' : v).slice(0, max);
|
|
14
|
+
const num = (v, d = 0) => (Number.isFinite(+v) ? +v : d);
|
|
15
|
+
|
|
16
|
+
function createHub(opts = {}) {
|
|
17
|
+
const base = normBase(opts.path == null ? '' : opts.path);
|
|
18
|
+
const key = opts.key;
|
|
19
|
+
const dataFile = opts.dataFile === false ? null : path.resolve(opts.dataFile || path.join(process.cwd(), 'server-lens-data.json'));
|
|
20
|
+
const checkInterval = (opts.checkInterval || 30) * 1000;
|
|
21
|
+
|
|
22
|
+
const self = localSource({ id: 'hub', name: opts.name || 'Server Lens Hub', captureConsole: opts.captureConsole !== false });
|
|
23
|
+
const sources = new Map([[self.id, self]]);
|
|
24
|
+
// hub itself is listed last so the first real server is the default view
|
|
25
|
+
const list = () => [...sources.values()].filter((s) => s !== self).concat(self);
|
|
26
|
+
const dash = createDashboard({ base, title: opts.title || 'Server Lens', auth: opts.auth, interval: opts.interval, hub: true, sources: { list, get: (id) => sources.get(id) } });
|
|
27
|
+
dash.watch(self);
|
|
28
|
+
|
|
29
|
+
function addSource(src) { sources.set(src.id, src); dash.watch(src); return src; }
|
|
30
|
+
|
|
31
|
+
// ---- persistence ----
|
|
32
|
+
if (dataFile && fs.existsSync(dataFile)) {
|
|
33
|
+
try {
|
|
34
|
+
const saved = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
|
|
35
|
+
if (saved.hub) self.metrics.load(saved.hub);
|
|
36
|
+
for (const s of saved.servers || []) {
|
|
37
|
+
if (s.kind === 'url') addSource(urlSource({ id: s.id, name: s.name, url: s.url, interval: checkInterval, saved: s }));
|
|
38
|
+
else addSource(remoteSource({ id: s.id, name: s.name, saved: s }));
|
|
39
|
+
}
|
|
40
|
+
} catch (e) { console.error(`server-lens: could not read ${dataFile}: ${e.message}`); }
|
|
41
|
+
}
|
|
42
|
+
function save() {
|
|
43
|
+
if (!dataFile) return;
|
|
44
|
+
const data = { v: 1, savedAt: Date.now(), hub: self.metrics.toJSON(), servers: [...sources.values()].filter((s) => s !== self).map((s) => s.toJSON()) };
|
|
45
|
+
const tmp = `${dataFile}.tmp`;
|
|
46
|
+
try { fs.writeFileSync(tmp, JSON.stringify(data)); fs.renameSync(tmp, dataFile); } catch (e) { console.error(`server-lens: save failed: ${e.message}`); }
|
|
47
|
+
}
|
|
48
|
+
const saver = setInterval(save, 60 * 1000);
|
|
49
|
+
saver.unref();
|
|
50
|
+
|
|
51
|
+
// ---- ingest (agents & any language over HTTP) ----
|
|
52
|
+
function ingest(body) {
|
|
53
|
+
if (!body || !ID_RE.test(body.id || '')) return [400, { error: 'id must match ' + ID_RE }];
|
|
54
|
+
let src = sources.get(body.id);
|
|
55
|
+
if (src && src.kind !== 'agent') return [409, { error: 'id belongs to a URL monitor' }];
|
|
56
|
+
if (src === self) return [409, { error: 'reserved id' }];
|
|
57
|
+
if (!src) {
|
|
58
|
+
if (sources.size >= MAX_SERVERS) return [429, { error: 'server limit reached' }];
|
|
59
|
+
src = addSource(remoteSource({ id: body.id, name: str(body.name || body.id, 60) }));
|
|
60
|
+
console.log(`New server connected: ${src.name} (${src.id})`);
|
|
61
|
+
}
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
src.lastSeen = now;
|
|
64
|
+
if (body.name) src.name = str(body.name, 60);
|
|
65
|
+
if (body.info && typeof body.info === 'object') src.data = sanitizeInfo(body.info, src.name);
|
|
66
|
+
if (body.sample && typeof body.sample === 'object') {
|
|
67
|
+
const s = body.sample;
|
|
68
|
+
src.metrics.pushSample({ ts: now, cpu: num(s.cpu), sysCpu: num(s.sysCpu), rss: num(s.rss), heapUsed: num(s.heapUsed), freeMem: num(s.freeMem), lag: num(s.lag), load: Array.isArray(s.load) ? s.load.slice(0, 3).map((x) => num(x)) : [] });
|
|
69
|
+
}
|
|
70
|
+
for (const r of (Array.isArray(body.requests) ? body.requests : []).slice(0, 10000)) {
|
|
71
|
+
const ts = num(r.ts, now);
|
|
72
|
+
const route = str(r.route || normalizePath(r.path), 200);
|
|
73
|
+
src.metrics.record({
|
|
74
|
+
method: str(r.method || 'GET', 10).toUpperCase(), route, path: str(r.path || route, 300),
|
|
75
|
+
status: Math.trunc(num(r.status, 200)), ms: Math.max(0, num(r.ms)), ip: str(r.ip, 64),
|
|
76
|
+
now: ts > now + 60000 || ts < now - 400 * 864e5 ? now : ts,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
for (const l of (Array.isArray(body.logs) ? body.logs : []).slice(0, 2000)) src.logs.addAt(num(l.ts, now), str(l.level, 10), str(l.msg, 5000));
|
|
80
|
+
return [200, { ok: true }];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readBody(req, limit = 4 * 1024 * 1024) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
let size = 0; const chunks = [];
|
|
86
|
+
req.on('data', (c) => { size += c.length; if (size > limit) { reject(Object.assign(new Error('too large'), { code: 413 })); req.destroy(); } else chunks.push(c); });
|
|
87
|
+
req.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString() || '{}')); } catch { reject(Object.assign(new Error('invalid JSON'), { code: 400 })); } });
|
|
88
|
+
req.on('error', reject);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function handler(req, res) {
|
|
93
|
+
const pathname = (req.url || '/').split('?')[0];
|
|
94
|
+
const sub = pathname.startsWith(base) ? pathname.slice(base.length) || '/' : null;
|
|
95
|
+
const start = Date.now();
|
|
96
|
+
res.once('finish', () => { if (sub && sub.startsWith('/api/ingest')) self.metrics.record({ method: req.method, route: '/api/ingest', status: res.statusCode, ms: Date.now() - start, ip: req.socket.remoteAddress }); });
|
|
97
|
+
try {
|
|
98
|
+
if (sub === '/api/ingest' && req.method === 'POST') {
|
|
99
|
+
if (!key || !safeEqual((req.headers.authorization || '').replace(/^Bearer\s+/i, ''), key)) return json(res, 401, { error: 'invalid key' });
|
|
100
|
+
const [code, out] = ingest(await readBody(req));
|
|
101
|
+
return json(res, code, out);
|
|
102
|
+
}
|
|
103
|
+
if (sub && sub.startsWith('/api/') && req.method !== 'GET') {
|
|
104
|
+
if (!dash.authorized(req)) return json(res, 401, { error: 'auth required' });
|
|
105
|
+
if (sub === '/api/monitors' && req.method === 'POST') {
|
|
106
|
+
const b = await readBody(req, 16 * 1024);
|
|
107
|
+
let u; try { u = new URL(String(b.url)); } catch { return json(res, 400, { error: 'invalid url' }); }
|
|
108
|
+
if (!/^https?:$/.test(u.protocol)) return json(res, 400, { error: 'url must be http(s)' });
|
|
109
|
+
if (sources.size >= MAX_SERVERS) return json(res, 429, { error: 'server limit reached' });
|
|
110
|
+
const src = addSource(urlSource({ id: 'url-' + crypto.randomBytes(4).toString('hex'), name: str(b.name || u.host, 60), url: u.href, interval: checkInterval }));
|
|
111
|
+
save();
|
|
112
|
+
return json(res, 201, { id: src.id });
|
|
113
|
+
}
|
|
114
|
+
const m = sub.match(/^\/api\/servers\/([\w.-]+)$/);
|
|
115
|
+
if (m && req.method === 'DELETE') {
|
|
116
|
+
const src = sources.get(m[1]);
|
|
117
|
+
if (!src || src === self) return json(res, 404, { error: 'not found' });
|
|
118
|
+
src.close(); sources.delete(src.id); save();
|
|
119
|
+
return json(res, 200, { ok: true });
|
|
120
|
+
}
|
|
121
|
+
return json(res, 404, { error: 'not found' });
|
|
122
|
+
}
|
|
123
|
+
if (sub && dash.handle(req, res, pathname) !== false) return;
|
|
124
|
+
res.writeHead(sub === null ? 302 : 404, sub === null ? { Location: base + '/' } : { 'Content-Type': 'text/plain' });
|
|
125
|
+
res.end(sub === null ? '' : 'Not found');
|
|
126
|
+
} catch (e) {
|
|
127
|
+
if (!res.headersSent) json(res, e.code === 413 || e.code === 400 ? e.code : 500, { error: e.message });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const server = http.createServer(handler);
|
|
132
|
+
self.httpServer = server;
|
|
133
|
+
server.on('upgrade', (req, socket, head) => (dash.isWs(req) ? dash.handleUpgrade(req, socket, head) : socket.destroy()));
|
|
134
|
+
|
|
135
|
+
const shutdown = () => { save(); process.exit(0); };
|
|
136
|
+
if (opts.handleSignals !== false) { process.once('SIGINT', shutdown); process.once('SIGTERM', shutdown); }
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
server, handler, ingest, save, sources,
|
|
140
|
+
listen: (...args) => server.listen(...args),
|
|
141
|
+
close() { clearInterval(saver); save(); dash.close(); for (const s of sources.values()) s.close(); server.close(); },
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function sanitizeInfo(i, name) {
|
|
146
|
+
const out = { hostname: str(i.hostname || name, 120), ips: [] };
|
|
147
|
+
for (const k of ['runtime', 'platform', 'arch', 'cpuModel', 'env']) if (i[k] != null) out[k] = str(i[k], 120);
|
|
148
|
+
for (const k of ['port', 'pid', 'cpus', 'totalMem', 'startedAt', 'uptime', 'osUptime']) if (i[k] != null) out[k] = num(i[k]);
|
|
149
|
+
if (Array.isArray(i.ips)) out.ips = i.ips.slice(0, 16).map((x) => ({ name: str(x && x.name, 32), address: str(x && x.address, 64), family: str(x && x.family, 8) }));
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
module.exports = { createHub };
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse, Server } from 'http';
|
|
2
|
+
import type { Duplex } from 'stream';
|
|
3
|
+
|
|
4
|
+
export interface HubTarget {
|
|
5
|
+
/** Base URL of your Server Lens hub, e.g. https://lens.example.com */
|
|
6
|
+
url: string;
|
|
7
|
+
/** Ingest key (SERVER_LENS_KEY on the hub) */
|
|
8
|
+
key: string;
|
|
9
|
+
/** Stable id for this server. Default: `<hostname>-<port>` */
|
|
10
|
+
id?: string;
|
|
11
|
+
/** Display name in the hub. Default: `name` option or hostname */
|
|
12
|
+
name?: string;
|
|
13
|
+
/** Push interval in ms. Default 5000 */
|
|
14
|
+
interval?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ServerLensOptions {
|
|
18
|
+
/** Dashboard mount path. Default '/server-lens' */
|
|
19
|
+
path?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
/** Protect the dashboard with basic auth or a custom check */
|
|
23
|
+
auth?: { username: string; password: string } | ((req: IncomingMessage) => boolean);
|
|
24
|
+
/** Set false to only report to a hub (no embedded dashboard) */
|
|
25
|
+
dashboard?: boolean;
|
|
26
|
+
/** Report this server to a Server Lens hub */
|
|
27
|
+
hub?: HubTarget;
|
|
28
|
+
/** Capture console.log/info/warn/error/debug into live logs. Default true */
|
|
29
|
+
captureConsole?: boolean;
|
|
30
|
+
/** Paths (prefix string or RegExp) not to record */
|
|
31
|
+
ignore?: Array<string | RegExp>;
|
|
32
|
+
/** Live update interval in ms. Default 2000 */
|
|
33
|
+
interval?: number;
|
|
34
|
+
maxLogs?: number;
|
|
35
|
+
maxRoutes?: number;
|
|
36
|
+
maxRecent?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ServerLens {
|
|
40
|
+
(req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void): void;
|
|
41
|
+
attach(server: Server): ServerLens;
|
|
42
|
+
bind(server: Server): void;
|
|
43
|
+
isWs(req: IncomingMessage): boolean;
|
|
44
|
+
handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;
|
|
45
|
+
snapshot(): unknown;
|
|
46
|
+
log(level: 'debug' | 'info' | 'warn' | 'error', ...args: unknown[]): void;
|
|
47
|
+
close(): void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface HubOptions {
|
|
51
|
+
key: string;
|
|
52
|
+
path?: string;
|
|
53
|
+
title?: string;
|
|
54
|
+
name?: string;
|
|
55
|
+
auth?: { username: string; password: string } | ((req: IncomingMessage) => boolean);
|
|
56
|
+
/** JSON file for history. false = in-memory only */
|
|
57
|
+
dataFile?: string | false;
|
|
58
|
+
/** URL monitor interval, seconds. Default 30 */
|
|
59
|
+
checkInterval?: number;
|
|
60
|
+
interval?: number;
|
|
61
|
+
captureConsole?: boolean;
|
|
62
|
+
handleSignals?: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface Hub {
|
|
66
|
+
server: Server;
|
|
67
|
+
handler(req: IncomingMessage, res: ServerResponse): void;
|
|
68
|
+
listen: Server['listen'];
|
|
69
|
+
save(): void;
|
|
70
|
+
close(): void;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
declare function serverLens(opts?: ServerLensOptions): ServerLens;
|
|
74
|
+
declare namespace serverLens {
|
|
75
|
+
function instrument(opts?: ServerLensOptions): ServerLens;
|
|
76
|
+
function createHub(opts: HubOptions): Hub;
|
|
77
|
+
export { serverLens, instrument, createHub };
|
|
78
|
+
}
|
|
79
|
+
export default serverLens;
|
|
80
|
+
export = serverLens;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const http = require('http');
|
|
3
|
+
const https = require('https');
|
|
4
|
+
const { normalizePath } = require('./metrics');
|
|
5
|
+
const { localSource } = require('./source');
|
|
6
|
+
const { createDashboard, normBase } = require('./dashboard');
|
|
7
|
+
const { createHub } = require('./hub');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create a Server Lens agent. It is an Express/Connect-style middleware:
|
|
11
|
+
* app.use(serverLens())
|
|
12
|
+
* plain node http:
|
|
13
|
+
* http.createServer((req, res) => lens(req, res, () => handler(req, res)))
|
|
14
|
+
* or, for any Node server (Next.js, Fastify, Koa, NestJS…), use serverLens.instrument().
|
|
15
|
+
*/
|
|
16
|
+
function serverLens(opts = {}) {
|
|
17
|
+
const base = normBase(opts.path);
|
|
18
|
+
const ignore = opts.ignore || [];
|
|
19
|
+
const src = localSource({ name: opts.name, captureConsole: opts.captureConsole !== false, maxLogs: opts.maxLogs, maxRoutes: opts.maxRoutes, maxRecent: opts.maxRecent });
|
|
20
|
+
const metrics = src.metrics;
|
|
21
|
+
|
|
22
|
+
const dash = opts.dashboard === false ? null : createDashboard({
|
|
23
|
+
base, title: opts.title || 'Server Lens', auth: opts.auth, interval: opts.interval,
|
|
24
|
+
sources: { list: () => [src], get: () => src },
|
|
25
|
+
});
|
|
26
|
+
if (dash) dash.watch(src);
|
|
27
|
+
if (dash && !opts.auth && process.env.NODE_ENV === 'production') {
|
|
28
|
+
process.emitWarning(`server-lens: dashboard at ${base || '/'} has no auth. Pass { auth: { username, password } } in production.`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const reporter = opts.hub ? createReporter(opts.hub, src) : null;
|
|
32
|
+
let attached = false;
|
|
33
|
+
|
|
34
|
+
function bind(server) { if (!src.httpServer && server) src.httpServer = server; }
|
|
35
|
+
|
|
36
|
+
function attach(server) {
|
|
37
|
+
bind(server);
|
|
38
|
+
if (attached || !dash || !server || typeof server.on !== 'function') return lens;
|
|
39
|
+
attached = true;
|
|
40
|
+
server.on('upgrade', (req, socket, head) => { if (dash.isWs(req)) dash.handleUpgrade(req, socket, head); });
|
|
41
|
+
return lens;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function record(req, res, pathname) {
|
|
45
|
+
const start = process.hrtime.bigint();
|
|
46
|
+
res.once('finish', () => {
|
|
47
|
+
const ms = Number(process.hrtime.bigint() - start) / 1e6;
|
|
48
|
+
const route = req.route && typeof req.route.path === 'string' ? (req.baseUrl || '') + req.route.path : normalizePath(pathname);
|
|
49
|
+
const r = { method: req.method, route, status: res.statusCode, ms, path: pathname, ip: clientIp(req), now: Date.now() };
|
|
50
|
+
metrics.record(r);
|
|
51
|
+
if (reporter) reporter.request(r);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function lens(req, res, next) {
|
|
56
|
+
if (!attached && req.socket && req.socket.server) attach(req.socket.server);
|
|
57
|
+
const pathname = (req.originalUrl || req.url || '/').split('?')[0];
|
|
58
|
+
if (dash && (pathname === base || pathname.startsWith(`${base}/`))) {
|
|
59
|
+
if (dash.handle(req, res, pathname) !== false) return;
|
|
60
|
+
}
|
|
61
|
+
if (!ignore.some((p) => (p instanceof RegExp ? p.test(pathname) : pathname.startsWith(p)))) record(req, res, pathname);
|
|
62
|
+
if (next) next();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
lens.attach = attach;
|
|
66
|
+
lens.bind = bind;
|
|
67
|
+
lens.isWs = (req) => !!dash && dash.isWs(req);
|
|
68
|
+
lens.handleUpgrade = (req, socket, head) => dash.handleUpgrade(req, socket, head);
|
|
69
|
+
lens.snapshot = () => dash && dash.snapshot(src);
|
|
70
|
+
lens.metrics = metrics;
|
|
71
|
+
lens.logs = src.logs;
|
|
72
|
+
/** Push a line from any logger (pino, winston, …) into the live log stream. */
|
|
73
|
+
lens.log = (level, ...args) => src.logs.add(level, ...args);
|
|
74
|
+
lens.close = () => { if (dash) dash.close(); if (reporter) reporter.stop(); src.close(); };
|
|
75
|
+
return lens;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Monitor every HTTP server in this Node process without touching your routes.
|
|
80
|
+
* Works with Next.js (instrumentation.ts), Fastify, Koa, NestJS, Hapi, raw http/https.
|
|
81
|
+
*/
|
|
82
|
+
function instrument(opts = {}) {
|
|
83
|
+
if (instrument.lens) return instrument.lens;
|
|
84
|
+
const lens = serverLens({ ...opts, ignore: ['/_next/', '/__nextjs', '/favicon.ico', ...(opts.ignore || [])] });
|
|
85
|
+
for (const S of [http.Server, https.Server]) {
|
|
86
|
+
const orig = S.prototype.emit;
|
|
87
|
+
S.prototype.emit = function (ev, a, b, c) {
|
|
88
|
+
if (ev === 'request') { lens.bind(this); lens(a, b, () => orig.call(this, ev, a, b)); return true; }
|
|
89
|
+
if (ev === 'upgrade' && lens.isWs(a)) { lens.bind(this); lens.handleUpgrade(a, b, c); return true; }
|
|
90
|
+
return orig.apply(this, arguments);
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
instrument.lens = lens;
|
|
94
|
+
return lens;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Batches requests, logs and system samples and pushes them to a Server Lens hub. */
|
|
98
|
+
function createReporter({ url, key, id, name, interval = 5000 }, src) {
|
|
99
|
+
if (!url) throw new Error('server-lens: hub.url is required');
|
|
100
|
+
const endpoint = `${String(url).replace(/\/+$/, '')}/api/ingest`;
|
|
101
|
+
let requests = [], logs = [], warned = false, busy = false;
|
|
102
|
+
src.logs.on('log', (e) => { logs.push({ ts: e.ts, level: e.level, msg: e.msg }); if (logs.length > 1000) logs.shift(); });
|
|
103
|
+
|
|
104
|
+
async function flush() {
|
|
105
|
+
if (busy) return;
|
|
106
|
+
busy = true;
|
|
107
|
+
const info = src.info();
|
|
108
|
+
const body = {
|
|
109
|
+
id: id || `${info.hostname}-${info.port || 'app'}`.toLowerCase().replace(/[^\w.-]+/g, '-'),
|
|
110
|
+
name: name || src.name, info,
|
|
111
|
+
sample: src.metrics.samples[src.metrics.samples.length - 1],
|
|
112
|
+
requests: requests.slice(0, 5000), logs: logs.slice(0, 1000),
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
const res = await fetch(endpoint, {
|
|
116
|
+
method: 'POST', body: JSON.stringify(body), signal: AbortSignal.timeout(8000),
|
|
117
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key || ''}` },
|
|
118
|
+
});
|
|
119
|
+
if (!res.ok) throw new Error(`hub responded ${res.status}`);
|
|
120
|
+
requests.splice(0, body.requests.length);
|
|
121
|
+
logs.splice(0, body.logs.length);
|
|
122
|
+
warned = false;
|
|
123
|
+
} catch (e) {
|
|
124
|
+
if (!warned) { warned = true; process.stderr.write(`server-lens: cannot reach hub ${endpoint} (${e.message}); will retry\n`); }
|
|
125
|
+
} finally { busy = false; }
|
|
126
|
+
}
|
|
127
|
+
const timer = setInterval(flush, interval);
|
|
128
|
+
timer.unref();
|
|
129
|
+
setTimeout(flush, 500).unref();
|
|
130
|
+
return {
|
|
131
|
+
request(r) { requests.push({ ts: r.now, method: r.method, route: r.route, path: r.path, status: r.status, ms: r.ms, ip: r.ip }); if (requests.length > 20000) requests.shift(); },
|
|
132
|
+
stop: () => clearInterval(timer),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function clientIp(req) {
|
|
137
|
+
const fwd = req.headers['x-forwarded-for'];
|
|
138
|
+
return (fwd ? String(fwd).split(',')[0].trim() : (req.socket && req.socket.remoteAddress) || '').replace(/^::ffff:/, '');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = serverLens;
|
|
142
|
+
module.exports.default = serverLens;
|
|
143
|
+
module.exports.serverLens = serverLens;
|
|
144
|
+
module.exports.instrument = instrument;
|
|
145
|
+
module.exports.createHub = createHub;
|
package/src/logs.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const util = require('util');
|
|
3
|
+
const { EventEmitter } = require('events');
|
|
4
|
+
|
|
5
|
+
const LEVELS = ['debug', 'info', 'warn', 'error'];
|
|
6
|
+
|
|
7
|
+
class LogStore extends EventEmitter {
|
|
8
|
+
constructor({ max = 1000 } = {}) {
|
|
9
|
+
super();
|
|
10
|
+
this.max = max;
|
|
11
|
+
this.entries = [];
|
|
12
|
+
this.seq = 0;
|
|
13
|
+
this.restore = null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
add(level, ...args) { return this.addAt(Date.now(), level, util.format(...args)); }
|
|
17
|
+
|
|
18
|
+
addAt(ts, level, msg) {
|
|
19
|
+
const entry = {
|
|
20
|
+
id: ++this.seq,
|
|
21
|
+
ts,
|
|
22
|
+
level: LEVELS.includes(level) ? level : 'info',
|
|
23
|
+
msg: String(msg).slice(0, 5000),
|
|
24
|
+
};
|
|
25
|
+
this.entries.push(entry);
|
|
26
|
+
if (this.entries.length > this.max) this.entries.shift();
|
|
27
|
+
this.emit('log', entry);
|
|
28
|
+
return entry;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
captureConsole() {
|
|
32
|
+
if (this.restore) return;
|
|
33
|
+
const map = { log: 'info', info: 'info', warn: 'warn', error: 'error', debug: 'debug' };
|
|
34
|
+
const originals = {};
|
|
35
|
+
for (const [method, level] of Object.entries(map)) {
|
|
36
|
+
originals[method] = console[method];
|
|
37
|
+
console[method] = (...args) => {
|
|
38
|
+
originals[method].apply(console, args);
|
|
39
|
+
try { this.add(level, ...args); } catch { /* never break the host app's logging */ }
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
this.restore = () => { Object.assign(console, originals); this.restore = null; };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { LogStore, LEVELS };
|