feat(api): resolve-by-pattern endpoint, purge threshold, contract tests (BIT-732)
Add POST /api/error-monitoring/resolve-by-pattern with advanced filters: severity, project_slug, fingerprint, message_pattern, time range. Enhance purge-resolved with optional older_than_days threshold so only stale resolved incidents are deleted. 27 contract tests (vitest) cover all four mutation endpoints: auth gating, validation, response shapes, and CRM-compatible behaviour. Paperclip-Agent: peter-spark Paperclip-Issue: BIT-732 Paperclip-Run: 749dfb41-182b-48c8-b6e7-74f14bdb9d41
This commit is contained in:
1 parent
de68f68103
commit
dee670ef9f
3 files changed
+775
-4
No files matched your search
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* Contract tests for CRM-parity mutation endpoints.
|
||||
* Validates request/response shapes, auth gating, and validation rules
|
||||
* without a live database — handler logic is exercised via Fastify inject.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import jwt from '@fastify/jwt';
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
|
||||
import errorMonitoringMutationsRoutes from './errorMonitoringMutations.js';
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock database pool */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function makePool(overrides: {
|
||||
execute?: (...args: unknown[]) => Promise<unknown[]>;
|
||||
getConnection?: () => Promise<unknown>;
|
||||
} = {}) {
|
||||
const mockConn = {
|
||||
beginTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
execute: vi.fn().mockResolvedValue([{ affectedRows: 1 } as ResultSetHeader]),
|
||||
commit: vi.fn().mockResolvedValue(undefined),
|
||||
rollback: vi.fn().mockResolvedValue(undefined),
|
||||
release: vi.fn(),
|
||||
};
|
||||
return {
|
||||
execute: overrides.execute ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
|
||||
getConnection: overrides.getConnection ?? vi.fn().mockResolvedValue(mockConn),
|
||||
_mockConn: mockConn,
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: false });
|
||||
|
||||
// Cookie + JWT plugins so request.cookies and request.jwtVerify exist
|
||||
await app.register(cookie, { secret: 'test-cookie-secret' });
|
||||
await app.register(jwt, {
|
||||
secret: 'test-jwt-secret',
|
||||
cookie: { cookieName: '__Host-access', signed: false },
|
||||
});
|
||||
|
||||
const p = pool ?? makePool();
|
||||
app.decorate('db', p as unknown as FastifyInstance['db']);
|
||||
app.decorate('auditLog', vi.fn().mockResolvedValue(undefined));
|
||||
app.decorate('rateLimits', {
|
||||
ingest: {}, login: {}, global: {},
|
||||
mutation: { max: 100, timeWindow: 60_000 },
|
||||
} as unknown as FastifyInstance['rateLimits']);
|
||||
|
||||
await app.register(errorMonitoringMutationsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
const API_KEY = 'test-mutation-secret-key';
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
return { 'x-error-resolve-key': API_KEY };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Tests */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('POST /api/error-monitoring/resolve', () => {
|
||||
let app: FastifyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', API_KEY);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns 401 without auth', async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve',
|
||||
payload: { unique_id: '123' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 400 when unique_id is missing', async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve',
|
||||
headers: authHeaders(),
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.message).toMatch(/unique.*id/i);
|
||||
});
|
||||
|
||||
it('returns 400 when unique_id is not numeric', async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_id: 'abc' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('returns 404 when incident not found', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
|
||||
});
|
||||
app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_id: '999' },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 200 with success envelope when incident resolved', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn()
|
||||
// First call: lookupIncidentForUniqueId (occurrence lookup)
|
||||
.mockResolvedValueOnce([[{ incident_id: '10', project_id: '1', current_state: 'open' }]])
|
||||
// No more pool.execute calls — markIncidentResolved uses conn
|
||||
});
|
||||
app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_id: '100', resolution_notes: 'Fixed in deploy' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data).toBeDefined();
|
||||
expect(body.data.unique_id).toBe('100');
|
||||
expect(body.data.resolution_notes).toBe('Fixed in deploy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/error-monitoring/bulk-resolve', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', API_KEY);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns 400 when neither unique_ids nor message_pattern is provided', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/bulk-resolve',
|
||||
headers: authHeaders(),
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 400 for empty unique_ids array', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/bulk-resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_ids: [] },
|
||||
});
|
||||
// Empty array falls through to message_pattern check, which also fails
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('returns 200 with by=unique_ids when resolving by ids', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn()
|
||||
// lookupIncidentForUniqueId for id "1" — occurrence lookup
|
||||
.mockResolvedValueOnce([[{ incident_id: '10', project_id: '1', current_state: 'open' }]])
|
||||
// lookupIncidentForUniqueId for id "2" — occurrence lookup
|
||||
.mockResolvedValueOnce([[{ incident_id: '20', project_id: '1', current_state: 'investigating' }]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/bulk-resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_ids: ['1', '2'] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.by).toBe('unique_ids');
|
||||
expect(typeof body.data.resolved).toBe('number');
|
||||
});
|
||||
|
||||
it('returns 200 with by=message_pattern when resolving by pattern', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn()
|
||||
.mockResolvedValueOnce([[
|
||||
{ incident_id: '10', project_id: '1', current_state: 'open' },
|
||||
]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/bulk-resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { message_pattern: 'timeout' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.by).toBe('message_pattern');
|
||||
});
|
||||
|
||||
it('unique_ids takes precedence over message_pattern (CRM behaviour)', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn()
|
||||
.mockResolvedValueOnce([[{ incident_id: '10', project_id: '1', current_state: 'open' }]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/bulk-resolve',
|
||||
headers: authHeaders(),
|
||||
payload: { unique_ids: ['1'], message_pattern: 'timeout' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data.by).toBe('unique_ids');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/error-monitoring/resolve-by-pattern', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', API_KEY);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns 401 without auth', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
payload: { severity: 'low' },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 400 when no filters are provided', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.message).toMatch(/at least one filter/i);
|
||||
});
|
||||
|
||||
it('accepts severity filter and returns success envelope', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[
|
||||
{ incident_id: '10', project_id: '1', current_state: 'open' },
|
||||
]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { severity: 'low' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(typeof body.data.resolved).toBe('number');
|
||||
expect(typeof body.data.matched).toBe('number');
|
||||
});
|
||||
|
||||
it('accepts fingerprint filter (string)', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { fingerprint: 'abc123def' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.resolved).toBe(0);
|
||||
expect(body.data.matched).toBe(0);
|
||||
});
|
||||
|
||||
it('accepts fingerprint filter (array)', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { fingerprint: ['fp1', 'fp2'] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts severity array filter', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { severity: ['critical', 'high'] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts project_slug filter', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { project_slug: 'wdmi' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts time range filters', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { from_date: '2026-01-01T00:00:00Z', to_date: '2026-03-31T23:59:59Z' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts message_pattern filter', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { message_pattern: 'connection refused' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('accepts combined filters', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[
|
||||
{ incident_id: '5', project_id: '2', current_state: 'investigating' },
|
||||
]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: {
|
||||
severity: 'critical',
|
||||
project_slug: 'wdmi',
|
||||
message_pattern: 'timeout',
|
||||
from_date: '2026-03-01T00:00:00Z',
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.matched).toBe(1);
|
||||
});
|
||||
|
||||
it('ignores invalid severity values', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/resolve-by-pattern',
|
||||
headers: authHeaders(),
|
||||
payload: { severity: 'bogus' },
|
||||
});
|
||||
// 'bogus' is not a valid severity, so it's ignored → no filters → 400
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/error-monitoring/purge-resolved', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', API_KEY);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns 401 without auth', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns dry_run count without deleting', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[{ c: 42 }]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
headers: authHeaders(),
|
||||
payload: { dry_run: true },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.dry_run).toBe(true);
|
||||
expect(body.data.would_delete).toBe(42);
|
||||
});
|
||||
|
||||
it('deletes all resolved when no older_than_days is set', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn()
|
||||
.mockResolvedValueOnce([[{ c: 5 }]]) // count query
|
||||
.mockResolvedValueOnce([{ affectedRows: 5 } as ResultSetHeader]), // delete
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
headers: authHeaders(),
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.deleted).toBe(5);
|
||||
});
|
||||
|
||||
it('accepts older_than_days and includes it in dry_run response', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[{ c: 10 }]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
headers: authHeaders(),
|
||||
payload: { dry_run: true, older_than_days: 30 },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data.dry_run).toBe(true);
|
||||
expect(body.data.older_than_days).toBe(30);
|
||||
expect(body.data.would_delete).toBe(10);
|
||||
});
|
||||
|
||||
it('returns 400 for negative older_than_days', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
headers: authHeaders(),
|
||||
payload: { older_than_days: -5 },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = res.json();
|
||||
expect(body.message).toMatch(/older_than_days/i);
|
||||
});
|
||||
|
||||
it('returns 200 with deleted: 0 when nothing to purge', async () => {
|
||||
const pool = makePool({
|
||||
execute: vi.fn().mockResolvedValueOnce([[{ c: 0 }]]),
|
||||
});
|
||||
const app = await buildApp(pool);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/error-monitoring/purge-resolved',
|
||||
headers: authHeaders(),
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data.deleted).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@
|
||||
* 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/resolve-by-pattern
|
||||
* POST /api/error-monitoring/purge-resolved
|
||||
*/
|
||||
|
||||
@@ -342,6 +343,198 @@ async function handleBulkResolve(request: FastifyRequest, reply: FastifyReply):
|
||||
});
|
||||
}
|
||||
|
||||
const VALID_SEVERITIES = new Set(['critical', 'high', 'medium', 'low', 'info']);
|
||||
|
||||
async function handleResolveByPattern(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 = 'Resolved by pattern via API';
|
||||
}
|
||||
const assignedTo = typeof body.assigned_to === 'string' ? body.assigned_to.trim() : '';
|
||||
const changeNoteBase =
|
||||
assignedTo !== '' ? `${resolutionNotes} (assigned_to: ${assignedTo})` : resolutionNotes;
|
||||
|
||||
// Build filter conditions
|
||||
const conditions: string[] = ["i.current_state IN ('open','investigating')"];
|
||||
const params: Array<string | number> = [];
|
||||
|
||||
// message_pattern — LIKE matching (string or array, max 20)
|
||||
const patternInput = body.message_pattern;
|
||||
if (patternInput !== undefined && patternInput !== null && patternInput !== '') {
|
||||
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 capped = likePatterns.slice(0, 20);
|
||||
if (capped.length > 0) {
|
||||
conditions.push(`(${capped.map(() => 'o.message LIKE ?').join(' OR ')})`);
|
||||
params.push(...capped);
|
||||
}
|
||||
}
|
||||
|
||||
// fingerprint — exact match (string or array, max 50)
|
||||
const fpInput = body.fingerprint;
|
||||
if (fpInput !== undefined && fpInput !== null && fpInput !== '') {
|
||||
const fps = Array.isArray(fpInput) ? fpInput : [fpInput];
|
||||
const validFps: string[] = [];
|
||||
for (const f of fps) {
|
||||
const s = typeof f === 'string' ? f.trim() : '';
|
||||
if (s !== '') {
|
||||
validFps.push(s);
|
||||
}
|
||||
}
|
||||
const capped = validFps.slice(0, 50);
|
||||
if (capped.length > 0) {
|
||||
conditions.push(`i.fingerprint IN (${capped.map(() => '?').join(',')})`);
|
||||
params.push(...capped);
|
||||
}
|
||||
}
|
||||
|
||||
// severity — exact match (string or array)
|
||||
const sevInput = body.severity;
|
||||
if (sevInput !== undefined && sevInput !== null && sevInput !== '') {
|
||||
const sevs = Array.isArray(sevInput) ? sevInput : [sevInput];
|
||||
const validSevs: string[] = [];
|
||||
for (const s of sevs) {
|
||||
const sv = typeof s === 'string' ? s.trim().toLowerCase() : '';
|
||||
if (sv !== '' && VALID_SEVERITIES.has(sv)) {
|
||||
validSevs.push(sv);
|
||||
}
|
||||
}
|
||||
if (validSevs.length > 0) {
|
||||
conditions.push(`i.severity IN (${validSevs.map(() => '?').join(',')})`);
|
||||
params.push(...validSevs);
|
||||
}
|
||||
}
|
||||
|
||||
// project_slug — exact match
|
||||
const projectSlug = typeof body.project_slug === 'string' ? body.project_slug.trim().toLowerCase() : '';
|
||||
if (projectSlug !== '') {
|
||||
conditions.push('p.slug = ?');
|
||||
params.push(projectSlug);
|
||||
}
|
||||
|
||||
// time range — filter on i.last_seen_at
|
||||
const fromDate = typeof body.from_date === 'string' ? body.from_date.trim() : '';
|
||||
const toDate = typeof body.to_date === 'string' ? body.to_date.trim() : '';
|
||||
if (fromDate !== '') {
|
||||
conditions.push('i.last_seen_at >= ?');
|
||||
params.push(fromDate);
|
||||
}
|
||||
if (toDate !== '') {
|
||||
conditions.push('i.last_seen_at <= ?');
|
||||
params.push(toDate);
|
||||
}
|
||||
|
||||
// Must have at least one filter beyond the base state filter
|
||||
if (conditions.length <= 1) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: 'At least one filter is required: message_pattern, fingerprint, severity, project_slug, from_date, or to_date',
|
||||
});
|
||||
}
|
||||
|
||||
// Determine if we need occurrence join (only for message_pattern)
|
||||
const needsOccurrenceJoin = patternInput !== undefined && patternInput !== null && patternInput !== '';
|
||||
const needsProjectJoin = projectSlug !== '';
|
||||
|
||||
const joins: string[] = [];
|
||||
if (needsOccurrenceJoin) {
|
||||
joins.push('INNER JOIN er_incident_occurrences o ON o.incident_id = i.id');
|
||||
}
|
||||
if (needsProjectJoin) {
|
||||
joins.push('INNER JOIN er_projects p ON p.id = i.project_id');
|
||||
}
|
||||
|
||||
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
|
||||
${joins.join('\n ')}
|
||||
WHERE ${conditions.join(' AND ')}
|
||||
LIMIT 5000
|
||||
`;
|
||||
|
||||
const [matchRows] = await db.execute<RowDataPacket[]>(sql, params);
|
||||
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
|
||||
incidentId: String(r.incident_id),
|
||||
projectId: String(r.project_id),
|
||||
currentState: String(r.current_state),
|
||||
}));
|
||||
|
||||
if (targets.length === 0) {
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'No matching incidents found',
|
||||
data: { resolved: 0, matched: 0 },
|
||||
});
|
||||
}
|
||||
|
||||
const { type, ref } = changedByRef(auth);
|
||||
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();
|
||||
}
|
||||
|
||||
const filters: Record<string, unknown> = {};
|
||||
if (patternInput) filters.message_pattern = patternInput;
|
||||
if (fpInput) filters.fingerprint = fpInput;
|
||||
if (sevInput) filters.severity = sevInput;
|
||||
if (projectSlug) filters.project_slug = projectSlug;
|
||||
if (fromDate) filters.from_date = fromDate;
|
||||
if (toDate) filters.to_date = toDate;
|
||||
|
||||
await auditMutation(request.server, request, auth, 'error_monitoring.resolve_by_pattern', 'batch', {
|
||||
resolved,
|
||||
matched: targets.length,
|
||||
filters,
|
||||
});
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: `Resolved ${resolved} incident(s) by pattern`,
|
||||
data: { resolved, matched: targets.length },
|
||||
});
|
||||
}
|
||||
|
||||
async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
@@ -352,8 +545,28 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
|
||||
|
||||
const dryRun = Boolean(body.dry_run);
|
||||
|
||||
// older_than_days — only purge resolved incidents last seen more than N days ago
|
||||
const rawDays = body.older_than_days;
|
||||
let olderThanDays: number | null = null;
|
||||
if (rawDays !== undefined && rawDays !== null) {
|
||||
const n = typeof rawDays === 'number' ? rawDays : parseInt(String(rawDays), 10);
|
||||
if (!Number.isFinite(n) || n < 0) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: 'older_than_days must be a non-negative integer',
|
||||
});
|
||||
}
|
||||
olderThanDays = Math.floor(n);
|
||||
}
|
||||
|
||||
const whereClause = olderThanDays !== null
|
||||
? `current_state = 'resolved' AND last_seen_at < DATE_SUB(NOW(), INTERVAL ? DAY)`
|
||||
: `current_state = 'resolved'`;
|
||||
const whereParams: Array<string | number> = olderThanDays !== null ? [olderThanDays] : [];
|
||||
|
||||
const [countRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(*) AS c FROM er_incidents WHERE current_state = 'resolved'`,
|
||||
`SELECT COUNT(*) AS c FROM er_incidents WHERE ${whereClause}`,
|
||||
whereParams,
|
||||
);
|
||||
const count = Number((countRows[0] as { c?: number }).c ?? 0);
|
||||
|
||||
@@ -364,12 +577,12 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
|
||||
auth,
|
||||
'error_monitoring.purge_resolved_dry_run',
|
||||
'er_incidents',
|
||||
{ would_delete: count },
|
||||
{ would_delete: count, ...(olderThanDays !== null ? { older_than_days: olderThanDays } : {}) },
|
||||
);
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Dry run',
|
||||
data: { dry_run: true, would_delete: count },
|
||||
data: { dry_run: true, would_delete: count, ...(olderThanDays !== null ? { older_than_days: olderThanDays } : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -382,11 +595,13 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
|
||||
}
|
||||
|
||||
const [del] = await db.execute<ResultSetHeader>(
|
||||
`DELETE FROM er_incidents WHERE current_state = 'resolved'`,
|
||||
`DELETE FROM er_incidents WHERE ${whereClause}`,
|
||||
whereParams,
|
||||
);
|
||||
|
||||
await auditMutation(request.server, request, auth, 'error_monitoring.purge_resolved', 'er_incidents', {
|
||||
deleted: del.affectedRows,
|
||||
...(olderThanDays !== null ? { older_than_days: olderThanDays } : {}),
|
||||
});
|
||||
|
||||
return void reply.send({
|
||||
@@ -400,5 +615,6 @@ export default async function errorMonitoringMutationsRoutes(app: FastifyInstanc
|
||||
const rl = { config: { rateLimit: app.rateLimits.mutation } };
|
||||
app.post('/api/error-monitoring/resolve', rl, handleResolve);
|
||||
app.post('/api/error-monitoring/bulk-resolve', rl, handleBulkResolve);
|
||||
app.post('/api/error-monitoring/resolve-by-pattern', rl, handleResolveByPattern);
|
||||
app.post('/api/error-monitoring/purge-resolved', rl, handlePurgeResolved);
|
||||
}
|
||||
Reference in new issue
Block a user