ingest-api: export error_hub_* Prometheus metrics for hub freshness alerts
CI / Test ingest-api (pull_request) Successful in 38s
CI / Test api (pull_request) Successful in 43s
CI / Lint and typecheck admin-ui (pull_request) Successful in 1m30s
CI / Validate Docker build (pull_request) Successful in 5m45s

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
This commit is contained in:
David Santos committed 2026-04-21 05:08:42 +00:00
1 parent 988b4c57a4
commit b7cbf528ee
5 files changed
+91 -16

No files matched your search

+32 -7
View File
@@ -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<F
bodyHash: _bodyHash,
});
// Track event outcomes
if (_out.body && typeof _out.body === 'object' && 'results' in _out.body) {
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++;
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<F
message: "occurred_at must be a valid ISO-8601 timestamp.",
});
}
ingestEventsTotal.inc({ outcome: 'error' }, _body.events.length);
ingestEventsTotal.inc({ outcome: "error" }, _body.events.length);
const _slugErr = request.ingestAuth?.projectSlug ?? "";
if (_slugErr !== "") {
errorHubIngestFailuresTotal.inc({ project_slug: _slugErr }, _body.events.length);
}
request.log.error(_err, "ingest_failed");
return reply.status(500).send({
error: "internal_error",
@@ -132,6 +132,33 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
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",
+16
View File
@@ -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(
+15 -9
View File
@@ -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<RowDataPacket[]>(
`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,
};
+1
View File
@@ -5,6 +5,7 @@ declare module "fastify" {
ingestAuth?: {
keyId: string;
projectId: string;
projectSlug: string;
rateLimitMax: number | null;
rateLimitWindowMs: number | null;
};