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

+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,
});
},
);
}