import { Injectable } from '@nestjs/common'; import pg from 'pg'; import { DatabaseClient } from '../../database/database.client.js'; import type { Message } from '../message.js'; // A committed row always carries the response: the claim and the stored response // are written by one statement, so there is no poisoned intermediate state to // re-check at replay time. export type IdempotencyRecord = { request_fingerprint: string; status_code: number; response_body: Message; created_at: Date | string; expired: boolean; is_member: boolean; }; const PURGE_BATCH_LIMIT = 1000; const PURGE_BATCHES = 10; @Injectable() export class IdempotencyRepository { constructor(private readonly database: DatabaseClient) {} /** * Reads the stored result and re-checks access in the same round trip: a * replay must still prove that the caller may read this chat. */ async read( userId: string, path: string, key: string, chatId: string, ttlSeconds: number, ): Promise { const result = await this.database.query( 'idempotency.read', `SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at, k.created_at < now() - make_interval(secs => $4::double precision) AS expired, EXISTS ( SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1 ) AS is_member FROM idempotency_keys k WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`, [userId, path, key, ttlSeconds, chatId], ); return result.rows[0]; } async forget( userId: string, path: string, key: string, ttlSeconds: number, ): Promise { await this.database.query( 'idempotency.forget', `DELETE FROM idempotency_keys WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3 AND created_at < now() - make_interval(secs => $4::double precision)`, [userId, path, key, ttlSeconds], ); } async isMember(chatId: string, userId: string): Promise { const result = await this.database.query<{ is_member: boolean }>( 'messages.checkMembership', `SELECT EXISTS ( SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2 ) AS is_member`, [chatId, userId], ); return result.rows[0]?.is_member === true; } /** * Deletes expired claims in bounded batches. The transaction-scoped advisory * lock makes the pass single-flight across replicas without risking a lock * leaking back into the pool with a released connection. Returns the number * of deleted rows (0 when another replica is purging). */ async purgeExpired(ttlSeconds: number): Promise { const client: pg.PoolClient = await this.database.pool.connect(); try { await client.query('BEGIN'); try { const lock = await client.query<{ locked: boolean }>( "SELECT pg_try_advisory_xact_lock(hashtext('idempotency_gc')) AS locked", ); if (lock.rows[0]?.locked !== true) { await client.query('ROLLBACK'); return 0; } let purged = 0; for (let batch = 0; batch < PURGE_BATCHES; batch += 1) { const result = await client.query( `DELETE FROM idempotency_keys WHERE ctid IN ( SELECT ctid FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1::double precision) LIMIT ${PURGE_BATCH_LIMIT} )`, [ttlSeconds], ); const deleted = result.rowCount ?? 0; purged += deleted; if (deleted < PURGE_BATCH_LIMIT) break; } await client.query('COMMIT'); return purged; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } } finally { client.release(); } } }