Files
mtusi2026lab5/app/src/database/database.client.ts
T
ilya.tyunin 1982bdb690 lab5: базовый коммит из lab4 (abba248)
Перенесено дерево lab4 целиком: NestJS-приложение с вложениями и S3,
Dockerfile, compose.yaml, infra/{haproxy,minio}, стендовые скрипты,
scripts/lab4, evidence/lab4 и contracts/extensions.openapi.json.

Задание lab5 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,examples},
tests, compose.example.yaml, .github/pull_request_template.md.

Адаптации при переносе:
- docker-проект mtusi-lab4 -> mtusi-lab5 и тег образа mtusi-messenger:lab5,
  чтобы тома и контейнеры не пересекались с lab4 (scripts/stop-one.sh:
  LAB_PROJECT вместо LAB4_PROJECT);
- Makefile: цели lab5 сохранены, добавлены стендовые (stand-up/down,
  wait-ready, init-env, test-e2e, test-dependencies, s3-security,
  consistency, bench);
- .env.example: реальные переменные приложения и стенда lab4 (без них
  compose.yaml не поднимается) + блок lab5 (BROKER_URL_FILE, WORKER_*).
2026-11-04 23:44:11 +03:00

94 lines
3.0 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',
),
});
// 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();
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<void> {
await Promise.all([this.pool.end(), this.healthPool.end()]);
}
}