106 lines
3.6 KiB
TypeScript
106 lines
3.6 KiB
TypeScript
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<AppConfig>,
|
|
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',
|
|
),
|
|
// A relay that waits on the broker must not leave the transaction
|
|
// idle forever if confirm handling stalls.
|
|
options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_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<T extends pg.QueryResultRow = pg.QueryResultRow>(
|
|
label: string,
|
|
text: string,
|
|
values: readonly unknown[] = [],
|
|
): Promise<pg.QueryResult<T>> {
|
|
this.metrics.increment(label);
|
|
return this.pool.query<T>({ text, values: [...values] });
|
|
}
|
|
|
|
async health(): Promise<void> {
|
|
this.metrics.increment('health.database');
|
|
await this.healthPool.query('SELECT 1');
|
|
}
|
|
|
|
async withTransaction<T>(
|
|
work: (client: pg.PoolClient) => Promise<T>,
|
|
): Promise<T> {
|
|
const client = await this.pool.connect();
|
|
// A server-side idle_in_transaction_session_timeout or a network drop
|
|
// can emit 'error' on a checked-out client after pg-pool removed its
|
|
// idle listener. Without this listener Node treats it as uncaught.
|
|
let fatal: Error | undefined;
|
|
const onError = (error: Error): void => {
|
|
fatal = error;
|
|
};
|
|
client.on('error', onError);
|
|
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.removeListener('error', onError);
|
|
client.release(fatal);
|
|
}
|
|
}
|
|
|
|
async onModuleDestroy(): Promise<void> {
|
|
await Promise.all([this.pool.end(), this.healthPool.end()]);
|
|
}
|
|
}
|