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
+61 -2
View File
@@ -5,6 +5,12 @@ import {
type ConfirmChannel,
type ConsumeMessage,
} from 'amqplib';
import {
context,
propagation,
SpanKind,
type Span,
} from '@opentelemetry/api';
import {
Injectable,
Logger,
@@ -22,6 +28,8 @@ import {
JOB_ROUTING_KEY,
} from './broker.topology.js';
import type { JobMessage } from './job-message.js';
import { instruments } from '../telemetry/instruments.js';
import { markSpanError, tracer } from '../telemetry/tracing.js';
export class BrokerUnavailableError extends ServiceUnavailableException {
constructor() {
@@ -70,7 +78,58 @@ export class BrokerClient implements OnModuleDestroy {
);
}
/**
* PRODUCER span around publish + broker confirm. Its context goes into the
* AMQP headers (W3C traceparent/tracestate), so the worker's CONSUMER span
* becomes its child; the body keeps the context of the transaction that
* wrote the outbox row.
*/
async publish(message: JobMessage | Buffer): Promise<void> {
const attributes = {
'messaging.system': 'rabbitmq',
'messaging.operation.type': 'send',
'messaging.operation.name': 'publish',
'messaging.destination.name': JOB_EXCHANGE,
'messaging.rabbitmq.destination.routing_key': JOB_ROUTING_KEY,
...(Buffer.isBuffer(message)
? {}
: {
'messaging.message.id': message.job_id,
'messenger.job.id': message.job_id,
'messenger.job.attempt': message.attempt,
}),
};
return tracer().startActiveSpan(
`publish ${JOB_EXCHANGE}`,
{ kind: SpanKind.PRODUCER, attributes },
async (span: Span) => {
const traceHeaders: Record<string, string> = {};
propagation.inject(context.active(), traceHeaders);
const labels = { 'messaging.destination.name': JOB_EXCHANGE };
try {
await this.publishConfirmed(message, traceHeaders);
instruments().brokerPublished.add(1, {
...labels,
outcome: 'success',
});
} catch (error) {
instruments().brokerPublished.add(1, {
...labels,
outcome: 'failed',
});
markSpanError(span, error);
throw error;
} finally {
span.end();
}
},
);
}
private async publishConfirmed(
message: JobMessage | Buffer,
traceHeaders: Record<string, string>,
): Promise<void> {
const channel = await this.withTimeout(
this.ensureConnected(),
this.publishTimeoutMs,
@@ -85,11 +144,11 @@ export class BrokerClient implements OnModuleDestroy {
mandatory: true,
correlationId,
...(Buffer.isBuffer(message)
? {}
? { headers: traceHeaders }
: {
messageId: message.job_id,
type: message.type,
headers: { 'x-attempt': message.attempt },
headers: { 'x-attempt': message.attempt, ...traceHeaders },
}),
};
const { promise, resolve, reject } = Promise.withResolvers<void>();
+30 -16
View File
@@ -4,6 +4,20 @@ import type { PoolClient } from 'pg';
import type { AttachmentRow, VariantRow } from '../attachments/attachment.js';
import { DatabaseClient } from '../database/database.client.js';
import { buildJobMessage, type JobMessage } from './job-message.js';
import { currentTraceFields } from '../telemetry/tracing.js';
/**
* Every outbox row carries the W3C trace context of the transaction that
* wrote it (optional traceparent/tracestate of contracts/jobs.schema.json),
* so causality survives restarts of the API, the broker and the worker.
* Writers without an active span (lease reaper, reconciler, CLI) produce the
* same message as before.
*/
function tracedJobMessage(
job: Parameters<typeof buildJobMessage>[0],
): JobMessage {
return { ...buildJobMessage(job), ...currentTraceFields() };
}
export type JobStatus =
'queued' | 'processing' | 'succeeded' | 'failed' | 'superseded';
@@ -70,7 +84,7 @@ export class JobsRepository {
pipelineVersion: number,
maxAttempts: number,
): Promise<AttachmentRow | undefined> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.accept_upload', async (client) => {
const accepted = await client.query<AttachmentRow>(
`UPDATE attachments
SET status = 'queued', size_bytes = $2, sha256 = $3,
@@ -104,7 +118,7 @@ export class JobsRepository {
[
job.job_id,
JSON.stringify(
buildJobMessage({
tracedJobMessage({
...job,
created_at: job.created_at,
}),
@@ -121,7 +135,7 @@ export class JobsRepository {
workerId: string,
leaseSeconds: number,
): Promise<ClaimResult> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.claim', async (client) => {
// Lock order is always job -> attachment, matching commitSuccess and
// commitFailure. A join FOR UPDATE would let the planner choose the
// opposite order under a concurrent duplicate delivery.
@@ -240,7 +254,7 @@ export class JobsRepository {
token: string,
variants: VariantWrite[],
): Promise<CommitSuccessResult> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.commit_success', async (client) => {
const succeeded = await client.query<AttachmentJobRow>(
`UPDATE attachment_jobs
SET status = 'succeeded', lease_owner = NULL, lease_token = NULL,
@@ -325,7 +339,7 @@ export class JobsRepository {
failure: { kind: 'permanent' | 'transient'; code: string },
delayMs: number,
): Promise<CommitFailureResult> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.commit_failure', async (client) => {
const found = await client.query<AttachmentJobRow>(
`SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
@@ -389,7 +403,7 @@ export class JobsRepository {
[
job.job_id,
JSON.stringify(
buildJobMessage({ ...job, attempt: nextAttempt }),
tracedJobMessage({ ...job, attempt: nextAttempt }),
),
delayMs / 1000,
],
@@ -412,7 +426,7 @@ export class JobsRepository {
limit: number,
delayFor: (attempt: number) => number,
): Promise<number> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.reap_expired_leases', async (client) => {
const expired = await client.query<AttachmentJobRow>(
`SELECT * FROM attachment_jobs
WHERE status = 'processing' AND lease_until < now()
@@ -492,7 +506,7 @@ export class JobsRepository {
[
job.job_id,
JSON.stringify(
buildJobMessage({ ...job, attempt: nextAttempt }),
tracedJobMessage({ ...job, attempt: nextAttempt }),
),
delayMs / 1000,
],
@@ -518,7 +532,7 @@ export class JobsRepository {
limit: number,
graceSeconds: number,
): Promise<number> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.reconcile_queued', async (client) => {
const stuck = await client.query<AttachmentJobRow>(
`SELECT j.* FROM attachment_jobs j
WHERE j.status = 'queued'
@@ -546,7 +560,7 @@ export class JobsRepository {
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, now())`,
[job.job_id, JSON.stringify(buildJobMessage(job))],
[job.job_id, JSON.stringify(tracedJobMessage(job))],
);
await this.event(
client,
@@ -565,7 +579,7 @@ export class JobsRepository {
publish: (message: JobMessage) => Promise<void>,
afterPublish: () => Promise<void>,
): Promise<number> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('outbox.publish_pending', async (client) => {
const pending = await client.query<{
id: string;
payload: JobMessage;
@@ -641,7 +655,7 @@ export class JobsRepository {
key: string,
removeObject: (key: string) => Promise<void>,
): Promise<boolean> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('attachments.clear_staging', async (client) => {
// Keep the same job -> attachment lock order as claim/replay, then
// serialize cleanup with replay on the attachment row.
await client.query(
@@ -868,7 +882,7 @@ export class JobsRepository {
expectedStagingKey: string | null;
},
): Promise<ReplayResult> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.replay', async (client) => {
const found = await client.query<AttachmentJobRow>(
`SELECT * FROM attachment_jobs
WHERE attachment_id = $1 AND status = 'failed'
@@ -945,7 +959,7 @@ export class JobsRepository {
VALUES ($1, $2::jsonb, now())`,
[
job.job_id,
JSON.stringify(buildJobMessage({ ...job, attempt })),
JSON.stringify(tracedJobMessage({ ...job, attempt })),
],
);
await this.event(client, job.job_id, 'replayed', attempt, {
@@ -962,7 +976,7 @@ export class JobsRepository {
pipelineVersion: number,
options: { reason: string; operator: string; maxAttempts: number },
): Promise<ReprocessResult> {
return this.database.withTransaction(async (client) => {
return this.database.transaction('jobs.reprocess', async (client) => {
const attachment = await client.query<AttachmentRow>(
`SELECT * FROM attachments WHERE id = $1 FOR UPDATE`,
[attachmentId],
@@ -1002,7 +1016,7 @@ export class JobsRepository {
await client.query(
`INSERT INTO job_outbox (job_id, payload, available_at)
VALUES ($1, $2::jsonb, now())`,
[job.job_id, JSON.stringify(buildJobMessage(job))],
[job.job_id, JSON.stringify(tracedJobMessage(job))],
);
await this.event(client, job.job_id, 'created', 1, {
reason: options.reason,
+11 -2
View File
@@ -4,12 +4,14 @@ import {
OnApplicationBootstrap,
OnModuleDestroy,
} from '@nestjs/common';
import { context, ROOT_CONTEXT } from '@opentelemetry/api';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
import { MetricsService } from '../metrics/metrics.service.js';
import { BrokerClient } from './broker.client.js';
import { FaultInjector } from './fault-injector.js';
import { JobsRepository } from './jobs.repository.js';
import { contextFromTraceFields } from '../telemetry/tracing.js';
const BATCH_SIZE = 20;
@@ -58,7 +60,10 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
return;
}
this.running = true;
this.current = this.drain()
// A batch belongs to no particular request or job: each message carries
// its own trace context (see drain).
this.current = context
.with(ROOT_CONTEXT, () => this.drain())
.catch((error: unknown) => {
this.metrics.increment('outbox.publish_failed');
this.retryAt = Date.now() + this.retryDelayMs;
@@ -93,7 +98,11 @@ export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy {
async (message) => {
if (Date.now() - started > budgetMs)
throw new Error('outbox batch deadline exceeded');
await this.broker.publish(message);
// The PRODUCER span continues the trace of the request that wrote
// the outbox row.
await context.with(contextFromTraceFields(message), () =>
this.broker.publish(message),
);
},
() => this.faults.point('relay.after_publish_before_mark'),
);