Compare commits

...
Author SHA1 Message Date
David Santos 113eee0b97 feat(obs): add Loki ruler alert rules and MONITORING.md Loki section (BIT-19957)
- deploy/loki/rules/fake/errors_hub_alerts.yaml: four LogQL-based Loki ruler
  alert rules (error rate per service, fatal detection, ingest-api sustained
  errors, collector-worker stall detection)
- deploy/loki/loki.yaml: add explicit ruler.storage (local), rule_path, and
  enable_api/enable_alertmanager_v2 so Loki loads rules from /loki/rules
- docker-compose.yml: mount deploy/loki/rules → /loki/rules:ro in the loki
  service (observability profile)
- docs/MONITORING.md: add Loki section with label table, alert rule summary,
  config file index, and LXC deployment note

Paperclip-Issue: BIT-19957
Paperclip-Agent: cto
2026-05-14 09:31:31 +00:00
David Santos c74e05b844 feat(obs): add Loki/Promtail LXC config for central production stack (BIT-21663)
- deploy/loki/promtail-lxc.yaml: journald-based Promtail config for native
  LXC/systemd deployment; unit filter on bitreport-error-reporting-*.service;
  LOKI_PUSH_URL via env var expansion (-config.expand-env=true)
- deploy/loki/systemd/promtail.service: systemd unit; loopback-only binding;
  EnvironmentFile=/etc/promtail/env for secrets
- docs/deployment/loki-lxc-runbook.md: full operational runbook — Loki on
  central obs CT, Promtail on app LXC, firewall, smoke LogQL queries
- docs/OBSERVABILITY_LOKI.md: document production topology divergence vs
  lab compose; update configuration files table

Paperclip-Task: BIT-21663
Paperclip-Agent: tiago-neves
2026-05-11 22:18:58 +00:00
David Santos b4356e747d docs: sync BIT-2477 inventory status after Paperclip closure
Align INVENTORY_CODE_INTEGRATIONS_VS_ROADMAP.md with parent issue done: header status, summary table, related-issues table, and document history entry.

Paperclip-Issue: BIT-2477
Paperclip-Run: 7526edc1-a6be-416d-84a2-77d30789f15d
2026-05-09 01:37:06 +00:00
David Santos 46294a4ce3 docs(planning): add code and integrations inventory vs roadmap (BIT-2477)
Maps all existing services, integrations, and documentation against the
roadmap, identifies Phase 2 gaps (Loki, notifications, analytics), and
links to 3 child issues for follow-up work.

Paperclip-Issue: BIT-2477
Paperclip-Run: ab268dc2-587c-41f3-a7d5-5c1cabaae443
2026-05-07 03:29:13 +00:00
Diana Neves 665b4af0cc docs(governance): add root CODEOWNERS baseline (BIT-3492)
Paperclip-Agent: Diana Neves (urlKey diana-neves; id 4427016d-7e8f-46e9-9694-3d062e78cc3a)
Paperclip-Issue: BIT-3492
Paperclip-Run: 9280060a-beda-4265-ac1e-c080464cbbd8
2026-05-07 01:27:27 +00:00
David SantosandPaperclip 3d4444eb21 BIT-15744: add remaining unit tests for admin-ui, api routes, collector-worker db, ingest-api services
Complete test coverage implementation for errors.bitreport.pt:

admin-ui (98 tests):
- test/components/: AppShell, DataAlert, IncidentNotes, KpiCard, SeverityBadge, StateBadge
- test/lib/: format, demo-incidents, incidents-data, incidents-data-api, stats-data, stats-data-api
- vitest.config.ts with jsdom + v8 coverage + @vitejs/plugin-react

api route tests (54 tests):
- src/routes/admin/auth.test.ts (15 tests)
- src/routes/admin/incidents.test.ts (11 tests)
- src/routes/admin/stats.test.ts (18 tests)
- src/routes/public/errorMonitoringStats.test.ts (10 tests)

collector-worker db/scheduler tests (22 tests):
- src/db/collectorRunWriter.test.ts (10 tests)
- src/db/loadActiveSources.test.ts (6 tests)
- src/scheduler/runHttpSourceOnce.test.ts (6 tests)

ingest-api service tests (13 tests):
- src/buildApp.test.ts, plugins/prometheus.test.ts
- services/ingestAuth.test.ts, services/processIngestBatch.utils.test.ts

Total: 187 additional tests (255 total across all modules). All pass.

Paperclip-Issue: BIT-15744
Co-Authored-By: Paperclip <[email protected]>
2026-05-03 07:24:38 +00:00
David Santos 989a92ba07 BIT-15744: add unit tests and coverage config for api, ingest-api, collector-worker
Add 68 new unit tests covering:
- api/src/types/auth.ts: can() RBAC function and ROLE_PERMISSIONS matrix (10 tests)
- ingest-api/src/lib/hash.ts: sha256Hex() and stableJsonHash() pure functions (12 tests)
- ingest-api/src/config/env.ts: loadEnv() with defaults, validation, clamping (8 tests)
- collector-worker/src/config/loadEnv.ts: loadEnv() with all opts (11 tests)
- collector-worker/src/log/structuredLog.ts: logInfo/logWarn/logError output (11 tests)
- collector-worker/src/poll/fetchHttpEvents.ts: full validation/error path coverage (16 tests)

Also add coverage reporting to vitest.config.ts (v8 provider, text/json/html reporters)
and @vitest/coverage-v8 to devDependencies + test:coverage script in each service.

All 68 tests pass. Run npm install && npm run test:coverage in each service directory.

Paperclip-Issue: BIT-15744
Paperclip-Run: 2ff0b69d-853a-46fe-add7-43aa07012016
2026-04-29 04:44:48 +00:00
David SantosandClaude Sonnet 4.6 9a4939a2ba feat(ci): implement full CI/CD pipeline with Gitea Actions (BIT-14249)
- Enhance ci.yml: add collector-worker tests, Python 3 for ingest-api
  contract checker, lint/typecheck for all services, per-service Docker
  Buildx builds, and failure webhook notification job
- Add deploy.yml: workflow_run trigger on CI pass; staging auto-deploy
  via SSH; production deploy gated by manual environment approval;
  success/failure notifications for both environments
- Update docs/CI_PIPELINE.md: document full pipeline, required secrets,
  Gitea environment setup, manual deploy procedure, and failure handling

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-27 10:26:23 +00:00
David SantosandClaude Sonnet 4.6 da57d2a444 feat(clients): add Python, Go, and Java client libraries (BIT-14250)
Zero-dependency clients for errors.bitreport.pt following the same
patterns as clients/node and clients/php: batch size 25, 5 s flush
interval, 8 s HTTP timeout, fire-and-forget, env-var config.

Each client ships with unit tests backed by an embedded HTTP server
(no mocks), an example file, and a build manifest (pyproject.toml,
go.mod, pom.xml).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-27 10:08:11 +00:00
David SantosandClaude Sonnet 4.6 8bb49ce32b feat(observability): integrate Loki for centralised log aggregation (BIT-14248)
Adds Grafana Loki + Promtail to the Docker Compose observability profile,
enabling structured-log collection from all errors.bitreport.pt services.

- deploy/loki/loki.yaml: Loki server (filesystem storage, TSDB v13, 30-day retention)
- deploy/loki/promtail.yaml: Docker SD auto-discovery, JSON parse, Pino level normalisation
- deploy/grafana/loki-logs-dashboard.json: Grafana log dashboard (uid er-loki-logs)
- docs/OBSERVABILITY_LOKI.md: setup, key LogQL queries, troubleshooting runbook
- docker-compose.yml: loki + promtail services under --profile observability; LOG_LEVEL env
- .env.example / ingest-api/.env.example: LOG_LEVEL + ER_PUBLISH_LOKI_PORT documented

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-27 08:03:20 +00:00
David SantosandPaperclip 94d2d12c97 feat(web): add Vitest test framework with 8 test files (BIT-14221)
- Install Vitest, @testing-library/react, @testing-library/user-event,
  @testing-library/jest-dom, jsdom, @vitest/coverage-v8
- Add vitest.config.ts with jsdom environment and v8 coverage
- Add src/test/setup.ts with jest-dom matchers
- Write 5 component tests and 3 integration tests for LoginPage:
    renders, form-fields, button-state, error-alert, loading-state,
    submit-success, submit-error-response, submit-network-error
- 31 tests pass; 92%+ stmt/branch coverage on page.tsx
- Add test-web CI job to .gitea/workflows/ci.yml

Co-Authored-By: Paperclip <[email protected]>
2026-04-27 07:53:58 +00:00
83 changed files with 13950 additions and 174 deletions

No files matched your search

