feat(api): CRM parity mutations and recent-errors filters (BIT-726)

Add POST /api/error-monitoring/resolve, bulk-resolve, and purge-resolved with
resolve key or admin JWT (errors:triage / errors:delete). Extend GET
recent-errors with status, severity, project_slug, q, offset, and stable
ordering. Document contracts in api/docs/ERROR_MONITORING_PUBLIC_API.md;
add vitest for public auth helpers. Proxy new routes and widen admin-ui
middleware for /api/error-monitoring/*.

Paperclip-Issue: BIT-726
Paperclip-Run: 3fbf92be-736e-4b11-8e90-cf993d8cd5ca
Paperclip-Agent: Pedro Alves (id d706f4e6-5d05-4cec-b6e8-f8fb1f203aae)
Made-with: Cursor
This commit is contained in:
David Santos committed 2026-04-02 10:50:06 +00:00
1 parent e0af92eda1
commit 8b0044be82
10 files changed
+919 -49

No files matched your search

@@ -0,0 +1,350 @@
/**
* CRM-shaped operational mutations for the hub (same paths as CRM module).
* POST /api/error-monitoring/resolve
* POST /api/error-monitoring/bulk-resolve
* POST /api/error-monitoring/purge-resolved
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
import {
authorizeMutation,
changedByRef,
type MutationAuth,
} from '../../lib/errorMonitoringAuth.js';
function parseJsonBody(raw: unknown): Record<string, unknown> {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
return {};
}
return raw as Record<string, unknown>;
}
async function lookupIncidentForUniqueId(
db: FastifyInstance['db'],
uniqueId: string,
): Promise<{ incidentId: string; projectId: string; currentState: string } | null> {
const [oRows] = await db.execute<RowDataPacket[]>(
`SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(i.project_id AS CHAR) AS project_id,
i.current_state AS current_state
FROM er_incident_occurrences o
INNER JOIN er_incidents i ON i.id = o.incident_id
WHERE o.id = ?
LIMIT 1`,
[uniqueId],
);
const o = oRows[0] as Record<string, unknown> | undefined;
if (o) {
return {
incidentId: String(o.incident_id),
projectId: String(o.project_id),
currentState: String(o.current_state),
};
}
const [iRows] = await db.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS incident_id,
CAST(project_id AS CHAR) AS project_id,
current_state AS current_state
FROM er_incidents
WHERE id = ?
LIMIT 1`,
[uniqueId],
);
const ir = iRows[0] as Record<string, unknown> | undefined;
if (!ir) {
return null;
}
return {
incidentId: String(ir.incident_id),
projectId: String(ir.project_id),
currentState: String(ir.current_state),
};
}
async function markIncidentResolved(
db: FastifyInstance['db'],
row: { incidentId: string; projectId: string; currentState: string },
changeNote: string,
auth: MutationAuth,
): Promise<boolean> {
if (!['open', 'investigating'].includes(row.currentState)) {
return false;
}
const { type, ref } = changedByRef(auth);
const conn = await db.getConnection();
try {
await conn.beginTransaction();
const [upd] = await conn.execute<ResultSetHeader>(
`UPDATE er_incidents
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
WHERE id = ? AND current_state IN ('open','investigating')`,
[row.incidentId],
);
if (upd.affectedRows === 0) {
await conn.rollback();
return false;
}
await conn.execute(
`INSERT INTO er_incident_state_history
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
[row.incidentId, row.projectId, row.currentState, type, ref, changeNote || null],
);
await conn.commit();
return true;
} catch (e) {
await conn.rollback();
throw e;
} finally {
conn.release();
}
}
async function handleResolve(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
const body = parseJsonBody(request.body);
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
if (!auth) {
return;
}
const uniqueId = typeof body.unique_id === 'string' ? body.unique_id.trim() : '';
if (!uniqueId || !/^\d+$/.test(uniqueId)) {
return void reply.code(400).send({ success: false, message: 'Unique ID é obrigatório' });
}
let resolutionNotes =
typeof body.resolution_notes === 'string' ? body.resolution_notes.trim() : '';
if (resolutionNotes === '') {
resolutionNotes = 'Marked as resolved via API';
}
const assignedTo = typeof body.assigned_to === 'string' ? body.assigned_to.trim() : '';
const changeNote =
assignedTo !== '' ? `${resolutionNotes} (assigned_to: ${assignedTo})` : resolutionNotes;
const row = await lookupIncidentForUniqueId(db, uniqueId);
if (!row) {
return void reply.code(404).send({ success: false, message: 'Erro não encontrado' });
}
const ok = await markIncidentResolved(db, row, changeNote, auth);
if (!ok) {
return void reply.code(404).send({
success: false,
message: 'Incidente já resolvido ou estado inválido.',
});
}
return void reply.send({
success: true,
message: 'Erro marcado como resolvido',
data: { unique_id: uniqueId, resolution_notes: resolutionNotes },
});
}
async function handleBulkResolve(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
const body = parseJsonBody(request.body);
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
if (!auth) {
return;
}
let resolutionNotes =
typeof body.resolution_notes === 'string' ? body.resolution_notes.trim() : '';
if (resolutionNotes === '') {
resolutionNotes = 'Bulk resolved via API';
}
const assignedTo = typeof body.assigned_to === 'string' ? body.assigned_to.trim() : '';
const changeNoteBase =
assignedTo !== '' ? `${resolutionNotes} (assigned_to: ${assignedTo})` : resolutionNotes;
const { type, ref } = changedByRef(auth);
const rawIds = body.unique_ids;
if (Array.isArray(rawIds) && rawIds.length > 0) {
const uniqueIds = rawIds
.filter((x): x is string => typeof x === 'string')
.map((s) => s.trim())
.filter((s) => /^\d+$/.test(s));
const capped = uniqueIds.slice(0, 1000);
if (capped.length === 0) {
return void reply.code(400).send({
success: false,
message: 'unique_ids must be non-empty array of numeric strings',
});
}
const seen = new Set<string>();
const targets: { incidentId: string; projectId: string; currentState: string }[] = [];
for (const uid of capped) {
const row = await lookupIncidentForUniqueId(db, uid);
if (row && ['open', 'investigating'].includes(row.currentState) && !seen.has(row.incidentId)) {
seen.add(row.incidentId);
targets.push(row);
}
}
let resolved = 0;
const conn = await db.getConnection();
try {
await conn.beginTransaction();
for (const row of targets) {
const [upd] = await conn.execute<ResultSetHeader>(
`UPDATE er_incidents
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
WHERE id = ? AND current_state IN ('open','investigating')`,
[row.incidentId],
);
if (upd.affectedRows === 0) {
continue;
}
await conn.execute(
`INSERT INTO er_incident_state_history
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
[row.incidentId, row.projectId, row.currentState, type, ref, changeNoteBase || null],
);
resolved += upd.affectedRows;
}
await conn.commit();
} catch (e) {
await conn.rollback();
throw e;
} finally {
conn.release();
}
return void reply.send({
success: true,
message: 'Bulk resolve by unique_ids completed',
data: { resolved, by: 'unique_ids' as const },
});
}
const patternInput = body.message_pattern;
if (patternInput === null || patternInput === '') {
return void reply.code(400).send({
success: false,
message: 'message_pattern or unique_ids is required',
});
}
const patternsIn = Array.isArray(patternInput) ? patternInput : [patternInput];
const likePatterns: string[] = [];
for (const p of patternsIn) {
const s = typeof p === 'string' ? p.trim() : '';
if (s !== '') {
likePatterns.push(`%${s}%`);
}
}
const patterns = likePatterns.slice(0, 20);
if (patterns.length === 0) {
return void reply.code(400).send({
success: false,
message: 'message_pattern must be non-empty string or array of strings',
});
}
const conds = patterns.map(() => 'o.message LIKE ?').join(' OR ');
const sql = `
SELECT DISTINCT CAST(i.id AS CHAR) AS incident_id,
CAST(i.project_id AS CHAR) AS project_id,
i.current_state AS current_state
FROM er_incidents i
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
WHERE i.current_state IN ('open','investigating')
AND (${conds})
`;
const [matchRows] = await db.execute<RowDataPacket[]>(sql, patterns);
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
incidentId: String(r.incident_id),
projectId: String(r.project_id),
currentState: String(r.current_state),
}));
let resolved = 0;
const conn = await db.getConnection();
try {
await conn.beginTransaction();
for (const row of targets) {
const [upd] = await conn.execute<ResultSetHeader>(
`UPDATE er_incidents
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
WHERE id = ? AND current_state IN ('open','investigating')`,
[row.incidentId],
);
if (upd.affectedRows === 0) {
continue;
}
await conn.execute(
`INSERT INTO er_incident_state_history
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
[row.incidentId, row.projectId, row.currentState, type, ref, changeNoteBase || null],
);
resolved += upd.affectedRows;
}
await conn.commit();
} catch (e) {
await conn.rollback();
throw e;
} finally {
conn.release();
}
return void reply.send({
success: true,
message: 'Bulk resolve by message pattern completed',
data: { resolved, by: 'message_pattern' as const, patterns: likePatterns },
});
}
async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
const body = parseJsonBody(request.body);
const auth = await authorizeMutation(request, reply, body, 'errors:delete');
if (!auth) {
return;
}
const dryRun = Boolean(body.dry_run);
const [countRows] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c FROM er_incidents WHERE current_state = 'resolved'`,
);
const count = Number((countRows[0] as { c?: number }).c ?? 0);
if (dryRun) {
return void reply.send({
success: true,
message: 'Dry run',
data: { dry_run: true, would_delete: count },
});
}
if (count === 0) {
return void reply.send({
success: true,
message: 'Nenhum incidente resolvido para apagar.',
data: { deleted: 0 },
});
}
const [del] = await db.execute<ResultSetHeader>(
`DELETE FROM er_incidents WHERE current_state = 'resolved'`,
);
return void reply.send({
success: true,
message: `Apagados ${del.affectedRows} incidentes resolvidos`,
data: { deleted: del.affectedRows },
});
}
export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise<void> {
app.post('/api/error-monitoring/resolve', handleResolve);
app.post('/api/error-monitoring/bulk-resolve', handleBulkResolve);
app.post('/api/error-monitoring/purge-resolved', handlePurgeResolved);
}
+106 -47
View File
@@ -1,8 +1,15 @@
/**
* Paperclip / CRM-compatible read-only listing for open incidents.
* Paths (same handler, Paperclip default query is the CRM-shaped one):
* GET /api/error-monitoring/recent-errors?limit=&api_key=|view_errors=
* GET /v1/paperclip/recent-errors?limit=&api_key=|view_errors=
* Paperclip / CRM-compatible listing for incidents (open by default; filters optional).
* Paths (same handler):
* GET /api/error-monitoring/recent-errors?limit=&offset=&api_key=|view_errors=
* GET /v1/paperclip/recent-errors?...
*
* Optional query filters (hub extension, backward compatible when omitted):
* status — comma-separated: open,investigating,resolved,ignored (default: open,investigating)
* severity — critical|high|medium|low|info
* project_slug — project slug (lowercase)
* q — search title, message, fingerprint (LIKE)
* order — occurred_at_desc (default) | occurred_at_asc
*
* Auth: query param must match ERROR_RESOLVE_API_KEY or ERROR_REPORTING_API_KEY (api_key),
* or DEBUG_VIEW_ERRORS_KEY (view_errors). At least one server secret must be configured.
@@ -10,42 +17,10 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { safeEqual } from '../../plugins/auth.js';
import { authorizeReadQuery } from '../../lib/errorMonitoringAuth.js';
function resolveApiSecrets(): { apiKey: string; viewKey: string } {
const apiKey =
(process.env.ERROR_RESOLVE_API_KEY ?? process.env.ERROR_REPORTING_API_KEY ?? '').trim();
const viewKey = (process.env.DEBUG_VIEW_ERRORS_KEY ?? '').trim();
return { apiKey, viewKey };
}
function authorizeQuery(request: FastifyRequest, reply: FastifyReply): boolean {
const { apiKey, viewKey } = resolveApiSecrets();
if (!apiKey && !viewKey) {
reply.code(503).send({
success: false,
message: 'Recent-errors API is not configured (set ERROR_RESOLVE_API_KEY and/or DEBUG_VIEW_ERRORS_KEY).',
});
return false;
}
const q = request.query as { api_key?: string; view_errors?: string };
const providedApi = typeof q.api_key === 'string' ? q.api_key : '';
const providedView = typeof q.view_errors === 'string' ? q.view_errors : '';
if (apiKey && providedApi && safeEqual(providedApi, apiKey)) {
return true;
}
if (viewKey && providedView && safeEqual(providedView, viewKey)) {
return true;
}
reply.code(401).send({
success: false,
message: 'Unauthorized',
});
return false;
}
const INCIDENT_STATES = ['open', 'investigating', 'resolved', 'ignored'] as const;
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
function parseJsonObject(raw: string | null): Record<string, unknown> | null {
if (raw == null || raw === '') {
@@ -71,14 +46,40 @@ function extractFileLine(ctx: Record<string, unknown> | null): { file_path: stri
return { file_path, line_number };
}
function parseStatusList(raw: string | undefined): string[] | null {
if (raw == null || raw.trim() === '') {
return ['open', 'investigating'];
}
const parts = raw
.split(',')
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
const allowed = new Set(INCIDENT_STATES as readonly string[]);
for (const p of parts) {
if (!allowed.has(p)) {
return null;
}
}
return parts.length > 0 ? parts : ['open', 'investigating'];
}
async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
if (!authorizeQuery(request, reply)) {
if (!authorizeReadQuery(request, reply)) {
return;
}
const q = request.query as { limit?: string };
const q = request.query as {
limit?: string;
offset?: string;
status?: string;
severity?: string;
project_slug?: string;
q?: string;
order?: string;
};
let limit = 999999;
if (q.limit != null && q.limit !== '') {
const n = parseInt(String(q.limit), 10);
@@ -88,6 +89,59 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
limit = Math.min(n, 999999);
}
let offset = 0;
if (q.offset != null && q.offset !== '') {
const o = parseInt(String(q.offset), 10);
if (!Number.isFinite(o) || o < 0) {
return void reply.code(400).send({ success: false, message: 'Invalid offset' });
}
offset = Math.min(o, 10_000_000);
}
const states = parseStatusList(q.status);
if (!states) {
return void reply.code(400).send({
success: false,
message: `Invalid status (use comma-separated: ${INCIDENT_STATES.join(',')})`,
});
}
if (q.severity != null && q.severity !== '') {
const sev = q.severity.trim().toLowerCase();
if (!(SEVERITIES as readonly string[]).includes(sev)) {
return void reply.code(400).send({
success: false,
message: `Invalid severity (allowed: ${SEVERITIES.join(',')})`,
});
}
}
const orderRaw = (q.order ?? 'occurred_at_desc').trim().toLowerCase();
const orderSql =
orderRaw === 'occurred_at_asc' ? 'r.occurred_at ASC, r.id ASC' : 'r.occurred_at DESC, r.id DESC';
const statePlaceholders = states.map(() => '?').join(', ');
const conditions: string[] = [`i.current_state IN (${statePlaceholders})`];
const params: Array<string | number> = [...states];
if (q.severity != null && q.severity !== '') {
conditions.push('i.severity = ?');
params.push(q.severity.trim().toLowerCase());
}
if (q.project_slug != null && q.project_slug.trim() !== '') {
conditions.push('p.slug = ?');
params.push(q.project_slug.trim().toLowerCase());
}
if (q.q != null && q.q.trim() !== '') {
const term = `%${q.q.trim()}%`;
conditions.push('(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)');
params.push(term, term, term);
}
const whereClause = conditions.join(' AND ');
const sql = `
WITH ranked AS (
SELECT o.id,
@@ -97,15 +151,17 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
o.context_json AS context_json,
o.environment,
o.occurred_at AS occurred_at,
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC) AS rn
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC, o.id DESC) AS rn
FROM er_incident_occurrences o
INNER JOIN er_incidents i ON i.id = o.incident_id
WHERE i.current_state IN ('open', 'investigating')
INNER JOIN er_projects p ON p.id = i.project_id
WHERE ${whereClause}
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
p.slug AS project_slug,
i.severity AS incident_severity,
i.current_state AS incident_state,
r.message,
r.stack_trace,
r.context_json,
@@ -115,20 +171,23 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
INNER JOIN er_incidents i ON i.id = r.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
ORDER BY r.occurred_at DESC
LIMIT ?
ORDER BY ${orderSql}
LIMIT ? OFFSET ?
`;
const [rows] = await db.execute<RowDataPacket[]>(sql, [limit]);
params.push(limit, offset);
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
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 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();
return {
status: 'open',
status: st === 'resolved' ? 'resolved' : st === 'ignored' ? 'ignored' : 'open',
message: String(row.message ?? ''),
error_message: String(row.message ?? ''),
stack_trace: row.stack_trace != null ? String(row.stack_trace) : '',