import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import pg from 'pg'; import { MetricsService } from '../metrics/metrics.service.js'; import type { AppConfig } from '../config/app-config.schema.js'; @Injectable() export class DatabaseClient implements OnModuleDestroy { readonly pool: pg.Pool; private readonly healthPool: pg.Pool; private readonly logger = new Logger(DatabaseClient.name); constructor( private readonly config: ConfigService, private readonly metrics: MetricsService, ) { this.pool = new pg.Pool({ connectionString: this.config.getOrThrow('DATABASE_URL'), max: this.config.getOrThrow('DATABASE_POOL_MAX'), connectionTimeoutMillis: this.config.getOrThrow( 'DATABASE_CONNECTION_TIMEOUT_MS', ), statement_timeout: this.config.getOrThrow( 'DATABASE_STATEMENT_TIMEOUT_MS', ), }); // Idle clients emit 'error' on the pool when the database drops; without a // listener Node treats it as uncaught and terminates the process. this.pool.on('error', (error: Error) => { this.metrics.increment('database.pool_error'); this.logger.warn(`PostgreSQL pool error: ${error.message}`); }); // Проба готовности не должна стоять в очереди за бизнес-запросами: занятый // общий пул — это перегрузка, а не потеря зависимости. this.healthPool = new pg.Pool({ connectionString: this.config.getOrThrow('DATABASE_URL'), max: 1, idleTimeoutMillis: 0, connectionTimeoutMillis: this.config.getOrThrow('HEALTH_TIMEOUT_MS'), query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'), }); this.healthPool.on('error', (error: Error) => { this.metrics.increment('database.health_pool_error'); this.logger.warn( `PostgreSQL health connection error: ${error.message}`, ); }); } query( label: string, text: string, values: readonly unknown[] = [], ): Promise> { this.metrics.increment(label); return this.pool.query({ text, values: [...values] }); } async health(): Promise { this.metrics.increment('health.database'); await this.healthPool.query('SELECT 1'); } async withTransaction( work: (client: pg.PoolClient) => Promise, ): Promise { const client = await this.pool.connect(); try { await client.query('BEGIN'); const result = await work(client); await client.query('COMMIT'); return result; } catch (error) { try { await client.query('ROLLBACK'); } catch (rollbackError) { this.metrics.increment('database.rollback_error'); this.logger.warn( `Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`, ); } // Callers must see the operation error, not the rollback error. throw error; } finally { client.release(); } } async onModuleDestroy(): Promise { await Promise.all([this.pool.end(), this.healthPool.end()]); } }