diff --git a/api/docs/ERROR_MONITORING_PUBLIC_API.md b/api/docs/ERROR_MONITORING_PUBLIC_API.md index f1d10aa..3d99337 100644 --- a/api/docs/ERROR_MONITORING_PUBLIC_API.md +++ b/api/docs/ERROR_MONITORING_PUBLIC_API.md @@ -2,9 +2,12 @@ CRM-shaped JSON endpoints served by the Fastify API (`@errors-bitreport/api`). Same paths as the CRM `ErrorMonitoring` module where noted. +**Canonical HTTP shapes + curl cookbook:** [`docs/HTTP_CONTRACTS.md`](../../docs/HTTP_CONTRACTS.md) (repo root). +**Operator runbooks:** [`docs/RUNBOOK_OPERATIONS.md`](../../docs/RUNBOOK_OPERATIONS.md), [`docs/RUNBOOK_INGEST_DEBUG.md`](../../docs/RUNBOOK_INGEST_DEBUG.md). + ## Authentication -### Read (`GET …/recent-errors`) +### Read (`GET …/recent-errors`, `GET …/stats`) - Query: `api_key` must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY`, **or** - Query: `view_errors` must match `DEBUG_VIEW_ERRORS_KEY`. @@ -18,6 +21,18 @@ CRM-shaped JSON endpoints served by the Fastify API (`@errors-bitreport/api`). S - `errors:delete` for purge-resolved - If no resolve key is configured → only session auth is accepted (token-only automation is disabled). +## `GET /api/error-monitoring/stats` + +Hub operational summary (24h ingestion, severity/state counts, per-project rollups). **Also** refreshes Prometheus gauges on the API process (best-effort). + +**Auth:** Same query keys as `recent-errors` (`api_key` or `view_errors`). + +**Example** + +```bash +curl -sS -G "${ER_API_BASE}/api/error-monitoring/stats" --data-urlencode "api_key=${ERROR_RESOLVE_API_KEY}" +``` + ## `GET /api/error-monitoring/recent-errors` Alias: `GET /v1/paperclip/recent-errors` @@ -36,6 +51,16 @@ Alias: `GET /v1/paperclip/recent-errors` Each row includes CRM-compatible fields. For non-resolved incidents, `status` is always `"open"` (including `investigating`) so Paperclip `error_loop` continues to treat rows as open. +**Example** + +```bash +curl -sS -G "${ER_API_BASE}/api/error-monitoring/recent-errors" \ + --data-urlencode "api_key=${ERROR_RESOLVE_API_KEY}" \ + --data-urlencode "status=open,investigating" \ + --data-urlencode "project_slug=crm" \ + --data-urlencode "limit=50" +``` + ## `POST /api/error-monitoring/resolve` **Body (JSON):** @@ -49,6 +74,15 @@ Each row includes CRM-compatible fields. For non-resolved incidents, `status` is **Responses:** **200** success envelope; **400** missing id; **401** auth; **404** not found or not resolvable; **503** if read keys not applicable (mutations use resolve key / session only). +**Example** + +```bash +curl -sS -X POST "${ER_API_BASE}/api/error-monitoring/resolve" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${ERROR_RESOLVE_API_KEY}" \ + -d '{"unique_id":"12345","resolution_notes":"verified in prod"}' +``` + ## `POST /api/error-monitoring/bulk-resolve` **Body (JSON):** @@ -63,6 +97,15 @@ Each row includes CRM-compatible fields. For non-resolved incidents, `status` is If both `unique_ids` and `message_pattern` are sent, **`unique_ids` wins** (CRM behaviour). +**Example (pattern)** + +```bash +curl -sS -X POST "${ER_API_BASE}/api/error-monitoring/bulk-resolve" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${ERROR_RESOLVE_API_KEY}" \ + -d '{"message_pattern":"Connection refused","resolution_notes":"dependency restored"}' +``` + ## `POST /api/error-monitoring/resolve-by-pattern` Bulk resolve incidents matching one or more advanced filters. At least one filter is required. @@ -95,7 +138,16 @@ Bulk resolve incidents matching one or more advanced filters. At least one filte | `older_than_days` | Non-negative integer; only purge resolved incidents with `last_seen_at` older than this many days. If omitted, purges all resolved. | | `api_key` | Optional resolve key | -**Effect:** `DELETE` from `er_incidents` where `current_state = 'resolved'` (cascades occurrences and related rows per schema). +**Effect:** `DELETE` from `er_incidents` where `current_state = 'resolved'` (cascades occurrences and related rows per schema). **All** resolved incidents are removed when `dry_run` is false — there is no age filter in the current handler. + +**Example** + +```bash +curl -sS -X POST "${ER_API_BASE}/api/error-monitoring/purge-resolved" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${ERROR_RESOLVE_API_KEY}" \ + -d '{"dry_run":true}' +``` ## Admin UI proxy diff --git a/docs/ADMIN_STATS_API.md b/docs/ADMIN_STATS_API.md index 2d9f17f..fbe305f 100644 --- a/docs/ADMIN_STATS_API.md +++ b/docs/ADMIN_STATS_API.md @@ -68,4 +68,5 @@ Heavy queries use: ## Related +- Curl examples (cookie login + `/v1/stats/*`): [`docs/HTTP_CONTRACTS.md`](HTTP_CONTRACTS.md). - Public ingest / `recent-errors`: `docs/` in this repo and Paperclip `ERROR_REPORTING_HUB_CONTRACT.md`. diff --git a/docs/HTTP_CONTRACTS.md b/docs/HTTP_CONTRACTS.md new file mode 100644 index 0000000..542d9d7 --- /dev/null +++ b/docs/HTTP_CONTRACTS.md @@ -0,0 +1,435 @@ +# HTTP contracts — errors.bitreport.pt + +**Audience:** Operators, automation, integrators. +**Scope:** Fastify **hub API** (`api/`, default port `3200`) and **ingest API** (`ingest-api/`). +**Companion:** Curl examples below mirror production paths; substitute `ER_API_BASE`, `INGEST_API_BASE`, and secrets from your vault. + +--- + +## Conventions + +- **JSON** bodies use `Content-Type: application/json` unless noted. +- **Hub public read** endpoints require `api_key` or `view_errors` query params when server secrets are configured (see [ERROR_MONITORING_PUBLIC_API.md](../api/docs/ERROR_MONITORING_PUBLIC_API.md)). +- **Hub mutations** accept `X-Error-Resolve-Key` or body field `api_key` matching `ERROR_RESOLVE_API_KEY` / `ERROR_REPORTING_API_KEY`, or an admin session cookie with RBAC. +- **Admin JSON** routes expect JWT in HTTP-only cookie `__Host-access` after `POST /admin/auth/login` (use a cookie jar with `curl`). + +--- + +## Hub API — health & metrics + +### `GET /health` + +**Response 200** + +```json +{ "ok": true, "ts": "2026-04-02T19:00:00.000Z" } +``` + +```bash +curl -sS "${ER_API_BASE:-http://127.0.0.1:3200}/health" +``` + +### `GET /metrics` + +Prometheus exposition format (`text/plain`). See [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). + +```bash +curl -sS "${ER_API_BASE:-http://127.0.0.1:3200}/metrics" | head +``` + +--- + +## Hub API — public error monitoring (token or view key) + +### `GET /api/error-monitoring/recent-errors` + +Alias: `GET /v1/paperclip/recent-errors` (same handler). + +**Query:** `api_key` *or* `view_errors`, plus optional `limit`, `offset`, `status`, `severity`, `project_slug`, `q`, `order`. + +**Response 200** + +```json +{ + "success": true, + "message": "ok", + "data": [ + { + "status": "open", + "message": "Exception: …", + "error_message": "Exception: …", + "stack_trace": "", + "file_path": "/app/src/foo.ts", + "line_number": "42", + "severity": "high", + "unique_id": "12345", + "project_slug": "crm", + "environment": "production" + } + ] +} +``` + +```bash +API_KEY="$ERROR_RESOLVE_API_KEY" +BASE="${ER_API_BASE:-http://127.0.0.1:3200}" +curl -sS -G "${BASE}/api/error-monitoring/recent-errors" \ + --data-urlencode "api_key=${API_KEY}" \ + --data-urlencode "status=open,investigating" \ + --data-urlencode "project_slug=crm" \ + --data-urlencode "limit=50" +``` + +### `GET /api/error-monitoring/stats` + +**Query:** `api_key` *or* `view_errors` only (no extra filters). + +**Response 200** (shape) + +```json +{ + "ingestion": { + "last24h": 0, + "resolvedLast24h": 0, + "hourlyTrend": [ + { + "hour": "2026-04-01 12:00:00", + "critical": 0, + "high": 0, + "medium": 0, + "low": 0, + "info": 0 + } + ] + }, + "bySeverity": { + "critical": 0, + "high": 0, + "medium": 0, + "low": 0, + "info": 0 + }, + "byState": { "open": 0 }, + "projects": [ + { + "slug": "crm", + "total": 0, + "open": 0, + "investigating": 0, + "resolved": 0, + "ignored": 0, + "critical": 0, + "resolutionRate": 0 + } + ] +} +``` + +Calling this endpoint also refreshes Prometheus gauges on the hub (best-effort, non-blocking). + +```bash +curl -sS -G "${BASE}/api/error-monitoring/stats" --data-urlencode "api_key=${API_KEY}" | jq . +``` + +### `POST /api/error-monitoring/resolve` + +**Auth:** resolve key or session with `errors:triage`. + +**Body** + +| Field | Type | Required | +|--------|------|----------| +| `unique_id` | string (digits) | yes | +| `resolution_notes` | string | no | +| `assigned_to` | string | no | +| `api_key` | string | no (if header used) | + +**Response 200** + +```json +{ + "success": true, + "message": "Erro marcado como resolvido", + "data": { "unique_id": "12345", "resolution_notes": "Marked as resolved via API" } +} +``` + +```bash +curl -sS -X POST "${BASE}/api/error-monitoring/resolve" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${API_KEY}" \ + -d '{"unique_id":"12345","resolution_notes":"ops: verified fix"}' +``` + +### `POST /api/error-monitoring/bulk-resolve` + +**Auth:** same as resolve. + +Provide **either** `unique_ids` (non-empty array of numeric strings, max 1000) **or** `message_pattern` (string or array, max 20 patterns). If both are sent, **`unique_ids` wins**. + +**Response 200** (by ids) + +```json +{ + "success": true, + "message": "Bulk resolve by unique_ids completed", + "data": { "resolved": 3, "by": "unique_ids" } +} +``` + +**Response 200** (by pattern) + +```json +{ + "success": true, + "message": "Bulk resolve by message pattern completed", + "data": { + "resolved": 2, + "by": "message_pattern", + "patterns": ["%timeout%"] + } +} +``` + +```bash +curl -sS -X POST "${BASE}/api/error-monitoring/bulk-resolve" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${API_KEY}" \ + -d '{"message_pattern":"Connection refused","resolution_notes":"bulk close"}' +``` + +> **Note:** A separate `POST …/resolve-by-pattern` route is **not** implemented on this service; use **`bulk-resolve`** with `message_pattern` (CRM-style bulk behaviour). + +### `POST /api/error-monitoring/purge-resolved` + +**Auth:** resolve key or session with `errors:delete`. + +**Body** + +| Field | Type | Description | +|--------|------|----------------| +| `dry_run` | boolean | If true, returns `would_delete` only | +| `api_key` | string | optional | + +**Effect:** Deletes **all** rows in `er_incidents` with `current_state = 'resolved'` (cascade per schema). There is **no** `older_than_days` filter in the current implementation. + +**Response 200** (dry run) + +```json +{ + "success": true, + "message": "Dry run", + "data": { "dry_run": true, "would_delete": 12 } +} +``` + +**Response 200** (execute) + +```json +{ + "success": true, + "message": "Apagados 12 incidentes resolvidos", + "data": { "deleted": 12 } +} +``` + +```bash +curl -sS -X POST "${BASE}/api/error-monitoring/purge-resolved" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${API_KEY}" \ + -d '{"dry_run":true}' +``` + +--- + +## Hub API — admin authentication + +Base path: `/admin/auth`. Responses use JSON; cookies are `__Host-*` (secure, path `/` in production). + +### `POST /admin/auth/login` + +**Body** + +```json +{ "email": "ops@example.com", "password": "…" } +``` + +**Response 200** — sets `__Host-access` and `__Host-refresh`; body: + +```json +{ "user": { "id": "…", "email": "ops@example.com", "role": "admin" } } +``` + +```bash +COOKIE_JAR="$(mktemp)" +curl -sS -c "$COOKIE_JAR" -X POST "${BASE}/admin/auth/login" \ + -H "Content-Type: application/json" \ + -d '{"email":"ops@example.com","password":"YOUR_PASSWORD"}' +``` + +### `POST /admin/auth/refresh` + +Uses `__Host-refresh` cookie; returns `{ "ok": true }` and rotates cookies. + +```bash +curl -sS -b "$COOKIE_JAR" -c "$COOKIE_JAR" -X POST "${BASE}/admin/auth/refresh" +``` + +### `POST /admin/auth/logout` + +Requires valid access cookie. + +```bash +curl -sS -b "$COOKIE_JAR" -X POST "${BASE}/admin/auth/logout" +``` + +### `GET /admin/auth/me` + +**Response 200** + +```json +{ "user": { "id": "…", "email": "ops@example.com", "role": "admin" } } +``` + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/admin/auth/me" +``` + +--- + +## Hub API — admin statistics (`errors:read`) + +All require `__Host-access` + permission `errors:read`. + +### `GET /v1/stats/summary` + +Optional query: `project=`. + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/summary?project=crm" +``` + +### `GET /v1/stats/trend` + +Query: `granularity=day|hour`, `days`, `hours`, optional `project`. + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/trend?granularity=day&days=14" +``` + +### `GET /v1/stats/recurrence` + +Query: optional `project`, `days` (1–90), `limit` (max 100). + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/v1/stats/recurrence?days=7&limit=20" +``` + +Response includes `windowDays`, `rangeStart`, `rangeEndExclusive`, `top[]` with `fingerprint`, `hitsInWindow`, etc. See [ADMIN_STATS_API.md](ADMIN_STATS_API.md). + +--- + +## Hub API — admin incidents (`errors:read`) + +### `GET /v1/incidents` + +Query: optional `state`, `severity`, `project`, `q` (max 500 rows). + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/v1/incidents?project=crm&state=open" +``` + +**Response 200** + +```json +{ + "incidents": [ + { + "id": "1", + "projectSlug": "crm", + "fingerprint": "abc…", + "title": "…", + "severity": "high", + "currentState": "open", + "firstSeenAt": "2026-04-01T12:00:00.000Z", + "lastSeenAt": "2026-04-02T10:00:00.000Z", + "occurrencesCount": 5 + } + ] +} +``` + +### `GET /v1/incidents/:id` + +**Response 200** — `{ "incident": { …, "occurrences": [ … ] } }` (up to 200 recent occurrences). + +```bash +curl -sS -b "$COOKIE_JAR" "${BASE}/v1/incidents/12345" +``` + +--- + +## Ingest API + +Default prefix: `/v1/ingest`. Authenticate with `Authorization: Bearer ` or `X-Api-Key: ` (project-bound ingest key). + +### `GET /health` + +```json +{ "status": "ok" } +``` + +### `GET /metrics` + +Ingest Prometheus metrics (`er_ingest_*`). See [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). + +### `GET /v1/openapi.json` + +OpenAPI 3.1 document generated from Fastify. + +### `GET /v1/docs/ui` + +Swagger UI (browser). + +### `POST /v1/ingest/events` + +**Body** + +```json +{ + "events": [ + { + "schema_version": 1, + "occurred_at": "2026-04-02T18:00:00.000Z", + "level": "error", + "message": "Something failed", + "fingerprint": "optional-custom-fp", + "stacktrace": "optional", + "context": { "file_path": "app.ts", "line_number": 10 } + } + ] +} +``` + +**Response 200** — includes `fingerprint_policy_version`, `noise_ruleset_version`, `noise_filtered_count`, `results[]` (each item either stored `{ incident_id, occurrence_id, fingerprint }` or skipped noise `{ skipped, rule_id, reason, … }`). + +**Headers:** optional `Idempotency-Key` (max 128 chars). Reuse with same body → cached **200**; reuse with different body → **409** `idempotency_conflict`. + +**Status codes:** **400** (schema / `occurred_at`), **401** (missing/invalid key), **429** (rate limit; `Retry-After`), **409** (idempotency), **500**. + +```bash +INGEST_BASE="${INGEST_API_BASE:-http://127.0.0.1:3210}" +INGEST_TOKEN="" +curl -sS -X POST "${INGEST_BASE}/v1/ingest/events" \ + -H "Authorization: Bearer ${INGEST_TOKEN}" \ + -H "Content-Type: application/json" \ + -d '{"events":[{"schema_version":1,"occurred_at":"2026-04-02T18:00:00.000Z","level":"error","message":"smoke test"}]}' +``` + +--- + +## Related + +- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — five common operational flows. +- [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) — ingestion failures and rate limits. +- [scripts/er-cli.sh](../scripts/er-cli.sh) — bash wrapper over public hub endpoints. diff --git a/docs/OBSERVABILITY_PROMETHEUS.md b/docs/OBSERVABILITY_PROMETHEUS.md new file mode 100644 index 0000000..8172fd7 --- /dev/null +++ b/docs/OBSERVABILITY_PROMETHEUS.md @@ -0,0 +1,104 @@ +# Observability — Prometheus & Grafana (errors.bitreport.pt) + +**Audience:** DevOps, SRE. +**Scope:** Two processes expose **`GET /metrics`** in Prometheus text format: + +| Service | Typical scrape URL | Metric prefix (node defaults) | +|---------|-------------------|-------------------------------| +| Hub API (`api/`) | `http://:3200/metrics` | `er_api_*`, plus domain gauges `er_*` | +| Ingest API (`ingest-api/`) | `http://:/metrics` | `er_ingest_*` | + +Scrape **both** targets in Prometheus; use Grafana for dashboards and alerts. + +--- + +## 1. Scraping configuration (Prometheus) + +Add two `static_configs` jobs (names are examples): + +```yaml +scrape_configs: + - job_name: errors_hub_api + metrics_path: /metrics + static_configs: + - targets: ['10.10.50.x:3200'] + labels: + service: errors_hub + env: production + + - job_name: errors_ingest_api + metrics_path: /metrics + static_configs: + - targets: ['10.10.50.y:3210'] + labels: + service: errors_ingest + env: production +``` + +If TLS or auth is fronted by Nginx, scrape the **internal** listener or enable mTLS/network policy as per your standard. + +--- + +## 2. Hub API — key metrics + +### HTTP traffic + +- **`er_api_http_requests_total`** — labels: `method`, `route`, `status_code`. +- **`er_api_http_request_duration_seconds`** — histogram for latency SLOs. + +### Domain gauges (refreshed when **`GET /api/error-monitoring/stats`** runs) + +Automation or Grafana can **poll** that endpoint on an interval (with read key) to keep gauges warm, **or** you rely on natural admin/UI traffic. + +| Metric | Labels | Meaning | +|--------|--------|---------| +| `er_incidents_total` | `state` | Count by `open`, `investigating`, `resolved`, `ignored` | +| `er_incidents_by_severity` | `severity` | Count by severity | +| `er_occurrences_last_24h` | — | Occurrence rows in last 24h | +| `er_resolved_last_24h` | — | Distinct incidents resolved in last 24h | +| `er_project_incidents_total` | `project`, `state` | Per-project counts | +| `er_project_resolution_rate` | `project` | Resolved ÷ total (0..1) | + +### Node/process defaults + +`collectDefaultMetrics` runs with prefix `er_api_` — includes event loop delay, heap, GC, etc. Use for generic health. + +--- + +## 3. Ingest API — key metrics + +| Metric | Labels | Meaning | +|--------|--------|---------| +| `er_ingest_request_duration_seconds` | `status_code` | End-to-end POST latency (SLO: watch p95/p99) | +| `er_ingest_requests_total` | `status_code` | Request volume by outcome class | +| `er_ingest_events_total` | `outcome` | `stored`, `skipped_noise`, `error` | +| `er_ingest_batch_size` | — | Histogram of events per request | +| `er_ingest_active_connections` | — | In-flight requests (gauge) | + +Plus `er_ingest_*` process defaults from `prom-client`. + +--- + +## 4. Grafana — starter panels + +1. **Ingest availability:** `sum(rate(er_ingest_requests_total[5m])) by (status_code)`. +2. **Ingest latency:** histogram quantiles on `er_ingest_request_duration_seconds` (e.g. `histogram_quantile(0.95, …)`). +3. **Noise vs stored:** `rate(er_ingest_events_total{outcome="stored"}[5m])` vs `skipped_noise`. +4. **Open incidents:** `er_incidents_total` by `state` (after stats refresh). +5. **Hub HTTP errors:** `sum(rate(er_api_http_requests_total{status_code=~"5.."}[5m]))`. + +--- + +## 5. Linking to the observability “stats” stream + +The hub’s **`GET /api/error-monitoring/stats`** JSON payload is the **operational summary** humans use; Prometheus mirrors a subset as **gauges** when that route is called. For Grafana: + +- Prefer **metrics** for trends and alerting. +- Use the **JSON endpoint** (with `api_key`) for ad-hoc checks or scripted reports — see [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md). + +--- + +## Related + +- [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) — curl examples including `/metrics`. +- [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) — 429 / auth aligned with `er_ingest_*`. diff --git a/docs/RUNBOOK_INGEST_DEBUG.md b/docs/RUNBOOK_INGEST_DEBUG.md new file mode 100644 index 0000000..23a0422 --- /dev/null +++ b/docs/RUNBOOK_INGEST_DEBUG.md @@ -0,0 +1,116 @@ +# Runbook — debugging ingest (errors.bitreport.pt) + +**Audience:** DevOps, on-call, integrators shipping events into the **ingest API**. +**Prerequisites:** `curl`, optional `jq`, a valid per-project ingest key from the vault/admin UI, and network path to `INGEST_API_BASE`. + +--- + +## 1. Quick health + +```bash +curl -sS "${INGEST_API_BASE}/health" +# expect: {"status":"ok"} +``` + +If this fails, treat as **process / proxy / TLS** — not application auth. + +--- + +## 2. HTTP 401 — `unauthorized` / missing credentials + +**Symptoms:** JSON like `{ "error": "unauthorized", "message": "Missing ingest credentials …" }` or `Invalid or inactive ingest key`. + +**Checks** + +1. **Header present:** send exactly one of: + - `Authorization: Bearer ` + - `X-Api-Key: ` +2. **Key state in DB:** key must be `active`, not revoked, not expired (`er_ingest_keys`). A common mistake is rotating the key in the UI but leaving old tokens in systemd/env on senders. +3. **Wrong environment:** staging token against production base URL (or vice versa). + +**Sanitized curl (no token in shell history):** read token from a file. + +```bash +curl -sS -X POST "${INGEST_API_BASE}/v1/ingest/events" \ + -H "Authorization: Bearer $(cat /run/secrets/er_ingest_token)" \ + -H "Content-Type: application/json" \ + -d '{"events":[{"schema_version":1,"occurred_at":"2026-04-02T12:00:00.000Z","level":"error","message":"auth probe"}]}' +``` + +--- + +## 3. HTTP 429 — rate limits + +Two layers: + +1. **Anonymous IP** — unauthenticated `POST /v1/ingest/events` from an IP is throttled (`INGEST_ANON_IP_MAX` / `INGEST_ANON_IP_WINDOW_MS`). Response includes **`Retry-After`** (seconds). +2. **Per API key** — after successful auth, limits use `rate_limit_max` / `rate_limit_window_ms` on the key row, else service defaults (`INGEST_RATE_LIMIT_MAX`, `INGEST_RATE_LIMIT_WINDOW_MS`). + +**What to do** + +- Back off using `Retry-After`. +- Fix misconfigured clients (tight loops, duplicate crons). +- For legitimate bursts, raise per-key limits in DB (or split traffic across keys only if product policy allows). + +**Metrics:** `er_ingest_requests_total{status_code="429"}` and histogram `er_ingest_request_duration_seconds` — see [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). + +--- + +## 4. Events accepted but “wrong” incident / duplicate noise — fingerprints + +Fingerprinting uses **message normalization** (first line, NFKC, collapsed whitespace) and **location** from `context` (`file_path` / `file`, `line_number` / `line` / `lineno`, or nested `stack_info`). See `ingest-api` `fingerprintPolicy.ts` and `normalize.ts`. + +**Symptoms** + +- Same logical bug creates **multiple incidents** because `message` differs slightly (timestamps, IDs in text). +- **Unexpected grouping** because `context.file_path` is missing or varies per host. + +**Checks** + +1. Compare **raw** `message` strings from the sender; normalize mentally (first line only). +2. Ensure **stable** `context.file_path` (and line) for stack-less errors. +3. Optionally send an explicit **`fingerprint`** field (max 128 chars) for stable dedup when message text is inherently volatile (document this choice per project). + +**Verify in hub:** use admin `GET /v1/incidents/:id` or public `recent-errors` with `q=` after triage key is set. + +--- + +## 5. HTTP 400 — `schema_version` / `occurred_at` + +- Only **`schema_version: 1`** is accepted. +- **`occurred_at`** must parse as valid ISO-8601 (see server validation). + +```bash +# Bad: will 400 +curl -sS -w "\n%{http_code}\n" -X POST "${INGEST_API_BASE}/v1/ingest/events" \ + -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + -d '{"events":[{"schema_version":2,"occurred_at":"not-a-date","level":"e","message":"x"}]}' +``` + +--- + +## 6. HTTP 409 — idempotency conflict + +When **`Idempotency-Key`** is reused with a **different** JSON body, the API returns **409** `idempotency_conflict`. Use a **new** key or retry the **exact** original payload. + +--- + +## 7. Noise rules — events “disappear” + +If the response shows `results[]` entries with `"skipped": true`, the event matched a **noise rule** (`rule_id`, `reason`). This is expected for filtered traffic. Check `noise_filtered_count` and compare with `er_ingest_events_total{outcome="skipped_noise"}` in Prometheus. + +--- + +## 8. OpenAPI / Swagger + +For interactive inspection (lab only): + +- `GET ${INGEST_API_BASE}/v1/openapi.json` +- Browser: `${INGEST_API_BASE}/v1/docs/ui` + +--- + +## Related + +- [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) — full request/response shapes. +- [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) — hub-side listing and mutations. diff --git a/docs/RUNBOOK_OPERATIONS.md b/docs/RUNBOOK_OPERATIONS.md new file mode 100644 index 0000000..6b67faf --- /dev/null +++ b/docs/RUNBOOK_OPERATIONS.md @@ -0,0 +1,116 @@ +# Runbook — five common operational scenarios (hub) + +**Audience:** Operators without the admin UI. +**Tools:** [scripts/er-cli.sh](../scripts/er-cli.sh) (recommended) or `curl` + `jq` as in [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md). + +```bash +export ERROR_RESOLVE_API_KEY="" +export ER_API_BASE="https://errors.bitreport.pt" # or internal Fastify URL +``` + +--- + +## Scenario 1 — List open incidents for a **project** + +**Goal:** See everything open/investigating for slug `crm`. + +```bash +./scripts/er-cli.sh list-open --project crm --limit 200 +``` + +**curl equivalent** + +```bash +curl -sS -G "${ER_API_BASE}/api/error-monitoring/recent-errors" \ + --data-urlencode "api_key=${ERROR_RESOLVE_API_KEY}" \ + --data-urlencode "status=open,investigating" \ + --data-urlencode "project_slug=crm" \ + --data-urlencode "limit=200" | jq '.data[] | {unique_id, project_slug, severity, message}' +``` + +--- + +## Scenario 2 — **Search** by title/message/fingerprint substring + +**Goal:** Find rows matching a failing dependency or error text. + +```bash +./scripts/er-cli.sh list-open --q "Redis connection" --limit 500 +``` + +Use **`export`** for offline analysis: + +```bash +./scripts/er-cli.sh export --state open --format json | jq '.[] | select(.message | test("Redis"; "i"))' +``` + +--- + +## Scenario 3 — **Resolve one** incident (by occurrence or incident id) + +**Goal:** Close after deploy; `unique_id` is the numeric id from `list-open` / `recent-errors`. + +```bash +./scripts/er-cli.sh resolve 123456789 --note "fixed in release 1.2.3" --assigned-to "oncall" +``` + +**curl** + +```bash +curl -sS -X POST "${ER_API_BASE}/api/error-monitoring/resolve" \ + -H "Content-Type: application/json" \ + -H "X-Error-Resolve-Key: ${ERROR_RESOLVE_API_KEY}" \ + -d '{"unique_id":"123456789","resolution_notes":"fixed in release 1.2.3"}' | jq . +``` + +--- + +## Scenario 4 — **Bulk resolve** by message pattern + +**Goal:** Clear a class of errors after a shared root cause. + +1. **Dry run** (lists matches, no mutation): + +```bash +./scripts/er-cli.sh resolve-by-pattern "Timeout contacting upstream" --dry-run +``` + +2. **Execute** + +```bash +./scripts/er-cli.sh resolve-by-pattern "Timeout contacting upstream" \ + --note "upstream restored 2026-04-02" +``` + +This calls `POST /api/error-monitoring/bulk-resolve` with `message_pattern`. + +--- + +## Scenario 5 — **Purge resolved** incidents (destructive) + +**Goal:** reclaim DB space after retention policy. **Always dry-run first.** + +```bash +./scripts/er-cli.sh purge --dry-run +# review would_delete +./scripts/er-cli.sh purge +``` + +> Current implementation deletes **all** resolved incidents in one call (no age filter). Plan maintenance accordingly; see [HTTP_CONTRACTS.md](HTTP_CONTRACTS.md) § purge-resolved. + +--- + +## Extras (same session) + +| Need | Command / endpoint | +|------|---------------------| +| Snapshot CSV | `./scripts/er-cli.sh export --state open --format csv > open.csv` | +| Hub stats + Prometheus gauge refresh | `GET /api/error-monitoring/stats?api_key=…` | +| Admin drill-down | Cookie login + `GET /v1/incidents/:id` ([HTTP_CONTRACTS.md](HTTP_CONTRACTS.md)) | + +--- + +## Related + +- [RUNBOOK_TRIAGE.md](RUNBOOK_TRIAGE.md) — broader triage and deploy notes. +- [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) — sender-side ingest issues. diff --git a/docs/RUNBOOK_TRIAGE.md b/docs/RUNBOOK_TRIAGE.md index 6cb025f..d22b244 100644 --- a/docs/RUNBOOK_TRIAGE.md +++ b/docs/RUNBOOK_TRIAGE.md @@ -4,6 +4,8 @@ **Última revisão:** 2026-04-02 **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), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). + --- ## Variáveis de ambiente necessárias diff --git a/scripts/examples/hub_public_smoke.sh b/scripts/examples/hub_public_smoke.sh new file mode 100755 index 0000000..6c48f90 --- /dev/null +++ b/scripts/examples/hub_public_smoke.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Optional smoke checks against the public hub API (read + health). +# Usage: +# export ER_API_BASE=https://errors.bitreport.pt +# export ERROR_RESOLVE_API_KEY=... +# ./scripts/examples/hub_public_smoke.sh +set -euo pipefail + +: "${ER_API_BASE:?set ER_API_BASE (e.g. https://errors.bitreport.pt)}" +: "${ERROR_RESOLVE_API_KEY:?set ERROR_RESOLVE_API_KEY or ERROR_REPORTING_API_KEY}" + +curl -sf --max-time 30 "${ER_API_BASE}/health" >/dev/null + +curl -sf --max-time 30 -G "${ER_API_BASE}/api/error-monitoring/recent-errors" \ + --data-urlencode "api_key=${ERROR_RESOLVE_API_KEY}" \ + --data-urlencode "status=open,investigating" \ + --data-urlencode "limit=1" >/dev/null + +curl -sf --max-time 60 -G "${ER_API_BASE}/api/error-monitoring/stats" \ + --data-urlencode "api_key=${ERROR_RESOLVE_API_KEY}" >/dev/null + +echo "hub_public_smoke: ok" diff --git a/scripts/examples/ingest_smoke.sh b/scripts/examples/ingest_smoke.sh new file mode 100755 index 0000000..b118c6c --- /dev/null +++ b/scripts/examples/ingest_smoke.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Optional smoke check: POST one minimal event to the ingest API. +# Usage: +# export INGEST_API_BASE=http://127.0.0.1:3210 +# export INGEST_API_TOKEN= +# ./scripts/examples/ingest_smoke.sh +set -euo pipefail + +: "${INGEST_API_BASE:?set INGEST_API_BASE}" +: "${INGEST_API_TOKEN:?set INGEST_API_TOKEN (project ingest key)}" + +BODY='{"events":[{"schema_version":1,"occurred_at":"2026-04-02T12:00:00.000Z","level":"error","message":"ingest_smoke.sh probe"}]}' + +curl -sf --max-time 30 -X POST "${INGEST_API_BASE}/v1/ingest/events" \ + -H "Authorization: Bearer ${INGEST_API_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "${BODY}" >/dev/null + +echo "ingest_smoke: ok"