@obzerver/server 0.8.0 → 0.9.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/dist/queries.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { VERSION } from './version.js';
2
- import { band, baseline, typical } from './history.js';
2
+ import { openSecretCount, secretGroups } from './secrets.js';
3
+ import { band, baseline, typical, historySplit, hybridOperations, hybridSeries, hybridTotals, historyErrorCount, usualWindow, rawOldest } from './history.js';
3
4
  // ------------------------------------------------------------------ helpers
4
5
  const BUCKETS = [10e3, 30e3, 60e3, 2 * 60e3, 5 * 60e3, 10 * 60e3, 15 * 60e3, 30 * 60e3, 3600e3, 3 * 3600e3, 6 * 3600e3, 12 * 3600e3, 86400e3];
5
6
  export function bucketFor(from, to, target = 60) {
@@ -123,9 +124,12 @@ export function meta(db) {
123
124
  const counts = db.get('SELECT (SELECT COUNT(*) FROM traces) traces, (SELECT COUNT(*) FROM errors) errors, (SELECT COUNT(*) FROM logs) logs');
124
125
  const unreadAlerts = db.get('SELECT COUNT(*) n FROM alert_events WHERE read = 0 AND state = ?', 'firing').n;
125
126
  const openIssues = db.get("SELECT COUNT(*) n FROM issues WHERE status NOT IN ('closed','resolved')").n;
126
- return { version: VERSION, services, versions, counts, unreadAlerts, openIssues, now: Date.now() };
127
+ return { version: VERSION, services, versions, counts, unreadAlerts, openIssues, openSecrets: openSecretCount(db), now: Date.now() };
127
128
  }
128
129
  export function overview(db, w) {
130
+ const split = historySplit(db, w.from);
131
+ if (split != null)
132
+ return overviewFromHistory(db, w, split);
129
133
  const s = scope(w);
130
134
  const http = db.all(`SELECT ts, duration, failed, status FROM traces WHERE kind = 'http' AND ${s.sql}`, ...s.args);
131
135
  const ps = scope({ ...w, from: w.from - (w.to - w.from), to: w.from });
@@ -143,17 +147,24 @@ export function overview(db, w) {
143
147
  const firing = db.all("SELECT id, name, type, last_value, last_change FROM alert_rules WHERE state = 'firing' AND enabled = 1");
144
148
  const s4 = http.filter((r) => (r.status ?? 0) >= 400 && (r.status ?? 0) < 500).length;
145
149
  const httpSeries = series(http, w);
150
+ const jobSeries = series(jobs, w, 'job');
151
+ // The previous window only counts when raw data really covers it; otherwise there is nothing to compare.
152
+ const oldest = rawOldest(db);
153
+ const prevCovered = oldest != null && oldest <= w.from - (w.to - w.from) + 60000;
146
154
  return {
147
155
  kpis: {
148
156
  requests: cur.calls, rpm: round(cur.calls / minutes), failureRate: cur.failureRate, failed: cur.failed, clientErrors: s4,
149
157
  avg: cur.avg, p95: cur.p95, p99: cur.p99, errors: errorCount, users,
150
- prev: { requests: pre.calls, failureRate: pre.failureRate, avg: pre.avg, p95: pre.p95 },
158
+ prev: prevCovered ? { requests: pre.calls, failureRate: pre.failureRate, avg: pre.avg, p95: pre.p95 } : null,
159
+ /** The same window on earlier weeks (or days): what is usual, from long-term history. */
160
+ usual: usualWindow(db, { series: 'op', kind: 'http', service: w.service }, w.from, w.to),
151
161
  jobs: jobs.length, jobsFailed: jobs.filter((j) => j.failed).length,
152
162
  },
153
163
  series: httpSeries,
154
164
  /** Normal range per bucket (same hour on earlier weeks/days), or null without enough history. */
155
165
  band: band(db, { series: 'op', kind: 'http', service: w.service }, httpSeries.points.map((p) => p.t), httpSeries.bucketMs),
156
- jobSeries: series(jobs, w, 'job'),
166
+ jobSeries: jobSeries,
167
+ jobBand: band(db, { series: 'op', kind: 'job', service: w.service }, jobSeries.points.map((p) => p.t), jobSeries.bucketMs),
157
168
  topByTime: [...ops].sort((a, b) => b.totalTime - a.totalTime).slice(0, 6),
158
169
  slowest: ops.filter((o) => o.calls >= 3).sort((a, b) => (b.p95 ?? 0) - (a.p95 ?? 0)).slice(0, 6),
159
170
  mostFailing: ops.filter((o) => o.failed > 0).sort((a, b) => b.failureRate - a.failureRate).slice(0, 6),
@@ -161,10 +172,55 @@ export function overview(db, w) {
161
172
  logCounts: Object.fromEntries(logCounts.map((l) => [l.level, l.n])),
162
173
  runtime: runtimeRows.map((r) => ({ service: r.service, instance: r.instance, cpu: round(r.cpu), rss: r.rss, elP99: round(r.el_p99), elu: round(r.elu), ts: r.ts })),
163
174
  firing,
175
+ /** Secrets that reached logs in this window, and places still to fix. */
176
+ secrets: secretSummary(db, w),
164
177
  };
165
178
  }
179
+ /** The overview for a window that reaches past raw retention: roll-ups up to `split`, raw data after it. */
180
+ function overviewFromHistory(db, w, split) {
181
+ const minutes = (w.to - w.from) / 60000;
182
+ const cur = hybridTotals(db, w, 'http', split);
183
+ const jobs = hybridTotals(db, w, 'job', split);
184
+ const ops = operations(db, w, 'http');
185
+ const s = scope({ ...w, from: Math.max(w.from, split) });
186
+ const rawErrors = w.to > split ? db.get(`SELECT COUNT(*) n FROM errors WHERE handled = 0 AND ${s.sql}`, ...s.args).n : 0;
187
+ const httpSeries = hybridSeries(db, w, 'http', split);
188
+ const jobHist = hybridSeries(db, w, 'job', split);
189
+ const firing = db.all("SELECT id, name, type, last_value, last_change FROM alert_rules WHERE state = 'firing' AND enabled = 1");
190
+ return {
191
+ fromHistory: { until: split, note: 'Older than raw data: numbers come from hourly summaries (latency within ~5%). Users, logs and error details are only kept for the raw-data period.' },
192
+ kpis: {
193
+ requests: cur.calls, rpm: round(cur.calls / minutes), failureRate: cur.failureRate, failed: cur.failed, clientErrors: cur.s4xx,
194
+ avg: cur.avg, p95: cur.p95, p99: cur.p99, errors: historyErrorCount(db, w.from, Math.min(split, w.to), w.service) + rawErrors, users: null,
195
+ prev: null, usual: usualWindow(db, { series: 'op', kind: 'http', service: w.service }, w.from, w.to),
196
+ jobs: jobs.calls, jobsFailed: jobs.failed,
197
+ },
198
+ series: httpSeries,
199
+ band: band(db, { series: 'op', kind: 'http', service: w.service }, httpSeries.points.map((p) => p.t), httpSeries.bucketMs),
200
+ jobSeries: jobHist,
201
+ jobBand: band(db, { series: 'op', kind: 'job', service: w.service }, jobHist.points.map((p) => p.t), jobHist.bucketMs),
202
+ topByTime: [...ops].sort((a, b) => b.totalTime - a.totalTime).slice(0, 6),
203
+ slowest: ops.filter((o) => o.calls >= 3).sort((a, b) => (b.p95 ?? 0) - (a.p95 ?? 0)).slice(0, 6),
204
+ mostFailing: ops.filter((o) => o.failed > 0).sort((a, b) => b.failureRate - a.failureRate).slice(0, 6),
205
+ errorGroups: errorGroups(db, w, { handled: '0' }).slice(0, 6),
206
+ logCounts: {},
207
+ runtime: [],
208
+ firing,
209
+ /** Secrets that reached logs in this window, and places still to fix. */
210
+ secrets: secretSummary(db, w),
211
+ };
212
+ }
213
+ function secretSummary(db, w) {
214
+ const groups = secretGroups(db, { from: w.from, to: w.to, service: w.service });
215
+ const open = groups.filter((g) => g.status === 'open');
216
+ return { open: open.length, inWindow: groups.reduce((a, g) => a + g.inWindow, 0), top: open.slice(0, 3) };
217
+ }
166
218
  // ------------------------------------------------------------------ operations
167
219
  export function operations(db, w, kind = 'http') {
220
+ // Older than raw retention: the long-term roll-ups answer (latency within ~5%), raw data for the rest.
221
+ const split = historySplit(db, w.from);
222
+ if (split != null)
223
+ return hybridOperations(db, w, kind, split);
168
224
  const s = scope(w);
169
225
  const rows = db.all(`SELECT service, name, method, route, duration, failed, status, ts, queue, queue_wait FROM traces WHERE kind = ? AND ${s.sql}`, kind, ...s.args);
170
226
  const minutes = (w.to - w.from) / 60000;
@@ -228,11 +284,16 @@ export function operation(db, w, { kind = 'http', name, service, sort = 'recent'
228
284
  FROM spans s WHERE s.operation = ? AND ${ss.sql}${service ? ' AND s.service = ?' : ''} GROUP BY s.name, s.kind ORDER BY self DESC LIMIT 15`, name, ...ss.args, ...svcArgs);
229
285
  const sampled = db.get(`SELECT COUNT(*) n FROM traces WHERE kind = ? AND name = ? AND sampled = 1 AND ${s.sql}${svcCond}`, kind, name, ...s.args, ...svcArgs).n || 1;
230
286
  const errors = db.all(`SELECT fingerprint, class, MAX(message) message, COUNT(*) n, MIN(handled) handled FROM errors WHERE operation = ? AND ${s.sql}${svcCond} GROUP BY fingerprint ORDER BY n DESC LIMIT 10`, name, ...s.args, ...svcArgs);
231
- const opSeries = series(rows, w, kind);
232
287
  const hf = { series: 'op', kind, service, name };
288
+ // Past raw retention, the numbers and charts come from roll-ups; executions exist only for the raw period.
289
+ const split = historySplit(db, w.from);
290
+ const hw = { from: w.from, to: w.to, service: service || null, name };
291
+ const opSeries = split != null ? hybridSeries(db, hw, kind, split) : series(rows, w, kind);
292
+ const fullStats = split != null ? hybridTotals(db, hw, kind, split) : st;
233
293
  return {
234
- name, kind, service, stats: { ...st, rpm: round(st.calls / ((w.to - w.from) / 60000)) }, statuses, histogram: hist,
294
+ name, kind, service, stats: { ...fullStats, rpm: round(fullStats.calls / ((w.to - w.from) / 60000)) }, statuses, histogram: hist,
235
295
  series: opSeries, executions, total,
296
+ fromHistory: split != null ? { until: split, note: 'Older than raw data: numbers and charts come from hourly summaries (latency within ~5%). Executions, status codes and the breakdown cover only the raw-data period.' } : null,
236
297
  band: band(db, hf, opSeries.points.map((p) => p.t), opSeries.bucketMs),
237
298
  /** What is normal: for this hour (seasonal) and over the last 4 weeks, from long-term roll-ups. */
238
299
  usual: { thisHour: baseline(db, hf, w.to), last4Weeks: typical(db, hf, w.to) },
@@ -564,6 +625,8 @@ export function runtime(db, w) {
564
625
  points: [...group(inst, (r) => Math.floor(r.ts / size) * size).entries()].sort((a, b) => a[0] - b[0]).map(([t, arr]) => ({
565
626
  t,
566
627
  cpu: round(pick(arr, (x) => x.cpu)),
628
+ cpuUtil: round(pick(arr, (x) => cpuUtilOf(x))),
629
+ memUtil: round(pick(arr, (x) => memUtilOf(x)?.pct ?? null)),
567
630
  rss: round((pick(arr, (x) => x.rss) ?? 0) / 1048576, 1),
568
631
  heapUsed: round((pick(arr, (x) => x.heap_used) ?? 0) / 1048576, 1),
569
632
  heapTotal: round((pick(arr, (x) => x.heap_total) ?? 0) / 1048576, 1),
@@ -638,6 +701,38 @@ function versionStats(db, service, version) {
638
701
  rpm: first && last && last > first ? round(rows.length / ((last - first) / 60000)) : null, routes,
639
702
  };
640
703
  }
704
+ /** Runtime samples of a service while a version was serving (its first to last request). */
705
+ function runtimeStats(db, service, from, to) {
706
+ if (from == null || to == null)
707
+ return null;
708
+ const rows = db.all(`SELECT ts, instance, cpu, rss, heap_used, heap_total, el_p50, el_p99, el_max, elu, gc_count, gc_ms, handles, inflight,
709
+ cpu_user, cpu_system, interval_ms, cores, cpu_limit, heap_limit, mem_limit FROM runtime WHERE service = ? AND ts >= ? AND ts <= ? ORDER BY ts`, service, from, to);
710
+ if (rows.length < 4)
711
+ return null;
712
+ const MB = 1048576;
713
+ const mean = (v) => { const x = v.filter((y) => y != null && Number.isFinite(y)); return x.length ? x.reduce((a, b) => a + b, 0) / x.length : null; };
714
+ const slope = (pts) => {
715
+ if (pts.length < 10 || pts[pts.length - 1][0] - pts[0][0] < 30 * 60000)
716
+ return null;
717
+ const mx = pts.reduce((a, p) => a + p[0], 0) / pts.length;
718
+ const my = pts.reduce((a, p) => a + p[1], 0) / pts.length;
719
+ let num = 0, den = 0;
720
+ for (const [x, y] of pts) {
721
+ num += (x - mx) * (y - my);
722
+ den += (x - mx) ** 2;
723
+ }
724
+ return den ? (num / den) * 3600e3 / MB : null; // bytes/ms → MB/hour
725
+ };
726
+ const insts = [...group(rows, (r) => r.instance).values()];
727
+ const growth = (col) => mean(insts.map((g) => slope(g.filter((r) => r[col] != null).map((r) => [r.ts, r[col]]))));
728
+ const level = (col) => { const v = mean(insts.map((g) => mean(g.map((r) => r[col])))); return v == null ? null : round(v / MB, 1); };
729
+ return {
730
+ samples: rows.length, hours: round((to - from) / 3600e3, 1),
731
+ heapUsed: level('heap_used'), rss: level('rss'),
732
+ heapGrowth: round(growth('heap_used'), 2), rssGrowth: round(growth('rss'), 2),
733
+ cpuUtil: round(mean(rows.map(cpuUtilOf)), 1), cpu: round(mean(rows.map((r) => r.cpu)), 1), elP99: round(mean(rows.map((r) => r.el_p99))),
734
+ };
735
+ }
641
736
  function spanProfile(db, service, version) {
642
737
  const traceCount = db.get('SELECT COUNT(*) n FROM traces WHERE service = ? AND version IS ? AND sampled = 1', service, version).n || 1;
643
738
  const rows = db.all('SELECT kind, name, statement, host, SUM(count) calls, SUM(self) self FROM spans WHERE service = ? AND version IS ? GROUP BY kind, name, statement, host', service, version);
@@ -725,17 +820,43 @@ function computeVerdict(db, service, version) {
725
820
  }
726
821
  if (changes.some((c) => c.type === 'outbound' && c.change === 'new'))
727
822
  evidence.push({ type: 'outbound', text: 'New outbound hosts called' });
823
+ // Runtime across the boundary: a steady heap climb is a leak; memory, CPU and event-loop shifts are changes.
824
+ const rtA = runtimeStats(db, service, prev.first, prev.last);
825
+ const rtB = runtimeStats(db, service, cur.first, cur.last);
826
+ let leak = null;
827
+ if (rtA && rtB) {
828
+ const g = rtB.heapGrowth ?? 0;
829
+ const gPrev = rtA.heapGrowth ?? 0;
830
+ if (rtB.hours >= 1 && g >= 5 && g > 3 * Math.max(gPrev, 1)) {
831
+ leak = `Heap grows ${round(g, 1)} MB/hour per instance since ${version} (${prevV}: ${round(gPrev, 1)} MB/hour)`;
832
+ evidence.push({ type: 'memory_leak', text: leak });
833
+ }
834
+ else if (rtA.heapUsed && rtB.heapUsed && rtB.heapUsed > rtA.heapUsed * 1.3 && rtB.heapUsed - rtA.heapUsed > 20) {
835
+ evidence.push({ type: 'memory', text: `Heap used per instance rose from ${rtA.heapUsed} MB to ${rtB.heapUsed} MB` });
836
+ }
837
+ const [ca, cb] = rtA.cpuUtil != null && rtB.cpuUtil != null ? [rtA.cpuUtil, rtB.cpuUtil] : [rtA.cpu, rtB.cpu];
838
+ if (ca != null && cb != null && cb > ca * 1.3 && cb - ca > 5)
839
+ evidence.push({ type: 'cpu', text: `CPU ${rtA.cpuUtil != null ? 'utilization' : 'usage'} rose from ${ca}% to ${cb}%` });
840
+ if (rtA.elP99 && rtB.elP99 && rtB.elP99 > rtA.elP99 * 1.5 && rtB.elP99 - rtA.elP99 > 10)
841
+ evidence.push({ type: 'event_loop', text: `Event-loop delay p99 rose from ${rtA.elP99}ms to ${rtB.elP99}ms` });
842
+ }
728
843
  let verdict = 'clean';
729
844
  let summary = `5xx rate ${prev.errorRate}% → ${cur.errorRate}%, p95 ${prev.p95}ms → ${cur.p95}ms; no new error groups or behaviour changes beyond noise.`;
730
845
  if (z > 2.5 && (cur.errorRate ?? 0) - (prev.errorRate ?? 0) > 0.3) {
731
846
  verdict = 'regression';
732
847
  summary = `5xx errors rose across the release boundary: ${prev.errorRate}% (${prev.s5xx}/${prev.requests}) → ${cur.errorRate}% (${cur.s5xx}/${cur.requests}), z=${round(z, 1)}.`;
848
+ if (leak)
849
+ summary += ` ${leak}.`;
850
+ }
851
+ else if (leak) {
852
+ verdict = 'regression';
853
+ summary = `Memory leak: ${leak}. 5xx rate ${prev.errorRate}% → ${cur.errorRate}%.`;
733
854
  }
734
855
  else if (evidence.length || changes.some((c) => c.change === 'new' || c.change === 'more_frequent' || c.change === 'slower')) {
735
856
  verdict = 'changed';
736
857
  summary = `No rise in 5xx (${prev.errorRate}% → ${cur.errorRate}%), but behaviour changed: ${evidence.map((e) => e.text).join('; ') || 'calls in the code path moved beyond noise'}.`;
737
858
  }
738
- return { ...base, previousStats: stripRoutes(prev), verdict, summary, evidence, changes: changes.slice(0, 40), z: round(z) };
859
+ return { ...base, previousStats: stripRoutes(prev), runtime: rtB, previousRuntime: rtA, verdict, summary, evidence, changes: changes.slice(0, 40), z: round(z) };
739
860
  }
740
861
  export function releases(db, w) {
741
862
  const services = db.all(`SELECT DISTINCT service FROM traces WHERE version IS NOT NULL${w.service ? ' AND service = ?' : ''}`, ...(w.service ? [w.service] : []));
@@ -867,4 +988,90 @@ export function agentPrompt(db, id) {
867
988
  lines.push('', '## Task', '1. Explain the root cause, citing the spans/logs/source above.', '2. Propose a diff that fixes it.', '3. Add or update tests that would have caught it.');
868
989
  return lines.join('\n');
869
990
  }
991
+ /** Share of the CPUs the process may use (container quota, else logical CPUs), %; null for SDKs older than 0.8.2. */
992
+ const cpuUtilOf = (r) => (r.cpu == null || !r.cores ? null : r.cpu / Math.min(r.cores, r.cpu_limit || r.cores));
993
+ /** The tighter of heap vs V8's heap limit and RSS vs the container's memory limit, %. */
994
+ function memUtilOf(r) {
995
+ const heap = r.heap_used != null && r.heap_limit ? (r.heap_used / r.heap_limit) * 100 : null;
996
+ const box = r.rss != null && r.mem_limit ? (r.rss / r.mem_limit) * 100 : null;
997
+ if (heap == null && box == null)
998
+ return null;
999
+ return (box ?? -1) > (heap ?? -1) ? { pct: box, basis: 'container' } : { pct: heap, basis: 'heap' };
1000
+ }
1001
+ const perSec = (v, ms) => (v == null || !ms ? null : (v / ms) * 1000);
1002
+ /**
1003
+ * The Profiler for one application (all its instances, or one): memory, memory utilization, CPU utilization,
1004
+ * CPU time (user/system), event loop and GC per bucket, window averages, and the previous window's averages.
1005
+ * Several instances: memory and CPU time are summed (the app's footprint); utilizations and the event loop
1006
+ * take the worst instance; ELU is averaged.
1007
+ */
1008
+ export function runtimeView(db, w, { service, instance }) {
1009
+ const load = (from, to) => db.all(`SELECT ts, instance, cpu, rss, heap_used, heap_total, el_p50, el_p99, el_max, elu, gc_count, gc_ms, handles, inflight,
1010
+ cpu_user, cpu_system, interval_ms, cores, cpu_limit, heap_limit, mem_limit FROM runtime WHERE service = ?${instance ? ' AND instance = ?' : ''} AND ts >= ? AND ts <= ? ORDER BY ts`, service, ...(instance ? [instance] : []), from, to);
1011
+ const rows = load(w.from, w.to);
1012
+ const size = bucketFor(w.from, w.to, 90);
1013
+ const mean = (v) => { const x = v.filter((y) => y != null && Number.isFinite(y)); return x.length ? x.reduce((a, b) => a + b, 0) / x.length : null; };
1014
+ const maxOf = (v) => { const x = v.filter((y) => y != null && Number.isFinite(y)); return x.length ? Math.max(...x) : null; };
1015
+ const sumOf = (v) => { const x = v.filter((y) => y != null && Number.isFinite(y)); return x.length ? x.reduce((a, b) => a + b, 0) : null; };
1016
+ const MB = 1048576;
1017
+ function bucketPoint(arr) {
1018
+ const byInst = [...group(arr, (r) => r.instance).values()];
1019
+ const per = byInst.map((g) => {
1020
+ const util = g.map(memUtilOf);
1021
+ const top = util.reduce((a, u) => (u && (!a || u.pct > a.pct) ? u : a), null);
1022
+ return {
1023
+ rss: mean(g.map((r) => r.rss)), heapUsed: mean(g.map((r) => r.heap_used)), heapTotal: mean(g.map((r) => r.heap_total)),
1024
+ memUtil: mean(util.map((u) => u?.pct ?? null)), memBasis: top?.basis ?? null,
1025
+ cpuUtil: mean(g.map(cpuUtilOf)), cpu: mean(g.map((r) => r.cpu)),
1026
+ user: mean(g.map((r) => perSec(r.cpu_user, r.interval_ms))), system: mean(g.map((r) => perSec(r.cpu_system, r.interval_ms))),
1027
+ elP50: mean(g.map((r) => r.el_p50)), elP99: mean(g.map((r) => r.el_p99)), elMax: maxOf(g.map((r) => r.el_max)), elu: mean(g.map((r) => r.elu)),
1028
+ gcMs: sumOf(g.map((r) => r.gc_ms)), gcCount: sumOf(g.map((r) => r.gc_count)),
1029
+ };
1030
+ });
1031
+ const worst = per.reduce((a, p) => (p.memUtil != null && (!a || (a.memUtil ?? -1) < p.memUtil) ? p : a), null);
1032
+ return {
1033
+ rss: sumOf(per.map((p) => p.rss)), heapUsed: sumOf(per.map((p) => p.heapUsed)), heapTotal: sumOf(per.map((p) => p.heapTotal)),
1034
+ memUtil: maxOf(per.map((p) => p.memUtil)), memBasis: worst?.memBasis ?? null,
1035
+ cpuUtil: maxOf(per.map((p) => p.cpuUtil)), cpu: sumOf(per.map((p) => p.cpu)),
1036
+ cpuUser: sumOf(per.map((p) => p.user)), cpuSystem: sumOf(per.map((p) => p.system)),
1037
+ elP50: mean(per.map((p) => p.elP50)), elP99: maxOf(per.map((p) => p.elP99)), elMax: maxOf(per.map((p) => p.elMax)), elu: mean(per.map((p) => p.elu)),
1038
+ gcMs: sumOf(per.map((p) => p.gcMs)), gcCount: sumOf(per.map((p) => p.gcCount)), instances: per.length,
1039
+ };
1040
+ }
1041
+ const buckets = [...group(rows, (r) => Math.floor(r.ts / size) * size).entries()].sort((a, b) => a[0] - b[0]).map(([t, arr]) => ({ t, ...bucketPoint(arr) }));
1042
+ const points = buckets.map((b) => ({
1043
+ t: b.t, rss: round(b.rss != null ? b.rss / MB : null, 1), heapUsed: round(b.heapUsed != null ? b.heapUsed / MB : null, 1), heapTotal: round(b.heapTotal != null ? b.heapTotal / MB : null, 1),
1044
+ memUtil: round(b.memUtil, 2), memBasis: b.memBasis, cpuUtil: round(b.cpuUtil, 2), cpu: round(b.cpu, 1), cpuUser: round(b.cpuUser, 2), cpuSystem: round(b.cpuSystem, 2),
1045
+ elP50: round(b.elP50), elP99: round(b.elP99), elMax: round(b.elMax), elu: round(b.elu, 2), gcMs: round(b.gcMs), gcCount: b.gcCount, instances: b.instances,
1046
+ }));
1047
+ const summarize = (list) => list.length ? {
1048
+ heapUsed: round((mean(list.map((b) => b.heapUsed)) ?? 0) / MB, 1), rss: round((mean(list.map((b) => b.rss)) ?? 0) / MB, 1),
1049
+ memUtil: round(mean(list.map((b) => b.memUtil)), 2), cpuUtil: round(mean(list.map((b) => b.cpuUtil)), 2),
1050
+ cpuTime: round(mean(list.map((b) => (b.cpuUser != null || b.cpuSystem != null ? (b.cpuUser ?? 0) + (b.cpuSystem ?? 0) : null))), 2),
1051
+ elP99: round(mean(list.map((b) => b.elP99))), elu: round(mean(list.map((b) => b.elu)), 2), gcMs: round(sumOf(list.map((b) => b.gcMs))),
1052
+ } : null;
1053
+ // The previous window counts only when raw samples cover it.
1054
+ const prevFrom = w.from - (w.to - w.from);
1055
+ const oldest = db.get('SELECT MIN(ts) t FROM runtime WHERE service = ?', service).t;
1056
+ const prevRows = oldest != null && oldest <= prevFrom + size ? load(prevFrom, w.from) : [];
1057
+ const prev = summarize([...group(prevRows, (r) => Math.floor(r.ts / size) * size).values()].map(bucketPoint));
1058
+ const latest = [...group(rows, (r) => r.instance).values()].map((g) => {
1059
+ const r = g[g.length - 1];
1060
+ const u = memUtilOf(r);
1061
+ return {
1062
+ instance: r.instance, ts: r.ts, cpu: round(r.cpu), cpuUtil: round(cpuUtilOf(r), 1), rss: round((r.rss ?? 0) / MB, 1), heapUsed: round((r.heap_used ?? 0) / MB, 1), heapTotal: round((r.heap_total ?? 0) / MB, 1),
1063
+ memUtil: round(u?.pct ?? null, 1), memBasis: u?.basis ?? null, elP99: round(r.el_p99), elu: round(r.elu, 1), gcMs: round(r.gc_ms), handles: r.handles, inflight: r.inflight,
1064
+ cores: r.cores, cpuLimit: r.cpu_limit, heapLimitMb: r.heap_limit ? round(r.heap_limit / MB, 0) : null, memLimitMb: r.mem_limit ? round(r.mem_limit / MB, 0) : null,
1065
+ };
1066
+ });
1067
+ // Per instance, for the charts that compare processes (utilization, event loop).
1068
+ const byInstance = [...group(rows, (r) => r.instance).entries()].map(([name, list]) => ({
1069
+ instance: name,
1070
+ points: [...group(list, (r) => Math.floor(r.ts / size) * size).entries()].sort((a, b) => a[0] - b[0]).map(([t, arr]) => {
1071
+ const p = bucketPoint(arr);
1072
+ return { t, memUtil: round(p.memUtil, 2), cpuUtil: round(p.cpuUtil, 2), elP99: round(p.elP99), elu: round(p.elu, 2) };
1073
+ }),
1074
+ }));
1075
+ return { service, instance: instance || null, bucketMs: size, points, byInstance, summary: summarize(buckets.map(({ t: _t, ...b }) => b)), prev, instances: latest };
1076
+ }
870
1077
  //# sourceMappingURL=queries.js.map