lab6: инструментирование кода — HTTP, PostgreSQL, RabbitMQ (W3C trace context), S3, обработка задач, структурные логи

This commit is contained in:
Ilya
2026-11-09 20:38:40 +03:00
parent cf87f4dd43
commit 63dba7627c
11 changed files with 613 additions and 64 deletions
+248 -28
View File
@@ -1,8 +1,97 @@
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SpanKind, type Attributes, type Span } from '@opentelemetry/api';
import pg from 'pg';
import { MetricsService } from '../metrics/metrics.service.js';
import type { AppConfig } from '../config/app-config.schema.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;
/** First SQL keyword (SELECT, INSERT, WITH, …): a bounded attribute. */
function sqlOperation(text: string): string {
const match = /^\s*([A-Za-z]+)/u.exec(text);
return match ? match[1].toUpperCase() : 'OTHER';
}
/** Best-effort table name for span names; never used as a metric label. */
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 } : {}),
};
}
/**
* Inside a traced transaction every statement gets its own CLIENT span
* (`UPDATE attachment_jobs`, `INSERT job_outbox`, …) while repository code
* stays unaware of tracing. Transaction control, callback-style calls and
* submittables (cursors, streams) pass through untouched. SQL text and
* parameter values are never recorded.
*/
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 {
@@ -49,15 +138,44 @@ export class DatabaseClient implements OnModuleDestroy {
`PostgreSQL health connection error: ${error.message}`,
);
});
this.observePool(this.config.getOrThrow('DATABASE_POOL_MAX'));
}
/**
* Same contract as pg.Pool#query — a failed query destroys its connection —
* but the checkout is explicit, so the wait for a pooled connection is
* measured apart from the statement: «the pool is exhausted» and «the
* database is slow» are different incidents with different runbooks.
*/
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] });
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) {
failure ??=
error instanceof Error ? error : new Error('Query failed');
throw error;
} finally {
client.removeListener('error', onError);
client.release(failure);
}
},
);
}
async health(): Promise<void> {
@@ -65,41 +183,143 @@ export class DatabaseClient implements OnModuleDestroy {
await this.healthPool.query('SELECT 1');
}
async withTransaction<T>(
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) {
return this.transaction('transaction', work);
}
/**
* A labelled transaction: one span for the unit of work with a child span
* per statement and one db.client.operation.duration sample (pool wait
* included) with db.operation.name = TRANSACTION.
*/
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();
// 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('ROLLBACK');
} catch (rollbackError) {
this.metrics.increment('database.rollback_error');
this.logger.warn(
`Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`,
await client.query('BEGIN');
const result = await work(
span ? tracedClient(client, label) : 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);
}
// 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()]);
}
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.pool.connect();
} catch (error) {
failure = errorType(error);
throw error;
} finally {
instruments().dbConnectionWait.record(elapsedSeconds(started), {
'db.client.connection.pool.name': POOL_NAME,
...(failure ? { 'error.type': failure } : {}),
});
}
}
/** Pool saturation: used vs max connections and callers queued for one. */
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 idle = this.pool.idleCount;
result.observe(count, this.pool.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, this.pool.waitingCount, pool);
},
[count, limit, pending],
);
}
}