import type { Pool, PoolConnection } from "mysql2/promise"; import type { ResultSetHeader, RowDataPacket } from "mysql2"; import { extractLocationFromContext, FINGERPRINT_POLICY_VERSION, } from "../lib/fingerprintPolicy.js"; import { stableJsonHash } from "../lib/hash.js"; import { computeFingerprint, incidentTitleFromMessage, normalizeLevelToSeverity, parseOccurredAt, } from "../lib/normalize.js"; import { evaluateNoise, NOISE_RULESET_VERSION } from "../lib/noisePolicy.js"; import { clientProvidedStack, synthesizeStackTraceForOccurrence, } from "../lib/ingestStacktrace.js"; export type IngestEventInput = { schema_version: number; occurred_at: string; level: string; message: string; fingerprint?: string; stacktrace?: string; /** CRM / snake_case alias for `stacktrace` (same fingerprint rules as stacktrace). */ stack_trace?: string; context?: Record; }; export type IngestStoredResult = { incident_id: string; occurrence_id: string; fingerprint: string; }; export type IngestSkippedResult = { skipped: true; rule_id: string; reason: string; noise_ruleset_version: string; fingerprint_policy_version: number; }; export type IngestResultItem = IngestStoredResult | IngestSkippedResult; function _parseStoredJson(raw: unknown): unknown { if (raw === null || raw === undefined) { return raw; } if (typeof raw === "object") { return raw; } if (typeof raw === "string") { try { return JSON.parse(raw) as unknown; } catch { return raw; } } return raw; } export async function processIngestBatch(input: { pool: Pool; ingestKeyId: string; projectId: string; events: IngestEventInput[]; idempotencyKey: string | null; bodyHash: string; }): Promise<{ status: 200 | 409; body: unknown }> { const _client = await input.pool.getConnection(); try { await _client.query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"); await _client.beginTransaction(); if (input.idempotencyKey !== null) { const [rows] = await _client.execute( `SELECT body_hash, response_json, http_status FROM er_ingest_idempotency WHERE ingest_key_id = ? AND idempotency_key = ? LIMIT 1`, [input.ingestKeyId, input.idempotencyKey], ); const _row0 = rows[0] as | { body_hash: string; response_json: unknown; http_status: number } | undefined; if (_row0) { if (_row0.body_hash !== input.bodyHash) { await _client.rollback(); return { status: 409, body: { error: "idempotency_conflict", message: "The same Idempotency-Key was reused with a different request body. Use a new key or retry the original payload.", }, }; } await _client.commit(); return { status: 200, body: _parseStoredJson(_row0.response_json) }; } } const _results: IngestResultItem[] = []; for (const _ev of input.events) { const _item = await _ingestOneEvent(_client, { ingestKeyId: input.ingestKeyId, projectId: input.projectId, event: _ev, }); _results.push(_item); } const _noiseFiltered = _results.filter((r) => "skipped" in r && r.skipped === true).length; const _responseBody = { fingerprint_policy_version: FINGERPRINT_POLICY_VERSION, noise_ruleset_version: NOISE_RULESET_VERSION, noise_filtered_count: _noiseFiltered, results: _results, }; if (input.idempotencyKey !== null) { const _firstStored = _results.find((r): r is IngestStoredResult => !("skipped" in r)); const _firstIncidentId = _firstStored?.incident_id; if (typeof _firstIncidentId === "string") { await _client.execute( `INSERT INTO er_ingest_idempotency ( ingest_key_id, project_id, idempotency_key, body_hash, incident_id, http_status, response_json ) VALUES (?, ?, ?, ?, ?, 200, ?)`, [ input.ingestKeyId, input.projectId, input.idempotencyKey, input.bodyHash, _firstIncidentId, JSON.stringify(_responseBody), ], ); } } await _client.execute(`UPDATE er_ingest_keys SET last_used_at = NOW(6) WHERE id = ?`, [ input.ingestKeyId, ]); await _client.commit(); return { status: 200, body: _responseBody }; } catch (_err) { await _client.rollback(); throw _err; } finally { _client.release(); } } async function _ingestOneEvent( client: PoolConnection, input: { ingestKeyId: string; projectId: string; event: IngestEventInput }, ): Promise { const _ev = input.event; if (_ev.schema_version !== 1) { throw new Error("unsupported_schema_version"); } const _occurredMs = parseOccurredAt(_ev.occurred_at); const _occurred = new Date(_occurredMs); const _levelRaw = _ev.level.trim().slice(0, 32); const _severity = normalizeLevelToSeverity(_ev.level); const _message = _ev.message.trim(); const _context = _ev.context && typeof _ev.context === "object" ? _ev.context : null; const _noise = evaluateNoise({ level: _ev.level, message: _message, context: _context ?? undefined, filePathHint: extractLocationFromContext(_context).filePath, }); if (_noise.matched) { return { skipped: true, rule_id: _noise.ruleId, reason: _noise.reason, noise_ruleset_version: NOISE_RULESET_VERSION, fingerprint_policy_version: FINGERPRINT_POLICY_VERSION, }; } const _clientStack = clientProvidedStack(_ev); const _fingerprint = computeFingerprint({ clientFingerprint: _ev.fingerprint, message: _message, ...(_clientStack !== null ? { stacktrace: _clientStack } : {}), context: _context, }); const _title = incidentTitleFromMessage(_message); const _stack = _clientStack !== null ? _clientStack : synthesizeStackTraceForOccurrence(_message, _context); await client.execute( `INSERT INTO er_incidents ( project_id, fingerprint, title, severity, first_seen_at, last_seen_at, occurrences_count, last_ingest_key_id ) VALUES (?, ?, ?, ?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE last_seen_at = VALUES(last_seen_at), occurrences_count = er_incidents.occurrences_count + 1, last_ingest_key_id = VALUES(last_ingest_key_id), updated_at = CURRENT_TIMESTAMP(6)`, [input.projectId, _fingerprint, _title, _severity, _occurred, _occurred, input.ingestKeyId], ); const [incRows] = await client.execute( `SELECT CAST(id AS CHAR) AS id FROM er_incidents WHERE project_id = ? AND fingerprint = ? LIMIT 1`, [input.projectId, _fingerprint], ); const _incidentRow = incRows[0] as { id: string } | undefined; if (!_incidentRow) { throw new Error("incident_upsert_failed"); } const [occHeader] = await client.execute( `INSERT INTO er_incident_occurrences ( project_id, incident_id, ingest_key_id, occurred_at, level_raw, severity, message, stack_trace, context_json, schema_version, environment ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'production')`, [ input.projectId, _incidentRow.id, input.ingestKeyId, _occurred, _levelRaw, _severity, _message, _stack, _context === null ? null : JSON.stringify(_context), _ev.schema_version, ], ); const _occId = occHeader.insertId; if (typeof _occId !== "bigint" && typeof _occId !== "number") { throw new Error("occurrence_insert_failed"); } if (Number(_occId) <= 0) { throw new Error("occurrence_insert_failed"); } return { incident_id: _incidentRow.id, occurrence_id: String(_occId), fingerprint: _fingerprint, }; } export function computeRequestBodyHash(body: unknown): string { return stableJsonHash(body); }