database migrated to POSTGRESQL

This commit is contained in:
2026-10-13 16:11:51 +03:30
parent 41ad8c1063
commit 514c3ccaf0
47 changed files with 1500 additions and 891 deletions
+102 -57
View File
@@ -1,11 +1,11 @@
import { createHash } from 'node:crypto';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
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,
IdempotencyRecordDocument,
IdempotencyRecordStatus,
} from './schemas/idempotency-record.schema';
@@ -31,16 +31,30 @@ export interface IdempotencyBeginResult {
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 {
export class IdempotencyService implements OnModuleInit, OnModuleDestroy {
private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS);
private cleanupTimer?: NodeJS.Timeout;
constructor(
@InjectModel(IdempotencyRecord.name)
private readonly recordModel: Model<IdempotencyRecordDocument>,
@InjectRepository(IdempotencyRecord)
private readonly records: Repository<IdempotencyRecord>,
) {}
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<IdempotencyBeginResult> {
const key = input.key.trim();
if (!key || key.length > 256) {
@@ -52,23 +66,32 @@ export class IdempotencyService {
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);
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 record = await this.recordModel.findOne({ scopeHash }).exec();
let created = false;
if (!record) {
if (!record || record.expiresAt.getTime() <= now) {
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,
});
record = await this.records.save(
this.records.create({
scopeHash,
requestFingerprint,
status: IdempotencyRecordStatus.IN_PROGRESS,
expiresAt: inProgressExpiresAt,
requestId: input.requestId,
}),
);
created = true;
} catch (error) {
if (!this.isDuplicateKey(error)) throw error;
record = await this.recordModel.findOne({ scopeHash }).exec();
if (!isUniqueViolation(error)) throw error;
record = await this.records.findOne({ where: { scopeHash } });
}
}
@@ -78,6 +101,13 @@ export class IdempotencyService {
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');
}
@@ -93,47 +123,66 @@ export class IdempotencyService {
};
}
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<void> {
await this.recordModel
.updateOne(
{ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
{
$set: {
status: IdempotencyRecordStatus.COMPLETED,
responseStatus,
responseBody,
expiresAt: new Date(Date.now() + this.ttlMs),
},
},
)
.exec();
const values: QueryDeepPartialEntity<IdempotencyRecord> = {
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<void> {
await this.recordModel
.deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS })
.exec();
await this.records.delete({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS });
}
private async reclaim(
id: string,
requestFingerprint: string,
expiresAt: Date,
requestId?: string,
): Promise<boolean> {
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<void> {
await this.records
.createQueryBuilder()
.delete()
.from(IdempotencyRecord)
.where('expires_at <= :now', { now: new Date() })
.execute();
}
private asJsonObject(value: unknown): Record<string, unknown> | null {
if (value === null || value === undefined) return null;
if (typeof value === 'object' && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return { value };
}
private hash(value: string): string {
@@ -150,10 +199,6 @@ export class IdempotencyService {
.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;