From b7cbf528ee9f4866efa6f7572d4291d7d774453f Mon Sep 17 00:00:00 2001 From: David Santos Date: Tue, 21 Apr 2026 05:08:42 +0000 Subject: [PATCH] ingest-api: export error_hub_* Prometheus metrics for hub freshness alerts Join er_projects in ingest auth to expose lowercase project slug. Record error_hub_last_event_timestamp from stored events occurred_at and error_hub_ingest_failures_total on HTTP 500 batches (BIT-4903 / BIT-4932). Add integration assertion when ERROR_REPORTING_TEST_DATABASE_URL is set. Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f) Paperclip-Issue: BIT-4932 Paperclip-Run: 00b93610-8794-4264-81a9-6f4cb39a9d8d Made-with: Cursor --- ingest-api/src/buildApp.ts | 39 +++++++++++++++---- .../src/integration.twoProjects.test.ts | 27 +++++++++++++ ingest-api/src/plugins/prometheus.ts | 16 ++++++++ ingest-api/src/services/ingestAuth.ts | 24 +++++++----- ingest-api/src/types/fastify.d.ts | 1 + 5 files changed, 91 insertions(+), 16 deletions(-) diff --git a/ingest-api/src/buildApp.ts b/ingest-api/src/buildApp.ts index 8222682..d6619ff 100644 --- a/ingest-api/src/buildApp.ts +++ b/ingest-api/src/buildApp.ts @@ -15,7 +15,10 @@ import { import prometheusPlugin, { ingestEventsTotal, ingestBatchSize, + errorHubLastEventTimestamp, + errorHubIngestFailuresTotal, } from "./plugins/prometheus.js"; +import { parseOccurredAt } from "./lib/normalize.js"; import { ingestBatchBodyJsonSchema } from "./ingestJsonSchemas.js"; const _ingestResultStoredSchema = { @@ -237,16 +240,34 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise }).results; let stored = 0; let skipped = 0; - for (const r of results) { - if (r.skipped) skipped++; - else stored++; + let _maxOccurredSec = 0; + for (let _i = 0; _i < results.length; _i++) { + const r = results[_i]!; + if (r.skipped) { + skipped++; + continue; + } + stored++; + const _ev = _body.events[_i]; + if (_ev && typeof _ev.occurred_at === "string") { + try { + const _sec = Math.floor(parseOccurredAt(_ev.occurred_at) / 1000); + if (_sec > _maxOccurredSec) _maxOccurredSec = _sec; + } catch { + /* parseOccurredAt throws on invalid — skip gauge for this row */ + } + } + } + if (stored > 0) ingestEventsTotal.inc({ outcome: "stored" }, stored); + if (skipped > 0) ingestEventsTotal.inc({ outcome: "skipped_noise" }, skipped); + const _slug = request.ingestAuth.projectSlug; + if (_slug !== "" && _maxOccurredSec > 0) { + errorHubLastEventTimestamp.set({ project_slug: _slug }, _maxOccurredSec); } - 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) { @@ -263,7 +284,11 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { expect(Number((checkB[0] as { c: number }).c)).toBe(1); }); + it("exposes error_hub_last_event_timestamp on /metrics after stored ingest (BIT-4903)", async () => { + const _occurredIso = "2026-04-21T12:00:00.000Z"; + const _expectedSec = Math.floor(Date.parse(_occurredIso) / 1000); + const _res = await _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: { authorization: `Bearer ${_tokenA}` }, + payload: { + events: [ + { + schema_version: 1, + occurred_at: _occurredIso, + level: "error", + message: "error hub prometheus metric probe", + fingerprint: "fp-error-hub-metric-1", + }, + ], + }, + }); + expect(_res.statusCode).toBe(200); + const _metrics = await _app.inject({ method: "GET", url: "/metrics" }); + expect(_metrics.statusCode).toBe(200); + expect(_metrics.body).toContain( + `error_hub_last_event_timestamp{project_slug="pa"} ${_expectedSec}`, + ); + }); + it("accepts unknown event-level fields (forward-compatible for CRM / deploy smokes)", async () => { const _res = await _app.inject({ method: "POST", diff --git a/ingest-api/src/plugins/prometheus.ts b/ingest-api/src/plugins/prometheus.ts index e4e6126..77124f9 100644 --- a/ingest-api/src/plugins/prometheus.ts +++ b/ingest-api/src/plugins/prometheus.ts @@ -60,6 +60,22 @@ export const activeConnections = new Gauge({ registers: [register], }); +/* ── Error hub SLO / alerting (BIT-4903 / BIT-4932) — names match Prometheus rules in Paperclip bundle ─ */ + +export const errorHubLastEventTimestamp = new Gauge({ + name: "error_hub_last_event_timestamp", + help: "Unix time (seconds) of the latest successfully stored ingest event occurred_at, per project_slug", + labelNames: ["project_slug"] as const, + registers: [register], +}); + +export const errorHubIngestFailuresTotal = new Counter({ + name: "error_hub_ingest_failures_total", + help: "Ingest handler failures (HTTP 500) counted by events in the failed batch, per project_slug", + labelNames: ["project_slug"] as const, + registers: [register], +}); + export { register as prometheusRegistry }; export default async function prometheusPlugin( diff --git a/ingest-api/src/services/ingestAuth.ts b/ingest-api/src/services/ingestAuth.ts index 055f347..9985c16 100644 --- a/ingest-api/src/services/ingestAuth.ts +++ b/ingest-api/src/services/ingestAuth.ts @@ -6,6 +6,8 @@ import { sha256Hex } from "../lib/hash.js"; export type IngestAuthContext = { keyId: string; projectId: string; + /** Lowercase `er_projects.slug` — Prometheus `project_slug` label (BIT-4903). */ + projectSlug: string; rateLimitMax: number | null; rateLimitWindowMs: number | null; }; @@ -39,15 +41,17 @@ export async function attachIngestAuth( } const _hash = sha256Hex(_token); const [rows] = await pool.execute( - `SELECT CAST(id AS CHAR) AS id, - CAST(project_id AS CHAR) AS project_id, - rate_limit_max, - rate_limit_window_ms - FROM er_ingest_keys - WHERE token_hash = ? - AND status = 'active' - AND revoked_at IS NULL - AND (expires_at IS NULL OR expires_at > NOW(6))`, + `SELECT CAST(k.id AS CHAR) AS id, + CAST(k.project_id AS CHAR) AS project_id, + LOWER(p.slug) AS project_slug, + k.rate_limit_max, + k.rate_limit_window_ms + FROM er_ingest_keys k + INNER JOIN er_projects p ON p.id = k.project_id + WHERE k.token_hash = ? + AND k.status = 'active' + AND k.revoked_at IS NULL + AND (k.expires_at IS NULL OR k.expires_at > NOW(6))`, [_hash], ); if (rows.length === 0) { @@ -60,6 +64,7 @@ export async function attachIngestAuth( const _row = rows[0] as { id: string; project_id: string; + project_slug: string; rate_limit_max: unknown; rate_limit_window_ms: unknown; }; @@ -75,6 +80,7 @@ export async function attachIngestAuth( request.ingestAuth = { keyId: _row.id, projectId: _row.project_id, + projectSlug: String(_row.project_slug ?? "").trim().toLowerCase(), rateLimitMax: Number.isFinite(_rlMaxNum) && _rlMaxNum > 0 ? _rlMaxNum : null, rateLimitWindowMs: Number.isFinite(_rlWinNum) && _rlWinNum > 0 ? _rlWinNum : null, }; diff --git a/ingest-api/src/types/fastify.d.ts b/ingest-api/src/types/fastify.d.ts index 63e828a..a56e178 100644 --- a/ingest-api/src/types/fastify.d.ts +++ b/ingest-api/src/types/fastify.d.ts @@ -5,6 +5,7 @@ declare module "fastify" { ingestAuth?: { keyId: string; projectId: string; + projectSlug: string; rateLimitMax: number | null; rateLimitWindowMs: number | null; };