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
110 changed files with 15809 additions and 419 deletions

No files matched your search

@@ -1,29 +0,0 @@
---
alwaysApply: true
---
# Deploy: nunca sobrescrever `.env` de produção (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
## Proibido em scripts de deploy e agentes
| Proibido | Alternativa |
|----------|------------|
| `cp .env.example .env` sobre `.env` **já existente** em produção | `git pull` / rsync **excluindo** `.env` |
| Escrever `root`, `changeme`, `password` ou superuser como credencial de BD em produção | Valores da vault; documentar chaves novas em `.env.example` **vazias** |
| Alterar `DB_*` / `DATABASE_*` / `MYSQL_*` no host sem issue, rollback e log | Entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo) antes de aplicar |
## Regras obrigatórias
1. Scripts de deploy devem **falhar** (`exit 1`) se um passo tentaria sobrescrever um `.env` existente com conteúdo de exemplo.
2. Usar **`rsync --exclude='.env'`** (e paths documentados por serviço) ou `git pull` sem toque no `.env`.
3. Pós-deploy: validar que variáveis críticas **não** regressaram a placeholders (`changeme`, `root`, `password`, `secret`, etc.).
4. Qualquer alteração a `.env` de produção requer: issue explícita, plano de rollback, e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md`.
## Quando a regra se aplica
- Todos os scripts de deploy (webhook, CI, manual).
- Agentes que editam, geram ou sugerem alterações a ficheiros `.env`, `.env.example`, `docker-compose.yml` com variáveis de ambiente, ou scripts que copiam/escrevem ficheiros de configuração em produção.
**Referência:** `docs/DEPLOY_STANDARD.md` §3.1 no meta-repo `paperclip` (regra canónica).
+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
+122 -8
View File
@@ -1,6 +1,6 @@
name: CI
'on':
on:
push:
branches:
- master
@@ -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
+3 -3
View File
@@ -4,7 +4,7 @@ import type { IncidentDetail, IncidentSummary } from "./types";
const _demoSummaries: IncidentSummary[] = [
{
id: "demo-1",
projectSlug: "crm",
projectSlug: "wdmi-store",
fingerprint: "fp_checkout_timeout",
title: "Checkout API timeout after 30s",
severity: "high",
@@ -15,7 +15,7 @@ const _demoSummaries: IncidentSummary[] = [
},
{
id: "demo-2",
projectSlug: "ott",
projectSlug: "crm-wdmi",
fingerprint: "fp_null_sku",
title: "TypeError: Cannot read properties of undefined (reading 'sku')",
severity: "medium",
@@ -26,7 +26,7 @@ const _demoSummaries: IncidentSummary[] = [
},
{
id: "demo-3",
projectSlug: "crm",
projectSlug: "wdmi-store",
fingerprint: "fp_rate_limit",
title: "429 Too Many Requests on /api/v1/prices",
severity: "low",
+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);
});
});
@@ -359,7 +359,7 @@ describe('POST /api/error-monitoring/resolve-by-pattern', () => {
method: 'POST',
url: '/api/error-monitoring/resolve-by-pattern',
headers: authHeaders(),
payload: { project_slug: 'crm' },
payload: { project_slug: 'wdmi' },
});
expect(res.statusCode).toBe(200);
});
@@ -405,7 +405,7 @@ describe('POST /api/error-monitoring/resolve-by-pattern', () => {
headers: authHeaders(),
payload: {
severity: 'critical',
project_slug: 'crm',
project_slug: 'wdmi',
message_pattern: 'timeout',
from_date: '2026-03-01T00:00:00Z',
},
@@ -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;
}
});
});
+3 -3
View File
@@ -31,13 +31,13 @@ describe('GET /api/error-monitoring/recent-errors', () => {
{
incident_id: '1',
occurrence_id: '99',
project_slug: 'crm',
project_slug: 'wdmi-store',
incident_severity: 'high',
incident_state: 'open',
message: 'probe',
stack_trace: '',
context_json: JSON.stringify({
gitea_repo: 'BitReport.pt/CRM_Project',
gitea_repo: 'BitReport.pt/WDMI_STORE',
file_path: '/src/x.ts',
line_number: 3,
}),
@@ -54,7 +54,7 @@ describe('GET /api/error-monitoring/recent-errors', () => {
expect(res.statusCode).toBe(200);
const body = res.json() as { data: Array<{ gitea_repo?: string; file_path?: string }> };
expect(body.data).toHaveLength(1);
expect(body.data[0].gitea_repo).toBe('BitReport.pt/CRM_Project');
expect(body.data[0].gitea_repo).toBe('BitReport.pt/WDMI_STORE');
expect(body.data[0].file_path).toBe('/src/x.ts');
});
+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"],
},
},
});
@@ -1,5 +0,0 @@
-- Irreversible: WDMI project rows and incident history were purged in the up migration (BIT-24704).
-- Re-onboarding WDMI slugs is intentionally blocked in ingest-api (`retiredProjects.ts`).
BEGIN;
COMMIT;
@@ -1,29 +0,0 @@
BEGIN;
-- Retire WDMI-family projects from the hub (BIT-24704).
-- Slug families: wdmi, wdmi-*, *-wdmi, crm-wdmi*.
UPDATE er_ingest_keys k
INNER JOIN er_projects p ON p.id = k.project_id
SET k.status = 'revoked',
k.revoked_at = NOW(6)
WHERE LOWER(p.slug) = 'wdmi'
OR LOWER(p.slug) LIKE 'wdmi-%'
OR LOWER(p.slug) LIKE '%-wdmi'
OR LOWER(p.slug) LIKE 'crm-wdmi%';
UPDATE er_collector_sources cs
INNER JOIN er_projects p ON p.id = cs.project_id
SET cs.is_active = FALSE
WHERE LOWER(p.slug) = 'wdmi'
OR LOWER(p.slug) LIKE 'wdmi-%'
OR LOWER(p.slug) LIKE '%-wdmi'
OR LOWER(p.slug) LIKE 'crm-wdmi%';
DELETE FROM er_projects
WHERE LOWER(slug) = 'wdmi'
OR LOWER(slug) LIKE 'wdmi-%'
OR LOWER(slug) LIKE '%-wdmi'
OR LOWER(slug) LIKE 'crm-wdmi%';
COMMIT;
+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
-1
View File
@@ -57,7 +57,6 @@ _run_sql "${_MIG_ER}/20260322044500_add_ingest_idempotency.up.sql"
_run_sql "${_MIG_ER}/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql "${_MIG_ER}/20260402103000_add_occurred_at_for_stats.up.sql"
_run_sql "${_MIG_ER}/20260402140000_ingest_key_rate_limits.up.sql"
_run_sql "${_MIG_ER}/20260608150000_retire_wdmi_projects.up.sql"
_run_sql "${_MIG_ADMIN}/001_admin_users.sql"
_run_sql "${_MIG_ADMIN}/002_admin_refresh_tokens.sql"
_run_sql "${_MIG_ADMIN}/003_audit_logs.sql"
+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 |
@@ -0,0 +1,75 @@
# DevOps runbook — SSH from Paperclip host to WDMI Importer (BIT-1044)
**Issue:** [BIT-1044](/BIT/issues/BIT-1044)
**Unblocks:** [BIT-1041](/BIT/issues/BIT-1041) (Importer maintenance scripts on the production guest, not in `WDMI_UBUNTU` git).
## Goal
From the Paperclip execution host (**`10.10.50.17`**, user **`paperclip`**), run:
```bash
ssh -o BatchMode=yes -o ConnectTimeout=10 root@192.168.1.123 echo ok
```
Expected stdout: `ok` (no password prompt).
Canonical Importer LAN IP and deploy path: [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) §2.
## Prerequisites (network)
The host has **dual homing**: VLAN **1050** (`10.10.50.17`) and LAN **`192.168.1.0/24`** (`192.168.1.239` on `eth1`). Traffic to **`192.168.1.123`** must leave via **`eth1`** with working L2/L3 to the Importer.
**Typical failure (pre-fix):** `ip neigh show 192.168.1.123` stays **`INCOMPLETE`** / **`FAILED`**; `ping` loss; SSH **`No route to host`**.
**Route OK, auth missing:** SSH connects (no *No route to host*) but **`Permission denied (publickey,password)`** with **BatchMode** means **TCP/22** is fine and **`root`** is not yet accepting **`paperclip@bitreport-cto`** — apply the **SSH key** section below on **`192.168.1.123`** (console or an existing privileged session).
**Isolation check (Paperclip host, 2026-04):** On **`10.10.50.17`**, if **`192.168.1.1`** (gateway) and **`192.168.1.17`** (CT 220 `wdmi-store` `eth1`) answer **`ping`** but **`192.168.1.123`** does not, the Paperclip **`eth1`** path on **`192.168.1.0/24`** is healthy and the fault is almost certainly **Importer-specific** (wrong IP, guest down, host firewall, isolated switch port, or ACL dropping that host). Fix those before spending time on VLAN **1050** routing.
**Operator actions (edge firewall / switch / guest):**
1. Confirm **`192.168.1.123`** is the live Importer address (vault / inventory).
2. Allow **TCP/22** from at least:
- **`192.168.1.239`** (Paperclip `eth1`), and
- **`192.168.1.17`** (CT 220 `wdmi-store` `eth1`, if CTO uses that hop).
3. Ensure the Importer OS is up, `sshd` listening on **`:22`**, and no host firewall drops those sources.
## SSH key (Paperclip → `root` on Importer)
Use the same **Ed25519** public key as [BIT-720](/BIT/issues/BIT-720) / [BIT-721](/BIT/issues/BIT-721) (`paperclip@bitreport-cto`):
On **`10.10.50.17`** as **`paperclip`**:
```bash
cat ~/.ssh/id_ed25519.pub
```
On **`192.168.1.123`** as a user with privilege to edit **`root`** keys (console, IPMI, or existing SSH):
```bash
install -d -m 700 /root/.ssh
touch /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
grep -qF '<paste line from id_ed25519.pub>' /root/.ssh/authorized_keys || echo '<paste line>' >> /root/.ssh/authorized_keys
```
**Do not** commit private keys or paste them into issues.
## Alternative path (Proxmox guest)
If the Importer is an LXC/VM on **node9** and LAN routing cannot be fixed quickly, **`root`** on the Paperclip host may use **`pct`** via **`ssh [email protected]`** after one-time trust — see Paperclip meta-repo `docs/runbooks/AUTOMATION_PAPERCLIP_HOST_NODE9.md` and `tools/proxmox/push_pubkey_to_lxc_via_node9.sh` (workstation or **`root`** on **10.10.50.17** with node9 key). The unprivileged **`paperclip`** account does not perform that hop unless explicitly configured.
## Verification (automation-friendly)
From the **`errors.bitreport.pt`** repo on a machine that should have access (normally **10.10.50.17**):
```bash
./scripts/devops/verify_importer_ssh_bit1044.sh
```
Exit code **0** only when the BatchMode SSH check succeeds.
## Related hub docs
- [BIT-1079](/BIT/issues/BIT-1079) — CTO escalation when **`192.168.1.123`** is offline or LAN routing is broken for multiple dependents ([BIT-1044](/BIT/issues/BIT-1044), [BIT-1041](/BIT/issues/BIT-1041), etc.).
- [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — Importer reachability note for runners.
- [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — Importer deploy references.
+110
View File
@@ -0,0 +1,110 @@
# Runbook — `wdmi-store` Importer: `mkdir(): File exists` (cache em disco)
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
**Contraste:** [RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md](RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md) cobre **`mkdir(): Permission denied`** no CRM; aqui a mensagem é **`File exists`**, com causa raiz diferente.
**Última revisão:** 2026-04-05
**Contexto:** O stack no hub pode citar **`Engine\CacheFilesystem::putFile()`** / `CacheFilesystem.class.php` (~28) em instalações ou árvores antigas; no **Importer que alimenta produção** (`BitReport.pt/WDMI_UBUNTU`, sync para o guest — ver comentários em [BIT-985](/BIT/issues/BIT-985)), a criação de directórios de cache foi corrigida em **`Engine/Cache.class.php`** (`setCachedFile()` → `ensureCacheDirectory()` com `mkdir` idempotente, commit [4cd6d10d](https://git.bitreport.pt/BitReport.pt/WDMI_UBUNTU/commit/4cd6d10d) em `master`). A corrida manifesta-se sob jobs paralelos (`__maintenance_build.php`, `_ingram.php`, etc.). No hub: [BIT-924](/BIT/issues/BIT-924), cluster `ERRCLUSTER:57ccbd98f57e`, loop [BIT-309](/BIT/issues/BIT-309). **Se a assinatura voltar após [BIT-985](/BIT/issues/BIT-985) fechada com gate de deploy:** confirmar que **todo** o código em execução no guest inclui `ensureCacheDirectory` (pull/webhook, sem PHP opcache antigo) e resolver incidentes antigos no hub com `er-cli`.
---
## 1. O que o erro significa
- O código tenta **`mkdir()`** para garantir um directório de cache antes de escrever um ficheiro.
- **`mkdir(): File exists`** (PHP warning, frequentemente capturado pelo `ErrorMonitoringReporter`) significa que o alvo **já existe no filesystem** de forma incompatível com `mkdir` naquele momento — não é (tipicamente) falta de permissão (ver runbook CRM acima).
- Causas frequentes:
1. **Condição de corrida:** dois ou mais processos PHP criam o mesmo subdirectório em simultâneo; um ganha e o outro recebe `EEXIST`.
2. **Colisão path/ficheiro:** o segmento final do caminho de cache **já é um ficheiro** (chave de cache mapeada para um path inválido, artefacto de deploy, ou limpeza parcial).
3. **Estrutura inconsistente:** symlink ou árvore de cache partilhada entre ambientes/jobs de forma inesperada.
Isto é um problema **no host `wdmi-store` / código Importer e uso concorrente do cache**, não do hub de erros.
---
## 2. Reprodução e diagnóstico no host afetado
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
1. **Identificar onde o `mkdir` é chamado na árvore *real* em execução:**
- Preferir **`Engine/Cache.class.php`** — procurar `ensureCacheDirectory` / `setCachedFile` / `mkdir`.
- Em árvores legadas ou monorepos diferentes, pode existir **`Engine/CacheFilesystem.class.php`**; alinhar o diagnóstico ao ficheiro que o autoload efectivamente carrega.
2. **Correlacionar com o evento no hub:** `unique_id` / contexto da mensagem, se disponível, e horário — cruzar com **cron** de `__maintenance_build.php`, jobs `_ingram.php`, e número de workers PHP.
3. **Inspeccionar o path alvo** quando o erro ocorre (log adicional temporário ou `strace` / audit em ambiente de staging, se política permitir):
- Se o último componente **já existe como ficheiro** → tratar como colisão de naming ou limpeza.
- Se é directório e o erro é esporádico sob carga → forte indício de **corrida**.
4. **Listar concorrência:** verificar se o mesmo job está agendado em sobreposição (múltiplas entradas crontab, `systemd` timers, ou deploy com duas versões a correr).
---
## 3. Checklist de causa raiz (ordem sugerida)
1. **Sobreposição de jobs** — duas instâncias do mesmo maintenance/import ao mesmo tempo.
2. **Race em `mkdir`** — código que não trata “já existe” de forma idempotente (deveria usar `is_dir` / `clearstatcache` após `@mkdir`, ou tratar `EEXIST` como sucesso quando o resultado final é um directório válido).
3. **Colisão ficheiro vs directório** no path de cache.
4. **Cache partilhado** entre utilizadores/processos com permissões que permitem criar ficheiros no meio da árvore esperada.
5. **Deploy incompleto** — repositório corrigido em Gitea mas guest ainda sem `ensureCacheDirectory` em `Cache.class.php` (ver §2).
6. **Não mascarar no hub** — não filtrar esta assinatura como ruído até existir correção ou mitigação no Importer em execução; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando existir no repositório.
---
## 4. Mitigação recomendada (código / operações)
- **Código (referência aplicada em WDMI_UBUNTU):** `ensureCacheDirectory()` com criação recursiva idempotente (`@mkdir`, `clearstatcache`, validação `is_dir`; retry sem `@` em falhas reais) antes de escrever ficheiros em cache — ver [BIT-985](/BIT/issues/BIT-985) e commit ligado no § *Contexto*.
- **Operações:** evitar **overlap** explícito de crons pesados; garantir **single runner** por job de manutenção onde aplicável; após `git pull`, reiniciar PHP-FPM se necessário para limpar opcache.
- Após deploy da correcção, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com a mesma `ERRSIG`.
---
## 5. Ligação ao hub (errors.bitreport.pt)
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:57ccbd98f57e"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:db6f9979f37d"
./scripts/er-cli.sh list-open --project wdmi-store --q "db6f9979f37d"
./scripts/er-cli.sh list-open --project wdmi-store --q "Cache.class.php"
./scripts/er-cli.sh list-open --project wdmi-store --q "CacheFilesystem.class.php"
./scripts/er-cli.sh list-open --project wdmi-store --q "mkdir(): File exists"
./scripts/er-cli.sh list-open --project wdmi-store --q "CacheFilesystem"
```
### 5.1 Caso documentado — `wdmi-store` / cache (`mkdir` `File exists`, BIT-924)
- **Paperclip:** [BIT-924](/BIT/issues/BIT-924) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309)); entrega de código em [BIT-985](/BIT/issues/BIT-985).
- **Cluster (hub):** `ERRCLUSTER:57ccbd98f57e` (pode coincidir com o título da issue no Paperclip)
- **Mensagem típica:** `mkdir(): File exists`
- **Origem no stack (hub):** frequentemente `Engine\CacheFilesystem.class.php` (~28) **ou** caminhos via `Engine\Cache` → `ProductInformation` → `Product` → `_ingram.php` / `__maintenance_build.php` — validar no servidor qual ficheiro está em uso.
- **Acção no produto:** confirmar mitigação em **`Engine/Cache.class.php`** no guest de produção; usar §2–§3 para corrida vs colisão vs deploy pendente.
---
## 6. Evidência de deploy (gate Paperclip `in_review`)
O comentário automático `paperclip-in-review-gate` exige **evidência de produção** na thread da issue. Quem tiver SSH ao guest Importer deve colar num **comentário** em [BIT-924](/BIT/issues/BIT-924) a saída (ou equivalente) de:
```bash
# No host onde corre o Importer (ajustar path se diferente)
grep -n ensureCacheDirectory /data/wwwroot/default/Importer/Engine/Cache.class.php | head -5
cd /data/wwwroot/default/Importer && (git rev-parse HEAD 2>/dev/null || echo "checkout não-git / path alternativo")
```
Opcional — hub sem incidentes abertos para o cluster:
```bash
# Máquina com ERROR_RESOLVE_API_KEY e acesso à API do hub
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:57ccbd98f57e"
```
**Nota:** mesmo com `eth1` `192.168.1.239/24` no host Paperclip (`10.10.50.17`), o alvo **`192.168.1.123`** (Importer LAN canónico) continua **inacessível** (ICMP sem resposta; TCP/22 *No route to host*; vizinho ARP **INCOMPLETE** / **FAILED**). O mesmo sintoma verifica-se a partir do LXC **CT 220** (`wdmi-store`, `192.168.1.17`). Abrir firewall / rota ou confirmar IP de produção em [BIT-1044](/BIT/issues/BIT-1044). Até lá, runners **não** substituem evidência no guest; só documentar o procedimento.
**Reabertura pelo loop após `done`:** se o loop [BIT-309](/BIT/issues/BIT-309) voltar a registar recorrência na issue [BIT-924](/BIT/issues/BIT-924) **depois** de o gate `in_review` ter passado e a issue ter ido para `done`, tratar como **revalidação obrigatória**: repetir §6 e §3 — vários pools PHP / opcache, segundo docroot ou release antiga, ou incidentes ainda **abertos** no hub (resolver com `er-cli` após confirmar ausência de novos eventos).
---
## Ver também
- [RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md](RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md) — rede + SSH Paperclip → Importer **192.168.1.123** ([BIT-1044](/BIT/issues/BIT-1044)).
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
- [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — upload de feeds (`clients.wdmi.pt`).
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
File diff suppressed because it is too large. Load diff
+297
View File
@@ -0,0 +1,297 @@
# Runbook — `simplexml_load_file` no Importer Flexit (`wdmi-store`)
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
**Última revisão:** 2026-04-05
**Contexto:** Erros de PHP em `simplexml_load_file()` originados em `Importer/_flexit.php` (tipicamente linha ~53), incluídos via `__maintenance_build.php`. Exemplos de assinatura no hub: `ERRSIG:6f82e20ec332`, `ERRSIG:5278058355a5`, `ERRSIG:948b0236b852`, `ERRSIG:033b36032168`, `ERRSIG:102101c1758d`, `ERRSIG:37670027b2d7`, `ERRSIG:5e3b58b8a99f`, `ERRSIG:63100e2b35c0`, `ERRSIG:4ca3a546fb62`, `ERRSIG:8e233f7a57b8`.
---
## 1. O que o erro significa
- `simplexml_load_file()` falha quando o **ficheiro ou URL** passado não é legível, não existe, está vazio/corrupto, ou o conteúdo **não é XML válido**.
- O stack típico inclui `_flexit.php` ← `__maintenance_build.php` (job de manutenção / build de dados Flexit).
Isto é um problema **no host / ficheiros de entrada / conteúdo XML** do job Importer, não um bug do hub de erros.
---
## 2. Reprodução e diagnóstico no host afetado
Executar **no mesmo servidor** onde corre o PHP (caminho típico `/data/wwwroot/default/Importer/`).
1. **Confirmar o argumento efectivo** em `_flexit.php` (caminho local, URL, ou variável derivada) na linha indicada pelo stack — sem isso não há correção segura.
2. **Se for caminho local:**
- `test -r "<path>" && echo OK || echo unreadable`
- `head -c 400 "<path>"` — ver se há conteúdo e se começa por `<?xml` ou elemento raiz esperado.
3. **Se for URL remota:**
- `curl -sfS --max-time 30 -o /tmp/flexit-sample.xml "<url>" && xmllint --noout /tmp/flexit-sample.xml`
- Verificar `allow_url_fopen`, timeouts, TLS e DNS no host (ver também [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) se o feed passar por HTTPS problemático).
4. **Permissões e utilizador do PHP-FPM / Apache** — o processo web/CLI que corre o maintenance script tem de conseguir ler o ficheiro ou alcançar a URL.
### 2.1 Ficheiro local `FlexIT.XML` (wdmi-store — path típico)
No host onde corre o Importer, alinhar com o checklist [BIT-984](/BIT/issues/BIT-984) (execução fora de `errors.bitreport.pt`). A partir de `/data/wwwroot/default/Importer`:
```bash
test -r downloads/FlexIT.XML && echo OK || echo unreadable
head -c 400 downloads/FlexIT.XML
xmllint --noout downloads/FlexIT.XML
```
Equivalente a partir de `/data/wwwroot/default`:
```bash
test -r Importer/downloads/FlexIT.XML && echo OK || echo unreadable
head -c 400 Importer/downloads/FlexIT.XML
xmllint --noout Importer/downloads/FlexIT.XML
```
Se a fonte for **URL remota**, usar o padrão do §2 (item 3) com o URL efectivo lido em `_flexit.php`.
---
## 3. Checklist de causa raiz (ordem sugerida)
1. **Ficheiro ausente ou path errado** — deploy incompleto, variável de ambiente errada, ou directorio de trabalho diferente entre cron e web.
2. **Ficheiro vazio ou truncado** — escrita concorrente, disco cheio, download incompleto.
3. **XML inválido** — feed externo alterado, encoding errado (BOM, `UTF-8` vs `ISO-8859-1`), entidades não declaradas.
4. **Race / ordem de jobs** — `__maintenance_build.php` a correr antes de o ficheiro estar disponível; considerar lock ou pré-condição explícita no script.
5. **Não mascarar no hub** — evitar filtros de ruído até a causa de dados/caminho estar tratada; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md).
---
## 4. Mitigação na aplicação (recomendado)
- Validar existência e tamanho mínimo **antes** de `simplexml_load_file()`; logar caminho/URL (sanitizado) e `libxml_get_errors()` em falha.
- Usar `libxml_use_internal_errors(true)` para mensagens controladas e não depender só do warning genérico.
- Tornar o job **idempotente** e, se aplicável, **retry com backoff** quando a fonte for remota e intermitente.
---
## 5. Ligação ao hub (errors.bitreport.pt)
- Listar incidentes abertos por assinatura ou texto:
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:6f82e20ec332"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5278058355a5"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:e83a5ee5e95d"
./scripts/er-cli.sh list-open --project wdmi-store --q "e83a5ee5e95d"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:948b0236b852"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:8e1c5d253902"
./scripts/er-cli.sh list-open --project wdmi-store --q "8e1c5d253902"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:033b36032168"
./scripts/er-cli.sh list-open --project wdmi-store --q "d75e81fb29c9"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:102101c1758d"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:37670027b2d7"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:32b818809f98"
./scripts/er-cli.sh list-open --project wdmi-store --q "32b818809f98"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:4ca3a546fb62"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:8e233f7a57b8"
./scripts/er-cli.sh list-open --project wdmi-store --q "eb0dad83413f"
./scripts/er-cli.sh list-open --project wdmi-store --q "f2d78c625221"
./scripts/er-cli.sh list-open --project wdmi-store --q "simplexml_load_file"
./scripts/er-cli.sh list-open --project wdmi-store --q "_flexit.php"
```
- Após correcção no reporter (ficheiro válido, path correcto, ou tratamento de erro explícito), **resolver** incidentes conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar que novos eventos deixaram de ingressar.
### 5.1 Caso documentado — `wdmi-store` / Flexit (BIT-877)
- **Assinatura:** `ERRSIG:6f82e20ec332`
- **Cluster (loop BIT-309):** `ERRCLUSTER:0eaf1e3a7ef5` — o título ou comentários Paperclip podem referir este cluster; a triagem operacional é a mesma que para a assinatura acima.
- **Mensagem típica:** `simplexml_load_file():` (warning/notice capturado pelo reporter)
- **Stack útil:** `_flexit.php` ← `__maintenance_build.php`
- **Correção aplicacional (histórico):** filho [BIT-915](/BIT/issues/BIT-915) fechado com endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` (validação pré-parse, `simplexml_load_string` com flags libxml). **Deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (`gitea-sync-importer.sh` a partir de `BitReport.pt/WDMI_UBUNTU.git`).
- **Acção no produto:** após deploy, confirmar ausência de novos eventos; **resolver** incidentes antigos ainda abertos no hub para esta assinatura/cluster (ver comandos abaixo). Se o cluster voltar a ingressar após deploy verificado, reabrir triagem no produto (feed ou ficheiro local corrupto).
- **Ciclo Paperclip:** se [BIT-877](/BIT/issues/BIT-877) for fechada e o loop BIT-309 **reabrir** o mesmo ticket com este cluster, tratar primeiro como **deploy não reflectido** ou **incidentes `open` no hub** — não como defeito novo do repositório `errors.bitreport.pt` sem evidência em produção.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:0eaf1e3a7ef5"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:6f82e20ec332"
```
### 5.2 Caso documentado — `wdmi-store` / Flexit (BIT-903)
- **Assinatura:** `ERRSIG:5278058355a5`
- **Cluster (loop BIT-309):** `ERRCLUSTER:e83a5ee5e95d` — quando o título ou comentários Paperclip referirem este cluster, a triagem operacional é a mesma que para **ERRSIG:5278058355a5**.
- **Paperclip:** [BIT-903](/BIT/issues/BIT-903) (recorrências agregadas pelo loop BIT-309)
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" na mesma thread confirmam que o loop voltou a observar eventos neste cluster (ou incidentes ainda relevantes no hub). Tratar como **sinal do reporter / dados de entrada** ou backlog de resolução no hub — **não** como falha de ingest em `errors.bitreport.pt`.
- **Mensagem típica (excerpt):** texto de erro que inclui fragmentos de markup (`…ebDescription></Record><Record><Manufacturer>HPINC…`) — indica **XML mal formado ou truncado** (parser a falhar no meio do stream), não um problema do hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Correção aplicacional (referência):** endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` e checklist de host em [BIT-915](/BIT/issues/BIT-915) / [BIT-984](/BIT/issues/BIT-984); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou os dados de entrada estarem estáveis, novos eventos podem continuar a ingressar.
- **Acção no produto:** seguir §2–§4 deste runbook no host de `wdmi-store` (validar ficheiro/URL de entrada, `xmllint`, permissões, corrupção de feed); aplicar validação pré-parse e logging com `libxml_get_errors()` antes de marcar resolvido no hub.
- **Stack ainda com `simplexml_load_file()` em `_flexit.php` (~53):** tratar primeiro como Importer em produção **sem** o endurecimento BIT-915 (`47d2c2bf`) — usar os mesmos comandos `grep` / `nl` de verificação pós-deploy descritos em §5.3.1 (*Código antigo em produção*, BIT-968); o procedimento é o mesmo para **ERRSIG:5278058355a5** e para as outras assinaturas FlexIT deste runbook.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5278058355a5"
./scripts/er-cli.sh list-open --project wdmi-store --q "5278058355a5"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:e83a5ee5e95d"
./scripts/er-cli.sh list-open --project wdmi-store --q "e83a5ee5e95d"
```
### 5.3 Caso documentado — `wdmi-store` / Flexit (BIT-920)
- **Assinatura:** `ERRSIG:948b0236b852`
- **Cluster (loop BIT-309):** `ERRCLUSTER:8e1c5d253902` — o título ou comentários Paperclip podem referir este cluster; a triagem operacional é a mesma que para a assinatura acima.
- **Paperclip:** [BIT-920](/BIT/issues/BIT-920) (recorrências agregadas pelo loop BIT-309). Execução no host: follow-up [BIT-968](/BIT/issues/BIT-968) (quando aberto).
- **Mensagem típica (excerpt):** `simplexml_load_file(): ><NAVPN>L70777-051-RP</NAVPN><OS></OS><WebDescription></WebDescription></Record>` — fragmento de markup no texto do erro; mesma classe operacional que §5.2 (**XML mal formado ou truncado** / entrada inválida para o parser), não falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Acção no produto:** seguir §2–§4 deste runbook no host de `wdmi-store`; alinhar com §5.2 para validação pré-parse e logging. Resolver no hub após deploy e confirmação de ausência de novos eventos com esta assinatura.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:948b0236b852"
./scripts/er-cli.sh list-open --project wdmi-store --q "948b0236b852"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:8e1c5d253902"
./scripts/er-cli.sh list-open --project wdmi-store --q "8e1c5d253902"
./scripts/er-cli.sh list-open --project wdmi-store --q "NAVPN"
```
#### 5.3.1 Código antigo em produção — `simplexml_load_file()` na linha ~53 (BIT-968)
- **Projecto no hub vs. guest Proxmox:** o projecto de erros **`wdmi-store`** no hub identifica a **aplicação** que reporta; o caminho típico **`/data/wwwroot/default/Importer/`** é docroot **PHP** (Importer clássico). O LXC **`wdmi-store`** (CT **220**, **10.10.50.20** na matriz interna — ver `docs/ENVIRONMENTS.md` § LXC) é a stack **WDMI_STORE** (Node/Fastify) e **não** expõe, por omissão, esse docroot. **Não** assumir que o hostname do projecto no hub coincide com o guest onde corre o PHP Importer.
- **Alvo canónico (deploy PHP Importer):** conforme o [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) §2, o sync da árvore **`WDMI_UBUNTU`** aplica-se ao servidor **Importer** em **LAN `192.168.1.123`** (`/usr/local/sbin/gitea-sync-importer.sh`; fila CRM **69** → SSH ao **123**). O código fonte está no monorepo **`BitReport.pt/WDMI`**, caminho **`WDMI_UBUNTU/default/Importer/`**. Isto **não** é o LXC **CT 220** `wdmi-store` (**WDMI_STORE**). Excepções ao IP ficam apenas no **vault** / inventário aprovado pelo board.
- Se o stack no hub ainda mostrar **`simplexml_load_file()`** em **`_flexit.php` (~53)**, o docroot em produção **não** reflecte o Importer endurecido já fundido no monorepo **`BitReport.pt/WDMI`**, caminho **`WDMI_UBUNTU/default/Importer/_flexit.php`** (commit **`47d2c2bf`** — *harden FlexIT XML parse for error hub BIT-915*; antecessor histórico BIT-877 / [BIT-915](/BIT/issues/BIT-915)).
- No **`main`** actual de **`BitReport.pt/WDMI`** (directório **`WDMI_UBUNTU/default/Importer/_flexit.php`**), por volta da linha 53 aparece **`$oXML = false;`**, seguido de **`file_get_contents`** + **`simplexml_load_string(..., LIBXML_NOERROR | LIBXML_NOWARNING)`** — não **`simplexml_load_file()`**.
- **Remediação:** sincronizar `default/Importer/` para `/data/wwwroot/default/Importer/` conforme o [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (ex.: **`gitea-sync-importer.sh`** a partir de **`WDMI_UBUNTU`**; alinhar com §5.1 / BIT-915).
- **Verificação pós-deploy** no servidor:
```bash
grep -n simplexml_load_file /data/wwwroot/default/Importer/_flexit.php || echo "OK: no simplexml_load_file in _flexit.php"
nl -ba /data/wwwroot/default/Importer/_flexit.php | sed -n '50,72p'
```
- Só depois disto faz sentido tratar **feed/XML inválido** como causa residual (§2–§4). Fechar **BIT-968** / **BIT-920** após deploy **e** ausência de novos eventos **`ERRSIG:948b0236b852`** (ver [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md)).
### 5.4 Caso documentado — `wdmi-store` / Flexit (BIT-926)
- **Assinatura:** `ERRSIG:033b36032168`
- **Cluster (loop BIT-309):** `ERRCLUSTER:d75e81fb29c9` — quando o título ou comentário Paperclip referir este cluster, a triagem operacional é a mesma que para **ERRSIG:033b36032168** (histórico único na board).
- **Paperclip:** [BIT-926](/BIT/issues/BIT-926) (recorrências agregadas pelo loop BIT-309)
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Opening and ending tag mismatch: Record line 1 and ManufacturerPartNumber` — **XML mal formado** (tags não fechadas na ordem esperada ou conteúdo corrupto no ficheiro local `FlexIT.XML`), mesma classe operacional que §5.2–§5.3; não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Correção aplicacional (referência):** checklist no host + hardening `_flexit.php` em [BIT-984](/BIT/issues/BIT-984) (filha de [BIT-950](/BIT/issues/BIT-950)); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, o loop pode continuar a comentar recorrências nesta issue.
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:033b36032168"
./scripts/er-cli.sh list-open --project wdmi-store --q "033b36032168"
./scripts/er-cli.sh list-open --project wdmi-store --q "d75e81fb29c9"
./scripts/er-cli.sh list-open --project wdmi-store --q "FlexIT.XML"
```
### 5.5 Caso documentado — `wdmi-store` / Flexit (BIT-932)
- **Assinatura:** `ERRSIG:102101c1758d`
- **Paperclip:** [BIT-932](/BIT/issues/BIT-932) (recorrências agregadas pelo loop BIT-309)
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Couldn't find end of Start Tag Manufac1-RP-N2 line 1` — **XML mal formado** (tag de abertura não fechada / conteúdo corrupto no ficheiro local `FlexIT.XML`), mesma classe operacional que §5.2–§5.4; não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente, feed truncado); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:102101c1758d"
./scripts/er-cli.sh list-open --project wdmi-store --q "102101c1758d"
./scripts/er-cli.sh list-open --project wdmi-store --q "Manufac1-RP-N2"
```
### 5.6 Caso documentado — `wdmi-store` / Flexit (BIT-939)
- **Assinatura:** `ERRSIG:37670027b2d7`
- **Cluster (loop BIT-309):** `ERRCLUSTER:32b818809f98` — quando o título ou comentários Paperclip referirem este cluster, a triagem operacional é a mesma que para **ERRSIG:37670027b2d7** (histórico único na board).
- **Paperclip:** [BIT-939](/BIT/issues/BIT-939) (recorrências agregadas pelo loop BIT-309)
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" ou "Recorrência após fecho" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Extra content at the end of the document` — indica **XML com mais do que um documento raiz**, lixo/append após o fecho do documento válido, ou **ficheiro concatenado / escrita concorrente** que deixou bytes extra no `FlexIT.XML` local; mesma classe operacional que §5.2–§5.5; não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Correção aplicacional (referência):** checklist no host + hardening `_flexit.php` em [BIT-984](/BIT/issues/BIT-984) (filha de [BIT-950](/BIT/issues/BIT-950)); alinhar com [BIT-915](/BIT/issues/BIT-915) e §2–§4; **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, o loop pode continuar a comentar recorrências nesta issue.
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (tamanho, `tail`, procura por segundo `<?xml` ou markup após o fecho do primeiro documento); validar com `xmllint --noout`; rever download atómico / lock se dois jobs escrevem o mesmo path; seguir §2–§4. Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
- **Ciclo Paperclip:** se [BIT-939](/BIT/issues/BIT-939) for fechada e o loop BIT-309 **reabrir** a mesma issue com este cluster, tratar primeiro como **dados de entrada / deploy não reflectido** ou **incidentes `open` no hub** — não como defeito novo do repositório `errors.bitreport.pt` sem evidência em produção.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:37670027b2d7"
./scripts/er-cli.sh list-open --project wdmi-store --q "37670027b2d7"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:32b818809f98"
./scripts/er-cli.sh list-open --project wdmi-store --q "32b818809f98"
./scripts/er-cli.sh list-open --project wdmi-store --q "Extra content at the end"
```
### 5.7 Caso documentado — `wdmi-store` / Flexit (BIT-945)
- **Assinatura:** `ERRSIG:5e3b58b8a99f`
- **Paperclip:** [BIT-945](/BIT/issues/BIT-945) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
- **Cluster (agregação BIT-309):** `ERRCLUSTER:2f4da462d83a` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família que §5.2–§5.6.
- **Comentários automáticos de recorrência (BIT-309):** entradas do tipo "Recorrência detetada" ou "Recorrência após fecho" na mesma thread confirmam que o loop voltou a observar eventos neste cluster — **sem nova causa no hub**; tratar como sinal de **dados de entrada / guest** ou incidentes ainda `open` no hub até deploy e resolução em massa.
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : attributes construct error` — indica **atributos XML mal formados** (aspas em falta ou desemparelhadas, `=` inválido, caracteres não escapados em valores de atributo, ou markup corrupto na primeira linha do ficheiro local `FlexIT.XML`); mesma classe operacional que §5.2–§5.6 (**XML inválido no ficheiro de entrada**); não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Correção aplicacional (referência):** checklist no host + endurecimento em `WDMI_UBUNTU/default/Importer/_flexit.php` em [BIT-984](/BIT/issues/BIT-984) / [BIT-915](/BIT/issues/BIT-915); **deploy** para `/data/wwwroot/default/Importer/` conforme [WDMI deploy runbook](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/WDMI_DEPLOY_RUNBOOK.md) (`gitea-sync-importer.sh` a partir de `BitReport.pt/WDMI_UBUNTU.git`). Até o guest reflectir o código ou o `FlexIT.XML` estar válido, novos eventos podem continuar a ingressar.
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (`head`, `xmllint --noout`, encoding); seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência / download atómico se aplicável). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
- **Reabertura após fecho (loop [BIT-309](/BIT/issues/BIT-309)):** novos eventos com a mesma assinatura ou cluster **depois** de a issue Paperclip estar `done` significam que o **Importer em `wdmi-store` continua a receber ou a parsear XML inválido** — repetir diagnósticos §2–§4; só então marcar a issue como concluída e resolver incidentes no hub com evidência (`./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"` vazio ou janela 24–48h estável sem ingresso).
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:5e3b58b8a99f"
./scripts/er-cli.sh list-open --project wdmi-store --q "5e3b58b8a99f"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:2f4da462d83a"
./scripts/er-cli.sh list-open --project wdmi-store --q "2f4da462d83a"
./scripts/er-cli.sh list-open --project wdmi-store --q "attributes construct error"
```
### 5.8 Caso documentado — `wdmi-store` / Flexit (BIT-946)
- **Assinatura:** `ERRSIG:63100e2b35c0`
- **Paperclip:** [BIT-946](/BIT/issues/BIT-946) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
- **Cluster (agregação BIT-309):** `ERRCLUSTER:a44bd34001aa` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família que §5.2–§5.7.
- **Mensagem típica (excerpt):** `simplexml_load_file(): ecord><Manufacturer>HPINC</Manufacturer><Manufac1-RP-N2</ManufacturerPartNumber>` — fragmento de markup truncado ou corrupto no texto do erro (stream incompleto / XML inválido), alinhado com §5.2 e §5.5 (inclui referência a `Manufac1-RP-N2`); não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Acção no produto:** no host de `wdmi-store`, seguir §2–§4 (inspeccionar `Importer/downloads/FlexIT.XML` ou URL de origem, `xmllint --noout`, encoding, download atómico e locks se houver escrita concorrente). Resolver no hub após deploy e confirmação de ausência de novos eventos com esta assinatura.
- **Reabertura após fecho (loop [BIT-309](/BIT/issues/BIT-309)):** novos eventos com a mesma assinatura ou cluster **depois** de a issue Paperclip estar `done` significam que o **Importer em `wdmi-store` continua a falhar com XML truncado/corrupto** — o runbook no repositório `errors.bitreport.pt` não substitui deploy no guest. Repetir diagnósticos §2–§4; só então marcar a issue como concluída e resolver incidentes no hub com evidência (`./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"` sem novos abertos relevantes ou janela 24–48h estável sem ingresso).
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:63100e2b35c0"
./scripts/er-cli.sh list-open --project wdmi-store --q "63100e2b35c0"
./scripts/er-cli.sh list-open --project wdmi-store --q "Manufac1-RP-N2"
```
### 5.9 Caso documentado — `wdmi-store` / Flexit (BIT-943)
- **Assinatura:** `ERRSIG:4ca3a546fb62`
- **Paperclip:** [BIT-943](/BIT/issues/BIT-943) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
- **Cluster (agregação BIT-309):** `ERRCLUSTER:eb0dad83413f` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família operacional que §5.7 (**atributos / markup inválido na primeira linha** do `FlexIT.XML` local), com texto de diagnóstico libxml distinto.
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : error parsing attribute name` — indica **nome de atributo XML inválido** ou **estrutura de atributos corrupta** (token inesperado antes de `=`, caracteres ilegais no nome do atributo, ou markup partido na zona de atributos); não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (`head -c`, `xmllint --noout`, encoding); alinhar com §5.7 para hipóteses (aspas, `=`, entidades); seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, download atómico / locks se aplicável). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:4ca3a546fb62"
./scripts/er-cli.sh list-open --project wdmi-store --q "4ca3a546fb62"
./scripts/er-cli.sh list-open --project wdmi-store --q "eb0dad83413f"
./scripts/er-cli.sh list-open --project wdmi-store --q "error parsing attribute name"
```
### 5.10 Caso documentado — `wdmi-store` / Flexit (BIT-950)
- **Assinatura:** `ERRSIG:8e233f7a57b8`
- **Paperclip:** [BIT-950](/BIT/issues/BIT-950) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309)); tarefa filha operacional [BIT-984](/BIT/issues/BIT-984) (validação no host + hardening `_flexit.php`). Meta de fila / ownership quando o pulse assinalar execução presa: [BIT-988](/BIT/issues/BIT-988) (filha de BIT-984).
- **Cluster (agregação BIT-309):** `ERRCLUSTER:f2d78c625221` — pode conter só esta assinatura enquanto o sintoma for estável; tratar como a mesma família operacional que §5.4 (**tag mismatch** no `FlexIT.XML` local).
- **Mensagem típica (excerpt):** `simplexml_load_file(): …/Importer/downloads/FlexIT.XML:1: parser error : Opening and ending tag mismatch: FlexIT_DataExport line 1 and Record` — **XML mal formado** (estrutura de tags incoerente na raiz ou conteúdo corrupto no ficheiro local `FlexIT.XML`); não é falha de ingest no hub.
- **Stack útil:** `_flexit.php` (≈53) ← `__maintenance_build.php`
- **Acção no produto:** no host de `wdmi-store`, inspeccionar `Importer/downloads/FlexIT.XML` (integridade, encoding, escrita concorrente, feed truncado); validar com `xmllint --noout`; seguir §2–§4 (pré-validação, `libxml_use_internal_errors`, idempotência). Resolver no hub após deploy e ausência de novos eventos com esta assinatura.
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:8e233f7a57b8"
./scripts/er-cli.sh list-open --project wdmi-store --q "8e233f7a57b8"
./scripts/er-cli.sh list-open --project wdmi-store --q "f2d78c625221"
./scripts/er-cli.sh list-open --project wdmi-store --q "FlexIT_DataExport"
```
---
## Ver também
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
- [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — falhas de upload de feed para `clients.wdmi.pt` (`_upload_feed_via_api`).
- [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) — TLS/cURL para APIs Google no reporter PHP.
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
@@ -0,0 +1,112 @@
# Runbook — Importer (`wdmi-store` / `wdmi-ubuntu`): `SimpleXLS` / `_auferma.php` (`Uninitialized string offset`)
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store`, **`wdmi-ubuntu`** / `Importer`).
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
**Última revisão:** 2026-04-05
**Contexto:** Avisos/erros PHP do tipo **`Uninitialized string offset`** (índice muito elevado, ex. `557102`) originados em `vendor/shuchkin/simplexls/src/SimpleXLS.php` durante `_parse()`, invocados desde `_auferma.php` (tipicamente `SimpleXLS::parse()` ≈ linha 61) e incluídos via `__maintenance_build.php`. No hub, caso documentado em **`wdmi-store`:** [BIT-869](/BIT/issues/BIT-869) com **cluster** `ERRCLUSTER:0a642d62d724` (agregação [BIT-309](/BIT/issues/BIT-309)), onde o hub pode agregar mais do que uma `ERRSIG` (p.ex. `57ad438cb103` e `9a08d2cdd005` na mesma recorrência). Instalações com **`project_slug` `wdmi-ubuntu`** seguem o **mesmo plano técnico** no guest onde corre o Importer — ver §5.3 ([BIT-1055](/BIT/issues/BIT-1055)).
---
## 1. O que o erro significa
- A biblioteca **SimpleXLS** (Shuchkin) está a indexar uma **string interna** (buffer do ficheiro BIFF/XLS) **fora dos limites** — o índice reportado costuma reflectir **offset binário** dentro do stream parseado.
- Causas típicas no **reporter**:
1. **Ficheiro `.xls` corrupto, truncado ou incompleto** (download interrompido, disco cheio, escrita concorrente).
2. **Ficheiro que não é um XLS legível** pela versão do vendor (extensão errada, HTML de erro no lugar do binário, ficheiro vazio).
3. **Bug ou limite** na versão fixada do `vendor/shuchkin/simplexls` para certos inputs (menos comum que ficheiro inválido).
Isto é um problema **no host onde corre o Importer** (`wdmi-store`, **`wdmi-ubuntu`**, etc.) — **ficheiro de entrada e parser XLS** — não do hub de erros.
---
## 2. Reprodução e diagnóstico no host afetado
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
1. **Identificar o path do `.xls`** passado a `SimpleXLS::parse()` em `_auferma.php` (variável ou constante efectiva na linha indicada pelo stack).
2. **Inspeccionar o ficheiro:**
- `ls -l "<path>"` — tamanho zero ou suspeitamente pequeno vs. esperado.
- `file "<path>"` — deve indicar dados compostos / CDF / Microsoft Excel (conforme `file` no host).
- `xxd "<path>" | head` — assinatura binária; ficheiros HTML ou texto puro são red flag.
3. **Correlacionar com ingestão:** o ficheiro vem de download HTTP, cópia de rede, ou filesystem partilhado? Verificar **atomicidade** (escrever para `.tmp` + `rename`) e **locks** se vários jobs partilham o mesmo path.
4. **Reproduzir em CLI** no host (PHP do mesmo ambiente): invocar o mesmo `parse()` sobre uma cópia do ficheiro problemático para confirmar.
---
## 3. Checklist de causa raiz (ordem sugerida)
1. **Integridade do ficheiro** — truncado, corrupto, ou substituído por resposta de erro (HTML/JSON).
2. **Concorrência** — dois processos a escrever o mesmo `.xls` durante o parse.
3. **Path errado** — apontar para cache antigo ou ficheiro intermédio errado.
4. **Versão do vendor** — actualizar ou substituir apenas após reprodução controlada; preferir primeiro validar input.
5. **Não mascarar no hub** — não filtrar esta assinatura como ruído até existir validação pré-parse ou correção de fonte de dados; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando existir no repositório.
---
## 4. Mitigação recomendada (código / operações)
- **Antes de `parse()`:** verificar `is_readable`, tamanho mínimo, e opcionalmente assinatura/magic bytes esperados para XLS.
- **Download / escrita:** ficheiro temporário + `rename` atómico; evitar que `__maintenance_build` leia meio-download.
- **Logging:** path (sanitizado), tamanho, e hash curto do ficheiro em falha para correlacionar com o hub (`unique_id`).
- **Vendor:** após confirmar inputs válidos, avaliar actualização do pacote `shuchkin/simplexls` ou substituição por parser mais tolerante — sempre com teste em staging.
- Após deploy, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com as mesmas `ERRSIG` / o mesmo `ERRCLUSTER`.
---
## 5. Ligação ao hub (errors.bitreport.pt)
**`wdmi-store`:**
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:57ad438cb103"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:9a08d2cdd005"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:0a642d62d724"
./scripts/er-cli.sh list-open --project wdmi-store --q "57ad438cb103"
./scripts/er-cli.sh list-open --project wdmi-store --q "_auferma.php"
./scripts/er-cli.sh list-open --project wdmi-store --q "SimpleXLS.php"
```
**`wdmi-ubuntu` (mesma família de stack):**
```bash
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRSIG:4f8c89aa27c0"
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRSIG:9e119a768e6d"
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "ERRCLUSTER:640553efed73"
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "_auferma.php"
./scripts/er-cli.sh list-open --project wdmi-ubuntu --q "SimpleXLS.php"
```
### 5.1 Caso documentado — `wdmi-store` / Auferma + SimpleXLS ([BIT-869](/BIT/issues/BIT-869))
- **Assinaturas (exemplos no mesmo cluster):** `ERRSIG:57ad438cb103`, `ERRSIG:9a08d2cdd005` — tratar como **mesma classe operacional** até o hub deixar de as agregar em `ERRCLUSTER:0a642d62d724`.
- **Cluster (agregação [BIT-309](/BIT/issues/BIT-309)):** `ERRCLUSTER:0a642d62d724`
- **Mensagem típica (excerpt):** `Uninitialized string offset 557102` em `SimpleXLS.php` (≈671) durante `_parse()`.
- **Stack útil:** `SimpleXLS.php` ← `_auferma.php` (≈61) ← `__maintenance_build.php` (≈50)
- **Acção no produto:** validar o `.xls` de entrada e a pipeline que o produz (§2–§4); não fechar no hub só por documentação sem deploy ou evidência de ficheiros válidos.
### 5.2 Reabertura automática (recorrência [BIT-309](/BIT/issues/BIT-309))
- Se o cartão Paperclip [BIT-869](/BIT/issues/BIT-869) tiver sido fechado com âmbito **só documentação** no repositório do hub, mas as **occurrences continuarem** no mesmo `ERRCLUSTER:0a642d62d724`, o agregador do loop **[BIT-309](/BIT/issues/BIT-309)** pode **reabrir** o mesmo issue (histórico único, sem duplicar cartões) e registar no comentário o volume do ciclo (ex.: ocorrências no período).
- Isto **não** indica regressão do serviço `errors.bitreport.pt`: confirma que a **causa no reporter** (`wdmi-store` / Importer / ficheiro de entrada) **persiste**. Priorizar diagnóstico §2–§4 e **deploy ou correcção no host**; só marcar o cartão Paperclip como `done` outra vez com **evidência** (ex.: ausência de novos eventos após deploy, ou resolução explícita dos incidentes no hub).
### 5.3 Caso documentado — `wdmi-ubuntu` / Auferma + SimpleXLS ([BIT-1055](/BIT/issues/BIT-1055))
- **Assinaturas agregadas no mesmo cluster:** `ERRSIG:4f8c89aa27c0`, `ERRSIG:9e119a768e6d`.
- **Cluster (agregação [BIT-309](/BIT/issues/BIT-309)):** `ERRCLUSTER:640553efed73`.
- **Mensagem típica (excerpt):** `Uninitialized string offset 557104` em `SimpleXLS.php` (≈674) durante `_parse()`.
- **Stack útil:** `SimpleXLS.php` ← `_auferma.php` (≈61) ← `__maintenance_build.php` (≈50) — mesmo desenho que §5.1; **`project_slug` no hub:** `wdmi-ubuntu`.
- **Paperclip:** cartão no projecto **[CLI] WDMI_UBUNTU** (`cli-wdmi-ubuntu`); **código / deploy:** repositório Gitea **BitReport.pt/WDMI_UBUNTU** (não o hub `errors.bitreport.pt`).
- **Acção no produto:** §2–§4 (validar `.xls`, pipeline, possível actualização do vendor); fecho no board só com **PR/commit em WDMI_UBUNTU** ou evidência operacional equivalente.
### 5.4 Reabertura — `wdmi-ubuntu` (`ERRCLUSTER:640553efed73`)
- Comentários *Recorrência* no Paperclip com o mesmo `ERRSIG` / `ERRCLUSTER` **depois** de `done` ou `bulk-resolve` no hub indicam que o **Importer em `wdmi-ubuntu` continua a falhar no parse XLS** — repetir §2–§4 no **guest correcto**; correlacionar com `er-cli` usando `--project wdmi-ubuntu` (comandos em §5).
---
## Ver também
- [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — outros jobs Importer / XML (`_flexit.php`).
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
@@ -0,0 +1,72 @@
# Runbook — `wdmi-store` Importer: Visiotech / `strlen()` com `null` (PHP 8.1+)
**Audiência:** Operação e engenharia que mantêm **aplicações que reportam** para `errors.bitreport.pt` (ex.: `wdmi-store` / `Importer`).
**Não confundir com** falhas de **ingest** no hub — para isso ver [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md).
**Última revisão:** 2026-04-05
**Contexto:** Em PHP 8.1+, **`strlen()`** com argumento **`null`** gera *deprecation* (`Passing null to parameter #1 ($string) of type string is deprecated`), frequentemente capturada pelo `ErrorMonitoringReporter` como incidente no hub. Pilhas observadas incluem `_visiotech.php` (ex.: linha ~108) durante `Product->save()` / `_applyBeforeInsert()`, acionadas por `__maintenance_build.php`. O caso documentado em [BIT-954](/BIT/issues/BIT-954) usa **assinatura** `ERRSIG:a26dda2636bd` e **cluster** `ERRCLUSTER:634c0a250aba` (agregação [BIT-309](/BIT/issues/BIT-309)). A correcção definitiva é **no código Importer** (repo **WDMI_UBUNTU** / deploy no guest); este runbook orienta triagem e fecho no hub após deploy.
---
## 1. O que o erro significa
- **`strlen(): Passing null … is deprecated`:** algum caminho de código chama `strlen($x)` quando `$x` pode ser **`null`** (campo opcional do produto, valor não preenchido no feed Visiotech, ou conversão incompleta antes do insert).
- O stack típico referencia **`_visiotech.php`** e **`Engine\Product->_applyBeforeInsert()`** — a lógica de normalização antes de gravar está a assumir string onde o runtime entrega `null`.
- Isto é **comportamento do reporter PHP** sob PHP 8.1+, não falha do hub de erros nem da API de ingestão.
---
## 2. Reprodução e diagnóstico no host afetado
Executar no servidor onde está o Importer (caminho típico `/data/wwwroot/default/Importer/`).
1. **Confirmar versão PHP** (`php -v`) — deprecations deste tipo aparecem a partir do 8.1 com `error_reporting` que inclui `E_DEPRECATED`.
2. **Abrir `_visiotech.php`** em torno da linha citada no incidente (ex.: 108) e localizar **`strlen(`** (ou helpers que o invocam indirectamente).
3. **Rastrear a origem do `null`:** campos mapeados do feed Visiotech → `Product` / arrays intermediários; verificar propriedades opcionais não inicializadas.
4. **Correlacionar com o job:** stack com `__maintenance_build.php` → reproduzir o include de `_visiotech.php` no mesmo contexto (dados de teste ou log de SKU/produto quando disponível).
---
## 3. Checklist de causa raiz (ordem sugerida)
1. **Chamada directa** `strlen($var)` sem garantir tipo `string` — substituir por padrão seguro (ver §4).
2. **Campo de produto `null`** no ramo Visiotech antes de `_applyBeforeInsert` — corrigir mapeamento / default no importador.
3. **Confundir com outro `strlen`** noutro ficheiro — validar sempre **ficheiro e linha** do evento no hub.
4. **Não filtrar como ruído** no hub até existir correcção em código — alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md) quando aplicável.
---
## 4. Mitigação recomendada (código)
- **Garantir string antes de medir comprimento:** por exemplo `(string) ($var ?? '')`, ou `strlen((string) $var)` apenas quando `null` deve contar como vazio; preferir **`$var === null || $var === ''`** quando a intenção é “vazio”, em vez de `strlen` em valores potencialmente `null`.
- **Normalizar no mapeamento Visiotech** (defaults explícitos para campos opcionais) para que `_applyBeforeInsert` não receba `null` onde esperava string.
- Após deploy, **resolver** incidentes no hub conforme [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) e confirmar ausência de novos eventos com a mesma `ERRSIG` (24–48h estáveis).
---
## 5. Ligação ao hub (errors.bitreport.pt)
```bash
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRCLUSTER:634c0a250aba"
./scripts/er-cli.sh list-open --project wdmi-store --q "ERRSIG:a26dda2636bd"
./scripts/er-cli.sh list-open --project wdmi-store --q "a26dda2636bd"
./scripts/er-cli.sh list-open --project wdmi-store --q "_visiotech.php"
./scripts/er-cli.sh list-open --project wdmi-store --q "strlen(): Passing null"
```
### 5.1 Caso documentado — `wdmi-store` / Visiotech + `Product` insert (BIT-954)
- **Paperclip:** [BIT-954](/BIT/issues/BIT-954) (recorrências agregadas pelo loop [BIT-309](/BIT/issues/BIT-309))
- **Assinatura:** `ERRSIG:a26dda2636bd`
- **Cluster:** `ERRCLUSTER:634c0a250aba`
- **Mensagem típica:** `strlen(): Passing null to parameter #1 ($string) of type string is deprecated`
- **Origem útil:** `_visiotech.php` (~108); stack com `ErrorMonitoringReporter::handleError`, `Engine\Product->_applyBeforeInsert()`, `Product->save()`, `__maintenance_build.php`
- **Acção no produto:** aplicar §4 no Importer / deploy em `wdmi-store`; usar §2 para confirmar o campo ou ramo que entrega `null`.
---
## Ver também
- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — triagem e fecho no hub.
- [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — outro padrão de erros no Importer `wdmi-store`.
- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — cenários CLI.
+7 -7
View File
@@ -1,10 +1,10 @@
# Runbook — errors.bitreport.pt: Triagem, Correção, Deploy e Fecho
**Audiência:** Operação, agentes Paperclip, on-call.
**Última revisão:** 2026-06-08
**Última revisão:** 2026-04-05
**Requisitos:** `curl`, `jq`, acesso à variável `ERROR_RESOLVE_API_KEY`, acesso SSH ao LXC host (se deploy necessário).
**Documentação relacionada:** [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) (contratos + curl), [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) (5 cenários CLI), [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) (ingest 401/429/fingerprint), [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) (cURL 35 / 6 — TLS e DNS / Google OAuth no **reporter** PHP), runbooks CRM em [docs/runbooks/README.md](runbooks/README.md), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). Projetos WDMI foram retirados do hub em [BIT-24704](/BIT/issues/BIT-24704).
**Documentação relacionada:** [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) (contratos + curl), [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) (5 cenários CLI), [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) (ingest 401/429/fingerprint), [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md) (cURL 35 / 6 — TLS e DNS / Google OAuth no **reporter** PHP; HTTP 503/500 Sheets `backendError` — §5.7–§5.9, p.ex. [BIT-909](/BIT/issues/BIT-909) / [BIT-938](/BIT/issues/BIT-938) (503), [BIT-912](/BIT/issues/BIT-912) / [BIT-916](/BIT/issues/BIT-916) (500); DNS `oauth2` + `import_margin` em `wdmi-store` — §5.11 / [BIT-921](/BIT/issues/BIT-921); CRM `import_margin` cURL 35 em `sheets.googleapis.com` — §5.12 / [BIT-947](/BIT/issues/BIT-947); DNS `sheets.googleapis.com` (folha **Portes**, supplier fees) no **CRM** — §5.6 / [BIT-995](/BIT/issues/BIT-995)), [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) (`simplexml_load_file` / Flexit Importer no **reporter** PHP; p.ex. [BIT-903](/BIT/issues/BIT-903) — `ERRCLUSTER:e83a5ee5e95d` / §5.2; [BIT-943](/BIT/issues/BIT-943) — `ERRCLUSTER:eb0dad83413f` / §5.9 *error parsing attribute name*), [RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md](RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md) (`SimpleXLS` / `_auferma.php` / `Uninitialized string offset` no **reporter** `wdmi-store` ou **`wdmi-ubuntu`**; p.ex. [BIT-869](/BIT/issues/BIT-869) — `ERRCLUSTER:0a642d62d724` / §5.1; [BIT-1055](/BIT/issues/BIT-1055) — `ERRCLUSTER:640553efed73` / §5.3), [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) (upload de feed / `upload_feed_tier` / `clients.wdmi.pt` no **reporter** PHP; confusão *host ingestão* vs URL de upload — ver §1.1 desse runbook), [RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) (`mkdir(): File exists` / cache Importer — `Cache.class.php` em WDMI_UBUNTU; stack pode citar `CacheFilesystem` legado — ver runbook; [BIT-924](/BIT/issues/BIT-924) / [BIT-985](/BIT/issues/BIT-985)), [RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md](RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md) (Importer `_visiotech.php` / `strlen(null)` deprecation PHP 8.1+ no **reporter** `wdmi-store`), [RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md](RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md) (CRM `View.php` / `@errormonitoring/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md](RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md) (CRM `View.php` / `@processmanager/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md](RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md) (CRM `Logger.php` / `mkdir(): Permission denied` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_USERPROFILE_SANITIZE.md](RUNBOOK_REPORTER_CRM_USERPROFILE_SANITIZE.md) (CRM `UserController` / `array_map('Sanitize::…')` vs classe global — perfil & skills no **reporter** PHP; [BIT-881](/BIT/issues/BIT-881)), [RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md](RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md) (CRM `layouts/auth.php` / password reset basic / `Closure` com layout aninhado no **reporter** PHP; [BIT-935](/BIT/issues/BIT-935)), [RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md](RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md) (CRM `Validate::email` / argumento `string` vs `null` no POST de login — `AuthController::handleLogin`; [BIT-941](/BIT/issues/BIT-941)), [RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md](RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md) (CRM `vendor.*.js` / `classList` em nó nulo no **reporter** front-end; [BIT-936](/BIT/issues/BIT-936)), [RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md](RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md) (CRM `crm_tasks.due_time` / string vazia vs `NULL` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) (CRM SQL 1064 próximo a `'10'` / `LIMIT`–`OFFSET` quotados ou binds incorrectos no **reporter** PHP; [BIT-937](/BIT/issues/BIT-937) / [BIT-952](/BIT/issues/BIT-952)), [RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md](RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md) (CRM `DatabaseManager.php` / esgotamento de `memory_limit` no **reporter** PHP), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md).
---
@@ -29,7 +29,7 @@ Filtros opcionais:
```bash
./scripts/er-cli.sh list-open --project crm --severity critical
./scripts/er-cli.sh list-open --project ott --limit 50
./scripts/er-cli.sh list-open --project wdmi --limit 50
./scripts/er-cli.sh list-open --q "Connection refused"
```
@@ -65,8 +65,8 @@ curl -sf "${ER_API_BASE}/api/error-monitoring/recent-errors?api_key=${ERROR_RESO
### 1.5 Paperclip — loop [BIT-309](/BIT/issues/BIT-309) e reaberturas
- Comentários **“Recorrência após fecho”** (ou equivalente no loop) reabrem a **mesma** issue Paperclip para `todo` para evitar duplicados — não implica por si um bug novo no repositório **errors.bitreport.pt**.
- **Sweeps / fecho administrativo:** antes de marcar uma issue do **error loop** como concluída só com base no último comentário de agente («Done» / «Fecho» com documentação no hub) ou num sweep operacional, confirmar no **hub** que não há incidentes abertos para a mesma assinatura ou cluster (`./scripts/er-cli.sh list-open --project <slug> --q "ERRSIG:…"` ou texto do título). Se o **reporter** ainda ingressa o erro, o loop volta a comentar **«Recorrência após fecho»**; a causa continua no guest (runbook do serviço de origem — ex. CRM SQL [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1 / [BIT-937](/BIT/issues/BIT-937)).
- Enquanto o **reporter** continuar a emitir o mesmo erro em produção, o hub e o Paperclip reflectem-no; a causa raiz segue os runbooks do **sistema de origem** (ex.: Google TLS no CRM — [RUNBOOK_REPORTER_GOOGLE_TLS.md](RUNBOOK_REPORTER_GOOGLE_TLS.md)).
- **Sweeps / fecho administrativo:** antes de marcar uma issue do **error loop** como concluída só com base no último comentário de agente («Done» / «Fecho» com documentação no hub) ou num sweep operacional, confirmar no **hub** que não há incidentes abertos para a mesma assinatura ou cluster (`./scripts/er-cli.sh list-open --project <slug> --q "ERRSIG:…"` ou texto do título). Se o **reporter** ainda ingressa o erro, o loop volta a comentar **«Recorrência após fecho»**; a causa continua no guest (runbook do serviço de origem — ex. Flexit [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) §5.8 / [BIT-946](/BIT/issues/BIT-946), §5.9 / [BIT-943](/BIT/issues/BIT-943) *parser error : error parsing attribute name* em `FlexIT.XML`).
- Enquanto o **reporter** continuar a emitir o mesmo erro em produção, o hub e o Paperclip reflectem-no; a causa raiz segue os runbooks do **sistema de origem** (ex.: upload de feed — [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) §5.28 / [BIT-925](/BIT/issues/BIT-925)).
- **Agentes:** só é necessário novo commit no hub se a documentação ou o contrato mudarem; caso o runbook já cubra a assinatura, actualizar a thread Paperclip com ponteiro para a secção e fechar conforme governança após verificação (ou deixar explícito o que falta em ops no reporter).
---
@@ -214,9 +214,9 @@ echo "Backup: ${BACKUP_FILE} ($(wc -l < "${BACKUP_FILE}") linhas)"
### 6.1 Issues Paperclip (Error Loop / BIT-309) com causa no **reporter**
Muitos tickets descrevem erros **ingeridos** pelo hub cuja **causa raiz** está no código ou na infra do projecto reporter (`crm`, `ott`, etc.), não no serviço `errors.bitreport.pt`.
Muitos tickets descrevem erros **ingeridos** pelo hub cuja **causa raiz** está no código ou na infra do projecto reporter (`wdmi-store`, `crm`, etc.), não no serviço `errors.bitreport.pt`.
- Trabalho **só no repositório do hub** (runbooks, contratos HTTP) **não elimina** novas occurrences no produto reporter; o loop **BIT-309** pode **reabrir** o mesmo issue Paperclip enquanto os eventos continuarem a chegar (ex.: [BIT-937](/BIT/issues/BIT-937) / `ERRCLUSTER:5291566782c4` no **CRM** com SQL `LIMIT` quotado — [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1).
- Trabalho **só no repositório do hub** (runbooks, contratos HTTP) **não elimina** novas occurrences no produto reporter; o loop **BIT-309** pode **reabrir** o mesmo issue Paperclip enquanto os eventos continuarem a chegar (ex.: [BIT-904](/BIT/issues/BIT-904) após fecho com documentação de upload tier `ref_1`, [BIT-910](/BIT/issues/BIT-910) com o mesmo padrão para tier `ref_2` / `ERRCLUSTER:026e79c87500`, [BIT-905](/BIT/issues/BIT-905) com `upload_feed_base` / `feed_ref` / `ref` — ver [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) §5.20 (BIT-904), §5.24 (BIT-910) e §5.21 (BIT-905), ou [BIT-937](/BIT/issues/BIT-937) / `ERRCLUSTER:5291566782c4` no **CRM** com SQL `LIMIT` quotado — [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) §5.1).
- **Consolidação CTO (`cancelled` / duplicado):** vários sintomas de upload podem fundir-se num ticket canónico (ex.: [BIT-905](/BIT/issues/BIT-905) ou [BIT-906](/BIT/issues/BIT-906) → [BIT-1020](/BIT/issues/BIT-1020)). O plano de correcção e o estado Paperclip seguem o **issue canónico**; o runbook (§5.21 [BIT-905](/BIT/issues/BIT-905), §5.22 [BIT-906](/BIT/issues/BIT-906)) mantém `ERRSIG` / `er-cli` para diagnóstico.
- Marcar o issue Paperclip como **`done`** só após **verificação em produção** (repro desapareceu, `curl` de upload OK, deploy aplicado) **ou** acordo explícito de que o âmbito era **apenas documentação** e que recorrências são esperadas até alguém tratar o reporter.
- Não adicionar regras de ruído no ingest do hub para **esconder** estes erros até a causa no destino estar tratada; alinhar com [operations/ingest-hardening-runbook.md](operations/ingest-hardening-runbook.md).
@@ -9,20 +9,10 @@ Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API, **3040** → admin UI. Ajustáveis em `.env` (`ER_PUBLISH_*`).
## Preservação de `.env` em runtime (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
- **Nunca** executar `cp .env.example .env` sobre um `.env` **já existente** em produção ou staging.
- O `cp` abaixo aplica-se **apenas** à configuração inicial num servidor novo onde não existe ainda `.env`.
- Em redeploys: `git pull` apenas; o `.env` existente **não é tocado**.
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
## Arranque reproduzível (qualquer ambiente)
```bash
cd /path/to/errors.bitreport.pt # raiz do clone (ver inventário em docs/ENVIRONMENTS.md)
# APENAS para configuração inicial — NÃO executar se já existir .env em produção (BIT-25005)
cp .env.example .env
# Editar .env: definir palavras-passe fortes antes de produção
docker compose up --build -d
@@ -2,15 +2,6 @@
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **MariaDB 10.11+** (ou MySQL 8+), **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
## Preservação de `.env` em runtime (BIT-25005)
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
- **Nunca** sobrescrever `/etc/error-reporting/env` (ou `.env` no clone) com conteúdo de exemplo num servidor de produção já configurado.
- Ficheiro de env em `/etc/error-reporting/env` é **fora do Git** — nunca incluir no repositório.
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
- Credenciais de placeholder (`CHANGE_ME_STRONG`, `changeme`) são proibidas em produção.
Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml).
## Redis
+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` |
+9 -4
View File
@@ -17,6 +17,14 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
- [`RUNBOOK_INGEST_DEBUG.md`](../RUNBOOK_INGEST_DEBUG.md) — debug ingest API behaviour and payloads.
- [`operations/ingest-hardening-runbook.md`](../operations/ingest-hardening-runbook.md) — post-deploy validation after ingest hardening / rate-limit changes (BIT-735).
## Reporter (PHP) — WDMI / Importer
- [`RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md`](../RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md) — feed upload API with no response (`wdmi-store` / `clients.wdmi.pt`).
- [`RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md`](../RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) — `simplexml_load_file` in Flexit Importer (`wdmi-store`).
- [`RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md`](../RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md) — `SimpleXLS` / `_auferma.php` uninitialized string offset.
- [`RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md`](../RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) — `mkdir(): File exists` on Importer cache disk.
- [`RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md`](../RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md) — Visiotech / `strlen()` with `null` (PHP 8.1+).
## Reporter (PHP) — CRM
- [`RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md`](../RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md) — `Validate::email()` with `null` at login.
@@ -41,6 +49,7 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
## Operations & observability
- [`RUNBOOK_OPERATIONS.md`](../RUNBOOK_OPERATIONS.md) — five common operational scenarios on the hub.
- [`RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md`](../RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md) — SSH from Paperclip host to WDMI Importer (BIT-1044).
- [`OBSERVABILITY_PROMETHEUS.md`](../OBSERVABILITY_PROMETHEUS.md) — Prometheus & Grafana for this stack.
## Deployment
@@ -53,7 +62,3 @@ Index of **hub-local** operational docs in this repository (pointers only). Gove
- [`HTTP_CONTRACTS.md`](../HTTP_CONTRACTS.md) — HTTP API contracts for this hub.
- [`ADMIN_STATS_API.md`](../ADMIN_STATS_API.md) — `/v1/stats/*` operational statistics.
- [`permission-matrix.md`](../permission-matrix.md) — admin RBAC permission matrix.
## Retired clients
WDMI-family projects were removed from this hub in [BIT-24704](/BIT/issues/BIT-24704). Ingest rejects retired slugs; use `scripts/offboard-project.sh` for future client removals.
+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;
});
});
@@ -265,7 +265,7 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
schema_version: 1,
occurred_at: "2026-04-05T10:00:00.000Z",
level: "error",
message: "Error: BIT-SMOKE-CRM-DIRECT-INGEST",
message: "Error: BIT-SMOKE-WDMI-DIRECT-INGEST",
},
],
},
+2 -2
View File
@@ -34,8 +34,8 @@ describe("extractLocationFromContext", () => {
describe("extractProjectStableKey", () => {
it("prefers project_slug", () => {
expect(extractProjectStableKey({ project_slug: "crm", project_name: "X" })).toBe(
"crm",
expect(extractProjectStableKey({ project_slug: "wdmi-store", project_name: "X" })).toBe(
"wdmi-store",
);
});
});
+1 -1
View File
@@ -21,7 +21,7 @@ function _asTrimmedString(value: unknown): string {
}
/**
* Pull file + line from ingest `context` (CRM ErrorCollector shapes).
* Pull file + line from ingest `context` (CRM / WDMI ErrorCollector shapes).
*/
export function extractLocationFromContext(
context: Record<string, unknown> | null | undefined,
+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"));
});
});
+6 -6
View File
@@ -57,7 +57,7 @@ describe("evaluateNoise", () => {
level: "error",
message:
"Uncaught TypeError: Cannot read properties of undefined (reading '_x_refreshXForScope')",
filePathHint: "/data/wwwroot/crm/app/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php",
filePathHint: "/data/wwwroot/crm-wdmi/app/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php",
});
expect(_r).toEqual({
matched: true,
@@ -76,11 +76,11 @@ describe("evaluateNoise", () => {
expect(_r).toEqual({ matched: false });
});
it("matches reserved BIT-SMOKE- probe messages (direct ingest smoke)", () => {
it("matches reserved BIT-SMOKE- probe messages (wdmi direct ingest smoke)", () => {
const _r = evaluateNoise({
level: "error",
message: "Error: BIT-SMOKE-CRM-DIRECT-INGEST",
filePathHint: "/smoke/crm-main.php",
message: "Error: BIT-SMOKE-WDMI-DIRECT-INGEST",
filePathHint: "/smoke/wdmi.js",
});
expect(_r).toEqual({
matched: true,
@@ -92,7 +92,7 @@ describe("evaluateNoise", () => {
it("suppresses BIT-SMOKE- even at critical ingest level", () => {
const _r = evaluateNoise({
level: "critical",
message: "BIT-SMOKE-CRM-DIRECT-INGEST",
message: "BIT-SMOKE-WDMI-DIRECT-INGEST",
filePathHint: "",
});
expect(_r).toEqual({
@@ -143,7 +143,7 @@ describe("evaluateNoise", () => {
});
});
it("matches CRM deploy ingest live-check failure ribbon (BIT-931 family)", () => {
it("matches wdmi-store / CRM deploy ingest live-check failure ribbon (BIT-931 family)", () => {
const _r = evaluateNoise({
level: "critical",
message: "BIT-SMOKE error hub ingest live check",
+10 -4
View File
@@ -4,7 +4,7 @@ import { normalizeLevelToSeverity } from "./normalize.js";
* Versioned ruleset id (document in release notes when rules change).
* Rule inventory and validation steps: `docs/operations/ingest-hardening-runbook.md`.
*/
export const NOISE_RULESET_VERSION = "1.0.6";
export const NOISE_RULESET_VERSION = "1.0.5";
export type NoiseEvaluation =
| { matched: false }
@@ -90,6 +90,12 @@ const _RULES: NoiseRule[] = [
match: (i) =>
i.message.includes("ResizeObserver loop completed with undelivered notifications"),
},
{
id: "wdmi_media_bitreport_load",
reason: "filtered_media_404_noise",
match: (i) =>
i.message.startsWith("Resource failed to load: https://wdmi-media.bitreport.pt/media/"),
},
{
id: "transient_offset_null",
reason: "filtered_transient_frontend_noise",
@@ -121,7 +127,7 @@ const _RULES: NoiseRule[] = [
reason: "filtered_transient_frontend_noise",
match: (i) => i.message.includes("Unhandled Promise Rejection: Error: parser Error"),
},
/** Alpine.js v3 internal during teardown / navigation when scope is already gone. */
/** Alpine.js v3 internal during teardown / navigation when scope is already gone (crm-wdmi / wdmi-store). */
{
id: "alpine_refresh_x_for_scope_teardown",
reason: "filtered_transient_frontend_noise",
@@ -133,8 +139,8 @@ const _RULES: NoiseRule[] = [
/**
* Conservative: never classify fatal/critical ingest levels as noise (avoid hiding real outages).
* Exception: reserved `BIT-SMOKE-` markers are intentional end-to-end probes (e.g. CRM
* `/smoke/crm-main.php`) and are filtered at every ingest level so they do
* Exception: reserved `BIT-SMOKE-` markers are intentional end-to-end probes (e.g. wdmi-store
* `/smoke/wdmi.js`, CRM `/smoke/crm-main.php`) and are filtered at every ingest level so they do
* not open incidents. Some PHP reporters put the marker only in `stack_trace`, not in `message`.
*
* Deploy probes also emit a fixed failure ribbon `BIT-SMOKE error hub ingest live check` (space, not
@@ -1,23 +0,0 @@
import { describe, expect, it } from "vitest";
import { isRetiredProjectSlug } from "./retiredProjects.js";
describe("isRetiredProjectSlug", () => {
it("matches known WDMI hub slugs", () => {
expect(isRetiredProjectSlug("wdmi")).toBe(true);
expect(isRetiredProjectSlug("wdmi-store")).toBe(true);
expect(isRetiredProjectSlug("crm-wdmi")).toBe(true);
expect(isRetiredProjectSlug("wdmi-ubuntu")).toBe(true);
});
it("matches WDMI slug families", () => {
expect(isRetiredProjectSlug("wdmi-legacy")).toBe(true);
expect(isRetiredProjectSlug("store-wdmi")).toBe(true);
expect(isRetiredProjectSlug("crm-wdmi-staging")).toBe(true);
});
it("does not match unrelated projects", () => {
expect(isRetiredProjectSlug("crm")).toBe(false);
expect(isRetiredProjectSlug("pa")).toBe(false);
expect(isRetiredProjectSlug("ott")).toBe(false);
});
});
-27
View File
@@ -1,27 +0,0 @@
/**
* Projects removed from the error reporting hub (BIT-24704).
* Ingest must reject these slugs even if a project row or key is recreated by mistake.
*/
export const RETIRED_PROJECT_SLUGS = new Set([
"wdmi",
"wdmi-store",
"crm-wdmi",
"wdmi-ubuntu",
]);
export function isRetiredProjectSlug(slug: string): boolean {
const _normalized = slug.trim().toLowerCase();
if (_normalized === "") {
return false;
}
if (RETIRED_PROJECT_SLUGS.has(_normalized)) {
return true;
}
if (_normalized.startsWith("wdmi-") || _normalized.endsWith("-wdmi")) {
return true;
}
if (_normalized.startsWith("crm-wdmi")) {
return true;
}
return false;
}
+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');
});
});
+1 -11
View File
@@ -2,7 +2,6 @@ import type { Pool } from "mysql2/promise";
import type { RowDataPacket } from "mysql2";
import type { FastifyReply, FastifyRequest } from "fastify";
import { sha256Hex } from "../lib/hash.js";
import { isRetiredProjectSlug } from "../lib/retiredProjects.js";
export type IngestAuthContext = {
keyId: string;
@@ -52,7 +51,6 @@ export async function attachIngestAuth(
WHERE k.token_hash = ?
AND k.status = 'active'
AND k.revoked_at IS NULL
AND p.is_active = TRUE
AND (k.expires_at IS NULL OR k.expires_at > NOW(6))`,
[_hash],
);
@@ -77,20 +75,12 @@ export async function attachIngestAuth(
});
return;
}
const _projectSlug = String(_row.project_slug ?? "").trim().toLowerCase();
if (isRetiredProjectSlug(_projectSlug)) {
await reply.status(403).send({
error: "project_retired",
message: "This project is no longer accepted by the error reporting hub.",
});
return;
}
const _rlMaxNum = _row.rate_limit_max != null ? Number(_row.rate_limit_max) : NaN;
const _rlWinNum = _row.rate_limit_window_ms != null ? Number(_row.rate_limit_window_ms) : NaN;
request.ingestAuth = {
keyId: _row.id,
projectId: _row.project_id,
projectSlug: _projectSlug,
projectSlug: String(_row.project_slug ?? "").trim().toLowerCase(),
rateLimitMax: Number.isFinite(_rlMaxNum) && _rlMaxNum > 0 ? _rlMaxNum : null,
rateLimitWindowMs: Number.isFinite(_rlWinNum) && _rlWinNum > 0 ? _rlWinNum : null,
};
@@ -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"],
},
},
});
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Acceptance check for BIT-1044: BatchMode SSH from this host to WDMI Importer (LAN).
# See docs/RUNBOOK_DEVOPS_IMPORTER_SSH_BIT1044.md
#
# Usage:
# ./scripts/devops/verify_importer_ssh_bit1044.sh
# IMPORTER_HOST=192.168.1.123 SSH_USER=root ./scripts/devops/verify_importer_ssh_bit1044.sh
# ./scripts/devops/verify_importer_ssh_bit1044.sh --diagnose # print route/neigh/ping, then SSH; exit code from SSH only
set -euo pipefail
readonly IMPORTER_HOST="${IMPORTER_HOST:-192.168.1.123}"
readonly SSH_USER="${SSH_USER:-root}"
readonly CONNECT_TIMEOUT="${SSH_CONNECT_TIMEOUT:-10}"
_diagnose=0
if [[ "${1:-}" == "--diagnose" ]]; then
_diagnose=1
fi
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
sed -n '1,20p' "$0"
exit 0
fi
if [[ -n "${1:-}" && "${1}" != "--diagnose" ]]; then
echo "unknown argument: $1 (use --diagnose or no args)" >&2
exit 2
fi
if ((_diagnose)); then
echo "verify_importer_ssh_bit1044: route to ${IMPORTER_HOST}"
ip route get "${IMPORTER_HOST}" 2>/dev/null || true
echo "verify_importer_ssh_bit1044: neighbour ${IMPORTER_HOST}"
ip neigh show "${IMPORTER_HOST}" 2>/dev/null || true
echo "verify_importer_ssh_bit1044: ping (2 probes, 2s max wait)"
ping -c 2 -W 2 "${IMPORTER_HOST}" 2>&1 || true
fi
echo "verify_importer_ssh_bit1044: ssh BatchMode ${SSH_USER}@${IMPORTER_HOST} echo ok"
if ssh -o BatchMode=yes -o ConnectTimeout="${CONNECT_TIMEOUT}" -o StrictHostKeyChecking=accept-new \
"${SSH_USER}@${IMPORTER_HOST}" echo ok; then
exit 0
fi
echo "verify_importer_ssh_bit1044: SSH failed; neighbour ${IMPORTER_HOST}:" >&2
ip neigh show "${IMPORTER_HOST}" 2>/dev/null || true
echo "verify_importer_ssh_bit1044: hint: run with --diagnose for route + ping" >&2
exit 1
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env bash
# offboard-project.sh — revoke keys, disable collectors, and delete a project from error_reporting.
#
# Usage:
# offboard-project.sh <slug>
#
# Example:
# ./scripts/offboard-project.sh wdmi-store
#
# Environment:
# DATABASE_URL If set and mysql client available, applies SQL directly.
# Otherwise prints SQL to stdout.
set -euo pipefail
_die() { echo "error: $*" >&2; exit 1; }
[[ $# -eq 1 ]] || _die "Usage: offboard-project.sh <slug>"
SLUG="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
[[ "${SLUG}" =~ ^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$ ]] \
|| _die "slug must be 2-64 lowercase alphanumeric/hyphens: ${SLUG}"
SQL="$(cat <<EOSQL
-- Offboard project: ${SLUG}
BEGIN;
UPDATE er_ingest_keys k
INNER JOIN er_projects p ON p.id = k.project_id
SET k.status = 'revoked',
k.revoked_at = NOW(6)
WHERE LOWER(p.slug) = '${SLUG}';
UPDATE er_collector_sources cs
INNER JOIN er_projects p ON p.id = cs.project_id
SET cs.is_active = FALSE
WHERE LOWER(p.slug) = '${SLUG}';
DELETE FROM er_projects WHERE LOWER(slug) = '${SLUG}';
COMMIT;
EOSQL
)"
echo "================================================================"
echo " Offboard project slug: ${SLUG}"
echo "================================================================"
echo ""
echo "--- SQL (apply to error_reporting database) ---"
echo "${SQL}"
echo ""
if [[ -n "${DATABASE_URL:-}" ]] && command -v mysql >/dev/null 2>&1; then
echo "DATABASE_URL is set. Applying SQL..."
DB_URL="${DATABASE_URL#mysql://}"
DB_USER="${DB_URL%%:*}"
DB_REST="${DB_URL#*:}"
DB_PASS="${DB_REST%%@*}"
DB_REST="${DB_REST#*@}"
DB_HOST="${DB_REST%%:*}"
DB_REST="${DB_REST#*:}"
DB_PORT="${DB_REST%%/*}"
DB_NAME="${DB_REST#*/}"
echo "${SQL}" | mysql -h"${DB_HOST}" -P"${DB_PORT}" -u"${DB_USER}" -p"${DB_PASS}" "${DB_NAME}"
echo "Applied successfully."
fi
+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"
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more