173 lines
5.6 KiB
TypeScript
173 lines
5.6 KiB
TypeScript
|
|
/**
|
||
|
|
* Error event capture + retrieval.
|
||
|
|
*
|
||
|
|
* `captureErrorEvent(...)` is called from `errorResponse(...)` whenever
|
||
|
|
* an unhandled (5xx) error fires inside a route handler. It pulls the
|
||
|
|
* request context from AsyncLocalStorage, sanitizes the payload, and
|
||
|
|
* inserts one row into `error_events`. Failure to write must NEVER
|
||
|
|
* throw — the caller is already in the error path.
|
||
|
|
*
|
||
|
|
* `listErrorEvents` / `getErrorEventById` back the super-admin inspector.
|
||
|
|
*/
|
||
|
|
|
||
|
|
import { and, desc, eq, gte, lte } from 'drizzle-orm';
|
||
|
|
|
||
|
|
import { db } from '@/lib/db';
|
||
|
|
import { errorEvents, type ErrorEvent } from '@/lib/db/schema/system';
|
||
|
|
import { logger } from '@/lib/logger';
|
||
|
|
import { getRequestContext } from '@/lib/request-context';
|
||
|
|
|
||
|
|
const STACK_MAX_BYTES = 4 * 1024;
|
||
|
|
const BODY_MAX_BYTES = 1 * 1024;
|
||
|
|
|
||
|
|
/** Keys whose values are never persisted to the body excerpt. */
|
||
|
|
const SENSITIVE_KEYS = new Set([
|
||
|
|
'password',
|
||
|
|
'newPassword',
|
||
|
|
'oldPassword',
|
||
|
|
'token',
|
||
|
|
'secret',
|
||
|
|
'apiKey',
|
||
|
|
'accessKey',
|
||
|
|
'secretKey',
|
||
|
|
'creditCard',
|
||
|
|
'cardNumber',
|
||
|
|
'cvv',
|
||
|
|
'ssn',
|
||
|
|
'authorization',
|
||
|
|
]);
|
||
|
|
|
||
|
|
/** Drop sensitive keys + cap the JSON length. */
|
||
|
|
function sanitizeBody(body: unknown): string | null {
|
||
|
|
if (body === null || body === undefined) return null;
|
||
|
|
let cloned: unknown;
|
||
|
|
try {
|
||
|
|
cloned = JSON.parse(JSON.stringify(body));
|
||
|
|
} catch {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
function walk(value: unknown): unknown {
|
||
|
|
if (Array.isArray(value)) return value.map(walk);
|
||
|
|
if (value && typeof value === 'object') {
|
||
|
|
const out: Record<string, unknown> = {};
|
||
|
|
for (const [k, v] of Object.entries(value)) {
|
||
|
|
if (SENSITIVE_KEYS.has(k)) {
|
||
|
|
out[k] = '[REDACTED]';
|
||
|
|
} else {
|
||
|
|
out[k] = walk(v);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
return value;
|
||
|
|
}
|
||
|
|
const sanitized = walk(cloned);
|
||
|
|
let serialized: string;
|
||
|
|
try {
|
||
|
|
serialized = JSON.stringify(sanitized);
|
||
|
|
} catch {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
if (Buffer.byteLength(serialized, 'utf8') > BODY_MAX_BYTES) {
|
||
|
|
serialized = serialized.slice(0, BODY_MAX_BYTES) + '…[truncated]';
|
||
|
|
}
|
||
|
|
return serialized;
|
||
|
|
}
|
||
|
|
|
||
|
|
interface CaptureArgs {
|
||
|
|
statusCode: number;
|
||
|
|
error: unknown;
|
||
|
|
/** Optional structured metadata (e.g. zod issues parsed from a ZodError). */
|
||
|
|
metadata?: Record<string, unknown>;
|
||
|
|
/** Sanitized request body (already JSON-serializable). Optional. */
|
||
|
|
body?: unknown;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Persist an error_events row tied to the active request context.
|
||
|
|
* Best-effort — silently swallows any DB failure (the caller is
|
||
|
|
* already returning the user an error response; we do NOT want to
|
||
|
|
* mask the original error with a logging-pipeline failure).
|
||
|
|
*/
|
||
|
|
export async function captureErrorEvent(args: CaptureArgs): Promise<void> {
|
||
|
|
const ctx = getRequestContext();
|
||
|
|
if (!ctx) {
|
||
|
|
// Outside a request context (e.g. queue worker). Log but skip — the
|
||
|
|
// queue has its own failure-capture in BullMQ.
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const err = args.error;
|
||
|
|
const errorName = err instanceof Error ? err.name : typeof err;
|
||
|
|
const errorMessage = err instanceof Error ? err.message : err === undefined ? '' : String(err);
|
||
|
|
const stack = err instanceof Error && err.stack ? err.stack.slice(0, STACK_MAX_BYTES) : null;
|
||
|
|
const durationMs = Date.now() - ctx.startedAt;
|
||
|
|
|
||
|
|
// Pull through any well-known fields the upstream library decorated
|
||
|
|
// onto the error — Postgres driver uses `code` (SQLSTATE) and
|
||
|
|
// `severity`, fetch errors carry `cause.code`, etc. The classifier
|
||
|
|
// reads from `metadata.code` to drive the "likely culprit" badge.
|
||
|
|
const enriched: Record<string, unknown> = { ...(args.metadata ?? {}) };
|
||
|
|
if (err && typeof err === 'object') {
|
||
|
|
const e = err as { code?: unknown; severity?: unknown; cause?: { code?: unknown } };
|
||
|
|
if (typeof e.code === 'string') enriched.code = e.code;
|
||
|
|
if (typeof e.severity === 'string') enriched.severity = e.severity;
|
||
|
|
if (e.cause && typeof e.cause === 'object' && typeof e.cause.code === 'string') {
|
||
|
|
enriched.causeCode = e.cause.code;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
await db
|
||
|
|
.insert(errorEvents)
|
||
|
|
.values({
|
||
|
|
requestId: ctx.requestId,
|
||
|
|
portId: ctx.portId || null,
|
||
|
|
userId: ctx.userId || null,
|
||
|
|
statusCode: args.statusCode,
|
||
|
|
method: ctx.method,
|
||
|
|
path: ctx.path,
|
||
|
|
errorName,
|
||
|
|
errorMessage,
|
||
|
|
errorStack: stack,
|
||
|
|
requestBodyExcerpt: sanitizeBody(args.body),
|
||
|
|
metadata: enriched,
|
||
|
|
durationMs,
|
||
|
|
})
|
||
|
|
.onConflictDoNothing();
|
||
|
|
} catch (writeErr) {
|
||
|
|
// Logged but never thrown — the caller is in the error path already.
|
||
|
|
logger.error({ err: writeErr }, 'Failed to persist error_events row');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export interface ListErrorEventsFilter {
|
||
|
|
portId?: string;
|
||
|
|
statusCode?: number;
|
||
|
|
/** ISO date strings; defaults to last 7 days. */
|
||
|
|
from?: string;
|
||
|
|
to?: string;
|
||
|
|
limit?: number;
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function listErrorEvents(filter: ListErrorEventsFilter): Promise<ErrorEvent[]> {
|
||
|
|
const conditions = [];
|
||
|
|
if (filter.portId) conditions.push(eq(errorEvents.portId, filter.portId));
|
||
|
|
if (filter.statusCode) conditions.push(eq(errorEvents.statusCode, filter.statusCode));
|
||
|
|
if (filter.from) conditions.push(gte(errorEvents.createdAt, new Date(filter.from)));
|
||
|
|
if (filter.to) conditions.push(lte(errorEvents.createdAt, new Date(filter.to)));
|
||
|
|
|
||
|
|
return db
|
||
|
|
.select()
|
||
|
|
.from(errorEvents)
|
||
|
|
.where(conditions.length ? and(...conditions) : undefined)
|
||
|
|
.orderBy(desc(errorEvents.createdAt))
|
||
|
|
.limit(filter.limit ?? 100);
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function getErrorEventById(requestId: string): Promise<ErrorEvent | null> {
|
||
|
|
const row = await db.query.errorEvents.findFirst({
|
||
|
|
where: eq(errorEvents.requestId, requestId),
|
||
|
|
});
|
||
|
|
return row ?? null;
|
||
|
|
}
|