Files
mtusi2026lab7/app/src/database/database.client.ts
T

437 lines
12 KiB
TypeScript

import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
Optional,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SpanKind, type Attributes, type Span } from '@opentelemetry/api';
import { URL } from 'node:url';
import pg from 'pg';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { RuntimeSecretsStore } from '../openbao/runtime-secrets.service.js';
import { TlsMaterialManager } from '../security/tls-material.js';
import { instruments, meter } from '../telemetry/instruments.js';
import { errorType, withChildSpan } from '../telemetry/tracing.js';
const DB_SYSTEM = 'postgresql';
const POOL_NAME = 'main';
const TRANSACTION_CONTROL =
/^\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/iu;
const SQL_TARGET =
/\b(?:FROM|INTO|UPDATE|JOIN)\s+"?([A-Za-z_][A-Za-z0-9_]*)"?/iu;
function sqlOperation(text: string): string {
const match = /^\s*([A-Za-z]+)/u.exec(text);
return match ? match[1].toUpperCase() : 'OTHER';
}
function sqlTarget(text: string): string | undefined {
return SQL_TARGET.exec(text)?.[1]?.toLowerCase();
}
function queryText(args: readonly unknown[]): string {
const first = args[0];
if (typeof first === 'string') return first;
if (typeof first === 'object' && first !== null) {
const text = (first as { text?: unknown }).text;
if (typeof text === 'string') return text;
}
return '';
}
function isPassThrough(args: readonly unknown[]): boolean {
const first = args[0];
return (
typeof args[args.length - 1] === 'function' ||
(typeof first === 'object' &&
first !== null &&
typeof (first as { submit?: unknown }).submit === 'function')
);
}
function elapsedSeconds(started: bigint): number {
return Number(process.hrtime.bigint() - started) / 1e9;
}
function statementAttributes(
label: string,
operation: string,
target: string | undefined,
): Attributes {
return {
'db.system.name': DB_SYSTEM,
'db.operation.name': operation,
'db.query.summary': label,
...(target ? { 'db.collection.name': target } : {}),
};
}
function isPgAuthError(error: unknown): boolean {
if (typeof error !== 'object' || error === null) return false;
const code = (error as { code?: unknown }).code;
return code === '28P01' || code === '28000';
}
function parseDatabaseUrl(urlString: string | undefined): {
host?: string;
port?: number;
database?: string;
user?: string;
password?: string;
} {
if (!urlString) return {};
try {
const parsed = new URL(urlString);
const dbName = parsed.pathname.replace(/^\/+/u, '');
return {
host: parsed.hostname || undefined,
port: parsed.port ? Number(parsed.port) : undefined,
database: dbName || undefined,
user: parsed.username ? decodeURIComponent(parsed.username) : undefined,
password: parsed.password
? decodeURIComponent(parsed.password)
: undefined,
};
} catch {
return {};
}
}
function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient {
return new Proxy(client, {
get(target, property) {
const value: unknown = Reflect.get(target, property, target);
if (typeof value !== 'function') return value;
const method = value as (...args: unknown[]) => unknown;
if (property !== 'query') return method.bind(target);
return (...args: unknown[]): unknown => {
const text = queryText(args);
if (isPassThrough(args) || TRANSACTION_CONTROL.test(text))
return method.apply(target, args);
const operation = sqlOperation(text);
const table = sqlTarget(text);
return withChildSpan(
`${operation} ${table ?? label}`,
SpanKind.CLIENT,
statementAttributes(label, operation, table),
async () => method.apply(target, args),
);
};
},
});
}
@Injectable()
export class DatabaseClient implements OnModuleDestroy {
private activePool: pg.Pool;
private activeHealthPool: pg.Pool;
private readonly logger = new Logger(DatabaseClient.name);
private readonly onRotateDb: () => void;
private readonly onTlsReload: () => void;
constructor(
private readonly config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
@Optional() @Inject(TlsMaterialManager) private readonly tls?: TlsMaterialManager,
@Optional() @Inject(RuntimeSecretsStore) private readonly secrets?: RuntimeSecretsStore,
) {
this.activePool = this.createMainPool();
this.activeHealthPool = this.createHealthPool();
this.observePool(this.config.getOrThrow('DATABASE_POOL_MAX'));
this.onRotateDb = () => this.rotatePools('secret_rotated');
this.onTlsReload = () => this.rotatePools('tls_reloaded');
this.secrets?.on('rotated:db', this.onRotateDb);
this.tls?.on('reloaded', this.onTlsReload);
}
get pool(): pg.Pool {
return this.activePool;
}
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
label: string,
text: string,
values: readonly unknown[] = [],
): Promise<pg.QueryResult<T>> {
this.metrics.increment(label);
return this.observe(
label,
sqlOperation(text),
sqlTarget(text),
async () => {
const client = await this.checkout();
let failure: Error | undefined;
const onError = (error: Error): void => {
failure = error;
};
client.on('error', onError);
try {
return await client.query<T>({ text, values: [...values] });
} catch (error) {
this.maybeRefreshOnAuthError(error);
failure ??=
error instanceof Error ? error : new Error('Query failed');
throw error;
} finally {
client.removeListener('error', onError);
client.release(failure);
}
},
);
}
async health(): Promise<void> {
this.metrics.increment('health.database');
try {
await this.activeHealthPool.query('SELECT 1');
} catch (error) {
this.maybeRefreshOnAuthError(error);
throw error;
}
}
withTransaction<T>(
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
return this.transaction('transaction', work);
}
transaction<T>(
label: string,
work: (client: pg.PoolClient) => Promise<T>,
): Promise<T> {
return this.observe(label, 'TRANSACTION', undefined, async (span) => {
const client = await this.checkout();
let fatal: Error | undefined;
const onError = (error: Error): void => {
fatal = error;
};
client.on('error', onError);
try {
await client.query('BEGIN');
const result = await work(
span ? tracedClient(client, label) : client,
);
await client.query('COMMIT');
return result;
} catch (error) {
this.maybeRefreshOnAuthError(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'}`,
);
}
throw error;
} finally {
client.removeListener('error', onError);
client.release(fatal);
}
});
}
async onModuleDestroy(): Promise<void> {
this.secrets?.off('rotated:db', this.onRotateDb);
this.tls?.off('reloaded', this.onTlsReload);
await Promise.all([this.activePool.end(), this.activeHealthPool.end()]);
}
private buildConnectionFields(): pg.PoolConfig {
const getOpt = <K extends keyof AppConfig>(key: K): AppConfig[K] | undefined =>
typeof this.config.get === 'function' ? this.config.get(key) : undefined;
const parsed = parseDatabaseUrl(getOpt('DATABASE_URL'));
const host = getOpt('PG_HOST') ?? parsed.host ?? 'postgres';
const port = getOpt('PG_PORT') ?? parsed.port ?? 5432;
const database = getOpt('PG_DATABASE') ?? parsed.database ?? 'messenger';
const creds = this.secrets?.getDbCredentials();
const user = creds?.user ?? getOpt('PG_USER') ?? parsed.user;
const password =
creds?.password ?? getOpt('PG_PASSWORD') ?? parsed.password;
const tlsEnabled = this.tls?.enabled ?? Boolean(getOpt('TLS_ENABLED'));
const pgMtls = Boolean(getOpt('PG_TLS_MTLS'));
let ssl: pg.PoolConfig['ssl'];
if (tlsEnabled) {
if (!this.tls?.ca) {
throw new Error(
'PostgreSQL TLS requires CA certificate (TLS_CA_FILE)',
);
}
ssl = {
ca: this.tls.ca,
rejectUnauthorized: true,
servername: host,
minVersion: 'TLSv1.2',
...(pgMtls && this.tls.clientCert && this.tls.clientKey
? { cert: this.tls.clientCert, key: this.tls.clientKey }
: {}),
};
}
return {
host,
port,
database,
user,
password,
...(ssl ? { ssl } : {}),
};
}
private createMainPool(): pg.Pool {
const pool = new pg.Pool({
...this.buildConnectionFields(),
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
connectionTimeoutMillis: this.config.getOrThrow(
'DATABASE_CONNECTION_TIMEOUT_MS',
),
statement_timeout: this.config.getOrThrow(
'DATABASE_STATEMENT_TIMEOUT_MS',
),
options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`,
});
pool.on('error', (error: Error) => {
this.metrics.increment('database.pool_error');
this.maybeRefreshOnAuthError(error);
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
});
return pool;
}
private createHealthPool(): pg.Pool {
const pool = new pg.Pool({
...this.buildConnectionFields(),
max: 1,
idleTimeoutMillis: 0,
connectionTimeoutMillis:
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
});
pool.on('error', (error: Error) => {
this.metrics.increment('database.health_pool_error');
this.maybeRefreshOnAuthError(error);
this.logger.warn(
`PostgreSQL health connection error: ${error.message}`,
);
});
return pool;
}
private rotatePools(reason: string): void {
try {
const nextMain = this.createMainPool();
const nextHealth = this.createHealthPool();
const oldMain = this.activePool;
const oldHealth = this.activeHealthPool;
this.activePool = nextMain;
this.activeHealthPool = nextHealth;
this.logger.log(`Swapped PostgreSQL pools (${reason})`);
void Promise.allSettled([oldMain.end(), oldHealth.end()]);
} catch (error) {
this.logger.warn(
`PostgreSQL pool swap skipped (${reason}): ${error instanceof Error ? error.name : 'unknown error'}`,
);
}
}
private maybeRefreshOnAuthError(error: unknown): void {
if (isPgAuthError(error)) {
void this.secrets?.refreshNow('pg_auth_error');
}
}
private observe<T>(
label: string,
operation: string,
target: string | undefined,
work: (span: Span | undefined) => Promise<T>,
): Promise<T> {
const started = process.hrtime.bigint();
return withChildSpan(
`${operation} ${target ?? label}`,
SpanKind.CLIENT,
statementAttributes(label, operation, target),
async (span) => {
let failure: string | undefined;
try {
return await work(span);
} catch (error) {
failure = errorType(error);
throw error;
} finally {
instruments().dbOperationDuration.record(elapsedSeconds(started), {
'db.system.name': DB_SYSTEM,
'db.operation.name': operation,
'db.query.summary': label,
...(failure ? { 'error.type': failure } : {}),
});
}
},
);
}
private async checkout(): Promise<pg.PoolClient> {
const started = process.hrtime.bigint();
let failure: string | undefined;
try {
return await this.activePool.connect();
} catch (error) {
this.maybeRefreshOnAuthError(error);
failure = errorType(error);
throw error;
} finally {
instruments().dbConnectionWait.record(elapsedSeconds(started), {
'db.client.connection.pool.name': POOL_NAME,
...(failure ? { 'error.type': failure } : {}),
});
}
}
private observePool(max: number): void {
const m = meter();
const pool = { 'db.client.connection.pool.name': POOL_NAME };
const count = m.createObservableUpDownCounter(
'db.client.connection.count',
{
unit: '{connection}',
description: 'Connections in the main pool by state',
},
);
const limit = m.createObservableUpDownCounter('db.client.connection.max', {
unit: '{connection}',
description: 'Maximum size of the main pool (DATABASE_POOL_MAX)',
});
const pending = m.createObservableUpDownCounter(
'db.client.connection.pending_requests',
{
unit: '{request}',
description: 'Callers waiting for a connection from the main pool',
},
);
m.addBatchObservableCallback(
(result) => {
const current = this.activePool;
const idle = current.idleCount;
result.observe(count, current.totalCount - idle, {
...pool,
'db.client.connection.state': 'used',
});
result.observe(count, idle, {
...pool,
'db.client.connection.state': 'idle',
});
result.observe(limit, max, pool);
result.observe(pending, current.waitingCount, pool);
},
[count, limit, pending],
);
}
}