diff --git a/ingest-api/src/buildApp.ts b/ingest-api/src/buildApp.ts index 3a96722..8222682 100644 --- a/ingest-api/src/buildApp.ts +++ b/ingest-api/src/buildApp.ts @@ -180,6 +180,13 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise { expect(Number((occ[0] as { c: number }).c)).toBe(3); }); + it("parallel identical idempotent requests yield one stored occurrence", async () => { + const _payload = { + events: [ + { + schema_version: 1, + occurred_at: "2026-03-22T14:00:00.000Z", + level: "info", + message: "parallel idempotent ingest probe", + fingerprint: "fp-parallel-idem-probe", + }, + ], + }; + const _headers = { + authorization: `Bearer ${_tokenA}`, + "idempotency-key": "idem-parallel-probe-1", + }; + const [_r1, _r2] = await Promise.all([ + _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: _headers, + payload: _payload, + }), + _app.inject({ + method: "POST", + url: "/v1/ingest/events", + headers: _headers, + payload: _payload, + }), + ]); + expect(_r1.statusCode).toBe(200); + expect(_r2.statusCode).toBe(200); + expect(_r1.body).toBe(_r2.body); + const [occ] = await _pool.execute( + `SELECT COUNT(*) AS c + FROM er_incident_occurrences o + INNER JOIN er_incidents i ON i.id = o.incident_id + WHERE i.project_id = ? + AND o.message = 'parallel idempotent ingest probe'`, + [_projectIdA], + ); + expect(Number((occ[0] as { c: number }).c)).toBe(1); + }); + it("returns 409 when idempotency key is reused with a different body", async () => { const _headers = { authorization: `Bearer ${_tokenA}`, diff --git a/ingest-api/src/services/processIngestBatch.ts b/ingest-api/src/services/processIngestBatch.ts index 13d3322..532dfd6 100644 --- a/ingest-api/src/services/processIngestBatch.ts +++ b/ingest-api/src/services/processIngestBatch.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import type { Pool, PoolConnection } from "mysql2/promise"; import type { ResultSetHeader, RowDataPacket } from "mysql2"; import { @@ -45,6 +46,25 @@ export type IngestSkippedResult = { export type IngestResultItem = IngestStoredResult | IngestSkippedResult; +/** Named lock for parallel idempotent ingests (MySQL max lock name length 64). */ +function _idempotencyLockName(ingestKeyId: string, idempotencyKey: string): string { + const h = createHash("sha256") + .update(ingestKeyId, "utf8") + .update("\0", "utf8") + .update(idempotencyKey, "utf8") + .digest("hex") + .slice(0, 32); + return `eri_${h}`; +} + +function _isMysqlDuplicateKey(err: unknown): boolean { + if (err === null || typeof err !== "object") { + return false; + } + const o = err as { code?: string; errno?: number }; + return o.code === "ER_DUP_ENTRY" || o.errno === 1062; +} + function _parseStoredJson(raw: unknown): unknown { if (raw === null || raw === undefined) { return raw; @@ -69,12 +89,33 @@ export async function processIngestBatch(input: { events: IngestEventInput[]; idempotencyKey: string | null; bodyHash: string; -}): Promise<{ status: 200 | 409; body: unknown }> { +}): Promise<{ status: 200 | 409 | 503; body: unknown }> { const _client = await input.pool.getConnection(); + let _lockName: string | null = null; + let _lockHeld = false; try { await _client.query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"); await _client.beginTransaction(); + if (input.idempotencyKey !== null) { + _lockName = _idempotencyLockName(input.ingestKeyId, input.idempotencyKey); + const [lockRows] = await _client.query("SELECT GET_LOCK(?, 30) AS got", [ + _lockName, + ]); + const _got = (lockRows[0] as { got: number | null } | undefined)?.got; + if (_got !== 1) { + await _client.rollback(); + return { + status: 503, + body: { + error: "idempotency_busy", + message: + "Could not serialize this idempotent ingest; retry after a short backoff.", + }, + }; + } + _lockHeld = true; + const [rows] = await _client.execute( `SELECT body_hash, response_json, http_status FROM er_ingest_idempotency @@ -125,19 +166,52 @@ export async function processIngestBatch(input: { 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), - ], - ); + try { + 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), + ], + ); + } catch (_insErr) { + if (!_isMysqlDuplicateKey(_insErr)) { + throw _insErr; + } + const [idemRows] = 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 _idem = idemRows[0] as + | { body_hash: string; response_json: unknown; http_status: number } + | undefined; + if (!_idem) { + throw _insErr; + } + if (_idem.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.rollback(); + return { status: 200, body: _parseStoredJson(_idem.response_json) }; + } } } @@ -151,6 +225,9 @@ export async function processIngestBatch(input: { await _client.rollback(); throw _err; } finally { + if (_lockHeld && _lockName !== null) { + await _client.query("SELECT RELEASE_LOCK(?)", [_lockName]); + } _client.release(); } }