+8
View File
@@ -38,5 +38,13 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one
# MAX_BACKOFF_EXPONENT=8
# COLLECTOR_DEFAULT_INGEST_TOKEN=
# --- Log level (ingest-api, collector-worker, api) ---
# Controls verbosity. Values: trace | debug | info | warn | error | fatal
# LOG_LEVEL=info
# --- Observability: Loki (profile: observability) ---
# Host port mapped to Loki HTTP API
# ER_PUBLISH_LOKI_PORT=3100
# Node apps (ingest-api, collector-worker, api/) expect:
# DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/DATABASE
+121 -7
View File
@@ -15,6 +15,11 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Set up Python 3
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Set up Node.js
uses: actions/setup-node@v4
with:
@@ -26,10 +31,43 @@ jobs:
working-directory: ingest-api
run: npm ci
- name: Lint and typecheck
working-directory: ingest-api
run: |
npm run lint --if-present
npm run typecheck --if-present
- name: Run tests
working-directory: ingest-api
run: npm test
test-collector-worker:
name: Test collector-worker
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: 'collector-worker/package-lock.json'
- name: Install dependencies
working-directory: collector-worker
run: npm ci
- name: Lint and typecheck
working-directory: collector-worker
run: |
npm run lint --if-present
npm run typecheck --if-present
- name: Run tests
working-directory: collector-worker
run: npm test
test-api:
name: Test api
runs-on: ubuntu-latest
@@ -47,6 +85,12 @@ jobs:
working-directory: api
run: npm ci
- name: Lint and typecheck
working-directory: api
run: |
npm run lint --if-present
npm run typecheck --if-present
- name: Run tests
working-directory: api
run: npm test
@@ -76,8 +120,39 @@ jobs:
working-directory: admin-ui
run: npm run typecheck
test-web:
name: Test and lint web
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: 'web/package-lock.json'
- name: Install dependencies
working-directory: web
run: npm ci
- name: Lint and typecheck
working-directory: web
run: |
npm run lint --if-present
npm run typecheck --if-present
- name: Run tests
working-directory: web
run: npm test
- name: Run coverage
working-directory: web
run: npm run test:coverage
docker-build:
name: Validate Docker build
name: Validate Docker builds
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -85,10 +160,49 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build Docker images
run: docker compose build
- name: Build ingest-api image
uses: docker/build-push-action@v5
with:
context: ./ingest-api
push: false
tags: errors-bitreport/ingest-api:ci
- name: Build collector-worker image
uses: docker/build-push-action@v5
with:
context: ./collector-worker
push: false
tags: errors-bitreport/collector-worker:ci
- name: Build admin-ui image
uses: docker/build-push-action@v5
with:
context: ./admin-ui
push: false
tags: errors-bitreport/admin-ui:ci
notify-failure:
name: Notify on CI failure
runs-on: ubuntu-latest
needs:
- test-ingest-api
- test-collector-worker
- test-api
- lint-admin-ui
- test-web
- docker-build
if: failure()
steps:
- name: Send failure webhook
env:
ER_MYSQL_ROOT_PASSWORD: devrootchange
ER_MYSQL_USER: er_app
ER_MYSQL_PASSWORD: er_app_secret
ER_MYSQL_DATABASE: error_reporting
WEBHOOK_URL: ${{ secrets.NOTIFY_WEBHOOK_URL }}
REPO: ${{ github.repository }}
REF: ${{ github.ref_name }}
SHA: ${{ github.sha }}
ACTOR: ${{ github.actor }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
[ -n "$WEBHOOK_URL" ] && curl -fsSL -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"❌ CI failed on *${REPO}*\\nBranch: \`${REF}\`\\nCommit: \`${SHA}\`\\nActor: ${ACTOR}\\nRun: ${RUN_URL}\"}" \
|| true
+124
View File
@@ -0,0 +1,124 @@
name: Deploy
on:
workflow_run:
workflows:
- CI
types:
- completed
branches:
- master
jobs:
deploy-staging:
name: Deploy to staging
runs-on: ubuntu-latest
environment: staging
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- uses: actions/checkout@v4
- name: Setup SSH key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -p "${{ secrets.STAGING_PORT || '22' }}" "${{ secrets.STAGING_HOST }}" >> ~/.ssh/known_hosts
- name: Deploy to staging
env:
HOST: ${{ secrets.STAGING_HOST }}
PORT: ${{ secrets.STAGING_PORT || '22' }}
USER: ${{ secrets.STAGING_USER }}
run: |
ssh -i ~/.ssh/deploy_key -p "$PORT" "$USER@$HOST" bash -s << 'REMOTE'
set -e
cd /opt/bitreport/errors.bitreport.pt
git fetch origin master
git reset --hard origin/master
docker compose up -d --build ingest-api collector-worker admin-ui
docker compose ps
echo "Staging deploy complete: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
REMOTE
- name: Notify staging deploy success
if: success()
env:
WEBHOOK_URL: ${{ secrets.NOTIFY_WEBHOOK_URL }}
SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
[ -n "$WEBHOOK_URL" ] && curl -fsSL -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"✅ Staging deploy succeeded\\nRepo: *${REPO}*\\nCommit: \`${SHA}\`\"}" \
|| true
- name: Notify staging deploy failure
if: failure()
env:
WEBHOOK_URL: ${{ secrets.NOTIFY_WEBHOOK_URL }}
SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
[ -n "$WEBHOOK_URL" ] && curl -fsSL -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"❌ Staging deploy FAILED\\nRepo: *${REPO}*\\nCommit: \`${SHA}\`\\nRun: ${RUN_URL}\"}" \
|| true
deploy-production:
name: Deploy to production
runs-on: ubuntu-latest
environment: production
needs: deploy-staging
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- uses: actions/checkout@v4
- name: Setup SSH key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.PROD_SSH_KEY }}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -p "${{ secrets.PROD_PORT || '22' }}" "${{ secrets.PROD_HOST }}" >> ~/.ssh/known_hosts
- name: Deploy to production
env:
HOST: ${{ secrets.PROD_HOST }}
PORT: ${{ secrets.PROD_PORT || '22' }}
USER: ${{ secrets.PROD_USER }}
run: |
ssh -i ~/.ssh/deploy_key -p "$PORT" "$USER@$HOST" bash -s << 'REMOTE'
set -e
cd /opt/bitreport/errors.bitreport.pt
git fetch origin master
git reset --hard origin/master
docker compose up -d --build ingest-api collector-worker admin-ui
docker compose ps
echo "Production deploy complete: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
REMOTE
- name: Notify production deploy success
if: success()
env:
WEBHOOK_URL: ${{ secrets.NOTIFY_WEBHOOK_URL }}
SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
[ -n "$WEBHOOK_URL" ] && curl -fsSL -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"🚀 Production deploy succeeded\\nRepo: *${REPO}*\\nCommit: \`${SHA}\`\"}" \
|| true
- name: Notify production deploy failure
if: failure()
env:
WEBHOOK_URL: ${{ secrets.NOTIFY_WEBHOOK_URL }}
SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
[ -n "$WEBHOOK_URL" ] && curl -fsSL -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"🔥 Production deploy FAILED\\nRepo: *${REPO}*\\nCommit: \`${SHA}\`\\nRun: ${RUN_URL}\"}" \
|| true
+12
View File
@@ -0,0 +1,12 @@
# Tier 2 baseline CODEOWNERS for BitReport repos
# Replace/add owners as needed per repository domain.
# CI and forge metadata
/.gitea/ @tiago-neves @david-santos
/.gitea/workflows/ @tiago-neves @david-santos
# Documentation
/docs/ @david-santos @planner
# Catch-all
* @david-santos
+2164 -19
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -8,7 +8,10 @@
"build": "next build",
"start": "next start -p 3040",
"lint": "next lint",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"bootstrap": "^5.3.3",
@@ -18,13 +21,19 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/node": "^22.9.0",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.5",
"eslint": "^9.15.0",
"eslint-config-next": "15.5.15",
"jsdom": "^29.1.0",
"sass": "^1.81.0",
"typescript": "^5.6.3"
"typescript": "^5.6.3",
"vitest": "^4.1.5"
},
"engines": {
"node": ">=20"
@@ -0,0 +1,69 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { AppShell } from '@/components/AppShell';
vi.mock('next/link', () => ({
default: ({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) => (
<a href={href} className={className}>{children}</a>
),
}));
describe('AppShell', () => {
it('renders the page title', () => {
render(<AppShell title="Dashboard"><div>content</div></AppShell>);
expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
});
it('renders child content', () => {
render(<AppShell title="Test"><p>Hello content</p></AppShell>);
expect(screen.getByText('Hello content')).toBeInTheDocument();
});
it('renders the BitReport brand link', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.getByText('BitReport')).toBeInTheDocument();
});
it('renders nav links for Painel and Incidentes', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.getByRole('link', { name: /Painel/i })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Incidentes/i })).toBeInTheDocument();
});
it('renders breadcrumb when provided', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Home', href: '/' }, { label: 'Current' }]}>
<div />
</AppShell>
);
expect(screen.getByRole('navigation', { name: 'breadcrumb' })).toBeInTheDocument();
expect(screen.getByText('Home')).toBeInTheDocument();
expect(screen.getByText('Current')).toBeInTheDocument();
});
it('does not render breadcrumb nav when breadcrumb is empty', () => {
render(<AppShell title="T" breadcrumb={[]}><div /></AppShell>);
expect(screen.queryByRole('navigation', { name: 'breadcrumb' })).toBeNull();
});
it('does not render breadcrumb nav when breadcrumb is omitted', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.queryByRole('navigation', { name: 'breadcrumb' })).toBeNull();
});
it('breadcrumb item with href renders as a link', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Home', href: '/home' }]}><div /></AppShell>
);
const link = screen.getByText('Home').closest('a');
expect(link).not.toBeNull();
});
it('breadcrumb item without href has aria-current="page"', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Current page' }]}><div /></AppShell>
);
const item = screen.getByText('Current page').closest('li');
expect(item?.getAttribute('aria-current')).toBe('page');
});
});
@@ -0,0 +1,41 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { DataAlert } from '@/components/DataAlert';
describe('DataAlert', () => {
it('renders the title', () => {
render(<DataAlert variant="warning" title="Aviso" body="Algo correu mal." />);
expect(screen.getByText('Aviso')).toBeInTheDocument();
});
it('renders the body text', () => {
render(<DataAlert variant="info" title="Info" body="Nenhuma informação disponível." />);
expect(screen.getByText('Nenhuma informação disponível.')).toBeInTheDocument();
});
it('applies the correct alert variant class', () => {
const { container } = render(<DataAlert variant="danger" title="Erro" body="Falha." />);
expect(container.querySelector('.alert-danger')).not.toBeNull();
});
it('applies alert-warning class for warning variant', () => {
const { container } = render(<DataAlert variant="warning" title="X" body="Y" />);
expect(container.querySelector('.alert-warning')).not.toBeNull();
});
it('applies alert-info class for info variant', () => {
const { container } = render(<DataAlert variant="info" title="X" body="Y" />);
expect(container.querySelector('.alert-info')).not.toBeNull();
});
it('has role="status" for accessibility', () => {
render(<DataAlert variant="warning" title="Status" body="OK" />);
expect(screen.getByRole('status')).toBeInTheDocument();
});
it('renders title in a strong element', () => {
render(<DataAlert variant="info" title="My Title" body="body text" />);
const strong = screen.getByText('My Title');
expect(strong.tagName).toBe('STRONG');
});
});
@@ -0,0 +1,51 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { IncidentNotes } from '@/components/IncidentNotes';
describe('IncidentNotes', () => {
beforeEach(() => {
sessionStorage.clear();
});
it('renders the label', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByText('Notas do operador')).toBeInTheDocument();
});
it('renders a textarea', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByRole('textbox')).toBeInTheDocument();
});
it('starts with empty textarea when no stored value', () => {
render(<IncidentNotes incidentId="inc-new" />);
const ta = screen.getByRole('textbox') as HTMLTextAreaElement;
expect(ta.value).toBe('');
});
it('loads stored value from sessionStorage', () => {
sessionStorage.setItem('er-incident-notes:inc-42', 'saved note');
render(<IncidentNotes incidentId="inc-42" />);
const ta = screen.getByRole('textbox') as HTMLTextAreaElement;
expect(ta.value).toBe('saved note');
});
it('saves to sessionStorage when user types', () => {
render(<IncidentNotes incidentId="inc-99" />);
const ta = screen.getByRole('textbox');
fireEvent.change(ta, { target: { value: 'new note text' } });
expect(sessionStorage.getItem('er-incident-notes:inc-99')).toBe('new note text');
});
it('shows the helper text about server persistence', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByText(/não são enviadas ao servidor/i)).toBeInTheDocument();
});
it('textarea is linked to its label via htmlFor/id', () => {
render(<IncidentNotes incidentId="inc-1" />);
const label = screen.getByText('Notas do operador');
const ta = screen.getByRole('textbox');
expect(label.getAttribute('for')).toBe(ta.getAttribute('id'));
});
});
+42
View File
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { KpiCard } from '@/components/KpiCard';
describe('KpiCard', () => {
it('renders the label text', () => {
render(<KpiCard label="Total Errors" value={42} variant="danger" />);
expect(screen.getByText('Total Errors')).toBeInTheDocument();
});
it('renders the numeric value', () => {
render(<KpiCard label="Open Incidents" value={7} variant="primary" />);
expect(screen.getByText('7')).toBeInTheDocument();
});
it('applies the correct border variant class', () => {
const { container } = render(<KpiCard label="Resolved" value={100} variant="success" />);
expect(container.querySelector('.border-success')).not.toBeNull();
});
it('applies the correct text variant class', () => {
render(<KpiCard label="Critical" value={3} variant="dark" />);
const valueEl = screen.getByText('3');
expect(valueEl.className).toContain('text-dark');
});
it('renders value zero', () => {
render(<KpiCard label="No errors" value={0} variant="secondary" />);
expect(screen.getByText('0')).toBeInTheDocument();
});
it('renders large numbers', () => {
render(<KpiCard label="All time" value={99999} variant="warning" />);
expect(screen.getByText('99999')).toBeInTheDocument();
});
it('applies card and col wrapper classes', () => {
const { container } = render(<KpiCard label="test" value={1} variant="primary" />);
expect(container.querySelector('.card')).not.toBeNull();
expect(container.querySelector('.card-body')).not.toBeNull();
});
});
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { SeverityBadge } from '@/components/SeverityBadge';
import type { Severity } from '@/lib/types';
describe('SeverityBadge', () => {
const cases: { severity: Severity; label: string; cssClass: string }[] = [
{ severity: 'critical', label: 'Crítico', cssClass: 'text-bg-dark' },
{ severity: 'high', label: 'Alto', cssClass: 'text-bg-danger' },
{ severity: 'medium', label: 'Médio', cssClass: 'text-bg-warning' },
{ severity: 'low', label: 'Baixo', cssClass: 'text-bg-info' },
{ severity: 'info', label: 'Info', cssClass: 'text-bg-light' },
];
cases.forEach(({ severity, label, cssClass }) => {
it(`renders "${label}" label for severity="${severity}"`, () => {
render(<SeverityBadge severity={severity} />);
expect(screen.getByText(label)).toBeInTheDocument();
});
it(`applies "${cssClass}" class for severity="${severity}"`, () => {
render(<SeverityBadge severity={severity} />);
const badge = screen.getByText(label);
expect(badge.className).toContain(cssClass);
expect(badge.className).toContain('badge');
});
});
it('renders as a span element', () => {
render(<SeverityBadge severity="high" />);
expect(screen.getByText('Alto').tagName).toBe('SPAN');
});
});
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { StateBadge } from '@/components/StateBadge';
import type { IncidentState } from '@/lib/types';
describe('StateBadge', () => {
const cases: { state: IncidentState; label: string; cssClass: string }[] = [
{ state: 'open', label: 'Aberto', cssClass: 'text-bg-danger' },
{ state: 'investigating', label: 'Em investigação', cssClass: 'text-bg-warning' },
{ state: 'resolved', label: 'Resolvido', cssClass: 'text-bg-success' },
{ state: 'ignored', label: 'Ignorado', cssClass: 'text-bg-secondary' },
];
cases.forEach(({ state, label, cssClass }) => {
it(`renders "${label}" label for state="${state}"`, () => {
render(<StateBadge state={state} />);
expect(screen.getByText(label)).toBeInTheDocument();
});
it(`applies "${cssClass}" class for state="${state}"`, () => {
render(<StateBadge state={state} />);
const badge = screen.getByText(label);
expect(badge.className).toContain(cssClass);
expect(badge.className).toContain('badge');
});
});
it('renders as a span element', () => {
render(<StateBadge state="open" />);
expect(screen.getByText('Aberto').tagName).toBe('SPAN');
});
});
+54
View File
@@ -0,0 +1,54 @@
import { describe, it, expect } from 'vitest';
import { getDemoIncidentSummaries, getDemoIncidentDetail } from '@/lib/demo-incidents';
describe('getDemoIncidentSummaries', () => {
it('returns a non-empty array', () => {
const result = getDemoIncidentSummaries();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
});
it('each summary has required fields', () => {
const summaries = getDemoIncidentSummaries();
for (const s of summaries) {
expect(typeof s.id).toBe('string');
expect(typeof s.projectSlug).toBe('string');
expect(typeof s.fingerprint).toBe('string');
expect(typeof s.title).toBe('string');
expect(['critical', 'high', 'medium', 'low', 'info']).toContain(s.severity);
expect(['open', 'investigating', 'resolved', 'ignored']).toContain(s.currentState);
expect(typeof s.occurrencesCount).toBe('number');
}
});
it('returns a stable list on repeated calls', () => {
const first = getDemoIncidentSummaries();
const second = getDemoIncidentSummaries();
expect(first.length).toBe(second.length);
expect(first[0].id).toBe(second[0].id);
});
});
describe('getDemoIncidentDetail', () => {
it('returns null for unknown id', () => {
expect(getDemoIncidentDetail('nonexistent-id')).toBeNull();
});
it('returns a detail for a known demo id', () => {
const summaries = getDemoIncidentSummaries();
const id = summaries[0].id;
const detail = getDemoIncidentDetail(id);
expect(detail).not.toBeNull();
expect(detail?.id).toBe(id);
});
it('returned detail has occurrences array', () => {
const summaries = getDemoIncidentSummaries();
const detail = getDemoIncidentDetail(summaries[0].id);
expect(Array.isArray(detail?.occurrences)).toBe(true);
});
it('returns null for empty string id', () => {
expect(getDemoIncidentDetail('')).toBeNull();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { formatDateTime } from '@/lib/format';
describe('formatDateTime', () => {
it('formats a valid ISO string', () => {
const result = formatDateTime('2024-01-15T10:30:00Z');
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
expect(result).not.toBe('2024-01-15T10:30:00Z');
});
it('returns the raw string for an invalid date', () => {
expect(formatDateTime('not-a-date')).toBe('not-a-date');
});
it('returns the raw string for an empty string', () => {
expect(formatDateTime('')).toBe('');
});
it('handles date-only ISO strings', () => {
const result = formatDateTime('2024-06-01');
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
});
it('handles ISO strings with milliseconds', () => {
const result = formatDateTime('2024-03-20T14:22:33.456Z');
expect(typeof result).toBe('string');
expect(result).not.toBe('2024-03-20T14:22:33.456Z');
});
it('returns consistent output for the same input', () => {
const iso = '2024-07-04T12:00:00Z';
expect(formatDateTime(iso)).toBe(formatDateTime(iso));
});
});
@@ -0,0 +1,190 @@
/**
* Tests for fetchIncidentList and fetchIncidentDetail covering the API-backed paths.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchIncidentList, fetchIncidentDetail } from '@/lib/incidents-data';
import type { IncidentSummary } from '@/lib/types';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const PREV_API_BASE = process.env.ERROR_REPORTING_ADMIN_API_BASE;
const mockIncident: IncidentSummary = {
id: 'inc-001',
projectSlug: 'wdmi-store',
fingerprint: 'fp-abc',
title: 'Uncaught TypeError',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00Z',
lastSeenAt: '2026-01-02T00:00:00Z',
occurrencesCount: 5,
};
beforeEach(() => {
process.env.ERROR_REPORTING_ADMIN_API_BASE = 'http://test-api.local';
delete process.env.ERROR_REPORTING_UI_DEMO;
});
afterEach(() => {
if (PREV_API_BASE === undefined) {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
} else {
process.env.ERROR_REPORTING_ADMIN_API_BASE = PREV_API_BASE;
}
vi.restoreAllMocks();
});
describe('fetchIncidentList — API mode', () => {
it('returns incidents from API on success', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [mockIncident] }),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incidents).toHaveLength(1);
expect(result.incidents[0].id).toBe('inc-001');
expect(result.source).toBe('api');
}
});
it('passes state/severity/project/q as query params', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [] }),
});
await fetchIncidentList({ state: 'open', severity: 'high', project: 'wdmi', q: 'TypeError' });
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).toContain('state=open');
expect(calledUrl).toContain('severity=high');
expect(calledUrl).toContain('project=wdmi');
expect(calledUrl).toContain('q=TypeError');
});
it('omits empty params from query string', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [] }),
});
await fetchIncidentList({});
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).not.toContain('state=');
expect(calledUrl).not.toContain('severity=');
});
it('returns unreachable error when fetch throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('ECONNREFUSED'));
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
expect(result.message).toContain('ECONNREFUSED');
}
});
it('returns unreachable error when API returns non-ok status', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
}
});
it('returns empty incidents array when payload has no incidents field', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incidents).toHaveLength(0);
}
});
});
describe('fetchIncidentDetail — API mode', () => {
const detailPayload = {
incident: {
id: 'inc-001',
projectSlug: 'wdmi-store',
fingerprint: 'fp-abc',
title: 'Uncaught TypeError',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00Z',
lastSeenAt: '2026-01-02T00:00:00Z',
occurrencesCount: 5,
recentOccurrences: [],
stateHistory: [],
},
};
it('returns incident detail on success', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(detailPayload),
});
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incident.id).toBe('inc-001');
expect(result.source).toBe('api');
}
});
it('returns not_found on 404', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 404,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentDetail('unknown-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_found');
}
});
it('returns unreachable when API throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('timeout'));
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
expect(result.message).toContain('timeout');
}
});
it('returns unreachable on non-404 HTTP error', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
}
});
it('URL-encodes the incident id', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(detailPayload),
});
await fetchIncidentDetail('inc/with/slashes');
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).toContain('inc%2Fwith%2Fslashes');
});
});
+176
View File
@@ -0,0 +1,176 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { computeKpis, fetchIncidentList, fetchIncidentDetail } from '@/lib/incidents-data';
import { getDemoIncidentSummaries } from '@/lib/demo-incidents';
import type { IncidentSummary } from '@/lib/types';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const makeIncident = (state: IncidentSummary['currentState']): IncidentSummary => ({
id: Math.random().toString(),
projectSlug: 'test',
fingerprint: 'fp',
title: 'Error',
severity: 'high',
currentState: state,
firstSeenAt: '2024-01-01T00:00:00Z',
lastSeenAt: '2024-01-01T00:00:00Z',
occurrencesCount: 1,
});
describe('computeKpis', () => {
it('returns all zeros for empty list', () => {
const result = computeKpis([]);
expect(result).toEqual({ total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 });
});
it('counts total correctly', () => {
const incidents = [makeIncident('open'), makeIncident('resolved'), makeIncident('ignored')];
expect(computeKpis(incidents).total).toBe(3);
});
it('counts each state correctly', () => {
const incidents = [
makeIncident('open'),
makeIncident('open'),
makeIncident('investigating'),
makeIncident('resolved'),
makeIncident('ignored'),
];
const result = computeKpis(incidents);
expect(result.open).toBe(2);
expect(result.investigating).toBe(1);
expect(result.resolved).toBe(1);
expect(result.ignored).toBe(1);
expect(result.total).toBe(5);
});
it('handles all incidents in a single state', () => {
const incidents = [makeIncident('resolved'), makeIncident('resolved')];
const result = computeKpis(incidents);
expect(result.resolved).toBe(2);
expect(result.open).toBe(0);
});
});
describe('fetchIncidentList — not_configured', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns not_configured when API base is missing and demo is off', async () => {
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_configured');
}
});
});
describe('fetchIncidentList — demo mode', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
process.env.ERROR_REPORTING_UI_DEMO = '1';
});
afterEach(() => {
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns demo incidents when no API base is set', async () => {
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.source).toBe('demo');
expect(result.incidents.length).toBeGreaterThan(0);
}
});
it('filters demo incidents by state', async () => {
const allDemo = getDemoIncidentSummaries();
const openCount = allDemo.filter((i) => i.currentState === 'open').length;
const result = await fetchIncidentList({ state: 'open' });
if (result.ok) {
expect(result.incidents.every((i) => i.currentState === 'open')).toBe(true);
expect(result.incidents.length).toBe(openCount);
}
});
it('filters demo incidents by severity', async () => {
const result = await fetchIncidentList({ severity: 'high' });
if (result.ok) {
expect(result.incidents.every((i) => i.severity === 'high')).toBe(true);
}
});
it('filters demo incidents by project slug', async () => {
const allDemo = getDemoIncidentSummaries();
const firstSlug = allDemo[0].projectSlug;
const result = await fetchIncidentList({ project: firstSlug });
if (result.ok) {
expect(result.incidents.every((i) => i.projectSlug === firstSlug)).toBe(true);
}
});
it('filters demo incidents by query string', async () => {
const allDemo = getDemoIncidentSummaries();
const word = allDemo[0].title.split(' ')[0].toLowerCase();
const result = await fetchIncidentList({ q: word });
if (result.ok) {
expect(result.incidents.length).toBeGreaterThan(0);
}
});
it('returns empty list when no demo incidents match filter', async () => {
const result = await fetchIncidentList({ q: 'xyzzy_no_match_abc_999' });
if (result.ok) {
expect(result.incidents).toHaveLength(0);
}
});
});
describe('fetchIncidentDetail — demo mode', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
process.env.ERROR_REPORTING_UI_DEMO = '1';
});
afterEach(() => {
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns detail for a known demo incident', async () => {
const demos = getDemoIncidentSummaries();
const result = await fetchIncidentDetail(demos[0].id);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incident.id).toBe(demos[0].id);
expect(result.source).toBe('demo');
}
});
it('returns not_found for an unknown demo id', async () => {
const result = await fetchIncidentDetail('no-such-incident-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_found');
}
});
});
describe('fetchIncidentDetail — not_configured', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns not_configured when API is not set and demo is off', async () => {
const result = await fetchIncidentDetail('some-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_configured');
}
});
});
+146
View File
@@ -0,0 +1,146 @@
/**
* Tests for fetchOperationalStats covering the API-backed success and error paths.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchOperationalStats, type StatsSummaryPayload } from '@/lib/stats-data';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const PREV_API_BASE = process.env.ERROR_REPORTING_ADMIN_API_BASE;
const mockSummary: StatsSummaryPayload = {
byProject: [
{ slug: 'wdmi', total: 5, open: 2, investigating: 1, resolved: 1, ignored: 1, critical: 0 },
],
bySeverity: { critical: 1, high: 2, medium: 1, low: 0, info: 0 },
resolvedLast24h: 3,
totalLast24h: 10,
};
const mockTrendDay = { granularity: 'day', dates: ['2026-01-01'], series: { high: [1] } };
const mockTrendHour = { granularity: 'hour', hours: ['2026-01-01 00:00:00'], series: { high: [1] } };
const mockRecurrence = { windowDays: 7, rangeStart: '2026-01-01', rangeEndExclusive: '2026-01-08', top: [] };
function makeFetchMock(responses: Map<string, unknown>) {
return vi.fn().mockImplementation((url: string) => {
for (const [key, value] of responses) {
if (url.includes(key)) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(value),
});
}
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
}
beforeEach(() => {
process.env.ERROR_REPORTING_ADMIN_API_BASE = 'http://test-api.local';
});
afterEach(() => {
if (PREV_API_BASE === undefined) {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
} else {
process.env.ERROR_REPORTING_ADMIN_API_BASE = PREV_API_BASE;
}
vi.restoreAllMocks();
});
describe('fetchOperationalStats — API mode', () => {
it('returns ok:true with all data when all fetches succeed', async () => {
global.fetch = makeFetchMock(
new Map([
['/v1/stats/summary', mockSummary],
['/v1/stats/trend?granularity=day', mockTrendDay],
['/v1/stats/trend?granularity=hour', mockTrendHour],
['/v1/stats/recurrence', mockRecurrence],
]),
);
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.summary.byProject).toHaveLength(1);
expect(result.trendDay.granularity).toBe('day');
expect(result.trendHour.granularity).toBe('hour');
expect(result.recurrence.windowDays).toBe(7);
}
});
it('returns error when summary fetch throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('network error'));
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.message).toContain('network error');
}
});
it('returns error when summary returns non-ok HTTP status', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: () => Promise.resolve({}),
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.message).toContain('503');
}
});
it('falls back to empty trendDay when trend day fetch fails', async () => {
let callCount = 0;
global.fetch = vi.fn().mockImplementation((url: string) => {
callCount++;
if (url.includes('/v1/stats/summary')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockSummary) });
}
if (url.includes('granularity=day')) {
return Promise.reject(new Error('day trend unavailable'));
}
if (url.includes('granularity=hour')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendHour) });
}
if (url.includes('recurrence')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockRecurrence) });
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.trendDay.dates).toHaveLength(0);
expect(result.trendHour.granularity).toBe('hour');
}
});
it('falls back to empty recurrence when recurrence fetch fails', async () => {
global.fetch = vi.fn().mockImplementation((url: string) => {
if (url.includes('/v1/stats/summary')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockSummary) });
}
if (url.includes('granularity=day')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendDay) });
}
if (url.includes('granularity=hour')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendHour) });
}
if (url.includes('recurrence')) {
return Promise.reject(new Error('recurrence unavailable'));
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.recurrence.top).toHaveLength(0);
}
});
});
+67
View File
@@ -0,0 +1,67 @@
import { describe, it, expect, vi } from 'vitest';
import { aggregateIncidentKpisFromSummary } from '@/lib/stats-data';
import type { StatsSummaryPayload } from '@/lib/stats-data';
import { fetchOperationalStats } from '@/lib/stats-data';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
describe('fetchOperationalStats — not_configured', () => {
it('returns error when API is not configured', async () => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(typeof result.message).toBe('string');
}
});
});
describe('aggregateIncidentKpisFromSummary', () => {
it('returns zeros for empty byProject list', () => {
const summary: StatsSummaryPayload = { byProject: [] };
const result = aggregateIncidentKpisFromSummary(summary);
expect(result).toEqual({ total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 });
});
it('sums across a single project', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'proj-a', total: 10, open: 3, investigating: 2, resolved: 4, ignored: 1 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(10);
expect(result.open).toBe(3);
expect(result.investigating).toBe(2);
expect(result.resolved).toBe(4);
expect(result.ignored).toBe(1);
});
it('sums across multiple projects', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'proj-a', total: 5, open: 2, investigating: 1, resolved: 1, ignored: 1 },
{ projectSlug: 'proj-b', total: 8, open: 4, investigating: 2, resolved: 2, ignored: 0 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(13);
expect(result.open).toBe(6);
expect(result.investigating).toBe(3);
expect(result.resolved).toBe(3);
expect(result.ignored).toBe(1);
});
it('handles projects with all zeros', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'empty', total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(0);
});
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom';
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'node:path';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./test/setup.ts'],
globals: true,
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['components/**/*.{ts,tsx}', 'lib/**/*.{ts,tsx}'],
exclude: ['**/*.d.ts', 'test/**'],
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
},
},
});
+315
View File
@@ -24,11 +24,83 @@
"devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/node": "^20.14.0",
"@vitest/coverage-v8": "^1.6.1",
"tsx": "^4.15.6",
"typescript": "^5.4.5",
"vitest": "^1.6.0"
}
},
"node_modules/@ampproject/remapping": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.28.5",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
"integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.0"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true,
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
@@ -629,6 +701,16 @@
"node": ">=12"
}
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
"integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/@jest/schemas": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
@@ -642,6 +724,27 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -649,6 +752,17 @@
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lukeed/ms": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
@@ -1086,6 +1200,34 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@vitest/coverage-v8": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-1.6.1.tgz",
"integrity": "sha512-6YeRZwuO4oTGKxD3bijok756oktHSIm3eczVVzNe3scqzuhLwltIF3S9ZL/vwOVIpURmU6SnZhziXXAfw8/Qlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.2.1",
"@bcoe/v8-coverage": "^0.2.3",
"debug": "^4.3.4",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-lib-source-maps": "^5.0.4",
"istanbul-reports": "^3.1.6",
"magic-string": "^0.30.5",
"magicast": "^0.3.3",
"picocolors": "^1.0.0",
"std-env": "^3.5.0",
"strip-literal": "^2.0.0",
"test-exclude": "^6.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"vitest": "1.6.1"
}
},
"node_modules/@vitest/expect": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
@@ -2091,6 +2233,16 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/has-unicode": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
@@ -2106,6 +2258,13 @@
"node": ">=16.0.0"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -2221,6 +2380,76 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-report/node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/istanbul-lib-source-maps": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz",
"integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.23",
"debug": "^4.1.1",
"istanbul-lib-coverage": "^3.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
@@ -2350,6 +2579,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz",
"integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.25.4",
"@babel/types": "^7.25.4",
"source-map-js": "^1.2.0"
}
},
"node_modules/make-dir": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
@@ -3450,6 +3691,19 @@
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/tar": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
@@ -3486,6 +3740,67 @@
"bintrees": "1.0.2"
}
},
"node_modules/test-exclude": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",
"integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==",
"dev": true,
"license": "ISC",
"dependencies": {
"@istanbuljs/schema": "^0.1.2",
"glob": "^7.1.4",
"minimatch": "^3.0.4"
},
"engines": {
"node": ">=8"
}
},
"node_modules/test-exclude/node_modules/brace-expansion": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",
"integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/test-exclude/node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
"dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/test-exclude/node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+2
View File
@@ -10,6 +10,7 @@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"db:migrate": "bash ../scripts/run-mysql-migrations.sh"
},
"dependencies": {
@@ -29,6 +30,7 @@
"devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/node": "^20.14.0",
"@vitest/coverage-v8": "^1.6.1",
"tsx": "^4.15.6",
"typescript": "^5.4.5",
"vitest": "^1.6.0"
+257
View File
@@ -0,0 +1,257 @@
/**
* Tests for admin auth routes.
* Exercises login, refresh, logout, and /me without a live database.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import cookie from '@fastify/cookie';
import jwt from '@fastify/jwt';
import type { RowDataPacket } from 'mysql2';
import adminAuthRoutes from './auth.js';
vi.mock('bcrypt', () => ({
default: {
compare: vi.fn().mockResolvedValue(false),
hash: vi.fn(),
},
}));
vi.mock('../../plugins/audit.js', () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
import bcrypt from 'bcrypt';
const mockBcrypt = vi.mocked(bcrypt);
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
await app.register(cookie, { secret: 'test-cookie-secret' });
await app.register(jwt, {
secret: 'test-jwt-secret',
cookie: { cookieName: '__Host-access', signed: false },
});
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('rateLimits', {
login: { max: 10, timeWindow: 300_000 },
ingest: { max: 1000, timeWindow: 60_000 },
global: { max: 500, timeWindow: 60_000 },
mutation: { max: 100, timeWindow: 60_000 },
});
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
await app.register(adminAuthRoutes);
return app;
}
describe('POST /admin/auth/login', () => {
beforeEach(() => {
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
});
it('returns 400 for missing email field', async () => {
const app = await buildApp();
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { password: 'secret' },
});
expect(res.statusCode).toBe(400);
});
it('returns 400 for invalid email format', async () => {
const app = await buildApp();
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: 'not-an-email', password: 'secret' },
});
expect(res.statusCode).toBe(400);
});
it('returns 401 when user not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'pass' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Invalid credentials' });
});
it('returns 401 when password is wrong', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'wrongpass' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when user is inactive', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 0 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'pass' },
});
expect(res.statusCode).toBe(401);
});
it('returns 200 with user info on successful login', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'correct' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ user: { id: 'u1', email: '[email protected]', role: 'admin' } });
});
});
describe('POST /admin/auth/refresh', () => {
it('returns 401 when no refresh token cookie present', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'POST', url: '/admin/auth/refresh' });
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'No refresh token' });
});
it('returns 401 when token hash not found in db', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Refresh token invalid or expired' });
});
it('returns 401 when token is revoked', async () => {
const tokenRow = [{
id: 't1',
user_id: 'u1',
expires_at: new Date(Date.now() + 1_000_000),
revoked_at: new Date(),
}];
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when token is expired', async () => {
const tokenRow = [{
id: 't1',
user_id: 'u1',
expires_at: new Date(Date.now() - 1_000),
revoked_at: null,
}];
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when user no longer active after valid token', async () => {
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
const user: RowDataPacket[] = [];
const execute = vi.fn()
.mockResolvedValueOnce([tokenRow])
.mockResolvedValueOnce([[]])
.mockResolvedValue([user]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'User no longer active' });
});
it('returns 200 with ok:true on valid refresh', async () => {
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
const userRow = [{ id: 'u1', email: '[email protected]', role: 'admin', is_active: 1 }];
const execute = vi.fn()
.mockResolvedValueOnce([tokenRow])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([userRow])
.mockResolvedValue([[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ ok: true });
});
});
describe('POST /admin/auth/logout', () => {
it('returns 200 and clears cookies', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/logout',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ ok: true });
});
it('returns 200 even without refresh cookie', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'POST', url: '/admin/auth/logout' });
expect(res.statusCode).toBe(200);
});
});
describe('GET /admin/auth/me', () => {
it('returns current user info from auth context', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/admin/auth/me' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({
user: { id: 'u1', email: '[email protected]', role: 'admin' },
});
});
});
+192
View File
@@ -0,0 +1,192 @@
/**
* Tests for admin incident routes.
* Uses mock DB and bypassed auth decorators — no live database required.
*/
import { describe, it, expect, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import adminIncidentsRoutes from './incidents.js';
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
// passthrough — permission already granted by mock authenticate
});
await app.register(adminIncidentsRoutes);
return app;
}
const baseIncident = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 5,
};
describe('GET /v1/incidents', () => {
it('returns empty list when no incidents', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ incidents: [] });
});
it('returns mapped incident list', async () => {
const row = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 5,
};
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incidents: typeof baseIncident[] };
expect(body.incidents).toHaveLength(1);
expect(body.incidents[0]).toMatchObject({ id: '42', severity: 'high', currentState: 'open' });
});
it('accepts valid state filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=resolved' });
expect(res.statusCode).toBe(200);
});
it('accepts valid severity filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?severity=critical' });
expect(res.statusCode).toBe(200);
});
it('accepts project slug filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?project=myproject' });
expect(res.statusCode).toBe(200);
});
it('accepts search query filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?q=TypeError' });
expect(res.statusCode).toBe(200);
});
it('accepts combined filters', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=open&severity=high&project=proj&q=crash' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ incidents: [] });
});
});
describe('GET /v1/incidents/:id', () => {
it('returns 404 for non-numeric id', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/incidents/abc-not-numeric' });
expect(res.statusCode).toBe(404);
});
it('returns 404 when incident not found in db', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/9999' });
expect(res.statusCode).toBe(404);
});
it('returns incident with occurrences on found', async () => {
const incidentRow = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 1,
metadataJson: null,
ingestKeyLabel: 'prod-key',
};
const occurrenceRow = {
id: '1',
occurredAt: '2026-01-01T00:00:00.000Z',
levelRaw: 'error',
severity: 'high',
message: 'Something failed',
stacktrace: null,
contextJson: '{"env":"production"}',
};
const execute = vi.fn()
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/42' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incident: { id: string; occurrences: unknown[] } };
expect(body.incident.id).toBe('42');
expect(body.incident.occurrences).toHaveLength(1);
});
it('handles occurrence with null stacktrace and contextJson', async () => {
const incidentRow = {
id: '1',
projectSlug: 'proj',
fingerprint: 'fp',
title: 'err',
severity: 'low',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-01T00:00:00.000Z',
occurrencesCount: 1,
metadataJson: '{"key":"val"}',
ingestKeyLabel: null,
};
const occurrenceRow = {
id: '2',
occurredAt: '2026-01-01T00:00:00.000Z',
levelRaw: 'warn',
severity: 'low',
message: 'warn',
stacktrace: null,
contextJson: null,
};
const execute = vi.fn()
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/1' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incident: { metadataJson: unknown; ingestKeyLabel: unknown } };
expect(body.incident.metadataJson).toMatchObject({ key: 'val' });
expect(body.incident.ingestKeyLabel).toBeNull();
});
});
+245
View File
@@ -0,0 +1,245 @@
/**
* Tests for admin stats routes.
* Uses mock DB and bypassed auth decorators — no live database required.
*/
import { describe, it, expect, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import adminStatsRoutes from './stats.js';
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
// passthrough
});
await app.register(adminStatsRoutes);
return app;
}
describe('GET /v1/stats/trend', () => {
it('returns day granularity by default with empty series', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend' });
expect(res.statusCode).toBe(200);
const body = res.json() as { granularity: string; dates: string[]; series: Record<string, number[]> };
expect(body.granularity).toBe('day');
expect(Array.isArray(body.dates)).toBe(true);
expect(body.dates.length).toBeGreaterThan(0);
expect(body.series).toHaveProperty('critical');
expect(body.series).toHaveProperty('high');
expect(body.series).toHaveProperty('low');
expect(body.series).toHaveProperty('info');
});
it('returns hour granularity when requested', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=5' });
expect(res.statusCode).toBe(200);
const body = res.json() as { granularity: string; hours: string[] };
expect(body.granularity).toBe('hour');
expect(body.hours).toHaveLength(5);
});
it('returns 404 when project slug not found for day granularity', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('returns 404 when project slug not found for hour granularity', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('maps DB aggregate rows into series data for day granularity', async () => {
const today = new Date();
const dateStr = today.toISOString().slice(0, 10);
const aggRow = { d: dateStr, severity: 'critical', c: 7 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=3' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
const criticalSeries = body.series['critical'] ?? [];
expect(criticalSeries.some((v) => v === 7)).toBe(true);
});
it('maps DB aggregate rows into series data for hour granularity', async () => {
const now = new Date();
now.setUTCMinutes(0, 0, 0);
now.setUTCMilliseconds(0);
const y = now.getUTCFullYear();
const mo = String(now.getUTCMonth() + 1).padStart(2, '0');
const day = String(now.getUTCDate()).padStart(2, '0');
const h = String(now.getUTCHours()).padStart(2, '0');
const bucketLabel = `${y}-${mo}-${day} ${h}:00:00`;
const aggRow = { b: bucketLabel, severity: 'high', c: 3 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=3' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
expect(body.series['high']?.some((v) => v === 3)).toBe(true);
});
it('ignores unknown severity in aggregate rows', async () => {
const aggRow = { d: new Date().toISOString().slice(0, 10), severity: 'unknown-severity', c: 10 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=1' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
expect(body.series['critical']?.every((v) => v === 0)).toBe(true);
});
it('accepts days parameter for day granularity', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=7' });
expect(res.statusCode).toBe(200);
const body = res.json() as { dates: string[] };
expect(body.dates).toHaveLength(7);
});
});
describe('GET /v1/stats/summary', () => {
const defaultExecute = vi.fn()
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ severity: 'critical', c: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
it('returns byProject, bySeverity, resolvedLast24h, totalLast24h', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ severity: 'high', c: 4 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
expect(body.byProject).toHaveLength(1);
expect(body.bySeverity.high).toBe(4);
expect(body.resolvedLast24h).toBe(2);
expect(body.totalLast24h).toBe(10);
});
it('returns 404 when project slug not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('handles empty results gracefully', async () => {
const execute = vi.fn().mockResolvedValue([[] as RowDataPacket[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
expect(body.byProject).toHaveLength(0);
expect(body.resolvedLast24h).toBe(0);
expect(body.totalLast24h).toBe(0);
});
it('skips unknown severity values from summary rows', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[{ severity: 'badvalue', c: 99 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { bySeverity: Record<string, number> };
expect(body.bySeverity.critical).toBe(0);
});
it('accepts valid project filter when project exists', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=myproject' });
expect(res.statusCode).toBe(200);
});
});
describe('GET /v1/stats/recurrence', () => {
it('returns empty top list when no occurrences', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
expect(res.statusCode).toBe(200);
const body = res.json() as { top: unknown[]; windowDays: number };
expect(body.top).toHaveLength(0);
expect(body.windowDays).toBe(7);
});
it('maps top incidents correctly', async () => {
const row = {
id: '1',
project_slug: 'proj',
fingerprint: 'fp1',
title: 'Crash in module',
severity: 'critical',
current_state: 'open',
hits_in_window: 42,
lifetime_occurrences: 100,
};
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?days=14&limit=5' });
expect(res.statusCode).toBe(200);
const body = res.json() as { top: Array<{ hitsInWindow: number; lifetimeOccurrences: number }> };
expect(body.top[0]?.hitsInWindow).toBe(42);
expect(body.top[0]?.lifetimeOccurrences).toBe(100);
});
it('returns 404 when project slug not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('accepts valid project when it exists', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
.mockResolvedValue([[] as RowDataPacket[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=validproject' });
expect(res.statusCode).toBe(200);
});
it('uses default days=7 and limit=15 when not specified', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
expect(res.statusCode).toBe(200);
const body = res.json() as { windowDays: number };
expect(body.windowDays).toBe(7);
});
});
@@ -0,0 +1,230 @@
/**
* Tests for GET /api/error-monitoring/stats
* Uses the same in-process Fastify injection pattern as other route tests.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import errorMonitoringStatsRoutes from './errorMonitoringStats.js';
vi.mock('../../plugins/prometheus.js', () => ({
metricsGauges: {
occurrences24hGauge: { set: vi.fn() },
resolved24hGauge: { set: vi.fn() },
incidentsBySeverityGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
incidentsTotalGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
projectIncidentsGauge: {
reset: vi.fn(),
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
},
projectResolutionRateGauge: {
reset: vi.fn(),
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
},
},
}));
function makeExecute(responses: unknown[][]) {
let call = 0;
return vi.fn().mockImplementation(() => Promise.resolve([responses[call++] ?? []]));
}
async function buildApp(execute: ReturnType<typeof vi.fn>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
app.decorate('db', { execute } as unknown as FastifyInstance['db']);
await app.register(errorMonitoringStatsRoutes);
return app;
}
const PREV_KEY = process.env.ERROR_RESOLVE_API_KEY;
beforeEach(() => {
process.env.ERROR_RESOLVE_API_KEY = 'test-stats-key';
});
afterEach(() => {
if (PREV_KEY === undefined) {
delete process.env.ERROR_RESOLVE_API_KEY;
} else {
process.env.ERROR_RESOLVE_API_KEY = PREV_KEY;
}
});
describe('GET /api/error-monitoring/stats', () => {
function makeDefaultExecute() {
return makeExecute([
// sevRows
[
{ severity: 'critical', c: 5 } as RowDataPacket,
{ severity: 'high', c: 10 } as RowDataPacket,
{ severity: 'unknown_sev', c: 1 } as RowDataPacket,
],
// stateRows
[
{ state: 'open', c: 8 } as RowDataPacket,
{ state: 'resolved', c: 7 } as RowDataPacket,
],
// vol24h
[{ c: 42 } as RowDataPacket],
// res24h
[{ c: 3 } as RowDataPacket],
// hourlyRows
[
{ hour_bucket: '2026-01-01 00:00:00', severity: 'high', cnt: 2 } as RowDataPacket,
{ hour_bucket: '2026-01-01 00:00:00', severity: 'bad_sev', cnt: 1 } as RowDataPacket,
],
// projRows
[
{
slug: 'wdmi',
total: 10,
open_cnt: 3,
investigating_cnt: 2,
resolved_cnt: 4,
ignored_cnt: 1,
critical_cnt: 2,
} as RowDataPacket,
],
]);
}
it('returns 401 without a valid api_key', async () => {
const execute = makeExecute([]);
const app = await buildApp(execute);
const res = await app.inject({ method: 'GET', url: '/api/error-monitoring/stats' });
expect(res.statusCode).toBe(401);
});
it('returns 200 with api_key query param', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
expect(res.statusCode).toBe(200);
});
it('returns correct bySeverity counts', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ bySeverity: Record<string, number> }>();
expect(body.bySeverity.critical).toBe(5);
expect(body.bySeverity.high).toBe(10);
expect(body.bySeverity.medium).toBe(0);
expect(body.bySeverity.low).toBe(0);
expect(body.bySeverity.info).toBe(0);
});
it('returns correct byState counts', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ byState: Record<string, number> }>();
expect(body.byState.open).toBe(8);
expect(body.byState.resolved).toBe(7);
});
it('returns correct 24h ingestion volume', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ ingestion: { last24h: number; resolvedLast24h: number } }>();
expect(body.ingestion.last24h).toBe(42);
expect(body.ingestion.resolvedLast24h).toBe(3);
});
it('returns 24-entry hourlyTrend array (zero-filled)', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ ingestion: { hourlyTrend: unknown[] } }>();
expect(body.ingestion.hourlyTrend).toHaveLength(24);
});
it('returns correct per-project metrics with resolutionRate', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{
projects: Array<{ slug: string; total: number; resolved: number; resolutionRate: number }>;
}>();
expect(body.projects).toHaveLength(1);
const proj = body.projects[0];
expect(proj.slug).toBe('wdmi');
expect(proj.total).toBe(10);
expect(proj.resolved).toBe(4);
expect(proj.resolutionRate).toBe(0.4);
});
it('returns resolutionRate of 0 when total is 0', async () => {
const execute = makeExecute([
[],
[],
[{ c: 0 } as RowDataPacket],
[{ c: 0 } as RowDataPacket],
[],
[
{
slug: 'empty-proj',
total: 0,
open_cnt: 0,
investigating_cnt: 0,
resolved_cnt: 0,
ignored_cnt: 0,
critical_cnt: 0,
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ projects: Array<{ resolutionRate: number }> }>();
expect(body.projects[0].resolutionRate).toBe(0);
});
it('returns 401 with wrong api_key', async () => {
const execute = makeExecute([]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=wrong-key',
});
expect(res.statusCode).toBe(401);
});
it('accepts view_errors query param when DEBUG_VIEW_ERRORS_KEY is set', async () => {
const prevViewKey = process.env.DEBUG_VIEW_ERRORS_KEY;
process.env.DEBUG_VIEW_ERRORS_KEY = 'view-only-key';
try {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?view_errors=view-only-key',
});
expect(res.statusCode).toBe(200);
} finally {
if (prevViewKey === undefined) delete process.env.DEBUG_VIEW_ERRORS_KEY;
else process.env.DEBUG_VIEW_ERRORS_KEY = prevViewKey;
}
});
});
+93
View File
@@ -0,0 +1,93 @@
import { describe, it, expect } from 'vitest';
import { can, ROLE_PERMISSIONS } from './auth.js';
import type { AdminRole, Permission } from './auth.js';
describe('ROLE_PERMISSIONS', () => {
it('superadmin has all permissions', () => {
const perms = ROLE_PERMISSIONS.superadmin;
expect(perms.has('projects:delete')).toBe(true);
expect(perms.has('users:delete')).toBe(true);
expect(perms.has('settings:update')).toBe(true);
expect(perms.has('audit_logs:read')).toBe(true);
});
it('admin does not have user management permissions', () => {
const perms = ROLE_PERMISSIONS.admin;
expect(perms.has('users:create')).toBe(false);
expect(perms.has('users:update')).toBe(false);
expect(perms.has('users:delete')).toBe(false);
});
it('admin has project and error management permissions', () => {
const perms = ROLE_PERMISSIONS.admin;
expect(perms.has('projects:read')).toBe(true);
expect(perms.has('projects:create')).toBe(true);
expect(perms.has('errors:read')).toBe(true);
expect(perms.has('errors:triage')).toBe(true);
expect(perms.has('errors:delete')).toBe(true);
});
it('admin cannot delete projects', () => {
expect(ROLE_PERMISSIONS.admin.has('projects:delete')).toBe(false);
});
it('viewer has only read permissions', () => {
const perms = ROLE_PERMISSIONS.viewer;
expect(perms.has('projects:read')).toBe(true);
expect(perms.has('errors:read')).toBe(true);
expect(perms.has('ingest_tokens:read')).toBe(true);
expect(perms.has('sources:read')).toBe(true);
expect(perms.has('settings:read')).toBe(true);
expect(perms.has('audit_logs:read')).toBe(true);
});
it('viewer cannot create or modify anything', () => {
const writePerms: Permission[] = [
'projects:create', 'projects:update', 'projects:delete',
'errors:triage', 'errors:delete',
'ingest_tokens:create', 'ingest_tokens:revoke',
'sources:create', 'sources:update', 'sources:delete',
'users:read', 'users:create', 'users:update', 'users:delete',
'settings:update',
];
for (const perm of writePerms) {
expect(ROLE_PERMISSIONS.viewer.has(perm), `viewer should not have ${perm}`).toBe(false);
}
});
});
describe('can()', () => {
it('returns true when role has permission', () => {
expect(can('superadmin', 'users:delete')).toBe(true);
expect(can('admin', 'errors:triage')).toBe(true);
expect(can('viewer', 'projects:read')).toBe(true);
});
it('returns false when role lacks permission', () => {
expect(can('viewer', 'projects:create')).toBe(false);
expect(can('admin', 'users:delete')).toBe(false);
expect(can('viewer', 'settings:update')).toBe(false);
});
it('superadmin can do everything', () => {
const allPermissions: Permission[] = [
'projects:read', 'projects:create', 'projects:update', 'projects:delete',
'errors:read', 'errors:triage', 'errors:delete',
'ingest_tokens:read', 'ingest_tokens:create', 'ingest_tokens:revoke',
'sources:read', 'sources:create', 'sources:update', 'sources:delete',
'users:read', 'users:create', 'users:update', 'users:delete',
'settings:read', 'settings:update',
'audit_logs:read',
];
for (const perm of allPermissions) {
expect(can('superadmin', perm), `superadmin should have ${perm}`).toBe(true);
}
});
it('all roles have audit_logs:read', () => {
const roles: AdminRole[] = ['superadmin', 'admin', 'viewer'];
for (const role of roles) {
expect(can(role, 'audit_logs:read'), `${role} should have audit_logs:read`).toBe(true);
}
});
});
+6
View File
@@ -4,5 +4,11 @@ export default defineConfig({
test: {
environment: 'node',
include: ['src/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['src/**/*.ts'],
exclude: ['src/**/*.test.ts', '**/*.d.ts'],
},
},
});
+326
View File
@@ -0,0 +1,326 @@
// Package errorreporter is a lightweight client for errors.bitreport.pt.
//
// Drop this file (and go.mod) into any Go 1.21+ project. Zero external dependencies.
//
// Usage:
//
// import errorreporter "pt.bitreport/errors-go"
//
// func main() {
// errorreporter.Init(errorreporter.Config{Token: os.Getenv("ERROR_REPORTING_TOKEN")})
// defer errorreporter.Flush()
// ...
// if err := doSomething(); err != nil {
// errorreporter.ReportError(err, nil)
// }
// }
//
// Environment variables:
//
// ERROR_REPORTING_TOKEN — ingest API key (required)
// ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
// ERROR_REPORTING_DISABLED — set to "1" to disable
// ERROR_REPORTING_PROJECT_NAME — display name (optional)
// ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
// ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
package errorreporter
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"runtime"
"strings"
"sync"
"time"
)
const (
defaultEndpoint = "https://errors.bitreport.pt"
batchSize = 25
flushInterval = 5 * time.Second
httpTimeout = 8 * time.Second
)
// Config holds reporter configuration. All fields are optional; unset fields
// fall back to the corresponding environment variable.
type Config struct {
Token string
Endpoint string
Disabled bool
ProjectName string
ProjectSlug string
GiteaRepo string
}
type ingestEvent struct {
SchemaVersion int `json:"schema_version"`
OccurredAt string `json:"occurred_at"`
Level string `json:"level"`
Message string `json:"message"`
Stacktrace string `json:"stacktrace,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
}
var (
mu sync.Mutex
cfg Config
queue []ingestEvent
flushTimer *time.Timer
httpClient = &http.Client{Timeout: httpTimeout}
)
// Init initialises the reporter. Call once at startup before any Report* calls.
func Init(c Config) {
mu.Lock()
defer mu.Unlock()
cfg.Token = coalesce(c.Token, os.Getenv("ERROR_REPORTING_TOKEN"))
ep := coalesce(c.Endpoint, os.Getenv("ERROR_REPORTING_ENDPOINT"), defaultEndpoint)
cfg.Endpoint = strings.TrimRight(ep, "/")
cfg.Disabled = c.Disabled || os.Getenv("ERROR_REPORTING_DISABLED") == "1"
cfg.ProjectName = coalesce(c.ProjectName, os.Getenv("ERROR_REPORTING_PROJECT_NAME"))
cfg.ProjectSlug = coalesce(c.ProjectSlug, os.Getenv("ERROR_REPORTING_PROJECT_SLUG"))
cfg.GiteaRepo = coalesce(c.GiteaRepo, os.Getenv("ERROR_REPORTING_GITEA_REPO"))
}
// ReportError reports an error with an optional context map.
func ReportError(err error, ctx map[string]interface{}) {
mu.Lock()
tok, dis, pn, ps, gr, ep := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo, cfg.Endpoint
mu.Unlock()
if dis || tok == "" || err == nil {
return
}
_ = ep // used via snapshot; referenced in send
buf := make([]byte, 8192)
n := runtime.Stack(buf, false)
stack := string(buf[:n])
filePath, lineNum := callerInfo()
c := map[string]interface{}{
"error_type": typeName(err),
}
if filePath != "" {
c["file_path"] = filePath
}
if lineNum > 0 {
c["line_number"] = lineNum
}
if pn != "" {
c["project_name"] = pn
}
if ps != "" {
c["project_slug"] = ps
}
if gr != "" {
c["gitea_repo"] = gr
}
for k, v := range ctx {
c[k] = v
}
enqueue(ingestEvent{
SchemaVersion: 1,
OccurredAt: nowISO(),
Level: "error",
Message: err.Error(),
Stacktrace: stack,
Context: c,
})
}
// ReportMessage reports a plain string message at the given level.
// level must be one of: "error", "warning", "info", "critical".
func ReportMessage(message, level string, ctx map[string]interface{}) {
mu.Lock()
tok, dis, pn, ps, gr := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo
mu.Unlock()
if dis || tok == "" {
return
}
if level == "" {
level = "error"
}
c := map[string]interface{}{}
if pn != "" {
c["project_name"] = pn
}
if ps != "" {
c["project_slug"] = ps
}
if gr != "" {
c["gitea_repo"] = gr
}
for k, v := range ctx {
c[k] = v
}
ev := ingestEvent{
SchemaVersion: 1,
OccurredAt: nowISO(),
Level: level,
Message: message,
}
if len(c) > 0 {
ev.Context = c
}
enqueue(ev)
}
// Flush sends all queued events synchronously. Call before process exit (e.g. via defer).
func Flush() {
mu.Lock()
if flushTimer != nil {
flushTimer.Stop()
flushTimer = nil
}
batch := make([]ingestEvent, len(queue))
copy(batch, queue)
queue = queue[:0]
mu.Unlock()
send(batch)
}
// RecoverAndReport is a deferred helper that catches a panic, reports it, flushes,
// then re-panics so the runtime still terminates the goroutine normally.
//
// defer errorreporter.RecoverAndReport(nil)
func RecoverAndReport(ctx map[string]interface{}) {
if r := recover(); r != nil {
var err error
switch v := r.(type) {
case error:
err = v
default:
err = fmt.Errorf("%v", v)
}
ReportError(err, ctx)
Flush()
panic(r)
}
}
// --- internals ---
func enqueue(ev ingestEvent) {
var toSend []ingestEvent
mu.Lock()
queue = append(queue, ev)
if len(queue) >= batchSize {
toSend = make([]ingestEvent, len(queue))
copy(toSend, queue)
queue = queue[:0]
} else if flushTimer == nil {
flushTimer = time.AfterFunc(flushInterval, flushAsync)
}
mu.Unlock()
if toSend != nil {
go send(toSend)
}
}
func flushAsync() {
mu.Lock()
flushTimer = nil
if len(queue) == 0 {
mu.Unlock()
return
}
batch := make([]ingestEvent, len(queue))
copy(batch, queue)
queue = queue[:0]
mu.Unlock()
send(batch)
}
func send(events []ingestEvent) {
if len(events) == 0 {
return
}
mu.Lock()
tok := cfg.Token
ep := cfg.Endpoint
mu.Unlock()
for i := 0; i < len(events); i += batchSize {
end := i + batchSize
if end > len(events) {
end = len(events)
}
sendBatch(tok, ep, events[i:end])
}
}
func sendBatch(token, endpoint string, events []ingestEvent) {
body, err := json.Marshal(map[string]interface{}{"events": events})
if err != nil {
return
}
req, err := http.NewRequest(http.MethodPost, endpoint+"/v1/ingest/events", bytes.NewReader(body))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := httpClient.Do(req)
if err != nil {
return
}
resp.Body.Close()
}
func nowISO() string {
t := time.Now().UTC()
ms := t.Nanosecond() / 1e6
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), ms)
}
func callerInfo() (string, int) {
pcs := make([]uintptr, 16)
// skip: runtime.Callers, callerInfo, ReportError/ReportMessage
n := runtime.Callers(3, pcs)
frames := runtime.CallersFrames(pcs[:n])
for {
f, more := frames.Next()
if !strings.HasSuffix(f.File, "error_reporter.go") {
return f.File, f.Line
}
if !more {
break
}
}
return "", 0
}
func typeName(err error) string {
if err == nil {
return ""
}
t := fmt.Sprintf("%T", err)
if idx := strings.LastIndex(t, "."); idx >= 0 {
return t[idx+1:]
}
return t
}
func coalesce(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
+187
View File
@@ -0,0 +1,187 @@
package errorreporter_test
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
errorreporter "pt.bitreport/errors-go"
)
// captureServer starts a test HTTP server that collects posted request bodies.
func captureServer(t *testing.T) (*httptest.Server, *[]map[string]interface{}, *sync.Mutex) {
t.Helper()
var mu sync.Mutex
var bodies []map[string]interface{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Logf("decode error: %v", err)
return
}
mu.Lock()
bodies = append(bodies, body)
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
return srv, &bodies, &mu
}
func TestReportError(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
errorreporter.ReportError(errors.New("something failed"), nil)
errorreporter.Flush()
mu.Lock()
defer mu.Unlock()
if len(*bodies) != 1 {
t.Fatalf("expected 1 request, got %d", len(*bodies))
}
events := (*bodies)[0]["events"].([]interface{})
if len(events) != 1 {
t.Fatalf("expected 1 event, got %d", len(events))
}
ev := events[0].(map[string]interface{})
if ev["level"] != "error" {
t.Errorf("level = %v, want error", ev["level"])
}
if ev["message"] != "something failed" {
t.Errorf("message = %v, want 'something failed'", ev["message"])
}
if ev["schema_version"].(float64) != 1 {
t.Errorf("schema_version = %v, want 1", ev["schema_version"])
}
if ev["stacktrace"] == "" {
t.Error("expected non-empty stacktrace")
}
ctx := ev["context"].(map[string]interface{})
if ctx["error_type"] == "" {
t.Error("expected non-empty error_type in context")
}
}
func TestReportMessage(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
errorreporter.ReportMessage("disk nearly full", "warning", map[string]interface{}{"used_pct": 95})
errorreporter.Flush()
mu.Lock()
defer mu.Unlock()
if len(*bodies) != 1 {
t.Fatalf("expected 1 request, got %d", len(*bodies))
}
ev := (*bodies)[0]["events"].([]interface{})[0].(map[string]interface{})
if ev["level"] != "warning" {
t.Errorf("level = %v, want warning", ev["level"])
}
if ev["message"] != "disk nearly full" {
t.Errorf("message = %v, want 'disk nearly full'", ev["message"])
}
ctx := ev["context"].(map[string]interface{})
if ctx["used_pct"].(float64) != 95 {
t.Errorf("used_pct = %v, want 95", ctx["used_pct"])
}
}
func TestProjectContext(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{
Token: "test-tok",
Endpoint: srv.URL,
ProjectName: "Test App",
ProjectSlug: "test-app",
GiteaRepo: "org/test-app",
})
errorreporter.ReportMessage("hello", "info", nil)
errorreporter.Flush()
mu.Lock()
defer mu.Unlock()
ctx := (*bodies)[0]["events"].([]interface{})[0].(map[string]interface{})["context"].(map[string]interface{})
if ctx["project_name"] != "Test App" {
t.Errorf("project_name = %v", ctx["project_name"])
}
if ctx["project_slug"] != "test-app" {
t.Errorf("project_slug = %v", ctx["project_slug"])
}
if ctx["gitea_repo"] != "org/test-app" {
t.Errorf("gitea_repo = %v", ctx["gitea_repo"])
}
}
func TestDisabledSkipsRequests(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL, Disabled: true})
errorreporter.ReportMessage("should not send", "error", nil)
errorreporter.Flush()
mu.Lock()
defer mu.Unlock()
if len(*bodies) != 0 {
t.Errorf("expected 0 requests when disabled, got %d", len(*bodies))
}
}
func TestNoTokenSkipsRequests(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{Token: "", Endpoint: srv.URL})
errorreporter.ReportMessage("no token", "error", nil)
errorreporter.Flush()
mu.Lock()
defer mu.Unlock()
if len(*bodies) != 0 {
t.Errorf("expected 0 requests without token, got %d", len(*bodies))
}
}
func TestAuthorizationHeader(t *testing.T) {
var capturedAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedAuth = r.Header.Get("Authorization")
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
errorreporter.Init(errorreporter.Config{Token: "my-secret-token", Endpoint: srv.URL})
errorreporter.ReportMessage("auth check", "info", nil)
errorreporter.Flush()
if capturedAuth != "Bearer my-secret-token" {
t.Errorf("Authorization = %q, want 'Bearer my-secret-token'", capturedAuth)
}
}
func TestBatchFlushOnSize(t *testing.T) {
srv, bodies, mu := captureServer(t)
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
for i := 0; i < 25; i++ {
errorreporter.ReportMessage("msg", "info", nil)
}
// Allow time for background goroutine triggered by batch overflow
time.Sleep(200 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
total := 0
for _, b := range *bodies {
total += len(b["events"].([]interface{}))
}
if total != 25 {
t.Errorf("expected 25 events total across batches, got %d", total)
}
}
+46
View File
@@ -0,0 +1,46 @@
//go:build ignore
// Basic usage example for the BitReport Go error reporter.
//
// Run with:
//
// ERROR_REPORTING_TOKEN=your_token go run basic_usage.go
package main
import (
"errors"
"fmt"
"os"
errorreporter "pt.bitreport/errors-go"
)
func main() {
errorreporter.Init(errorreporter.Config{
Token: os.Getenv("ERROR_REPORTING_TOKEN"),
ProjectName: "My Go App",
ProjectSlug: "my-go-app",
})
defer errorreporter.Flush()
// Report a plain message
errorreporter.ReportMessage("Application started", "info", nil)
// Report a warning with extra context
errorreporter.ReportMessage("Cache miss", "warning", map[string]interface{}{
"cache_key": "user:42",
})
// Report an error
if err := riskyOperation(); err != nil {
errorreporter.ReportError(err, map[string]interface{}{
"operation": "riskyOperation",
})
}
fmt.Println("Events sent. Check your errors.bitreport.pt dashboard.")
}
func riskyOperation() error {
return errors.New("something went wrong")
}
+3
View File
@@ -0,0 +1,3 @@
module pt.bitreport/errors-go
go 1.21
+40
View File
@@ -0,0 +1,40 @@
import pt.bitreport.errors.ErrorReporter;
import java.util.Map;
/**
* Basic usage example for the BitReport Java error reporter.
*
* Compile and run:
* javac -cp path/to/bitreport-errors-1.0.0.jar BasicUsage.java
* ERROR_REPORTING_TOKEN=your_token java -cp .:path/to/bitreport-errors-1.0.0.jar BasicUsage
*/
public class BasicUsage {
public static void main(String[] args) {
ErrorReporter.init(ErrorReporter.Config.builder()
.token(System.getenv("ERROR_REPORTING_TOKEN"))
.projectName("My Java App")
.projectSlug("my-java-app")
.build());
// Always flush before the JVM exits
Runtime.getRuntime().addShutdownHook(new Thread(ErrorReporter::flush));
// Report a plain message
ErrorReporter.reportMessage("Application started", "info", null);
// Report a warning with context
ErrorReporter.reportMessage("Cache miss", "warning", Map.of("cache_key", "user:42"));
// Report a caught exception
try {
int result = Integer.parseInt("not-a-number");
} catch (NumberFormatException e) {
ErrorReporter.reportError(e, Map.of("input", "not-a-number"));
}
// Flush synchronously so the example does not exit with pending events
ErrorReporter.flush();
System.out.println("Events sent. Check your errors.bitreport.pt dashboard.");
}
}
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pt.bitreport</groupId>
<artifactId>bitreport-errors</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>BitReport Error Reporter</name>
<description>Lightweight Java client for errors.bitreport.pt</description>
<url>https://errors.bitreport.pt</url>
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.10.2</junit.version>
</properties>
<dependencies>
<!-- No runtime dependencies — zero external deps is a design constraint -->
<!-- Test-only -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,366 @@
package pt.bitreport.errors;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* BitReport Error Reporter — Java client for errors.bitreport.pt ingest API.
*
* <p>Drop this file into any Java 11+ project. Zero external dependencies.
*
* <p>Usage:
* <pre>{@code
* ErrorReporter.init(ErrorReporter.Config.builder()
* .token(System.getenv("ERROR_REPORTING_TOKEN"))
* .projectSlug("my-java-app")
* .build());
*
* try {
* riskyOperation();
* } catch (Exception e) {
* ErrorReporter.reportError(e, Map.of("operation", "riskyOperation"));
* }
*
* // Before shutdown:
* ErrorReporter.flush();
* }</pre>
*
* <p>Environment variables:
* <ul>
* <li>{@code ERROR_REPORTING_TOKEN} — ingest API key (required)</li>
* <li>{@code ERROR_REPORTING_ENDPOINT} — base URL (default: https://errors.bitreport.pt)</li>
* <li>{@code ERROR_REPORTING_DISABLED} — set to "1" to disable</li>
* <li>{@code ERROR_REPORTING_PROJECT_NAME} — display name (optional)</li>
* <li>{@code ERROR_REPORTING_PROJECT_SLUG} — stable product slug (optional)</li>
* <li>{@code ERROR_REPORTING_GITEA_REPO} — canonical owner/repo on Gitea (optional)</li>
* </ul>
*/
public final class ErrorReporter {
private static final String DEFAULT_ENDPOINT = "https://errors.bitreport.pt";
private static final int BATCH_SIZE = 25;
private static final long FLUSH_MS = 5_000L;
private static final int TIMEOUT_MS = 8_000;
private static final DateTimeFormatter ISO_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
// --- Config ---
public static final class Config {
final String token;
final String endpoint;
final boolean disabled;
final String projectName;
final String projectSlug;
final String giteaRepo;
private Config(Builder b) {
this.token = coalesce(b.token, env("ERROR_REPORTING_TOKEN"));
this.endpoint = stripTrailingSlash(
coalesce(b.endpoint, env("ERROR_REPORTING_ENDPOINT"), DEFAULT_ENDPOINT));
this.disabled = b.disabled || "1".equals(env("ERROR_REPORTING_DISABLED"));
this.projectName = coalesce(b.projectName, env("ERROR_REPORTING_PROJECT_NAME"));
this.projectSlug = coalesce(b.projectSlug, env("ERROR_REPORTING_PROJECT_SLUG"));
this.giteaRepo = coalesce(b.giteaRepo, env("ERROR_REPORTING_GITEA_REPO"));
}
public static Builder builder() { return new Builder(); }
public static final class Builder {
private String token = "";
private String endpoint = "";
private boolean disabled = false;
private String projectName = "";
private String projectSlug = "";
private String giteaRepo = "";
public Builder token(String v) { this.token = v != null ? v : ""; return this; }
public Builder endpoint(String v) { this.endpoint = v != null ? v : ""; return this; }
public Builder disabled(boolean v) { this.disabled = v; return this; }
public Builder projectName(String v) { this.projectName = v != null ? v : ""; return this; }
public Builder projectSlug(String v) { this.projectSlug = v != null ? v : ""; return this; }
public Builder giteaRepo(String v) { this.giteaRepo = v != null ? v : ""; return this; }
public Config build() { return new Config(this); }
}
}
// --- Shared state ---
private static final AtomicReference<Config> CONFIG = new AtomicReference<>(
Config.builder().build());
private static final List<Map<String, Object>> QUEUE =
Collections.synchronizedList(new ArrayList<>());
private static final ScheduledExecutorService SCHEDULER =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "bitreport-flush");
t.setDaemon(true);
return t;
});
private static final AtomicBoolean TIMER_RUNNING = new AtomicBoolean(false);
private static volatile ScheduledFuture<?> FLUSH_TASK = null;
// prevent instantiation
private ErrorReporter() {}
// --- Public API ---
/** Initialise the reporter. Call once at startup. */
public static void init(Config config) {
CONFIG.set(config);
}
/** Report a {@link Throwable} with optional extra context. */
public static void reportError(Throwable t, Map<String, Object> extraContext) {
Config c = CONFIG.get();
if (c.disabled || c.token.isEmpty() || t == null) return;
Map<String, Object> ctx = new LinkedHashMap<>();
ctx.put("error_type", t.getClass().getSimpleName());
// Extract deepest stack frame outside this class
StackTraceElement caller = findCaller(t.getStackTrace());
if (caller != null) {
ctx.put("file_path", caller.getFileName() != null ? caller.getFileName() : "");
ctx.put("line_number", caller.getLineNumber());
}
addProjectFields(ctx, c);
if (extraContext != null) ctx.putAll(extraContext);
String stack = stackTraceString(t);
Map<String, Object> event = new LinkedHashMap<>();
event.put("schema_version", 1);
event.put("occurred_at", nowISO());
event.put("level", "error");
event.put("message", t.getMessage() != null ? t.getMessage() : t.toString());
event.put("stacktrace", stack);
event.put("context", ctx);
enqueue(event);
}
/**
* Report a plain message.
*
* @param message the message text
* @param level one of: "error", "warning", "info", "critical"
* @param context optional key-value pairs (may be null)
*/
public static void reportMessage(String message, String level, Map<String, Object> context) {
Config c = CONFIG.get();
if (c.disabled || c.token.isEmpty()) return;
Map<String, Object> ctx = new LinkedHashMap<>();
addProjectFields(ctx, c);
if (context != null) ctx.putAll(context);
Map<String, Object> event = new LinkedHashMap<>();
event.put("schema_version", 1);
event.put("occurred_at", nowISO());
event.put("level", level != null && !level.isEmpty() ? level : "error");
event.put("message", message);
if (!ctx.isEmpty()) event.put("context", ctx);
enqueue(event);
}
/** Flush all queued events synchronously. Call before JVM shutdown. */
public static void flush() {
cancelTimer();
List<Map<String, Object>> snapshot;
synchronized (QUEUE) {
snapshot = new ArrayList<>(QUEUE);
QUEUE.clear();
}
sendInBatches(snapshot);
}
// --- internals ---
private static void enqueue(Map<String, Object> event) {
List<Map<String, Object>> batch = null;
synchronized (QUEUE) {
QUEUE.add(event);
if (QUEUE.size() >= BATCH_SIZE) {
batch = new ArrayList<>(QUEUE);
QUEUE.clear();
}
}
if (batch != null) {
final List<Map<String, Object>> toSend = batch;
SCHEDULER.submit(() -> sendInBatches(toSend));
} else {
scheduleFlushTimer();
}
}
private static synchronized void scheduleFlushTimer() {
if (FLUSH_TASK == null || FLUSH_TASK.isDone()) {
FLUSH_TASK = SCHEDULER.schedule(() -> {
List<Map<String, Object>> batch;
synchronized (QUEUE) {
batch = new ArrayList<>(QUEUE);
QUEUE.clear();
}
sendInBatches(batch);
}, FLUSH_MS, TimeUnit.MILLISECONDS);
}
}
private static synchronized void cancelTimer() {
if (FLUSH_TASK != null) {
FLUSH_TASK.cancel(false);
FLUSH_TASK = null;
}
}
private static void sendInBatches(List<Map<String, Object>> events) {
if (events.isEmpty()) return;
for (int i = 0; i < events.size(); i += BATCH_SIZE) {
int end = Math.min(i + BATCH_SIZE, events.size());
sendBatch(events.subList(i, end));
}
}
private static void sendBatch(List<Map<String, Object>> events) {
if (events.isEmpty()) return;
Config c = CONFIG.get();
try {
String body = toJson(Map.of("events", events));
byte[] payload = body.getBytes(StandardCharsets.UTF_8);
URL url = new URL(c.endpoint + "/v1/ingest/events");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + c.token);
conn.setConnectTimeout(TIMEOUT_MS);
conn.setReadTimeout(TIMEOUT_MS);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(payload);
}
conn.getResponseCode(); // consume response so the connection is reusable
conn.disconnect();
} catch (Exception ignored) {
// fire-and-forget: never crash the host app
}
}
// --- helpers ---
private static void addProjectFields(Map<String, Object> ctx, Config c) {
if (!c.projectName.isEmpty()) ctx.put("project_name", c.projectName);
if (!c.projectSlug.isEmpty()) ctx.put("project_slug", c.projectSlug);
if (!c.giteaRepo.isEmpty()) ctx.put("gitea_repo", c.giteaRepo);
}
private static StackTraceElement findCaller(StackTraceElement[] frames) {
String thisClass = ErrorReporter.class.getName();
for (StackTraceElement f : frames) {
if (!f.getClassName().equals(thisClass)) return f;
}
return frames.length > 0 ? frames[0] : null;
}
private static String stackTraceString(Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append(t.toString()).append('\n');
for (StackTraceElement e : t.getStackTrace()) {
sb.append("\tat ").append(e).append('\n');
}
Throwable cause = t.getCause();
if (cause != null) {
sb.append("Caused by: ").append(stackTraceString(cause));
}
return sb.toString().trim();
}
private static String nowISO() {
return ISO_FMT.format(Instant.now());
}
private static String env(String key) {
String v = System.getenv(key);
return v != null ? v.trim() : "";
}
private static String coalesce(String... vals) {
for (String v : vals) {
if (v != null && !v.isEmpty()) return v;
}
return "";
}
private static String stripTrailingSlash(String s) {
return s.endsWith("/") ? s.substring(0, s.length() - 1) : s;
}
// Minimal JSON serialiser — supports: String, Number, Boolean, null, Map, List
@SuppressWarnings("unchecked")
static String toJson(Object value) {
if (value == null) return "null";
if (value instanceof Boolean) return value.toString();
if (value instanceof Number) return value.toString();
if (value instanceof String) return jsonString((String) value);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (!first) sb.append(',');
sb.append(jsonString(entry.getKey())).append(':').append(toJson(entry.getValue()));
first = false;
}
return sb.append('}').toString();
}
if (value instanceof List) {
List<Object> list = (List<Object>) value;
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(',');
sb.append(toJson(list.get(i)));
}
return sb.append(']').toString();
}
return jsonString(value.toString());
}
private static String jsonString(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '"') {
sb.append("\\\"");
} else if (ch == '\\') {
sb.append("\\\\");
} else if (ch == '\n') {
sb.append("\\n");
} else if (ch == '\r') {
sb.append("\\r");
} else if (ch == '\t') {
sb.append("\\t");
} else if (ch < 0x20) {
sb.append(String.format("\\u%04x", (int) ch));
} else {
sb.append(ch);
}
}
return sb.append('"').toString();
}
}
@@ -0,0 +1,184 @@
package pt.bitreport.errors;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.junit.jupiter.api.Assertions.*;
class ErrorReporterTest {
/** Minimal embedded HTTP server that records raw request bodies. */
static HttpServer httpServer;
static int port;
static final List<String> RECEIVED = new CopyOnWriteArrayList<>();
@BeforeAll
static void startServer() throws IOException {
httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
port = httpServer.getAddress().getPort();
httpServer.createContext("/v1/ingest/events", exchange -> {
try (InputStream is = exchange.getRequestBody()) {
RECEIVED.add(new String(is.readAllBytes(), StandardCharsets.UTF_8));
}
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
httpServer.start();
}
@AfterAll
static void stopServer() {
httpServer.stop(0);
}
@BeforeEach
void reset() {
RECEIVED.clear();
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.build());
}
// --- reportError ---
@Test
void reportError_sendsOneEvent() throws Exception {
ErrorReporter.reportError(new IllegalArgumentException("bad arg"), null);
ErrorReporter.flush();
assertEquals(1, RECEIVED.size());
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"error\""), "level should be error");
assertTrue(body.contains("\"message\":\"bad arg\""), "message should be present");
assertTrue(body.contains("\"schema_version\":1"), "schema_version should be 1");
assertTrue(body.contains("\"stacktrace\""), "stacktrace should be present");
assertTrue(body.contains("IllegalArgumentException"), "error_type should be in context");
}
@Test
void reportError_includesFileAndLine() throws Exception {
ErrorReporter.reportError(new RuntimeException("loc"), null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"file_path\""), "file_path should be in context");
assertTrue(body.contains("\"line_number\""), "line_number should be in context");
}
@Test
void reportError_mergesExtraContext() throws Exception {
Map<String, Object> ctx = new LinkedHashMap<>();
ctx.put("request_id", "req-abc");
ctx.put("user_id", 42);
ErrorReporter.reportError(new RuntimeException("ctx test"), ctx);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"request_id\":\"req-abc\""), "request_id should be present");
assertTrue(body.contains("\"user_id\":42"), "user_id should be present");
}
// --- reportMessage ---
@Test
void reportMessage_defaultLevel() throws Exception {
ErrorReporter.reportMessage("something happened", null, null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"error\""), "default level should be error");
assertTrue(body.contains("\"message\":\"something happened\""));
}
@Test
void reportMessage_customLevel() throws Exception {
ErrorReporter.reportMessage("disk usage high", "warning", Map.of("used_pct", 91));
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"warning\""));
assertTrue(body.contains("\"used_pct\":91"));
}
// --- project context ---
@Test
void projectFields_addedToContext() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.projectName("Test App")
.projectSlug("test-app")
.giteaRepo("org/test-app")
.build());
ErrorReporter.reportMessage("test", "info", null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"project_name\":\"Test App\""));
assertTrue(body.contains("\"project_slug\":\"test-app\""));
assertTrue(body.contains("\"gitea_repo\":\"org/test-app\""));
}
// --- disabled / no token ---
@Test
void disabled_skipsRequests() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.disabled(true)
.build());
ErrorReporter.reportMessage("nope", "error", null);
ErrorReporter.flush();
assertEquals(0, RECEIVED.size());
}
@Test
void noToken_skipsRequests() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("")
.endpoint("http://127.0.0.1:" + port)
.build());
ErrorReporter.reportMessage("nope", "error", null);
ErrorReporter.flush();
assertEquals(0, RECEIVED.size());
}
// --- JSON serialiser ---
@Test
void toJson_escapesSpecialCharacters() {
String result = ErrorReporter.toJson("hello\nworld\t\"quotes\"");
assertEquals("\"hello\\nworld\\t\\\"quotes\\\"\"", result);
}
@Test
void toJson_handlesNestedMap() {
Map<String, Object> inner = new LinkedHashMap<>();
inner.put("a", 1);
inner.put("b", true);
Map<String, Object> outer = new LinkedHashMap<>();
outer.put("key", inner);
String json = ErrorReporter.toJson(outer);
assertEquals("{\"key\":{\"a\":1,\"b\":true}}", json);
}
@Test
void toJson_handlesNullValue() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("x", null);
assertEquals("{\"x\":null}", ErrorReporter.toJson(m));
}
}
+223
View File
@@ -0,0 +1,223 @@
"""
BitReport Error Reporter — Python client for errors.bitreport.pt ingest API.
Drop this file into any Python 3.8+ project. Zero dependencies (uses urllib).
Usage:
from error_reporter import init_reporter, report_error, report_message, flush
init_reporter(token=os.environ['ERROR_REPORTING_TOKEN'])
try:
risky_operation()
except Exception as e:
report_error(e, {'url': '/api/foo'})
Environment variables:
ERROR_REPORTING_TOKEN — ingest API key (required)
ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
ERROR_REPORTING_DISABLED — set to "1" to disable
ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional)
ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
"""
import json
import os
import sys
import threading
import traceback
import urllib.request
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
_token: str = ""
_endpoint: str = "https://errors.bitreport.pt"
_disabled: bool = False
_project_name: str = os.environ.get("ERROR_REPORTING_PROJECT_NAME", "")
_project_slug: str = os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "")
_gitea_repo: str = os.environ.get("ERROR_REPORTING_GITEA_REPO", "")
_queue: List[Dict[str, Any]] = []
_lock = threading.Lock()
_flush_timer: Optional[threading.Timer] = None
BATCH_SIZE = 25
FLUSH_SECS = 5.0
TIMEOUT_SECS = 8.0
def init_reporter(
token: str = "",
endpoint: str = "",
disabled: Optional[bool] = None,
project_name: str = "",
project_slug: str = "",
gitea_repo: str = "",
) -> None:
"""Initialise the reporter. Call once at startup."""
global _token, _endpoint, _disabled, _project_name, _project_slug, _gitea_repo
_token = token or os.environ.get("ERROR_REPORTING_TOKEN", "")
_endpoint = (
endpoint
or os.environ.get("ERROR_REPORTING_ENDPOINT", "")
or "https://errors.bitreport.pt"
).rstrip("/")
_disabled = disabled if disabled is not None else os.environ.get("ERROR_REPORTING_DISABLED") == "1"
_project_name = project_name or os.environ.get("ERROR_REPORTING_PROJECT_NAME", "") or _project_name
_project_slug = project_slug or os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "") or _project_slug
_gitea_repo = gitea_repo or os.environ.get("ERROR_REPORTING_GITEA_REPO", "") or _gitea_repo
if not _disabled and _token:
_orig_excepthook = sys.excepthook
def _excepthook(exc_type, exc_value, exc_tb):
report_error(exc_value, {"uncaught": True})
_orig_excepthook(exc_type, exc_value, exc_tb)
sys.excepthook = _excepthook
def report_error(exc: BaseException, context: Optional[Dict[str, Any]] = None) -> None:
"""Report an exception with an optional extra context dict."""
if _disabled or not _token:
return
if context is None:
context = {}
tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
stack = "".join(tb_lines).strip()
file_path = ""
line_number: Optional[int] = None
if exc.__traceback__:
tb = exc.__traceback__
while tb.tb_next:
tb = tb.tb_next
file_path = tb.tb_frame.f_code.co_filename
line_number = tb.tb_lineno
ctx: Dict[str, Any] = {"error_type": type(exc).__name__}
if file_path:
ctx["file_path"] = file_path
if line_number is not None:
ctx["line_number"] = line_number
if _project_name:
ctx["project_name"] = _project_name
if _project_slug:
ctx["project_slug"] = _project_slug
if _gitea_repo:
ctx["gitea_repo"] = _gitea_repo
ctx.update(context)
_enqueue({
"schema_version": 1,
"occurred_at": _now_iso(),
"level": "error",
"message": str(exc),
"stacktrace": stack,
"context": ctx,
})
def report_message(
message: str,
level: str = "error",
context: Optional[Dict[str, Any]] = None,
) -> None:
"""Report a plain message (warning, info, etc.)."""
if _disabled or not _token:
return
if context is None:
context = {}
ctx: Dict[str, Any] = {}
if _project_name:
ctx["project_name"] = _project_name
if _project_slug:
ctx["project_slug"] = _project_slug
if _gitea_repo:
ctx["gitea_repo"] = _gitea_repo
ctx.update(context)
event: Dict[str, Any] = {
"schema_version": 1,
"occurred_at": _now_iso(),
"level": level,
"message": message,
}
if ctx:
event["context"] = ctx
_enqueue(event)
def flush() -> None:
"""Flush all queued events synchronously. Call before process exit."""
global _flush_timer
with _lock:
if _flush_timer is not None:
_flush_timer.cancel()
_flush_timer = None
to_send = list(_queue)
del _queue[:]
for i in range(0, max(len(to_send), 1), BATCH_SIZE):
batch = to_send[i : i + BATCH_SIZE]
if batch:
_send(batch)
# --- internals ---
def _now_iso() -> str:
now = datetime.now(timezone.utc)
return now.strftime(f"%Y-%m-%dT%H:%M:%S.{now.microsecond // 1000:03d}Z")
def _enqueue(event: Dict[str, Any]) -> None:
global _flush_timer
batch_to_send: Optional[List[Dict[str, Any]]] = None
with _lock:
_queue.append(event)
if len(_queue) >= BATCH_SIZE:
batch_to_send = _queue[:BATCH_SIZE]
del _queue[:BATCH_SIZE]
elif _flush_timer is None:
_flush_timer = threading.Timer(FLUSH_SECS, _flush_timer_cb)
_flush_timer.daemon = True
_flush_timer.start()
if batch_to_send is not None:
threading.Thread(target=_send, args=(batch_to_send,), daemon=True).start()
def _flush_timer_cb() -> None:
global _flush_timer
with _lock:
_flush_timer = None
if not _queue:
return
batch = _queue[:BATCH_SIZE]
del _queue[:BATCH_SIZE]
if batch:
threading.Thread(target=_send, args=(batch,), daemon=True).start()
def _send(events: List[Dict[str, Any]]) -> None:
if not events:
return
try:
payload = json.dumps({"events": events}).encode("utf-8")
req = urllib.request.Request(
f"{_endpoint}/v1/ingest/events",
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {_token}",
},
method="POST",
)
urllib.request.urlopen(req, timeout=TIMEOUT_SECS)
except Exception:
pass # fire-and-forget: never crash the host app
+36
View File
@@ -0,0 +1,36 @@
"""
Basic usage example for the BitReport Python error reporter.
Run with:
ERROR_REPORTING_TOKEN=your_token python basic_usage.py
"""
import atexit
import os
from error_reporter import flush, init_reporter, report_error, report_message
init_reporter(
token=os.environ.get("ERROR_REPORTING_TOKEN", ""),
project_name="My Python App",
project_slug="my-python-app",
)
# Flush before the process exits so queued events are not lost
atexit.register(flush)
# Report a plain message
report_message("Application started", level="info")
# Report a warning with extra context
report_message("Cache miss", level="warning", context={"cache_key": "user:42"})
# Report an exception caught in a try/except
try:
result = 1 / 0
except ZeroDivisionError as e:
report_error(e, {"operation": "divide", "numerator": 1, "denominator": 0})
# Flush immediately so the example does not exit before events are sent
flush()
print("Events sent. Check your errors.bitreport.pt dashboard.")
+32
View File
@@ -0,0 +1,32 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.backends.legacy:build"
[project]
name = "bitreport-errors"
version = "1.0.0"
description = "Lightweight error reporting client for errors.bitreport.pt"
readme = "README.md"
requires-python = ">=3.8"
license = { text = "MIT" }
keywords = ["error-reporting", "monitoring", "bitreport"]
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: System :: Monitoring",
]
[project.urls]
Homepage = "https://errors.bitreport.pt"
[tool.setuptools]
py-modules = ["error_reporter"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+164
View File
@@ -0,0 +1,164 @@
"""Unit tests for error_reporter.py — uses an embedded HTTP server, no mocks."""
import json
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
import error_reporter as er
class _CapturingHandler(BaseHTTPRequestHandler):
bodies: list = []
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
_CapturingHandler.bodies.append(json.loads(body))
self.send_response(200)
self.end_headers()
def log_message(self, *_):
pass
class TestErrorReporter(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = HTTPServer(("127.0.0.1", 0), _CapturingHandler)
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.server_thread.start()
cls.port = cls.server.server_address[1]
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
def setUp(self):
_CapturingHandler.bodies = []
er._token = "test-token"
er._endpoint = f"http://127.0.0.1:{self.port}"
er._disabled = False
er._project_name = ""
er._project_slug = ""
er._gitea_repo = ""
with er._lock:
er._queue.clear()
if er._flush_timer is not None:
er._flush_timer.cancel()
er._flush_timer = None
# --- report_error ---
def test_report_error_sends_event(self):
try:
raise ValueError("boom")
except ValueError as exc:
er.report_error(exc)
er.flush()
self.assertEqual(len(_CapturingHandler.bodies), 1)
events = _CapturingHandler.bodies[0]["events"]
self.assertEqual(len(events), 1)
ev = events[0]
self.assertEqual(ev["schema_version"], 1)
self.assertEqual(ev["level"], "error")
self.assertEqual(ev["message"], "boom")
self.assertIn("stacktrace", ev)
self.assertEqual(ev["context"]["error_type"], "ValueError")
def test_report_error_extracts_file_line(self):
try:
raise RuntimeError("loc test")
except RuntimeError as exc:
er.report_error(exc)
er.flush()
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
self.assertIn("file_path", ctx)
self.assertIn("line_number", ctx)
self.assertIsInstance(ctx["line_number"], int)
def test_report_error_with_extra_context(self):
try:
raise KeyError("key")
except KeyError as exc:
er.report_error(exc, {"request_id": "abc123"})
er.flush()
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
self.assertEqual(ctx["request_id"], "abc123")
# --- report_message ---
def test_report_message_default_level(self):
er.report_message("something bad")
er.flush()
ev = _CapturingHandler.bodies[0]["events"][0]
self.assertEqual(ev["level"], "error")
self.assertEqual(ev["message"], "something bad")
def test_report_message_warning(self):
er.report_message("heads up", "warning", {"foo": "bar"})
er.flush()
ev = _CapturingHandler.bodies[0]["events"][0]
self.assertEqual(ev["level"], "warning")
self.assertEqual(ev["context"]["foo"], "bar")
# --- project context ---
def test_project_fields_added(self):
er._project_name = "My App"
er._project_slug = "my-app"
er._gitea_repo = "org/my-app"
er.report_message("test")
er.flush()
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
self.assertEqual(ctx["project_name"], "My App")
self.assertEqual(ctx["project_slug"], "my-app")
self.assertEqual(ctx["gitea_repo"], "org/my-app")
# --- disabled / no token ---
def test_disabled_skips(self):
er._disabled = True
er.report_message("nope")
er.flush()
self.assertEqual(len(_CapturingHandler.bodies), 0)
def test_no_token_skips(self):
er._token = ""
er.report_message("nope")
er.flush()
self.assertEqual(len(_CapturingHandler.bodies), 0)
# --- batching ---
def test_batch_flushed_on_size(self):
for i in range(25):
er.report_message(f"msg {i}")
time.sleep(0.2) # allow background send thread to complete
self.assertGreaterEqual(len(_CapturingHandler.bodies), 1)
total_events = sum(len(b["events"]) for b in _CapturingHandler.bodies)
self.assertEqual(total_events, 25)
def test_authorization_header(self):
# Capture headers by extending the server handler temporarily
captured_headers = {}
class HeaderHandler(_CapturingHandler):
def do_POST(self):
captured_headers["auth"] = self.headers.get("Authorization")
super().do_POST()
self.server.RequestHandlerClass = HeaderHandler
try:
er.report_message("check auth")
er.flush()
finally:
self.server.RequestHandlerClass = _CapturingHandler
self.assertEqual(captured_headers.get("auth"), "Bearer test-token")
if __name__ == "__main__":
unittest.main()
+840
View File
@@ -13,6 +13,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
@@ -21,6 +22,77 @@
"node": ">=20"
}
},
"node_modules/@ampproject/remapping": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.28.5",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
"integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.0"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true,
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
@@ -463,6 +535,55 @@
"node": ">=18"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
"string-width-cjs": "npm:string-width@^4.2.0",
"strip-ansi": "^7.0.1",
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
"wrap-ansi": "^8.1.0",
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
"integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -470,6 +591,28 @@
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
"node": ">=14"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.59.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.1.tgz",
@@ -836,6 +979,39 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@vitest/coverage-v8": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-2.1.9.tgz",
"integrity": "sha512-Z2cOr0ksM00MpEfyVE8KXIYPEcBFxdbLSs56L8PO0QQMxt/6bDj45uQfxoc96v05KW3clk7vvgP0qfDit9DmfQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.3.0",
"@bcoe/v8-coverage": "^0.2.3",
"debug": "^4.3.7",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-lib-source-maps": "^5.0.6",
"istanbul-reports": "^3.1.7",
"magic-string": "^0.30.12",
"magicast": "^0.3.5",
"std-env": "^3.8.0",
"test-exclude": "^7.0.1",
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "2.1.9",
"vitest": "2.1.9"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -949,6 +1125,32 @@
"url": "https://opencollective.com/vitest"
}
},
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -968,6 +1170,29 @@
"node": ">= 6.0.0"
}
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/brace-expansion": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -1005,6 +1230,41 @@
"node": ">= 16"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT"
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -1054,6 +1314,20 @@
"url": "https://dotenvx.com"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"dev": true,
"license": "MIT"
},
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"dev": true,
"license": "MIT"
},
"node_modules/es-module-lexer": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
@@ -1123,6 +1397,23 @@
"node": ">=12.0.0"
}
},
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
"dev": true,
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
"signal-exit": "^4.0.1"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -1160,6 +1451,78 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/glob": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
"dev": true,
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
"jackspeak": "^3.1.2",
"minimatch": "^9.0.4",
"minipass": "^7.1.2",
"package-json-from-dist": "^1.0.0",
"path-scurry": "^1.11.1"
},
"bin": {
"glob": "dist/esm/bin.mjs"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/glob/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
"integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/glob/node_modules/minimatch": {
"version": "9.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.2"
},
"engines": {
"node": ">=16 || 14 >=14.17"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
@@ -1176,12 +1539,99 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
"license": "MIT"
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-source-maps": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz",
"integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.23",
"debug": "^4.1.1",
"istanbul-lib-coverage": "^3.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
"integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^8.0.2"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"optionalDependencies": {
"@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
@@ -1195,6 +1645,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"dev": true,
"license": "ISC"
},
"node_modules/lru.min": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz",
@@ -1220,6 +1677,60 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz",
"integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.25.4",
"@babel/types": "^7.25.4",
"source-map-js": "^1.2.0"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"brace-expansion": "^5.0.5"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minipass": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -1280,6 +1791,40 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^10.2.0",
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
},
"engines": {
"node": ">=16 || 14 >=14.18"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/pathe": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
@@ -1394,6 +1939,42 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -1401,6 +1982,19 @@
"dev": true,
"license": "ISC"
},
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -1440,6 +2034,138 @@
"dev": true,
"license": "MIT"
},
"node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"eastasianwidth": "^0.2.0",
"emoji-regex": "^9.2.2",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/string-width-cjs": {
"name": "string-width",
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/string-width-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/string-width-cjs/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width-cjs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.2.2"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/strip-ansi-cjs": {
"name": "strip-ansi",
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/test-exclude": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz",
"integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==",
"dev": true,
"license": "ISC",
"dependencies": {
"@istanbuljs/schema": "^0.1.2",
"glob": "^10.4.1",
"minimatch": "^10.2.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -2103,6 +2829,22 @@
}
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -2119,6 +2861,104 @@
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.1.0",
"string-width": "^5.0.1",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs": {
"name": "wrap-ansi",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi-cjs/node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/wrap-ansi-cjs/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/wrap-ansi-cjs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
}
}
}
+4 -1
View File
@@ -9,7 +9,9 @@
"build": "tsc",
"start": "node dist/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run"
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"dotenv": "^16.4.5",
@@ -17,6 +19,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
+124
View File
@@ -0,0 +1,124 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { loadEnv } from "./loadEnv.js";
const REQUIRED_ENV = {
DATABASE_URL: "mysql://user:pass@localhost:3306/errors",
INGEST_BASE_URL: "http://ingest-api:3041",
};
function setEnv(vars: Record<string, string | undefined>): void {
for (const [key, value] of Object.entries(vars)) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
describe("loadEnv() — collector-worker", () => {
const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
// Save and set required vars
for (const key of Object.keys(REQUIRED_ENV)) {
savedEnv[key] = process.env[key];
}
setEnv(REQUIRED_ENV);
});
afterEach(() => {
setEnv(savedEnv);
});
it("returns defaults when optional vars are absent", () => {
setEnv({
HTTP_FETCH_TIMEOUT_MS: undefined,
INGEST_PUSH_TIMEOUT_MS: undefined,
INGEST_PUSH_MAX_RETRIES: undefined,
INGEST_PUSH_RETRY_BASE_MS: undefined,
INGEST_PUSH_RETRY_MAX_JITTER_MS: undefined,
TICK_INTERVAL_MS: undefined,
SOURCE_REFRESH_MS: undefined,
MAX_BACKOFF_EXPONENT: undefined,
});
const env = loadEnv();
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(30_000);
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(60_000);
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(3);
expect(env.INGEST_PUSH_RETRY_BASE_MS).toBe(500);
expect(env.INGEST_PUSH_RETRY_MAX_JITTER_MS).toBe(250);
expect(env.TICK_INTERVAL_MS).toBe(2000);
expect(env.SOURCE_REFRESH_MS).toBe(10_000);
expect(env.MAX_BACKOFF_EXPONENT).toBe(8);
});
it("trims and returns DATABASE_URL", () => {
setEnv({ DATABASE_URL: " mysql://trimmed:pass@host/db " });
const env = loadEnv();
expect(env.DATABASE_URL).toBe("mysql://trimmed:pass@host/db");
});
it("trims trailing slash from INGEST_BASE_URL", () => {
setEnv({ INGEST_BASE_URL: "http://ingest-api:3041/" });
const env = loadEnv();
expect(env.INGEST_BASE_URL).toBe("http://ingest-api:3041");
});
it("throws when DATABASE_URL is missing", () => {
setEnv({ DATABASE_URL: undefined });
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
});
it("throws when DATABASE_URL is blank", () => {
setEnv({ DATABASE_URL: " " });
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
});
it("throws when INGEST_BASE_URL is missing", () => {
setEnv({ INGEST_BASE_URL: undefined });
expect(() => loadEnv()).toThrow("INGEST_BASE_URL is required");
});
it("parses custom integer values", () => {
setEnv({
HTTP_FETCH_TIMEOUT_MS: "15000",
INGEST_PUSH_TIMEOUT_MS: "45000",
INGEST_PUSH_MAX_RETRIES: "5",
TICK_INTERVAL_MS: "3000",
MAX_BACKOFF_EXPONENT: "6",
});
const env = loadEnv();
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(15000);
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(45000);
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(5);
expect(env.TICK_INTERVAL_MS).toBe(3000);
expect(env.MAX_BACKOFF_EXPONENT).toBe(6);
});
it("clamps INGEST_PUSH_TIMEOUT_MS to minimum 1000", () => {
setEnv({ INGEST_PUSH_TIMEOUT_MS: "0" });
const env = loadEnv();
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(1000);
});
it("clamps INGEST_PUSH_MAX_RETRIES to max 12", () => {
setEnv({ INGEST_PUSH_MAX_RETRIES: "20" });
const env = loadEnv();
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(12);
});
it("falls back to default for non-numeric values", () => {
setEnv({ HTTP_FETCH_TIMEOUT_MS: "not-a-number" });
const env = loadEnv();
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(30_000);
});
it("uses development as default NODE_ENV", () => {
const saved = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const env = loadEnv();
expect(env.NODE_ENV).toBe("development");
if (saved !== undefined) process.env.NODE_ENV = saved;
});
});
@@ -0,0 +1,139 @@
/**
* Tests for collectorRunWriter DB helpers.
*/
import { describe, it, expect, vi } from 'vitest';
import type { ResultSetHeader } from 'mysql2';
import {
insertRunStarted,
finishRun,
markSourceSuccess,
markSourceFailure,
} from './collectorRunWriter.js';
function makeClient(insertId: number | bigint = 42, overrides: Partial<{
execute: ReturnType<typeof vi.fn>;
}> = {}) {
return {
execute: overrides.execute ?? vi.fn().mockResolvedValue([{ insertId } as ResultSetHeader]),
};
}
function makePool() {
return {
execute: vi.fn().mockResolvedValue([{ affectedRows: 1 } as ResultSetHeader]),
};
}
describe('insertRunStarted', () => {
it('returns stringified insertId on success', async () => {
const client = makeClient(99);
const result = await insertRunStarted(client as never, {
collectorSourceId: 'src-1',
projectId: 'proj-1',
});
expect(result).toBe('99');
});
it('executes the INSERT statement with correct args', async () => {
const client = makeClient(1);
await insertRunStarted(client as never, {
collectorSourceId: 'src-abc',
projectId: 'proj-xyz',
});
expect(client.execute).toHaveBeenCalledWith(
expect.stringContaining('INSERT INTO er_collector_runs'),
['src-abc', 'proj-xyz'],
);
});
it('throws when insertId is zero', async () => {
const client = makeClient(0);
await expect(
insertRunStarted(client as never, { collectorSourceId: 's', projectId: 'p' }),
).rejects.toThrow('collector_run_insert_failed');
});
it('throws when insertId is not a number', async () => {
const client = {
execute: vi.fn().mockResolvedValue([{ insertId: undefined }]),
};
await expect(
insertRunStarted(client as never, { collectorSourceId: 's', projectId: 'p' }),
).rejects.toThrow('collector_run_insert_failed');
});
it('handles bigint insertId', async () => {
const client = makeClient(BigInt(123));
const result = await insertRunStarted(client as never, {
collectorSourceId: 's',
projectId: 'p',
});
expect(result).toBe('123');
});
});
describe('finishRun', () => {
it('executes UPDATE with all fields', async () => {
const client = { execute: vi.fn().mockResolvedValue([{}]) };
await finishRun(client as never, {
runId: '42',
status: 'success',
fetchedCount: 10,
acceptedCount: 9,
deduplicatedCount: 1,
failedCount: 0,
errorSummary: null,
});
expect(client.execute).toHaveBeenCalledWith(
expect.stringContaining('UPDATE er_collector_runs'),
['success', 10, 9, 1, 0, null, '42'],
);
});
it('accepts partial/failed status', async () => {
const client = { execute: vi.fn().mockResolvedValue([{}]) };
await finishRun(client as never, {
runId: '7',
status: 'failed',
fetchedCount: 0,
acceptedCount: 0,
deduplicatedCount: 0,
failedCount: 3,
errorSummary: 'timeout',
});
expect(client.execute).toHaveBeenCalledWith(
expect.any(String),
['failed', 0, 0, 0, 3, 'timeout', '7'],
);
});
});
describe('markSourceSuccess', () => {
it('executes UPDATE on correct table', async () => {
const pool = makePool();
await markSourceSuccess(pool as never, 'src-id-1');
expect(pool.execute).toHaveBeenCalledWith(
expect.stringContaining('UPDATE er_collector_sources'),
['src-id-1'],
);
});
});
describe('markSourceFailure', () => {
it('executes UPDATE with message and sourceId', async () => {
const pool = makePool();
await markSourceFailure(pool as never, { sourceId: 'src-2', message: 'connection refused' });
expect(pool.execute).toHaveBeenCalledWith(
expect.stringContaining('UPDATE er_collector_sources'),
['connection refused', 'src-2'],
);
});
it('truncates error message at 4000 chars', async () => {
const pool = makePool();
const longMsg = 'x'.repeat(5000);
await markSourceFailure(pool as never, { sourceId: 's', message: longMsg });
const callArgs = pool.execute.mock.calls[0] as [string, [string, string]];
expect(callArgs[1][0]).toHaveLength(4000);
});
});
@@ -0,0 +1,76 @@
/**
* Tests for loadActiveSources — DB query and row mapping.
*/
import { describe, it, expect, vi } from 'vitest';
import type { RowDataPacket } from 'mysql2';
import { loadActiveSources } from './loadActiveSources.js';
function makePool(rows: RowDataPacket[]) {
return {
execute: vi.fn().mockResolvedValue([rows]),
};
}
const dbRow = (overrides: Partial<RowDataPacket> = {}): RowDataPacket =>
({
id: '1',
project_id: '42',
name: 'My Source',
source_type: 'http_poll',
endpoint_uri: 'https://example.com/events',
auth_secret_ref: 'secret/token',
poll_interval_seconds: '30',
...overrides,
}) as RowDataPacket;
describe('loadActiveSources', () => {
it('returns empty array when no rows', async () => {
const pool = makePool([]);
const result = await loadActiveSources(pool as never);
expect(result).toHaveLength(0);
});
it('maps DB row fields to CollectorSourceRow', async () => {
const pool = makePool([dbRow()]);
const [source] = await loadActiveSources(pool as never);
expect(source.id).toBe('1');
expect(source.project_id).toBe('42');
expect(source.name).toBe('My Source');
expect(source.source_type).toBe('http_poll');
expect(source.endpoint_uri).toBe('https://example.com/events');
expect(source.auth_secret_ref).toBe('secret/token');
expect(source.poll_interval_seconds).toBe(30);
});
it('parses poll_interval_seconds as integer', async () => {
const pool = makePool([dbRow({ poll_interval_seconds: '60' })]);
const [source] = await loadActiveSources(pool as never);
expect(source.poll_interval_seconds).toBe(60);
expect(typeof source.poll_interval_seconds).toBe('number');
});
it('preserves null auth_secret_ref', async () => {
const pool = makePool([dbRow({ auth_secret_ref: null })]);
const [source] = await loadActiveSources(pool as never);
expect(source.auth_secret_ref).toBeNull();
});
it('maps multiple rows', async () => {
const pool = makePool([
dbRow({ id: '1', name: 'Source A' }),
dbRow({ id: '2', name: 'Source B' }),
]);
const result = await loadActiveSources(pool as never);
expect(result).toHaveLength(2);
expect(result[0].name).toBe('Source A');
expect(result[1].name).toBe('Source B');
});
it('queries only active sources', async () => {
const pool = makePool([]);
await loadActiveSources(pool as never);
expect(pool.execute).toHaveBeenCalledWith(
expect.stringContaining('is_active = TRUE'),
);
});
});
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { logInfo, logWarn, logError } from "./structuredLog.js";
describe("structuredLog", () => {
let consoleLogs: string[];
let consoleWarns: string[];
let consoleErrors: string[];
beforeEach(() => {
consoleLogs = [];
consoleWarns = [];
consoleErrors = [];
vi.spyOn(console, "log").mockImplementation((msg: string) => { consoleLogs.push(msg); });
vi.spyOn(console, "warn").mockImplementation((msg: string) => { consoleWarns.push(msg); });
vi.spyOn(console, "error").mockImplementation((msg: string) => { consoleErrors.push(msg); });
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("logInfo()", () => {
it("writes to console.log with level=info", () => {
logInfo({ msg: "test info" });
expect(consoleLogs).toHaveLength(1);
const parsed = JSON.parse(consoleLogs[0]);
expect(parsed.level).toBe("info");
});
it("includes the msg field", () => {
logInfo({ msg: "hello world" });
const parsed = JSON.parse(consoleLogs[0]);
expect(parsed.msg).toBe("hello world");
});
it("includes a ts field that is a valid ISO string", () => {
logInfo({ msg: "ts test" });
const parsed = JSON.parse(consoleLogs[0]);
expect(parsed.ts).toBeDefined();
expect(() => new Date(parsed.ts)).not.toThrow();
expect(Number.isFinite(new Date(parsed.ts).getTime())).toBe(true);
});
it("passes through extra fields", () => {
logInfo({ msg: "with extras", sourceId: "src-1", eventCount: 5 });
const parsed = JSON.parse(consoleLogs[0]);
expect(parsed.sourceId).toBe("src-1");
expect(parsed.eventCount).toBe(5);
});
it("does not write to console.warn or console.error", () => {
logInfo({ msg: "info only" });
expect(consoleWarns).toHaveLength(0);
expect(consoleErrors).toHaveLength(0);
});
});
describe("logWarn()", () => {
it("writes to console.warn with level=warn", () => {
logWarn({ msg: "watch out" });
expect(consoleWarns).toHaveLength(1);
const parsed = JSON.parse(consoleWarns[0]);
expect(parsed.level).toBe("warn");
expect(parsed.msg).toBe("watch out");
});
it("includes ts field", () => {
logWarn({ msg: "ts check" });
const parsed = JSON.parse(consoleWarns[0]);
expect(parsed.ts).toBeDefined();
});
it("does not write to console.log", () => {
logWarn({ msg: "warn only" });
expect(consoleLogs).toHaveLength(0);
});
});
describe("logError()", () => {
it("writes to console.error with level=error", () => {
logError({ msg: "something broke" });
expect(consoleErrors).toHaveLength(1);
const parsed = JSON.parse(consoleErrors[0]);
expect(parsed.level).toBe("error");
expect(parsed.msg).toBe("something broke");
});
it("includes ts field", () => {
logError({ msg: "error ts" });
const parsed = JSON.parse(consoleErrors[0]);
expect(parsed.ts).toBeDefined();
});
it("passes through extra fields like error messages", () => {
logError({ msg: "db failed", err: "ECONNREFUSED", code: 500 });
const parsed = JSON.parse(consoleErrors[0]);
expect(parsed.err).toBe("ECONNREFUSED");
expect(parsed.code).toBe(500);
});
it("does not write to console.log or console.warn", () => {
logError({ msg: "error only" });
expect(consoleLogs).toHaveLength(0);
expect(consoleWarns).toHaveLength(0);
});
});
});
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { fetchHttpPollEvents } from "./fetchHttpEvents.js";
import type { IngestEventInput } from "../types/ingest.js";
function makeValidEvent(overrides: Partial<IngestEventInput> = {}): IngestEventInput {
return {
schema_version: 1,
occurred_at: "2026-01-01T00:00:00Z",
level: "error",
message: "Test error",
...overrides,
};
}
function mockFetch(response: { ok: boolean; status?: number; body?: unknown }): void {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: response.ok,
status: response.status ?? (response.ok ? 200 : 500),
text: vi.fn().mockResolvedValue(
typeof response.body === "string" ? response.body : JSON.stringify(response.body),
),
}));
}
const INPUT = { endpointUri: "http://example.com/events", timeoutMs: 5000 };
describe("fetchHttpPollEvents()", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
it("returns ok=true with parsed events for a valid response", async () => {
const events = [makeValidEvent()];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.events).toHaveLength(1);
expect(result.events[0].message).toBe("Test error");
}
});
it("returns ok=false with http_status_* on non-OK HTTP response", async () => {
mockFetch({ ok: false, status: 503 });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("http_status_503");
}
});
it("returns ok=false with invalid_json when body is not JSON", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
status: 200,
text: vi.fn().mockResolvedValue("not-json{{{"),
}));
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_json");
}
});
it("returns ok=false with expected_json_object when body is a JSON array", async () => {
mockFetch({ ok: true, body: [1, 2, 3] });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("expected_json_object");
}
});
it("returns ok=false with missing_events_array when events key is absent", async () => {
mockFetch({ ok: true, body: { data: [] } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("missing_events_array");
}
});
it("returns ok=false with missing_events_array when events is not an array", async () => {
mockFetch({ ok: true, body: { events: "not-array" } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("missing_events_array");
}
});
it("returns ok=false with too_many_events_max_50 when events > 50", async () => {
const events = Array.from({ length: 51 }, () => makeValidEvent());
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("too_many_events_max_50");
}
});
it("returns ok=true with exactly 50 events", async () => {
const events = Array.from({ length: 50 }, () => makeValidEvent());
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.events).toHaveLength(50);
}
});
it("returns ok=false with invalid_event_shape when event is missing schema_version", async () => {
const events = [{ occurred_at: "2026-01-01T00:00:00Z", level: "error", message: "Test" }];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_event_shape");
}
});
it("returns ok=false with invalid_event_shape when event has wrong schema_version", async () => {
const events = [{ ...makeValidEvent(), schema_version: 2 }];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_event_shape");
}
});
it("returns ok=false with invalid_event_shape when level is empty", async () => {
const events = [makeValidEvent({ level: " " })];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_event_shape");
}
});
it("returns ok=false with invalid_event_shape when message is empty", async () => {
const events = [makeValidEvent({ message: "" })];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_event_shape");
}
});
it("returns ok=false with invalid_event_shape when occurred_at is missing", async () => {
const events = [{ schema_version: 1, level: "error", message: "Test" }];
mockFetch({ ok: true, body: { events } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("invalid_event_shape");
}
});
it("returns ok=true with empty events array", async () => {
mockFetch({ ok: true, body: { events: [] } });
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.events).toHaveLength(0);
}
});
it("returns ok=false with fetch_timeout when aborted", async () => {
vi.stubGlobal("fetch", vi.fn().mockImplementation(() =>
new Promise((_, reject) => {
const err = new Error("The operation was aborted");
err.name = "AbortError";
setTimeout(() => reject(err), 100);
}),
));
const resultPromise = fetchHttpPollEvents({ endpointUri: "http://example.com", timeoutMs: 50 });
vi.advanceTimersByTime(200);
const result = await resultPromise;
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("fetch_timeout");
}
});
it("returns ok=false with error message on generic network error", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
const result = await fetchHttpPollEvents(INPUT);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe("ECONNREFUSED");
}
});
});
@@ -0,0 +1,223 @@
/**
* Unit tests for runHttpSourceOnce — covers the main state machine paths
* without network or DB access.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { runHttpSourceOnce } from './runHttpSourceOnce.js';
import type { SourceRuntimeState } from './sourceState.js';
import type { CollectorSourceRow } from '../types/ingest.js';
vi.mock('../auth/resolveSecret.js', () => ({
resolveIngestToken: vi.fn(),
}));
vi.mock('../db/collectorRunWriter.js', () => ({
insertRunStarted: vi.fn(),
finishRun: vi.fn(),
markSourceSuccess: vi.fn(),
markSourceFailure: vi.fn(),
}));
vi.mock('../poll/fetchHttpEvents.js', () => ({
fetchHttpPollEvents: vi.fn(),
}));
vi.mock('../ingest/pushEvents.js', () => ({
pushEventsToIngest: vi.fn(),
}));
vi.mock('../log/structuredLog.js', () => ({
logInfo: vi.fn(),
logError: vi.fn(),
}));
import { resolveIngestToken } from '../auth/resolveSecret.js';
import {
insertRunStarted,
finishRun,
markSourceSuccess,
markSourceFailure,
} from '../db/collectorRunWriter.js';
import { fetchHttpPollEvents } from '../poll/fetchHttpEvents.js';
import { pushEventsToIngest } from '../ingest/pushEvents.js';
const mockInsertRunStarted = vi.mocked(insertRunStarted);
const mockFetchHttpPollEvents = vi.mocked(fetchHttpPollEvents);
const mockResolveIngestToken = vi.mocked(resolveIngestToken);
const mockPushEventsToIngest = vi.mocked(pushEventsToIngest);
const mockMarkSourceSuccess = vi.mocked(markSourceSuccess);
const mockMarkSourceFailure = vi.mocked(markSourceFailure);
const mockFinishRun = vi.mocked(finishRun);
function makeClient() {
return {
beginTransaction: vi.fn().mockResolvedValue(undefined),
execute: vi.fn().mockResolvedValue([{ insertId: 1 }]),
commit: vi.fn().mockResolvedValue(undefined),
rollback: vi.fn().mockResolvedValue(undefined),
release: vi.fn(),
};
}
function makePool() {
const client = makeClient();
return {
_client: client,
execute: vi.fn().mockResolvedValue([{ affectedRows: 1 }]),
getConnection: vi.fn().mockResolvedValue(client),
};
}
const baseEnv = {
HTTP_FETCH_TIMEOUT_MS: 10000,
INGEST_BASE_URL: 'http://ingest.local',
INGEST_PUSH_TIMEOUT_MS: 10000,
INGEST_PUSH_MAX_RETRIES: 2,
INGEST_PUSH_RETRY_BASE_MS: 100,
INGEST_PUSH_RETRY_MAX_JITTER_MS: 50,
MAX_BACKOFF_EXPONENT: 6,
INGEST_RATE_LIMIT_MAX: 500,
INGEST_RATE_LIMIT_WINDOW_MS: 60000,
INGEST_ANON_IP_MAX: 20,
INGEST_ANON_IP_WINDOW_MS: 60000,
NODE_ENV: 'test',
};
const baseSource: CollectorSourceRow = {
id: 'src-1',
project_id: 'proj-1',
name: 'Test Source',
source_type: 'http_poll',
endpoint_uri: 'https://example.com/events',
auth_secret_ref: 'secret/token',
poll_interval_seconds: 60,
};
function makeState(): SourceRuntimeState {
return { consecutiveFailures: 0, nextAtMs: 0 };
}
beforeEach(() => {
vi.clearAllMocks();
mockInsertRunStarted.mockResolvedValue('run-42');
});
describe('runHttpSourceOnce — run start failure', () => {
it('marks failure and increments consecutiveFailures when DB insert throws', async () => {
const pool = makePool();
pool._client.commit.mockRejectedValue(new Error('DB down'));
mockInsertRunStarted.mockRejectedValue(new Error('DB down'));
const state = makeState();
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(1);
expect(mockMarkSourceFailure).toHaveBeenCalledWith(pool, {
sourceId: 'src-1',
message: 'DB down',
});
});
});
describe('runHttpSourceOnce — fetch failure', () => {
it('increments failure count and marks source failure when HTTP fetch fails', async () => {
const pool = makePool();
mockFetchHttpPollEvents.mockResolvedValue({ ok: false, error: 'connection refused' });
const state = makeState();
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(1);
expect(mockMarkSourceFailure).toHaveBeenCalledWith(pool, {
sourceId: 'src-1',
message: 'connection refused',
});
});
});
describe('runHttpSourceOnce — missing token', () => {
it('marks failure when ingest token cannot be resolved', async () => {
const pool = makePool();
mockFetchHttpPollEvents.mockResolvedValue({
ok: true,
events: [{ schema_version: 1, occurred_at: '2026-01-01T00:00:00Z', level: 'error', message: 'err' }],
});
mockResolveIngestToken.mockReturnValue(null);
const state = makeState();
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(1);
expect(mockMarkSourceFailure).toHaveBeenCalledWith(pool, {
sourceId: 'src-1',
message: 'missing_ingest_token',
});
});
});
describe('runHttpSourceOnce — empty events', () => {
it('marks success and resets consecutiveFailures when fetch returns 0 events', async () => {
const pool = makePool();
mockFetchHttpPollEvents.mockResolvedValue({ ok: true, events: [] });
mockResolveIngestToken.mockReturnValue('test-token');
const state = makeState();
state.consecutiveFailures = 3;
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(0);
expect(mockMarkSourceSuccess).toHaveBeenCalledWith(pool, 'src-1');
expect(mockFinishRun).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ status: 'success', fetchedCount: 0 }),
);
});
});
describe('runHttpSourceOnce — push failure', () => {
it('marks failure when push to ingest API fails', async () => {
const pool = makePool();
const events = [
{ schema_version: 1, occurred_at: '2026-01-01T00:00:00Z', level: 'error', message: 'e1' },
];
mockFetchHttpPollEvents.mockResolvedValue({ ok: true, events });
mockResolveIngestToken.mockReturnValue('test-token');
mockPushEventsToIngest.mockResolvedValue({
ok: false,
error: 'HTTP 503',
status: 503,
attempts: 3,
});
const state = makeState();
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(1);
expect(mockMarkSourceFailure).toHaveBeenCalledWith(pool, {
sourceId: 'src-1',
message: 'HTTP 503',
});
});
});
describe('runHttpSourceOnce — success path', () => {
it('marks success and resets state when events are fetched and pushed', async () => {
const pool = makePool();
const events = [
{ schema_version: 1, occurred_at: '2026-01-01T00:00:00Z', level: 'error', message: 'e1' },
{ schema_version: 1, occurred_at: '2026-01-01T01:00:00Z', level: 'warn', message: 'e2' },
];
mockFetchHttpPollEvents.mockResolvedValue({ ok: true, events });
mockResolveIngestToken.mockReturnValue('test-token');
mockPushEventsToIngest.mockResolvedValue({ ok: true, accepted: 2, attempts: 1 });
const state = makeState();
state.consecutiveFailures = 2;
await runHttpSourceOnce({ pool: pool as never, env: baseEnv as never, source: baseSource, state });
expect(state.consecutiveFailures).toBe(0);
expect(mockMarkSourceSuccess).toHaveBeenCalledWith(pool, 'src-1');
expect(mockFinishRun).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ status: 'success', fetchedCount: 2, acceptedCount: 2 }),
);
});
});
+6
View File
@@ -4,5 +4,11 @@ export default defineConfig({
test: {
environment: "node",
include: ["src/**/*.test.ts"],
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
include: ["src/**/*.ts"],
exclude: ["src/**/*.test.ts", "**/*.d.ts"],
},
},
});
+567
View File
@@ -0,0 +1,567 @@
{
"__inputs": [
{
"name": "DS_LOKI",
"label": "Loki",
"description": "Loki log aggregation datasource",
"type": "datasource",
"pluginId": "loki",
"pluginName": "Loki"
}
],
"__requires": [
{
"type": "grafana",
"id": "grafana",
"name": "Grafana",
"version": "10.0.0"
},
{
"type": "datasource",
"id": "loki",
"name": "Loki",
"version": "1.0.0"
},
{
"type": "panel",
"id": "logs",
"name": "Logs",
"version": ""
},
{
"type": "panel",
"id": "timeseries",
"name": "Time series",
"version": ""
},
{
"type": "panel",
"id": "stat",
"name": "Stat",
"version": ""
},
{
"type": "panel",
"id": "piechart",
"name": "Pie chart",
"version": ""
}
],
"annotations": {
"list": []
},
"description": "Centralised log view for all errors.bitreport.pt services via Loki. Docs: docs/OBSERVABILITY_LOKI.md",
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [
{
"icon": "external link",
"title": "Error Monitoring SLO",
"tooltip": "Prometheus operational dashboard",
"type": "link",
"url": "/d/er-ops-slo"
}
],
"panels": [
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },
"id": 100,
"title": "Overview",
"type": "row"
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "thresholds" },
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 1 },
{ "color": "red", "value": 10 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 4, "w": 4, "x": 0, "y": 1 },
"id": 1,
"options": {
"colorMode": "background",
"graphMode": "none",
"justifyMode": "center",
"orientation": "auto",
"reduceOptions": { "calcs": ["sum"], "fields": "", "values": false },
"textMode": "auto"
},
"title": "Errors (window)",
"type": "stat",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum(count_over_time({app=\"errors-hub\", level=\"error\"}[$__range]))",
"legendFormat": "errors",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "thresholds" },
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "red", "value": 1 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 4, "w": 4, "x": 4, "y": 1 },
"id": 2,
"options": {
"colorMode": "background",
"graphMode": "none",
"justifyMode": "center",
"orientation": "auto",
"reduceOptions": { "calcs": ["sum"], "fields": "", "values": false },
"textMode": "auto"
},
"title": "Fatals (window)",
"type": "stat",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum(count_over_time({app=\"errors-hub\", level=\"fatal\"}[$__range]))",
"legendFormat": "fatals",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "thresholds" },
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 50 },
{ "color": "red", "value": 200 }
]
},
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 4, "w": 4, "x": 8, "y": 1 },
"id": 3,
"options": {
"colorMode": "value",
"graphMode": "none",
"justifyMode": "center",
"orientation": "auto",
"reduceOptions": { "calcs": ["sum"], "fields": "", "values": false },
"textMode": "auto"
},
"title": "Warnings (window)",
"type": "stat",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum(count_over_time({app=\"errors-hub\", level=\"warn\"}[$__range]))",
"legendFormat": "warnings",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"hideFrom": { "legend": false, "tooltip": false, "viz": false }
}
},
"overrides": []
},
"gridPos": { "h": 4, "w": 12, "x": 12, "y": 1 },
"id": 4,
"options": {
"displayLabels": ["name", "percent"],
"legend": { "displayMode": "table", "placement": "right", "values": ["value"] },
"pieType": "donut",
"tooltip": { "mode": "single", "sort": "none" }
},
"title": "Log volume by level (window)",
"type": "piechart",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum by (level) (count_over_time({app=\"errors-hub\"}[$__range]))",
"legendFormat": "{{level}}",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 5 },
"id": 101,
"title": "Log Rate",
"type": "row"
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "lines/s",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "bars",
"fillOpacity": 70,
"gradientMode": "none",
"hideFrom": { "legend": false, "tooltip": false, "viz": false },
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": { "type": "linear" },
"showPoints": "never",
"spanNulls": false,
"stacking": { "group": "A", "mode": "normal" },
"thresholdsStyle": { "mode": "off" }
},
"mappings": [],
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": [
{ "matcher": { "id": "byName", "options": "error" }, "properties": [{ "id": "color", "value": { "fixedColor": "red", "mode": "fixed" } }] },
{ "matcher": { "id": "byName", "options": "fatal" }, "properties": [{ "id": "color", "value": { "fixedColor": "dark-red", "mode": "fixed" } }] },
{ "matcher": { "id": "byName", "options": "warn" }, "properties": [{ "id": "color", "value": { "fixedColor": "orange", "mode": "fixed" } }] },
{ "matcher": { "id": "byName", "options": "info" }, "properties": [{ "id": "color", "value": { "fixedColor": "blue", "mode": "fixed" } }] }
]
},
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 6 },
"id": 10,
"options": {
"legend": { "calcs": ["sum"], "displayMode": "table", "placement": "bottom", "showLegend": true },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Log rate by level",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum by (level) (rate({app=\"errors-hub\"}[2m]))",
"legendFormat": "{{level}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "lines/s",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "bars",
"fillOpacity": 70,
"gradientMode": "none",
"hideFrom": { "legend": false, "tooltip": false, "viz": false },
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": { "type": "linear" },
"showPoints": "never",
"spanNulls": false,
"stacking": { "group": "A", "mode": "normal" },
"thresholdsStyle": { "mode": "off" }
},
"mappings": [],
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 6 },
"id": 11,
"options": {
"legend": { "calcs": ["sum"], "displayMode": "table", "placement": "bottom", "showLegend": true },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Log rate by service",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum by (service) (rate({app=\"errors-hub\"}[2m]))",
"legendFormat": "{{service}}",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"fieldConfig": {
"defaults": {
"color": { "mode": "palette-classic" },
"custom": {
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "errors/s",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "bars",
"fillOpacity": 70,
"gradientMode": "none",
"hideFrom": { "legend": false, "tooltip": false, "viz": false },
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": { "type": "linear" },
"showPoints": "never",
"spanNulls": false,
"stacking": { "group": "A", "mode": "normal" },
"thresholdsStyle": { "mode": "off" }
},
"mappings": [],
"thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 0.01 }] },
"unit": "short"
},
"overrides": []
},
"gridPos": { "h": 8, "w": 24, "x": 0, "y": 14 },
"id": 12,
"options": {
"legend": { "calcs": ["max", "sum"], "displayMode": "table", "placement": "bottom", "showLegend": true },
"tooltip": { "mode": "multi", "sort": "desc" }
},
"title": "Error + Fatal rate by service",
"type": "timeseries",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "sum by (service) (rate({app=\"errors-hub\", level=~\"error|fatal\"}[2m]))",
"legendFormat": "{{service}}",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 22 },
"id": 102,
"title": "Error & Fatal Logs",
"type": "row"
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"gridPos": { "h": 14, "w": 24, "x": 0, "y": 23 },
"id": 20,
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"prettifyLogMessage": false,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": true
},
"title": "Errors & Fatals — all services",
"type": "logs",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "{app=\"errors-hub\", level=~\"error|fatal\"} | json",
"legendFormat": "",
"refId": "A"
}
]
},
{
"collapsed": false,
"gridPos": { "h": 1, "w": 24, "x": 0, "y": 37 },
"id": 103,
"title": "Service Logs",
"type": "row"
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"gridPos": { "h": 10, "w": 12, "x": 0, "y": 38 },
"id": 30,
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"prettifyLogMessage": false,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
},
"title": "ingest-api logs",
"type": "logs",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "{app=\"errors-hub\", service=\"ingest-api\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"",
"legendFormat": "",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"gridPos": { "h": 10, "w": 12, "x": 12, "y": 38 },
"id": 31,
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"prettifyLogMessage": false,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
},
"title": "collector-worker logs",
"type": "logs",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "{app=\"errors-hub\", service=\"collector-worker\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"",
"legendFormat": "",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"gridPos": { "h": 10, "w": 12, "x": 0, "y": 48 },
"id": 32,
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"prettifyLogMessage": false,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
},
"title": "admin-ui logs",
"type": "logs",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "{app=\"errors-hub\", service=\"admin-ui\"} | json",
"legendFormat": "",
"refId": "A"
}
]
},
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"gridPos": { "h": 10, "w": 12, "x": 12, "y": 48 },
"id": 33,
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"prettifyLogMessage": false,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
},
"title": "api logs",
"type": "logs",
"targets": [
{
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"expr": "{app=\"errors-hub\", service=\"api\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"",
"legendFormat": "",
"refId": "A"
}
]
}
],
"refresh": "30s",
"schemaVersion": 38,
"tags": ["bitreport", "loki", "logs"],
"templating": {
"list": [
{
"current": {},
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"definition": "label_values({app=\"errors-hub\"}, service)",
"hide": 0,
"includeAll": true,
"multi": true,
"name": "service",
"options": [],
"query": {
"label": "service",
"refId": "LokiVariableQueryEditor-VariableQuery",
"stream": "{app=\"errors-hub\"}",
"type": 1
},
"refresh": 2,
"sort": 1,
"type": "query",
"label": "Service"
},
{
"current": { "selected": false, "text": "All", "value": "$__all" },
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
"definition": "label_values({app=\"errors-hub\"}, level)",
"hide": 0,
"includeAll": true,
"multi": true,
"name": "level",
"options": [],
"query": {
"label": "level",
"refId": "LokiVariableQueryEditor-VariableQuery",
"stream": "{app=\"errors-hub\"}",
"type": 1
},
"refresh": 2,
"sort": 1,
"type": "query",
"label": "Level"
}
]
},
"time": { "from": "now-1h", "to": "now" },
"timepicker": {},
"timezone": "browser",
"title": "BitReport — Loki Logs",
"uid": "er-loki-logs",
"version": 1
}
+63
View File
@@ -0,0 +1,63 @@
# Loki configuration for errors.bitreport.pt log aggregation.
# Docs: docs/OBSERVABILITY_LOKI.md
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
query_range:
results_cache:
cache:
embedded_cache:
enabled: true
max_size_mb: 100
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
ruler:
alertmanager_url: http://localhost:9093
storage:
type: local
local:
directory: /loki/rules
rule_path: /tmp/loki-ruler-tmp
enable_api: true
enable_alertmanager_v2: true
limits_config:
retention_period: 30d
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
max_cache_freshness_per_query: 10m
reject_old_samples: true
reject_old_samples_max_age: 168h
compactor:
working_directory: /loki/compactor
retention_enabled: true
retention_delete_delay: 2h
retention_delete_worker_count: 150
delete_request_store: filesystem
+79
View File
@@ -0,0 +1,79 @@
# Promtail configuration for errors.bitreport.pt — native LXC/systemd deployment.
# Reads logs from the systemd journal (no Docker socket needed).
# Ships to a central Loki instance; set LOKI_PUSH_URL in the systemd unit environment.
# Start promtail with: promtail -config.file=... -config.expand-env=true
# Docs: docs/deployment/loki-lxc-runbook.md, docs/OBSERVABILITY_LOKI.md
server:
# Bind only to loopback — no external exposure from the app LXC.
http_listen_address: 127.0.0.1
http_listen_port: 9080
grpc_listen_port: 0
log_level: warn
positions:
filename: /var/lib/promtail/positions.yaml
clients:
- url: ${LOKI_PUSH_URL}
backoff_config:
min_period: 500ms
max_period: 5m
max_retries: 10
scrape_configs:
# ── errors-hub services (systemd journal) ──────────────────────────────────
- job_name: errors-hub-journal
journal:
json: false
max_age: 12h
# Path to journal; /var/log/journal if persistent logging is enabled,
# otherwise /run/log/journal (volatile, cleared on reboot).
path: /var/log/journal
labels:
app: errors-hub
env: production
relabel_configs:
# Only keep journal entries from the four bitreport-error-reporting units.
- source_labels: [__journal__systemd_unit]
regex: "bitreport-error-reporting-(.+)\\.service"
action: keep
# Extract service name: "bitreport-error-reporting-ingest-api.service" → "ingest-api"
- source_labels: [__journal__systemd_unit]
regex: "bitreport-error-reporting-(.+)\\.service"
replacement: "$1"
target_label: service
pipeline_stages:
# ── Attempt JSON parse (Pino / structured logs) ───────────────────────
- json:
expressions:
pino_level: level
log_msg: msg
log_err: err
# ── Normalize Pino numeric levels to human-readable strings ───────────
# Pino: 10=trace 20=debug 30=info 40=warn 50=error 60=fatal
- template:
source: pino_level
template: |
{{ if eq .Value "10" }}trace
{{- else if eq .Value "20" }}debug
{{- else if eq .Value "30" }}info
{{- else if eq .Value "40" }}warn
{{- else if eq .Value "50" }}error
{{- else if eq .Value "60" }}fatal
{{- else }}{{ .Value }}
{{- end }}
# Promote the normalised level to a Loki label (low-cardinality).
- labels:
level: pino_level
# ── Drop trace/debug in production ────────────────────────────────────
- match:
selector: '{level=~"trace|debug"}'
action: drop
drop_counter_reason: below_min_level
+82
View File
@@ -0,0 +1,82 @@
# Promtail configuration for errors.bitreport.pt log shipping.
# Discovers Docker containers by compose service name, parses structured JSON logs,
# and ships to the Loki instance in the same Docker network.
# Docs: docs/OBSERVABILITY_LOKI.md
server:
http_listen_port: 9080
grpc_listen_port: 0
log_level: warn
positions:
filename: /run/promtail/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
backoff_config:
min_period: 500ms
max_period: 5m
max_retries: 10
scrape_configs:
# --- errors-hub services (Docker Compose auto-discovery) ---
- job_name: errors-hub-docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 10s
filters:
# Only scrape containers that belong to this compose project.
- name: label
values: ["com.docker.compose.project=errors-bitreport-pt"]
relabel_configs:
# Map compose service name → `service` label
- source_labels: [__meta_docker_container_label_com_docker_compose_service]
target_label: service
# Compose project → `compose_project`
- source_labels: [__meta_docker_container_label_com_docker_compose_project]
target_label: compose_project
# Container name for uniqueness
- source_labels: [__meta_docker_container_name]
regex: "/(.*)"
target_label: container
# Static labels for every log line from this hub
- replacement: errors-hub
target_label: app
- replacement: production
target_label: env
pipeline_stages:
# ── Attempt JSON parse ──────────────────────────────────────────────
- json:
expressions:
# Pino uses a numeric `level` (30=info, 40=warn, 50=error)
# Collector-worker uses a string `level` ("info"/"warn"/"error")
pino_level: level
log_msg: msg
log_err: err
log_pid: pid
# ── Normalize Pino numeric levels to strings ────────────────────────
# Pino: 10=trace 20=debug 30=info 40=warn 50=error 60=fatal
- template:
source: pino_level
template: |
{{ if eq .Value "10" }}trace
{{- else if eq .Value "20" }}debug
{{- else if eq .Value "30" }}info
{{- else if eq .Value "40" }}warn
{{- else if eq .Value "50" }}error
{{- else if eq .Value "60" }}fatal
{{- else }}{{ .Value }}
{{- end }}
# Promote the normalized level to a Loki label (low-cardinality)
- labels:
level: pino_level
# ── Drop noisy debug/trace in production ────────────────────────────
- match:
selector: '{level=~"trace|debug"}'
action: drop
drop_counter_reason: below_min_level
@@ -0,0 +1,79 @@
# Loki ruler alert rules — errors.bitreport.pt (errors-hub)
# Tenant: fake (auth_enabled: false single-binary)
# Labels app="errors-hub", env="production" are set by promtail (both Docker and LXC configs).
# Service label values: ingest-api, api, collector-worker, admin-ui, web
# Docs: docs/OBSERVABILITY_LOKI.md
groups:
- name: errors_hub_log_alerts
interval: 1m
rules:
# ── Error rate per service ─────────────────────────────────────────────
- alert: ErrorsHubServiceErrorRateHigh
expr: |
sum by (service) (
rate({app="errors-hub", level="error"}[5m])
) > 0.1
for: 5m
labels:
severity: warning
team: observability
app: errors-hub
annotations:
summary: "High error log rate on {{ $labels.service }}"
description: >
Service {{ $labels.service }} is emitting error-level logs at
{{ $value | printf "%.2f" }} lines/s (threshold 0.1/s, 5m window).
Check service health; run: docker compose logs {{ $labels.service }} --tail=100
# ── Fatal log detected ─────────────────────────────────────────────────
- alert: ErrorsHubFatalLogDetected
expr: |
sum by (service) (
rate({app="errors-hub", level="fatal"}[5m])
) > 0
for: 1m
labels:
severity: critical
team: observability
app: errors-hub
annotations:
summary: "Fatal log in {{ $labels.service }}"
description: >
Service {{ $labels.service }} emitted at least one fatal-level log
in the last 5 minutes. Immediate investigation required.
Query: {app="errors-hub", service="{{ $labels.service }}", level="fatal"}
# ── Ingest API sustained error rate ───────────────────────────────────
- alert: ErrorsHubIngestApiHighErrorRate
expr: |
rate({app="errors-hub", service="ingest-api", level="error"}[10m]) > 0.05
for: 10m
labels:
severity: critical
team: observability
app: errors-hub
annotations:
summary: "ingest-api sustained error rate (>0.05/s for 10m)"
description: >
ingest-api is logging errors at {{ $value | printf "%.3f" }} lines/s
for 10+ minutes. This may indicate DB connection issues, schema errors,
or upstream pressure. Check: {service="ingest-api", level="error"} | json
# ── Collector worker stalled ───────────────────────────────────────────
- alert: ErrorsHubCollectorWorkerStalled
expr: |
sum(
rate({app="errors-hub", service="collector-worker"}[10m])
) == 0
for: 15m
labels:
severity: warning
team: observability
app: errors-hub
annotations:
summary: "collector-worker has no log output for 15m"
description: >
collector-worker emitted zero log lines over the last 10m window for
15+ minutes. The service may be stopped or stuck in a silent loop.
Check: docker compose ps collector-worker; systemctl status bitreport-error-reporting-collector-worker
+48
View File
@@ -0,0 +1,48 @@
# systemd unit for Promtail on the errors.bitreport.pt app LXC.
# Ships journald logs from the four bitreport-error-reporting-*.service units
# to the central Loki instance.
#
# Installation (run as root on the app LXC):
# cp this file /etc/systemd/system/bitreport-promtail.service
# systemctl daemon-reload
# systemctl enable --now bitreport-promtail.service
#
# Required before enabling:
# 1. Binary installed: /usr/local/bin/promtail (see runbook)
# 2. Config deployed: /etc/promtail/promtail-lxc.yaml
# 3. Data directory: install -d -m 0750 -o promtail -g promtail /var/lib/promtail
# 4. User created: useradd --system --no-create-home --shell /usr/sbin/nologin promtail
# usermod -aG systemd-journal promtail
# 5. Set LOKI_PUSH_URL in /etc/promtail/env (no quotes, no export):
# LOKI_PUSH_URL=http://<central-loki-ip>:3100/loki/api/v1/push
#
# Full runbook: docs/deployment/loki-lxc-runbook.md
[Unit]
Description=Promtail — errors-hub log shipper to central Loki
Documentation=https://grafana.com/docs/loki/latest/send-data/promtail/
After=network.target
# Start after the app services so journal entries are already flowing.
After=bitreport-error-reporting-ingest-api.service
After=bitreport-error-reporting-api.service
After=bitreport-error-reporting-collector-worker.service
After=bitreport-error-reporting-admin-ui.service
[Service]
Type=simple
User=promtail
Group=promtail
# Read LOKI_PUSH_URL from a separate secrets file (not in git).
EnvironmentFile=/etc/promtail/env
ExecStart=/usr/local/bin/promtail \
-config.file=/etc/promtail/promtail-lxc.yaml \
-config.expand-env=true
Restart=on-failure
RestartSec=10s
# Cap memory; Promtail is lightweight — adjust if ingestion volume grows.
MemoryMax=128M
# Journal read requires supplementary group membership (usermod -aG systemd-journal promtail).
# No extra SupplementaryGroups= directive needed when usermod is used.
[Install]
WantedBy=multi-user.target
+39
View File
@@ -69,6 +69,7 @@ services:
NODE_ENV: production
INGEST_RATE_LIMIT_MAX: ${INGEST_RATE_LIMIT_MAX:-300}
INGEST_RATE_LIMIT_WINDOW_MS: ${INGEST_RATE_LIMIT_WINDOW_MS:-60000}
LOG_LEVEL: ${LOG_LEVEL:-info}
ports:
- "${ER_PUBLISH_INGEST_PORT:-3041}:3041"
healthcheck:
@@ -105,6 +106,7 @@ services:
INGEST_PUSH_RETRY_MAX_JITTER_MS: ${INGEST_PUSH_RETRY_MAX_JITTER_MS:-250}
MAX_BACKOFF_EXPONENT: ${MAX_BACKOFF_EXPONENT:-8}
NODE_ENV: production
LOG_LEVEL: ${LOG_LEVEL:-info}
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
@@ -135,3 +137,40 @@ services:
timeout: 5s
retries: 6
start_period: 45s
# ── Loki log aggregation (profile: observability) ──────────────────────
# Start with: docker compose --profile observability up
# Docs: docs/OBSERVABILITY_LOKI.md
loki:
image: grafana/loki:3.4.3
profiles: [observability]
command: -config.file=/etc/loki/loki.yaml
volumes:
- ./deploy/loki/loki.yaml:/etc/loki/loki.yaml:ro
- loki-data:/loki
- ./deploy/loki/rules:/loki/rules:ro
ports:
- "${ER_PUBLISH_LOKI_PORT:-3100}:3100"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3100/ready || exit 1"]
interval: 10s
timeout: 5s
retries: 12
start_period: 30s
promtail:
image: grafana/promtail:3.4.3
profiles: [observability]
command: -config.file=/etc/promtail/promtail.yaml
depends_on:
loki:
condition: service_healthy
volumes:
- ./deploy/loki/promtail.yaml:/etc/promtail/promtail.yaml:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- promtail-positions:/run/promtail
volumes:
loki-data:
promtail-positions:
+174 -134
View File
@@ -2,155 +2,195 @@
## Overview
This document describes the Gitea Actions CI/CD pipeline for the `errors.bitreport.pt` project. The pipeline automatically tests, validates, and builds all services on every commit to the `master` branch and on pull requests.
The CI/CD pipeline for `errors.bitreport.pt` runs on Gitea Actions in two stages:
## Pipeline Structure
1. **CI** (`.gitea/workflows/ci.yml`) — runs on every push to `master` and on every pull request
2. **Deploy** (`.gitea/workflows/deploy.yml`) — triggers automatically after CI passes on `master`; deploys to staging automatically, and to production after manual approval
The CI pipeline runs four independent validation jobs in parallel:
## CI Pipeline
### 1. **Test ingest-api** (`test-ingest-api`)
### Jobs (run in parallel)
Tests the Node.js ingest API service using Vitest.
| Job | Service | What it does |
|-----|---------|--------------|
| `test-ingest-api` | `ingest-api/` | Node 20 + Python 3, `npm ci`, lint, typecheck, `npm test` (Vitest + Python contract check) |
| `test-collector-worker` | `collector-worker/` | Node 20, `npm ci`, lint, typecheck, `npm test` (Vitest) |
| `test-api` | `api/` | Node 20, `npm ci`, lint, typecheck, `npm test` (Vitest) |
| `lint-admin-ui` | `admin-ui/` | Node 20, `npm ci`, `npm run lint`, `npm run typecheck` |
| `test-web` | `web/` | Node 20, `npm ci`, lint, typecheck, `npm test`, `npm run test:coverage` |
| `docker-build` | ingest-api, collector-worker, admin-ui | Builds each Docker image separately via Buildx |
| `notify-failure` | — | Sends webhook notification if any job fails |
- **Service:** `ingest-api/`
- **Steps:**
- Node.js 20 setup with npm cache
- `npm ci` — install dependencies with exact versions
- `npm test` — runs Vitest unit tests + Python validation of error reporter context contract
- **Purpose:** Validates ingest API logic and contract with client SDKs
### Triggers
### 2. **Test api** (`test-api`)
- Push to `master`
- Pull requests targeting `master`
Tests the Node.js admin API service using Vitest.
### Python dependency (ingest-api)
- **Service:** `api/`
- **Steps:**
- Node.js 20 setup with npm cache
- `npm ci` — install dependencies
- `npm test` — runs Vitest unit tests
- **Purpose:** Validates admin API logic and type safety
The `test-ingest-api` job installs Python 3 because `npm test` in `ingest-api/` invokes `tools/ci/check_error_reporter_context_contract.py` to validate the client SDK contract.
### 3. **Lint and Typecheck admin-ui** (`lint-admin-ui`)
### NPM caching
Validates frontend code quality and type safety.
- **Service:** `admin-ui/`
- **Steps:**
- Node.js 20 setup with npm cache
- `npm ci` — install dependencies
- `npm run lint` — Next.js ESLint validation
- `npm run typecheck` — TypeScript type checking
- **Purpose:** Ensures admin UI code quality before runtime testing
### 4. **Validate Docker Build** (`docker-build`)
Builds all Docker images defined in `docker-compose.yml`.
- **Services:** ingest-api, collector-worker, admin-ui
- **Steps:**
- Docker Buildx setup for multi-platform builds
- `docker compose build` — validates all Dockerfiles and layers
- Environment variables provided for build-time configuration
- **Purpose:** Ensures production container images build cleanly
## Trigger Events
The pipeline runs automatically on:
1. **Push to master** — every commit merged to main branch
2. **Pull requests** — on creation and on new pushes to PR branches
## Dependencies and Runtime
- **Node.js version:** 20 (as specified in `ingest-api/package.json` and `api/package.json`)
- **Runtime:** Ubuntu latest
- **Parallel execution:** All four jobs run in parallel; no job waits for another
- **Total runtime:** ~5–10 minutes (depending on dependency installation and test suite size)
## Caching
NPM package caches are built per service based on their `package-lock.json` files:
Each service caches its `node_modules` keyed on its own `package-lock.json`:
- `ingest-api/package-lock.json`
- `collector-worker/package-lock.json`
- `api/package-lock.json`
- `admin-ui/package-lock.json`
- `web/package-lock.json`
This accelerates dependency installation on subsequent runs.
### Failure notifications
## Configuration
### Workflow file
Location: `.gitea/workflows/ci.yml`
Modify this file to:
- Add or remove services
- Change trigger branches
- Adjust Node.js version
- Add new jobs (e.g., integration tests, security scanning)
### Environment Variables (Docker Build)
The `docker-build` job provides standard dev environment values:
```yaml
ER_MYSQL_ROOT_PASSWORD: devrootchange
ER_MYSQL_USER: er_app
ER_MYSQL_PASSWORD: er_app_secret
ER_MYSQL_DATABASE: error_reporting
```
To change defaults (e.g., for staging builds), update these in the workflow file.
## Failure Handling
If any job fails, the entire pipeline is marked as failed. Pull requests will show a **red check** and cannot be merged until all jobs pass.
### Common Failure Causes
| Job | Cause | Resolution |
|-----|-------|-----------|
| `test-ingest-api` | Failed Vitest or Python validation | Check ingest API tests and client SDK contract |
| `test-api` | Failed Vitest | Check API tests and type safety |
| `lint-admin-ui` | Lint errors or type errors | Fix ESLint violations and TypeScript errors |
| `docker-build` | Layer build failure, missing Dockerfile | Check Dockerfile syntax and base image availability |
## Local Testing
To replicate the CI pipeline locally:
```bash
# Test ingest-api
cd ingest-api
npm ci && npm test
cd ..
# Test api
cd api
npm ci && npm test
cd ..
# Test admin-ui
cd admin-ui
npm ci && npm run lint && npm run typecheck
cd ..
# Validate Docker build
docker compose build
```
## Future Enhancements
Potential pipeline extensions:
1. **Integration Tests** — Run full stack with docker-compose (requires longer runtime)
2. **Performance Benchmarks** — Track API response times over time
3. **Security Scanning** — SAST, dependency vulnerability checks
4. **Coverage Reports** — Publish code coverage metrics
5. **Artifact Publishing** — Push built images to registry on master merges
6. **Staged Deployments** — Auto-deploy to staging/production environments
The `notify-failure` job runs only when any CI job fails. It sends a JSON POST to `secrets.NOTIFY_WEBHOOK_URL` (Slack/Teams/etc.). If the secret is unset it silently skips.
---
**Last updated:** 2026-04-12
**Maintained by:** Planner Agent (Patrícia Santos)
**Related issues:** [BIT-2481](/BIT/issues/BIT-2481), [BIT-2498](/BIT/issues/BIT-2498)
## Deploy Pipeline
File: `.gitea/workflows/deploy.yml`
### Flow
```
CI passes on master
│
▼
deploy-staging (automatic, environment: staging)
│ success
▼
deploy-production (requires manual approval in Gitea, environment: production)
```
If CI fails, neither deploy job runs.
### Staging deploy
- **Trigger:** Automatic after CI workflow completes successfully on `master`
- **Environment:** `staging` (configure in Gitea → Repository → Environments)
- **Mechanism:** SSH into the staging host, `git reset --hard origin/master`, `docker compose up -d --build`
- **Notification:** Webhook on success and failure
### Production deploy
- **Trigger:** Automatic after `deploy-staging` succeeds, but **gated by manual approval**
- **Environment:** `production` (configure in Gitea → Repository → Environments → protection rules)
- **Mechanism:** Same SSH deploy procedure as staging against the production host
- **Notification:** Webhook on success and failure
---
## Required Secrets
Configure these in Gitea → Repository → Settings → Secrets:
| Secret | Used in | Purpose |
|--------|---------|---------|
| `STAGING_HOST` | deploy.yml | Hostname or IP of the staging server |
| `STAGING_PORT` | deploy.yml | SSH port (default: 22) |
| `STAGING_USER` | deploy.yml | SSH username on the staging server |
| `STAGING_SSH_KEY` | deploy.yml | Private SSH key (PEM format) for staging access |
| `PROD_HOST` | deploy.yml | Hostname or IP of the production server |
| `PROD_PORT` | deploy.yml | SSH port (default: 22) |
| `PROD_USER` | deploy.yml | SSH username on the production server |
| `PROD_SSH_KEY` | deploy.yml | Private SSH key (PEM format) for production access |
| `NOTIFY_WEBHOOK_URL` | ci.yml, deploy.yml | Webhook URL for failure/success notifications (Slack/Teams) |
---
## Gitea Environment Setup
### Creating environments
1. Go to **Repository → Settings → Environments**
2. Create `staging` with no protection rules (auto-deploy)
3. Create `production` with:
- **Required reviewers:** add the team leads who must approve production deploys
- **Wait timer:** optional (e.g., 10 minutes after staging deploy)
### Adding secrets to environments
Environment-scoped secrets (e.g., `STAGING_SSH_KEY`) can be placed at repository level. If staging and production keys differ, use environment-scoped secrets under each environment instead.
---
## Deploy Procedure (Manual)
If the pipeline cannot run (e.g., Gitea Actions runner is down), deploy manually:
```bash
# On the target server (staging or production)
cd /opt/bitreport/errors.bitreport.pt
git fetch origin master
git reset --hard origin/master
docker compose up -d --build ingest-api collector-worker admin-ui
docker compose ps
```
Before deploying manually, ensure:
- All CI checks are green on the commit you are deploying
- The database migration container has run for any schema changes (`docker compose run --rm migrate`)
---
## Failure Handling
### CI failure
1. Check the failing job in Gitea Actions
2. Fix the issue in a branch and open a PR
3. CI re-runs automatically on push to the PR branch
4. Merge only after all checks are green
### Deploy failure
1. Check the deploy job logs in Gitea Actions
2. SSH into the affected host to investigate (check `docker compose logs`)
3. If staging failed, fix and push — the pipeline will retry from CI
4. If production failed but staging succeeded, re-run the production job from the Gitea Actions UI after investigating
### Common failures
| Job | Cause | Resolution |
|-----|-------|-----------|
| `test-ingest-api` | Vitest failure or Python contract mismatch | Check `ingest-api/` tests and `tools/ci/` contract file |
| `test-collector-worker` | Vitest failure | Check `collector-worker/` tests |
| `test-api` | Vitest failure | Check `api/` tests |
| `lint-admin-ui` | ESLint or TypeScript errors | Run `npm run lint && npm run typecheck` locally in `admin-ui/` |
| `test-web` | Test failure or coverage threshold | Run `npm test` locally in `web/` |
| `docker-build` | Dockerfile syntax error or missing layer | Run `docker build ./ingest-api` locally to reproduce |
| `deploy-staging` | SSH key rejected or host unreachable | Verify `STAGING_HOST`, `STAGING_USER`, `STAGING_SSH_KEY` secrets |
| `deploy-production` | Same as staging | Verify `PROD_*` secrets |
---
## Local Testing
Replicate CI locally before pushing:
```bash
# ingest-api (requires Python 3)
cd ingest-api && npm ci && npm test && cd ..
# collector-worker
cd collector-worker && npm ci && npm test && cd ..
# api
cd api && npm ci && npm test && cd ..
# admin-ui
cd admin-ui && npm ci && npm run lint && npm run typecheck && cd ..
# web
cd web && npm ci && npm test && npm run test:coverage && cd ..
# Docker builds
docker build ./ingest-api -t errors-bitreport/ingest-api:local
docker build ./collector-worker -t errors-bitreport/collector-worker:local
docker build ./admin-ui -t errors-bitreport/admin-ui:local
```
---
**Last updated:** 2026-04-27
**Maintained by:** Maria Papoila
**Related issues:** [BIT-14249](/BIT/issues/BIT-14249), [BIT-2477](/BIT/issues/BIT-2477), [BIT-2481](/BIT/issues/BIT-2481)
@@ -0,0 +1,634 @@
# Code & Integration Inventory vs Roadmap
**Issue:** BIT-2477 [errors.bitreport.pt] Inventário código e integrações vs roadmap
**Owner:** Patrícia Santos (Planner)
**Status:** Completed (parent BIT-2477 closed 2026-05-09)
**Date:** 2026-04-26
---
## Executive Summary
The errors.bitreport.pt repository is a **production-ready** central error reporting platform with **complete application code** across multiple services. Infrastructure and integrations are **deployed and operational** with comprehensive documentation, runbooks, and monitoring. This inventory reconciles what **exists in code**, what **is documented**, and what **is planned or missing**.
**Key finding:** Platform is **production-ready** with all core components implemented. Roadmap is focused on **observability enhancements**, **additional integrations**, and **operational improvements**. No critical blockers identified.
---
## 1. Code & Tools Inventory (What Actually Exists)
### 1.1 Repository Structure
```
/opt/bitreport/errors.bitreport.pt/
├── .git/ # Git repo (BitReport Gitea)
├── docs/ # Documentation (all markdown)
│ ├── MONITORING.md # Monitoring & observability hub
│ ├── HTTP_CONTRACTS.md # API contracts for hub & ingest
│ ├── RUNBOOK_*.md # Operational runbooks (10+ files)
│ ├── OBSERVABILITY_PROMETHEUS.md # Prometheus metrics & labels
│ ├── RUNBOOK_SLO.md # SLO targets & alert rules
│ ├── ADMIN_STATS_API.md # Admin API documentation
│ ├── permission-matrix.md # RBAC permissions
│ └── deployment/ # Deployment guides (Compose, LXC)
├── ingest-api/ # Fastify HTTP ingest service (Node.js)
│ ├── src/
│ │ ├── server.ts # Main server entry point
│ │ ├── buildApp.ts # Fastify app builder
│ │ ├── services/ # Ingest business logic
│ │ ├── lib/ # Core libraries (fingerprinting, noise)
│ │ └── plugins/ # Prometheus plugin
│ ├── package.json # Dependencies: fastify, mysql2, prom-client
│ └── Dockerfile # Multi-stage build
├── collector-worker/ # Active polling collectors (Node.js)
│ ├── src/
│ │ ├── main.ts # Worker entry point
│ │ ├── poll/ # HTTP polling logic
│ │ ├── ingest/ # Push to ingest API
│ │ ├── scheduler/ # Source state management
│ │ ├── db/ # Database operations
│ │ └── auth/ # Secret resolution
│ ├── package.json # Dependencies: mysql2
│ └── Dockerfile
├── admin-ui/ # Next.js operator UI (React 19)
│ ├── src/ # Next.js app directory
│ ├── package.json # Dependencies: next 15.5.15, react 19.2.5
│ └── Dockerfile
├── api/ # Fastify admin API (Node.js)
│ ├── src/
│ │ ├── index.ts # Main server entry point
│ │ ├── routes/ # API routes (admin, public)
│ │ ├── plugins/ # DB, RBAC, rate-limit, audit, prometheus
│ │ └── lib/ # Auth, utilities
│ ├── package.json # Dependencies: fastify, mysql2, bcrypt, zod
│ └── Dockerfile
├── web/ # Next.js admin login/UI
│ ├── src/ # Next.js app directory
│ ├── package.json # Dependencies: next 15.5.15, react 19.2.5
│ └── Dockerfile
├── database/error_reporting/ # SQL migrations + seed
│ ├── migrations/ # Versioned migrations (up/down)
│ └── seed/ # Dev fixtures
├── db/migrations/ # Admin portal migrations
├── clients/ # Client libraries
│ ├── node/ # JavaScript/TypeScript reporters
│ └── php/ # PHP reporter
├── scripts/ # Utility scripts
│ ├── docker-migrate.sh # Docker migration runner
│ ├── run-mysql-migrations.sh # Manual migration runner
│ └── er-cli.sh # CLI wrapper for API
├── deploy/ # Deployment artifacts
│ ├── lxc/ # LXC deployment configs
│ └── grafana/ # Grafana dashboard JSON
├── docker-compose.yml # Full stack (MariaDB, migrate, services)
└── .env.example # Environment template
```
### 1.2 Application Code
| Path | Type | Purpose | Status | Owner |
|------|------|---------|--------|-------|
| `ingest-api/` | Fastify service | HTTP ingest API with rate limiting, auth, noise filtering | ✅ **Production-ready** | Backend Team |
| `collector-worker/` | Node.js worker | Active polling from configured sources → ingest API | ✅ **Production-ready** | Backend Team |
| `admin-ui/` | Next.js app | Operator UI for incident management (Velzon-style) | ✅ **Production-ready** | Frontend Team |
| `api/` | Fastify service | Admin API with RBAC, sessions, audit logging | ✅ **Production-ready** | Backend Team |
| `web/` | Next.js app | Admin login/UI for RBAC portal | ✅ **Production-ready** | Frontend Team |
| `database/error_reporting/` | SQL migrations | Core schema (incidents, occurrences, collectors) | ✅ **Production-ready** | DBA |
| `db/migrations/` | SQL migrations | Admin portal schema (users, tokens, audit) | ✅ **Production-ready** | DBA |
### 1.3 Client Libraries
| Library | Language | Purpose | Status | Owner |
|---------|----------|---------|--------|-------|
| `clients/node/errorReporter.mjs` | JavaScript/TypeScript | ESM client for error reporting | ✅ **Ready** | Backend Team |
| `clients/node/errorReporter.cjs` | JavaScript | CommonJS client for error reporting | ✅ **Ready** | Backend Team |
| `clients/php/ErrorReporter.php` | PHP | PHP client for error reporting | ✅ **Ready** | Backend Team |
### 1.4 Utility Scripts
| Script | Purpose | Input | Output | Status | Owner |
|--------|---------|-------|--------|--------|-------|
| `scripts/docker-migrate.sh` | Apply migrations in Docker | Compose env | Migrated DB | ✅ **Ready** | DevOps |
| `scripts/run-mysql-migrations.sh` | Manual migration runner | DB connection | Migrated DB | ✅ **Ready** | DevOps |
| `scripts/er-cli.sh` | CLI wrapper for public API | API keys | JSON output | ✅ **Ready** | DevOps |
---
## 2. Integrations Inventory (What Is Documented/Planned)
### 2.1 Infrastructure & Compute
| Integration | Type | Status | Details | Roadmap Link |
|-------------|------|--------|---------|--------------|
| **MariaDB 11** | Database | ✅ **Live** | Primary data store; migrations versioned | [docker-compose.yml](../docker-compose.yml) |
| **Docker Compose** | Orchestration | ✅ **Live** | Full stack reproducible deployment | [deployment guide](docs/deployment/bitreport-error-reporting-compose-proxmox.md) |
| **LXC + systemd** | Orchestration | ✅ **Live** | Alternative native deployment | [LXC guide](docs/deployment/bitreport-error-reporting-lxc-proxmox.md) |
| **Proxmox** | Hypervisor | ✅ **Live** | Host for LXC containers/VMs | Company ENVIRONMENTS.md |
| **Prometheus** | Metrics | ✅ **Live** | Scrape targets on both APIs | [OBSERVABILITY_PROMETHEUS.md](docs/OBSERVABILITY_PROMETHEUS.md) |
| **Grafana** | Dashboards | ✅ **Live** | Pre-built dashboard JSON | [deploy/grafana/](deploy/grafana/) |
### 2.2 Observability & Monitoring
| Component | Type | Status | Choice | Roadmap Link |
|-----------|------|--------|--------|--------------|
| **Metrics exporter** | Agent | ✅ **Live** | prom-client (Node.js) | [OBSERVABILITY_PROMETHEUS.md](docs/OBSERVABILITY_PROMETHEUS.md) |
| **Metrics scrape** | Service | ✅ **Live** | Prometheus | [MONITORING.md](docs/MONITORING.md) |
| **Log aggregation** | Service | 📋 **Planned** | Loki (company standard) | Company MONITORING_INDEX.md |
| **Dashboards** | UI | ✅ **Live** | Grafana (pre-built) | [RUNBOOK_SLO.md](docs/RUNBOOK_SLO.md) |
| **Alert rules** | Config | ✅ **Live** | Prometheus rules (documented) | [RUNBOOK_SLO.md](docs/RUNBOOK_SLO.md) |
| **SLO targets** | Policy | ✅ **Live** | Documented thresholds | [RUNBOOK_SLO.md](docs/RUNBOOK_SLO.md) |
| **Health checks** | Endpoint | ✅ **Live** | `/health` on all services | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
### 2.3 Authentication & Authorization
| Component | Type | Status | Details | Link |
|----------|------|--------|---------|------|
| **Ingest auth** | Token-based | ✅ **Live** | Project-bound ingest keys (DB-backed) | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **Admin auth** | JWT + sessions | ✅ **Live** | HTTP-only cookies, RBAC, refresh tokens | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **Rate limiting** | Plugin | ✅ **Live** | @fastify/rate-limit with presets | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **RBAC** | Plugin | ✅ **Live** | Permission-based access control | [permission-matrix.md](docs/permission-matrix.md) |
| **Audit logging** | Plugin | ✅ **Live** | All mutations logged | [api/src/plugins/audit.ts](api/src/plugins/audit.ts) |
### 2.4 API Contracts
| API | Type | Status | Endpoints | Link |
|-----|------|--------|-----------|------|
| **Ingest API** | REST | ✅ **Live** | POST /v1/ingest/events, /health, /metrics, /docs | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **Hub API (public)** | REST | ✅ **Live** | /api/error-monitoring/*, /v1/paperclip/* | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **Hub API (admin)** | REST | ✅ **Live** | /admin/auth/*, /v1/stats/*, /v1/incidents/* | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **OpenAPI** | Spec | ✅ **Live** | Auto-generated from Fastify | GET /v1/openapi.json |
### 2.5 Data Processing Features
| Feature | Type | Status | Details | Link |
|---------|------|--------|---------|------|
| **Fingerprinting** | Algorithm | ✅ **Live** | Configurable policy, hash-based | [ingest-api/src/lib/fingerprintPolicy.ts](ingest-api/src/lib/fingerprintPolicy.ts) |
| **Noise filtering** | Algorithm | ✅ **Live** | Rule-based noise detection | [ingest-api/src/lib/noisePolicy.ts](ingest-api/src/lib/noisePolicy.ts) |
| **Stack trace synthesis** | Algorithm | ✅ **Live** | Fallback for missing traces | [api/src/lib/synthesizeStackTraceForDisplay.ts](api/src/lib/synthesizeStackTraceForDisplay.ts) |
| **Idempotency** | Feature | ✅ **Live** | Idempotency-Key header support | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
| **Bulk operations** | Feature | ✅ **Live** | Bulk resolve, purge | [HTTP_CONTRACTS.md](docs/HTTP_CONTRACTS.md) |
### 2.6 Deployment & Operations
| Component | Type | Status | Tool | Roadmap Link |
|-----------|------|--------|------|--------------|
| **Code hosting** | Service | ✅ **Live** | Gitea (self-hosted) | Company ENVIRONMENTS.md |
| **CI/CD pipeline** | Automation | 📋 **Planned** | Gitea Actions / TBD | Company ROADMAP.md |
| **Build & test** | Stage | ✅ **Live** | npm test, docker build | [README.md](README.md) |
| **Deployment** | Automation | ✅ **Live** | Docker Compose / LXC + systemd | [deployment guides](docs/deployment/) |
| **Rollback** | Procedure | ✅ **Live** | git checkout + restart | Documented in runbooks |
| **Runbooks** | Documentation | ✅ **Live** | 10+ operational procedures | [docs/](docs/) |
---
## 3. Roadmap Items (Planned Work)
### 3.1 In-Progress Issues
| Issue | Title | Owner | Due | Status | Blocked |
|-------|-------|-------|-----|--------|---------|
| **BIT-2477** | [errors.bitreport.pt] Inventário código e integrações vs roadmap | Planner | ✅ 2026-04-26 | **Completed** | No |
| **BIT-247** | Migration from OTT/error-reporting/ | CTO | ✅ Completed | **Completed** | No |
### 3.2 Planned Work Breakdown (From Company Roadmap)
| Rank | Item | Owner | Due | Related issue | Blocker |
|------|------|-------|-----|----------------|---------|
| **P0** | **Log aggregation** (Loki integration) | DevOps | TBD | Child issue (Create) | None |
| **P1** | **CI/CD pipeline** (Gitea Actions) | DevOps | TBD | Child issue (Create) | None |
| **P1** | **Additional client libraries** (Python, Go, Java) | Backend | TBD | Child issue (Create) | None |
| **P2** | **Real-time alerts** (webhook, Slack, email) | Backend | TBD | Child issue (Create) | None |
| **P2** | **Advanced analytics** (trends, correlations) | Backend | TBD | Child issue (Create) | None |
| **P2** | **Mobile app** (React Native) | Frontend | TBD | Child issue (Create) | None |
### 3.3 Completed Items (Phase 1: Core Platform)
| Item | Completed | Issue | Notes |
|------|-----------|-------|-------|
| Core database schema (incidents, occurrences) | 2026-03-22 | BIT-178 | Versioned migrations, reversible |
| Ingest API with rate limiting & auth | 2026-03-22 | BIT-154.3 | Fastify, prom-client metrics |
| Collector worker (HTTP polling) | 2026-03-22 | BIT-180 | Active polling, backoff retry |
| Admin UI (Next.js, Velzon-style) | 2026-04-01 | BIT-181 | React 19, Bootstrap 5 |
| Admin API with RBAC | 2026-04-01 | BIT-183 | JWT sessions, audit logging |
| Client libraries (Node, PHP) | 2026-04-08 | BIT-154.x | ESM, CJS, PHP support |
| Prometheus metrics & Grafana dashboard | 2026-04-04 | BIT-154.x | SLO targets, alert rules |
| Deployment guides (Compose, LXC) | 2026-04-16 | BIT-154.x | Proxmox integration |
| Operational runbooks (10+ docs) | 2026-04-01 | BIT-154.x | Triage, debugging, ops |
---
## 4. Gap Analysis: Code/Integrations vs Roadmap
### 4.1 What Exists and Is Used
✅ **Core Platform (Live & Production-Ready):**
- Complete error reporting pipeline (ingest → storage → UI)
- Multi-service architecture (ingest-api, collector-worker, admin-ui, api, web)
- Database with versioned migrations (MariaDB 11)
- Authentication & authorization (JWT, RBAC, audit logging)
- Rate limiting & security (Fastify plugins)
- Client libraries (Node.js, PHP)
✅ **Observability (Live):**
- Prometheus metrics on all services
- Grafana dashboard (pre-built JSON)
- SLO targets & alert rules
- Health checks on all endpoints
- OpenAPI documentation
✅ **Documentation (Complete):**
- HTTP contracts (comprehensive API docs)
- Monitoring & observability guide
- 10+ operational runbooks
- Deployment guides (Docker Compose, LXC)
- Permission matrix & RBAC docs
✅ **Deployment (Live):**
- Docker Compose stack (reproducible)
- LXC + systemd deployment (native)
- Proxmox integration
- Environment templates (.env.example)
### 4.2 What Is Planned but Not Yet Deployed
📋 **Log aggregation** (company standard, not yet integrated):
- Loki log shipper configuration
- Log parsing and indexing
- Log-based alerting
📋 **CI/CD pipeline** (manual deployment today):
- Gitea Actions workflow
- Automated testing & builds
- Automated deployment gates
📋 **Additional client libraries** (Node and PHP only today):
- Python client
- Go client
- Java client
- .NET client
📋 **Real-time notifications** (no push today):
- Webhook notifications
- Slack integration
- Email alerts
- SMS alerts (optional)
📋 **Advanced analytics** (basic stats only today):
- Trend analysis
- Correlation detection
- Anomaly detection
- Predictive alerting
### 4.3 What Is Missing (Not Documented)
❌ **Mobile applications** (not in current roadmap):
- React Native mobile app
- iOS app
- Android app
❌ **Alternative integrations** (not in current roadmap):
- Kafka message queue
- Redis caching layer
- Elasticsearch for full-text search
❌ **Advanced features** (post-Phase 1):
- Machine learning for anomaly detection
- Automated incident resolution
- Cost tracking & chargeback
- Multi-tenant isolation (beyond RBAC)
**Rationale:** These items are either **future enhancements** (roadmap priority), **not yet required** (current needs met), or **out of scope** (company standards handle some aspects).
### 4.4 Alignment Check: Roadmap vs Infrastructure
| Roadmap item | Infrastructure ready | Documentation ready | Blocker | Status |
|--------------|----------------------|----------------------|---------|--------|
| Core error reporting | ✅ (all services live) | ✅ (HTTP contracts, runbooks) | None | **Production-ready** |
| Observability (metrics) | ✅ (Prometheus + Grafana) | ✅ (SLO, alert rules) | None | **Live** |
| Observability (logs) | ✅ (journalctl, app logs) | ✅ (company standards) | **Implementation needed** | Planned |
| CI/CD pipeline | ✅ (Gitea available) | ✅ (company standards) | **Implementation needed** | Planned |
| Additional clients | ✅ (pattern established) | ✅ (HTTP contracts) | **Implementation needed** | Planned |
| Real-time alerts | ✅ (webhook capability) | 📋 (design needed) | **Design needed** | Planned |
| Advanced analytics | ✅ (data available) | 📋 (requirements needed) | **Requirements needed** | Planned |
---
## 5. Blockers & Dependencies
### 5.1 Critical Path
```
Phase 1: Core Platform (COMPLETED)
├─ Database schema (migrations)
├─ Ingest API (auth, rate limiting, noise filtering)
├─ Collector worker (HTTP polling)
├─ Admin UI (Next.js, React 19)
├─ Admin API (RBAC, audit logging)
├─ Client libraries (Node, PHP)
├─ Observability (Prometheus, Grafana)
└─ Deployment (Docker Compose, LXC)
Phase 2: Operational Excellence (PLANNED)
├─ Log aggregation (Loki integration)
├─ CI/CD pipeline (Gitea Actions)
├─ Additional client libraries (Python, Go, Java)
└─ Real-time notifications (webhooks, Slack)
Phase 3: Advanced Features (FUTURE)
├─ Advanced analytics (trends, correlations)
├─ Mobile applications (React Native)
└─ ML-based anomaly detection
```
### 5.2 Staffing Dependencies
| Role | Task | Assigned | Status |
|------|------|----------|--------|
| **Backend Engineer** | Core platform, API development | ✅ Assigned | **Active** |
| **Frontend Engineer** | Admin UI, web UI | ✅ Assigned | **Active** |
| **DevOps Engineer** | Deployment, observability | ✅ Assigned | **Active** |
| **DBA** | Database schema, migrations | ✅ Assigned | **Active** |
| **QA Engineer** | Testing, integration | TBD | 🔴 **Open** |
| **Mobile Developer** | React Native app | TBD | 🔴 **Open** |
**Action:** Consider hiring QA Engineer and Mobile Developer for Phase 2 & 3.
### 5.3 Decision Points (Not Blockers)
| Decision | Options | Status | Due | Owner |
|----------|---------|--------|-----|-------|
| Log stack | Loki (company standard) vs alternatives | ✅ **Decided** | — | DevOps |
| CI/CD tool | Gitea Actions vs Jenkins vs external | 📋 To decide | TBD | DevOps |
| Notification channels | Webhook, Slack, email, SMS | 📋 To decide | TBD | Product |
| Analytics scope | Basic vs advanced vs ML | 📋 To decide | TBD | Product |
---
## 6. Summary Table: Code vs Roadmap Alignment
| Dimension | Current State | Roadmap Status | Gap | Risk |
|-----------|--------------|-----------------|-----|------|
| **Core platform** | Live (all services) | ✅ Complete | None | Low |
| **Database** | Live (MariaDB 11) | ✅ Complete | None | Low |
| **Authentication** | Live (JWT, RBAC) | ✅ Complete | None | Low |
| **Client libraries** | Node, PHP ready | 📋 More languages | Python, Go, Java | Low |
| **Observability (metrics)** | Live (Prometheus) | ✅ Complete | None | Low |
| **Observability (logs)** | Not integrated | 📋 Planned | Loki integration | Low |
| **CI/CD** | Manual deployment | 📋 Planned | Gitea Actions | Low |
| **Real-time alerts** | Not implemented | 📋 Planned | Webhooks, Slack | Medium |
| **Advanced analytics** | Basic stats only | 📋 Planned | Trends, ML | Medium |
| **Mobile apps** | Not started | 📋 Future | React Native | High |
| **Documentation** | Complete (15+ docs) | ✅ Complete | None | None |
---
## 7. Recommendations
### 7.1 For CTO (Next Steps)
1. **Log aggregation (P0):** Create child issue for Loki integration. Follow company standards from MONITORING_INDEX.md.
2. **CI/CD pipeline (P1):** Create child issue for Gitea Actions workflow. Include lint, test, build, and deployment gates.
3. **Additional clients (P1):** Create child issues for Python, Go, and Java client libraries. Follow the pattern established by Node and PHP clients.
4. **Real-time notifications (P2):** Create child issue for webhook notifications and Slack integration. Define notification triggers and templates.
5. **Advanced analytics (P2):** Create child issue for trend analysis and correlation detection. Define requirements and success metrics.
6. **Staffing (P2):** Consider hiring QA Engineer for automated testing and Mobile Developer for React Native app.
### 7.2 For Teams
- **Backend Team:** No changes needed. Core platform is production-ready. Focus on additional clients and real-time notifications.
- **Frontend Team:** No changes needed. Admin UI and web UI are complete. Consider mobile app planning.
- **DevOps Team:** Implement log aggregation (Loki) and CI/CD pipeline (Gitea Actions). Follow company standards.
- **DBA:** No changes needed. Database schema is complete with versioned migrations.
- **Product Team:** Define requirements for real-time notifications and advanced analytics. Prioritize based on user feedback.
### 7.3 For Future Maintenance
- **Update this inventory quarterly** to track Phase 2 & 3 progress.
- **Link child issues** from BIT-2477 to this document once created.
- **Track staffing hires** in company AGENT_TEAM.md.
- **Archive completed items** in a "Completed (Phase N)" section below (see § 8).
---
## 8. Completed Items (Phase 1: Core Platform)
| Item | Completed | Issue | Notes |
|------|-----------|-------|-------|
| Database schema (incidents, occurrences) | 2026-03-22 | BIT-178 | Versioned migrations, reversible |
| Ingest API (Fastify, auth, rate limiting) | 2026-03-22 | BIT-154.3 | Noise filtering, fingerprinting |
| Collector worker (HTTP polling) | 2026-03-22 | BIT-180 | Backoff retry, state management |
| Admin UI (Next.js, React 19) | 2026-04-01 | BIT-181 | Velzon-style dashboard |
| Admin API (RBAC, audit logging) | 2026-04-01 | BIT-183 | JWT sessions, permissions |
| Client libraries (Node, PHP) | 2026-04-08 | BIT-154.x | ESM, CJS, PHP support |
| Prometheus metrics & Grafana dashboard | 2026-04-04 | BIT-154.x | SLO targets, alert rules |
| Deployment guides (Compose, LXC) | 2026-04-16 | BIT-154.x | Proxmox integration |
| Operational runbooks (10+ docs) | 2026-04-01 | BIT-154.x | Triage, debugging, ops |
| HTTP contracts documentation | 2026-04-01 | BIT-154.x | Comprehensive API docs |
---
## 9. Appendix: Integration Details
### 9.1 Database Schema (BIT-178)
**Current state:** MariaDB 11 with versioned migrations under `database/error_reporting/migrations/`.
**Core tables:**
- `er_projects` - Project configuration
- `er_ingest_keys` - Ingest authentication tokens
- `er_incidents` - Aggregated error incidents
- `er_incident_occurrences` - Individual error occurrences
- `er_collectors` - Collector configuration
- `er_collector_runs` - Collector execution history
- `er_audit_log` - Audit trail (admin portal)
**Admin portal tables:**
- `admin_users` - Admin user accounts
- `admin_refresh_tokens` - JWT refresh tokens
- `admin_audit_log` - Admin audit trail
**What's working:**
- ✅ All migrations are reversible (up/down SQL)
- ✅ Seed data for development (two projects, demo HTTP source)
- ✅ Foreign key constraints and indexes
- ✅ Applied via Docker Compose and LXC deployment
**What's pending:**
- None (schema is complete for Phase 1)
### 9.2 Ingest API (BIT-154.3)
**Current state:** Fastify service on port 3041 with comprehensive features.
**Features:**
- POST /v1/ingest/events - Batch event ingestion
- GET /health - Health check endpoint
- GET /metrics - Prometheus metrics
- GET /v1/openapi.json - OpenAPI specification
- GET /v1/docs/ui - Swagger UI
- Rate limiting (configurable)
- Project-bound authentication (DB-backed tokens)
- Noise filtering (rule-based)
- Fingerprinting (configurable policy)
- Idempotency (Idempotency-Key header)
- Stack trace synthesis (fallback)
**What's working:**
- ✅ Production-ready with comprehensive error handling
- ✅ Prometheus metrics (er_ingest_* family)
- ✅ OpenAPI documentation
- ✅ Integration tests (two projects scenario)
**What's pending:**
- None (core features complete)
### 9.3 Collector Worker (BIT-180)
**Current state:** Node.js worker that polls HTTP sources and pushes to ingest API.
**Features:**
- HTTP polling from configured sources
- Exponential backoff with jitter
- State management (last poll time, success/failure)
- Push to ingest API with retry logic
- Configurable intervals and timeouts
- Secret resolution (env vars or vault)
**What's working:**
- ✅ Active polling with configurable intervals
- ✅ Robust error handling and retry logic
- ✅ Integration with ingest API
- ✅ Demo HTTP fixture for testing
**What's pending:**
- Additional source types (Kafka, Redis, etc.) - future
### 9.4 Admin UI (BIT-181)
**Current state:** Next.js 15.5.15 with React 19.2.5, Velzon-style dashboard.
**Features:**
- Incident list with filtering
- Incident detail view
- Bulk operations (resolve, ignore)
- Statistics dashboard
- Demo mode (no admin API required)
- Production mode (connects to admin API)
**What's working:**
- ✅ Responsive design with Bootstrap 5
- ✅ Real-time updates (polling)
- ✅ Demo mode for standalone deployment
- ✅ Production mode with admin API integration
**What's pending:**
- Real-time updates via WebSocket - future
### 9.5 Admin API (BIT-183)
**Current state:** Fastify service with RBAC, JWT sessions, and audit logging.
**Features:**
- JWT-based authentication
- HTTP-only cookie sessions
- Refresh token rotation
- RBAC with permissions
- Audit logging for all mutations
- Rate limiting with presets
- Public API (error monitoring)
- Admin API (stats, incidents)
**What's working:**
- ✅ Secure authentication flow
- ✅ Permission-based access control
- ✅ Comprehensive audit trail
- ✅ Rate limiting protection
**What's pending:**
- None (core features complete)
### 9.6 Client Libraries
**Node.js (ESM & CJS):**
- errorReporter.mjs - ESM module
- errorReporter.cjs - CommonJS module
- Features: error capture, context, stack traces
- Status: ✅ Ready for use
**PHP:**
- ErrorReporter.php - PHP class
- Features: error capture, context, stack traces
- Status: ✅ Ready for use
**What's working:**
- ✅ Both libraries follow HTTP contracts
- ✅ Comprehensive error handling
- ✅ Context and stack trace support
**What's pending:**
- Python client - planned
- Go client - planned
- Java client - planned
### 9.7 Observability
**Prometheus metrics:**
- er_ingest_* - Ingest API metrics
- er_api_* - Hub API metrics
- er_collector_* - Collector worker metrics
- Scrape targets: /metrics on all services
**Grafana dashboard:**
- Pre-built JSON in deploy/grafana/
- Panels: ingestion rate, error rate, incidents by severity, etc.
- Status: ✅ Ready to import
**SLO targets:**
- Documented in RUNBOOK_SLO.md
- Alert rules defined
- Status: ✅ Live
**What's working:**
- ✅ Comprehensive metrics coverage
- ✅ Pre-built dashboards
- ✅ SLO targets and alert rules
**What's pending:**
- Log aggregation (Loki) - planned
---
## 10. Related Issues & References
| Issue | Title | Relation | Status |
|-------|-------|----------|--------|
| **BIT-247** | Migration from OTT/error-reporting/ | Parent epic | ✅ **Completed** |
| **BIT-2477** | [errors.bitreport.pt] Inventário código e integrações vs roadmap | This issue | ✅ **Completed** |
| **BIT-178** | Error Reporting Database | Child issue | ✅ **Completed** |
| **BIT-154.3** | Ingest API | Child issue | ✅ **Completed** |
| **BIT-180** | Collector Worker | Child issue | ✅ **Completed** |
| **BIT-181** | Admin UI | Child issue | ✅ **Completed** |
| **BIT-183** | Admin API | Child issue | ✅ **Completed** |
---
## 11. Document History
| Date (UTC) | Author | Change |
|-----------|--------|--------|
| 2026-04-26 | Patrícia Santos (Planner) | Created comprehensive code and integration inventory; reconciled with roadmap; identified Phase 2 & 3 opportunities. |
| 2026-05-09 | CEO (Maria Papoila) | Paperclip row synced to `done`; recovery BIT-19745 cleared; doc status updated to match closure. |
---
**Next review:** 2026-07-26 (post-Phase-2 operational excellence)
**Questions?** Ping @Planner in Slack or comment on BIT-2477 in Paperclip.
+55
View File
@@ -24,3 +24,58 @@ Company standards for signals (logs, metrics, tracing, alerting) are summarized
| Grafana dashboard JSON (import into your Grafana) | [`../deploy/grafana/error-monitoring-dashboard.json`](../deploy/grafana/error-monitoring-dashboard.json) |
Scrape **both** the hub API and the ingest API; see `OBSERVABILITY_PROMETHEUS.md` for paths and metric families.
---
## Log aggregation (Loki)
| Topic | Location |
|-------|----------|
| Architecture, labels, LogQL queries, troubleshooting | [`OBSERVABILITY_LOKI.md`](OBSERVABILITY_LOKI.md) |
| Loki server config (schema, retention, ruler) | [`../deploy/loki/loki.yaml`](../deploy/loki/loki.yaml) |
| Promtail config — Docker Compose lab | [`../deploy/loki/promtail.yaml`](../deploy/loki/promtail.yaml) |
| Promtail config — LXC / production | [`../deploy/loki/promtail-lxc.yaml`](../deploy/loki/promtail-lxc.yaml) |
| Promtail systemd unit (LXC) | [`../deploy/loki/systemd/promtail.service`](../deploy/loki/systemd/promtail.service) |
| Grafana log dashboard | [`../deploy/grafana/loki-logs-dashboard.json`](../deploy/grafana/loki-logs-dashboard.json) |
| Loki ruler alert rules | [`../deploy/loki/rules/fake/errors_hub_alerts.yaml`](../deploy/loki/rules/fake/errors_hub_alerts.yaml) |
| LXC operational runbook | [`deployment/loki-lxc-runbook.md`](deployment/loki-lxc-runbook.md) |
### Labels
Every log line from errors-hub carries these Loki labels:
| Label | Values |
|-------|--------|
| `app` | `errors-hub` (static) |
| `env` | `production` (static) |
| `service` | `ingest-api`, `api`, `collector-worker`, `admin-ui`, `web` |
| `level` | `info`, `warn`, `error`, `fatal` (normalised from Pino numeric levels) |
Labels are consistent across Docker Compose (Docker SD) and LXC (journald) deployments.
`trace` and `debug` lines are dropped by Promtail in both configs.
### Starting the observability stack
```bash
# Docker Compose (lab) — core services + Loki + Promtail
docker compose --profile observability up -d
# Verify log ingestion
curl -s 'http://localhost:3100/loki/api/v1/labels'
```
### Alert rules (Loki ruler)
Rules live in `deploy/loki/rules/fake/errors_hub_alerts.yaml` and are evaluated by the Loki ruler component.
| Alert | Condition | Severity |
|-------|-----------|----------|
| `ErrorsHubServiceErrorRateHigh` | Any service >0.1 error lines/s for 5m | warning |
| `ErrorsHubFatalLogDetected` | Any fatal line in any service for 1m | critical |
| `ErrorsHubIngestApiHighErrorRate` | ingest-api >0.05 error lines/s for 10m | critical |
| `ErrorsHubCollectorWorkerStalled` | collector-worker silent for 15m | warning |
Alerts route to Alertmanager (`ruler.alertmanager_url` in `deploy/loki/loki.yaml`).
For production LXC: point `alertmanager_url` to the central Alertmanager (`http://<observability-ct>:9093`).
For production LXC deployment, copy `deploy/loki/rules/` to `/loki/rules/` on the Loki LXC; see [`deployment/loki-lxc-runbook.md`](deployment/loki-lxc-runbook.md).
+213
View File
@@ -0,0 +1,213 @@
# Loki Log Aggregation — errors.bitreport.pt
Centralised log aggregation for all errors.bitreport.pt services using Grafana Loki + Promtail.
## Architecture
### Development / lab (Docker Compose)
```
ingest-api ──┐
collector-worker ─┤ stdout/stderr ┌──────────────┐ HTTP push ┌──────┐
admin-ui ──┤ ──────────────────▶│ Promtail │──────────────▶│ Loki │
api ──┤ (Docker socket) │ (Docker SD) │ └──────┘
mariadb ──┘ └──────────────┘ │
▼
Grafana (LogQL)
```
Promtail discovers containers via the Docker socket by matching the `errors-bitreport-pt` compose project label. All services emit structured JSON logs (Pino format); Promtail parses them and normalises Pino numeric levels to human-readable strings before shipping.
### Production (LXC/systemd — stack central)
In production the services run as **native systemd units on an LXC container** (no Docker). Promtail runs on the same app LXC and reads logs from the **systemd journal** instead of the Docker socket. Loki runs on a **separate central observability LXC** shared across company services.
```
┌─────────────────────────────────────┐
│ LXC: errors-hub (app) │
│ ingest-api / api / collector-worker│
│ admin-ui (systemd units) │
│ │
│ Promtail 127.0.0.1:9080 │──── journald (/var/log/journal)
└──────────────┬──────────────────────┘
│ HTTP push :3100 (LAN)
▼
┌──────────────────────────────────────┐
│ LXC: observability (central CT) │
│ Loki :3100 (LAN only) │──▶ Grafana (LogQL)
└──────────────────────────────────────┘
```
**Key differences from the lab setup:**
| Aspect | Lab (Compose) | Production (LXC) |
|--------|--------------|-----------------|
| Log source | Docker socket (container SD) | systemd journal |
| Promtail config | `deploy/loki/promtail.yaml` | `deploy/loki/promtail-lxc.yaml` |
| Loki location | Same host as app | Central observability LXC |
| Service filter | `com.docker.compose.project=errors-bitreport-pt` | `bitreport-error-reporting-*.service` units |
| Promtail binding | Docker network | 127.0.0.1 (loopback only) |
Full operational runbook: **[`docs/deployment/loki-lxc-runbook.md`](deployment/loki-lxc-runbook.md)**
## Starting the observability stack
```bash
# Start core services + Loki + Promtail
docker compose --profile observability up -d
# Core services only (no log aggregation)
docker compose up -d
```
Loki listens on port `3100` (configurable via `ER_PUBLISH_LOKI_PORT` in `.env`).
## Loki labels
Every log line carries these labels:
| Label | Source | Example values |
|---|---|---|
| `service` | compose service name | `ingest-api`, `collector-worker`, `admin-ui` |
| `compose_project` | Docker label | `errors-bitreport-pt` |
| `container` | Docker container name | `/errors-bitreport-pt-ingest-api-1` |
| `app` | static | `errors-hub` |
| `env` | static | `production` |
| `level` | normalised from Pino JSON `level` field | `info`, `warn`, `error`, `fatal` |
`trace` and `debug` lines are **dropped** by Promtail in production.
## Key LogQL queries
### Error logs across all services (last 1 h)
```logql
{app="errors-hub", level="error"} | json
```
### Logs for a specific service
```logql
{app="errors-hub", service="ingest-api"} | json
```
### Error rate per service (rate over 5 m)
```logql
sum by (service) (rate({app="errors-hub", level="error"}[5m]))
```
### Fatal logs (immediate on-call signal)
```logql
{app="errors-hub", level="fatal"} | json
```
### Ingest API request logs — errors only
```logql
{service="ingest-api", level="error"} | json | line_format "{{.msg}} err={{.err}}"
```
### Collector-worker retry / backoff events
```logql
{service="collector-worker"} |= "retry" | json
```
### All logs containing a specific error string
```logql
{app="errors-hub"} |= "ECONNREFUSED"
```
### Log volume by service over time (panel query)
```logql
sum by (service) (count_over_time({app="errors-hub"}[1m]))
```
## Grafana integration
The Loki datasource must be added to Grafana with URL `http://loki:3100` (or the host-mapped port if Grafana runs outside the compose network).
The pre-built log visualisation dashboard is at `deploy/grafana/loki-logs-dashboard.json`. Import it via **Dashboards → Import → Upload JSON**.
The dashboard requires a Loki datasource named `Loki` (or update the `datasource` field in the JSON to match your instance name).
## Troubleshooting
### Promtail not shipping logs
1. Check Promtail is running and healthy:
```bash
docker compose --profile observability ps promtail
curl http://localhost:9080/ready
```
2. Inspect Promtail targets (shows which containers are being scraped):
```bash
curl http://localhost:9080/targets
```
3. Check Promtail logs for errors:
```bash
docker compose --profile observability logs promtail --tail=50
```
4. Verify the Docker socket is accessible:
```bash
docker compose --profile observability exec promtail ls -la /var/run/docker.sock
```
### Loki not receiving data
1. Check Loki readiness:
```bash
curl http://localhost:3100/ready
# expected: "ready"
```
2. Inspect Loki ingestion metrics:
```bash
curl -s http://localhost:3100/metrics | grep loki_distributor_lines
```
3. Check for rejected samples (old timestamps):
```bash
curl -s http://localhost:3100/metrics | grep loki_discarded_samples
```
If services were offline for > 168 h (the `reject_old_samples_max_age`), logs from the gap period will be rejected. Adjust `reject_old_samples_max_age` in `deploy/loki/loki.yaml` if needed.
### Logs visible in Loki but not in Grafana
1. Confirm the Grafana datasource URL points to Loki (`http://loki:3100` inside Docker, or `http://localhost:3100` / configured `ER_PUBLISH_LOKI_PORT` from the host).
2. Verify the time range in the Grafana explore panel covers when services were running.
3. Run a raw label query to confirm data exists:
```bash
curl 'http://localhost:3100/loki/api/v1/labels'
curl 'http://localhost:3100/loki/api/v1/query?query=\{app="errors-hub"\}&limit=5'
```
### JSON not being parsed (raw log lines in Grafana)
Promtail only runs the JSON pipeline stage; if a service emits plain-text lines (e.g. MariaDB), the `json` stage is silently skipped and the raw line is stored as-is. The `level` label will be absent for those lines.
### Disk usage
Loki retains logs for **30 days** (configurable via `limits_config.retention_period` in `deploy/loki/loki.yaml`). Data is stored in the `loki-data` Docker volume. To check current volume size:
```bash
docker system df -v | grep loki-data
```
To purge all Loki data and start fresh:
```bash
docker compose --profile observability down
docker volume rm errors-bitreport-pt_loki-data errors-bitreport-pt_promtail-positions
docker compose --profile observability up -d
```
## Configuration files
| File | Purpose |
|---|---|
| `deploy/loki/loki.yaml` | Loki server — storage, schema, retention (lab and production) |
| `deploy/loki/promtail.yaml` | Promtail — Docker socket SD (lab/compose only) |
| `deploy/loki/promtail-lxc.yaml` | Promtail — journald SD (production LXC) |
| `deploy/loki/systemd/promtail.service` | systemd unit for Promtail on the app LXC |
| `deploy/grafana/loki-logs-dashboard.json` | Grafana log visualisation dashboard |
| `docs/deployment/loki-lxc-runbook.md` | Operational runbook — LXC/central stack setup |
+269
View File
@@ -0,0 +1,269 @@
# Loki/Promtail — produção LXC (stack central)
Runbook operacional para a stack de logs da plataforma **errors.bitreport.pt** em produção (LXC/systemd, fora do compose de laboratório). Complementa `docs/OBSERVABILITY_LOKI.md` — a diferença chave é o método de descoberta de logs: **journald** em vez de Docker socket.
---
## 1. Arquitectura de produção
```
┌─────────────────────────────────────┐ rede interna (LAN/VLAN)
│ LXC: errors-hub (app) │
│ │
│ ingest-api.service (3041) │──┐
│ api.service (3200) │ │ journald
│ collector-worker.service │ │
│ admin-ui.service (3040) │ │
│ │ │
│ promtail.service (127.0.0.1:9080)│─┘ → lê /var/log/journal
└────────────────────┬────────────────┘
│ HTTP push → :3100
▼
┌──────────────────────────────────────┐
│ LXC: observability (CT obs) │
│ Loki :3100 (LAN only) │
│ Grafana :3000 (LAN/VPN) │
└──────────────────────────────────────┘
```
### Decisões de design
| Decisão | Escolha | Razão |
|---------|---------|-------|
| Onde corre Loki | CT dedicado (observability) | Isolamento; partilhado por outros serviços da empresa |
| Onde corre Promtail | Mesmo LXC que a app (errors-hub) | Acesso directo ao journal; sem socket Docker |
| Método de descoberta | `journal` (systemd) | LXC sem Docker; unidades `bitreport-error-reporting-*.service` |
| Porto Loki externo | 3100 (LAN only — não exposto à internet) | Sem colisão; app LXC usa 3040/3041/3200 |
| Porto Promtail | 127.0.0.1:9080 (loopback only) | Sem exposição externa; só métricas locais |
| Retenção | 30 dias | Alinhado com config de laboratório |
| TLS Promtail→Loki | Não (LAN interna) | Se Loki migrar para fora da LAN, adicionar mTLS |
---
## 2. CT observability — instalar Loki
### 2.1 Criar o LXC (Proxmox)
- Template Debian 12 ou Ubuntu 24.04 (alinhado com restante infra)
- 1 GB RAM, 1 vCPU, ≥ 20 GB disco SSD (dados Loki crescem ~1-2 GB/dia com tráfego típico a 30 dias)
- Sem nesting (não é necessário Docker se usar binário nativo)
- IP LAN fixo (ex.: anotar na vault e em `docs/ENVIRONMENTS.md`)
### 2.2 Instalar Loki (binário nativo)
```bash
# Descarregar binário (substituir VERSION pela última estável)
LOKI_VERSION=3.4.3
curl -LO "https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}/loki-linux-amd64.zip"
unzip loki-linux-amd64.zip
install -m 0755 loki-linux-amd64 /usr/local/bin/loki
# Utilizador de serviço
useradd --system --no-create-home --shell /usr/sbin/nologin loki
# Direcórias de dados e config
install -d -m 0750 -o loki -g loki /etc/loki /var/lib/loki /var/lib/loki/chunks /var/lib/loki/rules /var/lib/loki/compactor
```
### 2.3 Deploy da config
```bash
# O loki.yaml de produção é o mesmo que deploy/loki/loki.yaml (filesystem storage).
# Ajuste os caminhos para /var/lib/loki em vez de /loki:
cp /opt/errors.bitreport.pt/deploy/loki/loki.yaml /etc/loki/loki.yaml
```
Editar `/etc/loki/loki.yaml` — alterar `path_prefix` e `chunks_directory` para `/var/lib/loki`:
```yaml
common:
instance_addr: 127.0.0.1
path_prefix: /var/lib/loki
storage:
filesystem:
chunks_directory: /var/lib/loki/chunks
rules_directory: /var/lib/loki/rules
```
### 2.4 Systemd unit para Loki
```ini
# /etc/systemd/system/loki.service
[Unit]
Description=Loki — log aggregation (BitReport observability)
After=network.target
[Service]
Type=simple
User=loki
Group=loki
ExecStart=/usr/local/bin/loki -config.file=/etc/loki/loki.yaml
Restart=on-failure
RestartSec=10s
MemoryMax=512M
[Install]
WantedBy=multi-user.target
```
```bash
systemctl daemon-reload
systemctl enable --now loki.service
# Verificar
curl http://localhost:3100/ready # → "ready"
```
### 2.5 Firewall — expor porto apenas na LAN
```bash
# Exemplo UFW: permitir apenas a sub-rede interna (ajustar ao VLAN real)
ufw allow from 192.168.1.0/24 to any port 3100 proto tcp
ufw deny 3100
```
---
## 3. LXC errors-hub — instalar Promtail
### 3.1 Instalar binário
```bash
PROMTAIL_VERSION=3.4.3
curl -LO "https://github.com/grafana/loki/releases/download/v${PROMTAIL_VERSION}/promtail-linux-amd64.zip"
unzip promtail-linux-amd64.zip
install -m 0755 promtail-linux-amd64 /usr/local/bin/promtail
# Utilizador de serviço com acesso ao journal
useradd --system --no-create-home --shell /usr/sbin/nologin promtail
usermod -aG systemd-journal promtail
# Direcórias
install -d -m 0750 -o promtail -g promtail /etc/promtail /var/lib/promtail
```
### 3.2 Deploy da config
```bash
cp /opt/errors.bitreport.pt/deploy/loki/promtail-lxc.yaml /etc/promtail/promtail-lxc.yaml
chmod 644 /etc/promtail/promtail-lxc.yaml
```
### 3.3 Ficheiro de ambiente (segredos fora do git)
```bash
# /etc/promtail/env (mode 640, root:promtail)
install -m 0640 /dev/null /etc/promtail/env
chown root:promtail /etc/promtail/env
```
Conteúdo de `/etc/promtail/env` (sem `export`, sem aspas):
```
LOKI_PUSH_URL=http://<IP-LAN-DO-CT-OBS>:3100/loki/api/v1/push
```
### 3.4 Instalar e activar systemd unit
```bash
cp /opt/errors.bitreport.pt/deploy/loki/systemd/promtail.service \
/etc/systemd/system/bitreport-promtail.service
systemctl daemon-reload
systemctl enable --now bitreport-promtail.service
```
### 3.5 Verificar que o Promtail está a recolher
```bash
# Estado do serviço
systemctl status bitreport-promtail.service
# Readiness
curl http://127.0.0.1:9080/ready
# Targets activos (deve mostrar as 4 unidades bitreport-error-reporting-*)
curl -s http://127.0.0.1:9080/targets | python3 -m json.tool | grep -E "job|labels|health"
# Logs do próprio Promtail
journalctl -u bitreport-promtail.service -f --no-pager
```
---
## 4. Grafana — ligar ao Loki central
Na instância Grafana da empresa (CT obs ou Grafana Cloud):
1. **Connections → Data sources → Add → Loki**
2. URL: `http://<IP-LAN-DO-CT-OBS>:3100` (ou `http://localhost:3100` se Grafana estiver no mesmo CT)
3. Nome da datasource: **`Loki`** (para compatibilidade com o dashboard existente)
4. Guardar e testar.
Importar o dashboard: **Dashboards → Import → Upload JSON** → `deploy/grafana/loki-logs-dashboard.json`.
---
## 5. Smoke — validação em staging
Após arranque dos serviços, executar as seguintes queries no **Grafana Explore** com datasource `Loki`:
### 5.1 Confirmar que há dados das 4 unidades
```logql
{app="errors-hub"} | limit 20
```
Esperado: linhas com `service` ∈ `{ingest-api, api, collector-worker, admin-ui}`.
### 5.2 Logs de erro recentes
```logql
{app="errors-hub", level="error"} | json
```
### 5.3 Logs da ingest-api (última hora)
```logql
{app="errors-hub", service="ingest-api"} | json
```
### 5.4 Verificação via API Loki (sem Grafana)
```bash
# Labels presentes (confirmar `app=errors-hub`)
curl 'http://<IP-LOKI>:3100/loki/api/v1/labels'
# 5 linhas recentes de qualquer serviço errors-hub
curl -G 'http://<IP-LOKI>:3100/loki/api/v1/query_range' \
--data-urlencode 'query={app="errors-hub"}' \
--data-urlencode 'limit=5' \
--data-urlencode "start=$(date -d '1 hour ago' +%s)000000000" \
--data-urlencode "end=$(date +%s)000000000"
```
Critério de aceitação: resposta com `status: "success"` e `data.result` não vazio.
---
## 6. Troubleshooting rápido
| Sintoma | Verificação |
|---------|-------------|
| Promtail não arranca | `journalctl -u bitreport-promtail -n 50`; verificar `LOKI_PUSH_URL` em `/etc/promtail/env` |
| Sem targets no `/targets` | Confirmar que as unidades `bitreport-error-reporting-*.service` estão a correr; verificar permissão journal (`id promtail`) |
| Loki recusa amostras antigas | `curl -s http://<LOKI>:3100/metrics | grep loki_discarded`; ajustar `reject_old_samples_max_age` em `loki.yaml` |
| Journal não persistente | `ls /var/log/journal` vazio → activar: `mkdir -p /var/log/journal && systemctl restart systemd-journald` |
| Logs sem label `level` | Serviço não emite JSON (ex.: MariaDB) — normal; `level` fica ausente para linhas plain-text |
---
## 7. Referência de artefactos
| Artefacto | Caminho |
|-----------|---------|
| Config Promtail (LXC/journald) | `deploy/loki/promtail-lxc.yaml` |
| Config Promtail (lab/Docker) | `deploy/loki/promtail.yaml` |
| Config Loki | `deploy/loki/loki.yaml` |
| Systemd unit Promtail | `deploy/loki/systemd/promtail.service` |
| Dashboard Grafana | `deploy/grafana/loki-logs-dashboard.json` |
| Doc principal Loki | `docs/OBSERVABILITY_LOKI.md` |
+2
View File
@@ -2,3 +2,5 @@ PORT=3041
DATABASE_URL=postgres://postgres:[email protected]:5432/error_reporting
INGEST_RATE_LIMIT_MAX=300
INGEST_RATE_LIMIT_WINDOW_MS=60000
# Log verbosity: trace | debug | info | warn | error | fatal (default: info)
# LOG_LEVEL=info
+313
View File
@@ -17,6 +17,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"ajv": "^8.18.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
@@ -26,6 +27,77 @@
"node": ">=20"
}
},
"node_modules/@ampproject/remapping": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.28.5",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
"integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.0"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true,
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
@@ -582,6 +654,37 @@
"node": ">=12"
}
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
"integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -589,6 +692,17 @@
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lukeed/ms": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
@@ -989,6 +1103,39 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@vitest/coverage-v8": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-2.1.9.tgz",
"integrity": "sha512-Z2cOr0ksM00MpEfyVE8KXIYPEcBFxdbLSs56L8PO0QQMxt/6bDj45uQfxoc96v05KW3clk7vvgP0qfDit9DmfQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.3.0",
"@bcoe/v8-coverage": "^0.2.3",
"debug": "^4.3.7",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-lib-source-maps": "^5.0.6",
"istanbul-reports": "^3.1.7",
"magic-string": "^0.30.12",
"magicast": "^0.3.5",
"std-env": "^3.8.0",
"test-exclude": "^7.0.1",
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "2.1.9",
"vitest": "2.1.9"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1685,6 +1832,23 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -1753,6 +1917,60 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-source-maps": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz",
"integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.23",
"debug": "^4.1.1",
"istanbul-lib-coverage": "^3.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
@@ -1855,6 +2073,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz",
"integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.25.4",
"@babel/types": "^7.25.4",
"source-map-js": "^1.2.0"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mime": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
@@ -2523,6 +2769,19 @@
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/tdigest": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",
@@ -2532,6 +2791,60 @@
"bintrees": "1.0.2"
}
},
"node_modules/test-exclude": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz",
"integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==",
"dev": true,
"license": "ISC",
"dependencies": {
"@istanbuljs/schema": "^0.1.2",
"glob": "^10.4.1",
"minimatch": "^10.2.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/test-exclude/node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/test-exclude/node_modules/brace-expansion": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/test-exclude/node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"brace-expansion": "^5.0.5"
},
"engines": {
"node": "18 || 20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+3 -1
View File
@@ -10,7 +10,8 @@
"start": "node dist/server.js",
"typecheck": "tsc --noEmit",
"test": "vitest run && python3 ../tools/ci/check_error_reporter_context_contract.py --path ../clients",
"test:watch": "vitest"
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@fastify/swagger": "^8.15.0",
@@ -22,6 +23,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"@vitest/coverage-v8": "^2.1.9",
"ajv": "^8.18.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
+156
View File
@@ -0,0 +1,156 @@
/**
* Integration tests for buildApp — exercises routes via Fastify inject,
* mocking DB pool and processIngestBatch so no real DB is needed.
*/
import { describe, it, expect, vi, beforeAll } from 'vitest';
import type { FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { buildApp } from './buildApp.js';
import { sha256Hex } from './lib/hash.js';
vi.mock('./plugins/prometheus.js', () => ({
default: async () => {},
ingestEventsTotal: { inc: vi.fn() },
ingestBatchSize: { observe: vi.fn() },
errorHubLastEventTimestamp: { set: vi.fn() },
errorHubIngestFailuresTotal: { inc: vi.fn() },
}));
vi.mock('./services/processIngestBatch.js', () => ({
processIngestBatch: vi.fn().mockResolvedValue({
status: 200,
body: {
fingerprint_policy_version: 1,
noise_ruleset_version: '1',
noise_filtered_count: 0,
results: [{ incident_id: 'inc-1', occurrence_id: 'occ-1', fingerprint: 'fp-1' }],
},
}),
computeRequestBodyHash: vi.fn().mockReturnValue('hash-abc'),
}));
const TOKEN = 'my-ingest-token';
const TOKEN_HASH = sha256Hex(TOKEN);
const validKeyRow: RowDataPacket = {
id: 'key-1',
project_id: 'proj-1',
project_slug: 'wdmi-store',
rate_limit_max: null,
rate_limit_window_ms: null,
} as unknown as RowDataPacket;
const baseEnv = {
NODE_ENV: 'test',
PORT: 3000,
INGEST_BASE_URL: 'http://ingest.local',
INGEST_RATE_LIMIT_MAX: 500,
INGEST_RATE_LIMIT_WINDOW_MS: 60000,
INGEST_ANON_IP_MAX: 20,
INGEST_ANON_IP_WINDOW_MS: 60000,
INGEST_PUSH_TIMEOUT_MS: 10000,
INGEST_PUSH_MAX_RETRIES: 2,
INGEST_PUSH_RETRY_BASE_MS: 100,
INGEST_PUSH_RETRY_MAX_JITTER_MS: 50,
HTTP_FETCH_TIMEOUT_MS: 10000,
MAX_BACKOFF_EXPONENT: 6,
};
function makePool(keyRows: RowDataPacket[] = []) {
return {
execute: vi.fn().mockResolvedValue([keyRows]),
};
}
let app: FastifyInstance;
beforeAll(async () => {
app = await buildApp({ env: baseEnv as never, pool: makePool([validKeyRow]) as never });
});
describe('GET /health', () => {
it('returns 200 with status ok', async () => {
const res = await app.inject({ method: 'GET', url: '/health' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ status: 'ok' });
});
});
describe('POST /v1/ingest/events — auth rejection', () => {
it('returns 401 when no credentials provided', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when API key is not found in DB', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: 'Bearer invalid-key' },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
});
describe('POST /v1/ingest/events — successful ingest', () => {
it('returns 200 with ingest results on valid auth and payload', async () => {
const localPool = makePool([validKeyRow]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: `Bearer ${TOKEN}` },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'Test error message',
},
],
},
});
expect(res.statusCode).toBe(200);
const body = res.json<{ results: unknown[] }>();
expect(body.results).toHaveLength(1);
});
});
describe('GET /v1/openapi.json', () => {
it('returns OpenAPI JSON spec', async () => {
const res = await app.inject({ method: 'GET', url: '/v1/openapi.json' });
expect(res.statusCode).toBe(200);
const spec = res.json<{ openapi: string; info: { title: string } }>();
expect(spec.openapi).toBe('3.1.0');
expect(spec.info.title).toContain('ingest');
});
});
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { loadEnv } from "./env.js";
function setEnv(vars: Record<string, string | undefined>): void {
for (const [key, value] of Object.entries(vars)) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
describe("loadEnv() — ingest-api", () => {
const REQUIRED = { DATABASE_URL: "mysql://user:pass@localhost/errors" };
const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
savedEnv.DATABASE_URL = process.env.DATABASE_URL;
setEnv(REQUIRED);
});
afterEach(() => {
setEnv(savedEnv);
});
it("returns defaults for optional vars", () => {
setEnv({
PORT: undefined,
INGEST_RATE_LIMIT_MAX: undefined,
INGEST_RATE_LIMIT_WINDOW_MS: undefined,
INGEST_ANON_IP_MAX: undefined,
INGEST_ANON_IP_WINDOW_MS: undefined,
});
const env = loadEnv();
expect(env.PORT).toBe(3041);
expect(env.INGEST_RATE_LIMIT_MAX).toBe(300);
expect(env.INGEST_RATE_LIMIT_WINDOW_MS).toBe(60_000);
expect(env.INGEST_ANON_IP_MAX).toBe(120);
expect(env.INGEST_ANON_IP_WINDOW_MS).toBe(60_000);
});
it("trims DATABASE_URL", () => {
setEnv({ DATABASE_URL: " mysql://host/db " });
const env = loadEnv();
expect(env.DATABASE_URL).toBe("mysql://host/db");
});
it("throws when DATABASE_URL is missing", () => {
setEnv({ DATABASE_URL: undefined });
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
});
it("throws when DATABASE_URL is blank", () => {
setEnv({ DATABASE_URL: " " });
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
});
it("parses custom integer values", () => {
setEnv({
PORT: "4000",
INGEST_RATE_LIMIT_MAX: "100",
INGEST_ANON_IP_MAX: "50",
});
const env = loadEnv();
expect(env.PORT).toBe(4000);
expect(env.INGEST_RATE_LIMIT_MAX).toBe(100);
expect(env.INGEST_ANON_IP_MAX).toBe(50);
});
it("falls back to default for non-numeric values", () => {
setEnv({ PORT: "invalid" });
const env = loadEnv();
expect(env.PORT).toBe(3041);
});
it("uses development as default NODE_ENV", () => {
const saved = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const env = loadEnv();
expect(env.NODE_ENV).toBe("development");
if (saved !== undefined) process.env.NODE_ENV = saved;
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, it, expect } from "vitest";
import { sha256Hex, stableJsonHash } from "./hash.js";
describe("sha256Hex()", () => {
it("returns a 64-char hex string", () => {
const result = sha256Hex("hello");
expect(result).toMatch(/^[0-9a-f]{64}$/);
});
it("returns known hash for 'hello'", () => {
expect(sha256Hex("hello")).toBe(
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
);
});
it("returns known hash for empty string", () => {
expect(sha256Hex("")).toBe(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
);
});
it("is deterministic", () => {
expect(sha256Hex("test input")).toBe(sha256Hex("test input"));
});
it("produces different hashes for different inputs", () => {
expect(sha256Hex("a")).not.toBe(sha256Hex("b"));
});
});
describe("stableJsonHash()", () => {
it("hashes primitive values", () => {
const h1 = stableJsonHash(42);
expect(h1).toMatch(/^[0-9a-f]{64}$/);
expect(h1).toBe(stableJsonHash(42));
});
it("hashes null", () => {
const h = stableJsonHash(null);
expect(h).toMatch(/^[0-9a-f]{64}$/);
expect(h).toBe(stableJsonHash(null));
});
it("is key-order independent for objects", () => {
const a = stableJsonHash({ z: 1, a: 2 });
const b = stableJsonHash({ a: 2, z: 1 });
expect(a).toBe(b);
});
it("produces different hashes for different values", () => {
expect(stableJsonHash({ x: 1 })).not.toBe(stableJsonHash({ x: 2 }));
});
it("handles nested objects with key-order independence", () => {
const a = stableJsonHash({ outer: { b: 2, a: 1 } });
const b = stableJsonHash({ outer: { a: 1, b: 2 } });
expect(a).toBe(b);
});
it("handles arrays (preserves order)", () => {
expect(stableJsonHash([1, 2, 3])).not.toBe(stableJsonHash([3, 2, 1]));
});
it("hashes string values", () => {
const h = stableJsonHash("hello world");
expect(h).toMatch(/^[0-9a-f]{64}$/);
expect(h).toBe(stableJsonHash("hello world"));
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Tests for the Prometheus metrics plugin in ingest-api.
*/
import { describe, it, expect } from 'vitest';
import Fastify from 'fastify';
import prometheusPlugin from './prometheus.js';
async function buildTestApp() {
const app = Fastify({ logger: false });
await app.register(prometheusPlugin);
return app;
}
describe('prometheusPlugin', () => {
it('exposes GET /metrics returning Prometheus text format', async () => {
const app = await buildTestApp();
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toContain('text/plain');
expect(res.payload).toContain('er_ingest_');
});
it('increments active connections on request and decrements on response', async () => {
const app = await buildTestApp();
// Fire a request — active connections hook runs around it
await app.inject({ method: 'GET', url: '/metrics' });
// No assertion on exact gauge value since it resets per request,
// but confirm the metrics endpoint still returns data
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
});
it('records ingest request duration for /v1/ingest paths', async () => {
const app = Fastify({ logger: false });
await app.register(prometheusPlugin);
app.post('/v1/ingest/events', async (_req, reply) => reply.status(200).send({ ok: true }));
await app.inject({ method: 'POST', url: '/v1/ingest/events', payload: {} });
const metricsRes = await app.inject({ method: 'GET', url: '/metrics' });
expect(metricsRes.payload).toContain('er_ingest_request_duration_seconds');
expect(metricsRes.payload).toContain('er_ingest_requests_total');
});
it('does not track /metrics itself in SLO histogram', async () => {
const app = await buildTestApp();
// Call metrics twice — the second call should not create a recursive entry
await app.inject({ method: 'GET', url: '/metrics' });
const res = await app.inject({ method: 'GET', url: '/metrics' });
expect(res.statusCode).toBe(200);
});
});
+167
View File
@@ -0,0 +1,167 @@
/**
* Tests for attachIngestAuth — validates token extraction, DB lookup, and error paths.
*/
import { describe, it, expect, vi } from 'vitest';
import type { FastifyReply, FastifyRequest } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { attachIngestAuth } from './ingestAuth.js';
import { sha256Hex } from '../lib/hash.js';
function makeReply() {
const reply = {
statusCode: 200,
_body: null as unknown,
status: vi.fn().mockReturnThis() as ReturnType<typeof vi.fn>,
send: vi.fn().mockImplementation(function (this: unknown, body: unknown) {
(reply as { _body: unknown })._body = body;
return Promise.resolve();
}),
};
(reply.status as ReturnType<typeof vi.fn>).mockReturnValue(reply);
return reply;
}
function makeRequest(overrides: {
authorization?: string;
'x-api-key'?: string;
}): FastifyRequest {
return {
headers: overrides,
ingestAuth: undefined,
} as unknown as FastifyRequest;
}
function makePool(rows: RowDataPacket[]) {
return {
execute: vi.fn().mockResolvedValue([rows]),
};
}
describe('attachIngestAuth', () => {
const TOKEN = 'my-secret-token';
const TOKEN_HASH = sha256Hex(TOKEN);
const validRow: RowDataPacket = {
id: 'key-id-123',
project_id: 'proj-id-456',
project_slug: 'wdmi-store',
rate_limit_max: 100,
rate_limit_window_ms: 60000,
} as unknown as RowDataPacket;
it('returns 401 when no authorization header and no x-api-key', async () => {
const pool = makePool([]);
const request = makeRequest({});
const reply = makeReply();
await attachIngestAuth(
pool as never,
request,
reply as unknown as FastifyReply,
);
expect(reply.status).toHaveBeenCalledWith(401);
expect(reply._body).toMatchObject({ error: 'unauthorized' });
});
it('returns 401 when authorization header has no Bearer prefix', async () => {
const pool = makePool([]);
const request = makeRequest({ authorization: 'Basic abc123' });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).toHaveBeenCalledWith(401);
});
it('returns 401 when token not found in DB (Bearer auth)', async () => {
const pool = makePool([]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).toHaveBeenCalledWith(401);
expect(reply._body).toMatchObject({ error: 'unauthorized', message: expect.stringContaining('Invalid') });
});
it('attaches ingestAuth on valid Bearer token', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(reply.status).not.toHaveBeenCalled();
expect(request.ingestAuth).toMatchObject({
keyId: 'key-id-123',
projectId: 'proj-id-456',
projectSlug: 'wdmi-store',
rateLimitMax: 100,
rateLimitWindowMs: 60000,
});
});
it('attaches ingestAuth via X-Api-Key header', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ 'x-api-key': TOKEN });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth).toBeDefined();
expect(request.ingestAuth?.projectSlug).toBe('wdmi-store');
});
it('sends hashed token to DB query', async () => {
const pool = makePool([validRow]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(pool.execute).toHaveBeenCalledWith(
expect.any(String),
[TOKEN_HASH],
);
});
it('sets rateLimitMax to null when DB value is zero', async () => {
const rowWithZeroLimit: RowDataPacket = {
...validRow,
rate_limit_max: 0,
rate_limit_window_ms: 0,
} as unknown as RowDataPacket;
const pool = makePool([rowWithZeroLimit]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.rateLimitMax).toBeNull();
expect(request.ingestAuth?.rateLimitWindowMs).toBeNull();
});
it('sets rateLimitMax to null when DB value is null', async () => {
const rowWithNullLimit: RowDataPacket = {
...validRow,
rate_limit_max: null,
rate_limit_window_ms: null,
} as unknown as RowDataPacket;
const pool = makePool([rowWithNullLimit]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.rateLimitMax).toBeNull();
expect(request.ingestAuth?.rateLimitWindowMs).toBeNull();
});
it('prefers Authorization header over X-Api-Key', async () => {
const pool = makePool([validRow]);
const request = makeRequest({
authorization: `Bearer ${TOKEN}`,
'x-api-key': 'different-token',
});
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(pool.execute).toHaveBeenCalledWith(expect.any(String), [TOKEN_HASH]);
});
it('lowercases projectSlug', async () => {
const rowUpperSlug: RowDataPacket = {
...validRow,
project_slug: 'WDMI-Store',
} as unknown as RowDataPacket;
const pool = makePool([rowUpperSlug]);
const request = makeRequest({ authorization: `Bearer ${TOKEN}` });
const reply = makeReply();
await attachIngestAuth(pool as never, request, reply as unknown as FastifyReply);
expect(request.ingestAuth?.projectSlug).toBe('wdmi-store');
});
});
@@ -0,0 +1,30 @@
/**
* Tests for exported helpers from processIngestBatch.
*/
import { describe, it, expect } from 'vitest';
import { computeRequestBodyHash } from './processIngestBatch.js';
describe('computeRequestBodyHash', () => {
it('returns a hex string', () => {
const hash = computeRequestBodyHash({ events: [] });
expect(typeof hash).toBe('string');
expect(hash).toMatch(/^[0-9a-f]{64}$/);
});
it('returns same hash for same input', () => {
const body = { events: [{ schema_version: 1, occurred_at: '2026-01-01T00:00:00Z', level: 'error', message: 'test' }] };
expect(computeRequestBodyHash(body)).toBe(computeRequestBodyHash(body));
});
it('returns different hash for different input', () => {
const a = computeRequestBodyHash({ events: [{ message: 'a' }] });
const b = computeRequestBodyHash({ events: [{ message: 'b' }] });
expect(a).not.toBe(b);
});
it('is order-independent for object keys', () => {
const a = computeRequestBodyHash({ a: 1, b: 2 });
const b = computeRequestBodyHash({ b: 2, a: 1 });
expect(a).toBe(b);
});
});
+7
View File
@@ -6,5 +6,12 @@ export default defineConfig({
environment: "node",
testTimeout: 60_000,
hookTimeout: 60_000,
include: ["src/**/*.test.ts"],
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
include: ["src/**/*.ts"],
exclude: ["src/**/*.test.ts", "**/*.d.ts"],
},
},
});
+2168 -8
View File
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -7,7 +7,10 @@
"build": "next build",
"start": "next start -p 3201",
"lint": "next lint",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"axios": "^1.7.2",
@@ -17,12 +20,19 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^22.9.0",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.5",
"eslint": "^9.15.0",
"eslint-config-next": "15.5.15",
"typescript": "^5.6.3"
"jsdom": "^29.0.2",
"typescript": "^5.6.3",
"vitest": "^4.1.5"
},
"engines": {
"node": ">=20"
@@ -0,0 +1,34 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — submit button enabled/disabled state', () => {
it('is disabled when both fields are empty', () => {
render(<LoginPage />);
expect(screen.getByRole('button', { name: 'Sign In' })).toBeDisabled();
});
it('is disabled when only email is filled', async () => {
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
expect(screen.getByRole('button', { name: 'Sign In' })).toBeDisabled();
});
it('is disabled when only password is filled', async () => {
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
expect(screen.getByRole('button', { name: 'Sign In' })).toBeDisabled();
});
it('is enabled when both email and password are filled', async () => {
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
expect(screen.getByRole('button', { name: 'Sign In' })).not.toBeDisabled();
});
});
@@ -0,0 +1,68 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — error alert display', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('shows API error message on failed login', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Invalid credentials.' }),
} as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'wrongpass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.getByText('Invalid credentials.')).toBeInTheDocument();
});
});
it('shows fallback message when API returns no message', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => ({}),
} as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByText('Invalid credentials. Please try again.')).toBeInTheDocument();
});
});
it('dismisses error when close button is clicked', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Bad credentials.' }),
} as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => screen.getByRole('alert'));
await userEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,39 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — form field interactions', () => {
it('updates email field on input', async () => {
render(<LoginPage />);
const emailInput = screen.getByLabelText('Email') as HTMLInputElement;
await userEvent.type(emailInput, '[email protected]');
expect(emailInput.value).toBe('[email protected]');
});
it('updates password field on input', async () => {
render(<LoginPage />);
const passwordInput = screen.getByLabelText('Password') as HTMLInputElement;
await userEvent.type(passwordInput, 'secret123');
expect(passwordInput.value).toBe('secret123');
});
it('email input has correct type', () => {
render(<LoginPage />);
expect(screen.getByLabelText('Email')).toHaveAttribute('type', 'email');
});
it('password input has correct type', () => {
render(<LoginPage />);
expect(screen.getByLabelText('Password')).toHaveAttribute('type', 'password');
});
it('email input has autocomplete=username', () => {
render(<LoginPage />);
expect(screen.getByLabelText('Email')).toHaveAttribute('autocomplete', 'username');
});
});
@@ -0,0 +1,58 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — loading state', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('shows spinner and "Signing In…" text during submit', async () => {
// Never resolve so we can catch the loading state
vi.mocked(fetch).mockReturnValueOnce(new Promise(() => {}));
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByText('Signing In…')).toBeInTheDocument();
});
});
it('disables email input while loading', async () => {
vi.mocked(fetch).mockReturnValueOnce(new Promise(() => {}));
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByLabelText('Email')).toBeDisabled();
});
});
it('disables password input while loading', async () => {
vi.mocked(fetch).mockReturnValueOnce(new Promise(() => {}));
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByLabelText('Password')).toBeDisabled();
});
});
});
+38
View File
@@ -0,0 +1,38 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — initial render', () => {
beforeEach(() => {
render(<LoginPage />);
});
it('renders the page heading', () => {
expect(screen.getByText('Welcome Back!')).toBeInTheDocument();
});
it('renders the email input', () => {
expect(screen.getByLabelText('Email')).toBeInTheDocument();
});
it('renders the password input', () => {
expect(screen.getByLabelText('Password')).toBeInTheDocument();
});
it('renders the submit button', () => {
expect(screen.getByRole('button', { name: 'Sign In' })).toBeInTheDocument();
});
it('shows the product tagline', () => {
expect(screen.getByText(/BitReport · Error Reporting Platform/i)).toBeInTheDocument();
});
it('renders the logo link', () => {
const logoLink = screen.getByRole('link');
expect(logoLink).toHaveAttribute('href', '/');
});
});
@@ -0,0 +1,68 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
const mockPush = vi.fn();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}));
describe('LoginPage — API error responses (integration)', () => {
beforeEach(() => {
mockPush.mockClear();
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('does NOT redirect on 401', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Unauthorized' }),
} as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'bad');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => screen.getByRole('alert'));
expect(mockPush).not.toHaveBeenCalled();
});
it('handles non-JSON error response gracefully', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => { throw new SyntaxError('not json'); },
} as unknown as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'bad');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(screen.getByText('Invalid credentials. Please try again.')).toBeInTheDocument();
});
});
it('re-enables the form after an error so the user can retry', async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Bad credentials.' }),
} as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'bad');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => screen.getByRole('alert'));
expect(screen.getByLabelText('Email')).not.toBeDisabled();
expect(screen.getByLabelText('Password')).not.toBeDisabled();
});
});
@@ -0,0 +1,60 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
describe('LoginPage — network failure (integration)', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('shows connection error message when fetch rejects', async () => {
vi.mocked(fetch).mockRejectedValueOnce(new TypeError('Failed to fetch'));
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(
screen.getByText('Unable to connect to the server. Please try again.'),
).toBeInTheDocument();
});
});
it('re-enables the submit button after network error', async () => {
vi.mocked(fetch).mockRejectedValueOnce(new TypeError('Failed to fetch'));
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => screen.getByRole('alert'));
expect(screen.getByRole('button', { name: 'Sign In' })).not.toBeDisabled();
});
it('dismisses network error and allows retry', async () => {
vi.mocked(fetch)
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce({ ok: true } as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'secret123');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => screen.getByRole('alert'));
await userEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,81 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginPage from '../../app/(admin)/login/page';
const mockPush = vi.fn();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}));
describe('LoginPage — successful login (integration)', () => {
beforeEach(() => {
mockPush.mockClear();
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('redirects to /admin/dashboard on 200 response', async () => {
vi.mocked(fetch).mockResolvedValueOnce({ ok: true } as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'correct-pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith('/admin/dashboard');
});
});
it('calls the login API with credentials:include', async () => {
vi.mocked(fetch).mockResolvedValueOnce({ ok: true } as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'correct-pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
expect(fetch).toHaveBeenCalledWith(
expect.stringContaining('/admin/auth/login'),
expect.objectContaining({
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
}),
);
});
});
it('sends trimmed email in the request body', async () => {
vi.mocked(fetch).mockResolvedValueOnce({ ok: true } as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), ' [email protected] ');
await userEvent.type(screen.getByLabelText('Password'), 'pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => {
const [, init] = vi.mocked(fetch).mock.calls[0];
const body = JSON.parse((init as RequestInit).body as string);
expect(body.email).toBe('[email protected]');
});
});
it('does not show an error alert after successful login', async () => {
vi.mocked(fetch).mockResolvedValueOnce({ ok: true } as Response);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
await userEvent.type(screen.getByLabelText('Password'), 'correct-pass');
await userEvent.click(screen.getByRole('button', { name: 'Sign In' }));
await waitFor(() => expect(mockPush).toHaveBeenCalled());
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom';
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'node:path';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.ts'],
globals: true,
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/test/**', '**/*.d.ts'],
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
});