@obzerver/server 0.7.0 → 0.8.5
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/dist/ai.js +4 -1
- package/dist/ai.js.map +1 -1
- package/dist/alerts.d.ts +8 -0
- package/dist/alerts.js +24 -1
- package/dist/alerts.js.map +1 -1
- package/dist/cli.js +7 -1
- package/dist/cli.js.map +1 -1
- package/dist/db.js +12 -0
- package/dist/db.js.map +1 -1
- package/dist/history.d.ts +188 -0
- package/dist/history.js +719 -0
- package/dist/history.js.map +1 -0
- package/dist/ingest.js +3 -2
- package/dist/ingest.js.map +1 -1
- package/dist/mcp.js +31 -2
- package/dist/mcp.js.map +1 -1
- package/dist/queries.d.ts +183 -1
- package/dist/queries.js +152 -4
- package/dist/queries.js.map +1 -1
- package/dist/seed.js +7 -1
- package/dist/seed.js.map +1 -1
- package/dist/server.d.ts +6 -0
- package/dist/server.js +24 -1
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
- package/public/assets/index-BCwlmKvv.js +568 -0
- package/public/assets/index-kvsNQU77.css +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-BZ2yBc5m.js +0 -543
- package/public/assets/index-CE6iYy2L.css +0 -1
package/dist/history.js
ADDED
|
@@ -0,0 +1,719 @@
|
|
|
1
|
+
// Long-term memory: hourly roll-ups of raw telemetry that outlive raw retention, merged into daily
|
|
2
|
+
// roll-ups after `hourlyDays`, and seasonal baselines ("what is normal for this hour") computed from them.
|
|
3
|
+
//
|
|
4
|
+
// Latency is kept as a log-bucketed histogram (relative error ~5%), so hours merge into days and
|
|
5
|
+
// percentiles stay correct after merging. Roll-ups never store payloads, ids or user data.
|
|
6
|
+
import { getSetting, setSetting } from './db.js';
|
|
7
|
+
export const HOUR = 3600e3;
|
|
8
|
+
export const DAY = 24 * HOUR;
|
|
9
|
+
export const WEEK = 7 * DAY;
|
|
10
|
+
const GAMMA = 1.1;
|
|
11
|
+
const LN_G = Math.log(GAMMA);
|
|
12
|
+
const MIN_BUCKET = -49; // everything <= 0.01 ms
|
|
13
|
+
/** SQL expression for the histogram bucket of a millisecond value. */
|
|
14
|
+
const BUCKET = (col) => `CASE WHEN ${col} <= 0.01 THEN ${MIN_BUCKET} ELSE CAST(ceil(ln(${col}) / ${LN_G}) AS INTEGER) END`;
|
|
15
|
+
/** Raw data younger than this may still be arriving from SDK buffers; its hour is rolled up later. */
|
|
16
|
+
const GRACE_MS = 5 * 60000;
|
|
17
|
+
// ---------------------------------------------------------------- histograms
|
|
18
|
+
export const bucketOf = (v) => (v <= 0.01 ? MIN_BUCKET : Math.ceil(Math.log(v) / LN_G));
|
|
19
|
+
const valueOf = (b) => (b <= MIN_BUCKET ? 0.01 : (2 * GAMMA ** b) / (GAMMA + 1));
|
|
20
|
+
export function histAdd(h, v, c = 1) { const k = String(bucketOf(v)); h[k] = (h[k] || 0) + c; return h; }
|
|
21
|
+
export function histMerge(a, b) { for (const [k, c] of Object.entries(b))
|
|
22
|
+
a[k] = (a[k] || 0) + c; return a; }
|
|
23
|
+
export function quantile(h, q, max) {
|
|
24
|
+
const keys = Object.keys(h).map(Number).sort((a, b) => a - b);
|
|
25
|
+
const total = keys.reduce((s, k) => s + h[k], 0);
|
|
26
|
+
if (!total)
|
|
27
|
+
return null;
|
|
28
|
+
const target = (q / 100) * total;
|
|
29
|
+
let acc = 0;
|
|
30
|
+
for (const k of keys) {
|
|
31
|
+
acc += h[k];
|
|
32
|
+
if (acc >= target) {
|
|
33
|
+
const v = valueOf(k);
|
|
34
|
+
return max != null ? Math.min(v, max) : v;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return valueOf(keys[keys.length - 1]);
|
|
38
|
+
}
|
|
39
|
+
const r1 = (v, d = 1) => (v == null || !Number.isFinite(v) ? null : Math.round(v * 10 ** d) / 10 ** d);
|
|
40
|
+
// ---------------------------------------------------------------- merging
|
|
41
|
+
function mergeX(a, b) {
|
|
42
|
+
for (const [k, v] of Object.entries(b)) {
|
|
43
|
+
if (typeof v === 'number')
|
|
44
|
+
a[k] = k.endsWith('Max') ? Math.max(a[k] ?? -Infinity, v) : (a[k] || 0) + v;
|
|
45
|
+
else if (v && typeof v === 'object')
|
|
46
|
+
a[k] = histMerge(a[k] || {}, v);
|
|
47
|
+
}
|
|
48
|
+
return a;
|
|
49
|
+
}
|
|
50
|
+
function mergeInto(a, b) {
|
|
51
|
+
a.n += b.n;
|
|
52
|
+
a.failed += b.failed;
|
|
53
|
+
a.sum += b.sum;
|
|
54
|
+
a.max = a.max == null ? b.max : b.max == null ? a.max : Math.max(a.max, b.max);
|
|
55
|
+
histMerge(a.hist, b.hist);
|
|
56
|
+
mergeX(a.x, b.x);
|
|
57
|
+
return a;
|
|
58
|
+
}
|
|
59
|
+
const emptyRow = (res, series, t, service, kind, name, version) => ({ res, series, t, service, kind, name, version, n: 0, failed: 0, sum: 0, max: null, hist: {}, x: {} });
|
|
60
|
+
const keyOf = (r) => [r.series, r.t, r.service, r.kind, r.name, r.version].join('\u0000');
|
|
61
|
+
function parse(r) {
|
|
62
|
+
return { ...r, hist: r.hist ? JSON.parse(r.hist) : {}, x: r.x ? JSON.parse(r.x) : {} };
|
|
63
|
+
}
|
|
64
|
+
/** Counts and sums stay exact for real data; merged or scaled values are kept to 2 decimals. */
|
|
65
|
+
const tidy = (_k, v) => (typeof v === 'number' && !Number.isInteger(v) ? Math.round(v * 100) / 100 : v);
|
|
66
|
+
function write(db, rows) {
|
|
67
|
+
const st = db.prepare(`INSERT OR REPLACE INTO history(res, series, t, service, kind, name, version, n, failed, sum, max, hist, x)
|
|
68
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
69
|
+
for (const r of rows) {
|
|
70
|
+
st.run(r.res, r.series, r.t, r.service, r.kind, r.name, r.version, r.n, r.failed, r.sum, r.max, Object.keys(r.hist).length ? JSON.stringify(r.hist, tidy) : null, Object.keys(r.x).length ? JSON.stringify(r.x, tidy) : null);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// ---------------------------------------------------------------- roll-up
|
|
74
|
+
/** Builds the hourly roll-up for [h, h + 1h) from raw tables. Idempotent: replaces that hour. */
|
|
75
|
+
export function rollHour(db, h) {
|
|
76
|
+
const to = h + HOUR;
|
|
77
|
+
const rows = new Map();
|
|
78
|
+
const at = (series, service, kind, name, version = '') => {
|
|
79
|
+
const r = emptyRow('h', series, h, service ?? '', kind ?? '', name ?? '', version ?? '');
|
|
80
|
+
const k = keyOf(r);
|
|
81
|
+
let cur = rows.get(k);
|
|
82
|
+
if (!cur) {
|
|
83
|
+
cur = r;
|
|
84
|
+
rows.set(k, cur);
|
|
85
|
+
}
|
|
86
|
+
return cur;
|
|
87
|
+
};
|
|
88
|
+
// Requests and jobs, by version.
|
|
89
|
+
for (const r of db.all(`SELECT service, kind, name, COALESCE(version, '') version, ${BUCKET('duration')} b, COUNT(*) n, SUM(failed) f, SUM(duration) s, MAX(duration) mx,
|
|
90
|
+
SUM(CASE WHEN status >= 400 AND status < 500 THEN 1 ELSE 0 END) s4, SUM(CASE WHEN status >= 500 THEN 1 ELSE 0 END) s5
|
|
91
|
+
FROM traces WHERE ts >= ? AND ts < ? GROUP BY service, kind, name, version, b`, h, to)) {
|
|
92
|
+
const o = at('op', r.service, r.kind, r.name, r.version);
|
|
93
|
+
o.n += r.n;
|
|
94
|
+
o.failed += r.f || 0;
|
|
95
|
+
o.sum += r.s || 0;
|
|
96
|
+
o.max = Math.max(o.max ?? 0, r.mx ?? 0);
|
|
97
|
+
o.hist[String(r.b)] = (o.hist[String(r.b)] || 0) + r.n;
|
|
98
|
+
mergeX(o.x, { s4: r.s4 || 0, s5: r.s5 || 0 });
|
|
99
|
+
}
|
|
100
|
+
for (const r of db.all(`SELECT service, kind, name, COALESCE(version, '') version, ${BUCKET('queue_wait')} b, COUNT(*) n, SUM(queue_wait) s
|
|
101
|
+
FROM traces WHERE kind = 'job' AND queue_wait IS NOT NULL AND ts >= ? AND ts < ? GROUP BY service, kind, name, version, b`, h, to)) {
|
|
102
|
+
mergeX(at('op', r.service, r.kind, r.name, r.version).x, { qw: { [String(r.b)]: r.n }, qwN: r.n, qwSum: r.s || 0 });
|
|
103
|
+
}
|
|
104
|
+
for (const r of totalsOf([...rows.values()]))
|
|
105
|
+
rows.set(keyOf(r), r);
|
|
106
|
+
// Dependencies (databases, Redis, outbound hosts) and code (service methods, handlers, middleware).
|
|
107
|
+
const per = 'duration / MAX("count", 1)';
|
|
108
|
+
for (const r of db.all(`SELECT service, kind, CASE WHEN kind = 'db' THEN COALESCE(system, 'db') WHEN kind = 'http' THEN COALESCE(host, name) ELSE name END target,
|
|
109
|
+
${BUCKET(per)} b, SUM(MAX("count", 1)) n, SUM(error) f, SUM(duration) s, MAX(${per}) mx, SUM(self) self
|
|
110
|
+
FROM spans WHERE ts >= ? AND ts < ? GROUP BY service, kind, target, b`, h, to)) {
|
|
111
|
+
const o = at('dep', r.service, r.kind, r.target);
|
|
112
|
+
o.n += r.n;
|
|
113
|
+
o.failed += r.f || 0;
|
|
114
|
+
o.sum += r.s || 0;
|
|
115
|
+
o.max = Math.max(o.max ?? 0, r.mx ?? 0);
|
|
116
|
+
o.hist[String(r.b)] = (o.hist[String(r.b)] || 0) + r.n;
|
|
117
|
+
mergeX(o.x, { self: r.self || 0 });
|
|
118
|
+
}
|
|
119
|
+
// SQL statements (values already stripped by the SDK): the 50 costliest per service and hour.
|
|
120
|
+
const sql = new Map();
|
|
121
|
+
for (const r of db.all(`SELECT service, COALESCE(system, 'db') system, SUBSTR(COALESCE(statement, name), 1, 500) stmt, ${BUCKET(per)} b, SUM(MAX("count", 1)) n, SUM(error) f, SUM(duration) s, MAX(${per}) mx
|
|
122
|
+
FROM spans WHERE kind = 'db' AND ts >= ? AND ts < ? GROUP BY service, system, stmt, b`, h, to)) {
|
|
123
|
+
const k = `${r.service}\u0000${r.system}\u0000${r.stmt}`;
|
|
124
|
+
let o = sql.get(k);
|
|
125
|
+
if (!o) {
|
|
126
|
+
o = emptyRow('h', 'sql', h, r.service, r.system, r.stmt, '');
|
|
127
|
+
sql.set(k, o);
|
|
128
|
+
}
|
|
129
|
+
o.n += r.n;
|
|
130
|
+
o.failed += r.f || 0;
|
|
131
|
+
o.sum += r.s || 0;
|
|
132
|
+
o.max = Math.max(o.max ?? 0, r.mx ?? 0);
|
|
133
|
+
o.hist[String(r.b)] = (o.hist[String(r.b)] || 0) + r.n;
|
|
134
|
+
}
|
|
135
|
+
const bySvc = new Map();
|
|
136
|
+
for (const o of sql.values())
|
|
137
|
+
bySvc.set(o.service, [...(bySvc.get(o.service) || []), o]);
|
|
138
|
+
for (const list of bySvc.values())
|
|
139
|
+
for (const o of list.sort((a, b) => b.sum - a.sum).slice(0, 50))
|
|
140
|
+
rows.set(keyOf(o), o);
|
|
141
|
+
// Errors per group and version.
|
|
142
|
+
for (const r of db.all(`SELECT service, fingerprint, COALESCE(version, '') version, handled, COUNT(*) n FROM errors WHERE ts >= ? AND ts < ? GROUP BY service, fingerprint, version, handled`, h, to)) {
|
|
143
|
+
at('err', r.service, r.handled ? 'handled' : 'unhandled', r.fingerprint, r.version).n += r.n;
|
|
144
|
+
}
|
|
145
|
+
// Host pressure per service.
|
|
146
|
+
for (const r of db.all(`SELECT service, COUNT(*) n, SUM(cpu) cpu, SUM(rss) rss, SUM(el_p99) el, MAX(el_p99) elMax, SUM(elu) elu FROM runtime WHERE ts >= ? AND ts < ? GROUP BY service`, h, to)) {
|
|
147
|
+
const o = at('rt', r.service, 'runtime', '');
|
|
148
|
+
o.n += r.n;
|
|
149
|
+
mergeX(o.x, { cpu: r.cpu || 0, rss: r.rss || 0, elP99: r.el || 0, elP99Max: r.elMax || 0, elu: r.elu || 0 });
|
|
150
|
+
}
|
|
151
|
+
db.tx(() => {
|
|
152
|
+
db.run("DELETE FROM history WHERE res = 'h' AND t = ?", h);
|
|
153
|
+
write(db, rows.values());
|
|
154
|
+
});
|
|
155
|
+
return rows.size;
|
|
156
|
+
}
|
|
157
|
+
const floorHour = (t) => Math.floor(t / HOUR) * HOUR;
|
|
158
|
+
/** Per-service totals of 'op' rows (one per service, kind and time slot). */
|
|
159
|
+
function totalsOf(rows) {
|
|
160
|
+
const out = new Map();
|
|
161
|
+
for (const r of rows) {
|
|
162
|
+
if (r.series !== 'op')
|
|
163
|
+
continue;
|
|
164
|
+
const t = { ...emptyRow(r.res, 'tot', r.t, r.service, r.kind, '', '') };
|
|
165
|
+
const k = keyOf(t);
|
|
166
|
+
const cur = out.get(k);
|
|
167
|
+
if (cur)
|
|
168
|
+
mergeInto(cur, r);
|
|
169
|
+
else
|
|
170
|
+
out.set(k, mergeInto(t, r));
|
|
171
|
+
}
|
|
172
|
+
return [...out.values()];
|
|
173
|
+
}
|
|
174
|
+
/** Roll-ups written before per-service totals existed get them once. */
|
|
175
|
+
function backfillTotals(db) {
|
|
176
|
+
if (getSetting(db, 'history_totals') || !db.get("SELECT 1 FROM history WHERE series = 'op' LIMIT 1")) {
|
|
177
|
+
setSetting(db, 'history_totals', '1');
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const ts = db.all("SELECT DISTINCT res, t FROM history WHERE series = 'op'");
|
|
181
|
+
db.tx(() => { for (const { res, t } of ts)
|
|
182
|
+
write(db, totalsOf(db.all("SELECT * FROM history WHERE series = 'op' AND res = ? AND t = ?", res, t).map(parse))); });
|
|
183
|
+
setSetting(db, 'history_totals', '1');
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Rolls up every finished hour not yet rolled up. Starts from the oldest raw data on first run, so an
|
|
187
|
+
* existing install keeps the days it already has. Bounded per call so a big backfill never blocks for long.
|
|
188
|
+
*/
|
|
189
|
+
export function rollup(db, now = Date.now(), maxHours = 48) {
|
|
190
|
+
let until = Number(getSetting(db, 'history_until')) || 0;
|
|
191
|
+
if (!until) {
|
|
192
|
+
const oldest = db.get('SELECT MIN(ts) t FROM traces').t;
|
|
193
|
+
until = floorHour(oldest ?? now - GRACE_MS);
|
|
194
|
+
}
|
|
195
|
+
let hours = 0;
|
|
196
|
+
while (until + HOUR <= now - GRACE_MS && hours < maxHours) {
|
|
197
|
+
rollHour(db, until);
|
|
198
|
+
until += HOUR;
|
|
199
|
+
hours++;
|
|
200
|
+
setSetting(db, 'history_until', String(until));
|
|
201
|
+
}
|
|
202
|
+
return { hours, until };
|
|
203
|
+
}
|
|
204
|
+
/** Re-reads raw data from `from` on (used after demo data is generated into the past). */
|
|
205
|
+
export function rebuild(db, from, now = Date.now()) {
|
|
206
|
+
setSetting(db, 'history_until', String(floorHour(from)));
|
|
207
|
+
let total = 0;
|
|
208
|
+
for (;;) {
|
|
209
|
+
const r = rollup(db, now, 1000);
|
|
210
|
+
total += r.hours;
|
|
211
|
+
if (r.hours < 1000)
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
return total;
|
|
215
|
+
}
|
|
216
|
+
/** Merges hourly rows older than `hourlyDays` into daily rows, and drops daily rows older than `days`. */
|
|
217
|
+
export function compact(db, { hourlyDays, days }, now = Date.now(), maxDays = 30) {
|
|
218
|
+
const cutoff = Math.floor((now - hourlyDays * DAY) / DAY) * DAY;
|
|
219
|
+
let merged = 0;
|
|
220
|
+
for (let i = 0; i < maxDays; i++) {
|
|
221
|
+
const oldest = db.get("SELECT MIN(t) t FROM history WHERE res = 'h' AND t < ?", cutoff).t;
|
|
222
|
+
if (oldest == null)
|
|
223
|
+
break;
|
|
224
|
+
const day = Math.floor(oldest / DAY) * DAY;
|
|
225
|
+
const out = new Map();
|
|
226
|
+
for (const raw of db.all("SELECT * FROM history WHERE res = 'd' AND t = ?", day)) {
|
|
227
|
+
const r = parse(raw);
|
|
228
|
+
out.set(keyOf(r), r);
|
|
229
|
+
}
|
|
230
|
+
for (const raw of db.all("SELECT * FROM history WHERE res = 'h' AND t >= ? AND t < ?", day, day + DAY)) {
|
|
231
|
+
const r = { ...parse(raw), res: 'd', t: day };
|
|
232
|
+
const k = keyOf(r);
|
|
233
|
+
const cur = out.get(k);
|
|
234
|
+
out.set(k, cur ? mergeInto(cur, r) : r);
|
|
235
|
+
}
|
|
236
|
+
db.tx(() => {
|
|
237
|
+
write(db, out.values());
|
|
238
|
+
db.run("DELETE FROM history WHERE res = 'h' AND t >= ? AND t < ?", day, day + DAY);
|
|
239
|
+
});
|
|
240
|
+
merged++;
|
|
241
|
+
}
|
|
242
|
+
db.run("DELETE FROM history WHERE res = 'd' AND t < ?", now - days * DAY);
|
|
243
|
+
return merged;
|
|
244
|
+
}
|
|
245
|
+
/** The background job: roll up, then compact. Runs before raw retention so nothing is lost. */
|
|
246
|
+
export function historyTick(db, cfg, now = Date.now(), maxHours = 48) {
|
|
247
|
+
backfillTotals(db);
|
|
248
|
+
rollup(db, now, maxHours);
|
|
249
|
+
compact(db, cfg, now);
|
|
250
|
+
}
|
|
251
|
+
export function historyInfo(db, cfg) {
|
|
252
|
+
const r = db.get("SELECT COUNT(*) n, MIN(t) oldest, MIN(CASE WHEN res = 'h' THEN t END) hourly FROM history");
|
|
253
|
+
let pages = null;
|
|
254
|
+
try {
|
|
255
|
+
pages = db.get("SELECT SUM(pgsize) n FROM dbstat WHERE name IN ('history', 'history_name')")?.n ?? null;
|
|
256
|
+
}
|
|
257
|
+
catch { /* dbstat not compiled in */ }
|
|
258
|
+
return { rows: r.n, oldest: r.oldest, hourlyFrom: r.hourly, rolledUntil: Number(getSetting(db, 'history_until')) || null, bytes: pages, ...cfg };
|
|
259
|
+
}
|
|
260
|
+
function load(db, f, from, to, res) {
|
|
261
|
+
const cond = ['series = ?', 't >= ?', 't < ?'];
|
|
262
|
+
const args = [f.series || 'op', from, to];
|
|
263
|
+
if (res) {
|
|
264
|
+
cond.push('res = ?');
|
|
265
|
+
args.push(res);
|
|
266
|
+
}
|
|
267
|
+
if (f.kind) {
|
|
268
|
+
cond.push('kind = ?');
|
|
269
|
+
args.push(f.kind);
|
|
270
|
+
}
|
|
271
|
+
if (f.service) {
|
|
272
|
+
cond.push('service = ?');
|
|
273
|
+
args.push(f.service);
|
|
274
|
+
}
|
|
275
|
+
if (f.name != null && f.name !== '') {
|
|
276
|
+
cond.push('name = ?');
|
|
277
|
+
args.push(f.name);
|
|
278
|
+
}
|
|
279
|
+
if (f.version) {
|
|
280
|
+
cond.push('version = ?');
|
|
281
|
+
args.push(f.version);
|
|
282
|
+
}
|
|
283
|
+
return db.all(`SELECT * FROM history WHERE ${cond.join(' AND ')}`, ...args).map(parse);
|
|
284
|
+
}
|
|
285
|
+
/** Without a route or job name, baselines read the per-service totals (far fewer rows than every route). */
|
|
286
|
+
const totals = (f) => (f.series === 'op' || !f.series) && !f.name ? { ...f, series: 'tot' } : f;
|
|
287
|
+
/** Collapses rows to one per time slot (all names/versions/services merged). */
|
|
288
|
+
function bySlot(rows, slot = (t) => t) {
|
|
289
|
+
const out = new Map();
|
|
290
|
+
for (const r of rows) {
|
|
291
|
+
const t = slot(r.t);
|
|
292
|
+
const cur = out.get(t);
|
|
293
|
+
if (cur)
|
|
294
|
+
mergeInto(cur, r);
|
|
295
|
+
else
|
|
296
|
+
out.set(t, mergeInto(emptyRow(r.res, r.series, t, '', '', '', ''), r));
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
export function statsOf(r) {
|
|
301
|
+
return {
|
|
302
|
+
calls: Math.round(r.n), failed: Math.round(r.failed), failureRate: r.n ? r1((r.failed / r.n) * 100, 2) : 0,
|
|
303
|
+
avg: r.n ? r1(r.sum / r.n) : null, p50: r1(quantile(r.hist, 50, r.max)), p95: r1(quantile(r.hist, 95, r.max)), p99: r1(quantile(r.hist, 99, r.max)), max: r1(r.max),
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
const median = (v) => { const s = [...v].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
|
|
307
|
+
/** Robust normal range: median ± 3 scaled MADs, never narrower than ±(rel × median) or ±abs. */
|
|
308
|
+
function rangeOf(values, rel, abs) {
|
|
309
|
+
const v = values.filter((x) => Number.isFinite(x));
|
|
310
|
+
if (v.length < 3)
|
|
311
|
+
return null;
|
|
312
|
+
const med = median(v);
|
|
313
|
+
const half = Math.max(3 * 1.4826 * median(v.map((x) => Math.abs(x - med))), rel * med, abs);
|
|
314
|
+
return { expected: r1(med, 2), low: r1(Math.max(0, med - half), 2), high: r1(med + half, 2) };
|
|
315
|
+
}
|
|
316
|
+
const MIN_CALLS = 5;
|
|
317
|
+
const WEEKS = 8;
|
|
318
|
+
const DAYS = 14;
|
|
319
|
+
function baselineFrom(slots, at, kind) {
|
|
320
|
+
const h = floorHour(at);
|
|
321
|
+
const pick = (step, k) => Array.from({ length: k }, (_, i) => slots.get(h - (i + 1) * step)).filter((r) => !!r && r.n > 0);
|
|
322
|
+
const weekly = pick(WEEK, WEEKS);
|
|
323
|
+
const daily = pick(DAY, DAYS);
|
|
324
|
+
const basis = weekly.length >= 3 ? 'week' : daily.length >= 3 ? 'day' : null;
|
|
325
|
+
const used = basis === 'week' ? weekly : basis === 'day' ? daily : [];
|
|
326
|
+
const withCalls = used.filter((r) => r.n >= MIN_CALLS);
|
|
327
|
+
const lat = (q) => withCalls.map((r) => quantile(r.hist, q, r.max) ?? NaN);
|
|
328
|
+
const qw = used.filter((r) => r.x.qwN >= MIN_CALLS).map((r) => quantile(r.x.qw, 95) ?? NaN);
|
|
329
|
+
const when = new Date(h).toISOString().slice(11, 16);
|
|
330
|
+
return {
|
|
331
|
+
at: h, basis, samples: used.length,
|
|
332
|
+
description: basis === 'week' ? `same hour (${when} UTC) on the same weekday over the last ${weekly.length} weeks`
|
|
333
|
+
: basis === 'day' ? `same hour (${when} UTC) over the last ${daily.length} days`
|
|
334
|
+
: 'not enough history yet (needs this hour on at least 3 earlier days)',
|
|
335
|
+
callsPerHour: rangeOf(used.map((r) => r.n), 0.3, 3),
|
|
336
|
+
failureRate: rangeOf(withCalls.map((r) => (r.failed / r.n) * 100), 0.5, 0.5),
|
|
337
|
+
avg: rangeOf(withCalls.map((r) => r.sum / r.n), 0.25, 1),
|
|
338
|
+
p50: rangeOf(lat(50), 0.25, 1),
|
|
339
|
+
p95: rangeOf(lat(95), 0.3, 2),
|
|
340
|
+
queueWaitP95: kind === 'job' ? rangeOf(qw, 0.4, 5) : null,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/** What is normal for this route, job, dependency or service at `at`, learned from past weeks (or days). */
|
|
344
|
+
export function baseline(db, f, at = Date.now()) {
|
|
345
|
+
const h = floorHour(at);
|
|
346
|
+
const rows = load(db, totals(f), h - WEEKS * WEEK, h, 'h').filter((r) => (h - r.t) % DAY === 0);
|
|
347
|
+
return baselineFrom(bySlot(rows), at, f.kind);
|
|
348
|
+
}
|
|
349
|
+
/** Normal ranges for each chart bucket of a window (one baseline per hour), scaled to the bucket size. */
|
|
350
|
+
export function band(db, f, starts, bucketMs) {
|
|
351
|
+
if (!starts.length || starts[starts.length - 1] - starts[0] > 8 * DAY)
|
|
352
|
+
return null;
|
|
353
|
+
const first = floorHour(starts[0]);
|
|
354
|
+
const slots = bySlot(load(db, totals(f), first - WEEKS * WEEK, floorHour(starts[starts.length - 1]), 'h'));
|
|
355
|
+
const cache = new Map();
|
|
356
|
+
const scale = bucketMs / HOUR;
|
|
357
|
+
const sc = (r, k) => (r ? { expected: r1(r.expected * k, 2), low: r1(r.low * k, 2), high: r1(r.high * k, 2) } : null);
|
|
358
|
+
let any = false;
|
|
359
|
+
const out = starts.map((t) => {
|
|
360
|
+
const h = floorHour(t);
|
|
361
|
+
let b = cache.get(h);
|
|
362
|
+
if (!b) {
|
|
363
|
+
b = baselineFrom(slots, h, f.kind);
|
|
364
|
+
cache.set(h, b);
|
|
365
|
+
}
|
|
366
|
+
if (b.basis)
|
|
367
|
+
any = true;
|
|
368
|
+
return { t, basis: b.basis, calls: sc(b.callsPerHour, scale), p95: b.p95, failureRate: b.failureRate };
|
|
369
|
+
});
|
|
370
|
+
return any ? out : null;
|
|
371
|
+
}
|
|
372
|
+
/** The long view: a route's (or job's, dependency's, service's) typical numbers over the last weeks. */
|
|
373
|
+
export function typical(db, f, now = Date.now(), days = 28) {
|
|
374
|
+
const from = now - days * DAY;
|
|
375
|
+
const rows = [...load(db, totals(f), from, now, 'h'), ...load(db, totals(f), from, now, 'd')];
|
|
376
|
+
if (!rows.length)
|
|
377
|
+
return null;
|
|
378
|
+
const all = [...bySlot(rows, () => 0).values()][0];
|
|
379
|
+
const recent = [...bySlot(rows.filter((r) => r.t >= now - 7 * DAY), () => 0).values()][0];
|
|
380
|
+
const before = [...bySlot(rows.filter((r) => r.t < now - 7 * DAY), () => 0).values()][0];
|
|
381
|
+
const span = (now - Math.min(...rows.map((r) => r.t))) / DAY;
|
|
382
|
+
const s = statsOf(all);
|
|
383
|
+
const p95Change = recent && before && recent.n >= 20 && before.n >= 20
|
|
384
|
+
? r1(((quantile(recent.hist, 95, recent.max) - quantile(before.hist, 95, before.max)) / quantile(before.hist, 95, before.max)) * 100, 0)
|
|
385
|
+
: null;
|
|
386
|
+
return { days: r1(Math.min(days, span), 1), ...s, callsPerDay: r1(all.n / Math.max(span, 1 / 24), 0), lastWeekVsBeforeP95Pct: p95Change };
|
|
387
|
+
}
|
|
388
|
+
/** Daily history over up to the full kept period (hourly and daily roll-ups merged). */
|
|
389
|
+
export function history(db, { kind = 'http', service, name, days = 30 }, now = Date.now()) {
|
|
390
|
+
const from = Math.floor((now - days * DAY) / DAY) * DAY;
|
|
391
|
+
const day = (t) => Math.floor(t / DAY) * DAY;
|
|
392
|
+
if (kind === 'errors') {
|
|
393
|
+
const rows = load(db, { series: 'err', kind: 'unhandled', service, name }, from, now);
|
|
394
|
+
const daily = [...bySlot(rows, day).values()].sort((a, b) => a.t - b.t).map((r) => ({ t: r.t, errors: r.n }));
|
|
395
|
+
const groups = new Map();
|
|
396
|
+
for (const r of rows) {
|
|
397
|
+
const g = groups.get(r.name) || { fingerprint: r.name, service: r.service, count: 0, days: new Set(), versions: new Set() };
|
|
398
|
+
g.count += r.n;
|
|
399
|
+
g.days.add(day(r.t));
|
|
400
|
+
if (r.version)
|
|
401
|
+
g.versions.add(r.version);
|
|
402
|
+
groups.set(r.name, g);
|
|
403
|
+
}
|
|
404
|
+
const meta = new Map(db.all('SELECT fingerprint, class, message FROM error_groups').map((g) => [g.fingerprint, g]));
|
|
405
|
+
return {
|
|
406
|
+
kind, from, to: now, resolution: 'day', points: daily,
|
|
407
|
+
groups: [...groups.values()].sort((a, b) => b.count - a.count).slice(0, 20).map((g) => ({
|
|
408
|
+
fingerprint: g.fingerprint, service: g.service, class: meta.get(g.fingerprint)?.class ?? null, message: meta.get(g.fingerprint)?.message?.slice(0, 200) ?? null,
|
|
409
|
+
count: g.count, daysSeen: g.days.size, versions: [...g.versions],
|
|
410
|
+
})),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
if (kind === 'runtime') {
|
|
414
|
+
const rows = load(db, { series: 'rt', service }, from, now);
|
|
415
|
+
const points = [...bySlot(rows, day).values()].sort((a, b) => a.t - b.t).map((r) => ({
|
|
416
|
+
t: r.t, cpu: r1(r.x.cpu / r.n), rssMb: r1(r.x.rss / r.n / 1048576, 0), eventLoopP99: r1(r.x.elP99 / r.n), eventLoopP99Max: r1(r.x.elP99Max), elu: r1(r.x.elu / r.n, 3),
|
|
417
|
+
}));
|
|
418
|
+
return { kind, from, to: now, resolution: 'day', points };
|
|
419
|
+
}
|
|
420
|
+
const f = kind === 'dependency' ? { series: 'dep', service, name } : { series: 'op', kind, service, name };
|
|
421
|
+
const rows = load(db, f, from, now);
|
|
422
|
+
const points = [...bySlot(rows, day).values()].sort((a, b) => a.t - b.t).map((r) => ({ t: r.t, ...statsOf(r) }));
|
|
423
|
+
const out = { kind, from, to: now, resolution: 'day', points };
|
|
424
|
+
if (kind !== 'dependency') {
|
|
425
|
+
const versions = new Map();
|
|
426
|
+
for (const r of rows)
|
|
427
|
+
versions.set(`${r.service}\u0000${r.version}`, [...(versions.get(`${r.service}\u0000${r.version}`) || []), r]);
|
|
428
|
+
out.versions = [...versions.values()].map((list) => {
|
|
429
|
+
const m = [...bySlot(list, () => 0).values()][0];
|
|
430
|
+
return { service: list[0].service, version: list[0].version || null, firstSeen: Math.min(...list.map((r) => r.t)), lastSeen: Math.max(...list.map((r) => r.t)), ...statsOf(m) };
|
|
431
|
+
}).sort((a, b) => a.firstSeen - b.firstSeen);
|
|
432
|
+
}
|
|
433
|
+
if (!name && kind !== 'dependency') {
|
|
434
|
+
const ops = new Map();
|
|
435
|
+
for (const r of rows)
|
|
436
|
+
ops.set(`${r.service}\u0000${r.name}`, [...(ops.get(`${r.service}\u0000${r.name}`) || []), r]);
|
|
437
|
+
out.operations = [...ops.values()].map((list) => ({ service: list[0].service, name: list[0].name, ...statsOf([...bySlot(list, () => 0).values()][0]) }))
|
|
438
|
+
.sort((a, b) => b.calls - a.calls).slice(0, 30);
|
|
439
|
+
}
|
|
440
|
+
return out;
|
|
441
|
+
}
|
|
442
|
+
// ---------------------------------------------------------------- windows that reach past raw retention
|
|
443
|
+
const scaleHist = (h, k) => Object.fromEntries(Object.entries(h).map(([b, c]) => [b, c * k]));
|
|
444
|
+
/** A row's counts, sums and histograms multiplied by k (k < 1 = the part of a row that falls in a window). */
|
|
445
|
+
function scaled(r, k) {
|
|
446
|
+
if (k === 1)
|
|
447
|
+
return r;
|
|
448
|
+
return {
|
|
449
|
+
...r, n: r.series === 'rt' ? r.n : r.n * k, failed: r.failed * k, sum: r.series === 'rt' ? r.sum : r.sum * k, hist: scaleHist(r.hist, k),
|
|
450
|
+
x: r.series === 'rt' ? r.x : Object.fromEntries(Object.entries(r.x).map(([key, v]) => [key, typeof v === 'number' ? (key.endsWith('Max') ? v : v * k) : scaleHist(v, k)])),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
const lenOf = (r) => (r.res === 'd' ? DAY : HOUR);
|
|
454
|
+
/** Roll-up rows overlapping [from, to), each cut down to the part inside the window. */
|
|
455
|
+
function windowRows(db, f, from, to) {
|
|
456
|
+
const out = [];
|
|
457
|
+
for (const r of load(db, f, from - DAY, to)) {
|
|
458
|
+
const len = lenOf(r);
|
|
459
|
+
const overlap = Math.min(to, r.t + len) - Math.max(from, r.t);
|
|
460
|
+
if (overlap > 0)
|
|
461
|
+
out.push(scaled(r, overlap / len));
|
|
462
|
+
}
|
|
463
|
+
return out;
|
|
464
|
+
}
|
|
465
|
+
export const rawOldest = (db) => db.get('SELECT MIN(ts) t FROM traces').t;
|
|
466
|
+
/**
|
|
467
|
+
* For a window that starts before the oldest raw data, the time up to which roll-ups are used (raw data
|
|
468
|
+
* after it). null when raw data covers the window, or there is no older history to use.
|
|
469
|
+
*/
|
|
470
|
+
export function historySplit(db, from) {
|
|
471
|
+
const until = Number(getSetting(db, 'history_until')) || 0;
|
|
472
|
+
const oldest = rawOldest(db);
|
|
473
|
+
if (!until || (oldest != null && from >= oldest - 60000))
|
|
474
|
+
return null;
|
|
475
|
+
if (!db.get('SELECT 1 FROM history WHERE t < ? LIMIT 1', oldest ?? until))
|
|
476
|
+
return null;
|
|
477
|
+
return until;
|
|
478
|
+
}
|
|
479
|
+
const opKey = (service, name) => `${service}\u0000${name}`;
|
|
480
|
+
/** Requests or jobs in a window, from roll-ups before `split` and raw data after it. */
|
|
481
|
+
function hybridAcc(db, w, kind, split, nSpark) {
|
|
482
|
+
const ops = new Map();
|
|
483
|
+
const sparkAt = (t) => Math.min(nSpark - 1, Math.max(0, Math.floor(((t - w.from) / (w.to - w.from)) * nSpark)));
|
|
484
|
+
const acc = (service, name) => {
|
|
485
|
+
const k = opKey(service, name);
|
|
486
|
+
let a = ops.get(k);
|
|
487
|
+
if (!a) {
|
|
488
|
+
const sp = name.indexOf(' ');
|
|
489
|
+
a = { row: emptyRow('h', 'op', 0, service, kind, name, ''), method: kind === 'http' && sp > 0 ? name.slice(0, sp) : null, route: kind === 'http' && sp > 0 ? name.slice(sp + 1) : null, queue: null, last: 0, spark: new Array(nSpark).fill(0) };
|
|
490
|
+
ops.set(k, a);
|
|
491
|
+
}
|
|
492
|
+
return a;
|
|
493
|
+
};
|
|
494
|
+
for (const r of windowRows(db, { series: 'op', kind, service: w.service, name: w.name }, w.from, Math.min(split, w.to))) {
|
|
495
|
+
const a = acc(r.service, r.name);
|
|
496
|
+
mergeInto(a.row, r);
|
|
497
|
+
a.last = Math.max(a.last, Math.min(r.t + lenOf(r), split));
|
|
498
|
+
a.spark[sparkAt(Math.max(r.t, w.from))] += r.n;
|
|
499
|
+
}
|
|
500
|
+
if (w.to > split) {
|
|
501
|
+
const cond = `${w.service ? ' AND service = ?' : ''}${w.name ? ' AND name = ?' : ''}`;
|
|
502
|
+
const args = [...(w.service ? [w.service] : []), ...(w.name ? [w.name] : [])];
|
|
503
|
+
for (const r of db.all(`SELECT service, name, method, route, queue, duration, failed, status, ts, queue_wait FROM traces WHERE kind = ? AND ts >= ? AND ts <= ?${cond}`, kind, Math.max(split, w.from), w.to, ...args)) {
|
|
504
|
+
const a = acc(r.service, r.name);
|
|
505
|
+
const o = a.row;
|
|
506
|
+
o.n++;
|
|
507
|
+
o.failed += r.failed;
|
|
508
|
+
o.sum += r.duration;
|
|
509
|
+
o.max = Math.max(o.max ?? 0, r.duration);
|
|
510
|
+
histAdd(o.hist, r.duration);
|
|
511
|
+
const st = r.status ?? 0;
|
|
512
|
+
mergeX(o.x, { s4: st >= 400 && st < 500 ? 1 : 0, s5: st >= 500 ? 1 : 0 });
|
|
513
|
+
if (r.queue_wait != null)
|
|
514
|
+
mergeX(o.x, { qw: histAdd({}, r.queue_wait), qwN: 1, qwSum: r.queue_wait });
|
|
515
|
+
if (r.method)
|
|
516
|
+
a.method = r.method;
|
|
517
|
+
if (r.route)
|
|
518
|
+
a.route = r.route;
|
|
519
|
+
if (r.queue)
|
|
520
|
+
a.queue = r.queue;
|
|
521
|
+
a.last = Math.max(a.last, r.ts);
|
|
522
|
+
a.spark[sparkAt(r.ts)]++;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return ops;
|
|
526
|
+
}
|
|
527
|
+
/** The Requests / Jobs list for a window reaching past raw retention (same shape as the raw-data list). */
|
|
528
|
+
export function hybridOperations(db, w, kind, split) {
|
|
529
|
+
const minutes = (w.to - w.from) / 60000;
|
|
530
|
+
return [...hybridAcc(db, w, kind, split, 24).values()].filter((a) => a.row.n >= 0.5).map((a) => {
|
|
531
|
+
const s = statsOf(a.row);
|
|
532
|
+
const out = {
|
|
533
|
+
service: a.row.service, name: a.row.name, method: a.method, route: a.route, ...s, totalTime: Math.round(a.row.sum),
|
|
534
|
+
rpm: r1(a.row.n / minutes, 2), lastSeen: a.last, spark: a.spark.map((v) => Math.round(v)), s4xx: Math.round(a.row.x.s4 || 0), fromHistory: true,
|
|
535
|
+
};
|
|
536
|
+
if (kind === 'job') {
|
|
537
|
+
out.queue = a.queue;
|
|
538
|
+
out.queueWaitAvg = a.row.x.qwN ? r1(a.row.x.qwSum / a.row.x.qwN) : null;
|
|
539
|
+
out.queueWaitP95 = a.row.x.qw ? r1(quantile(a.row.x.qw, 95)) : null;
|
|
540
|
+
}
|
|
541
|
+
return out;
|
|
542
|
+
}).sort((a, b) => b.calls - a.calls);
|
|
543
|
+
}
|
|
544
|
+
/** Chart series for a window reaching past raw retention: hourly (or coarser) buckets, same keys as raw series. */
|
|
545
|
+
export function hybridSeries(db, w, kind, split) {
|
|
546
|
+
const size = Math.max(HOUR, Math.ceil((w.to - w.from) / 60 / HOUR) * HOUR);
|
|
547
|
+
const start = Math.floor(w.from / size) * size;
|
|
548
|
+
const n = Math.max(1, Math.ceil((w.to - start) / size));
|
|
549
|
+
const buckets = Array.from({ length: n }, (_, i) => emptyRow('h', 'op', start + i * size, '', kind, '', ''));
|
|
550
|
+
const at = (t) => buckets[Math.min(n - 1, Math.max(0, Math.floor((t - start) / size)))];
|
|
551
|
+
for (const r of windowRows(db, totals({ series: 'op', kind, service: w.service, name: w.name }), w.from, Math.min(split, w.to)))
|
|
552
|
+
mergeInto(at(Math.max(r.t, w.from)), r);
|
|
553
|
+
if (w.to > split) {
|
|
554
|
+
for (const r of db.all(`SELECT duration, failed, status, ts, queue_wait FROM traces WHERE kind = ? AND ts >= ? AND ts <= ?${w.service ? ' AND service = ?' : ''}${w.name ? ' AND name = ?' : ''}`, kind, Math.max(split, w.from), w.to, ...(w.service ? [w.service] : []), ...(w.name ? [w.name] : []))) {
|
|
555
|
+
const o = at(r.ts);
|
|
556
|
+
o.n++;
|
|
557
|
+
o.failed += r.failed;
|
|
558
|
+
o.sum += r.duration;
|
|
559
|
+
o.max = Math.max(o.max ?? 0, r.duration);
|
|
560
|
+
histAdd(o.hist, r.duration);
|
|
561
|
+
const st = r.status ?? 0;
|
|
562
|
+
mergeX(o.x, { s4: st >= 400 && st < 500 ? 1 : 0, s5: st >= 500 ? 1 : 0 });
|
|
563
|
+
if (r.queue_wait != null)
|
|
564
|
+
mergeX(o.x, { qw: histAdd({}, r.queue_wait), qwN: 1, qwSum: r.queue_wait });
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
bucketMs: size,
|
|
569
|
+
fromHistory: true,
|
|
570
|
+
points: buckets.map((b) => {
|
|
571
|
+
const s4 = Math.round(b.x.s4 || 0), s5 = Math.round(b.x.s5 || 0), count = Math.round(b.n);
|
|
572
|
+
const p = {
|
|
573
|
+
t: b.t, count, rpm: r1(b.n / (size / 60000), 2), failed: Math.round(b.failed), s2xx: Math.max(0, count - s4 - s5), s4xx: s4, s5xx: s5,
|
|
574
|
+
avg: b.n ? r1(b.sum / b.n) : null, p95: r1(quantile(b.hist, 95, b.max)), p50: r1(quantile(b.hist, 50, b.max)), failureRate: b.n ? r1((b.failed / b.n) * 100, 2) : 0,
|
|
575
|
+
};
|
|
576
|
+
if (kind === 'job') {
|
|
577
|
+
p.queueWaitAvg = b.x.qwN ? r1(b.x.qwSum / b.x.qwN) : null;
|
|
578
|
+
p.queueWaitP95 = b.x.qw ? r1(quantile(b.x.qw, 95)) : null;
|
|
579
|
+
}
|
|
580
|
+
return p;
|
|
581
|
+
}),
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
/** Unhandled errors in the roll-ups between from and to (for windows past raw retention). */
|
|
585
|
+
export function historyErrorCount(db, from, to, service) {
|
|
586
|
+
return Math.round(windowRows(db, { series: 'err', kind: 'unhandled', service }, from, to).reduce((a, r) => a + r.n, 0));
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* The same window on earlier weeks (or, for windows up to a day, earlier days): the honest reference for
|
|
590
|
+
* "is this more or less than usual?". Only periods fully inside the kept history count.
|
|
591
|
+
*/
|
|
592
|
+
export function usualWindow(db, f, from, to) {
|
|
593
|
+
const until = Number(getSetting(db, 'history_until')) || 0;
|
|
594
|
+
const oldest = db.get('SELECT MIN(t) t FROM history').t;
|
|
595
|
+
if (!until || oldest == null)
|
|
596
|
+
return null;
|
|
597
|
+
const tryStep = (step, max, basis) => {
|
|
598
|
+
const samples = [];
|
|
599
|
+
for (let k = 1; k <= max; k++) {
|
|
600
|
+
const a = from - k * step, b = to - k * step;
|
|
601
|
+
if (a < oldest || b > until)
|
|
602
|
+
continue;
|
|
603
|
+
const m = [...bySlot(windowRows(db, totals(f), a, b), () => 0).values()][0];
|
|
604
|
+
samples.push(m ? statsOf(m) : { calls: 0, failed: 0, failureRate: 0, avg: null, p50: null, p95: null, p99: null, max: null });
|
|
605
|
+
}
|
|
606
|
+
if (samples.length < 2)
|
|
607
|
+
return null;
|
|
608
|
+
const med = (v) => { const x = v.filter((y) => y != null); return x.length ? r1(median(x), 2) : null; };
|
|
609
|
+
return {
|
|
610
|
+
basis, samples: samples.length,
|
|
611
|
+
description: basis === 'week' ? `the same window on the last ${samples.length} weeks` : `the same window on the last ${samples.length} days`,
|
|
612
|
+
requests: Math.round(median(samples.map((s) => s.calls))), failureRate: med(samples.map((s) => s.failureRate)) ?? 0, avg: med(samples.map((s) => s.avg)), p95: med(samples.map((s) => s.p95)),
|
|
613
|
+
};
|
|
614
|
+
};
|
|
615
|
+
return tryStep(WEEK, 4, 'week') ?? (to - from <= DAY ? tryStep(DAY, 7, 'day') : null);
|
|
616
|
+
}
|
|
617
|
+
// ---------------------------------------------------------------- demo data
|
|
618
|
+
/**
|
|
619
|
+
* Demo only: fills `days` of history before the generated raw data. Traffic follows the generated day's
|
|
620
|
+
* shape per hour of day (lighter on weekends, with jitter); latency, failures, dependencies and errors use
|
|
621
|
+
* each series' typical profile from before the demo's release, so one-off incidents in the generated day
|
|
622
|
+
* don't become "normal" and the release's regression still stands out.
|
|
623
|
+
*/
|
|
624
|
+
export function seedHistory(db, { days = 56, now = Date.now() } = {}) {
|
|
625
|
+
const oldest = db.get('SELECT MIN(ts) t FROM traces').t;
|
|
626
|
+
if (oldest == null)
|
|
627
|
+
return 0;
|
|
628
|
+
const rawFrom = floorHour(oldest);
|
|
629
|
+
const src = db.all("SELECT * FROM history WHERE res = 'h' AND t >= ? AND t < ?", rawFrom, floorHour(now)).map(parse);
|
|
630
|
+
const firstVersion = new Map();
|
|
631
|
+
for (const r of src)
|
|
632
|
+
if (r.series === 'op' && r.version && (!firstVersion.has(r.service) || r.t < firstVersion.get(r.service).t))
|
|
633
|
+
firstVersion.set(r.service, { t: r.t, v: r.version });
|
|
634
|
+
const pre = (r) => !r.version || r.version === firstVersion.get(r.service)?.v;
|
|
635
|
+
const scaleRow = scaled;
|
|
636
|
+
const merged = (rows) => { const m = new Map(); for (const r of rows) {
|
|
637
|
+
const k = `${r.series}\u0000${r.service}\u0000${r.kind}\u0000${r.name}`;
|
|
638
|
+
const c = m.get(k);
|
|
639
|
+
if (c)
|
|
640
|
+
mergeInto(c, r);
|
|
641
|
+
else
|
|
642
|
+
m.set(k, mergeInto({ ...emptyRow('h', r.series, 0, r.service, r.kind, r.name, ''), version: r.series === 'op' || r.series === 'err' ? firstVersion.get(r.service)?.v ?? '' : '' }, r));
|
|
643
|
+
} return m; };
|
|
644
|
+
const preOps = src.filter((r) => r.series === 'op' && pre(r));
|
|
645
|
+
const opProfile = merged(preOps.length ? preOps : src.filter((r) => r.series === 'op'));
|
|
646
|
+
const depProfile = merged(src.filter((r) => r.series === 'dep' || r.series === 'sql' || (r.series === 'err' && pre(r))));
|
|
647
|
+
// Dependencies scale with all of a service's traffic; errors with its traffic before the release.
|
|
648
|
+
const svcAll = new Map();
|
|
649
|
+
const svcPre = new Map();
|
|
650
|
+
for (const r of src)
|
|
651
|
+
if (r.series === 'op') {
|
|
652
|
+
svcAll.set(r.service, (svcAll.get(r.service) || 0) + r.n);
|
|
653
|
+
if (pre(r))
|
|
654
|
+
svcPre.set(r.service, (svcPre.get(r.service) || 0) + r.n);
|
|
655
|
+
}
|
|
656
|
+
// Traffic per hour of day, from the generated day (the first, partial hour only if it is the only one).
|
|
657
|
+
const hourRows = (hod) => {
|
|
658
|
+
const full = src.filter((r) => r.t > rawFrom && (r.t / HOUR) % 24 === hod);
|
|
659
|
+
if (full.length)
|
|
660
|
+
return { rows: full, k: 1 };
|
|
661
|
+
const part = (rawFrom + HOUR - oldest) / HOUR;
|
|
662
|
+
return { rows: src.filter((r) => r.t === rawFrom), k: part > 0.1 ? 1 / part : 0 };
|
|
663
|
+
};
|
|
664
|
+
const shapes = Array.from({ length: 24 }, (_, hod) => {
|
|
665
|
+
const { rows, k } = hourRows(hod);
|
|
666
|
+
const ops = new Map();
|
|
667
|
+
const svc = new Map();
|
|
668
|
+
for (const r of rows)
|
|
669
|
+
if (r.series === 'op') {
|
|
670
|
+
const key = `op\u0000${r.service}\u0000${r.kind}\u0000${r.name}`;
|
|
671
|
+
ops.set(key, (ops.get(key) || 0) + r.n * k);
|
|
672
|
+
svc.set(r.service, (svc.get(r.service) || 0) + r.n * k);
|
|
673
|
+
}
|
|
674
|
+
return { ops, svc, rt: rows.filter((r) => r.series === 'rt') };
|
|
675
|
+
});
|
|
676
|
+
let seed = 7;
|
|
677
|
+
const rnd = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
|
|
678
|
+
const out = [];
|
|
679
|
+
for (let t = rawFrom - days * DAY; t < rawFrom; t += HOUR) {
|
|
680
|
+
const dow = new Date(t).getUTCDay();
|
|
681
|
+
const k = (dow === 0 || dow === 6 ? 0.55 : 1) * (0.88 + rnd() * 0.24);
|
|
682
|
+
const shape = shapes[(t / HOUR) % 24];
|
|
683
|
+
for (const [key, n] of shape.ops) {
|
|
684
|
+
const p = opProfile.get(key);
|
|
685
|
+
if (p?.n)
|
|
686
|
+
out.push({ ...scaleRow(p, (n / p.n) * k), res: 'h', t });
|
|
687
|
+
}
|
|
688
|
+
for (const p of depProfile.values()) {
|
|
689
|
+
const total = (p.series === 'err' ? svcPre : svcAll).get(p.service);
|
|
690
|
+
const now_ = shape.svc.get(p.service);
|
|
691
|
+
if (total && now_ && p.n)
|
|
692
|
+
out.push({ ...scaleRow(p, (now_ / total) * k), res: 'h', t });
|
|
693
|
+
}
|
|
694
|
+
for (const r of shape.rt)
|
|
695
|
+
out.push({ ...r, res: 'h', t });
|
|
696
|
+
}
|
|
697
|
+
out.push(...totalsOf(out));
|
|
698
|
+
db.tx(() => write(db, out));
|
|
699
|
+
return out.length;
|
|
700
|
+
}
|
|
701
|
+
/** Totals (calls, failures, latency percentiles) of requests or jobs in a window past raw retention. */
|
|
702
|
+
export function hybridTotals(db, w, kind, split) {
|
|
703
|
+
const all = emptyRow('h', 'op', 0, '', kind, '', '');
|
|
704
|
+
for (const r of windowRows(db, totals({ series: 'op', kind, service: w.service, name: w.name }), w.from, Math.min(split, w.to)))
|
|
705
|
+
mergeInto(all, r);
|
|
706
|
+
if (w.to > split) {
|
|
707
|
+
for (const r of db.all(`SELECT duration, failed, status FROM traces WHERE kind = ? AND ts >= ? AND ts <= ?${w.service ? ' AND service = ?' : ''}${w.name ? ' AND name = ?' : ''}`, kind, Math.max(split, w.from), w.to, ...(w.service ? [w.service] : []), ...(w.name ? [w.name] : []))) {
|
|
708
|
+
all.n++;
|
|
709
|
+
all.failed += r.failed;
|
|
710
|
+
all.sum += r.duration;
|
|
711
|
+
all.max = Math.max(all.max ?? 0, r.duration);
|
|
712
|
+
histAdd(all.hist, r.duration);
|
|
713
|
+
if ((r.status ?? 0) >= 400 && (r.status ?? 0) < 500)
|
|
714
|
+
mergeX(all.x, { s4: 1 });
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return { ...statsOf(all), totalTime: Math.round(all.sum), s4xx: Math.round(all.x.s4 || 0) };
|
|
718
|
+
}
|
|
719
|
+
//# sourceMappingURL=history.js.map
|