Files
errors.bitreport.pt/ingest-api/src/buildApp.ts
T
David Santos 23704d2e59
CI / Test api (push) Successful in 54s
CI / Test ingest-api (push) Successful in 57s
CI / Lint and typecheck admin-ui (push) Successful in 1m48s
CI / Validate Docker build (push) Successful in 5m19s
feat(ingest): label er_ingest_events_total skipped_noise by rule_id
Break down noise filter counters per noise policy rule for Prometheus observability.

Paperclip-Agent: David Santos (urlKey david-santos; id 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376)
Paperclip-Issue: BIT-26791
Paperclip-Run: cea24469-2886-457d-9f6f-09d83aaf9e4a
2026-07-17 23:01:35 +00:00

325 lines
11 KiB
TypeScript

import { randomUUID } from "node:crypto";
import fastify from "fastify";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";
import type { Pool } from "mysql2/promise";
import type { IngestEnv } from "./config/env.js";
import { attachIngestAuth } from "./services/ingestAuth.js";
import { createIngestRateLimiter } from "./services/ingestRateLimit.js";
import {
computeRequestBodyHash,
processIngestBatch,
type IngestEventInput,
} from "./services/processIngestBatch.js";
import prometheusPlugin, {
ingestEventsTotal,
ingestBatchSize,
errorHubLastEventTimestamp,
errorHubIngestFailuresTotal,
} from "./plugins/prometheus.js";
import { parseOccurredAt } from "./lib/normalize.js";
import { ingestBatchBodyJsonSchema } from "./ingestJsonSchemas.js";
const _ingestResultStoredSchema = {
type: "object",
additionalProperties: false,
required: ["incident_id", "occurrence_id", "fingerprint"],
properties: {
incident_id: { type: "string" },
occurrence_id: { type: "string" },
fingerprint: { type: "string" },
},
} as const;
const _ingestResultSkippedSchema = {
type: "object",
additionalProperties: false,
required: ["skipped", "rule_id", "reason", "noise_ruleset_version", "fingerprint_policy_version"],
properties: {
skipped: { type: "boolean", enum: [true] },
rule_id: { type: "string" },
reason: { type: "string" },
noise_ruleset_version: { type: "string" },
fingerprint_policy_version: { type: "integer" },
},
} as const;
function _ingestEventsPostPath(url: string): boolean {
const _path = url.split("?", 1)[0] ?? url;
return _path === "/v1/ingest/events" || _path.endsWith("/v1/ingest/events");
}
export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<FastifyInstance> {
const _ingestLimiter = createIngestRateLimiter();
const _app = fastify({
logger: true,
requestIdHeader: "x-request-id",
genReqId: () => randomUUID(),
});
await _app.register(swagger, {
openapi: {
openapi: "3.1.0",
info: {
title: "BitReport error reporting — passive ingest API",
description:
"Authenticated per-project ingest for error events (BIT-154.3). Keys are hashed at rest; send the raw token via `Authorization: Bearer` or `X-Api-Key`.",
version: "0.1.0",
},
servers: [{ url: "/" }],
tags: [{ name: "ingest", description: "Event ingestion" }],
components: {
securitySchemes: {
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "opaque token",
},
apiKeyAuth: {
type: "apiKey",
in: "header",
name: "X-Api-Key",
},
},
},
},
});
await _app.register(swaggerUi, {
routePrefix: "/v1/docs/ui",
uiConfig: { docExpansion: "list", deepLinking: true },
});
await _app.register(prometheusPlugin);
_app.get("/health", {
schema: {
description: "Liveness probe",
tags: ["ingest"],
response: {
200: {
type: "object",
properties: { status: { type: "string" } },
},
},
},
handler: async () => ({ status: "ok" }),
});
await _app.register(
async (ingestScope: FastifyInstance) => {
ingestScope.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
if (request.method !== "POST" || !_ingestEventsPostPath(request.url)) {
return;
}
const _auth = request.headers.authorization;
const _ak = request.headers["x-api-key"];
const _hasCred =
(typeof _auth === "string" && _auth.trim() !== "") ||
(typeof _ak === "string" && _ak.trim() !== "");
if (_hasCred) {
return;
}
const _r = _ingestLimiter.tryConsume(
`anon_ip:${request.ip}`,
input.env.INGEST_ANON_IP_MAX,
input.env.INGEST_ANON_IP_WINDOW_MS,
);
if (!_r.ok) {
reply.header("retry-after", String(_r.retryAfterSec));
return reply.status(429).send({
error: "rate_limited",
message: "Too many unauthenticated ingest attempts from this address.",
});
}
});
ingestScope.post("/events", {
schema: {
description: "Ingest one or more error events for the project bound to the API key.",
tags: ["ingest"],
security: [{ bearerAuth: [] }, { apiKeyAuth: [] }],
body: ingestBatchBodyJsonSchema,
response: {
200: {
type: "object",
properties: {
fingerprint_policy_version: { type: "integer" },
noise_ruleset_version: { type: "string" },
noise_filtered_count: { type: "integer" },
results: {
type: "array",
items: {
oneOf: [_ingestResultStoredSchema, _ingestResultSkippedSchema],
},
},
},
required: [
"fingerprint_policy_version",
"noise_ruleset_version",
"noise_filtered_count",
"results",
],
},
401: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
429: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
409: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
503: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
500: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
},
},
preValidation: async (request: FastifyRequest, reply: FastifyReply) => {
await attachIngestAuth(input.pool, request, reply);
},
preHandler: async (request: FastifyRequest, reply: FastifyReply) => {
const _a = request.ingestAuth;
if (!_a) {
return;
}
const _max = _a.rateLimitMax ?? input.env.INGEST_RATE_LIMIT_MAX;
const _win = _a.rateLimitWindowMs ?? input.env.INGEST_RATE_LIMIT_WINDOW_MS;
const _r = _ingestLimiter.tryConsume(`ingest_key:${_a.keyId}`, _max, _win);
if (!_r.ok) {
reply.header("retry-after", String(_r.retryAfterSec));
return reply.status(429).send({
error: "rate_limited",
message: "Ingest rate limit exceeded for this API key; retry after the Retry-After interval.",
});
}
},
handler: async (request: FastifyRequest, reply: FastifyReply) => {
if (!request.ingestAuth) {
return;
}
const _body = request.body as { events: IngestEventInput[] };
const _idemHeader = request.headers["idempotency-key"];
const _idempotencyKey =
typeof _idemHeader === "string" && _idemHeader.trim() !== ""
? _idemHeader.trim().slice(0, 128)
: null;
const _bodyHash = computeRequestBodyHash(_body);
try {
ingestBatchSize.observe(_body.events.length);
const _out = await processIngestBatch({
pool: input.pool,
ingestKeyId: request.ingestAuth.keyId,
projectId: request.ingestAuth.projectId,
events: _body.events,
idempotencyKey: _idempotencyKey,
bodyHash: _bodyHash,
});
// Track event outcomes (rule_id on skipped_noise for BIT-26791)
if (_out.body && typeof _out.body === "object" && "results" in _out.body) {
const results = (
_out.body as { results: Array<{ skipped?: boolean; rule_id?: string }> }
).results;
let stored = 0;
let _maxOccurredSec = 0;
const skippedByRule = new Map<string, number>();
for (let _i = 0; _i < results.length; _i++) {
const r = results[_i]!;
if (r.skipped) {
const _ruleId =
typeof r.rule_id === "string" && r.rule_id !== "" ? r.rule_id : "unknown";
skippedByRule.set(_ruleId, (skippedByRule.get(_ruleId) ?? 0) + 1);
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", rule_id: "" }, stored);
}
for (const [_ruleId, _n] of skippedByRule) {
ingestEventsTotal.inc({ outcome: "skipped_noise", rule_id: _ruleId }, _n);
}
const _slug = request.ingestAuth.projectSlug;
if (_slug !== "" && _maxOccurredSec > 0) {
errorHubLastEventTimestamp.set({ project_slug: _slug }, _maxOccurredSec);
}
}
return reply.status(_out.status).send(_out.body);
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "ingest_failed";
if (_msg === "unsupported_schema_version") {
return reply.status(400).send({
error: "bad_request",
message: "Unsupported schema_version (only 1 is accepted).",
});
}
if (_msg === "invalid_occurred_at") {
return reply.status(400).send({
error: "bad_request",
message: "occurred_at must be a valid ISO-8601 timestamp.",
});
}
ingestEventsTotal.inc({ outcome: "error", rule_id: "" }, _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",
message:
input.env.NODE_ENV === "production"
? "Ingest failed; see server logs for request id."
: _msg,
});
}
},
});
},
{ prefix: "/v1/ingest" },
);
_app.addHook("onSend", async (_request: FastifyRequest, reply: FastifyReply) => {
reply.header("X-Content-Type-Options", "nosniff");
});
_app.get("/v1/openapi.json", async (_request: FastifyRequest, reply: FastifyReply) => {
return reply.send(_app.swagger());
});
return _app;
}