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; };