Merge branch 'feat/client-gitea-repo-context' (BIT-1599 php-error bridge + recent-errors gitea_repo)

This commit is contained in:
David Santos committed 2026-04-08 00:49:04 +00:00
commit 6e5d3ca2fc
3 files changed
+267 -1

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({