feat(BIT-247): consolidate error reporting repo from OTT

Merge ingest-api, collector-worker, admin-ui, database/error_reporting, deploy/lxc,
docker-compose, and deployment docs into the dedicated repository. Paths updated
for repo root (ER_REPO_ROOT, systemd WorkingDirectory). Root README documents layout.

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1sonhadorandPaperclip committed 2026-03-22 18:20:27 +00:00
1 parent eeb5039a3c
commit b0b733d5e1
88 files changed
+19321

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
# BitReport error reporting — Docker Compose (copy to `.env` in this directory).
# `docker compose` reads `.env` automatically for variable substitution in docker-compose.yml.
# --- PostgreSQL (service: postgres) ---
ER_POSTGRES_USER=postgres
ER_POSTGRES_PASSWORD=postgres
ER_POSTGRES_DB=error_reporting
# Host port mapped to Postgres (container always listens on 5432)
ER_PUBLISH_PG_PORT=5434
# --- Ingest API (service: ingest-api) ---
ER_PUBLISH_INGEST_PORT=3041
# Optional rate limiting (defaults match ingest-api/src/config/env.ts)
# INGEST_RATE_LIMIT_MAX=300
# INGEST_RATE_LIMIT_WINDOW_MS=60000
# --- Collector worker (service: collector-worker) ---
# Demo token for the seeded HTTP fixture source (must match project token in DB seed)
ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one
# TICK_INTERVAL_MS=3000
# SOURCE_REFRESH_MS=15000
# HTTP_FETCH_TIMEOUT_MS=15000
# MAX_BACKOFF_EXPONENT=8
# COLLECTOR_DEFAULT_INGEST_TOKEN=
+1
View File
@@ -5,3 +5,4 @@ dist/
.env.local
*.log
coverage/
.DS_Store
+43
View File
@@ -0,0 +1,43 @@
# errors.bitreport.pt
BitReport **central error reporting** platform: ingest API, collector worker, admin UI (incidents), PostgreSQL migrations, and optional **admin portal** (auth/RBAC) from BIT-183.
**Remote:** `https://git.bitreport.pt/BitReport.pt/errors.bitreport.pt.git`
**Tracking:** Paperclip **BIT-247** (migration from `OTT/error-reporting/`).
## Layout
| Path | Role |
|------|------|
| `ingest-api/` | Fastify HTTP ingest (BIT-154.x) |
| `collector-worker/` | Polls configured sources → ingest API |
| `admin-ui/` | Next.js operator UI (incidents) |
| `database/error_reporting/` | SQL migrations + dev seed (used by Compose + LXC) |
| `deploy/lxc/` | systemd, nginx examples, migrate script (no Docker) |
| `docker-compose.yml`, `.env.example` | Local / Proxmox Docker stack |
| `api/` | Fastify admin API — sessions, RBAC (BIT-183) |
| `web/` | Next.js admin login/UI for `api/` |
| `db/migrations/` | Admin-user schema (node-pg-migrate); distinct from `database/error_reporting/` |
| `docs/` | Permission matrix, deployment runbooks |
## Docker Compose (ingest stack)
From the **repository root**:
```bash
cp .env.example .env
docker compose up --build
curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health"
```
## Docs
- Compose + TLS: [`docs/deployment/bitreport-error-reporting-compose-proxmox.md`](docs/deployment/bitreport-error-reporting-compose-proxmox.md)
- LXC + systemd: [`docs/deployment/bitreport-error-reporting-lxc-proxmox.md`](docs/deployment/bitreport-error-reporting-lxc-proxmox.md)
## Tests (local)
```bash
cd ingest-api && npm ci && npm test
cd ../api && npm ci && npm test
```
+5
View File
@@ -0,0 +1,5 @@
# Base URL da API admin (Fastify) quando existir (BIT-179). Sem trailing slash.
# ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3050
# Apenas desenvolvimento: carrega dados fictícios para validar layout sem API.
# ERROR_REPORTING_UI_DEMO=1
+6
View File
@@ -0,0 +1,6 @@
.next/
node_modules/
out/
.env
.env.local
*.tsbuildinfo
+41
View File
@@ -0,0 +1,41 @@
@import "bootstrap/scss/bootstrap";
/* Velzon-adjacent shell (Bootstrap 5; no proprietary template assets). */
.er-app {
--er-sidebar-width: 260px;
}
.er-sidebar {
width: var(--er-sidebar-width);
background: linear-gradient(180deg, #1a1d21 0%, #212529 40%, #1a1d21 100%);
}
.er-nav-link {
border-radius: 0.35rem;
padding: 0.5rem 0.75rem;
}
.er-nav-link:hover,
.er-nav-link:focus {
background: rgba(255, 255, 255, 0.06);
color: #fff !important;
}
.er-topbar {
position: sticky;
top: 0;
z-index: 1020;
}
.er-main {
background-color: #f3f6f9;
min-height: calc(100vh - 72px);
}
pre.er-stack {
max-height: 320px;
overflow: auto;
font-size: 0.8rem;
white-space: pre-wrap;
word-break: break-word;
}
+20
View File
@@ -0,0 +1,20 @@
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
export default function IncidentNotFound() {
return (
<AppShell
title="Incidente não encontrado"
breadcrumb={[
{ label: "Painel", href: "/" },
{ label: "Incidentes", href: "/incidents" },
{ label: "404" },
]}
>
<p>O incidente pedido não existe ou foi removido.</p>
<Link href="/incidents" className="btn btn-primary">
Voltar à lista
</Link>
</AppShell>
);
}
+162
View File
@@ -0,0 +1,162 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { AppShell } from "@/components/AppShell";
import { DataAlert } from "@/components/DataAlert";
import { IncidentNotes } from "@/components/IncidentNotes";
import { SeverityBadge } from "@/components/SeverityBadge";
import { StateBadge } from "@/components/StateBadge";
import { formatDateTime } from "@/lib/format";
import { fetchIncidentDetail } from "@/lib/incidents-data";
export default async function IncidentDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
const _decoded = decodeURIComponent(id);
const _result = await fetchIncidentDetail(_decoded);
if (!_result.ok) {
if (_result.error === "not_found") {
notFound();
}
return (
<AppShell
title="Incidente"
breadcrumb={[
{ label: "Painel", href: "/" },
{ label: "Incidentes", href: "/incidents" },
{ label: "Detalhe" },
]}
>
<DataAlert
variant={_result.error === "not_configured" ? "warning" : "danger"}
title={_result.error === "not_configured" ? "Detalhe indisponível" : "Erro de ligação"}
body={_result.message}
/>
<Link href="/incidents" className="btn btn-outline-secondary">
Voltar à lista
</Link>
</AppShell>
);
}
const _inc = _result.incident;
const _occ = _inc.occurrences[0];
return (
<AppShell
title={_inc.title}
breadcrumb={[
{ label: "Painel", href: "/" },
{ label: "Incidentes", href: "/incidents" },
{ label: _inc.fingerprint },
]}
>
{_result.source === "demo" ? (
<p className="text-muted small">
Dados de demonstração — stack e contexto alinhados com o modelo relacional (BIT-178).
</p>
) : null}
<div className="row g-3">
<div className="col-lg-8">
<div className="card mb-3">
<div className="card-header d-flex flex-wrap gap-2 align-items-center justify-content-between">
<div className="d-flex flex-wrap gap-2 align-items-center">
<StateBadge state={_inc.currentState} />
<SeverityBadge severity={_inc.severity} />
</div>
<span className="small text-muted font-monospace">id: {_inc.id}</span>
</div>
<div className="card-body">
<dl className="row mb-0">
<dt className="col-sm-3">Projeto</dt>
<dd className="col-sm-9">
<code>{_inc.projectSlug}</code>
</dd>
<dt className="col-sm-3">Fingerprint</dt>
<dd className="col-sm-9">
<code>{_inc.fingerprint}</code>
</dd>
<dt className="col-sm-3">Origem (ingest)</dt>
<dd className="col-sm-9">{_inc.ingestKeyLabel ?? "—"}</dd>
<dt className="col-sm-3">Primeira vista</dt>
<dd className="col-sm-9">{formatDateTime(_inc.firstSeenAt)}</dd>
<dt className="col-sm-3">Última vista</dt>
<dd className="col-sm-9">{formatDateTime(_inc.lastSeenAt)}</dd>
<dt className="col-sm-3">Ocorrências</dt>
<dd className="col-sm-9 font-monospace">{_inc.occurrencesCount}</dd>
</dl>
</div>
</div>
<div className="card mb-3">
<div className="card-header fw-semibold">Meta (incidente)</div>
<div className="card-body">
{_inc.metadataJson && Object.keys(_inc.metadataJson).length > 0 ? (
<pre className="er-stack bg-light border rounded p-3 mb-0">
{JSON.stringify(_inc.metadataJson, null, 2)}
</pre>
) : (
<p className="text-muted mb-0">Sem metadados agregados neste incidente.</p>
)}
</div>
</div>
<div className="card mb-3">
<div className="card-header fw-semibold">Última ocorrência — mensagem</div>
<div className="card-body">
{_occ ? (
<>
<p className="mb-2">{_occ.message}</p>
<p className="small text-muted mb-0">
<span className="me-2">
Nível: <code>{_occ.levelRaw}</code>
</span>
· {formatDateTime(_occ.occurredAt)}
</p>
</>
) : (
<p className="text-muted mb-0">Sem ocorrências carregadas nesta vista.</p>
)}
</div>
</div>
<div className="card mb-3">
<div className="card-header fw-semibold">Stack trace</div>
<div className="card-body">
{_occ?.stacktrace ? (
<pre className="er-stack bg-dark text-light rounded p-3 mb-0">{_occ.stacktrace}</pre>
) : (
<p className="text-muted mb-0">Sem stack trace na última ocorrência.</p>
)}
</div>
</div>
<div className="card mb-3">
<div className="card-header fw-semibold">Contexto (JSON)</div>
<div className="card-body">
{_occ?.contextJson && Object.keys(_occ.contextJson).length > 0 ? (
<pre className="er-stack bg-light border rounded p-3 mb-0">
{JSON.stringify(_occ.contextJson, null, 2)}
</pre>
) : (
<p className="text-muted mb-0">Sem contexto estruturado na última ocorrência.</p>
)}
</div>
</div>
</div>
<div className="col-lg-4">
<div className="card mb-3">
<div className="card-header fw-semibold">Notas</div>
<div className="card-body">
<IncidentNotes incidentId={_inc.id} />
</div>
</div>
<Link href="/incidents" className="btn btn-outline-secondary w-100">
Voltar à lista
</Link>
</div>
</div>
</AppShell>
);
}
+200
View File
@@ -0,0 +1,200 @@
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { DataAlert } from "@/components/DataAlert";
import { SeverityBadge } from "@/components/SeverityBadge";
import { StateBadge } from "@/components/StateBadge";
import { formatDateTime } from "@/lib/format";
import { fetchIncidentList } from "@/lib/incidents-data";
import type { IncidentState, Severity } from "@/lib/types";
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
const _states: IncidentState[] = ["open", "investigating", "resolved", "ignored"];
const _severities: Severity[] = ["critical", "high", "medium", "low", "info"];
function _param(sp: Record<string, string | string[] | undefined>, key: string): string {
const _v = sp[key];
if (Array.isArray(_v)) {
return _v[0] ?? "";
}
return _v ?? "";
}
export default async function IncidentsPage(props: { searchParams: SearchParams }) {
const _sp = await props.searchParams;
const _state = _param(_sp, "state") as IncidentState | "";
const _severity = _param(_sp, "severity") as Severity | "";
const _project = _param(_sp, "project");
const _q = _param(_sp, "q");
// Fetch unfiltered list first to build the project dropdown options.
const _allList = await fetchIncidentList({});
const _projectSlugs: string[] = _allList.ok
? [...new Set(_allList.incidents.map((r) => r.projectSlug))].sort()
: [];
const _list = await fetchIncidentList({
state: _states.includes(_state as IncidentState) ? _state : "",
severity: _severities.includes(_severity as Severity) ? _severity : "",
project: _project,
q: _q,
});
return (
<AppShell
title="Incidentes"
breadcrumb={[{ label: "Painel", href: "/" }, { label: "Incidentes" }]}
>
{_list.ok && _list.source === "demo" ? (
<p className="text-muted small">
Dados de demonstração — ligue <code>ERROR_REPORTING_ADMIN_API_BASE</code> para dados reais
(BIT-179).
</p>
) : null}
{!_list.ok ? (
<DataAlert
variant={_list.error === "not_configured" ? "warning" : "danger"}
title={_list.error === "not_configured" ? "Lista indisponível" : "Erro de ligação"}
body={_list.message}
/>
) : null}
<div className="card mb-4">
<div className="card-header fw-semibold">Filtros</div>
<div className="card-body">
<form className="row g-3 align-items-end" method="get" action="/incidents">
<div className="col-md-2">
<label className="form-label" htmlFor="f-project">
Projeto
</label>
<select
id="f-project"
name="project"
className="form-select"
defaultValue={_project}
>
<option value="">Todos</option>
{_projectSlugs.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="f-state">
Estado
</label>
<select id="f-state" name="state" className="form-select" defaultValue={_state}>
<option value="">Todos</option>
{_states.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="f-severity">
Severidade
</label>
<select
id="f-severity"
name="severity"
className="form-select"
defaultValue={_severity}
>
<option value="">Todas</option>
{_severities.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="f-q">
Texto
</label>
<input
id="f-q"
name="q"
type="search"
className="form-control"
placeholder="Título ou fingerprint"
defaultValue={_q}
/>
</div>
<div className="col-md-2 d-grid">
<button type="submit" className="btn btn-primary">
Aplicar
</button>
</div>
</form>
</div>
</div>
<div className="card">
<div className="card-header d-flex justify-content-between align-items-center">
<span className="fw-semibold">Resultados</span>
{_list.ok ? (
<span className="badge text-bg-light text-dark border">{_list.incidents.length}</span>
) : null}
</div>
<div className="card-body p-0">
{_list.ok && _list.incidents.length === 0 ? (
<p className="p-4 mb-0 text-muted">Nenhum incidente corresponde aos filtros.</p>
) : null}
{_list.ok && _list.incidents.length > 0 ? (
<div className="table-responsive">
<table className="table table-hover table-striped mb-0 align-middle">
<thead className="table-light">
<tr>
<th scope="col">Estado</th>
<th scope="col">Severidade</th>
<th scope="col">Projeto</th>
<th scope="col">Título</th>
<th scope="col" className="text-end">
Ocorrências
</th>
<th scope="col">Última vista</th>
<th scope="col" />
</tr>
</thead>
<tbody>
{_list.incidents.map((row) => (
<tr key={row.id}>
<td>
<StateBadge state={row.currentState} />
</td>
<td>
<SeverityBadge severity={row.severity} />
</td>
<td>
<code className="small">{row.projectSlug}</code>
</td>
<td className="text-break">{row.title}</td>
<td className="text-end font-monospace">{row.occurrencesCount}</td>
<td className="text-nowrap small text-muted">
{formatDateTime(row.lastSeenAt)}
</td>
<td className="text-end">
<Link
href={`/incidents/${encodeURIComponent(row.id)}`}
className="btn btn-sm btn-outline-primary"
>
Detalhe
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</div>
</div>
</AppShell>
);
}
+15
View File
@@ -0,0 +1,15 @@
import type { Metadata } from "next";
import "./globals.scss";
export const metadata: Metadata = {
title: "BitReport — Error reporting",
description: "Painel central de incidentes (BIT-181)",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="pt">
<body className="bg-body text-body">{children}</body>
</html>
);
}
+63
View File
@@ -0,0 +1,63 @@
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { DataAlert } from "@/components/DataAlert";
import { KpiCard } from "@/components/KpiCard";
import { computeKpis, fetchIncidentList } from "@/lib/incidents-data";
export default async function DashboardPage() {
const _list = await fetchIncidentList({});
if (!_list.ok) {
return (
<AppShell title="Painel" breadcrumb={[{ label: "Painel" }]}>
<DataAlert
variant={_list.error === "not_configured" ? "warning" : "danger"}
title={_list.error === "not_configured" ? "Dados indisponíveis" : "Erro de ligação"}
body={_list.message}
/>
<p className="text-muted small mb-0">
Com <code>ERROR_REPORTING_UI_DEMO=1</code> pode visualizar KPIs de demonstração sem API.
</p>
</AppShell>
);
}
const _kpis = computeKpis(_list.incidents);
const _sourceHint =
_list.source === "demo" ? (
<p className="text-muted small">
Modo demonstração (<code>ERROR_REPORTING_UI_DEMO=1</code>) — substituir por API em
produção.
</p>
) : null;
return (
<AppShell title="Painel" breadcrumb={[{ label: "Painel" }]}>
{_sourceHint}
<div className="row g-3 mb-4">
<KpiCard label="Total (vista actual)" value={_kpis.total} variant="dark" />
<KpiCard label="Abertos" value={_kpis.open} variant="danger" />
<KpiCard label="Em investigação" value={_kpis.investigating} variant="warning" />
<KpiCard label="Resolvidos" value={_kpis.resolved} variant="success" />
</div>
<div className="row g-3 mb-4">
<div className="col-md-4">
<KpiCard label="Ignorados" value={_kpis.ignored} variant="secondary" />
</div>
</div>
<div className="card">
<div className="card-header d-flex align-items-center justify-content-between">
<span className="fw-semibold">Atalhos</span>
</div>
<div className="card-body">
<p className="mb-3">
Consulte a lista completa com filtros por estado, severidade e texto.
</p>
<Link href="/incidents" className="btn btn-primary">
Ver incidentes
</Link>
</div>
</div>
</AppShell>
);
}
+58
View File
@@ -0,0 +1,58 @@
import Link from "next/link";
import type { ReactNode } from "react";
export function AppShell({
children,
title,
breadcrumb,
}: {
children: ReactNode;
title: string;
breadcrumb?: { label: string; href?: string }[];
}) {
return (
<div className="er-app d-flex min-vh-100">
<aside className="er-sidebar text-white d-flex flex-column flex-shrink-0 p-3">
<Link href="/" className="text-white text-decoration-none fs-5 fw-semibold mb-4">
BitReport
<span className="d-block small text-white-50 fw-normal">Error reporting</span>
</Link>
<nav className="nav flex-column gap-1">
<Link className="nav-link text-white-50 er-nav-link" href="/">
Painel
</Link>
<Link className="nav-link text-white-50 er-nav-link" href="/incidents">
Incidentes
</Link>
</nav>
<div className="mt-auto small text-white-50 pt-4">
UI shell ·{" "}
<abbr title="Consistência visual com template Velzon (Bootstrap 5)">Velzon base</abbr>
</div>
</aside>
<div className="flex-grow-1 d-flex flex-column min-vw-0">
<header className="er-topbar border-bottom bg-body px-4 py-3 d-flex align-items-center justify-content-between">
<div>
<h1 className="h5 mb-1">{title}</h1>
{breadcrumb && breadcrumb.length > 0 ? (
<nav aria-label="breadcrumb">
<ol className="breadcrumb mb-0 small">
{breadcrumb.map((b, idx) => (
<li
key={`${b.label}-${idx}`}
className={`breadcrumb-item${b.href ? "" : " active"}`}
{...(!b.href ? { "aria-current": "page" } : {})}
>
{b.href ? <Link href={b.href}>{b.label}</Link> : b.label}
</li>
))}
</ol>
</nav>
) : null}
</div>
</header>
<main className="flex-grow-1 p-4 er-main">{children}</main>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
export function DataAlert({
variant,
title,
body,
}: {
variant: "warning" | "danger" | "info";
title: string;
body: string;
}) {
return (
<div className={`alert alert-${variant}`} role="status">
<strong className="d-block mb-1">{title}</strong>
{body}
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
"use client";
import { useEffect, useId, useState } from "react";
const _storageKey = (id: string) => `er-incident-notes:${id}`;
export function IncidentNotes({ incidentId }: { incidentId: string }) {
const _id = useId();
const [value, setValue] = useState("");
useEffect(() => {
if (typeof window === "undefined") {
return;
}
const _stored = window.sessionStorage.getItem(_storageKey(incidentId));
setValue(_stored ?? "");
}, [incidentId]);
useEffect(() => {
if (typeof window === "undefined") {
return;
}
window.sessionStorage.setItem(_storageKey(incidentId), value);
}, [incidentId, value]);
return (
<div>
<label className="form-label" htmlFor={_id}>
Notas do operador
</label>
<textarea
id={_id}
className="form-control font-monospace small"
rows={5}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Rascunho local (sessionStorage). A persistência no servidor chega com a API admin (BIT-179)."
/>
<p className="form-text mb-0">
Estas notas não são enviadas ao servidor nesta fase — apenas para acompanhamento na sessão do
browser.
</p>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
export function KpiCard({
label,
value,
variant,
}: {
label: string;
value: number;
variant: "primary" | "danger" | "warning" | "success" | "secondary" | "dark";
}) {
return (
<div className="col-sm-6 col-xl-3">
<div className={`card border-${variant} border-opacity-25 h-100`}>
<div className="card-body">
<p className="text-muted text-uppercase small mb-1">{label}</p>
<p className={`display-6 fw-semibold text-${variant} mb-0`}>{value}</p>
</div>
</div>
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { Severity } from "@/lib/types";
const _labels: Record<Severity, string> = {
critical: "Crítico",
high: "Alto",
medium: "Médio",
low: "Baixo",
info: "Info",
};
const _class: Record<Severity, string> = {
critical: "text-bg-dark",
high: "text-bg-danger",
medium: "text-bg-warning",
low: "text-bg-info",
info: "text-bg-light text-dark border",
};
export function SeverityBadge({ severity }: { severity: Severity }) {
return <span className={`badge ${_class[severity]}`}>{_labels[severity]}</span>;
}
+19
View File
@@ -0,0 +1,19 @@
import type { IncidentState } from "@/lib/types";
const _labels: Record<IncidentState, string> = {
open: "Aberto",
investigating: "Em investigação",
resolved: "Resolvido",
ignored: "Ignorado",
};
const _class: Record<IncidentState, string> = {
open: "text-bg-danger",
investigating: "text-bg-warning",
resolved: "text-bg-success",
ignored: "text-bg-secondary",
};
export function StateBadge({ state }: { state: IncidentState }) {
return <span className={`badge ${_class[state]}`}>{_labels[state]}</span>;
}
+14
View File
@@ -0,0 +1,14 @@
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [...compat.extends("next/core-web-vitals", "next/typescript")];
export default eslintConfig;
+123
View File
@@ -0,0 +1,123 @@
import type { IncidentDetail, IncidentSummary } from "./types";
/** Deterministic demo payloads for local UI review only (BIT-179 replaces with API). */
const _demoSummaries: IncidentSummary[] = [
{
id: "demo-1",
projectSlug: "wdmi-store",
fingerprint: "fp_checkout_timeout",
title: "Checkout API timeout after 30s",
severity: "high",
currentState: "open",
firstSeenAt: "2026-03-20T10:00:00.000Z",
lastSeenAt: "2026-03-22T03:12:44.000Z",
occurrencesCount: 142,
},
{
id: "demo-2",
projectSlug: "crm-wdmi",
fingerprint: "fp_null_sku",
title: "TypeError: Cannot read properties of undefined (reading 'sku')",
severity: "medium",
currentState: "investigating",
firstSeenAt: "2026-03-18T14:22:00.000Z",
lastSeenAt: "2026-03-21T18:01:02.000Z",
occurrencesCount: 38,
},
{
id: "demo-3",
projectSlug: "wdmi-store",
fingerprint: "fp_rate_limit",
title: "429 Too Many Requests on /api/v1/prices",
severity: "low",
currentState: "resolved",
firstSeenAt: "2026-03-10T08:00:00.000Z",
lastSeenAt: "2026-03-15T22:00:00.000Z",
occurrencesCount: 901,
},
{
id: "demo-4",
projectSlug: "legacy-ott",
fingerprint: "fp_deprecated_endpoint",
title: "Deprecated endpoint still called: /legacy/ping",
severity: "info",
currentState: "ignored",
firstSeenAt: "2026-01-05T12:00:00.000Z",
lastSeenAt: "2026-02-01T09:30:00.000Z",
occurrencesCount: 12,
},
];
const _stackSample = `TypeError: Cannot read properties of undefined (reading 'sku')
at mapLineItem (webpack-internal:///(api)/./src/cart.ts:42:17)
at Array.map (<anonymous>)
at POST (webpack-internal:///(api)/./src/routes/checkout.ts:118:22)`;
const _details: Record<string, IncidentDetail> = {
"demo-1": {
..._demoSummaries[0],
metadataJson: { route: "/checkout", release: "store-1.4.2" },
ingestKeyLabel: "production-web",
occurrences: [
{
id: "occ-1a",
occurredAt: "2026-03-22T03:12:44.000Z",
levelRaw: "error",
severity: "high",
message: "Upstream payment service did not respond within 30000ms",
stacktrace: null,
contextJson: { requestId: "req_9f2a", userAgent: "Mozilla/5.0 …" },
},
],
},
"demo-2": {
..._demoSummaries[1],
metadataJson: { module: "Ecommerce.Cart" },
ingestKeyLabel: "crm-php",
occurrences: [
{
id: "occ-2a",
occurredAt: "2026-03-21T18:01:02.000Z",
levelRaw: "error",
severity: "medium",
message: "TypeError: Cannot read properties of undefined (reading 'sku')",
stacktrace: _stackSample,
contextJson: { userId: 10294, cartId: "cart_88aa" },
},
],
},
"demo-3": {
..._demoSummaries[2],
metadataJson: { limit: 120, window: "1m" },
ingestKeyLabel: "store-bff",
occurrences: [
{
id: "occ-3a",
occurredAt: "2026-03-15T22:00:00.000Z",
levelRaw: "warn",
severity: "low",
message: "429 Too Many Requests",
stacktrace: null,
contextJson: { clientIp: "203.0.113.10" },
},
],
},
"demo-4": {
..._demoSummaries[3],
metadataJson: { owner: "platform" },
ingestKeyLabel: "ott-lb",
occurrences: [],
},
};
export function getDemoIncidentSummaries(): IncidentSummary[] {
return [..._demoSummaries];
}
export function getDemoIncidentDetail(id: string): IncidentDetail | null {
const _row = _details[id];
if (!_row) {
return null;
}
return { ..._row, occurrences: [..._row.occurrences] };
}
+14
View File
@@ -0,0 +1,14 @@
export function formatDateTime(iso: string): string {
try {
const _d = new Date(iso);
if (Number.isNaN(_d.getTime())) {
return iso;
}
return new Intl.DateTimeFormat("pt-PT", {
dateStyle: "short",
timeStyle: "medium",
}).format(_d);
} catch {
return iso;
}
}
+178
View File
@@ -0,0 +1,178 @@
import { getDemoIncidentDetail, getDemoIncidentSummaries } from "./demo-incidents";
import type { DetailResult, IncidentState, IncidentSummary, ListResult, Severity } from "./types";
function _isDemoEnabled(): boolean {
return process.env.ERROR_REPORTING_UI_DEMO === "1";
}
function _apiBase(): string | null {
const _raw = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
if (!_raw) {
return null;
}
return _raw.replace(/\/$/, "");
}
async function _fetchJson<T>(_path: string): Promise<T> {
const _base = _apiBase();
if (!_base) {
throw new Error("API base not configured");
}
const _url = `${_base}${_path.startsWith("/") ? _path : `/${_path}`}`;
const _res = await fetch(_url, {
next: { revalidate: 0 },
headers: { Accept: "application/json" },
});
if (!_res.ok) {
throw new Error(`HTTP ${_res.status}`);
}
return (await _res.json()) as T;
}
function _applyFilters(
rows: IncidentSummary[],
_params: { state?: IncidentState | ""; severity?: Severity | ""; q?: string; project?: string },
): IncidentSummary[] {
let _out = rows;
if (_params.state) {
_out = _out.filter((r) => r.currentState === _params.state);
}
if (_params.severity) {
_out = _out.filter((r) => r.severity === _params.severity);
}
if (_params.project?.trim()) {
const _slug = _params.project.trim().toLowerCase();
_out = _out.filter((r) => r.projectSlug.toLowerCase() === _slug);
}
if (_params.q?.trim()) {
const _q = _params.q.trim().toLowerCase();
_out = _out.filter(
(r) =>
r.title.toLowerCase().includes(_q) ||
r.fingerprint.toLowerCase().includes(_q) ||
r.projectSlug.toLowerCase().includes(_q),
);
}
return _out;
}
export async function fetchIncidentList(_params: {
state?: IncidentState | "";
severity?: Severity | "";
q?: string;
project?: string;
}): Promise<ListResult> {
const _base = _apiBase();
if (!_base) {
if (_isDemoEnabled()) {
const _rows = _applyFilters(getDemoIncidentSummaries(), {
state: _params.state,
severity: _params.severity,
q: _params.q,
project: _params.project,
});
return { ok: true, incidents: _rows, source: "demo" };
}
return {
ok: false,
error: "not_configured",
message:
"ERROR_REPORTING_ADMIN_API_BASE não está definido. Para pré-visualizar o layout, defina ERROR_REPORTING_UI_DEMO=1 (apenas desenvolvimento).",
};
}
try {
const _sp = new URLSearchParams();
if (_params.state) {
_sp.set("state", _params.state);
}
if (_params.severity) {
_sp.set("severity", _params.severity);
}
if (_params.project?.trim()) {
_sp.set("project", _params.project.trim());
}
if (_params.q?.trim()) {
_sp.set("q", _params.q.trim());
}
const _qs = _sp.toString();
const _path = `/v1/incidents${_qs ? `?${_qs}` : ""}`;
const _payload = await _fetchJson<{ incidents: IncidentSummary[] }>(_path);
return { ok: true, incidents: _payload.incidents ?? [], source: "api" };
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "fetch failed";
return {
ok: false,
error: "unreachable",
message: `Não foi possível contactar a API admin (${_msg}).`,
};
}
}
export async function fetchIncidentDetail(id: string): Promise<DetailResult> {
const _base = _apiBase();
if (!_base) {
if (_isDemoEnabled()) {
const _row = getDemoIncidentDetail(id);
if (!_row) {
return {
ok: false,
error: "not_found",
message: "Incidente não encontrado.",
};
}
return { ok: true, incident: _row, source: "demo" };
}
return {
ok: false,
error: "not_configured",
message:
"ERROR_REPORTING_ADMIN_API_BASE não está definido. Para pré-visualizar o layout, defina ERROR_REPORTING_UI_DEMO=1 (apenas desenvolvimento).",
};
}
try {
const _base = _apiBase();
if (!_base) {
throw new Error("unreachable");
}
const _url = `${_base}/v1/incidents/${encodeURIComponent(id)}`;
const _res = await fetch(_url, {
next: { revalidate: 0 },
headers: { Accept: "application/json" },
});
if (_res.status === 404) {
return {
ok: false,
error: "not_found",
message: "Incidente não encontrado.",
};
}
if (!_res.ok) {
throw new Error(`HTTP ${_res.status}`);
}
const _payload = (await _res.json()) as { incident: import("./types").IncidentDetail };
return { ok: true, incident: _payload.incident, source: "api" };
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "fetch failed";
return {
ok: false,
error: "unreachable",
message: `Não foi possível contactar a API admin (${_msg}).`,
};
}
}
export function computeKpis(incidents: IncidentSummary[]): Record<IncidentState | "total", number> {
const _acc: Record<IncidentState | "total", number> = {
total: incidents.length,
open: 0,
investigating: 0,
resolved: 0,
ignored: 0,
};
for (const _i of incidents) {
_acc[_i.currentState] += 1;
}
return _acc;
}
+47
View File
@@ -0,0 +1,47 @@
export type IncidentState =
| "open"
| "investigating"
| "resolved"
| "ignored";
export type Severity = "critical" | "high" | "medium" | "low" | "info";
export type IncidentSummary = {
id: string;
projectSlug: string;
fingerprint: string;
title: string;
severity: Severity;
currentState: IncidentState;
firstSeenAt: string;
lastSeenAt: string;
occurrencesCount: number;
};
export type IncidentOccurrence = {
id: string;
occurredAt: string;
levelRaw: string;
severity: Severity;
message: string;
stacktrace: string | null;
contextJson: Record<string, unknown> | null;
};
export type IncidentDetail = IncidentSummary & {
metadataJson: Record<string, unknown> | null;
ingestKeyLabel: string | null;
occurrences: IncidentOccurrence[];
};
export type ListResult =
| { ok: true; incidents: IncidentSummary[]; source: "api" | "demo" }
| { ok: false; error: "not_configured" | "unreachable"; message: string };
export type DetailResult =
| { ok: true; incident: IncidentDetail; source: "api" | "demo" }
| {
ok: false;
error: "not_configured" | "unreachable" | "not_found";
message: string;
};
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: true,
};
export default nextConfig;
+5847
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@bitreport/error-reporting-admin-ui",
"version": "0.1.0",
"private": true,
"description": "Velzon-style admin dashboard for BitReport error reporting (BIT-181)",
"scripts": {
"dev": "next dev --turbopack -p 3040",
"build": "next build",
"start": "next start -p 3040",
"lint": "next lint",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"bootstrap": "^5.3.3",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@types/node": "^22.9.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"eslint": "^9.15.0",
"eslint-config-next": "^15.1.0",
"sass": "^1.81.0",
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
+3842
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
node_modules/
dist/
+15
View File
@@ -0,0 +1,15 @@
FROM node:20-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
FROM node:20-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
CMD ["node", "dist/main.js"]
+12
View File
@@ -0,0 +1,12 @@
{
"events": [
{
"schema_version": 1,
"occurred_at": "2026-03-22T12:00:00.000Z",
"level": "error",
"message": "fixture: active collector polled this payload from docker-demo",
"fingerprint": "docker-demo-http-poll",
"context": { "origin": "fixture-poll", "collector": "BIT-180" }
}
]
}
+2160
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@bitreport/error-reporting-collector-worker",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Active polling collectors for BitReport error reporting (BIT-180)",
"scripts": {
"dev": "tsx watch src/main.ts",
"build": "tsc",
"start": "node dist/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"dotenv": "^16.4.5",
"pg": "^8.13.1"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
},
"engines": {
"node": ">=20"
}
}
@@ -0,0 +1,25 @@
import { afterEach, describe, expect, it } from "vitest";
import { resolveIngestToken } from "./resolveSecret.js";
describe("resolveIngestToken", () => {
afterEach(() => {
delete process.env.MY_TOKEN;
delete process.env.RAW_KEY;
delete process.env.COLLECTOR_DEFAULT_INGEST_TOKEN;
});
it("reads env: prefix", () => {
process.env.MY_TOKEN = "abc";
expect(resolveIngestToken("env:MY_TOKEN")).toBe("abc");
});
it("reads bare name as env key", () => {
process.env.RAW_KEY = "xyz";
expect(resolveIngestToken("RAW_KEY")).toBe("xyz");
});
it("uses COLLECTOR_DEFAULT_INGEST_TOKEN when ref empty", () => {
process.env.COLLECTOR_DEFAULT_INGEST_TOKEN = "fallback";
expect(resolveIngestToken(null)).toBe("fallback");
});
});
@@ -0,0 +1,33 @@
/**
* Resolves `auth_secret_ref` from er_collector_sources.
* - `env:VAR` or `ENV:VAR` → process.env.VAR
* - otherwise treat the whole string as an environment variable name
* - if null/empty, optional COLLECTOR_DEFAULT_INGEST_TOKEN for local demos
*/
export function resolveIngestToken(authSecretRef: string | null): string | null {
const _fallback = process.env.COLLECTOR_DEFAULT_INGEST_TOKEN;
if (authSecretRef === null || authSecretRef.trim() === "") {
if (typeof _fallback === "string" && _fallback.trim() !== "") {
return _fallback.trim();
}
return null;
}
const _ref = authSecretRef.trim();
const _envPrefix = /^env:/i.exec(_ref);
if (_envPrefix) {
const _key = _ref.slice(4).trim();
if (_key === "") {
return null;
}
const _v = process.env[_key];
if (typeof _v === "string" && _v.trim() !== "") {
return _v.trim();
}
return null;
}
const _v = process.env[_ref];
if (typeof _v === "string" && _v.trim() !== "") {
return _v.trim();
}
return null;
}
+42
View File
@@ -0,0 +1,42 @@
import "dotenv/config";
export type CollectorEnv = {
DATABASE_URL: string;
INGEST_BASE_URL: string;
HTTP_FETCH_TIMEOUT_MS: number;
TICK_INTERVAL_MS: number;
SOURCE_REFRESH_MS: number;
MAX_BACKOFF_EXPONENT: number;
NODE_ENV: string;
};
function _parseIntWithDefault(raw: string | undefined, fallback: number): number {
if (raw === undefined || raw.trim() === "") {
return fallback;
}
const _n = Number.parseInt(raw, 10);
if (!Number.isFinite(_n) || _n < 0) {
return fallback;
}
return _n;
}
export function loadEnv(): CollectorEnv {
const _databaseUrl = process.env.DATABASE_URL;
if (typeof _databaseUrl !== "string" || _databaseUrl.trim() === "") {
throw new Error("DATABASE_URL is required");
}
const _ingestBase = process.env.INGEST_BASE_URL;
if (typeof _ingestBase !== "string" || _ingestBase.trim() === "") {
throw new Error("INGEST_BASE_URL is required (e.g. http://ingest-api:3041)");
}
return {
DATABASE_URL: _databaseUrl.trim(),
INGEST_BASE_URL: _ingestBase.trim().replace(/\/$/, ""),
HTTP_FETCH_TIMEOUT_MS: _parseIntWithDefault(process.env.HTTP_FETCH_TIMEOUT_MS, 30_000),
TICK_INTERVAL_MS: _parseIntWithDefault(process.env.TICK_INTERVAL_MS, 2000),
SOURCE_REFRESH_MS: _parseIntWithDefault(process.env.SOURCE_REFRESH_MS, 10_000),
MAX_BACKOFF_EXPONENT: _parseIntWithDefault(process.env.MAX_BACKOFF_EXPONENT, 8),
NODE_ENV: process.env.NODE_ENV ?? "development",
};
}
@@ -0,0 +1,82 @@
import type { Pool, PoolClient } from "pg";
export async function insertRunStarted(
client: PoolClient,
input: { collectorSourceId: string; projectId: string },
): Promise<string> {
const _ins = await client.query<{ id: string }>(
`INSERT INTO er_collector_runs (
collector_source_id,
project_id,
triggered_by,
started_at,
status
) VALUES ($1::bigint, $2::bigint, 'scheduler', NOW(), 'running')
RETURNING id::text`,
[input.collectorSourceId, input.projectId],
);
const _id = _ins.rows[0]?.id;
if (!_id) {
throw new Error("collector_run_insert_failed");
}
return _id;
}
export async function finishRun(
client: PoolClient,
input: {
runId: string;
status: "success" | "failed" | "partial";
fetchedCount: number;
acceptedCount: number;
deduplicatedCount: number;
failedCount: number;
errorSummary: string | null;
},
): Promise<void> {
await client.query(
`UPDATE er_collector_runs
SET finished_at = NOW(),
status = $2,
fetched_count = $3,
accepted_count = $4,
deduplicated_count = $5,
failed_count = $6,
error_summary = $7
WHERE id = $1::bigint`,
[
input.runId,
input.status,
input.fetchedCount,
input.acceptedCount,
input.deduplicatedCount,
input.failedCount,
input.errorSummary,
],
);
}
export async function markSourceSuccess(pool: Pool, sourceId: string): Promise<void> {
await pool.query(
`UPDATE er_collector_sources
SET last_success_at = NOW(),
last_error_message = NULL,
updated_at = NOW()
WHERE id = $1::bigint`,
[sourceId],
);
}
export async function markSourceFailure(
pool: Pool,
input: { sourceId: string; message: string },
): Promise<void> {
await pool.query(
`UPDATE er_collector_sources
SET last_error_at = NOW(),
last_error_message = $2,
updated_at = NOW()
WHERE id = $1::bigint`,
[input.sourceId, input.message.slice(0, 4000)],
);
}
@@ -0,0 +1,33 @@
import type { Pool } from "pg";
import type { CollectorSourceRow } from "../types/ingest.js";
export async function loadActiveSources(pool: Pool): Promise<CollectorSourceRow[]> {
const _res = await pool.query<{
id: string;
project_id: string;
name: string;
source_type: string;
endpoint_uri: string;
auth_secret_ref: string | null;
poll_interval_seconds: string;
}>(
`SELECT id::text,
project_id::text,
name,
source_type,
endpoint_uri,
auth_secret_ref,
poll_interval_seconds::text
FROM er_collector_sources
WHERE is_active = TRUE`,
);
return _res.rows.map((row) => ({
id: row.id,
project_id: row.project_id,
name: row.name,
source_type: row.source_type,
endpoint_uri: row.endpoint_uri,
auth_secret_ref: row.auth_secret_ref,
poll_interval_seconds: Number.parseInt(row.poll_interval_seconds, 10),
}));
}
+38
View File
@@ -0,0 +1,38 @@
import type { IngestEventInput } from "../types/ingest.js";
export type PushIngestResult =
| { ok: true; status: number; accepted: number }
| { ok: false; status: number | null; error: string };
export async function pushEventsToIngest(input: {
ingestBaseUrl: string;
bearerToken: string;
events: IngestEventInput[];
}): Promise<PushIngestResult> {
if (input.events.length === 0) {
return { ok: true, status: 200, accepted: 0 };
}
const _url = `${input.ingestBaseUrl}/v1/ingest/events`;
try {
const _res = await fetch(_url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${input.bearerToken}`,
},
body: JSON.stringify({ events: input.events }),
});
if (!_res.ok) {
const _t = await _res.text();
return {
ok: false,
status: _res.status,
error: _t.slice(0, 500) || `http_${_res.status}`,
};
}
return { ok: true, status: _res.status, accepted: input.events.length };
} catch (_err) {
const _msg = _err instanceof Error ? _err.message : "ingest_post_failed";
return { ok: false, status: null, error: _msg };
}
}
+13
View File
@@ -0,0 +1,13 @@
export type LogRecord = Record<string, unknown> & { msg: string };
export function logInfo(record: LogRecord): void {
console.log(JSON.stringify({ level: "info", ts: new Date().toISOString(), ...record }));
}
export function logWarn(record: LogRecord): void {
console.warn(JSON.stringify({ level: "warn", ts: new Date().toISOString(), ...record }));
}
export function logError(record: LogRecord): void {
console.error(JSON.stringify({ level: "error", ts: new Date().toISOString(), ...record }));
}
+85
View File
@@ -0,0 +1,85 @@
import pg from "pg";
import { loadEnv } from "./config/loadEnv.js";
import { loadActiveSources } from "./db/loadActiveSources.js";
import { logError, logInfo } from "./log/structuredLog.js";
import { runHttpSourceOnce } from "./scheduler/runHttpSourceOnce.js";
import type { SourceRuntimeState } from "./scheduler/sourceState.js";
const _env = loadEnv();
const _pool = new pg.Pool({
connectionString: _env.DATABASE_URL,
max: 8,
idleTimeoutMillis: 30_000,
});
const _stateBySourceId = new Map<string, SourceRuntimeState>();
let _cachedSourcesAt = 0;
let _cachedSources = await loadActiveSources(_pool);
async function _refreshSourcesIfNeeded(): Promise<void> {
const _now = Date.now();
if (_now - _cachedSourcesAt < _env.SOURCE_REFRESH_MS) {
return;
}
_cachedSources = await loadActiveSources(_pool);
_cachedSourcesAt = _now;
const _active = new Set(_cachedSources.map((s) => s.id));
for (const _id of _stateBySourceId.keys()) {
if (!_active.has(_id)) {
_stateBySourceId.delete(_id);
}
}
}
async function _tick(): Promise<void> {
await _refreshSourcesIfNeeded();
const _now = Date.now();
for (const _source of _cachedSources) {
if (_source.source_type !== "http_poll") {
continue;
}
let _st = _stateBySourceId.get(_source.id);
if (!_st) {
_st = { consecutiveFailures: 0, nextAtMs: 0, inFlight: false };
_stateBySourceId.set(_source.id, _st);
}
if (_st.inFlight) {
continue;
}
if (_now < _st.nextAtMs) {
continue;
}
_st.inFlight = true;
void runHttpSourceOnce({ pool: _pool, env: _env, source: _source, state: _st }).finally(() => {
_st.inFlight = false;
});
}
}
logInfo({
msg: "collector_worker_started",
ingest_base_url: _env.INGEST_BASE_URL,
tick_interval_ms: _env.TICK_INTERVAL_MS,
});
const _interval = setInterval(() => {
void _tick().catch((_err) => {
const _msg = _err instanceof Error ? _err.message : "tick_failed";
logError({ msg: "collector_tick_failed", error: _msg });
});
}, _env.TICK_INTERVAL_MS);
void _tick();
const _shutdown = async () => {
clearInterval(_interval);
await _pool.end();
};
process.on("SIGINT", () => {
void _shutdown().then(() => process.exit(0));
});
process.on("SIGTERM", () => {
void _shutdown().then(() => process.exit(0));
});
@@ -0,0 +1,79 @@
import type { IngestEventInput } from "../types/ingest.js";
export type FetchHttpEventsResult =
| { ok: true; events: IngestEventInput[] }
| { ok: false; error: string };
function _isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function _isValidEvent(value: unknown): value is IngestEventInput {
if (!_isRecord(value)) {
return false;
}
if (value.schema_version !== 1) {
return false;
}
if (typeof value.occurred_at !== "string" || value.occurred_at.trim() === "") {
return false;
}
if (typeof value.level !== "string" || value.level.trim() === "") {
return false;
}
if (typeof value.message !== "string" || value.message.trim() === "") {
return false;
}
return true;
}
export async function fetchHttpPollEvents(input: {
endpointUri: string;
timeoutMs: number;
}): Promise<FetchHttpEventsResult> {
const _controller = new AbortController();
const _timer = setTimeout(() => _controller.abort(), input.timeoutMs);
try {
const _res = await fetch(input.endpointUri, {
method: "GET",
headers: { Accept: "application/json" },
signal: _controller.signal,
});
if (!_res.ok) {
return { ok: false, error: `http_status_${_res.status}` };
}
const _text = await _res.text();
let _json: unknown;
try {
_json = JSON.parse(_text) as unknown;
} catch {
return { ok: false, error: "invalid_json" };
}
if (!_isRecord(_json)) {
return { ok: false, error: "expected_json_object" };
}
const _eventsRaw = _json.events;
if (!Array.isArray(_eventsRaw)) {
return { ok: false, error: "missing_events_array" };
}
if (_eventsRaw.length > 50) {
return { ok: false, error: "too_many_events_max_50" };
}
const _events: IngestEventInput[] = [];
for (const _item of _eventsRaw) {
if (!_isValidEvent(_item)) {
return { ok: false, error: "invalid_event_shape" };
}
_events.push(_item);
}
return { ok: true, events: _events };
} catch (_err) {
if (_err instanceof Error && _err.name === "AbortError") {
return { ok: false, error: "fetch_timeout" };
}
const _msg = _err instanceof Error ? _err.message : "fetch_failed";
return { ok: false, error: _msg };
} finally {
clearTimeout(_timer);
}
}
@@ -0,0 +1,218 @@
import type { Pool } from "pg";
import { resolveIngestToken } from "../auth/resolveSecret.js";
import type { CollectorEnv } from "../config/loadEnv.js";
import {
finishRun,
insertRunStarted,
markSourceFailure,
markSourceSuccess,
} from "../db/collectorRunWriter.js";
import { fetchHttpPollEvents } from "../poll/fetchHttpEvents.js";
import { pushEventsToIngest } from "../ingest/pushEvents.js";
import { logError, logInfo } from "../log/structuredLog.js";
import { computeBackoffDelayMs, type SourceRuntimeState } from "./sourceState.js";
import type { CollectorSourceRow } from "../types/ingest.js";
export async function runHttpSourceOnce(input: {
pool: Pool;
env: CollectorEnv;
source: CollectorSourceRow;
state: SourceRuntimeState;
}): Promise<void> {
const { pool, env, source, state } = input;
const _baseMs = Math.max(source.poll_interval_seconds, 15) * 1000;
const _client = await pool.connect();
let _runId = "";
try {
await _client.query("BEGIN");
_runId = await insertRunStarted(_client, {
collectorSourceId: source.id,
projectId: source.project_id,
});
await _client.query("COMMIT");
} catch (_err) {
await _client.query("ROLLBACK");
_client.release();
const _msg = _err instanceof Error ? _err.message : "run_start_failed";
logError({
msg: "collector_run_start_failed",
source_id: source.id,
source_name: source.name,
error: _msg,
});
state.consecutiveFailures += 1;
state.nextAtMs = Date.now() + computeBackoffDelayMs({
baseIntervalMs: _baseMs,
consecutiveFailures: state.consecutiveFailures,
maxBackoffExponent: env.MAX_BACKOFF_EXPONENT,
});
await markSourceFailure(pool, { sourceId: source.id, message: _msg });
return;
}
_client.release();
const _fetched = await fetchHttpPollEvents({
endpointUri: source.endpoint_uri,
timeoutMs: env.HTTP_FETCH_TIMEOUT_MS,
});
if (!_fetched.ok) {
await _finishFailedRun(pool, _runId, {
fetched: 0,
accepted: 0,
failed: 1,
error: _fetched.error,
});
state.consecutiveFailures += 1;
state.nextAtMs = Date.now() + computeBackoffDelayMs({
baseIntervalMs: _baseMs,
consecutiveFailures: state.consecutiveFailures,
maxBackoffExponent: env.MAX_BACKOFF_EXPONENT,
});
await markSourceFailure(pool, { sourceId: source.id, message: _fetched.error });
logInfo({
msg: "collector_poll_failed",
source_id: source.id,
source_name: source.name,
error: _fetched.error,
consecutive_failures: state.consecutiveFailures,
next_delay_ms: state.nextAtMs - Date.now(),
});
return;
}
const _token = resolveIngestToken(source.auth_secret_ref);
if (_token === null) {
const _err = "missing_ingest_token";
await _finishFailedRun(pool, _runId, {
fetched: _fetched.events.length,
accepted: 0,
failed: 1,
error: _err,
});
state.consecutiveFailures += 1;
state.nextAtMs = Date.now() + computeBackoffDelayMs({
baseIntervalMs: _baseMs,
consecutiveFailures: state.consecutiveFailures,
maxBackoffExponent: env.MAX_BACKOFF_EXPONENT,
});
await markSourceFailure(pool, { sourceId: source.id, message: _err });
logError({
msg: "collector_missing_token",
source_id: source.id,
source_name: source.name,
});
return;
}
if (_fetched.events.length === 0) {
const _c2 = await pool.connect();
try {
await finishRun(_c2, {
runId: _runId,
status: "success",
fetchedCount: 0,
acceptedCount: 0,
deduplicatedCount: 0,
failedCount: 0,
errorSummary: null,
});
} finally {
_c2.release();
}
state.consecutiveFailures = 0;
state.nextAtMs = Date.now() + _baseMs;
await markSourceSuccess(pool, source.id);
logInfo({
msg: "collector_cycle_complete",
source_id: source.id,
source_name: source.name,
status: "success",
fetched_count: 0,
accepted_count: 0,
failed_count: 0,
});
return;
}
const _push = await pushEventsToIngest({
ingestBaseUrl: env.INGEST_BASE_URL,
bearerToken: _token,
events: _fetched.events,
});
if (!_push.ok) {
const _summary = _push.error;
await _finishFailedRun(pool, _runId, {
fetched: _fetched.events.length,
accepted: 0,
failed: _fetched.events.length,
error: _summary,
});
state.consecutiveFailures += 1;
state.nextAtMs = Date.now() + computeBackoffDelayMs({
baseIntervalMs: _baseMs,
consecutiveFailures: state.consecutiveFailures,
maxBackoffExponent: env.MAX_BACKOFF_EXPONENT,
});
await markSourceFailure(pool, { sourceId: source.id, message: _summary });
logInfo({
msg: "collector_ingest_failed",
source_id: source.id,
source_name: source.name,
http_status: _push.status,
error: _summary.slice(0, 200),
consecutive_failures: state.consecutiveFailures,
});
return;
}
const _c3 = await pool.connect();
try {
await finishRun(_c3, {
runId: _runId,
status: "success",
fetchedCount: _fetched.events.length,
acceptedCount: _push.accepted,
deduplicatedCount: 0,
failedCount: 0,
errorSummary: null,
});
} finally {
_c3.release();
}
state.consecutiveFailures = 0;
state.nextAtMs = Date.now() + _baseMs;
await markSourceSuccess(pool, source.id);
logInfo({
msg: "collector_cycle_complete",
source_id: source.id,
source_name: source.name,
status: "success",
fetched_count: _fetched.events.length,
accepted_count: _push.accepted,
failed_count: 0,
});
}
async function _finishFailedRun(
pool: Pool,
runId: string,
input: { fetched: number; accepted: number; failed: number; error: string },
): Promise<void> {
const _c = await pool.connect();
try {
await finishRun(_c, {
runId,
status: "failed",
fetchedCount: input.fetched,
acceptedCount: input.accepted,
deduplicatedCount: 0,
failedCount: input.failed,
errorSummary: input.error.slice(0, 4000),
});
} finally {
_c.release();
}
}
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { computeBackoffDelayMs } from "./sourceState.js";
describe("computeBackoffDelayMs", () => {
it("returns base when no failures", () => {
expect(
computeBackoffDelayMs({
baseIntervalMs: 30_000,
consecutiveFailures: 0,
maxBackoffExponent: 8,
}),
).toBe(30_000);
});
it("doubles per failure up to cap", () => {
expect(
computeBackoffDelayMs({
baseIntervalMs: 10_000,
consecutiveFailures: 2,
maxBackoffExponent: 8,
}),
).toBe(40_000);
});
it("respects max exponent", () => {
expect(
computeBackoffDelayMs({
baseIntervalMs: 1000,
consecutiveFailures: 100,
maxBackoffExponent: 3,
}),
).toBe(8000);
});
});
@@ -0,0 +1,20 @@
export type SourceRuntimeState = {
consecutiveFailures: number;
nextAtMs: number;
inFlight: boolean;
};
export function computeBackoffDelayMs(input: {
baseIntervalMs: number;
consecutiveFailures: number;
maxBackoffExponent: number;
}): number {
if (input.consecutiveFailures <= 0) {
return input.baseIntervalMs;
}
const _exp = Math.min(input.consecutiveFailures, input.maxBackoffExponent);
const _factor = 2 ** _exp;
const _raw = input.baseIntervalMs * _factor;
const _cap = 30 * 60 * 1000;
return Math.min(_raw, _cap);
}
+19
View File
@@ -0,0 +1,19 @@
export type IngestEventInput = {
schema_version: number;
occurred_at: string;
level: string;
message: string;
fingerprint?: string;
stacktrace?: string;
context?: Record<string, unknown>;
};
export type CollectorSourceRow = {
id: string;
project_id: string;
name: string;
source_type: string;
endpoint_uri: string;
auth_secret_ref: string | null;
poll_interval_seconds: number;
};
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": ["src/**/*.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
include: ["src/**/*.test.ts"],
},
});
+34
View File
@@ -0,0 +1,34 @@
# Error Reporting Database (BIT-178)
This folder contains the relational data model for the Error Reporting platform epic (`BIT-154`), implemented for task `BIT-178`.
Status and dependency:
- Stack baseline is defined by `docs/architecture/ADR-002-error-reporting-platform-phase1.md` (Fastify + PostgreSQL + Redis queue for phase 1).
- Schema changes must continue through versioned SQL migrations only (`up` + `down`), never ad hoc DDL.
## Migration layout
Migrations are versioned and reversible (`up` + `down`), timestamped, and idempotent:
1. `20260322043000_create_error_reporting_core.*`
2. `20260322044000_create_error_occurrences_and_states.*`
3. `20260322044500_add_ingest_idempotency.*`
4. `20260322045000_create_collectors_retention_and_audit.*`
## Apply manually (example)
```bash
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql
```
Rollback in reverse order with the matching `*.down.sql` files.
## Dev seed fixtures
For local integration tests:
- `seed/dev_two_projects.sql` creates two sample projects and ingest keys.
- `seed/dev_collector_http_fixture.sql` creates one demo HTTP polling source.
@@ -0,0 +1,12 @@
BEGIN;
DROP INDEX IF EXISTS er_incidents_project_severity_seen_idx;
DROP INDEX IF EXISTS er_incidents_project_state_seen_idx;
DROP TABLE IF EXISTS er_incidents;
DROP INDEX IF EXISTS er_ingest_keys_project_status_idx;
DROP TABLE IF EXISTS er_ingest_keys;
DROP TABLE IF EXISTS er_projects;
COMMIT;
@@ -0,0 +1,76 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_projects (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
slug VARCHAR(64) NOT NULL,
name VARCHAR(160) NOT NULL,
description TEXT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
timezone_name VARCHAR(64) NOT NULL DEFAULT 'UTC',
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_projects_slug_uniq UNIQUE (slug),
CONSTRAINT er_projects_slug_not_blank_chk CHECK (slug <> '')
);
CREATE TABLE IF NOT EXISTS er_ingest_keys (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL,
label VARCHAR(128) NOT NULL,
token_prefix CHAR(8) NOT NULL,
token_hash CHAR(64) NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'active',
last_used_at TIMESTAMP WITHOUT TIME ZONE NULL,
expires_at TIMESTAMP WITHOUT TIME ZONE NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
revoked_at TIMESTAMP WITHOUT TIME ZONE NULL,
CONSTRAINT er_ingest_keys_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_ingest_keys_project_label_uniq UNIQUE (project_id, label),
CONSTRAINT er_ingest_keys_token_hash_uniq UNIQUE (token_hash),
CONSTRAINT er_ingest_keys_token_prefix_not_blank_chk CHECK (token_prefix <> ''),
CONSTRAINT er_ingest_keys_status_chk CHECK (status IN ('active', 'disabled', 'revoked'))
);
CREATE INDEX IF NOT EXISTS er_ingest_keys_project_status_idx
ON er_ingest_keys (project_id, status);
CREATE TABLE IF NOT EXISTS er_incidents (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL,
fingerprint VARCHAR(128) NOT NULL,
title VARCHAR(300) NOT NULL,
severity VARCHAR(16) NOT NULL,
current_state VARCHAR(16) NOT NULL DEFAULT 'open',
first_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
last_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
occurrences_count BIGINT NOT NULL DEFAULT 1,
regression_count INTEGER NOT NULL DEFAULT 0,
last_ingest_key_id BIGINT NULL,
metadata_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_incidents_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incidents_last_ingest_key_fk FOREIGN KEY (last_ingest_key_id)
REFERENCES er_ingest_keys (id)
ON UPDATE CASCADE
ON DELETE SET NULL,
CONSTRAINT er_incidents_project_fingerprint_uniq UNIQUE (project_id, fingerprint),
CONSTRAINT er_incidents_occurrences_count_chk CHECK (occurrences_count >= 1),
CONSTRAINT er_incidents_regression_count_chk CHECK (regression_count >= 0),
CONSTRAINT er_incidents_severity_chk CHECK (severity IN ('critical', 'high', 'medium', 'low', 'info')),
CONSTRAINT er_incidents_state_chk CHECK (current_state IN ('open', 'investigating', 'resolved', 'ignored'))
);
CREATE INDEX IF NOT EXISTS er_incidents_project_state_seen_idx
ON er_incidents (project_id, current_state, last_seen_at DESC);
CREATE INDEX IF NOT EXISTS er_incidents_project_severity_seen_idx
ON er_incidents (project_id, severity, last_seen_at DESC);
COMMIT;
@@ -0,0 +1,18 @@
BEGIN;
DROP INDEX IF EXISTS er_incident_attachments_project_kind_time_idx;
DROP INDEX IF EXISTS er_incident_attachments_occurrence_idx;
DROP INDEX IF EXISTS er_incident_attachments_incident_time_idx;
DROP TABLE IF EXISTS er_incident_attachments;
DROP INDEX IF EXISTS er_incident_state_history_project_state_time_idx;
DROP INDEX IF EXISTS er_incident_state_history_incident_time_idx;
DROP TABLE IF EXISTS er_incident_state_history;
DROP INDEX IF EXISTS er_incident_occurrences_request_id_idx;
DROP INDEX IF EXISTS er_incident_occurrences_project_env_time_idx;
DROP INDEX IF EXISTS er_incident_occurrences_project_time_idx;
DROP INDEX IF EXISTS er_incident_occurrences_incident_time_idx;
DROP TABLE IF EXISTS er_incident_occurrences;
COMMIT;
@@ -0,0 +1,128 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_incident_occurrences (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
ingest_key_id BIGINT NULL,
occurred_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
level_raw VARCHAR(32) NOT NULL DEFAULT 'error',
severity VARCHAR(16) NOT NULL DEFAULT 'medium',
schema_version SMALLINT NOT NULL DEFAULT 1,
environment VARCHAR(32) NOT NULL DEFAULT 'production',
runtime_name VARCHAR(32) NULL,
runtime_version VARCHAR(32) NULL,
host_name VARCHAR(128) NULL,
release_version VARCHAR(64) NULL,
request_id VARCHAR(128) NULL,
message TEXT NOT NULL,
stack_trace TEXT NULL,
context_json TEXT NULL,
payload_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_incident_occurrences_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_occurrences_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_occurrences_ingest_key_fk FOREIGN KEY (ingest_key_id)
REFERENCES er_ingest_keys (id)
ON UPDATE CASCADE
ON DELETE SET NULL,
CONSTRAINT er_incident_occurrences_environment_not_blank_chk CHECK (environment <> ''),
CONSTRAINT er_incident_occurrences_severity_chk CHECK (
severity IN ('critical', 'high', 'medium', 'low', 'info')
),
CONSTRAINT er_incident_occurrences_schema_version_chk CHECK (schema_version >= 1)
);
CREATE INDEX IF NOT EXISTS er_incident_occurrences_incident_time_idx
ON er_incident_occurrences (incident_id, occurred_at DESC);
CREATE INDEX IF NOT EXISTS er_incident_occurrences_project_time_idx
ON er_incident_occurrences (project_id, occurred_at DESC);
CREATE INDEX IF NOT EXISTS er_incident_occurrences_project_env_time_idx
ON er_incident_occurrences (project_id, environment, occurred_at DESC);
CREATE INDEX IF NOT EXISTS er_incident_occurrences_request_id_idx
ON er_incident_occurrences (request_id);
CREATE TABLE IF NOT EXISTS er_incident_state_history (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
from_state VARCHAR(16) NULL,
to_state VARCHAR(16) NOT NULL,
changed_by_type VARCHAR(16) NOT NULL,
changed_by_ref VARCHAR(128) NOT NULL,
change_note TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_incident_state_history_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_state_history_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_state_history_from_state_chk CHECK (
from_state IS NULL OR from_state IN ('open', 'investigating', 'resolved', 'ignored')
),
CONSTRAINT er_incident_state_history_to_state_chk CHECK (
to_state IN ('open', 'investigating', 'resolved', 'ignored')
),
CONSTRAINT er_incident_state_history_changed_by_type_chk CHECK (
changed_by_type IN ('system', 'user', 'api_key', 'worker')
)
);
CREATE INDEX IF NOT EXISTS er_incident_state_history_incident_time_idx
ON er_incident_state_history (incident_id, created_at DESC);
CREATE INDEX IF NOT EXISTS er_incident_state_history_project_state_time_idx
ON er_incident_state_history (project_id, to_state, created_at DESC);
CREATE TABLE IF NOT EXISTS er_incident_attachments (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
occurrence_id BIGINT NOT NULL,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
attachment_kind VARCHAR(16) NOT NULL,
storage_uri VARCHAR(1024) NOT NULL,
content_type VARCHAR(128) NULL,
size_bytes BIGINT NOT NULL DEFAULT 0,
checksum_sha256 CHAR(64) NULL,
metadata_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_incident_attachments_occurrence_fk FOREIGN KEY (occurrence_id)
REFERENCES er_incident_occurrences (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_attachments_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_attachments_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_incident_attachments_kind_chk CHECK (
attachment_kind IN ('stack', 'payload', 'log', 'screenshot', 'link', 'file')
),
CONSTRAINT er_incident_attachments_size_bytes_chk CHECK (size_bytes >= 0)
);
CREATE INDEX IF NOT EXISTS er_incident_attachments_incident_time_idx
ON er_incident_attachments (incident_id, created_at DESC);
CREATE INDEX IF NOT EXISTS er_incident_attachments_occurrence_idx
ON er_incident_attachments (occurrence_id);
CREATE INDEX IF NOT EXISTS er_incident_attachments_project_kind_time_idx
ON er_incident_attachments (project_id, attachment_kind, created_at DESC);
COMMIT;
@@ -0,0 +1,7 @@
BEGIN;
DROP INDEX IF EXISTS er_ingest_idempotency_created_idx;
DROP INDEX IF EXISTS er_ingest_idempotency_project_created_idx;
DROP TABLE IF EXISTS er_ingest_idempotency;
COMMIT;
@@ -0,0 +1,42 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_ingest_idempotency (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
ingest_key_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
body_hash CHAR(64) NOT NULL,
incident_id BIGINT NOT NULL,
occurrence_id BIGINT NULL,
http_status SMALLINT NOT NULL DEFAULT 200,
response_json TEXT NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_ingest_idempotency_ingest_key_fk FOREIGN KEY (ingest_key_id)
REFERENCES er_ingest_keys (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_ingest_idempotency_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_ingest_idempotency_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_ingest_idempotency_occurrence_fk FOREIGN KEY (occurrence_id)
REFERENCES er_incident_occurrences (id)
ON UPDATE CASCADE
ON DELETE SET NULL,
CONSTRAINT er_ingest_idempotency_http_status_chk CHECK (
http_status BETWEEN 100 AND 599
),
CONSTRAINT er_ingest_idempotency_uniq UNIQUE (ingest_key_id, idempotency_key)
);
CREATE INDEX IF NOT EXISTS er_ingest_idempotency_project_created_idx
ON er_ingest_idempotency (project_id, created_at DESC);
CREATE INDEX IF NOT EXISTS er_ingest_idempotency_created_idx
ON er_ingest_idempotency (created_at);
COMMIT;
@@ -0,0 +1,18 @@
BEGIN;
DROP INDEX IF EXISTS er_audit_logs_request_id_idx;
DROP INDEX IF EXISTS er_audit_logs_project_entity_created_idx;
DROP INDEX IF EXISTS er_audit_logs_project_created_idx;
DROP TABLE IF EXISTS er_audit_logs;
DROP TABLE IF EXISTS er_retention_policies;
DROP INDEX IF EXISTS er_collector_runs_project_status_started_idx;
DROP INDEX IF EXISTS er_collector_runs_project_started_idx;
DROP INDEX IF EXISTS er_collector_runs_source_started_idx;
DROP TABLE IF EXISTS er_collector_runs;
DROP INDEX IF EXISTS er_collector_sources_project_active_idx;
DROP TABLE IF EXISTS er_collector_sources;
COMMIT;
@@ -0,0 +1,135 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_collector_sources (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL,
name VARCHAR(128) NOT NULL,
source_type VARCHAR(16) NOT NULL,
endpoint_uri VARCHAR(1024) NOT NULL,
auth_secret_ref VARCHAR(255) NULL,
poll_interval_seconds INTEGER NOT NULL DEFAULT 60,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
last_success_at TIMESTAMP WITHOUT TIME ZONE NULL,
last_error_at TIMESTAMP WITHOUT TIME ZONE NULL,
last_error_message TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_collector_sources_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_collector_sources_project_name_uniq UNIQUE (project_id, name),
CONSTRAINT er_collector_sources_source_type_chk CHECK (
source_type IN ('http_poll', 's3_poll', 'queue_pull', 'custom')
),
CONSTRAINT er_collector_sources_poll_interval_chk CHECK (poll_interval_seconds >= 15)
);
CREATE INDEX IF NOT EXISTS er_collector_sources_project_active_idx
ON er_collector_sources (project_id, is_active);
CREATE TABLE IF NOT EXISTS er_collector_runs (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
collector_source_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
triggered_by VARCHAR(16) NOT NULL,
started_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
finished_at TIMESTAMP WITHOUT TIME ZONE NULL,
status VARCHAR(16) NOT NULL,
fetched_count INTEGER NOT NULL DEFAULT 0,
accepted_count INTEGER NOT NULL DEFAULT 0,
deduplicated_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
error_summary TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_collector_runs_source_fk FOREIGN KEY (collector_source_id)
REFERENCES er_collector_sources (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_collector_runs_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_collector_runs_triggered_by_chk CHECK (
triggered_by IN ('scheduler', 'manual', 'retry')
),
CONSTRAINT er_collector_runs_status_chk CHECK (
status IN ('running', 'success', 'failed', 'partial')
),
CONSTRAINT er_collector_runs_fetched_count_chk CHECK (fetched_count >= 0),
CONSTRAINT er_collector_runs_accepted_count_chk CHECK (accepted_count >= 0),
CONSTRAINT er_collector_runs_deduplicated_count_chk CHECK (deduplicated_count >= 0),
CONSTRAINT er_collector_runs_failed_count_chk CHECK (failed_count >= 0)
);
CREATE INDEX IF NOT EXISTS er_collector_runs_source_started_idx
ON er_collector_runs (collector_source_id, started_at DESC);
CREATE INDEX IF NOT EXISTS er_collector_runs_project_started_idx
ON er_collector_runs (project_id, started_at DESC);
CREATE INDEX IF NOT EXISTS er_collector_runs_project_status_started_idx
ON er_collector_runs (project_id, status, started_at DESC);
CREATE TABLE IF NOT EXISTS er_retention_policies (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL,
keep_open_days INTEGER NOT NULL DEFAULT 90,
keep_resolved_days INTEGER NOT NULL DEFAULT 30,
keep_ignored_days INTEGER NOT NULL DEFAULT 7,
keep_attachments_days INTEGER NOT NULL DEFAULT 30,
keep_audit_days INTEGER NOT NULL DEFAULT 365,
delete_mode VARCHAR(16) NOT NULL DEFAULT 'soft',
updated_by_type VARCHAR(16) NOT NULL DEFAULT 'system',
updated_by_ref VARCHAR(128) NOT NULL DEFAULT 'bootstrap',
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_retention_policies_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_retention_policies_project_uniq UNIQUE (project_id),
CONSTRAINT er_retention_policies_keep_open_chk CHECK (keep_open_days >= 1),
CONSTRAINT er_retention_policies_keep_resolved_chk CHECK (keep_resolved_days >= 1),
CONSTRAINT er_retention_policies_keep_ignored_chk CHECK (keep_ignored_days >= 1),
CONSTRAINT er_retention_policies_keep_attachments_chk CHECK (keep_attachments_days >= 1),
CONSTRAINT er_retention_policies_keep_audit_chk CHECK (keep_audit_days >= 1),
CONSTRAINT er_retention_policies_delete_mode_chk CHECK (delete_mode IN ('soft', 'hard')),
CONSTRAINT er_retention_policies_updated_by_type_chk CHECK (updated_by_type IN ('system', 'user', 'api'))
);
CREATE TABLE IF NOT EXISTS er_audit_logs (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
project_id BIGINT NOT NULL,
actor_type VARCHAR(16) NOT NULL,
actor_ref VARCHAR(128) NOT NULL,
action VARCHAR(64) NOT NULL,
entity_type VARCHAR(32) NOT NULL,
entity_id VARCHAR(128) NOT NULL,
before_json TEXT NULL,
after_json TEXT NULL,
request_id VARCHAR(128) NULL,
ip_address VARCHAR(64) NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT er_audit_logs_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT er_audit_logs_actor_type_chk CHECK (
actor_type IN ('system', 'user', 'api_key', 'worker')
),
CONSTRAINT er_audit_logs_action_not_blank_chk CHECK (action <> ''),
CONSTRAINT er_audit_logs_entity_type_not_blank_chk CHECK (entity_type <> ''),
CONSTRAINT er_audit_logs_entity_id_not_blank_chk CHECK (entity_id <> '')
);
CREATE INDEX IF NOT EXISTS er_audit_logs_project_created_idx
ON er_audit_logs (project_id, created_at DESC);
CREATE INDEX IF NOT EXISTS er_audit_logs_project_entity_created_idx
ON er_audit_logs (project_id, entity_type, entity_id, created_at DESC);
CREATE INDEX IF NOT EXISTS er_audit_logs_request_id_idx
ON er_audit_logs (request_id);
COMMIT;
@@ -0,0 +1,26 @@
-- HTTP poll demo source for docker-compose (BIT-180). Depends on dev_two_projects.sql.
BEGIN;
INSERT INTO er_collector_sources (
project_id,
name,
source_type,
endpoint_uri,
auth_secret_ref,
poll_interval_seconds,
is_active
)
SELECT
p.id,
'docker-demo-http',
'http_poll',
'http://fixture-poll/errors.json',
'env:ER_COLLECTOR_PROJECT_ALPHA_TOKEN',
30,
TRUE
FROM er_projects p
WHERE p.slug = 'project-alpha'
ON CONFLICT (project_id, name) DO NOTHING;
COMMIT;
@@ -0,0 +1,24 @@
-- Dev fixtures: two projects + ingest keys (plaintext tokens documented for local tests only).
-- Token A: er_tst_a_secret_one
-- Token B: er_tst_b_secret_two
-- Apply after all error_reporting migrations.
BEGIN;
INSERT INTO er_projects (slug, name, description, is_active)
VALUES
('project-alpha', 'Project Alpha', 'Seed project A for passive ingest tests', TRUE),
('project-beta', 'Project Beta', 'Seed project B for passive ingest tests', TRUE)
ON CONFLICT (slug) DO NOTHING;
INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
SELECT p.id, 'default', 'tok_pr_a', '6b28a152af86ee5d2a30216c5c25e938c1b9bec58685a735b590c8cbaa005189', 'active'
FROM er_projects p WHERE p.slug = 'project-alpha'
ON CONFLICT (project_id, label) DO NOTHING;
INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
SELECT p.id, 'default', 'tok_pr_b', '63ca0b7048280893a98adb9e2a7333e431eb217d90b9470312b2f169ca736012', 'active'
FROM er_projects p WHERE p.slug = 'project-beta'
ON CONFLICT (project_id, label) DO NOTHING;
COMMIT;
+15
View File
@@ -0,0 +1,15 @@
# Native LXC deploy (no Docker)
Scripts and unit files for running **ingest-api**, **admin-ui**, and **collector-worker** on Debian/Ubuntu LXC with **PostgreSQL** on the same CT or another host.
Authoritative runbook: [`docs/deployment/bitreport-error-reporting-lxc-proxmox.md`](../../docs/deployment/bitreport-error-reporting-lxc-proxmox.md).
| Path | Purpose |
|------|---------|
| `env.example` | Template for `/etc/error-reporting/env` |
| `run-migrate.sh` | Apply migrations + seed (after Postgres is up) |
| `verify.sh` | `curl` ingest `/health` and optional checks |
| `systemd/*.service` | Unit files (adjust `WorkingDirectory` if not `/opt/errors.bitreport.pt`) |
| `nginx/*.conf.example` | TLS reverse proxy sketch |
Docker-based path remains in [`../../docker-compose.yml`](../../docker-compose.yml) and [`../../docs/deployment/bitreport-error-reporting-compose-proxmox.md`](../../docs/deployment/bitreport-error-reporting-compose-proxmox.md).
+32
View File
@@ -0,0 +1,32 @@
# Copy to /etc/error-reporting/env (mode 640, root:root or root:error-reporting).
# systemd parses this as EnvironmentFile= — use KEY=value only, no "export".
# --- Checkout root: this repository (contains database/, ingest-api/, admin-ui/, ...) ---
ER_REPO_ROOT=/opt/errors.bitreport.pt
# Legacy variable name (still read by run-migrate.sh if ER_REPO_ROOT is unset):
# OTT_ROOT=/opt/errors.bitreport.pt
# --- PostgreSQL (single LXC: localhost; split DB LXC: set host accordingly) ---
# URL-encode special characters in user/password per PostgreSQL libpq rules.
DATABASE_URL=postgres://postgres:[email protected]:5432/error_reporting
# --- ingest-api ---
PORT=3041
NODE_ENV=production
INGEST_RATE_LIMIT_MAX=300
INGEST_RATE_LIMIT_WINDOW_MS=60000
# --- collector-worker ---
INGEST_BASE_URL=http://127.0.0.1:3041
TICK_INTERVAL_MS=3000
SOURCE_REFRESH_MS=15000
HTTP_FETCH_TIMEOUT_MS=15000
MAX_BACKOFF_EXPONENT=8
# --- admin-ui (Next.js server-side API calls) ---
ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3041
# ERROR_REPORTING_UI_DEMO=1
# --- Demo / staging only: token must match seed SQL for project-alpha HTTP fixture ---
# ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one
# COLLECTOR_DEFAULT_INGEST_TOKEN=
@@ -0,0 +1,37 @@
# Example TLS reverse proxy on the Proxmox host or a dedicated proxy LXC.
# Replace hostnames and upstream ports (3041 = ingest-api, 3040 = admin-ui).
# Install: copy to /etc/nginx/sites-available/ and enable via symlink.
# --- Ingest API (clients, collectors) ---
server {
listen 443 ssl http2;
server_name er-ingest.example.com;
# ssl_certificate ...;
# ssl_certificate_key ...;
location / {
proxy_pass http://127.0.0.1:3041;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# --- Admin UI (operators) ---
server {
listen 443 ssl http2;
server_name er-admin.example.com;
# ssl_certificate ...;
# ssl_certificate_key ...;
location / {
proxy_pass http://127.0.0.1:3040;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Apply error_reporting SQL migrations and seeds (same order as docker-migrate.sh).
# Prerequisites: psql (postgresql-client), empty or already-migrated DB, DATABASE_URL + ER_REPO_ROOT (or legacy OTT_ROOT).
set -euo pipefail
_ENV_FILE="/etc/error-reporting/env"
if [[ -f "${_ENV_FILE}" ]]; then
set -a
# shellcheck disable=SC1090
source "${_ENV_FILE}"
set +a
fi
_REPO_ROOT="${ER_REPO_ROOT:-${OTT_ROOT:-}}"
: "${_REPO_ROOT:?Set ER_REPO_ROOT to this repository root (contains database/error_reporting/). Legacy OTT_ROOT is accepted.}"
: "${DATABASE_URL:?Set DATABASE_URL (postgres://...) for psql}"
_MIG="${_REPO_ROOT}/database/error_reporting/migrations"
_SEED="${_REPO_ROOT}/database/error_reporting/seed"
if [[ ! -d "${_MIG}" ]]; then
echo "run-migrate: migrations directory not found: ${_MIG}" >&2
exit 1
fi
_run_sql() {
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -f "$1"
}
_run_sql "${_MIG}/20260322043000_create_error_reporting_core.up.sql"
_run_sql "${_MIG}/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql "${_MIG}/20260322044500_add_ingest_idempotency.up.sql"
_run_sql "${_MIG}/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql "${_SEED}/dev_two_projects.sql"
_run_sql "${_SEED}/dev_collector_http_fixture.sql"
echo "run-migrate: complete"
@@ -0,0 +1,19 @@
[Unit]
Description=BitReport error reporting admin UI (Next.js)
After=network-online.target bitreport-error-reporting-ingest-api.service
Wants=network-online.target
[Service]
Type=simple
User=error-reporting
Group=error-reporting
EnvironmentFile=-/etc/error-reporting/env
WorkingDirectory=/opt/errors.bitreport.pt/admin-ui
ExecStart=/usr/bin/npm run start
Restart=on-failure
RestartSec=5
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,19 @@
[Unit]
Description=BitReport error reporting collector worker
After=network-online.target bitreport-error-reporting-ingest-api.service postgresql.service
Wants=network-online.target
[Service]
Type=simple
User=error-reporting
Group=error-reporting
EnvironmentFile=-/etc/error-reporting/env
WorkingDirectory=/opt/errors.bitreport.pt/collector-worker
ExecStart=/usr/bin/node dist/main.js
Restart=on-failure
RestartSec=5
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,19 @@
[Unit]
Description=BitReport error reporting ingest API (Fastify)
After=network-online.target postgresql.service
Wants=network-online.target
[Service]
Type=simple
User=error-reporting
Group=error-reporting
EnvironmentFile=-/etc/error-reporting/env
WorkingDirectory=/opt/errors.bitreport.pt/ingest-api
ExecStart=/usr/bin/node dist/server.js
Restart=on-failure
RestartSec=5
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Smoke checks after install: Postgres reachability (optional) + ingest /health.
set -euo pipefail
_ENV_FILE="/etc/error-reporting/env"
if [[ -f "${_ENV_FILE}" ]]; then
set -a
# shellcheck disable=SC1090
source "${_ENV_FILE}"
set +a
fi
_INGEST_URL="${INGEST_HEALTH_URL:-http://127.0.0.1:${PORT:-3041}/health}"
echo "verify: GET ${_INGEST_URL}"
if ! curl -sf "${_INGEST_URL}" >/dev/null; then
echo "verify: ingest /health failed" >&2
exit 1
fi
echo "verify: ingest OK"
if command -v pg_isready >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then
# pg_isready does not accept URI; probe TCP only when URL is simple localhost.
if [[ "${DATABASE_URL}" == *"@127.0.0.1:"* ]] || [[ "${DATABASE_URL}" == *"@localhost:"* ]]; then
echo "verify: pg_isready (best-effort, discrete vars may be needed on some hosts)"
_pgport="${PGPORT:-5432}"
pg_isready -h 127.0.0.1 -p "${_pgport}" || true
fi
fi
_ADMIN_PORT="${ADMIN_UI_PORT:-3040}"
if curl -sf "http://127.0.0.1:${_ADMIN_PORT}/" >/dev/null 2>&1; then
echo "verify: admin-ui HTTP on port ${_ADMIN_PORT} OK"
else
echo "verify: admin-ui not responding on ${_ADMIN_PORT} (expected if service stopped or demo mode off)"
fi
echo "verify: done"
+101
View File
@@ -0,0 +1,101 @@
# BitReport error reporting — reproducible stack: Postgres, migrate (one-shot), ingest API, collector worker.
# Prerequisites: Docker Engine + Compose v2.
#
# Quick start:
# cp .env.example .env
# docker compose up --build
#
# Verify: curl -sf http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health
#
# Docs: docs/deployment/bitreport-error-reporting-compose-proxmox.md
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: ${ER_POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${ER_POSTGRES_PASSWORD:-postgres}
POSTGRES_DB: ${ER_POSTGRES_DB:-error_reporting}
ports:
- "${ER_PUBLISH_PG_PORT:-5434}:5432"
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -U ${ER_POSTGRES_USER:-postgres} -d ${ER_POSTGRES_DB:-error_reporting}",
]
interval: 3s
timeout: 3s
retries: 15
migrate:
image: postgres:16-alpine
depends_on:
postgres:
condition: service_healthy
environment:
PGHOST: postgres
PGUSER: ${ER_POSTGRES_USER:-postgres}
PGPASSWORD: ${ER_POSTGRES_PASSWORD:-postgres}
PGDATABASE: ${ER_POSTGRES_DB:-error_reporting}
volumes:
- ./database/error_reporting/migrations:/migrations:ro
- ./database/error_reporting/seed:/seed:ro
- ./scripts/docker-migrate.sh:/docker-migrate.sh:ro
entrypoint: ["/bin/sh", "/docker-migrate.sh"]
fixture-poll:
image: nginx:alpine
volumes:
- ./collector-worker/fixture/errors.json:/usr/share/nginx/html/errors.json:ro
ingest-api:
build:
context: ./ingest-api
dockerfile: Dockerfile
depends_on:
migrate:
condition: service_completed_successfully
postgres:
condition: service_healthy
environment:
DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting}
PORT: "3041"
NODE_ENV: production
INGEST_RATE_LIMIT_MAX: ${INGEST_RATE_LIMIT_MAX:-300}
INGEST_RATE_LIMIT_WINDOW_MS: ${INGEST_RATE_LIMIT_WINDOW_MS:-60000}
ports:
- "${ER_PUBLISH_INGEST_PORT:-3041}:3041"
healthcheck:
test:
[
"CMD-SHELL",
"node -e \"fetch('http://127.0.0.1:3041/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\"",
]
interval: 5s
timeout: 5s
retries: 12
start_period: 20s
collector-worker:
build:
context: ./collector-worker
dockerfile: Dockerfile
depends_on:
migrate:
condition: service_completed_successfully
ingest-api:
condition: service_healthy
fixture-poll:
condition: service_started
environment:
DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting}
INGEST_BASE_URL: http://ingest-api:3041
TICK_INTERVAL_MS: ${TICK_INTERVAL_MS:-3000}
SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000}
HTTP_FETCH_TIMEOUT_MS: ${HTTP_FETCH_TIMEOUT_MS:-15000}
MAX_BACKOFF_EXPONENT: ${MAX_BACKOFF_EXPONENT:-8}
NODE_ENV: production
ER_COLLECTOR_PROJECT_ALPHA_TOKEN: ${ER_COLLECTOR_PROJECT_ALPHA_TOKEN:-er_tst_a_secret_one}
COLLECTOR_DEFAULT_INGEST_TOKEN: ${COLLECTOR_DEFAULT_INGEST_TOKEN:-}
restart: unless-stopped
@@ -0,0 +1,95 @@
# Error reporting — Docker Compose, Proxmox e exposição com TLS
**Deploy sem Docker (LXC nativo, systemd):** ver [`bitreport-error-reporting-lxc-proxmox.md`](./bitreport-error-reporting-lxc-proxmox.md) e [`deploy/lxc/`](../deploy/lxc/).
Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste repositório: **PostgreSQL**, **migrate** (one-shot), **ingest-api** (app), **collector-worker** (worker), mais **fixture-poll** para o cenário de demo com fonte HTTP local.
## Pré-requisitos
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
- Portas livres no host (por omissão): **5434** → Postgres, **3041** → ingest API. Ajustáveis em `.env` (`ER_PUBLISH_*`).
## Arranque reproduzível (qualquer ambiente)
```bash
cd /path/to/errors.bitreport.pt # raiz do clone (ver inventário em docs/ENVIRONMENTS.md)
cp .env.example .env
# Editar .env: definir palavras-passe fortes antes de produção
docker compose up --build -d
```
**Verificação mínima:**
```bash
curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health"
```
**Logs úteis:** `docker compose logs -f ingest-api collector-worker`
**Recriar BD do zero** (apaga volumes se existirem; em ambiente novo basta remover o container/volume do Postgres):
```bash
docker compose down -v
docker compose up --build
```
## Variáveis de ambiente (resumo)
| Variável | Onde | Descrição |
|----------|------|-----------|
| `ER_POSTGRES_USER` | postgres, migrate, apps | Utilizador da BD |
| `ER_POSTGRES_PASSWORD` | idem | Palavra-passe (evitar `@`, `:`, `/` na URL ou usar encoding na `DATABASE_URL` manual) |
| `ER_POSTGRES_DB` | idem | Nome da base |
| `ER_PUBLISH_PG_PORT` | postgres | Porta no host → 5432 no container |
| `ER_PUBLISH_INGEST_PORT` | ingest-api | Porta no host → API |
| `ER_COLLECTOR_PROJECT_ALPHA_TOKEN` | collector-worker | Token do projeto de demo (alinhado com seed SQL) |
| `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) |
| `INGEST_RATE_LIMIT_WINDOW_MS` | ingest-api | Janela em ms (opcional) |
| `TICK_INTERVAL_MS`, `SOURCE_REFRESH_MS`, `HTTP_FETCH_TIMEOUT_MS`, `MAX_BACKOFF_EXPONENT` | collector-worker | Intervalos e limites (opcional) |
| `COLLECTOR_DEFAULT_INGEST_TOKEN` | collector-worker | Fallback para referências `env:VAR` vazias (opcional) |
A `DATABASE_URL` usada nos containers é construída pelo Compose a partir de `ER_POSTGRES_*`. Palavras-passe com caracteres especiais na URL PostgreSQL devem ser [percent-encoded](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING).
## Proxmox (LXC ou VM)
1. **LXC com Docker:** ativar *nesting* no container (`features: nesting=1`) e instalar Docker como no Debian/Ubuntu oficial. Alternativa: VM com Docker — menos atrito com o kernel e cgroups.
2. **Recursos:** Postgres + Node para ingest + worker; para testes, 2 GB RAM e 2 vCPU costumam chegar; subir conforme carga.
3. **Armazenamento:** volume Docker ou bind mount em disco local rápido para `postgres` se quiseres persistência estável.
4. **Firewall (Proxmox / host):** em produção, **não** expor `ER_PUBLISH_PG_PORT` à Internet. Expor só o reverse proxy (80/443) ou VPN.
5. **Backups:** incluir volumes ou dumps (`pg_dump`) da base `ER_POSTGRES_DB`.
## Domínio externo, reverse proxy e TLS
A API escuta em HTTP dentro da rede Compose. Para um domínio público:
1. Manter `ingest-api` apenas na rede interna ou em `127.0.0.1` no host Proxmox.
2. Colocar **Caddy**, **nginx** ou **Traefik** no host (ou em container com rede partilhada) com TLS (Let’s Encrypt ou certificados internos).
3. Proxy só os paths necessários (ex.: tudo para `http://127.0.0.1:3041` ou o nome do serviço se o proxy estiver na mesma stack).
**Exemplo conceitual (nginx):**
```nginx
server {
listen 443 ssl;
server_name er-ingest.example.com;
# ssl_certificate / ssl_certificate_key ...
location / {
proxy_pass http://127.0.0.1:3041;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Ajustar `INGEST_RATE_LIMIT_*` se o tráfego passar por um único IP de proxy (pode ser preciso confiar em `X-Forwarded-For` na aplicação numa evolução futura).
## Produção — checklist rápido
- [ ] `ER_POSTGRES_PASSWORD` e tokens de projeto fortes e únicos.
- [ ] Postgres não publicado na Internet.
- [ ] TLS terminado no proxy; redirecionamento HTTP → HTTPS.
- [ ] `restart: unless-stopped` já no worker; política de restart para `ingest-api` alinhada com o vosso orchestrator.
- [ ] Logs centralizados e alertas para falhas de healthcheck.
@@ -0,0 +1,173 @@
# Error reporting — LXC Proxmox (sem Docker)
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **PostgreSQL**, **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml).
## Redis
A versão actual da plataforma (**ingest-api**, **collector-worker**, **admin-ui**) **não usa Redis**. Não é necessário instalar `redis-server` neste LXC. Se uma release futura passar a exigir filas/cache, seguir a convenção dos outros CT (Redis no mesmo LXC ou CT dedicado) e actualizar este documento.
## Arquitectura recomendada
| Opção | Quando usar |
|-------|-------------|
| **Tudo num CT** | Staging, MVP, baixo tráfego: PostgreSQL + apps no mesmo LXC. |
| **PostgreSQL noutro CT** | Produção alinhada com padrão “DB dedicado”: definir `DATABASE_URL` com hostname interno do CT da base. |
**Recursos de partida:** 2 GB RAM, 2 vCPU (subir com carga). Disco rápido para PostgreSQL (`/var/lib/postgresql`).
**Rede:** não expor a porta PostgreSQL à Internet; apenas 80/443 (proxy) ou VPN.
## 1. Proxmox — criar o LXC
1. Template **Debian 12** ou **Ubuntu 24.04** (mesma linha que os outros serviços).
2. Sem necessidade de **nesting** (não há Docker).
3. Activar backup do CT e incluir volumes de dados PostgreSQL nos backups ou `pg_dump` agendado.
## 2. Pacotes base e Node.js 20
No CT (como root):
```bash
apt-get update
apt-get install -y curl ca-certificates git postgresql postgresql-client nginx
# Node.js 20 LTS (exemplo NodeSource — confirmar URL actual em https://github.com/nodesource/distributions)
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
node -v # v20.x
```
## 3. PostgreSQL
Criar utilizador e base (ajustar palavras-passe):
```bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
CREATE USER er_app WITH PASSWORD 'CHANGE_ME_STRONG';
CREATE DATABASE error_reporting OWNER er_app;
GRANT ALL PRIVILEGES ON DATABASE error_reporting TO er_app;
SQL
```
Construir `DATABASE_URL` (codificar caracteres especiais na password se necessário):
`postgres://er_app:[email protected]:5432/error_reporting`
## 4. Código no CT
Convém um clone do repositório **`errors.bitreport.pt`** (Gitea: `BitReport.pt/errors.bitreport.pt.git`). Exemplo:
```bash
install -d -o root -g root -m 0755 /opt
git clone https://git.bitreport.pt/BitReport.pt/errors.bitreport.pt.git /opt/errors.bitreport.pt
```
Ajustar `ER_REPO_ROOT` no ficheiro de env (abaixo) se o caminho for outro.
## 5. Utilizador de serviço e permissões
```bash
useradd --system --home /opt/errors.bitreport.pt --shell /usr/sbin/nologin error-reporting
chown -R error-reporting:error-reporting /opt/errors.bitreport.pt
```
O utilizador precisa de leitura em `database/error_reporting/` apenas para **correr migrações** (normalmente como root ou postgres com script); em runtime as apps só precisam de `ingest-api`, `admin-ui`, `collector-worker`.
## 6. Ficheiro de ambiente
```bash
install -d -m 0755 /etc/error-reporting
cp /opt/errors.bitreport.pt/deploy/lxc/env.example /etc/error-reporting/env
chmod 640 /etc/error-reporting/env
chown root:error-reporting /etc/error-reporting/env
nano /etc/error-reporting/env # DATABASE_URL, ER_REPO_ROOT, tokens
```
Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL`, `INGEST_BASE_URL` (normalmente `http://127.0.0.1:3041`), `ERROR_REPORTING_ADMIN_API_BASE` (URL que o **Next.js** usa no servidor para falar com a API — em CT único, `http://127.0.0.1:3041`).
## 7. Dependências Node e build
```bash
cd /opt/errors.bitreport.pt/ingest-api && npm ci && npm run build
cd /opt/errors.bitreport.pt/admin-ui && npm ci && npm run build
cd /opt/errors.bitreport.pt/collector-worker && npm ci && npm run build
chown -R error-reporting:error-reporting /opt/errors.bitreport.pt
```
## 8. Migrações e seed
```bash
set -a
source /etc/error-reporting/env
set +a
sudo -E /opt/errors.bitreport.pt/deploy/lxc/run-migrate.sh
```
**Produção:** rever se o seed de desenvolvimento (`dev_two_projects.sql`, fixture HTTP) é aceitável; caso contrário aplicar apenas migrações e dados operacionais via processo aprovado.
## 9. systemd
```bash
cp /opt/errors.bitreport.pt/deploy/lxc/systemd/bitreport-error-reporting-*.service /etc/systemd/system/
```
Se o checkout **não** estiver em `/opt/errors.bitreport.pt`, criar *drop-ins* ou editar `WorkingDirectory=` e caminhos em cada unit.
Ordem de arranque sugerida:
```bash
systemctl daemon-reload
systemctl enable --now bitreport-error-reporting-ingest-api.service
systemctl enable --now bitreport-error-reporting-admin-ui.service
systemctl enable --now bitreport-error-reporting-collector-worker.service
```
O **collector-worker** exige `INGEST_BASE_URL` a apontar para a API já acessível; depende de `ingest-api` em `After=` (reinícios: `Restart=on-failure`).
## 10. Verificação
```bash
/opt/errors.bitreport.pt/deploy/lxc/verify.sh
curl -sf http://127.0.0.1:3041/health
```
Critério de aceitação: **`/health` da ingest-api responde HTTP 200**.
```bash
systemctl status bitreport-error-reporting-ingest-api.service
journalctl -u bitreport-error-reporting-ingest-api.service -f
```
## 11. Fixture HTTP de demo (opcional)
No Compose, o worker usa um contentor nginx com `collector-worker/fixture/errors.json`. Em LXC nativo, para reproduzir o cenário de poll HTTP:
- Servir esse ficheiro com nginx ou `python3 -m http.server` numa porta interna;
- Garantir que a URL configurada na base bate certo com essa origem.
Em produção típica as fontes são URLs reais; este passo pode ignorar-se.
## 12. Reverse proxy e TLS
Colocar **nginx** (no host Proxmox, CT de proxy, ou o mesmo CT se política o permitir) a terminar TLS e a encaminhar para `127.0.0.1:3041` (ingest) e `127.0.0.1:3040` (admin). Ver exemplo em [`deploy/lxc/nginx/bitreport-error-reporting.site.conf.example`](../deploy/lxc/nginx/bitreport-error-reporting.site.conf.example).
## 13. Checklist rápido (produção)
- [ ] Palavras-passe e tokens fortes; `chmod 640` em `/etc/error-reporting/env`.
- [ ] PostgreSQL só na rede interna / localhost.
- [ ] TLS no proxy; redireccionamento HTTP → HTTPS.
- [ ] Logs (`journalctl`) e alertas para falhas de arranque.
- [ ] Backups testados (BD + env cifrado na vault, não no Git).
## Referência de artefactos
| Artefacto | Caminho no repo |
|-----------|-----------------|
| Env exemplo | `deploy/lxc/env.example` |
| Migrações + seed | `deploy/lxc/run-migrate.sh` |
| Smoke test | `deploy/lxc/verify.sh` |
| Units systemd | `deploy/lxc/systemd/` |
| Nginx exemplo | `deploy/lxc/nginx/` |
+4
View File
@@ -0,0 +1,4 @@
PORT=3041
DATABASE_URL=postgres://postgres:[email protected]:5432/error_reporting
INGEST_RATE_LIMIT_MAX=300
INGEST_RATE_LIMIT_WINDOW_MS=60000
+4
View File
@@ -0,0 +1,4 @@
node_modules/
dist/
.env
*.log
+16
View File
@@ -0,0 +1,16 @@
FROM node:20-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
FROM node:20-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
EXPOSE 3041
CMD ["node", "dist/server.js"]
+3373
View File
File diff suppressed because it is too large. Load diff
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@bitreport/error-reporting-ingest-api",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Passive HTTP ingest for BitReport central error reporting (BIT-154.3)",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@fastify/rate-limit": "^9.1.0",
"@fastify/swagger": "^8.15.0",
"@fastify/swagger-ui": "^3.1.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"pg": "^8.13.1"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
},
"engines": {
"node": ">=20"
}
}
+231
View File
@@ -0,0 +1,231 @@
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 rateLimit from "@fastify/rate-limit";
import type { Pool } from "pg";
import type { IngestEnv } from "./config/env.js";
import { sha256Hex } from "./lib/hash.js";
import { attachIngestAuth } from "./services/ingestAuth.js";
import {
computeRequestBodyHash,
processIngestBatch,
type IngestEventInput,
} from "./services/processIngestBatch.js";
const _ingestEventSchema = {
type: "object",
additionalProperties: false,
required: ["schema_version", "occurred_at", "level", "message"],
properties: {
schema_version: { type: "integer", minimum: 1, maximum: 1 },
occurred_at: { type: "string", minLength: 1, maxLength: 64 },
level: { type: "string", minLength: 1, maxLength: 32 },
message: { type: "string", minLength: 1, maxLength: 20000 },
fingerprint: { type: "string", minLength: 1, maxLength: 128 },
stacktrace: { type: "string", minLength: 1, maxLength: 500000 },
context: { type: "object", additionalProperties: true },
},
} as const;
const _ingestBodySchema = {
type: "object",
additionalProperties: false,
required: ["events"],
properties: {
events: {
type: "array",
minItems: 1,
maxItems: 50,
items: _ingestEventSchema,
},
},
} as const;
function _rateLimitKey(request: { headers: Record<string, unknown>; ip: string }): string {
const _auth = request.headers.authorization;
const _ak = request.headers["x-api-key"];
if (typeof _auth === "string" && _auth.trim() !== "") {
return `hdr:${sha256Hex(_auth)}`;
}
if (typeof _ak === "string" && _ak.trim() !== "") {
return `hdr:${sha256Hex(`x-api-key:${_ak}`)}`;
}
return `ip:${request.ip}`;
}
export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<FastifyInstance> {
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 },
});
_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) => {
await ingestScope.register(rateLimit, {
max: input.env.INGEST_RATE_LIMIT_MAX,
timeWindow: input.env.INGEST_RATE_LIMIT_WINDOW_MS,
keyGenerator: _rateLimitKey,
});
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: _ingestBodySchema,
response: {
200: {
type: "object",
properties: {
results: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
incident_id: { type: "string" },
occurrence_id: { type: "string" },
fingerprint: { type: "string" },
},
required: ["incident_id", "occurrence_id", "fingerprint"],
},
},
},
required: ["results"],
},
401: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
409: {
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);
},
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 {
const _out = await processIngestBatch({
pool: input.pool,
ingestKeyId: request.ingestAuth.keyId,
projectId: request.ingestAuth.projectId,
events: _body.events,
idempotencyKey: _idempotencyKey,
bodyHash: _bodyHash,
});
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.",
});
}
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;
}
+34
View File
@@ -0,0 +1,34 @@
import "dotenv/config";
export type IngestEnv = {
PORT: number;
DATABASE_URL: string;
INGEST_RATE_LIMIT_MAX: number;
INGEST_RATE_LIMIT_WINDOW_MS: number;
NODE_ENV: string;
};
function _parseIntWithDefault(raw: string | undefined, fallback: number): number {
if (raw === undefined || raw.trim() === "") {
return fallback;
}
const _n = Number.parseInt(raw, 10);
if (!Number.isFinite(_n) || _n < 0) {
return fallback;
}
return _n;
}
export function loadEnv(): IngestEnv {
const _databaseUrl = process.env.DATABASE_URL;
if (typeof _databaseUrl !== "string" || _databaseUrl.trim() === "") {
throw new Error("DATABASE_URL is required");
}
return {
PORT: _parseIntWithDefault(process.env.PORT, 3041),
DATABASE_URL: _databaseUrl.trim(),
INGEST_RATE_LIMIT_MAX: _parseIntWithDefault(process.env.INGEST_RATE_LIMIT_MAX, 300),
INGEST_RATE_LIMIT_WINDOW_MS: _parseIntWithDefault(process.env.INGEST_RATE_LIMIT_WINDOW_MS, 60_000),
NODE_ENV: process.env.NODE_ENV ?? "development",
};
}
@@ -0,0 +1,194 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import pg from "pg";
import { buildApp } from "./buildApp.js";
import type { IngestEnv } from "./config/env.js";
import { sha256Hex } from "./lib/hash.js";
const _testUrl = process.env.ERROR_REPORTING_TEST_DATABASE_URL;
describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
let _pool: pg.Pool;
let _app: Awaited<ReturnType<typeof buildApp>>;
const _tokenA = "er_tst_a_secret_one";
const _tokenB = "er_tst_b_secret_two";
let _projectIdA = "";
let _projectIdB = "";
beforeAll(async () => {
_pool = new pg.Pool({ connectionString: _testUrl, max: 4 });
await _pool.query(`
TRUNCATE TABLE
er_ingest_idempotency,
er_occurrence_events,
er_incidents,
er_ingest_keys,
er_projects
RESTART IDENTITY CASCADE
`);
const _p = await _pool.query<{ id: string }>(
`INSERT INTO er_projects (slug, name) VALUES ('pa', 'Project A'), ('pb', 'Project B')
RETURNING id::text`,
);
const _rows = _p.rows;
if (_rows.length < 2) {
throw new Error("seed projects failed");
}
_projectIdA = _rows[0]?.id ?? "";
_projectIdB = _rows[1]?.id ?? "";
await _pool.query(
`INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
VALUES ($1::bigint, 'default', 'tok_pr_a', $2, 'active'),
($3::bigint, 'default', 'tok_pr_b', $4, 'active')`,
[_projectIdA, sha256Hex(_tokenA), _projectIdB, sha256Hex(_tokenB)],
);
const _env: IngestEnv = {
PORT: 0,
DATABASE_URL: _testUrl!,
INGEST_RATE_LIMIT_MAX: 10_000,
INGEST_RATE_LIMIT_WINDOW_MS: 60_000,
NODE_ENV: "test",
};
_app = await buildApp({ env: _env, pool: _pool });
await _app.ready();
});
afterAll(async () => {
await _app.close();
await _pool.end();
});
it("ingests distinct events for project A and B with separate keys", async () => {
const _resA = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: { authorization: `Bearer ${_tokenA}` },
payload: {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T10:00:00.000Z",
level: "error",
message: "failure from project A",
fingerprint: "fp-a-1",
},
],
},
});
expect(_resA.statusCode).toBe(200);
const _bodyA = JSON.parse(_resA.body) as {
results: Array<{ incident_id: string; fingerprint: string }>;
};
expect(_bodyA.results).toHaveLength(1);
expect(_bodyA.results[0]?.fingerprint).toBe("fp-a-1");
const _resB = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: { "x-api-key": _tokenB },
payload: {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T10:00:01.000Z",
level: "warn",
message: "warning from project B",
fingerprint: "fp-b-1",
},
],
},
});
expect(_resB.statusCode).toBe(200);
const _bodyB = JSON.parse(_resB.body) as {
results: Array<{ incident_id: string; fingerprint: string }>;
};
expect(_bodyB.results[0]?.fingerprint).toBe("fp-b-1");
expect(_bodyB.results[0]?.incident_id).not.toBe(_bodyA.results[0]?.incident_id);
const _check = await _pool.query<{ c: string }>(
`SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`,
[_projectIdA],
);
expect(_check.rows[0]?.c).toBe("1");
const _checkB = await _pool.query<{ c: string }>(
`SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`,
[_projectIdB],
);
expect(_checkB.rows[0]?.c).toBe("1");
});
it("replays identical idempotent requests", async () => {
const _payload = {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T11:00:00.000Z",
level: "info",
message: "idempotent row",
fingerprint: "fp-idem-1",
},
],
};
const _headers = {
authorization: `Bearer ${_tokenA}`,
"idempotency-key": "idem-key-1",
};
const _first = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: _payload,
});
expect(_first.statusCode).toBe(200);
const _second = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: _payload,
});
expect(_second.statusCode).toBe(200);
expect(_second.body).toBe(_first.body);
const _occ = await _pool.query(`SELECT COUNT(*)::int AS c FROM er_occurrence_events`);
expect(_occ.rows[0]?.c).toBe(3);
});
it("returns 409 when idempotency key is reused with a different body", async () => {
const _headers = {
authorization: `Bearer ${_tokenA}`,
"idempotency-key": "idem-key-2",
};
const _r1 = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T12:00:00.000Z",
level: "error",
message: "first",
fingerprint: "fp-conflict-a",
},
],
},
});
expect(_r1.statusCode).toBe(200);
const _r2 = await _app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T12:00:00.000Z",
level: "error",
message: "second different",
fingerprint: "fp-conflict-b",
},
],
},
});
expect(_r2.statusCode).toBe(409);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { createHash } from "node:crypto";
export function sha256Hex(input: string): string {
return createHash("sha256").update(input, "utf8").digest("hex");
}
export function stableJsonHash(value: unknown): string {
return sha256Hex(JSON.stringify(canonicalizeJson(value)));
}
function canonicalizeJson(value: unknown): unknown {
if (value === null || typeof value !== "object") {
return value;
}
if (Array.isArray(value)) {
return value.map((item) => canonicalizeJson(item));
}
const _obj = value as Record<string, unknown>;
const _keys = Object.keys(_obj).sort();
const _out: Record<string, unknown> = {};
for (const _k of _keys) {
_out[_k] = canonicalizeJson(_obj[_k]);
}
return _out;
}
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import {
computeFingerprint,
incidentTitleFromMessage,
normalizeLevelToSeverity,
parseOccurredAt,
} from "./normalize.js";
describe("normalizeLevelToSeverity", () => {
it("maps common levels", () => {
expect(normalizeLevelToSeverity("error")).toBe("high");
expect(normalizeLevelToSeverity("warn")).toBe("medium");
expect(normalizeLevelToSeverity("info")).toBe("info");
expect(normalizeLevelToSeverity("debug")).toBe("low");
expect(normalizeLevelToSeverity("fatal")).toBe("critical");
});
});
describe("computeFingerprint", () => {
it("uses client fingerprint when provided", () => {
expect(
computeFingerprint({
clientFingerprint: "my-fp",
message: "x",
}),
).toBe("my-fp");
});
it("hashes when fingerprint missing", () => {
const _a = computeFingerprint({ message: "same" });
const _b = computeFingerprint({ message: "same" });
expect(_a).toBe(_b);
expect(_a.length).toBeLessThanOrEqual(128);
});
});
describe("incidentTitleFromMessage", () => {
it("takes first line and truncates", () => {
expect(incidentTitleFromMessage("one\ntwo")).toBe("one");
const _long = "x".repeat(400);
expect(incidentTitleFromMessage(_long).length).toBe(300);
});
});
describe("parseOccurredAt", () => {
it("accepts ISO strings", () => {
const _ms = parseOccurredAt("2026-03-22T04:00:00.000Z");
expect(_ms).toBe(Date.parse("2026-03-22T04:00:00.000Z"));
});
it("rejects invalid", () => {
expect(() => parseOccurredAt("not-a-date")).toThrow("invalid_occurred_at");
});
});
+53
View File
@@ -0,0 +1,53 @@
import { sha256Hex } from "./hash.js";
export function normalizeLevelToSeverity(level: string): string {
const _l = level.trim().toLowerCase();
if (_l === "fatal" || _l === "critical") {
return "critical";
}
if (_l === "error") {
return "high";
}
if (_l === "warn" || _l === "warning") {
return "medium";
}
if (_l === "info") {
return "info";
}
if (_l === "debug" || _l === "trace") {
return "low";
}
return "high";
}
export function computeFingerprint(input: {
clientFingerprint?: string;
message: string;
stacktrace?: string;
}): string {
if (typeof input.clientFingerprint === "string") {
const _fp = input.clientFingerprint.trim().slice(0, 128);
if (_fp.length > 0) {
return _fp;
}
}
const _basis = `${input.message}\n${input.stacktrace ?? ""}`;
return sha256Hex(_basis).slice(0, 128);
}
export function incidentTitleFromMessage(message: string): string {
const _line = message.split(/\r?\n/)[0] ?? message;
const _trimmed = _line.trim();
if (_trimmed.length <= 300) {
return _trimmed;
}
return `${_trimmed.slice(0, 297)}...`;
}
export function parseOccurredAt(iso: string): number {
const _d = Date.parse(iso);
if (!Number.isFinite(_d)) {
throw new Error("invalid_occurred_at");
}
return _d;
}
+27
View File
@@ -0,0 +1,27 @@
import pg from "pg";
import { loadEnv } from "./config/env.js";
import { buildApp } from "./buildApp.js";
const _env = loadEnv();
const _pool = new pg.Pool({
connectionString: _env.DATABASE_URL,
max: 16,
idleTimeoutMillis: 30_000,
});
const _app = await buildApp({ env: _env, pool: _pool });
const _close = async () => {
await _app.close();
await _pool.end();
};
process.on("SIGINT", () => {
void _close().then(() => process.exit(0));
});
process.on("SIGTERM", () => {
void _close().then(() => process.exit(0));
});
await _app.listen({ port: _env.PORT, host: "0.0.0.0" });
_app.log.info(`ingest-api listening on ${_env.PORT}`);
+69
View File
@@ -0,0 +1,69 @@
import type { Pool } from "pg";
import type { FastifyReply, FastifyRequest } from "fastify";
import { sha256Hex } from "../lib/hash.js";
export type IngestAuthContext = {
keyId: string;
projectId: string;
};
function _extractBearerToken(header: string | undefined): string | null {
if (typeof header !== "string" || header.trim() === "") {
return null;
}
const _m = /^Bearer\s+(\S+)$/i.exec(header.trim());
if (_m) {
return _m[1] ?? null;
}
return null;
}
export async function attachIngestAuth(
pool: Pool,
request: FastifyRequest,
reply: FastifyReply,
): Promise<void> {
const _fromAuth = _extractBearerToken(request.headers.authorization);
const _fromHeader =
typeof request.headers["x-api-key"] === "string" ? request.headers["x-api-key"].trim() : "";
const _token = _fromAuth ?? (_fromHeader !== "" ? _fromHeader : null);
if (_token === null) {
await reply.status(401).send({
error: "unauthorized",
message: "Missing ingest credentials (Authorization: Bearer or X-Api-Key).",
});
return;
}
const _hash = sha256Hex(_token);
const _result = await pool.query<{
id: string;
project_id: string;
}>(
`SELECT id::text, project_id::text
FROM er_ingest_keys
WHERE token_hash = $1
AND status = 'active'
AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > NOW())`,
[_hash],
);
if (_result.rowCount === 0) {
await reply.status(401).send({
error: "unauthorized",
message: "Invalid or inactive ingest key.",
});
return;
}
const _row = _result.rows[0];
if (!_row) {
await reply.status(401).send({
error: "unauthorized",
message: "Invalid or inactive ingest key.",
});
return;
}
request.ingestAuth = {
keyId: _row.id,
projectId: _row.project_id,
};
}
@@ -0,0 +1,189 @@
import type { Pool, PoolClient } from "pg";
import { stableJsonHash } from "../lib/hash.js";
import {
computeFingerprint,
incidentTitleFromMessage,
normalizeLevelToSeverity,
parseOccurredAt,
} from "../lib/normalize.js";
export type IngestEventInput = {
schema_version: number;
occurred_at: string;
level: string;
message: string;
fingerprint?: string;
stacktrace?: string;
context?: Record<string, unknown>;
};
export type IngestResultItem = {
incident_id: string;
occurrence_id: string;
fingerprint: string;
};
export async function processIngestBatch(input: {
pool: Pool;
ingestKeyId: string;
projectId: string;
events: IngestEventInput[];
idempotencyKey: string | null;
bodyHash: string;
}): Promise<{ status: 200 | 409; body: unknown }> {
const _client = await input.pool.connect();
try {
await _client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
if (input.idempotencyKey !== null) {
const _existing = await _client.query<{
body_hash: string;
response_json: unknown;
http_status: number;
}>(
`SELECT body_hash, response_json, http_status
FROM er_ingest_idempotency
WHERE ingest_key_id = $1::bigint
AND idempotency_key = $2`,
[input.ingestKeyId, input.idempotencyKey],
);
const _row0 = _existing.rows[0];
if (_row0) {
if (_row0.body_hash !== input.bodyHash) {
await _client.query("ROLLBACK");
return {
status: 409,
body: {
error: "idempotency_conflict",
message:
"The same Idempotency-Key was reused with a different request body. Use a new key or retry the original payload.",
},
};
}
await _client.query("COMMIT");
return { status: 200, body: _row0.response_json };
}
}
const _results: IngestResultItem[] = [];
for (const _ev of input.events) {
const _item = await _ingestOneEvent(_client, {
ingestKeyId: input.ingestKeyId,
projectId: input.projectId,
event: _ev,
});
_results.push(_item);
}
const _responseBody = { results: _results };
if (input.idempotencyKey !== null) {
const _firstIncidentId = _results[0]?.incident_id;
if (typeof _firstIncidentId === "string") {
await _client.query(
`INSERT INTO er_ingest_idempotency (
ingest_key_id, idempotency_key, body_hash, incident_id, http_status, response_json
) VALUES ($1::bigint, $2, $3, $4::bigint, 200, $5::jsonb)`,
[
input.ingestKeyId,
input.idempotencyKey,
input.bodyHash,
_firstIncidentId,
JSON.stringify(_responseBody),
],
);
}
}
await _client.query(
`UPDATE er_ingest_keys SET last_used_at = NOW() WHERE id = $1::bigint`,
[input.ingestKeyId],
);
await _client.query("COMMIT");
return { status: 200, body: _responseBody };
} catch (_err) {
await _client.query("ROLLBACK");
throw _err;
} finally {
_client.release();
}
}
async function _ingestOneEvent(
client: PoolClient,
input: { ingestKeyId: string; projectId: string; event: IngestEventInput },
): Promise<IngestResultItem> {
const _ev = input.event;
if (_ev.schema_version !== 1) {
throw new Error("unsupported_schema_version");
}
const _occurredMs = parseOccurredAt(_ev.occurred_at);
const _occurred = new Date(_occurredMs);
const _levelRaw = _ev.level.trim().slice(0, 32);
const _severity = normalizeLevelToSeverity(_ev.level);
const _message = _ev.message.trim();
const _fingerprint = computeFingerprint({
clientFingerprint: _ev.fingerprint,
message: _message,
stacktrace: _ev.stacktrace,
});
const _title = incidentTitleFromMessage(_message);
const _stack = typeof _ev.stacktrace === "string" ? _ev.stacktrace : null;
const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null;
const _incident = await client.query<{ id: string }>(
`INSERT INTO er_incidents (
project_id, fingerprint, title, severity, first_seen_at, last_seen_at,
occurrences_count, last_ingest_key_id
) VALUES (
$1::bigint, $2, $3, $4, $5::timestamp, $5::timestamp, 1, $6::bigint
)
ON CONFLICT (project_id, fingerprint) DO UPDATE SET
last_seen_at = EXCLUDED.last_seen_at,
occurrences_count = er_incidents.occurrences_count + 1,
last_ingest_key_id = EXCLUDED.last_ingest_key_id,
updated_at = CURRENT_TIMESTAMP
RETURNING id::text`,
[input.projectId, _fingerprint, _title, _severity, _occurred, input.ingestKeyId],
);
const _incidentRow = _incident.rows[0];
if (!_incidentRow) {
throw new Error("incident_upsert_failed");
}
const _occ = await client.query<{ id: string }>(
`INSERT INTO er_occurrence_events (
project_id, incident_id, ingest_key_id, occurred_at, level_raw, severity,
message, stacktrace, context_json, schema_version
) VALUES (
$1::bigint, $2::bigint, $3::bigint, $4::timestamptz, $5, $6, $7, $8, $9::jsonb, $10
)
RETURNING id::text`,
[
input.projectId,
_incidentRow.id,
input.ingestKeyId,
_occurred,
_levelRaw,
_severity,
_message,
_stack,
_context === null ? null : JSON.stringify(_context),
_ev.schema_version,
],
);
const _occRow = _occ.rows[0];
if (!_occRow) {
throw new Error("occurrence_insert_failed");
}
return {
incident_id: _incidentRow.id,
occurrence_id: _occRow.id,
fingerprint: _fingerprint,
};
}
export function computeRequestBodyHash(body: unknown): string {
return stableJsonHash(body);
}
+7
View File
@@ -0,0 +1,7 @@
import "fastify";
declare module "fastify" {
interface FastifyRequest {
ingestAuth?: { keyId: string; projectId: string };
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: false,
environment: "node",
testTimeout: 60_000,
hookTimeout: 60_000,
},
});
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
: "${PGHOST:=postgres}"
: "${PGUSER:=postgres}"
: "${PGDATABASE:=error_reporting}"
until pg_isready -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE"; do
sleep 1
done
_run_sql() {
psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -v ON_ERROR_STOP=1 -f "$1"
}
_run_sql "/migrations/20260322043000_create_error_reporting_core.up.sql"
_run_sql "/migrations/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql "/migrations/20260322044500_add_ingest_idempotency.up.sql"
_run_sql "/migrations/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql "/seed/dev_two_projects.sql"
_run_sql "/seed/dev_collector_http_fixture.sql"
echo "docker-migrate: complete"