import { createHash } from 'node:crypto'; import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { AppException } from '../common/exceptions/app-exception'; import { IdempotencyRecord, IdempotencyRecordDocument, 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; @Injectable() export class IdempotencyService { private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS); constructor( @InjectModel(IdempotencyRecord.name) private readonly recordModel: Model, ) {} 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 expiresAt = new Date(now + this.ttlMs); let record = await this.recordModel.findOne({ scopeHash }).exec(); let created = false; if (!record) { try { record = await this.recordModel.create({ scopeHash, requestFingerprint, status: IdempotencyRecordStatus.IN_PROGRESS, expiresAt: new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)), requestId: input.requestId, }); created = true; } catch (error) { if (!this.isDuplicateKey(error)) throw error; record = await this.recordModel.findOne({ scopeHash }).exec(); } } if (!record) { throw new AppException('INTERNAL_ERROR', { message: 'Unable to reserve idempotency key' }); } if (created) return { scopeHash }; 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, }, }; } if (record.expiresAt.getTime() <= now) { const reclaimed = await this.recordModel .findOneAndUpdate( { _id: record._id, expiresAt: { $lte: new Date(now) } }, { $set: { requestFingerprint, status: IdempotencyRecordStatus.IN_PROGRESS, expiresAt, requestId: input.requestId, }, }, { new: true }, ) .exec(); if (reclaimed) return { scopeHash }; } throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS'); } async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise { await this.recordModel .updateOne( { scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }, { $set: { status: IdempotencyRecordStatus.COMPLETED, responseStatus, responseBody, expiresAt: new Date(Date.now() + this.ttlMs), }, }, ) .exec(); } async abandon(scopeHash: string): Promise { await this.recordModel .deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS }) .exec(); } 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 isDuplicateKey(error: unknown): boolean { return Boolean(error && typeof error === 'object' && 'code' in error && (error as { code?: number }).code === 11000); } private readPositiveEnv(name: string, fallback: number): number { const value = Number.parseInt(process.env[name] ?? '', 10); return Number.isFinite(value) && value > 0 ? value : fallback; } }