merge: BIT-734 operational observability (stats, Prometheus, SLO, Grafana)

Paperclip-Issue: BIT-734
This commit is contained in:
Peter Spark committed 2026-04-02 19:41:23 +00:00
commit acac2ba034
11 files changed
+1098 -2

No files matched your search

+38
View File
@@ -18,6 +18,7 @@
"fastify": "^4.27.0",
"mysql2": "^3.11.5",
"pino": "^9.1.0",
"prom-client": "^15.1.3",
"zod": "^3.23.8"
},
"devDependencies": {
@@ -677,6 +678,15 @@
"node-pre-gyp": "bin/node-pre-gyp"
}
},
"node_modules/@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
"license": "Apache-2.0",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1364,6 +1374,12 @@
"node": ">= 10.0.0"
}
},
"node_modules/bintrees": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",
"integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
"license": "MIT"
},
"node_modules/bn.js": {
"version": "4.12.3",
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz",
@@ -2885,6 +2901,19 @@
"integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",
"license": "MIT"
},
"node_modules/prom-client": {
"version": "15.1.3",
"resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz",
"integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==",
"license": "Apache-2.0",
"dependencies": {
"@opentelemetry/api": "^1.4.0",
"tdigest": "^0.1.1"
},
"engines": {
"node": "^16 || ^18 || >=20"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -3448,6 +3477,15 @@
"node": ">=8"
}
},
"node_modules/tdigest": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
"integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==",
"license": "MIT",
"dependencies": {
"bintrees": "1.0.2"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+1
View File
@@ -23,6 +23,7 @@
"fastify": "^4.27.0",
"mysql2": "^3.11.5",
"pino": "^9.1.0",
"prom-client": "^15.1.3",
"zod": "^3.23.8"
},
"devDependencies": {
+4
View File
@@ -19,6 +19,8 @@ import adminStatsRoutes from './routes/admin/stats.js';
import adminIncidentsRoutes from './routes/admin/incidents.js';
import recentErrorsPublicRoutes from './routes/public/recentErrors.js';
import errorMonitoringMutationsRoutes from './routes/public/errorMonitoringMutations.js';
import errorMonitoringStatsRoutes from './routes/public/errorMonitoringStats.js';
import prometheusPlugin from './plugins/prometheus.js';
const IS_PROD = process.env.NODE_ENV === 'production';
@@ -63,10 +65,12 @@ await app.register(authPlugin);
await app.register(rbacPlugin);
await app.register(auditPlugin);
await app.register(rateLimitPlugin);
await app.register(prometheusPlugin);
// Routes
await app.register(recentErrorsPublicRoutes);
await app.register(errorMonitoringMutationsRoutes);
await app.register(errorMonitoringStatsRoutes);
await app.register(adminAuthRoutes);
await app.register(adminStatsRoutes);
await app.register(adminIncidentsRoutes);
+115
View File
@@ -0,0 +1,115 @@
/**
* Prometheus metrics plugin for the API service.
* Exposes GET /metrics (text/plain; Prometheus exposition format).
*
* Collects:
* - Default Node.js metrics (GC, event loop, heap, active handles)
* - HTTP request duration histogram (route, method, status)
* - Error-monitoring domain gauges (updated by /api/error-monitoring/stats)
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import {
Registry,
collectDefaultMetrics,
Histogram,
Gauge,
Counter,
} from 'prom-client';
const register = new Registry();
collectDefaultMetrics({ register, prefix: 'er_api_' });
/* ── HTTP request metrics ────────────────────────────────────────────── */
const httpRequestDuration = new Histogram({
name: 'er_api_http_request_duration_seconds',
help: 'HTTP request duration in seconds',
labelNames: ['method', 'route', 'status_code'] as const,
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
registers: [register],
});
const httpRequestsTotal = new Counter({
name: 'er_api_http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status_code'] as const,
registers: [register],
});
/* ── Domain gauges (set externally via metricsGauges) ────────────────── */
const incidentsTotalGauge = new Gauge({
name: 'er_incidents_total',
help: 'Total incidents by state',
labelNames: ['state'] as const,
registers: [register],
});
const incidentsBySeverityGauge = new Gauge({
name: 'er_incidents_by_severity',
help: 'Total incidents by severity',
labelNames: ['severity'] as const,
registers: [register],
});
const occurrences24hGauge = new Gauge({
name: 'er_occurrences_last_24h',
help: 'Occurrence count in the last 24 hours',
registers: [register],
});
const resolved24hGauge = new Gauge({
name: 'er_resolved_last_24h',
help: 'Incidents resolved in the last 24 hours',
registers: [register],
});
const projectIncidentsGauge = new Gauge({
name: 'er_project_incidents_total',
help: 'Total incidents per project',
labelNames: ['project', 'state'] as const,
registers: [register],
});
const projectResolutionRateGauge = new Gauge({
name: 'er_project_resolution_rate',
help: 'Resolution rate per project (0..1)',
labelNames: ['project'] as const,
registers: [register],
});
export const metricsGauges = {
incidentsTotalGauge,
incidentsBySeverityGauge,
occurrences24hGauge,
resolved24hGauge,
projectIncidentsGauge,
projectResolutionRateGauge,
};
export { register as prometheusRegistry };
export default async function prometheusPlugin(app: FastifyInstance): Promise<void> {
// Track request duration
app.addHook('onResponse', async (request: FastifyRequest, reply: FastifyReply) => {
const route = request.routeOptions?.url ?? request.url;
// Skip metrics endpoint itself to avoid recursion
if (route === '/metrics') return;
const elapsed = reply.elapsedTime / 1000; // ms → seconds
const labels = {
method: request.method,
route,
status_code: String(reply.statusCode),
};
httpRequestDuration.observe(labels, elapsed);
httpRequestsTotal.inc(labels);
});
// Expose /metrics
app.get('/metrics', async (_request: FastifyRequest, reply: FastifyReply) => {
reply.header('Content-Type', register.contentType);
return reply.send(await register.metrics());
});
}
@@ -0,0 +1,216 @@
/**
* CRM-parity operational stats endpoint.
* GET /api/error-monitoring/stats
*
* Returns 24h ingestion volume, severity distribution, per-project metrics,
* and resolution rates. Also refreshes Prometheus gauges on each call.
*
* Auth: same read-key scheme as recent-errors (api_key or view_errors query param).
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { authorizeReadQuery } from '../../lib/errorMonitoringAuth.js';
import { metricsGauges } from '../../plugins/prometheus.js';
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
type Severity = (typeof SEVERITIES)[number];
function isSeverity(s: string): s is Severity {
return (SEVERITIES as readonly string[]).includes(s);
}
interface ProjectRow {
slug: string;
total: number;
open: number;
investigating: number;
resolved: number;
ignored: number;
critical: number;
}
interface HourlyRow {
hour_bucket: string;
severity: string;
cnt: number;
}
export default async function errorMonitoringStatsRoutes(app: FastifyInstance): Promise<void> {
const db = app.db;
app.get(
'/api/error-monitoring/stats',
{
schema: {
querystring: {
type: 'object',
properties: {
api_key: { type: 'string' },
view_errors: { type: 'string' },
},
additionalProperties: false,
},
},
},
async (request: FastifyRequest, reply: FastifyReply) => {
if (!authorizeReadQuery(request, reply)) {
return;
}
// ── 1. Severity distribution (all incidents) ──────────────────────
const [sevRows] = await db.execute<RowDataPacket[]>(
`SELECT i.severity, COUNT(*) AS c
FROM er_incidents i
GROUP BY i.severity`,
);
const bySeverity: Record<Severity, number> = {
critical: 0, high: 0, medium: 0, low: 0, info: 0,
};
for (const row of sevRows) {
const sev = String(row.severity);
if (isSeverity(sev)) {
bySeverity[sev] = Number(row.c) || 0;
}
}
// ── 2. Incidents by state ─────────────────────────────────────────
const [stateRows] = await db.execute<RowDataPacket[]>(
`SELECT i.current_state AS state, COUNT(*) AS c
FROM er_incidents i
GROUP BY i.current_state`,
);
const byState: Record<string, number> = {};
for (const row of stateRows) {
byState[String(row.state)] = Number(row.c) || 0;
}
// ── 3. 24h ingestion volume ───────────────────────────────────────
const [vol24h] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c
FROM er_incident_occurrences o
WHERE o.occurred_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)`,
);
const totalLast24h = Number((vol24h[0] as { c: unknown })?.c) || 0;
// ── 4. Resolved in last 24h ───────────────────────────────────────
const [res24h] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(DISTINCT h.incident_id) AS c
FROM er_incident_state_history h
WHERE h.to_state = 'resolved'
AND h.created_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)`,
);
const resolvedLast24h = Number((res24h[0] as { c: unknown })?.c) || 0;
// ── 5. Hourly trend (last 24h by severity) ────────────────────────
const [hourlyRows] = await db.execute<RowDataPacket[]>(
`SELECT DATE_FORMAT(
CONVERT_TZ(o.occurred_at, @@session.time_zone, '+00:00'),
'%Y-%m-%d %H:00:00'
) AS hour_bucket,
o.severity,
COUNT(*) AS cnt
FROM er_incident_occurrences o
WHERE o.occurred_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)
GROUP BY hour_bucket, o.severity
ORDER BY hour_bucket ASC`,
);
// Build hourly trend as array of {hour, critical, high, medium, low, info}
const hourMap = new Map<string, Record<Severity, number>>();
for (const raw of hourlyRows as HourlyRow[]) {
const h = String(raw.hour_bucket);
const sev = String(raw.severity);
if (!isSeverity(sev)) continue;
if (!hourMap.has(h)) {
hourMap.set(h, { critical: 0, high: 0, medium: 0, low: 0, info: 0 });
}
hourMap.get(h)![sev] = Number(raw.cnt) || 0;
}
// Enumerate all 24 hours to zero-fill gaps
const now = new Date();
const hourlyTrend: Array<{ hour: string } & Record<Severity, number>> = [];
for (let i = 23; i >= 0; i--) {
const d = new Date(now.getTime() - i * 3600_000);
const y = d.getUTCFullYear();
const mo = String(d.getUTCMonth() + 1).padStart(2, '0');
const day = String(d.getUTCDate()).padStart(2, '0');
const hr = String(d.getUTCHours()).padStart(2, '0');
const label = `${y}-${mo}-${day} ${hr}:00:00`;
const vals = hourMap.get(label) ?? { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
hourlyTrend.push({ hour: label, ...vals });
}
// ── 6. Per-project metrics ────────────────────────────────────────
const [projRows] = await db.execute<RowDataPacket[]>(
`SELECT
p.slug,
COUNT(i.id) AS total,
SUM(CASE WHEN i.current_state = 'open' THEN 1 ELSE 0 END) AS open_cnt,
SUM(CASE WHEN i.current_state = 'investigating' THEN 1 ELSE 0 END) AS investigating_cnt,
SUM(CASE WHEN i.current_state = 'resolved' THEN 1 ELSE 0 END) AS resolved_cnt,
SUM(CASE WHEN i.current_state = 'ignored' THEN 1 ELSE 0 END) AS ignored_cnt,
SUM(CASE WHEN i.severity = 'critical' THEN 1 ELSE 0 END) AS critical_cnt
FROM er_projects p
LEFT JOIN er_incidents i ON i.project_id = p.id
GROUP BY p.id, p.slug
ORDER BY p.slug ASC`,
);
const projects: Array<ProjectRow & { resolutionRate: number }> = (
projRows as Record<string, unknown>[]
).map((row) => {
const total = Number(row.total) || 0;
const resolved = Number(row.resolved_cnt) || 0;
return {
slug: String(row.slug),
total,
open: Number(row.open_cnt) || 0,
investigating: Number(row.investigating_cnt) || 0,
resolved,
ignored: Number(row.ignored_cnt) || 0,
critical: Number(row.critical_cnt) || 0,
resolutionRate: total > 0 ? Math.round((resolved / total) * 10000) / 10000 : 0,
};
});
// ── 7. Refresh Prometheus gauges ──────────────────────────────────
try {
metricsGauges.occurrences24hGauge.set(totalLast24h);
metricsGauges.resolved24hGauge.set(resolvedLast24h);
for (const sev of SEVERITIES) {
metricsGauges.incidentsBySeverityGauge.labels(sev).set(bySeverity[sev]);
}
for (const [state, count] of Object.entries(byState)) {
metricsGauges.incidentsTotalGauge.labels(state).set(count);
}
metricsGauges.projectIncidentsGauge.reset();
metricsGauges.projectResolutionRateGauge.reset();
for (const proj of projects) {
for (const state of ['open', 'investigating', 'resolved', 'ignored'] as const) {
metricsGauges.projectIncidentsGauge.labels(proj.slug, state).set(proj[state]);
}
metricsGauges.projectResolutionRateGauge.labels(proj.slug).set(proj.resolutionRate);
}
} catch {
// Non-blocking: metric refresh failure must not break the endpoint.
}
return reply.send({
ingestion: {
last24h: totalLast24h,
resolvedLast24h,
hourlyTrend,
},
bySeverity,
byState,
projects,
});
},
);
}
@@ -0,0 +1,367 @@
{
"__inputs": [
{
"name": "DS_PROMETHEUS",
"label": "Prometheus",
"description": "Prometheus data source for error monitoring metrics",
"type": "datasource",
"pluginId": "prometheus",
"pluginName": "Prometheus"
}
],
"annotations": {
"list": []
},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"panels": [
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },
"id": 100,
"title": "Ingestion SLO",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 0.3 },
{ "color": "red", "value": 0.5 }
]
},
"unit": "s"
}
},
"gridPos": { "h": 6, "w": 8, "x": 0, "y": 1 },
"id": 1,
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"title": "Ingest p50 Latency",
"type": "stat",
"targets": [
{
"expr": "histogram_quantile(0.50, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p50"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 0.3 },
{ "color": "red", "value": 0.5 }
]
},
"unit": "s"
}
},
"gridPos": { "h": 6, "w": 8, "x": 8, "y": 1 },
"id": 2,
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"title": "Ingest p95 Latency (SLO < 500ms)",
"type": "stat",
"targets": [
{
"expr": "histogram_quantile(0.95, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p95"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 0.75 },
{ "color": "red", "value": 1.0 }
]
},
"unit": "s"
}
},
"gridPos": { "h": 6, "w": 8, "x": 16, "y": 1 },
"id": 3,
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"title": "Ingest p99 Latency (SLO < 1s)",
"type": "stat",
"targets": [
{
"expr": "histogram_quantile(0.99, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p99"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "s" }
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 7 },
"id": 4,
"title": "Ingest Latency Over Time",
"type": "timeseries",
"targets": [
{
"expr": "histogram_quantile(0.50, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p50"
},
{
"expr": "histogram_quantile(0.95, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p95"
},
{
"expr": "histogram_quantile(0.99, sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p99"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "reqps" }
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 7 },
"id": 5,
"title": "Ingest Request Rate",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(er_ingest_requests_total[5m])) by (status_code)",
"legendFormat": "{{status_code}}"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 15 },
"id": 101,
"title": "Error Volume",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "blue", "value": null }
]
}
}
},
"gridPos": { "h": 4, "w": 6, "x": 0, "y": 16 },
"id": 6,
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"title": "Occurrences (24h)",
"type": "stat",
"targets": [
{
"expr": "er_occurrences_last_24h",
"legendFormat": "24h"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null }
]
}
}
},
"gridPos": { "h": 4, "w": 6, "x": 6, "y": 16 },
"id": 7,
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"title": "Resolved (24h)",
"type": "stat",
"targets": [
{
"expr": "er_resolved_last_24h",
"legendFormat": "resolved"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "short" }
},
"gridPos": { "h": 4, "w": 12, "x": 12, "y": 16 },
"id": 8,
"title": "Events Ingested (rate)",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(er_ingest_events_total[5m])) by (outcome)",
"legendFormat": "{{outcome}}"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 20 },
"id": 102,
"title": "Severity & State Distribution",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "short" }
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 21 },
"id": 9,
"title": "Incidents by Severity",
"type": "piechart",
"targets": [
{
"expr": "er_incidents_by_severity",
"legendFormat": "{{severity}}"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "short" }
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 21 },
"id": 10,
"title": "Incidents by State",
"type": "piechart",
"targets": [
{
"expr": "er_incidents_total",
"legendFormat": "{{state}}"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 29 },
"id": 103,
"title": "Per-Project",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "short" }
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 30 },
"id": 11,
"title": "Incidents per Project by State",
"type": "barchart",
"options": { "stacking": "normal" },
"targets": [
{
"expr": "er_project_incidents_total",
"legendFormat": "{{project}} / {{state}}"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "red", "value": null },
{ "color": "yellow", "value": 0.5 },
{ "color": "green", "value": 0.8 }
]
}
}
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 30 },
"id": 12,
"title": "Resolution Rate by Project",
"type": "bargauge",
"options": { "reduceOptions": { "calcs": ["lastNotNull"] } },
"targets": [
{
"expr": "er_project_resolution_rate",
"legendFormat": "{{project}}"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 38 },
"id": 104,
"title": "Node.js Process (API)",
"type": "row"
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "bytes" }
},
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 39 },
"id": 13,
"title": "API Heap Usage",
"type": "timeseries",
"targets": [
{
"expr": "er_api_nodejs_heap_size_used_bytes",
"legendFormat": "heap used"
},
{
"expr": "er_api_nodejs_heap_size_total_bytes",
"legendFormat": "heap total"
}
]
},
{
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
"fieldConfig": {
"defaults": { "unit": "bytes" }
},
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 39 },
"id": 14,
"title": "Ingest-API Heap Usage",
"type": "timeseries",
"targets": [
{
"expr": "er_ingest_nodejs_heap_size_used_bytes",
"legendFormat": "heap used"
},
{
"expr": "er_ingest_nodejs_heap_size_total_bytes",
"legendFormat": "heap total"
}
]
}
],
"schemaVersion": 39,
"tags": ["bitreport", "error-monitoring", "slo"],
"templating": { "list": [] },
"time": { "from": "now-6h", "to": "now" },
"timepicker": {},
"timezone": "utc",
"title": "BitReport Error Monitoring — Operational SLO",
"uid": "er-ops-slo",
"version": 1
}
+200
View File
@@ -0,0 +1,200 @@
# Runbook: Error Monitoring SLO Alerts
Service: `errors.bitreport.pt` (api + ingest-api)
Dashboard: Grafana `er-ops-slo` (import `deploy/grafana/error-monitoring-dashboard.json`)
---
## SLO Targets
| Metric | Target | Alert Threshold |
|--------|--------|-----------------|
| Ingest p95 latency | < 500 ms | > 500 ms for 5 min |
| Ingest p99 latency | < 1 s | > 1 s for 5 min |
| Ingest error rate | < 1% | > 1% for 5 min |
| API uptime | 99.5% | /health fails for 30 s |
---
## Prometheus Alert Rules
Add to your Prometheus `rules.yml`:
```yaml
groups:
- name: er_ingest_slo
interval: 30s
rules:
- alert: IngestP95LatencyHigh
expr: >
histogram_quantile(0.95,
sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le)
) > 0.5
for: 5m
labels:
severity: warning
service: ingest-api
annotations:
summary: "Ingest p95 latency exceeds 500ms SLO"
description: >
p95 ingest latency is {{ $value | humanizeDuration }}.
Check DB query time, connection pool, and active connections.
- alert: IngestP99LatencyHigh
expr: >
histogram_quantile(0.99,
sum(rate(er_ingest_request_duration_seconds_bucket[5m])) by (le)
) > 1.0
for: 5m
labels:
severity: critical
service: ingest-api
annotations:
summary: "Ingest p99 latency exceeds 1s SLO"
description: >
p99 ingest latency is {{ $value | humanizeDuration }}.
Immediate investigation required.
- alert: IngestErrorRateHigh
expr: >
sum(rate(er_ingest_requests_total{status_code=~"5.."}[5m]))
/
sum(rate(er_ingest_requests_total[5m]))
> 0.01
for: 5m
labels:
severity: warning
service: ingest-api
annotations:
summary: "Ingest error rate exceeds 1%"
description: >
{{ $value | humanizePercentage }} of ingest requests are failing.
- alert: IngestApiDown
expr: up{job="ingest-api"} == 0
for: 30s
labels:
severity: critical
service: ingest-api
annotations:
summary: "Ingest API is unreachable"
- alert: ErrorApiDown
expr: up{job="error-api"} == 0
for: 30s
labels:
severity: critical
service: api
annotations:
summary: "Error monitoring API is unreachable"
```
---
## Prometheus Scrape Config
Add to `prometheus.yml`:
```yaml
scrape_configs:
- job_name: error-api
scrape_interval: 15s
static_configs:
- targets: ['api:3200']
metrics_path: /metrics
- job_name: ingest-api
scrape_interval: 15s
static_configs:
- targets: ['ingest-api:3041']
metrics_path: /metrics
```
---
## Triage: IngestP95LatencyHigh / IngestP99LatencyHigh
1. **Check Grafana dashboard** `er-ops-slo` > Ingestion SLO row.
2. **Active connections**: `er_ingest_active_connections` — if high, requests are queuing.
3. **DB pool saturation**: check MariaDB `Threads_running` and `Threads_connected`.
```sql
SHOW STATUS LIKE 'Threads_%';
SHOW PROCESSLIST;
```
4. **Slow queries**: check if large batches are locking `er_incidents` or `er_incident_occurrences`.
```sql
SHOW FULL PROCESSLIST;
SELECT * FROM information_schema.INNODB_TRX;
```
5. **Resource pressure**: check container CPU/memory via `docker stats` or node exporter.
6. **Mitigation**:
- Scale DB connection pool: `DB_POOL_MAX` (api), `connectionLimit` (ingest-api `server.ts`).
- Reduce `INGEST_RATE_LIMIT_MAX` to shed load.
- Restart ingest-api pod if event loop is stuck.
---
## Triage: IngestErrorRateHigh
1. Check ingest-api logs: `docker compose logs ingest-api --tail=200`
2. Filter 5xx: look for `ingest_failed` log entries.
3. Common causes:
- MariaDB connection refused (pool exhausted or DB down).
- Schema validation failures from malformed payloads.
- Deadlocks on `er_incidents` UPSERT (fingerprint contention).
4. **Mitigation**:
- If DB down: restart MariaDB, verify healthcheck.
- If deadlocks: check for hot fingerprints receiving concurrent writes.
- If payload issues: check collector-worker for malformed source data.
---
## Triage: IngestApiDown / ErrorApiDown
1. Check container status: `docker compose ps`
2. Check logs: `docker compose logs <service> --tail=50`
3. Common causes:
- OOM kill (check `dmesg | grep -i oom`).
- Port conflict.
- DB migration failure blocking startup.
4. **Mitigation**: `docker compose restart <service>`
---
## Key Endpoints for Manual Checks
| Check | Command |
|-------|---------|
| API health | `curl -sf http://localhost:3200/health` |
| Ingest health | `curl -sf http://localhost:3041/health` |
| API Prometheus | `curl -sf http://localhost:3200/metrics` |
| Ingest Prometheus | `curl -sf http://localhost:3041/metrics` |
| Operational stats | `curl -sf 'http://localhost:3200/api/error-monitoring/stats?api_key=...'` |
---
## Useful PromQL Queries
```promql
# Ingest throughput (events/sec)
sum(rate(er_ingest_events_total[5m])) by (outcome)
# Ingest request rate by status
sum(rate(er_ingest_requests_total[5m])) by (status_code)
# Average batch size
rate(er_ingest_batch_size_sum[5m]) / rate(er_ingest_batch_size_count[5m])
# Incidents by severity (gauge)
er_incidents_by_severity
# Resolution rate per project
er_project_resolution_rate
# API HTTP latency p95
histogram_quantile(0.95, sum(rate(er_api_http_request_duration_seconds_bucket[5m])) by (le, route))
```
+39 -1
View File
@@ -13,7 +13,8 @@
"@fastify/swagger-ui": "^3.1.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"mysql2": "^3.11.5"
"mysql2": "^3.11.5",
"prom-client": "^15.1.3"
},
"devDependencies": {
"@types/node": "^22.9.0",
@@ -608,6 +609,15 @@
"node": ">=8"
}
},
"node_modules/@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
"license": "Apache-2.0",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1226,6 +1236,12 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/bintrees": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",
"integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
@@ -2103,6 +2119,19 @@
"integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",
"license": "MIT"
},
"node_modules/prom-client": {
"version": "15.1.3",
"resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz",
"integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==",
"license": "Apache-2.0",
"dependencies": {
"@opentelemetry/api": "^1.4.0",
"tdigest": "^0.1.1"
},
"engines": {
"node": "^16 || ^18 || >=20"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -2505,6 +2534,15 @@
"node": ">=8"
}
},
"node_modules/tdigest": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
"integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==",
"license": "MIT",
"dependencies": {
"bintrees": "1.0.2"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+2 -1
View File
@@ -18,7 +18,8 @@
"@fastify/swagger-ui": "^3.1.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"mysql2": "^3.11.5"
"mysql2": "^3.11.5",
"prom-client": "^15.1.3"
},
"devDependencies": {
"@types/node": "^22.9.0",
+20
View File
@@ -13,6 +13,10 @@ import {
processIngestBatch,
type IngestEventInput,
} from "./services/processIngestBatch.js";
import prometheusPlugin, {
ingestEventsTotal,
ingestBatchSize,
} from "./plugins/prometheus.js";
const _ingestEventSchema = {
type: "object",
@@ -119,6 +123,8 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
uiConfig: { docExpansion: "list", deepLinking: true },
});
await _app.register(prometheusPlugin);
_app.get("/health", {
schema: {
description: "Liveness probe",
@@ -206,6 +212,7 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
: null;
const _bodyHash = computeRequestBodyHash(_body);
try {
ingestBatchSize.observe(_body.events.length);
const _out = await processIngestBatch({
pool: input.pool,
ingestKeyId: request.ingestAuth.keyId,
@@ -214,6 +221,18 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
idempotencyKey: _idempotencyKey,
bodyHash: _bodyHash,
});
// Track event outcomes
if (_out.body && typeof _out.body === 'object' && 'results' in _out.body) {
const results = (_out.body as { results: Array<{ skipped?: boolean }> }).results;
let stored = 0;
let skipped = 0;
for (const r of results) {
if (r.skipped) skipped++;
else stored++;
}
if (stored > 0) ingestEventsTotal.inc({ outcome: 'stored' }, stored);
if (skipped > 0) ingestEventsTotal.inc({ outcome: 'skipped_noise' }, skipped);
}
return reply.status(_out.status).send(_out.body);
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "ingest_failed";
@@ -229,6 +248,7 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
message: "occurred_at must be a valid ISO-8601 timestamp.",
});
}
ingestEventsTotal.inc({ outcome: 'error' }, _body.events.length);
request.log.error(_err, "ingest_failed");
return reply.status(500).send({
error: "internal_error",
+96
View File
@@ -0,0 +1,96 @@
/**
* Prometheus metrics plugin for ingest-api.
* Exposes GET /metrics (text/plain; Prometheus exposition format).
*
* Key SLO metric: er_ingest_request_duration_seconds histogram
* with p50/p95/p99 buckets for latency tracking.
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
import {
Registry,
collectDefaultMetrics,
Histogram,
Counter,
Gauge,
} from "prom-client";
const register = new Registry();
collectDefaultMetrics({ register, prefix: "er_ingest_" });
/* ── Ingest SLO: request latency histogram ───────────────────────────── */
export const ingestDuration = new Histogram({
name: "er_ingest_request_duration_seconds",
help: "Ingest request duration in seconds (SLO target: p95 < 500ms, p99 < 1s)",
labelNames: ["status_code"] as const,
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1, 2, 5],
registers: [register],
});
/* ── Ingest throughput counters ──────────────────────────────────────── */
export const ingestEventsTotal = new Counter({
name: "er_ingest_events_total",
help: "Total events ingested",
labelNames: ["outcome"] as const, // stored, skipped_noise, error
registers: [register],
});
export const ingestRequestsTotal = new Counter({
name: "er_ingest_requests_total",
help: "Total ingest HTTP requests",
labelNames: ["status_code"] as const,
registers: [register],
});
export const ingestBatchSize = new Histogram({
name: "er_ingest_batch_size",
help: "Number of events per ingest request",
buckets: [1, 2, 5, 10, 20, 50],
registers: [register],
});
/* ── Active connections gauge ────────────────────────────────────────── */
export const activeConnections = new Gauge({
name: "er_ingest_active_connections",
help: "Number of in-flight ingest requests",
registers: [register],
});
export { register as prometheusRegistry };
export default async function prometheusPlugin(
app: FastifyInstance,
): Promise<void> {
// Track all requests
app.addHook("onRequest", async () => {
activeConnections.inc();
});
app.addHook(
"onResponse",
async (request: FastifyRequest, reply: FastifyReply) => {
activeConnections.dec();
const route = request.routeOptions?.url ?? request.url;
if (route === "/metrics") return;
const elapsed = reply.elapsedTime / 1000;
const statusCode = String(reply.statusCode);
// Only track ingest endpoint for SLO histogram
if (route === "/events" || request.url.startsWith("/v1/ingest")) {
ingestDuration.observe({ status_code: statusCode }, elapsed);
ingestRequestsTotal.inc({ status_code: statusCode });
}
},
);
// Expose /metrics
app.get("/metrics", async (_request: FastifyRequest, reply: FastifyReply) => {
reply.header("Content-Type", register.contentType);
return reply.send(await register.metrics());
});
}