feat(errors): migrate error-reporting stack from PostgreSQL to MariaDB (BIT-255)

Replace Postgres with MariaDB 11 in docker-compose; convert all
database/error_reporting and db/migrations SQL to InnoDB-friendly syntax
(DATETIME(6), AUTO_INCREMENT, ON DUPLICATE KEY). Run admin portal DDL in the
same migrate one-shot as error_reporting.

Switch ingest-api, collector-worker, and api from pg to mysql2 (pools,
parameterized queries, transactions). Align ingest writes with
er_incident_occurrences and include project_id on idempotency inserts.

Add scripts/run-mysql-migrations.sh for host-side applies; update LXC
run-migrate/verify, deployment docs, and .env.example (mysql://, ER_MYSQL_*).

Verified: npm run build + npm test in ingest-api and collector-worker;
npm run build in api. Full docker compose not run here (no local daemon).

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1sonhadorandPaperclip committed 2026-03-22 19:29:11 +00:00
1 parent b0b733d5e1
commit 4604606033
44 files changed
+1547 -993

No files matched your search

+10 -6
View File
@@ -1,12 +1,13 @@
# BitReport error reporting — Docker Compose (copy to `.env` in this directory).
# `docker compose` reads `.env` automatically for variable substitution in docker-compose.yml.
# --- PostgreSQL (service: postgres) ---
ER_POSTGRES_USER=postgres
ER_POSTGRES_PASSWORD=postgres
ER_POSTGRES_DB=error_reporting
# Host port mapped to Postgres (container always listens on 5432)
ER_PUBLISH_PG_PORT=5434
# --- MariaDB (service: mariadb) ---
ER_MYSQL_ROOT_PASSWORD=devrootchange
ER_MYSQL_USER=er_app
ER_MYSQL_PASSWORD=er_app_secret
ER_MYSQL_DATABASE=error_reporting
# Host port mapped to MariaDB (container listens on 3306)
ER_PUBLISH_MYSQL_PORT=3306
# --- Ingest API (service: ingest-api) ---
ER_PUBLISH_INGEST_PORT=3041
@@ -22,3 +23,6 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one
# HTTP_FETCH_TIMEOUT_MS=15000
# MAX_BACKOFF_EXPONENT=8
# COLLECTOR_DEFAULT_INGEST_TOKEN=
# Node apps (ingest-api, collector-worker, api/) expect:
# DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/DATABASE
+9 -2
View File
@@ -1,6 +1,6 @@
# errors.bitreport.pt
BitReport **central error reporting** platform: ingest API, collector worker, admin UI (incidents), PostgreSQL migrations, and optional **admin portal** (auth/RBAC) from BIT-183.
BitReport **central error reporting** platform: ingest API, collector worker, admin UI (incidents), MariaDB migrations, and optional **admin portal** (auth/RBAC) from BIT-183.
**Remote:** `https://git.bitreport.pt/BitReport.pt/errors.bitreport.pt.git`
**Tracking:** Paperclip **BIT-247** (migration from `OTT/error-reporting/`).
@@ -17,7 +17,7 @@ BitReport **central error reporting** platform: ingest API, collector worker, ad
| `docker-compose.yml`, `.env.example` | Local / Proxmox Docker stack |
| `api/` | Fastify admin API — sessions, RBAC (BIT-183) |
| `web/` | Next.js admin login/UI for `api/` |
| `db/migrations/` | Admin-user schema (node-pg-migrate); distinct from `database/error_reporting/` |
| `db/migrations/` | Admin-user schema (SQL); applied with error_reporting migrations via `scripts/docker-migrate.sh` |
| `docs/` | Permission matrix, deployment runbooks |
## Docker Compose (ingest stack)
@@ -41,3 +41,10 @@ curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health"
cd ingest-api && npm ci && npm test
cd ../api && npm ci && npm test
```
Integration tests for ingest (`ingest-api/src/integration.twoProjects.test.ts`) require a migrated MariaDB and:
```bash
export ERROR_REPORTING_TEST_DATABASE_URL='mysql://USER:[email protected]:3306/error_reporting'
cd ingest-api && npm test
```
+724 -144
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -10,8 +10,7 @@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"db:migrate": "node-pg-migrate -d $DATABASE_URL up",
"db:migrate:down": "node-pg-migrate -d $DATABASE_URL down"
"db:migrate": "bash ../scripts/run-mysql-migrations.sh"
},
"dependencies": {
"@fastify/cookie": "^9.3.1",
@@ -20,14 +19,15 @@
"@fastify/rate-limit": "^9.1.0",
"@fastify/swagger": "^8.14.0",
"@fastify/swagger-ui": "^3.0.0",
"bcrypt": "^5.1.1",
"fastify": "^4.27.0",
"pg": "^8.11.5",
"mysql2": "^3.11.5",
"pino": "^9.1.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/node": "^20.14.0",
"@types/pg": "^8.11.6",
"tsx": "^4.15.6",
"typescript": "^5.4.5",
"vitest": "^1.6.0"
+5 -37
View File
@@ -6,42 +6,12 @@
* is preferable to data corruption. Critical operations must log AFTER the
* primary operation succeeds.
*
* Schema (created in migration 003_audit_logs):
*
* CREATE TABLE audit_logs (
* id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
* action VARCHAR(128) NOT NULL, -- e.g. 'projects.delete'
* actor_id UUID, -- NULL for anonymous (failed login)
* actor_ip INET,
* target TEXT, -- email, project ID, token ID, etc.
* metadata JSONB NOT NULL DEFAULT '{}',
* created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
* );
* CREATE INDEX ON audit_logs (actor_id, created_at DESC);
* CREATE INDEX ON audit_logs (action, created_at DESC);
*
* Critical actions that MUST emit audit events (see ROLE_PERMISSIONS for context):
* auth.login — successful login
* auth.login_failed — failed login attempt (includes reason)
* auth.logout — explicit logout
* users.create — new admin user created
* users.update — admin user role/email changed
* users.delete — admin user deleted
* projects.create — new project registered
* projects.update — project settings changed
* projects.delete — project deleted (destructive)
* ingest_tokens.create — new ingest token issued
* ingest_tokens.revoke — ingest token revoked
* sources.create — new active collector source added
* sources.delete — source removed
* errors.triage — error state changed (status transition + note)
* errors.delete — error record deleted
* settings.update — system settings changed
* Schema: db/migrations/003_audit_logs.sql (MariaDB).
*/
import fp from 'fastify-plugin';
import type { FastifyInstance } from 'fastify';
import type { Pool } from 'pg';
import type { Pool } from 'mysql2/promise';
export interface AuditEvent {
action: string;
@@ -52,7 +22,7 @@ export interface AuditEvent {
}
/**
* Write an audit log entry. Accepts a pg Pool or PoolClient so it can
* Write an audit log entry. Accepts a mysql2 Pool or PoolConnection so it can
* participate in an ongoing transaction if needed.
*/
export async function auditLog(
@@ -60,9 +30,9 @@ export async function auditLog(
event: AuditEvent,
): Promise<void> {
try {
await db.query(
await db.execute(
`INSERT INTO audit_logs (action, actor_id, actor_ip, target, metadata)
VALUES ($1, $2, $3::inet, $4, $5::jsonb)`,
VALUES (?, ?, ?, ?, ?)`,
[
event.action,
event.actor_id ?? null,
@@ -72,8 +42,6 @@ export async function auditLog(
],
);
} catch (err) {
// Audit failure must never break the main operation.
// Log the failure so ops can investigate.
console.error('[audit] Failed to write audit event', {
action: event.action,
error: String(err),
+16 -13
View File
@@ -1,10 +1,10 @@
/**
* PostgreSQL connection pool plugin.
* Decorates app with app.db (pg.Pool).
* Env vars: DATABASE_URL (preferred) or DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD.
* MariaDB / MySQL connection pool plugin.
* Decorates app with app.db (mysql2 Pool).
* Env: DATABASE_URL (mysql://user:pass@host:port/db) or discrete DB_* vars.
*/
import fp from 'fastify-plugin';
import { Pool } from 'pg';
import mysql, { type Pool } from 'mysql2/promise';
import type { FastifyInstance } from 'fastify';
declare module 'fastify' {
@@ -14,18 +14,21 @@ declare module 'fastify' {
}
export default fp(async function dbPlugin(app: FastifyInstance) {
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: parseInt(process.env.DB_POOL_MAX ?? '10', 10),
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
const _url = process.env.DATABASE_URL;
if (typeof _url !== 'string' || _url.trim() === '') {
throw new Error('DATABASE_URL is required');
}
const pool = mysql.createPool({
uri: _url.trim(),
connectionLimit: parseInt(process.env.DB_POOL_MAX ?? '10', 10),
waitForConnections: true,
enableKeepAlive: true,
});
// Verify connection on startup
const client = await pool.connect();
const client = await pool.getConnection();
try {
await client.query('SELECT 1');
app.log.info('PostgreSQL connected');
app.log.info('MariaDB connected');
} finally {
client.release();
}
@@ -34,6 +37,6 @@ export default fp(async function dbPlugin(app: FastifyInstance) {
app.addHook('onClose', async () => {
await pool.end();
app.log.info('PostgreSQL pool closed');
app.log.info('MariaDB pool closed');
});
}, { name: 'db' });
+47 -55
View File
@@ -8,6 +8,7 @@
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import bcrypt from 'bcrypt';
import {
setAccessCookie,
@@ -24,14 +25,8 @@ interface LoginBody {
password: string;
}
interface RefreshCookies {
'__Host-refresh'?: string;
}
const BCRYPT_ROUNDS = 12;
export default async function adminAuthRoutes(app: FastifyInstance): Promise<void> {
const db = app.db; // postgres pool — registered separately
const db = app.db;
/**
* POST /admin/auth/login
@@ -55,28 +50,29 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
async (request: FastifyRequest<{ Body: LoginBody }>, reply: FastifyReply) => {
const { email, password } = request.body;
// Lookup user — always run bcrypt even if not found (prevent timing oracle)
const result = await db.query<{
id: string;
email: string;
role: string;
password_hash: string;
is_active: boolean;
}>(
const [rows] = await db.execute<RowDataPacket[]>(
`SELECT id, email, role, password_hash, is_active
FROM admin_users
WHERE email = $1
WHERE LOWER(email) = LOWER(?)
LIMIT 1`,
[email.toLowerCase()],
[email],
);
const user = result.rows[0];
const user = rows[0] as
| {
id: string;
email: string;
role: string;
password_hash: string;
is_active: number | boolean;
}
| undefined;
// Use a dummy hash when user not found to prevent timing attacks
const hash_to_check = user?.password_hash ?? '$2b$12$invalidhashfortimingprotection000000000000000';
const password_ok = await bcrypt.compare(password, hash_to_check);
if (!user || !password_ok || !user.is_active) {
const _active = user ? Boolean(user.is_active) : false;
if (!user || !password_ok || !_active) {
await auditLog(db, {
action: 'auth.login_failed',
actor_id: null,
@@ -87,16 +83,15 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
return reply.code(401).send({ error: 'Invalid credentials' });
}
// Issue tokens
const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as any };
const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as JwtPayload['role'] };
const access_token = app.jwt.sign(payload, { expiresIn: '15m' });
const refresh_token = generateRefreshToken();
const refresh_hash = hashRefreshToken(refresh_token);
await db.query(
await db.execute(
`INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, NOW() + INTERVAL '7 days')`,
VALUES (?, ?, DATE_ADD(NOW(6), INTERVAL 7 DAY))`,
[user.id, refresh_hash],
);
@@ -121,9 +116,9 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
* POST /admin/auth/refresh
* Rotates the refresh token and issues a new access token.
*/
app.post<{ Cookies: RefreshCookies }>(
app.post(
'/admin/auth/refresh',
async (request: FastifyRequest<{ Cookies: RefreshCookies }>, reply: FastifyReply) => {
async (request: FastifyRequest, reply: FastifyReply) => {
const refresh_token = request.cookies['__Host-refresh'];
if (!refresh_token) {
return reply.code(401).send({ error: 'No refresh token' });
@@ -131,58 +126,55 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
const refresh_hash = hashRefreshToken(refresh_token);
const result = await db.query<{
id: string;
user_id: string;
expires_at: Date;
revoked_at: Date | null;
}>(
const [rows] = await db.execute<RowDataPacket[]>(
`SELECT id, user_id, expires_at, revoked_at
FROM admin_refresh_tokens
WHERE token_hash = $1
WHERE token_hash = ?
LIMIT 1`,
[refresh_hash],
);
const token_row = result.rows[0];
const token_row = rows[0] as
| {
id: string;
user_id: string;
expires_at: Date;
revoked_at: Date | null;
}
| undefined;
if (!token_row || token_row.revoked_at || token_row.expires_at < new Date()) {
clearAuthCookies(reply);
return reply.code(401).send({ error: 'Refresh token invalid or expired' });
}
// Revoke old refresh token (rotation — detect replay attacks)
await db.query(
`UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE id = $1`,
await db.execute(
`UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE id = ?`,
[token_row.id],
);
// Fetch user
const user_result = await db.query<{
id: string;
email: string;
role: string;
is_active: boolean;
}>(
`SELECT id, email, role, is_active FROM admin_users WHERE id = $1`,
const [userRows] = await db.execute<RowDataPacket[]>(
`SELECT id, email, role, is_active FROM admin_users WHERE id = ?`,
[token_row.user_id],
);
const user = user_result.rows[0];
if (!user || !user.is_active) {
const user = userRows[0] as
| { id: string; email: string; role: string; is_active: number | boolean }
| undefined;
const _uActive = user ? Boolean(user.is_active) : false;
if (!user || !_uActive) {
clearAuthCookies(reply);
return reply.code(401).send({ error: 'User no longer active' });
}
// Issue new token pair
const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as any };
const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as JwtPayload['role'] };
const new_access_token = app.jwt.sign(payload, { expiresIn: '15m' });
const new_refresh_token = generateRefreshToken();
const new_refresh_hash = hashRefreshToken(new_refresh_token);
await db.query(
await db.execute(
`INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, NOW() + INTERVAL '7 days')`,
VALUES (?, ?, DATE_ADD(NOW(6), INTERVAL 7 DAY))`,
[user.id, new_refresh_hash],
);
@@ -202,10 +194,10 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
async (request: FastifyRequest, reply: FastifyReply) => {
const refresh_token = request.cookies['__Host-refresh'];
if (refresh_token) {
const refresh_hash = hashRefreshToken(refresh_token);
await db.query(
`UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE token_hash = $1`,
[refresh_hash],
const rh = hashRefreshToken(refresh_token);
await db.execute(
`UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE token_hash = ?`,
[rh],
);
}
+123 -159
View File
@@ -9,11 +9,10 @@
"version": "0.1.0",
"dependencies": {
"dotenv": "^16.4.5",
"pg": "^8.13.1"
"mysql2": "^3.11.5"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
@@ -832,24 +831,11 @@
"version": "22.19.15",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -973,6 +959,15 @@
"node": ">=12"
}
},
"node_modules/aws-ssl-profiles": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -1038,6 +1033,15 @@
"node": ">=6"
}
},
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10"
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
@@ -1134,6 +1138,15 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"license": "MIT",
"dependencies": {
"is-property": "^1.0.2"
}
},
"node_modules/get-tsconfig": {
"version": "4.13.6",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
@@ -1147,6 +1160,34 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
"integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"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/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -1154,6 +1195,21 @@
"dev": true,
"license": "MIT"
},
"node_modules/lru.min": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz",
"integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=1.30.0",
"node": ">=8.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wellwelwel"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -1171,6 +1227,40 @@
"dev": true,
"license": "MIT"
},
"node_modules/mysql2": {
"version": "3.20.0",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.20.0.tgz",
"integrity": "sha512-eCLUs7BNbgA6nf/MZXsaBO1SfGs0LtLVrJD3WeWq+jPLDWkSufTD+aGMwykfUVPdZnblaUK1a8G/P63cl9FkKg==",
"license": "MIT",
"dependencies": {
"aws-ssl-profiles": "^1.1.2",
"denque": "^2.1.0",
"generate-function": "^2.3.1",
"iconv-lite": "^0.7.2",
"long": "^5.3.2",
"lru.min": "^1.1.4",
"named-placeholders": "^1.1.6",
"sql-escaper": "^1.3.3"
},
"engines": {
"node": ">= 8.0"
},
"peerDependencies": {
"@types/node": ">= 8"
}
},
"node_modules/named-placeholders": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
"integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
"license": "MIT",
"dependencies": {
"lru.min": "^1.1.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
@@ -1207,95 +1297,6 @@
"node": ">= 14.16"
}
},
"node_modules/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.12.0",
"pg-pool": "^3.13.0",
"pg-protocol": "^1.13.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.3.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",
"integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz",
"integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.13.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz",
"integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz",
"integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -1332,45 +1333,6 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
@@ -1426,6 +1388,12 @@
"fsevents": "~2.3.2"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
@@ -1443,13 +1411,19 @@
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"node_modules/sql-escaper": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz",
"integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==",
"license": "MIT",
"engines": {
"node": ">= 10.x"
"bun": ">=1.0.0",
"deno": ">=2.0.0",
"node": ">=12.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
}
},
"node_modules/stackback": {
@@ -1548,7 +1522,6 @@
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/vite": {
@@ -2146,15 +2119,6 @@
"engines": {
"node": ">=8"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
}
}
}
+1 -2
View File
@@ -13,11 +13,10 @@
},
"dependencies": {
"dotenv": "^16.4.5",
"pg": "^8.13.1"
"mysql2": "^3.11.5"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
+32 -29
View File
@@ -1,29 +1,32 @@
import type { Pool, PoolClient } from "pg";
import type { Pool, PoolConnection } from "mysql2/promise";
import type { ResultSetHeader } from "mysql2";
export async function insertRunStarted(
client: PoolClient,
client: PoolConnection,
input: { collectorSourceId: string; projectId: string },
): Promise<string> {
const _ins = await client.query<{ id: string }>(
const [res] = await client.execute<ResultSetHeader>(
`INSERT INTO er_collector_runs (
collector_source_id,
project_id,
triggered_by,
started_at,
status
) VALUES ($1::bigint, $2::bigint, 'scheduler', NOW(), 'running')
RETURNING id::text`,
) VALUES (?, ?, 'scheduler', NOW(6), 'running')`,
[input.collectorSourceId, input.projectId],
);
const _id = _ins.rows[0]?.id;
if (!_id) {
const _id = res.insertId;
if (typeof _id !== "number" && typeof _id !== "bigint") {
throw new Error("collector_run_insert_failed");
}
return _id;
if (Number(_id) <= 0) {
throw new Error("collector_run_insert_failed");
}
return String(_id);
}
export async function finishRun(
client: PoolClient,
client: PoolConnection,
input: {
runId: string;
status: "success" | "failed" | "partial";
@@ -34,35 +37,35 @@ export async function finishRun(
errorSummary: string | null;
},
): Promise<void> {
await client.query(
await client.execute(
`UPDATE er_collector_runs
SET finished_at = NOW(),
status = $2,
fetched_count = $3,
accepted_count = $4,
deduplicated_count = $5,
failed_count = $6,
error_summary = $7
WHERE id = $1::bigint`,
SET finished_at = NOW(6),
status = ?,
fetched_count = ?,
accepted_count = ?,
deduplicated_count = ?,
failed_count = ?,
error_summary = ?
WHERE id = ?`,
[
input.runId,
input.status,
input.fetchedCount,
input.acceptedCount,
input.deduplicatedCount,
input.failedCount,
input.errorSummary,
input.runId,
],
);
}
export async function markSourceSuccess(pool: Pool, sourceId: string): Promise<void> {
await pool.query(
await pool.execute(
`UPDATE er_collector_sources
SET last_success_at = NOW(),
SET last_success_at = NOW(6),
last_error_message = NULL,
updated_at = NOW()
WHERE id = $1::bigint`,
updated_at = NOW(6)
WHERE id = ?`,
[sourceId],
);
}
@@ -71,12 +74,12 @@ export async function markSourceFailure(
pool: Pool,
input: { sourceId: string; message: string },
): Promise<void> {
await pool.query(
await pool.execute(
`UPDATE er_collector_sources
SET last_error_at = NOW(),
last_error_message = $2,
updated_at = NOW()
WHERE id = $1::bigint`,
[input.sourceId, input.message.slice(0, 4000)],
SET last_error_at = NOW(6),
last_error_message = ?,
updated_at = NOW(6)
WHERE id = ?`,
[input.message.slice(0, 4000), input.sourceId],
);
}
+17 -21
View File
@@ -1,33 +1,29 @@
import type { Pool } from "pg";
import type { Pool } from "mysql2/promise";
import type { RowDataPacket } from "mysql2";
import type { CollectorSourceRow } from "../types/ingest.js";
export async function loadActiveSources(pool: Pool): Promise<CollectorSourceRow[]> {
const _res = await pool.query<{
id: string;
project_id: string;
name: string;
source_type: string;
endpoint_uri: string;
auth_secret_ref: string | null;
poll_interval_seconds: string;
}>(
`SELECT id::text,
project_id::text,
const [rows] = await pool.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS id,
CAST(project_id AS CHAR) AS project_id,
name,
source_type,
endpoint_uri,
auth_secret_ref,
poll_interval_seconds::text
CAST(poll_interval_seconds AS CHAR) AS poll_interval_seconds
FROM er_collector_sources
WHERE is_active = TRUE`,
);
return _res.rows.map((row) => ({
id: row.id,
project_id: row.project_id,
name: row.name,
source_type: row.source_type,
endpoint_uri: row.endpoint_uri,
auth_secret_ref: row.auth_secret_ref,
poll_interval_seconds: Number.parseInt(row.poll_interval_seconds, 10),
return rows.map((row) => ({
id: String((row as { id: string }).id),
project_id: String((row as { project_id: string }).project_id),
name: String((row as { name: string }).name),
source_type: String((row as { source_type: string }).source_type),
endpoint_uri: String((row as { endpoint_uri: string }).endpoint_uri),
auth_secret_ref: (row as { auth_secret_ref: string | null }).auth_secret_ref,
poll_interval_seconds: Number.parseInt(
String((row as { poll_interval_seconds: string }).poll_interval_seconds),
10,
),
}));
}
+6 -5
View File
@@ -1,4 +1,4 @@
import pg from "pg";
import mysql from "mysql2/promise";
import { loadEnv } from "./config/loadEnv.js";
import { loadActiveSources } from "./db/loadActiveSources.js";
import { logError, logInfo } from "./log/structuredLog.js";
@@ -6,10 +6,11 @@ import { runHttpSourceOnce } from "./scheduler/runHttpSourceOnce.js";
import type { SourceRuntimeState } from "./scheduler/sourceState.js";
const _env = loadEnv();
const _pool = new pg.Pool({
connectionString: _env.DATABASE_URL,
max: 8,
idleTimeoutMillis: 30_000,
const _pool = mysql.createPool({
uri: _env.DATABASE_URL,
connectionLimit: 8,
waitForConnections: true,
enableKeepAlive: true,
});
const _stateBySourceId = new Map<string, SourceRuntimeState>();
@@ -1,4 +1,4 @@
import type { Pool } from "pg";
import type { Pool } from "mysql2/promise";
import { resolveIngestToken } from "../auth/resolveSecret.js";
import type { CollectorEnv } from "../config/loadEnv.js";
import {
@@ -21,17 +21,17 @@ export async function runHttpSourceOnce(input: {
}): Promise<void> {
const { pool, env, source, state } = input;
const _baseMs = Math.max(source.poll_interval_seconds, 15) * 1000;
const _client = await pool.connect();
const _client = await pool.getConnection();
let _runId = "";
try {
await _client.query("BEGIN");
await _client.beginTransaction();
_runId = await insertRunStarted(_client, {
collectorSourceId: source.id,
projectId: source.project_id,
});
await _client.query("COMMIT");
await _client.commit();
} catch (_err) {
await _client.query("ROLLBACK");
await _client.rollback();
_client.release();
const _msg = _err instanceof Error ? _err.message : "run_start_failed";
logError({
@@ -106,7 +106,7 @@ export async function runHttpSourceOnce(input: {
}
if (_fetched.events.length === 0) {
const _c2 = await pool.connect();
const _c2 = await pool.getConnection();
try {
await finishRun(_c2, {
runId: _runId,
@@ -167,7 +167,7 @@ export async function runHttpSourceOnce(input: {
return;
}
const _c3 = await pool.connect();
const _c3 = await pool.getConnection();
try {
await finishRun(_c3, {
runId: _runId,
@@ -201,7 +201,7 @@ async function _finishFailedRun(
runId: string,
input: { fetched: number; accepted: number; failed: number; error: string },
): Promise<void> {
const _c = await pool.connect();
const _c = await pool.getConnection();
try {
await finishRun(_c, {
runId,
+14 -5
View File
@@ -3,7 +3,7 @@
This folder contains the relational data model for the Error Reporting platform epic (`BIT-154`), implemented for task `BIT-178`.
Status and dependency:
- Stack baseline is defined by `docs/architecture/ADR-002-error-reporting-platform-phase1.md` (Fastify + PostgreSQL + Redis queue for phase 1).
- Runtime target is **MariaDB 10.11+** (or MySQL 8+) with **InnoDB**; Compose and LXC apply the same SQL.
- Schema changes must continue through versioned SQL migrations only (`up` + `down`), never ad hoc DDL.
## Migration layout
@@ -15,13 +15,22 @@ Migrations are versioned and reversible (`up` + `down`), timestamped, and idempo
3. `20260322044500_add_ingest_idempotency.*`
4. `20260322045000_create_collectors_retention_and_audit.*`
Admin portal tables (`admin_users`, refresh tokens, audit) live under `db/migrations/` at repo root and are applied in the same database by `scripts/docker-migrate.sh` / `deploy/lxc/run-migrate.sh`.
## Apply manually (example)
From the repository root, with `mariadb` client and a `mysql://` (or discrete `ER_MYSQL_*`) connection:
```bash
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql
./scripts/run-mysql-migrations.sh
```
Or run individual files:
```bash
mariadb -h 127.0.0.1 -u er_app -p"$ER_MYSQL_PASSWORD" error_reporting \
< database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql
# ... remaining migrations + db/migrations/*.sql + seed as in scripts/docker-migrate.sh
```
Rollback in reverse order with the matching `*.down.sql` files.
@@ -1,12 +1,7 @@
BEGIN;
DROP INDEX IF EXISTS er_incidents_project_severity_seen_idx;
DROP INDEX IF EXISTS er_incidents_project_state_seen_idx;
DROP TABLE IF EXISTS er_incidents;
DROP INDEX IF EXISTS er_ingest_keys_project_status_idx;
DROP TABLE IF EXISTS er_ingest_keys;
DROP TABLE IF EXISTS er_projects;
COMMIT;
@@ -1,29 +1,29 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_projects (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
slug VARCHAR(64) NOT NULL,
name VARCHAR(160) NOT NULL,
description TEXT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
timezone_name VARCHAR(64) NOT NULL DEFAULT 'UTC',
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
CONSTRAINT er_projects_slug_uniq UNIQUE (slug),
CONSTRAINT er_projects_slug_not_blank_chk CHECK (slug <> '')
);
CREATE TABLE IF NOT EXISTS er_ingest_keys (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
project_id BIGINT NOT NULL,
label VARCHAR(128) NOT NULL,
token_prefix CHAR(8) NOT NULL,
token_hash CHAR(64) NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'active',
last_used_at TIMESTAMP WITHOUT TIME ZONE NULL,
expires_at TIMESTAMP WITHOUT TIME ZONE NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
revoked_at TIMESTAMP WITHOUT TIME ZONE NULL,
last_used_at DATETIME(6) NULL,
expires_at DATETIME(6) NULL,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
revoked_at DATETIME(6) NULL,
CONSTRAINT er_ingest_keys_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
@@ -38,20 +38,20 @@ CREATE INDEX IF NOT EXISTS er_ingest_keys_project_status_idx
ON er_ingest_keys (project_id, status);
CREATE TABLE IF NOT EXISTS er_incidents (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
project_id BIGINT NOT NULL,
fingerprint VARCHAR(128) NOT NULL,
title VARCHAR(300) NOT NULL,
severity VARCHAR(16) NOT NULL,
current_state VARCHAR(16) NOT NULL DEFAULT 'open',
first_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
last_seen_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
first_seen_at DATETIME(6) NOT NULL,
last_seen_at DATETIME(6) NOT NULL,
occurrences_count BIGINT NOT NULL DEFAULT 1,
regression_count INTEGER NOT NULL DEFAULT 0,
regression_count INT NOT NULL DEFAULT 0,
last_ingest_key_id BIGINT NULL,
metadata_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
CONSTRAINT er_incidents_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
@@ -1,18 +1,7 @@
BEGIN;
DROP INDEX IF EXISTS er_incident_attachments_project_kind_time_idx;
DROP INDEX IF EXISTS er_incident_attachments_occurrence_idx;
DROP INDEX IF EXISTS er_incident_attachments_incident_time_idx;
DROP TABLE IF EXISTS er_incident_attachments;
DROP INDEX IF EXISTS er_incident_state_history_project_state_time_idx;
DROP INDEX IF EXISTS er_incident_state_history_incident_time_idx;
DROP TABLE IF EXISTS er_incident_state_history;
DROP INDEX IF EXISTS er_incident_occurrences_request_id_idx;
DROP INDEX IF EXISTS er_incident_occurrences_project_env_time_idx;
DROP INDEX IF EXISTS er_incident_occurrences_project_time_idx;
DROP INDEX IF EXISTS er_incident_occurrences_incident_time_idx;
DROP TABLE IF EXISTS er_incident_occurrences;
COMMIT;
@@ -1,11 +1,11 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_incident_occurrences (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
ingest_key_id BIGINT NULL,
occurred_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
occurred_at DATETIME(6) NOT NULL,
level_raw VARCHAR(32) NOT NULL DEFAULT 'error',
severity VARCHAR(16) NOT NULL DEFAULT 'medium',
schema_version SMALLINT NOT NULL DEFAULT 1,
@@ -19,7 +19,7 @@ CREATE TABLE IF NOT EXISTS er_incident_occurrences (
stack_trace TEXT NULL,
context_json TEXT NULL,
payload_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_incident_occurrences_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
@@ -52,7 +52,7 @@ CREATE INDEX IF NOT EXISTS er_incident_occurrences_request_id_idx
ON er_incident_occurrences (request_id);
CREATE TABLE IF NOT EXISTS er_incident_state_history (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
from_state VARCHAR(16) NULL,
@@ -60,7 +60,7 @@ CREATE TABLE IF NOT EXISTS er_incident_state_history (
changed_by_type VARCHAR(16) NOT NULL,
changed_by_ref VARCHAR(128) NOT NULL,
change_note TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_incident_state_history_incident_fk FOREIGN KEY (incident_id)
REFERENCES er_incidents (id)
ON UPDATE CASCADE
@@ -87,7 +87,7 @@ CREATE INDEX IF NOT EXISTS er_incident_state_history_project_state_time_idx
ON er_incident_state_history (project_id, to_state, created_at DESC);
CREATE TABLE IF NOT EXISTS er_incident_attachments (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
occurrence_id BIGINT NOT NULL,
incident_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
@@ -97,7 +97,7 @@ CREATE TABLE IF NOT EXISTS er_incident_attachments (
size_bytes BIGINT NOT NULL DEFAULT 0,
checksum_sha256 CHAR(64) NULL,
metadata_json TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_incident_attachments_occurrence_fk FOREIGN KEY (occurrence_id)
REFERENCES er_incident_occurrences (id)
ON UPDATE CASCADE
@@ -1,7 +1,5 @@
BEGIN;
DROP INDEX IF EXISTS er_ingest_idempotency_created_idx;
DROP INDEX IF EXISTS er_ingest_idempotency_project_created_idx;
DROP TABLE IF EXISTS er_ingest_idempotency;
COMMIT;
@@ -1,7 +1,7 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_ingest_idempotency (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ingest_key_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
@@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS er_ingest_idempotency (
occurrence_id BIGINT NULL,
http_status SMALLINT NOT NULL DEFAULT 200,
response_json TEXT NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_ingest_idempotency_ingest_key_fk FOREIGN KEY (ingest_key_id)
REFERENCES er_ingest_keys (id)
ON UPDATE CASCADE
@@ -1,18 +1,8 @@
BEGIN;
DROP INDEX IF EXISTS er_audit_logs_request_id_idx;
DROP INDEX IF EXISTS er_audit_logs_project_entity_created_idx;
DROP INDEX IF EXISTS er_audit_logs_project_created_idx;
DROP TABLE IF EXISTS er_audit_logs;
DROP TABLE IF EXISTS er_retention_policies;
DROP INDEX IF EXISTS er_collector_runs_project_status_started_idx;
DROP INDEX IF EXISTS er_collector_runs_project_started_idx;
DROP INDEX IF EXISTS er_collector_runs_source_started_idx;
DROP TABLE IF EXISTS er_collector_runs;
DROP INDEX IF EXISTS er_collector_sources_project_active_idx;
DROP TABLE IF EXISTS er_collector_sources;
COMMIT;
@@ -1,19 +1,19 @@
BEGIN;
CREATE TABLE IF NOT EXISTS er_collector_sources (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
project_id BIGINT NOT NULL,
name VARCHAR(128) NOT NULL,
source_type VARCHAR(16) NOT NULL,
endpoint_uri VARCHAR(1024) NOT NULL,
auth_secret_ref VARCHAR(255) NULL,
poll_interval_seconds INTEGER NOT NULL DEFAULT 60,
poll_interval_seconds INT NOT NULL DEFAULT 60,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
last_success_at TIMESTAMP WITHOUT TIME ZONE NULL,
last_error_at TIMESTAMP WITHOUT TIME ZONE NULL,
last_success_at DATETIME(6) NULL,
last_error_at DATETIME(6) NULL,
last_error_message TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
CONSTRAINT er_collector_sources_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
@@ -29,19 +29,19 @@ CREATE INDEX IF NOT EXISTS er_collector_sources_project_active_idx
ON er_collector_sources (project_id, is_active);
CREATE TABLE IF NOT EXISTS er_collector_runs (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
collector_source_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
triggered_by VARCHAR(16) NOT NULL,
started_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
finished_at TIMESTAMP WITHOUT TIME ZONE NULL,
started_at DATETIME(6) NOT NULL,
finished_at DATETIME(6) NULL,
status VARCHAR(16) NOT NULL,
fetched_count INTEGER NOT NULL DEFAULT 0,
accepted_count INTEGER NOT NULL DEFAULT 0,
deduplicated_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
fetched_count INT NOT NULL DEFAULT 0,
accepted_count INT NOT NULL DEFAULT 0,
deduplicated_count INT NOT NULL DEFAULT 0,
failed_count INT NOT NULL DEFAULT 0,
error_summary TEXT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_collector_runs_source_fk FOREIGN KEY (collector_source_id)
REFERENCES er_collector_sources (id)
ON UPDATE CASCADE
@@ -72,18 +72,18 @@ CREATE INDEX IF NOT EXISTS er_collector_runs_project_status_started_idx
ON er_collector_runs (project_id, status, started_at DESC);
CREATE TABLE IF NOT EXISTS er_retention_policies (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
project_id BIGINT NOT NULL,
keep_open_days INTEGER NOT NULL DEFAULT 90,
keep_resolved_days INTEGER NOT NULL DEFAULT 30,
keep_ignored_days INTEGER NOT NULL DEFAULT 7,
keep_attachments_days INTEGER NOT NULL DEFAULT 30,
keep_audit_days INTEGER NOT NULL DEFAULT 365,
keep_open_days INT NOT NULL DEFAULT 90,
keep_resolved_days INT NOT NULL DEFAULT 30,
keep_ignored_days INT NOT NULL DEFAULT 7,
keep_attachments_days INT NOT NULL DEFAULT 30,
keep_audit_days INT NOT NULL DEFAULT 365,
delete_mode VARCHAR(16) NOT NULL DEFAULT 'soft',
updated_by_type VARCHAR(16) NOT NULL DEFAULT 'system',
updated_by_ref VARCHAR(128) NOT NULL DEFAULT 'bootstrap',
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
CONSTRAINT er_retention_policies_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
@@ -99,7 +99,7 @@ CREATE TABLE IF NOT EXISTS er_retention_policies (
);
CREATE TABLE IF NOT EXISTS er_audit_logs (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
project_id BIGINT NOT NULL,
actor_type VARCHAR(16) NOT NULL,
actor_ref VARCHAR(128) NOT NULL,
@@ -110,7 +110,7 @@ CREATE TABLE IF NOT EXISTS er_audit_logs (
after_json TEXT NULL,
request_id VARCHAR(128) NULL,
ip_address VARCHAR(64) NULL,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT er_audit_logs_project_fk FOREIGN KEY (project_id)
REFERENCES er_projects (id)
ON UPDATE CASCADE
@@ -21,6 +21,6 @@ SELECT
TRUE
FROM er_projects p
WHERE p.slug = 'project-alpha'
ON CONFLICT (project_id, name) DO NOTHING;
ON DUPLICATE KEY UPDATE endpoint_uri = VALUES(endpoint_uri);
COMMIT;
@@ -9,16 +9,16 @@ INSERT INTO er_projects (slug, name, description, is_active)
VALUES
('project-alpha', 'Project Alpha', 'Seed project A for passive ingest tests', TRUE),
('project-beta', 'Project Beta', 'Seed project B for passive ingest tests', TRUE)
ON CONFLICT (slug) DO NOTHING;
ON DUPLICATE KEY UPDATE slug = VALUES(slug);
INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
SELECT p.id, 'default', 'tok_pr_a', '6b28a152af86ee5d2a30216c5c25e938c1b9bec58685a735b590c8cbaa005189', 'active'
FROM er_projects p WHERE p.slug = 'project-alpha'
ON CONFLICT (project_id, label) DO NOTHING;
ON DUPLICATE KEY UPDATE label = label;
INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
SELECT p.id, 'default', 'tok_pr_b', '63ca0b7048280893a98adb9e2a7333e431eb217d90b9470312b2f169ca736012', 'active'
FROM er_projects p WHERE p.slug = 'project-beta'
ON CONFLICT (project_id, label) DO NOTHING;
ON DUPLICATE KEY UPDATE label = label;
COMMIT;
+6 -22
View File
@@ -1,35 +1,19 @@
-- Migration 001: admin_users table
-- Migration 001: admin_users table (MariaDB / MySQL 8+)
-- Stores admin panel users with role-based access control.
-- Passwords are hashed with bcrypt (cost 12) — never store plaintext.
--
-- Roles: superadmin | admin | viewer (see api/src/types/auth.ts)
CREATE TABLE IF NOT EXISTS admin_users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY,
email VARCHAR(320) NOT NULL,
password_hash VARCHAR(60) NOT NULL, -- bcrypt output is always 60 chars
password_hash VARCHAR(60) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'viewer'
CHECK (role IN ('superadmin', 'admin', 'viewer')),
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
);
CREATE UNIQUE INDEX IF NOT EXISTS admin_users_email_idx
ON admin_users (LOWER(email));
-- Auto-update updated_at on row change
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$;
CREATE TRIGGER admin_users_updated_at
BEFORE UPDATE ON admin_users
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
COMMENT ON TABLE admin_users IS 'Admin panel users (RBAC). Phase 1: global roles, no per-project scoping.';
COMMENT ON COLUMN admin_users.role IS 'superadmin = full access; admin = project mgmt; viewer = read-only';
ON admin_users ((LOWER(email)));
+9 -15
View File
@@ -1,15 +1,14 @@
-- Migration 002: admin_refresh_tokens table
-- Stores hashed refresh tokens for admin session rotation.
-- Only the SHA-256 hash is stored; the plaintext token is sent to the client
-- in an HTTP-only cookie and never persisted.
-- Migration 002: admin_refresh_tokens table (MariaDB / MySQL)
CREATE TABLE IF NOT EXISTS admin_refresh_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
token_hash VARCHAR(64) NOT NULL, -- SHA-256 hex (64 chars)
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY,
user_id CHAR(36) NOT NULL,
token_hash VARCHAR(64) NOT NULL,
expires_at DATETIME(6) NOT NULL,
revoked_at DATETIME(6) NULL,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
CONSTRAINT admin_refresh_tokens_user_fk FOREIGN KEY (user_id)
REFERENCES admin_users (id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS admin_refresh_tokens_hash_idx
@@ -17,8 +16,3 @@ CREATE UNIQUE INDEX IF NOT EXISTS admin_refresh_tokens_hash_idx
CREATE INDEX IF NOT EXISTS admin_refresh_tokens_user_idx
ON admin_refresh_tokens (user_id, created_at DESC);
-- Periodic cleanup: delete expired/revoked tokens older than 30 days.
-- Run via cron or pg_cron: DELETE FROM admin_refresh_tokens WHERE expires_at < NOW() - INTERVAL '30 days';
COMMENT ON TABLE admin_refresh_tokens IS 'Hashed refresh tokens for admin JWT rotation. Plaintext never stored.';
+9 -27
View File
@@ -1,39 +1,21 @@
-- Migration 003: audit_logs table
-- Migration 003: audit_logs table (MariaDB / MySQL)
-- Append-only audit trail for critical admin operations.
-- No UPDATE or DELETE on this table — immutability is the point.
-- Partitioning by month recommended when volume grows (phase 2).
CREATE TABLE IF NOT EXISTS audit_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
action VARCHAR(128) NOT NULL, -- e.g. 'auth.login', 'projects.delete'
actor_id UUID, -- NULL for unauthenticated events (login failures)
actor_ip INET,
target TEXT NOT NULL DEFAULT '', -- email, project ID, token ID, etc.
metadata JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY,
action VARCHAR(128) NOT NULL,
actor_id CHAR(36) NULL,
actor_ip VARCHAR(45) NULL,
target TEXT NOT NULL DEFAULT '',
metadata JSON NOT NULL DEFAULT (JSON_OBJECT()),
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
);
-- Query patterns:
-- 1. All actions by a user, recent first
CREATE INDEX IF NOT EXISTS audit_logs_actor_time_idx
ON audit_logs (actor_id, created_at DESC)
WHERE actor_id IS NOT NULL;
ON audit_logs (actor_id, created_at DESC);
-- 2. All events of a specific type, recent first
CREATE INDEX IF NOT EXISTS audit_logs_action_time_idx
ON audit_logs (action, created_at DESC);
-- 3. Recent activity feed (dashboard)
CREATE INDEX IF NOT EXISTS audit_logs_time_idx
ON audit_logs (created_at DESC);
-- Revoke DELETE and UPDATE on this table to enforce immutability.
-- (Run as superuser after migration)
-- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM PUBLIC;
-- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM app_user;
COMMENT ON TABLE audit_logs IS 'Append-only audit trail. Critical: no DELETEs or UPDATEs allowed.';
COMMENT ON COLUMN audit_logs.action IS 'Dot-notation: domain.verb (e.g. auth.login, projects.delete)';
COMMENT ON COLUMN audit_logs.actor_id IS 'NULL for pre-auth events (failed logins)';
COMMENT ON COLUMN audit_logs.target IS 'Human-readable target: email, ID, or description';
COMMENT ON COLUMN audit_logs.metadata IS 'Structured context: role, reason, old/new values (no secrets)';
+4 -17
View File
@@ -1,20 +1,7 @@
-- Migration 004: seed initial superadmin (dev/test only)
-- DO NOT run in production with hardcoded credentials.
-- In production: use the admin CLI (api/src/scripts/create-admin.ts) to create the first user.
--
-- Default dev credentials: [email protected] / changeme
-- Password hash below is bcrypt(cost=12) of 'changeme' — CHANGE IMMEDIATELY.
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM admin_users WHERE role = 'superadmin') THEN
INSERT INTO admin_users (email, password_hash, role)
VALUES (
'[email protected]',
'$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewYpfQN4ZSIMM.Ey', -- 'changeme'
'superadmin'
);
RAISE NOTICE 'Seeded default superadmin. CHANGE THE PASSWORD IMMEDIATELY.';
END IF;
END;
$$;
INSERT INTO admin_users (email, password_hash, role)
SELECT '[email protected]', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewYpfQN4ZSIMM.Ey', 'superadmin'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM admin_users WHERE role = 'superadmin' LIMIT 1);
+2 -2
View File
@@ -1,13 +1,13 @@
# Native LXC deploy (no Docker)
Scripts and unit files for running **ingest-api**, **admin-ui**, and **collector-worker** on Debian/Ubuntu LXC with **PostgreSQL** on the same CT or another host.
Scripts and unit files for running **ingest-api**, **admin-ui**, and **collector-worker** on Debian/Ubuntu LXC with **MariaDB** (or MySQL 8+) on the same CT or another host.
Authoritative runbook: [`docs/deployment/bitreport-error-reporting-lxc-proxmox.md`](../../docs/deployment/bitreport-error-reporting-lxc-proxmox.md).
| Path | Purpose |
|------|---------|
| `env.example` | Template for `/etc/error-reporting/env` |
| `run-migrate.sh` | Apply migrations + seed (after Postgres is up) |
| `run-migrate.sh` | Apply migrations + seed (after MariaDB is up) |
| `verify.sh` | `curl` ingest `/health` and optional checks |
| `systemd/*.service` | Unit files (adjust `WorkingDirectory` if not `/opt/errors.bitreport.pt`) |
| `nginx/*.conf.example` | TLS reverse proxy sketch |
+5 -5
View File
@@ -6,9 +6,9 @@ ER_REPO_ROOT=/opt/errors.bitreport.pt
# Legacy variable name (still read by run-migrate.sh if ER_REPO_ROOT is unset):
# OTT_ROOT=/opt/errors.bitreport.pt
# --- PostgreSQL (single LXC: localhost; split DB LXC: set host accordingly) ---
# URL-encode special characters in user/password per PostgreSQL libpq rules.
DATABASE_URL=postgres://postgres:[email protected]:5432/error_reporting
# --- MariaDB / MySQL (single LXC: localhost; split DB LXC: set host in URL) ---
# Percent-encode special characters in user/password (RFC 3986) when building the URL.
DATABASE_URL=mysql://er_app:[email protected]:3306/error_reporting
# --- ingest-api ---
PORT=3041
@@ -23,8 +23,8 @@ SOURCE_REFRESH_MS=15000
HTTP_FETCH_TIMEOUT_MS=15000
MAX_BACKOFF_EXPONENT=8
# --- admin-ui (Next.js server-side API calls) ---
ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3041
# --- admin-ui (Next.js server-side API calls) — target the Fastify `api/` service (default PORT 3200) ---
ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3200
# ERROR_REPORTING_UI_DEMO=1
# --- Demo / staging only: token must match seed SQL for project-alpha HTTP fixture ---
+42 -14
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# Apply error_reporting SQL migrations and seeds (same order as docker-migrate.sh).
# Prerequisites: psql (postgresql-client), empty or already-migrated DB, DATABASE_URL + ER_REPO_ROOT (or legacy OTT_ROOT).
# Apply error_reporting + admin SQL migrations and error_reporting seeds (same order as scripts/docker-migrate.sh).
# Prerequisites: mariadb client, empty or already-migrated DB, ER_REPO_ROOT, and either DATABASE_URL (mysql://...)
# or ER_MYSQL_HOST / ER_MYSQL_USER / ER_MYSQL_PASSWORD / ER_MYSQL_DATABASE.
set -euo pipefail
_ENV_FILE="/etc/error-reporting/env"
@@ -13,25 +14,52 @@ fi
_REPO_ROOT="${ER_REPO_ROOT:-${OTT_ROOT:-}}"
: "${_REPO_ROOT:?Set ER_REPO_ROOT to this repository root (contains database/error_reporting/). Legacy OTT_ROOT is accepted.}"
: "${DATABASE_URL:?Set DATABASE_URL (postgres://...) for psql}"
_MIG="${_REPO_ROOT}/database/error_reporting/migrations"
_SEED="${_REPO_ROOT}/database/error_reporting/seed"
_MIG_ER="${_REPO_ROOT}/database/error_reporting/migrations"
_SEED_ER="${_REPO_ROOT}/database/error_reporting/seed"
_MIG_ADMIN="${_REPO_ROOT}/db/migrations"
if [[ ! -d "${_MIG}" ]]; then
echo "run-migrate: migrations directory not found: ${_MIG}" >&2
if [[ ! -d "${_MIG_ER}" ]]; then
echo "run-migrate: migrations directory not found: ${_MIG_ER}" >&2
exit 1
fi
if [[ -n "${DATABASE_URL:-}" ]] && [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then
_PARSED="$(python3 -c "
import os
from urllib.parse import urlparse, unquote
u = urlparse(os.environ['DATABASE_URL'])
if u.scheme not in ('mysql', 'mariadb', 'mysqli'):
raise SystemExit('DATABASE_URL must be mysql:// or mariadb://')
host = u.hostname or '127.0.0.1'
port = u.port or 3306
user = unquote(u.username or '')
password = unquote(u.password or '')
db = (u.path or '/').lstrip('/').split('?')[0]
print(host, port, user, password, db)
")"
read -r ER_MYSQL_HOST ER_MYSQL_PORT ER_MYSQL_USER ER_MYSQL_PASSWORD ER_MYSQL_DATABASE <<< "${_PARSED}"
fi
: "${ER_MYSQL_HOST:?Set ER_MYSQL_HOST or mysql:// DATABASE_URL}"
: "${ER_MYSQL_USER:?Set ER_MYSQL_USER or DATABASE_URL}"
: "${ER_MYSQL_PASSWORD:?Set ER_MYSQL_PASSWORD or DATABASE_URL}"
: "${ER_MYSQL_DATABASE:?Set ER_MYSQL_DATABASE or DATABASE_URL}"
: "${ER_MYSQL_PORT:=3306}"
_run_sql() {
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -f "$1"
mariadb -h "${ER_MYSQL_HOST}" -P "${ER_MYSQL_PORT}" -u "${ER_MYSQL_USER}" -p"${ER_MYSQL_PASSWORD}" "${ER_MYSQL_DATABASE}" < "$1"
}
_run_sql "${_MIG}/20260322043000_create_error_reporting_core.up.sql"
_run_sql "${_MIG}/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql "${_MIG}/20260322044500_add_ingest_idempotency.up.sql"
_run_sql "${_MIG}/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql "${_SEED}/dev_two_projects.sql"
_run_sql "${_SEED}/dev_collector_http_fixture.sql"
_run_sql "${_MIG_ER}/20260322043000_create_error_reporting_core.up.sql"
_run_sql "${_MIG_ER}/20260322044000_create_error_occurrences_and_states.up.sql"
_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_ADMIN}/001_admin_users.sql"
_run_sql "${_MIG_ADMIN}/002_admin_refresh_tokens.sql"
_run_sql "${_MIG_ADMIN}/003_audit_logs.sql"
_run_sql "${_MIG_ADMIN}/004_seed_superadmin.sql"
_run_sql "${_SEED_ER}/dev_two_projects.sql"
_run_sql "${_SEED_ER}/dev_collector_http_fixture.sql"
echo "run-migrate: complete"
+20 -7
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Smoke checks after install: Postgres reachability (optional) + ingest /health.
# Smoke checks after install: MariaDB reachability (optional) + ingest /health.
set -euo pipefail
_ENV_FILE="/etc/error-reporting/env"
@@ -19,12 +19,25 @@ if ! curl -sf "${_INGEST_URL}" >/dev/null; then
fi
echo "verify: ingest OK"
if command -v pg_isready >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then
# pg_isready does not accept URI; probe TCP only when URL is simple localhost.
if [[ "${DATABASE_URL}" == *"@127.0.0.1:"* ]] || [[ "${DATABASE_URL}" == *"@localhost:"* ]]; then
echo "verify: pg_isready (best-effort, discrete vars may be needed on some hosts)"
_pgport="${PGPORT:-5432}"
pg_isready -h 127.0.0.1 -p "${_pgport}" || true
if command -v mariadb-admin >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then
if [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then
_PARSED="$(python3 -c "
import os
from urllib.parse import urlparse, unquote
u = urlparse(os.environ['DATABASE_URL'])
if u.scheme not in ('mysql', 'mariadb', 'mysqli'):
raise SystemExit(0)
host = u.hostname or '127.0.0.1'
port = u.port or 3306
user = unquote(u.username or '')
password = unquote(u.password or '')
print(host, port, user, password)
" 2>/dev/null)" || true
if [[ -n "${_PARSED}" ]]; then
read -r _h _p _u _pw <<< "${_PARSED}"
echo "verify: mariadb-admin ping (best-effort)"
mariadb-admin ping -h "${_h}" -P "${_p}" -u "${_u}" -p"${_pw}" --silent || true
fi
fi
fi
+26 -23
View File
@@ -1,4 +1,4 @@
# BitReport error reporting — reproducible stack: Postgres, migrate (one-shot), ingest API, collector worker.
# BitReport error reporting — reproducible stack: MariaDB, migrate (one-shot), ingest API, collector worker.
# Prerequisites: Docker Engine + Compose v2.
#
# Quick start:
@@ -10,39 +10,42 @@
# Docs: docs/deployment/bitreport-error-reporting-compose-proxmox.md
services:
postgres:
image: postgres:16-alpine
mariadb:
image: mariadb:11
environment:
POSTGRES_USER: ${ER_POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${ER_POSTGRES_PASSWORD:-postgres}
POSTGRES_DB: ${ER_POSTGRES_DB:-error_reporting}
MARIADB_ROOT_PASSWORD: ${ER_MYSQL_ROOT_PASSWORD:-devrootchange}
MARIADB_DATABASE: ${ER_MYSQL_DATABASE:-error_reporting}
MARIADB_USER: ${ER_MYSQL_USER:-er_app}
MARIADB_PASSWORD: ${ER_MYSQL_PASSWORD:-er_app_secret}
ports:
- "${ER_PUBLISH_PG_PORT:-5434}:5432"
- "${ER_PUBLISH_MYSQL_PORT:-3306}:3306"
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -U ${ER_POSTGRES_USER:-postgres} -d ${ER_POSTGRES_DB:-error_reporting}",
"mariadb-admin ping -h 127.0.0.1 -u \"$$MARIADB_USER\" -p\"$$MARIADB_PASSWORD\" --silent",
]
interval: 3s
timeout: 3s
retries: 15
interval: 5s
timeout: 5s
retries: 24
start_period: 20s
migrate:
image: postgres:16-alpine
image: mariadb:11
depends_on:
postgres:
mariadb:
condition: service_healthy
environment:
PGHOST: postgres
PGUSER: ${ER_POSTGRES_USER:-postgres}
PGPASSWORD: ${ER_POSTGRES_PASSWORD:-postgres}
PGDATABASE: ${ER_POSTGRES_DB:-error_reporting}
MARIADB_HOST: mariadb
MARIADB_USER: ${ER_MYSQL_USER:-er_app}
MARIADB_PASSWORD: ${ER_MYSQL_PASSWORD:-er_app_secret}
MARIADB_DATABASE: ${ER_MYSQL_DATABASE:-error_reporting}
volumes:
- ./database/error_reporting/migrations:/migrations:ro
- ./database/error_reporting/seed:/seed:ro
- ./database/error_reporting/migrations:/migrations/error_reporting:ro
- ./database/error_reporting/seed:/seed/error_reporting:ro
- ./db/migrations:/migrations/admin:ro
- ./scripts/docker-migrate.sh:/docker-migrate.sh:ro
entrypoint: ["/bin/sh", "/docker-migrate.sh"]
entrypoint: ["/bin/bash", "/docker-migrate.sh"]
fixture-poll:
image: nginx:alpine
@@ -56,10 +59,10 @@ services:
depends_on:
migrate:
condition: service_completed_successfully
postgres:
mariadb:
condition: service_healthy
environment:
DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting}
DATABASE_URL: mysql://${ER_MYSQL_USER:-er_app}:${ER_MYSQL_PASSWORD:-er_app_secret}@mariadb:3306/${ER_MYSQL_DATABASE:-error_reporting}
PORT: "3041"
NODE_ENV: production
INGEST_RATE_LIMIT_MAX: ${INGEST_RATE_LIMIT_MAX:-300}
@@ -89,7 +92,7 @@ services:
fixture-poll:
condition: service_started
environment:
DATABASE_URL: postgres://${ER_POSTGRES_USER:-postgres}:${ER_POSTGRES_PASSWORD:-postgres}@postgres:5432/${ER_POSTGRES_DB:-error_reporting}
DATABASE_URL: mysql://${ER_MYSQL_USER:-er_app}:${ER_MYSQL_PASSWORD:-er_app_secret}@mariadb:3306/${ER_MYSQL_DATABASE:-error_reporting}
INGEST_BASE_URL: http://ingest-api:3041
TICK_INTERVAL_MS: ${TICK_INTERVAL_MS:-3000}
SOURCE_REFRESH_MS: ${SOURCE_REFRESH_MS:-15000}
@@ -2,12 +2,12 @@
**Deploy sem Docker (LXC nativo, systemd):** ver [`bitreport-error-reporting-lxc-proxmox.md`](./bitreport-error-reporting-lxc-proxmox.md) e [`deploy/lxc/`](../deploy/lxc/).
Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste repositório: **PostgreSQL**, **migrate** (one-shot), **ingest-api** (app), **collector-worker** (worker), mais **fixture-poll** para o cenário de demo com fonte HTTP local.
Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste repositório: **MariaDB 11**, **migrate** (one-shot), **ingest-api** (app), **collector-worker** (worker), mais **fixture-poll** para o cenário de demo com fonte HTTP local.
## Pré-requisitos
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
- Portas livres no host (por omissão): **5434** → Postgres, **3041** → ingest API. Ajustáveis em `.env` (`ER_PUBLISH_*`).
- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API. Ajustáveis em `.env` (`ER_PUBLISH_*`).
## Arranque reproduzível (qualquer ambiente)
@@ -26,7 +26,7 @@ curl -sf "http://127.0.0.1:${ER_PUBLISH_INGEST_PORT:-3041}/health"
**Logs úteis:** `docker compose logs -f ingest-api collector-worker`
**Recriar BD do zero** (apaga volumes se existirem; em ambiente novo basta remover o container/volume do Postgres):
**Recriar BD do zero** (apaga volumes se existirem; em ambiente novo basta remover o container/volume do MariaDB):
```bash
docker compose down -v
@@ -37,10 +37,11 @@ docker compose up --build
| Variável | Onde | Descrição |
|----------|------|-----------|
| `ER_POSTGRES_USER` | postgres, migrate, apps | Utilizador da BD |
| `ER_POSTGRES_PASSWORD` | idem | Palavra-passe (evitar `@`, `:`, `/` na URL ou usar encoding na `DATABASE_URL` manual) |
| `ER_POSTGRES_DB` | idem | Nome da base |
| `ER_PUBLISH_PG_PORT` | postgres | Porta no host → 5432 no container |
| `ER_MYSQL_ROOT_PASSWORD` | mariadb (init) | Palavra-passe do `root` no primeiro arranque |
| `ER_MYSQL_USER` | mariadb, migrate, apps | Utilizador da aplicação |
| `ER_MYSQL_PASSWORD` | idem | Palavra-passe (percent-encode na `DATABASE_URL` se tiver `@`, `:`, `/`, etc.) |
| `ER_MYSQL_DATABASE` | idem | Nome da base |
| `ER_PUBLISH_MYSQL_PORT` | mariadb | Porta no host → 3306 no container |
| `ER_PUBLISH_INGEST_PORT` | ingest-api | Porta no host → API |
| `ER_COLLECTOR_PROJECT_ALPHA_TOKEN` | collector-worker | Token do projeto de demo (alinhado com seed SQL) |
| `INGEST_RATE_LIMIT_MAX` | ingest-api | Máx. pedidos por janela (opcional) |
@@ -48,15 +49,15 @@ docker compose up --build
| `TICK_INTERVAL_MS`, `SOURCE_REFRESH_MS`, `HTTP_FETCH_TIMEOUT_MS`, `MAX_BACKOFF_EXPONENT` | collector-worker | Intervalos e limites (opcional) |
| `COLLECTOR_DEFAULT_INGEST_TOKEN` | collector-worker | Fallback para referências `env:VAR` vazias (opcional) |
A `DATABASE_URL` usada nos containers é construída pelo Compose a partir de `ER_POSTGRES_*`. Palavras-passe com caracteres especiais na URL PostgreSQL devem ser [percent-encoded](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING).
A `DATABASE_URL` usada nos containers é construída pelo Compose no formato `mysql://USER:PASSWORD@mariadb:3306/DATABASE`. Palavras-passe com caracteres especiais devem ser [percent-encoded](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1).
## Proxmox (LXC ou VM)
1. **LXC com Docker:** ativar *nesting* no container (`features: nesting=1`) e instalar Docker como no Debian/Ubuntu oficial. Alternativa: VM com Docker — menos atrito com o kernel e cgroups.
2. **Recursos:** Postgres + Node para ingest + worker; para testes, 2 GB RAM e 2 vCPU costumam chegar; subir conforme carga.
3. **Armazenamento:** volume Docker ou bind mount em disco local rápido para `postgres` se quiseres persistência estável.
4. **Firewall (Proxmox / host):** em produção, **não** expor `ER_PUBLISH_PG_PORT` à Internet. Expor só o reverse proxy (80/443) ou VPN.
5. **Backups:** incluir volumes ou dumps (`pg_dump`) da base `ER_POSTGRES_DB`.
2. **Recursos:** MariaDB + Node para ingest + worker; para testes, 2 GB RAM e 2 vCPU costumam chegar; subir conforme carga.
3. **Armazenamento:** volume Docker ou bind mount em disco local rápido para `mariadb` se quiseres persistência estável.
4. **Firewall (Proxmox / host):** em produção, **não** expor `ER_PUBLISH_MYSQL_PORT` à Internet. Expor só o reverse proxy (80/443) ou VPN.
5. **Backups:** incluir volumes ou dumps lógicos (`mariadb-dump` / `mysqldump`) da base `ER_MYSQL_DATABASE`.
## Domínio externo, reverse proxy e TLS
@@ -88,8 +89,8 @@ Ajustar `INGEST_RATE_LIMIT_*` se o tráfego passar por um único IP de proxy (po
## Produção — checklist rápido
- [ ] `ER_POSTGRES_PASSWORD` e tokens de projeto fortes e únicos.
- [ ] Postgres não publicado na Internet.
- [ ] `ER_MYSQL_PASSWORD`, `ER_MYSQL_ROOT_PASSWORD` e tokens de projeto fortes e únicos.
- [ ] MariaDB não publicado na Internet.
- [ ] TLS terminado no proxy; redirecionamento HTTP → HTTPS.
- [ ] `restart: unless-stopped` já no worker; política de restart para `ingest-api` alinhada com o vosso orchestrator.
- [ ] Logs centralizados e alertas para falhas de healthcheck.
@@ -1,6 +1,6 @@
# Error reporting — LXC Proxmox (sem Docker)
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **PostgreSQL**, **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
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**.
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).
@@ -12,18 +12,18 @@ A versão actual da plataforma (**ingest-api**, **collector-worker**, **admin-ui
| Opção | Quando usar |
|-------|-------------|
| **Tudo num CT** | Staging, MVP, baixo tráfego: PostgreSQL + apps no mesmo LXC. |
| **PostgreSQL noutro CT** | Produção alinhada com padrão “DB dedicado”: definir `DATABASE_URL` com hostname interno do CT da base. |
| **Tudo num CT** | Staging, MVP, baixo tráfego: MariaDB + apps no mesmo LXC. |
| **MariaDB noutro CT** | Produção alinhada com padrão “DB dedicado”: definir `DATABASE_URL` com hostname interno do CT da base. |
**Recursos de partida:** 2 GB RAM, 2 vCPU (subir com carga). Disco rápido para PostgreSQL (`/var/lib/postgresql`).
**Recursos de partida:** 2 GB RAM, 2 vCPU (subir com carga). Disco rápido para dados InnoDB (`/var/lib/mysql`).
**Rede:** não expor a porta PostgreSQL à Internet; apenas 80/443 (proxy) ou VPN.
**Rede:** não expor a porta MariaDB (3306) à Internet; apenas 80/443 (proxy) ou VPN.
## 1. Proxmox — criar o LXC
1. Template **Debian 12** ou **Ubuntu 24.04** (mesma linha que os outros serviços).
2. Sem necessidade de **nesting** (não há Docker).
3. Activar backup do CT e incluir volumes de dados PostgreSQL nos backups ou `pg_dump` agendado.
3. Activar backup do CT e incluir volumes de dados MariaDB nos backups ou cópias lógicas (`mariadb-dump`) agendadas.
## 2. Pacotes base e Node.js 20
@@ -31,7 +31,7 @@ No CT (como root):
```bash
apt-get update
apt-get install -y curl ca-certificates git postgresql postgresql-client nginx
apt-get install -y curl ca-certificates git mariadb-server mariadb-client nginx python3
# Node.js 20 LTS (exemplo NodeSource — confirmar URL actual em https://github.com/nodesource/distributions)
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
@@ -40,21 +40,24 @@ apt-get install -y nodejs
node -v # v20.x
```
## 3. PostgreSQL
## 3. MariaDB
Criar utilizador e base (ajustar palavras-passe):
```bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
CREATE USER er_app WITH PASSWORD 'CHANGE_ME_STRONG';
CREATE DATABASE error_reporting OWNER er_app;
GRANT ALL PRIVILEGES ON DATABASE error_reporting TO er_app;
SQL
mariadb -u root -p -e "
CREATE DATABASE IF NOT EXISTS error_reporting CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'er_app'@'localhost' IDENTIFIED BY 'CHANGE_ME_STRONG';
GRANT ALL PRIVILEGES ON error_reporting.* TO 'er_app'@'localhost';
FLUSH PRIVILEGES;
"
```
Construir `DATABASE_URL` (codificar caracteres especiais na password se necessário):
`postgres://er_app:[email protected]:5432/error_reporting`
`mysql://er_app:[email protected]:3306/error_reporting`
Alternativa: definir `ER_MYSQL_HOST`, `ER_MYSQL_PORT`, `ER_MYSQL_USER`, `ER_MYSQL_PASSWORD`, `ER_MYSQL_DATABASE` e deixar `deploy/lxc/run-migrate.sh` derivar a ligação a partir de `DATABASE_URL` em formato `mysql://` (ver script).
## 4. Código no CT
@@ -74,7 +77,7 @@ useradd --system --home /opt/errors.bitreport.pt --shell /usr/sbin/nologin error
chown -R error-reporting:error-reporting /opt/errors.bitreport.pt
```
O utilizador precisa de leitura em `database/error_reporting/` apenas para **correr migrações** (normalmente como root ou postgres com script); em runtime as apps só precisam de `ingest-api`, `admin-ui`, `collector-worker`.
O utilizador precisa de leitura em `database/error_reporting/` e `db/migrations/` apenas para **correr migrações** (normalmente como root com script); em runtime as apps só precisam de `ingest-api`, `admin-ui`, `collector-worker`.
## 6. Ficheiro de ambiente
@@ -86,7 +89,7 @@ chown root:error-reporting /etc/error-reporting/env
nano /etc/error-reporting/env # DATABASE_URL, ER_REPO_ROOT, tokens
```
Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL`, `INGEST_BASE_URL` (normalmente `http://127.0.0.1:3041`), `ERROR_REPORTING_ADMIN_API_BASE` (URL que o **Next.js** usa no servidor para falar com a API — em CT único, `http://127.0.0.1:3041`).
Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL` (`mysql://...`), `INGEST_BASE_URL` (normalmente `http://127.0.0.1:3041`), `ERROR_REPORTING_ADMIN_API_BASE` (URL que o **Next.js** usa no servidor para falar com a API — em CT único, `http://127.0.0.1:3200` ou a porta onde corre o `api/`).
## 7. Dependências Node e build
@@ -94,6 +97,7 @@ Editar pelo menos: `ER_REPO_ROOT`, `DATABASE_URL`, `INGEST_BASE_URL` (normalment
cd /opt/errors.bitreport.pt/ingest-api && npm ci && npm run build
cd /opt/errors.bitreport.pt/admin-ui && npm ci && npm run build
cd /opt/errors.bitreport.pt/collector-worker && npm ci && npm run build
cd /opt/errors.bitreport.pt/api && npm ci && npm run build
chown -R error-reporting:error-reporting /opt/errors.bitreport.pt
```
@@ -157,7 +161,7 @@ Colocar **nginx** (no host Proxmox, CT de proxy, ou o mesmo CT se política o pe
## 13. Checklist rápido (produção)
- [ ] Palavras-passe e tokens fortes; `chmod 640` em `/etc/error-reporting/env`.
- [ ] PostgreSQL só na rede interna / localhost.
- [ ] MariaDB só na rede interna / localhost.
- [ ] TLS no proxy; redireccionamento HTTP → HTTPS.
- [ ] Logs (`journalctl`) e alertas para falhas de arranque.
- [ ] Backups testados (BD + env cifrado na vault, não no Git).
+126 -153
View File
@@ -13,11 +13,10 @@
"@fastify/swagger-ui": "^3.1.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"pg": "^8.13.1"
"mysql2": "^3.11.5"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
@@ -986,24 +985,11 @@
"version": "22.19.15",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1225,6 +1211,15 @@
"fastq": "^1.17.1"
}
},
"node_modules/aws-ssl-profiles": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -1357,6 +1352,15 @@
"node": ">=6"
}
},
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -1633,6 +1637,15 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"license": "MIT",
"dependencies": {
"is-property": "^1.0.2"
}
},
"node_modules/get-tsconfig": {
"version": "4.13.6",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
@@ -1683,6 +1696,22 @@
"node": ">= 0.8"
}
},
"node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
"integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -1707,6 +1736,12 @@
"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",
@@ -1771,6 +1806,12 @@
"set-cookie-parser": "^2.4.1"
}
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -1784,6 +1825,21 @@
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"license": "ISC"
},
"node_modules/lru.min": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz",
"integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=1.30.0",
"node": ">=8.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wellwelwel"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -1836,6 +1892,40 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/mysql2": {
"version": "3.20.0",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.20.0.tgz",
"integrity": "sha512-eCLUs7BNbgA6nf/MZXsaBO1SfGs0LtLVrJD3WeWq+jPLDWkSufTD+aGMwykfUVPdZnblaUK1a8G/P63cl9FkKg==",
"license": "MIT",
"dependencies": {
"aws-ssl-profiles": "^1.1.2",
"denque": "^2.1.0",
"generate-function": "^2.3.1",
"iconv-lite": "^0.7.2",
"long": "^5.3.2",
"lru.min": "^1.1.4",
"named-placeholders": "^1.1.6",
"sql-escaper": "^1.3.3"
},
"engines": {
"node": ">= 8.0"
},
"peerDependencies": {
"@types/node": ">= 8"
}
},
"node_modules/named-placeholders": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
"integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
"license": "MIT",
"dependencies": {
"lru.min": "^1.1.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
@@ -1918,95 +2008,6 @@
"node": ">= 14.16"
}
},
"node_modules/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.12.0",
"pg-pool": "^3.13.0",
"pg-protocol": "^1.13.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.3.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",
"integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz",
"integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.13.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz",
"integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz",
"integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -2096,45 +2097,6 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/process-warning": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
@@ -2305,6 +2267,12 @@
"node": ">=10"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/secure-json-parse": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",
@@ -2403,6 +2371,21 @@
"node": ">= 10.x"
}
},
"node_modules/sql-escaper": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz",
"integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=2.0.0",
"node": ">=12.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -2631,7 +2614,6 @@
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/uri-js": {
@@ -3345,15 +3327,6 @@
"node": ">=8"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yaml": {
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
+1 -2
View File
@@ -18,11 +18,10 @@
"@fastify/swagger-ui": "^3.1.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"pg": "^8.13.1"
"mysql2": "^3.11.5"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/pg": "^8.11.10",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
"vitest": "^2.1.0"
+1 -1
View File
@@ -4,7 +4,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";
import rateLimit from "@fastify/rate-limit";
import type { Pool } from "pg";
import type { Pool } from "mysql2/promise";
import type { IngestEnv } from "./config/env.js";
import { sha256Hex } from "./lib/hash.js";
import { attachIngestAuth } from "./services/ingestAuth.js";
+41 -31
View File
@@ -1,5 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import pg from "pg";
import mysql from "mysql2/promise";
import type { RowDataPacket } from "mysql2";
import { buildApp } from "./buildApp.js";
import type { IngestEnv } from "./config/env.js";
import { sha256Hex } from "./lib/hash.js";
@@ -7,7 +8,7 @@ import { sha256Hex } from "./lib/hash.js";
const _testUrl = process.env.ERROR_REPORTING_TEST_DATABASE_URL;
describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
let _pool: pg.Pool;
let _pool: mysql.Pool;
let _app: Awaited<ReturnType<typeof buildApp>>;
const _tokenA = "er_tst_a_secret_one";
const _tokenB = "er_tst_b_secret_two";
@@ -15,31 +16,38 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
let _projectIdB = "";
beforeAll(async () => {
_pool = new pg.Pool({ connectionString: _testUrl, max: 4 });
await _pool.query(`
TRUNCATE TABLE
er_ingest_idempotency,
er_occurrence_events,
er_incidents,
er_ingest_keys,
er_projects
RESTART IDENTITY CASCADE
`);
const _p = await _pool.query<{ id: string }>(
`INSERT INTO er_projects (slug, name) VALUES ('pa', 'Project A'), ('pb', 'Project B')
RETURNING id::text`,
_pool = mysql.createPool({ uri: _testUrl!, connectionLimit: 4, waitForConnections: true });
const _c = await _pool.getConnection();
try {
await _c.query("SET FOREIGN_KEY_CHECKS = 0");
await _c.query(`TRUNCATE TABLE er_ingest_idempotency`);
await _c.query(`TRUNCATE TABLE er_incident_occurrences`);
await _c.query(`TRUNCATE TABLE er_incidents`);
await _c.query(`TRUNCATE TABLE er_ingest_keys`);
await _c.query(`TRUNCATE TABLE er_projects`);
await _c.query("SET FOREIGN_KEY_CHECKS = 1");
} finally {
_c.release();
}
await _pool.execute(`INSERT INTO er_projects (slug, name) VALUES ('pa', 'Project A')`);
await _pool.execute(`INSERT INTO er_projects (slug, name) VALUES ('pb', 'Project B')`);
const [rows] = await _pool.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS id, slug FROM er_projects WHERE slug IN ('pa', 'pb') ORDER BY slug`,
);
const _rows = _p.rows;
if (_rows.length < 2) {
if (rows.length < 2) {
throw new Error("seed projects failed");
}
_projectIdA = _rows[0]?.id ?? "";
_projectIdB = _rows[1]?.id ?? "";
await _pool.query(
_projectIdA = String((rows[0] as { id: string }).id);
_projectIdB = String((rows[1] as { id: string }).id);
await _pool.execute(
`INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
VALUES ($1::bigint, 'default', 'tok_pr_a', $2, 'active'),
($3::bigint, 'default', 'tok_pr_b', $4, 'active')`,
[_projectIdA, sha256Hex(_tokenA), _projectIdB, sha256Hex(_tokenB)],
VALUES (?, 'default', 'tok_pr_a', ?, 'active')`,
[_projectIdA, sha256Hex(_tokenA)],
);
await _pool.execute(
`INSERT INTO er_ingest_keys (project_id, label, token_prefix, token_hash, status)
VALUES (?, 'default', 'tok_pr_b', ?, 'active')`,
[_projectIdB, sha256Hex(_tokenB)],
);
const _env: IngestEnv = {
PORT: 0,
@@ -104,16 +112,16 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
expect(_bodyB.results[0]?.fingerprint).toBe("fp-b-1");
expect(_bodyB.results[0]?.incident_id).not.toBe(_bodyA.results[0]?.incident_id);
const _check = await _pool.query<{ c: string }>(
`SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`,
const [checkA] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
[_projectIdA],
);
expect(_check.rows[0]?.c).toBe("1");
const _checkB = await _pool.query<{ c: string }>(
`SELECT COUNT(*)::text AS c FROM er_incidents WHERE project_id = $1::bigint`,
expect(Number((checkA[0] as { c: number }).c)).toBe(1);
const [checkB] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE project_id = ?`,
[_projectIdB],
);
expect(_checkB.rows[0]?.c).toBe("1");
expect(Number((checkB[0] as { c: number }).c)).toBe(1);
});
it("replays identical idempotent requests", async () => {
@@ -147,8 +155,10 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
});
expect(_second.statusCode).toBe(200);
expect(_second.body).toBe(_first.body);
const _occ = await _pool.query(`SELECT COUNT(*)::int AS c FROM er_occurrence_events`);
expect(_occ.rows[0]?.c).toBe(3);
const [occ] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incident_occurrences`,
);
expect(Number((occ[0] as { c: number }).c)).toBe(3);
});
it("returns 409 when idempotency key is reused with a different body", async () => {
+6 -5
View File
@@ -1,12 +1,13 @@
import pg from "pg";
import mysql from "mysql2/promise";
import { loadEnv } from "./config/env.js";
import { buildApp } from "./buildApp.js";
const _env = loadEnv();
const _pool = new pg.Pool({
connectionString: _env.DATABASE_URL,
max: 16,
idleTimeoutMillis: 30_000,
const _pool = mysql.createPool({
uri: _env.DATABASE_URL,
connectionLimit: 16,
waitForConnections: true,
enableKeepAlive: true,
});
const _app = await buildApp({ env: _env, pool: _pool });
+8 -10
View File
@@ -1,4 +1,5 @@
import type { Pool } from "pg";
import type { Pool } from "mysql2/promise";
import type { RowDataPacket } from "mysql2";
import type { FastifyReply, FastifyRequest } from "fastify";
import { sha256Hex } from "../lib/hash.js";
@@ -35,26 +36,23 @@ export async function attachIngestAuth(
return;
}
const _hash = sha256Hex(_token);
const _result = await pool.query<{
id: string;
project_id: string;
}>(
`SELECT id::text, project_id::text
const [rows] = await pool.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS id, CAST(project_id AS CHAR) AS project_id
FROM er_ingest_keys
WHERE token_hash = $1
WHERE token_hash = ?
AND status = 'active'
AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > NOW())`,
AND (expires_at IS NULL OR expires_at > NOW(6))`,
[_hash],
);
if (_result.rowCount === 0) {
if (rows.length === 0) {
await reply.status(401).send({
error: "unauthorized",
message: "Invalid or inactive ingest key.",
});
return;
}
const _row = _result.rows[0];
const _row = rows[0] as { id: string; project_id: string };
if (!_row) {
await reply.status(401).send({
error: "unauthorized",
+65 -45
View File
@@ -1,4 +1,5 @@
import type { Pool, PoolClient } from "pg";
import type { Pool, PoolConnection } from "mysql2/promise";
import type { ResultSetHeader, RowDataPacket } from "mysql2";
import { stableJsonHash } from "../lib/hash.js";
import {
computeFingerprint,
@@ -23,6 +24,23 @@ export type IngestResultItem = {
fingerprint: string;
};
function _parseStoredJson(raw: unknown): unknown {
if (raw === null || raw === undefined) {
return raw;
}
if (typeof raw === "object") {
return raw;
}
if (typeof raw === "string") {
try {
return JSON.parse(raw) as unknown;
} catch {
return raw;
}
}
return raw;
}
export async function processIngestBatch(input: {
pool: Pool;
ingestKeyId: string;
@@ -31,25 +49,25 @@ export async function processIngestBatch(input: {
idempotencyKey: string | null;
bodyHash: string;
}): Promise<{ status: 200 | 409; body: unknown }> {
const _client = await input.pool.connect();
const _client = await input.pool.getConnection();
try {
await _client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
await _client.query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED");
await _client.beginTransaction();
if (input.idempotencyKey !== null) {
const _existing = await _client.query<{
body_hash: string;
response_json: unknown;
http_status: number;
}>(
const [rows] = await _client.execute<RowDataPacket[]>(
`SELECT body_hash, response_json, http_status
FROM er_ingest_idempotency
WHERE ingest_key_id = $1::bigint
AND idempotency_key = $2`,
WHERE ingest_key_id = ?
AND idempotency_key = ?
LIMIT 1`,
[input.ingestKeyId, input.idempotencyKey],
);
const _row0 = _existing.rows[0];
const _row0 = rows[0] as
| { body_hash: string; response_json: unknown; http_status: number }
| undefined;
if (_row0) {
if (_row0.body_hash !== input.bodyHash) {
await _client.query("ROLLBACK");
await _client.rollback();
return {
status: 409,
body: {
@@ -59,8 +77,8 @@ export async function processIngestBatch(input: {
},
};
}
await _client.query("COMMIT");
return { status: 200, body: _row0.response_json };
await _client.commit();
return { status: 200, body: _parseStoredJson(_row0.response_json) };
}
}
@@ -79,12 +97,13 @@ export async function processIngestBatch(input: {
if (input.idempotencyKey !== null) {
const _firstIncidentId = _results[0]?.incident_id;
if (typeof _firstIncidentId === "string") {
await _client.query(
await _client.execute(
`INSERT INTO er_ingest_idempotency (
ingest_key_id, idempotency_key, body_hash, incident_id, http_status, response_json
) VALUES ($1::bigint, $2, $3, $4::bigint, 200, $5::jsonb)`,
ingest_key_id, project_id, idempotency_key, body_hash, incident_id, http_status, response_json
) VALUES (?, ?, ?, ?, ?, 200, ?)`,
[
input.ingestKeyId,
input.projectId,
input.idempotencyKey,
input.bodyHash,
_firstIncidentId,
@@ -94,15 +113,14 @@ export async function processIngestBatch(input: {
}
}
await _client.query(
`UPDATE er_ingest_keys SET last_used_at = NOW() WHERE id = $1::bigint`,
[input.ingestKeyId],
);
await _client.execute(`UPDATE er_ingest_keys SET last_used_at = NOW(6) WHERE id = ?`, [
input.ingestKeyId,
]);
await _client.query("COMMIT");
await _client.commit();
return { status: 200, body: _responseBody };
} catch (_err) {
await _client.query("ROLLBACK");
await _client.rollback();
throw _err;
} finally {
_client.release();
@@ -110,7 +128,7 @@ export async function processIngestBatch(input: {
}
async function _ingestOneEvent(
client: PoolClient,
client: PoolConnection,
input: { ingestKeyId: string; projectId: string; event: IngestEventInput },
): Promise<IngestResultItem> {
const _ev = input.event;
@@ -131,34 +149,33 @@ async function _ingestOneEvent(
const _stack = typeof _ev.stacktrace === "string" ? _ev.stacktrace : null;
const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null;
const _incident = await client.query<{ id: string }>(
await client.execute(
`INSERT INTO er_incidents (
project_id, fingerprint, title, severity, first_seen_at, last_seen_at,
occurrences_count, last_ingest_key_id
) VALUES (
$1::bigint, $2, $3, $4, $5::timestamp, $5::timestamp, 1, $6::bigint
)
ON CONFLICT (project_id, fingerprint) DO UPDATE SET
last_seen_at = EXCLUDED.last_seen_at,
) VALUES (?, ?, ?, ?, ?, ?, 1, ?)
ON DUPLICATE KEY UPDATE
last_seen_at = VALUES(last_seen_at),
occurrences_count = er_incidents.occurrences_count + 1,
last_ingest_key_id = EXCLUDED.last_ingest_key_id,
updated_at = CURRENT_TIMESTAMP
RETURNING id::text`,
[input.projectId, _fingerprint, _title, _severity, _occurred, input.ingestKeyId],
last_ingest_key_id = VALUES(last_ingest_key_id),
updated_at = CURRENT_TIMESTAMP(6)`,
[input.projectId, _fingerprint, _title, _severity, _occurred, _occurred, input.ingestKeyId],
);
const _incidentRow = _incident.rows[0];
const [incRows] = await client.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS id FROM er_incidents WHERE project_id = ? AND fingerprint = ? LIMIT 1`,
[input.projectId, _fingerprint],
);
const _incidentRow = incRows[0] as { id: string } | undefined;
if (!_incidentRow) {
throw new Error("incident_upsert_failed");
}
const _occ = await client.query<{ id: string }>(
`INSERT INTO er_occurrence_events (
const [occHeader] = await client.execute<ResultSetHeader>(
`INSERT INTO er_incident_occurrences (
project_id, incident_id, ingest_key_id, occurred_at, level_raw, severity,
message, stacktrace, context_json, schema_version
) VALUES (
$1::bigint, $2::bigint, $3::bigint, $4::timestamptz, $5, $6, $7, $8, $9::jsonb, $10
)
RETURNING id::text`,
message, stack_trace, context_json, schema_version, environment
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'production')`,
[
input.projectId,
_incidentRow.id,
@@ -172,14 +189,17 @@ async function _ingestOneEvent(
_ev.schema_version,
],
);
const _occRow = _occ.rows[0];
if (!_occRow) {
const _occId = occHeader.insertId;
if (typeof _occId !== "bigint" && typeof _occId !== "number") {
throw new Error("occurrence_insert_failed");
}
if (Number(_occId) <= 0) {
throw new Error("occurrence_insert_failed");
}
return {
incident_id: _incidentRow.id,
occurrence_id: _occRow.id,
occurrence_id: String(_occId),
fingerprint: _fingerprint,
};
}
+23 -14
View File
@@ -1,23 +1,32 @@
#!/bin/sh
set -eu
#!/usr/bin/env bash
# Apply error_reporting + admin SQL migrations and error_reporting seeds (Compose one-shot).
set -euo pipefail
: "${PGHOST:=postgres}"
: "${PGUSER:=postgres}"
: "${PGDATABASE:=error_reporting}"
: "${MARIADB_HOST:=mariadb}"
: "${MARIADB_USER:?MARIADB_USER required}"
: "${MARIADB_PASSWORD:?MARIADB_PASSWORD required}"
: "${MARIADB_DATABASE:?MARIADB_DATABASE required}"
until pg_isready -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE"; do
echo "docker-migrate: waiting for ${MARIADB_HOST}..."
until mariadb-admin ping -h "${MARIADB_HOST}" -u "${MARIADB_USER}" -p"${MARIADB_PASSWORD}" --silent; do
sleep 1
done
_run_sql() {
psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -v ON_ERROR_STOP=1 -f "$1"
_run_sql_file() {
_path="$1"
echo "docker-migrate: applying ${_path}"
mariadb -h "${MARIADB_HOST}" -u "${MARIADB_USER}" -p"${MARIADB_PASSWORD}" "${MARIADB_DATABASE}" < "${_path}"
}
_run_sql "/migrations/20260322043000_create_error_reporting_core.up.sql"
_run_sql "/migrations/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql "/migrations/20260322044500_add_ingest_idempotency.up.sql"
_run_sql "/migrations/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql "/seed/dev_two_projects.sql"
_run_sql "/seed/dev_collector_http_fixture.sql"
_run_sql_file "/migrations/error_reporting/20260322043000_create_error_reporting_core.up.sql"
_run_sql_file "/migrations/error_reporting/20260322044000_create_error_occurrences_and_states.up.sql"
_run_sql_file "/migrations/error_reporting/20260322044500_add_ingest_idempotency.up.sql"
_run_sql_file "/migrations/error_reporting/20260322045000_create_collectors_retention_and_audit.up.sql"
_run_sql_file "/migrations/admin/001_admin_users.sql"
_run_sql_file "/migrations/admin/002_admin_refresh_tokens.sql"
_run_sql_file "/migrations/admin/003_audit_logs.sql"
_run_sql_file "/migrations/admin/004_seed_superadmin.sql"
_run_sql_file "/seed/error_reporting/dev_two_projects.sql"
_run_sql_file "/seed/error_reporting/dev_collector_http_fixture.sql"
echo "docker-migrate: complete"
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# Run SQL migrations from repo root (same files as docker-migrate.sh). Requires mariadb client.
# Usage from errors.bitreport.pt root:
# ER_MYSQL_HOST=127.0.0.1 ER_MYSQL_USER=... ER_MYSQL_PASSWORD=... ER_MYSQL_DATABASE=... ./scripts/run-mysql-migrations.sh
# Or set DATABASE_URL=mysql://user:pass@host:port/db
set -euo pipefail
_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "${_ROOT}"
if [[ -n "${DATABASE_URL:-}" ]] && [[ "${DATABASE_URL}" == mysql://* || "${DATABASE_URL}" == mariadb://* ]]; then
_PARSED="$(python3 -c "
import os
from urllib.parse import urlparse, unquote
u = urlparse(os.environ['DATABASE_URL'])
if u.scheme not in ('mysql', 'mariadb', 'mysqli'):
raise SystemExit('DATABASE_URL must be mysql:// or mariadb://')
host = u.hostname or '127.0.0.1'
port = u.port or 3306
user = unquote(u.username or '')
password = unquote(u.password or '')
db = (u.path or '/').lstrip('/').split('?')[0]
print(host, port, user, password, db)
")"
read -r ER_MYSQL_HOST ER_MYSQL_PORT ER_MYSQL_USER ER_MYSQL_PASSWORD ER_MYSQL_DATABASE <<< "${_PARSED}"
fi
: "${ER_MYSQL_HOST:?ER_MYSQL_HOST or mysql DATABASE_URL required}"
: "${ER_MYSQL_USER:?ER_MYSQL_USER required}"
: "${ER_MYSQL_PASSWORD:?ER_MYSQL_PASSWORD required}"
: "${ER_MYSQL_DATABASE:?ER_MYSQL_DATABASE required}"
: "${ER_MYSQL_PORT:=3306}"
_run() {
echo "run-mysql-migrations: $1"
mariadb -h "${ER_MYSQL_HOST}" -P "${ER_MYSQL_PORT}" -u "${ER_MYSQL_USER}" -p"${ER_MYSQL_PASSWORD}" "${ER_MYSQL_DATABASE}" < "$1"
}
_run "${_ROOT}/database/error_reporting/migrations/20260322043000_create_error_reporting_core.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260322044000_create_error_occurrences_and_states.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260322044500_add_ingest_idempotency.up.sql"
_run "${_ROOT}/database/error_reporting/migrations/20260322045000_create_collectors_retention_and_audit.up.sql"
_run "${_ROOT}/db/migrations/001_admin_users.sql"
_run "${_ROOT}/db/migrations/002_admin_refresh_tokens.sql"
_run "${_ROOT}/db/migrations/003_audit_logs.sql"
_run "${_ROOT}/db/migrations/004_seed_superadmin.sql"
_run "${_ROOT}/database/error_reporting/seed/dev_two_projects.sql"
_run "${_ROOT}/database/error_reporting/seed/dev_collector_http_fixture.sql"
echo "run-mysql-migrations: complete"