feat(hub): php-error bridge + gitea_repo on recent-errors (BIT-1541, BIT-1291) #4

Merged
spark merged 1 commits from feat/php-error-bridge-and-gitea-repo into master 2026-04-08 19:34:17 +01:00
9 changed files with 452 additions and 5 deletions
Showing only changes of commit 0e4d359c09 - Show all commits

No files matched your search

@@ -0,0 +1,165 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/**
* CRM-shaped PHP error ingest bridge.
*
* Receives the legacy `X-Error-Monitoring-Key` + flat JSON payload sent by
* ErrorMonitoringReporter (CasamentoWeb, CRM, etc.) and translates it to the
* ingest-api `/v1/ingest/events` schema, ensuring `gitea_repo` and
* `project_slug` are promoted into the event `context` so they are persisted
* in `context_json` and returned by `GET /api/error-monitoring/recent-errors`.
*
* Auth: the `X-Error-Monitoring-Key` value is forwarded as `Authorization:
* Bearer` to the ingest-api — the key must exist in `er_ingest_keys`.
*/
interface CrmPhpPayload {
message?: unknown;
severity?: unknown;
level?: unknown;
stack_trace?: unknown;
stacktrace?: unknown;
file_path?: unknown;
line_number?: unknown;
error_type?: unknown;
environment?: unknown;
url?: unknown;
http_method?: unknown;
ip_address?: unknown;
user_agent?: unknown;
context_data?: unknown;
// routing metadata (hub-mirrored fields)
project_slug?: unknown;
project_name?: unknown;
gitea_repo?: unknown;
}
function safeStr(v: unknown): string {
return typeof v === "string" ? v : "";
}
export async function POST(request: NextRequest) {
const ingestApiUrl = (process.env.INGEST_API_URL ?? "http://127.0.0.1:3041").replace(/\/$/, "");
// Extract auth key — forwarded as Bearer to ingest-api.
const monitoringKey =
request.headers.get("x-error-monitoring-key")?.trim() ??
request.headers.get("x-api-key")?.trim() ??
"";
if (!monitoringKey) {
return NextResponse.json(
{ success: false, message: "Missing X-Error-Monitoring-Key header." },
{ status: 401 },
);
}
let body: CrmPhpPayload;
try {
body = (await request.json()) as CrmPhpPayload;
} catch {
return NextResponse.json(
{ success: false, message: "Invalid JSON body." },
{ status: 400 },
);
}
const message = safeStr(body.message);
if (!message) {
return NextResponse.json(
{ success: false, message: "Missing required field: message." },
{ status: 400 },
);
}
// Normalise severity → ingest level.
const level = safeStr(body.severity || body.level) || "error";
// Stack trace (CRM uses snake_case `stack_trace`).
const stackTrace = safeStr(body.stack_trace || body.stacktrace);
// Build context: start with context_data, then promote top-level routing
// fields so they land in context_json and are readable by recent-errors.
const contextData: Record<string, unknown> =
body.context_data !== null &&
typeof body.context_data === "object" &&
!Array.isArray(body.context_data)
? { ...(body.context_data as Record<string, unknown>) }
: {};
// Routing metadata — always overwrite so reporter values win.
const gitea_repo = safeStr(body.gitea_repo);
const project_slug = safeStr(body.project_slug);
const project_name = safeStr(body.project_name);
if (gitea_repo) contextData.gitea_repo = gitea_repo;
if (project_slug) contextData.project_slug = project_slug;
if (project_name) contextData.project_name = project_name;
// Preserve other top-level diagnostic fields.
const file_path = safeStr(body.file_path);
const line_number = safeStr(body.line_number);
const error_type = safeStr(body.error_type);
if (file_path) contextData.file_path = file_path;
if (line_number) contextData.line_number = line_number;
if (error_type) contextData.error_type = error_type;
const httpUrl = safeStr(body.url);
if (httpUrl) contextData.url = httpUrl;
const httpMethod = safeStr(body.http_method);
if (httpMethod) contextData.http_method = httpMethod;
const ipAddress = safeStr(body.ip_address);
if (ipAddress) contextData.ip_address = ipAddress;
const userAgent = safeStr(body.user_agent);
if (userAgent) contextData.user_agent = userAgent;
const event = {
schema_version: 1,
occurred_at: new Date().toISOString(),
level,
message,
...(stackTrace ? { stack_trace: stackTrace } : {}),
...(Object.keys(contextData).length > 0 ? { context: contextData } : {}),
};
const ingestTarget = `${ingestApiUrl}/v1/ingest/events`;
const ingestBody = JSON.stringify({ events: [event] });
let upstream: Response;
try {
upstream = await fetch(ingestTarget, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${monitoringKey}`,
},
body: ingestBody,
cache: "no-store",
});
} catch (err) {
const msg = err instanceof Error ? err.message : "ingest_unreachable";
return NextResponse.json(
{ success: false, message: `Ingest API unreachable: ${msg}` },
{ status: 502 },
);
}
if (upstream.status === 401) {
return NextResponse.json(
{ success: false, message: "Ingest key not recognised." },
{ status: 401 },
);
}
if (!upstream.ok) {
const errText = await upstream.text().catch(() => "");
return NextResponse.json(
{ success: false, message: `Ingest failed (${upstream.status}): ${errText}` },
{ status: upstream.status >= 500 ? 502 : upstream.status },
);
}
return NextResponse.json({ success: true, message: "ok" });
}
@@ -0,0 +1,87 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import recentErrorsPublicRoutes from './recentErrors.js';
describe('GET /api/error-monitoring/recent-errors', () => {
const prevResolve = process.env.ERROR_RESOLVE_API_KEY;
beforeEach(() => {
process.env.ERROR_RESOLVE_API_KEY = 'test-recent-errors-key';
});
afterEach(() => {
if (prevResolve === undefined) {
delete process.env.ERROR_RESOLVE_API_KEY;
} else {
process.env.ERROR_RESOLVE_API_KEY = prevResolve;
}
});
async function buildApp(execute: ReturnType<typeof vi.fn>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
app.decorate('db', { execute } as unknown as FastifyInstance['db']);
await app.register(recentErrorsPublicRoutes);
return app;
}
it('includes top-level gitea_repo when stored in context_json', async () => {
const execute = vi.fn().mockResolvedValue([
[
{
incident_id: '1',
occurrence_id: '99',
project_slug: 'wdmi-store',
incident_severity: 'high',
incident_state: 'open',
message: 'probe',
stack_trace: '',
context_json: JSON.stringify({
gitea_repo: 'BitReport.pt/WDMI_STORE',
file_path: '/src/x.ts',
line_number: 3,
}),
environment: 'production',
occurred_at: '2026-01-01T00:00:00.000Z',
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
const body = res.json() as { data: Array<{ gitea_repo?: string; file_path?: string }> };
expect(body.data).toHaveLength(1);
expect(body.data[0].gitea_repo).toBe('BitReport.pt/WDMI_STORE');
expect(body.data[0].file_path).toBe('/src/x.ts');
});
it('omits gitea_repo when not present in context', async () => {
const execute = vi.fn().mockResolvedValue([
[
{
incident_id: '1',
occurrence_id: '99',
project_slug: 'other',
incident_severity: 'medium',
incident_state: 'open',
message: 'x',
stack_trace: '',
context_json: JSON.stringify({ file_path: '/b.php' }),
environment: 'production',
occurred_at: '2026-01-01T00:00:00.000Z',
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/recent-errors?api_key=test-recent-errors-key',
});
expect(res.statusCode).toBe(200);
const body = res.json() as { data: Array<{ gitea_repo?: string }> };
expect(body.data[0].gitea_repo).toBeUndefined();
});
});
+15 -1
View File
@@ -65,6 +65,15 @@ function extractFileLine(ctx: Record<string, unknown> | null): { file_path: stri
return { file_path, line_number };
}
/** Paperclip error loop reads top-level `gitea_repo` on each recent-error row. */
function extractGiteaRepo(ctx: Record<string, unknown> | null): string {
if (!ctx) {
return '';
}
const raw = ctx.gitea_repo ?? ctx.giteaRepo ?? ctx.repo_full_name ?? ctx.repository;
return typeof raw === 'string' ? raw.trim() : '';
}
function parseStatusList(raw: string | undefined): string[] | null {
if (raw == null || raw.trim() === '') {
return ['open', 'investigating'];
@@ -201,6 +210,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
const data = (rows as Record<string, unknown>[]).map((row) => {
const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null);
const { file_path, line_number } = extractFileLine(ctx);
const gitea_repo = extractGiteaRepo(ctx);
const incSev = String(row.incident_severity ?? 'medium').toLowerCase();
const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium';
const st = String(row.incident_state ?? 'open').toLowerCase();
@@ -212,7 +222,7 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
const stack_trace =
rawStack !== '' ? rawStack : synthesizeStackTraceForDisplay(message, ctx);
return {
const rowOut: Record<string, unknown> = {
status: st === 'resolved' ? 'resolved' : st === 'ignored' ? 'ignored' : 'open',
message,
error_message: message,
@@ -225,6 +235,10 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
environment: String(row.environment ?? 'production'),
occurred_at: toIsoOccurredAt(row.occurred_at),
};
if (gitea_repo !== '') {
rowOut.gitea_repo = gitea_repo;
}
return rowOut;
});
return void reply.send({
+14 -1
View File
@@ -7,6 +7,9 @@
let _token = '';
let _endpoint = 'https://errors.bitreport.pt';
let _disabled = false;
let _projectName = process.env.ERROR_REPORTING_PROJECT_NAME || '';
let _projectSlug = process.env.ERROR_REPORTING_PROJECT_SLUG || '';
let _giteaRepo = process.env.ERROR_REPORTING_GITEA_REPO || '';
const _queue = [];
let _flushTimer = null;
const BATCH_SIZE = 25;
@@ -18,6 +21,9 @@ function initReporter(opts) {
_token = opts.token || process.env.ERROR_REPORTING_TOKEN || '';
_endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, '');
_disabled = opts.disabled != null ? opts.disabled : process.env.ERROR_REPORTING_DISABLED === '1';
_projectName = opts.projectName || process.env.ERROR_REPORTING_PROJECT_NAME || _projectName;
_projectSlug = opts.projectSlug || process.env.ERROR_REPORTING_PROJECT_SLUG || _projectSlug;
_giteaRepo = opts.giteaRepo || process.env.ERROR_REPORTING_GITEA_REPO || _giteaRepo;
if (!_disabled && _token) {
process.on('uncaughtException', function (err) {
@@ -51,6 +57,9 @@ function reportError(err, context) {
line_number: lineNumber || undefined,
error_type: (err && err.constructor && err.constructor.name) || 'Error',
error_code: (err && err.code) || undefined,
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
}, context),
});
}
@@ -62,7 +71,11 @@ function reportMessage(message, level, context) {
occurred_at: new Date().toISOString(),
level: level || 'error',
message: message,
context: context || {},
context: Object.assign({
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
}, context || {}),
});
}
+19 -2
View File
@@ -12,11 +12,17 @@
* ERROR_REPORTING_TOKEN — ingest API key (Bearer token)
* ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
* ERROR_REPORTING_DISABLED — set to "1" to disable
* ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional)
* ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
* ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
*/
let _token = '';
let _endpoint = 'https://errors.bitreport.pt';
let _disabled = false;
let _projectName = process.env.ERROR_REPORTING_PROJECT_NAME || '';
let _projectSlug = process.env.ERROR_REPORTING_PROJECT_SLUG || '';
let _giteaRepo = process.env.ERROR_REPORTING_GITEA_REPO || '';
const _queue = [];
let _flushTimer = null;
const BATCH_SIZE = 25;
@@ -25,12 +31,15 @@ const TIMEOUT_MS = 8000;
/**
* Initialise the reporter. Call once at startup.
* @param {{ token?: string, endpoint?: string, disabled?: boolean }} opts
* @param {{ token?: string, endpoint?: string, disabled?: boolean, projectName?: string, projectSlug?: string, giteaRepo?: string }} opts
*/
export function initReporter(opts = {}) {
_token = opts.token || process.env.ERROR_REPORTING_TOKEN || '';
_endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, '');
_disabled = opts.disabled ?? process.env.ERROR_REPORTING_DISABLED === '1';
_projectName = opts.projectName || process.env.ERROR_REPORTING_PROJECT_NAME || _projectName;
_projectSlug = opts.projectSlug || process.env.ERROR_REPORTING_PROJECT_SLUG || _projectSlug;
_giteaRepo = opts.giteaRepo || process.env.ERROR_REPORTING_GITEA_REPO || _giteaRepo;
if (!_disabled && _token) {
process.on('uncaughtException', (err) => {
@@ -69,6 +78,9 @@ export function reportError(err, context = {}) {
line_number: lineNumber || undefined,
error_type: err?.constructor?.name || 'Error',
error_code: err?.code || undefined,
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
...context,
},
});
@@ -87,7 +99,12 @@ export function reportMessage(message, level = 'error', context = {}) {
occurred_at: new Date().toISOString(),
level,
message,
context,
context: {
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
...context,
},
});
}
+21
View File
@@ -14,6 +14,8 @@ declare(strict_types=1);
* ERROR_REPORTING_TOKEN — ingest API key (required)
* ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
* ERROR_REPORTING_DISABLED — set to "1" to disable
* ERROR_REPORTING_PROJECT_SLUG — stable product slug for ERRSIG / Paperclip routing (optional)
* ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea, e.g. BitReport.pt/my-product (optional)
*/
namespace BitReport;
@@ -44,6 +46,22 @@ final class ErrorReporter
return self::env('ERROR_REPORTING_TOKEN');
}
private static function projectName(): string
{
return self::env('ERROR_REPORTING_PROJECT_NAME');
}
private static function projectSlug(): string
{
return self::env('ERROR_REPORTING_PROJECT_SLUG');
}
private static function giteaRepo(): string
{
return self::env('ERROR_REPORTING_GITEA_REPO');
}
private static function env(string $key): string
{
$v = getenv($key);
@@ -130,6 +148,9 @@ final class ErrorReporter
'request_uri' => $_SERVER['REQUEST_URI'] ?? null,
'http_method' => $_SERVER['REQUEST_METHOD'] ?? null,
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
'project_name' => self::projectName() !== '' ? self::projectName() : null,
'project_slug' => self::projectSlug() !== '' ? self::projectSlug() : null,
'gitea_repo' => self::giteaRepo() !== '' ? self::giteaRepo() : null,
], $context);
// Remove null values
+4
View File
@@ -17,6 +17,9 @@ set +a
_ROOT="${ER_REPO_ROOT:?ER_REPO_ROOT must be set in ${_ENV_FILE}}"
cd "${_ROOT}"
# Avoid `fatal: detected dubious ownership` when root runs git on a tree owned by error-reporting.
git config --global --add safe.directory "${_ROOT}" 2>/dev/null || true
# Match your deploy branch (repository uses master today).
_DEPLOY_BRANCH="${ER_DEPLOY_BRANCH:-master}"
git fetch origin "${_DEPLOY_BRANCH}"
@@ -40,6 +43,7 @@ if [[ "${ER_WEBHOOK_RESTART_SERVICES:-1}" == "1" ]]; then
systemctl restart bitreport-error-reporting-ingest-api.service
systemctl restart bitreport-error-reporting-admin-ui.service
systemctl restart bitreport-error-reporting-collector-worker.service
systemctl restart bitreport-error-reporting-api.service
fi
echo "webhook-deploy: done"
+1 -1
View File
@@ -9,7 +9,7 @@
"build": "tsc",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test": "vitest run && python3 ../tools/ci/check_error_reporter_context_contract.py --path ../clients",
"test:watch": "vitest"
},
"dependencies": {
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""CI gate: shipped ingest clients must document project_slug + gitea_repo routing."""
from __future__ import annotations
import argparse
import fnmatch
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
SCAN_EXTENSIONS = {".php", ".js", ".mjs", ".cjs", ".ts", ".py"}
EXCLUDE_PATTERNS = (
".git/*",
"node_modules/*",
"vendor/*",
".venv/*",
"venv/*",
"__pycache__/*",
"dist/*",
"build/*",
)
REPORTER_MARKERS = (
"php-error",
"js-error",
"error-monitoring",
"reporterror(",
"reportmessage(",
"sendtoingestapi",
"/v1/ingest/events",
)
SLUG_MARKERS = (
"project_slug",
"projectslug",
"error_monitoring_project_slug",
"error_reporting_project_slug",
)
REPO_MARKERS = (
"gitea_repo",
"gitearepo",
"error_monitoring_gitea_repo",
"error_reporting_gitea_repo",
)
def _is_excluded(rel_path: str) -> bool:
norm = rel_path.replace("\\", "/")
if "/node_modules/" in norm or norm.startswith("node_modules/"):
return True
if "/vendor/" in norm or norm.startswith("vendor/"):
return True
return any(fnmatch.fnmatch(rel_path, pattern) for pattern in EXCLUDE_PATTERNS)
def _is_candidate_file(rel_path: str, text_lower: str) -> bool:
if _is_excluded(rel_path):
return False
if Path(rel_path).suffix.lower() not in SCAN_EXTENSIONS:
return False
name = Path(rel_path).name.lower()
has_reporter_naming = (
"reporter" in name
or "errorreporter" in text_lower
or "errormonitoringreporter" in text_lower
)
if not has_reporter_naming:
return False
return any(marker in text_lower for marker in REPORTER_MARKERS)
def _contract_ok(text_lower: str) -> tuple[bool, bool]:
has_slug = any(marker in text_lower for marker in SLUG_MARKERS)
has_repo = any(marker in text_lower for marker in REPO_MARKERS)
return has_slug, has_repo
def main() -> int:
parser = argparse.ArgumentParser(description="Verify error reporter context contract in repository files.")
parser.add_argument(
"--path",
default=str(REPO_ROOT),
help="Repository root to scan.",
)
args = parser.parse_args()
root = Path(args.path).resolve()
if not root.is_dir():
print(f"error: scan root does not exist: {root}")
return 2
failures: list[tuple[str, bool, bool]] = []
candidates = 0
for file_path in root.rglob("*"):
if not file_path.is_file():
continue
rel = file_path.relative_to(root).as_posix()
if _is_excluded(rel):
continue
try:
content = file_path.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
low = content.lower()
if not _is_candidate_file(rel, low):
continue
candidates += 1
has_slug, has_repo = _contract_ok(low)
if not (has_slug and has_repo):
failures.append((rel, has_slug, has_repo))
print(f"reporter_contract_candidates={candidates}")
if not failures:
print("reporter_context_contract=ok")
return 0
print("reporter_context_contract=failed")
for rel, has_slug, has_repo in failures:
print(f"- {rel}: has_project_slug={int(has_slug)} has_gitea_repo={int(has_repo)}")
return 1
if __name__ == "__main__":
raise SystemExit(main())