import { createHash } from 'node:crypto'; import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { QueryDeepPartialEntity, Repository } from 'typeorm'; import { AppException } from '../common/exceptions/app-exception'; import { isUniqueViolation } from '../database/postgres.helpers'; import { IdempotencyRecord, IdempotencyRecordStatus, } from './schemas/idempotency-record.schema'; export interface IdempotencyBeginInput { key: string; callerId: string; method: string; path: string; body: unknown; requestId?: string; } export interface IdempotencyReplay { scopeHash: string; responseStatus: number; responseBody: unknown; } export interface IdempotencyBeginResult { scopeHash: string; replay?: IdempotencyReplay; } const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; const IN_PROGRESS_TTL_MS = 5 * 60 * 1000; const CLEANUP_INTERVAL_MS = 15 * 60 * 1000; @Injectable() export class IdempotencyService implements OnModuleInit, OnModuleDestroy { private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS); private cleanupTimer?: NodeJS.Timeout; constructor( @InjectRepository(IdempotencyRecord) private readonly records: Repository, ) {} onModuleInit(): void { void this.deleteExpired().catch(() => undefined); this.cleanupTimer = setInterval(() => { void this.deleteExpired().catch(() => undefined); }, CLEANUP_INTERVAL_MS); this.cleanupTimer.unref?.(); } onModuleDestroy(): void { if (this.cleanupTimer) clearInterval(this.cleanupTimer); } async begin(input: IdempotencyBeginInput): Promise { const key = input.key.trim(); if (!key || key.length > 256) { throw new AppException('VALIDATION_ERROR', { message: 'Idempotency-Key must be between 1 and 256 characters', }); } const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`); const requestFingerprint = this.hash(this.stableStringify(input.body)); const now = Date.now(); const inProgressExpiresAt = new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)); let record = await this.records.findOne({ where: { scopeHash } }); if (record && record.expiresAt.getTime() <= now) { if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) { return { scopeHash }; } record = await this.records.findOne({ where: { scopeHash } }); } let created = false; if (!record || record.expiresAt.getTime() <= now) { try { record = await this.records.save( this.records.create({ scopeHash, requestFingerprint, status: IdempotencyRecordStatus.IN_PROGRESS, expiresAt: inProgressExpiresAt, requestId: input.requestId, }), ); created = true; } catch (error) { if (!isUniqueViolation(error)) throw error; record = await this.records.findOne({ where: { scopeHash } }); } } if (!record) { throw new AppException('INTERNAL_ERROR', { message: 'Unable to reserve idempotency key' }); } if (created) return { scopeHash }; if (record.expiresAt.getTime() <= now) { if (await this.reclaim(record.id, requestFingerprint, inProgressExpiresAt, input.requestId)) { return { scopeHash }; } throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS'); } if (record.requestFingerprint !== requestFingerprint) { throw new AppException('IDEMPOTENCY_KEY_REUSED'); } if (record.status === IdempotencyRecordStatus.COMPLETED) { return { scopeHash, replay: { scopeHash, responseStatus: record.responseStatus ?? 200, responseBody: record.responseBody, }, }; } throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS'); } async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise { const values: QueryDeepPartialEntity = { status: IdempotencyRecordStatus.COMPLETED, responseStatus, responseBody: this.asJsonObject(responseBody) as QueryDeepPartialEntity< IdempotencyRecord >['responseBody'], expiresAt: new Date(Date.now() + this.ttlMs), }; await this.records.update( { scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }, values, ); } async abandon(scopeHash: string): Promise { await this.records.delete({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }); } private async reclaim( id: string, requestFingerprint: string, expiresAt: Date, requestId?: string, ): Promise { const result = await this.records .createQueryBuilder() .update(IdempotencyRecord) .set({ requestFingerprint, status: IdempotencyRecordStatus.IN_PROGRESS, expiresAt, requestId: requestId ?? null, responseStatus: null, responseBody: () => 'NULL', }) .where('id = :id', { id }) .andWhere('expires_at <= :now', { now: new Date() }) .execute(); return (result.affected ?? 0) > 0; } private async deleteExpired(): Promise { await this.records .createQueryBuilder() .delete() .from(IdempotencyRecord) .where('expires_at <= :now', { now: new Date() }) .execute(); } private asJsonObject(value: unknown): Record | null { if (value === null || value === undefined) return null; if (typeof value === 'object' && !Array.isArray(value)) { return value as Record; } return { value }; } private hash(value: string): string { return createHash('sha256').update(value).digest('hex'); } private stableStringify(value: unknown): string { if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined'; if (Array.isArray(value)) return `[${value.map((item) => this.stableStringify(item)).join(',')}]`; const object = value as Record; return `{${Object.keys(object) .sort() .map((key) => `${JSON.stringify(key)}:${this.stableStringify(object[key])}`) .join(',')}}`; } private readPositiveEnv(name: string, fallback: number): number { const value = Number.parseInt(process.env[name] ?? '', 10); return Number.isFinite(value) && value > 0 ? value : fallback; } }