forked from mtusi2026/mtusi2026lab6
feat: instrument api, relay and worker with opentelemetry
This commit is contained in:
@@ -8,6 +8,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { isDatabaseUnavailable } from '../../db/prisma.service';
|
||||
import { routeTemplate } from '../../telemetry/http';
|
||||
import { ApiError, ErrorCode } from './api-error';
|
||||
|
||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||
@@ -39,9 +40,14 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
||||
|
||||
const { status, code, message } = this.resolve(exception);
|
||||
if (status >= 500) {
|
||||
this.logger.error(
|
||||
`${request.method} ${request.url} -> ${status}: ${message}`,
|
||||
);
|
||||
this.logger.error({
|
||||
event: 'http.error',
|
||||
message,
|
||||
method: request.method,
|
||||
route: routeTemplate(request),
|
||||
status,
|
||||
request_id: requestId,
|
||||
});
|
||||
}
|
||||
|
||||
if (exception instanceof ApiError) {
|
||||
|
||||
+11
-4
@@ -1,4 +1,5 @@
|
||||
import { INestApplication, Logger } from '@nestjs/common';
|
||||
import { shutdownTelemetry } from '../telemetry/sdk';
|
||||
|
||||
let draining = false;
|
||||
|
||||
@@ -15,10 +16,16 @@ export function enableGracefulShutdown(app: INestApplication): void {
|
||||
draining = true;
|
||||
Logger.log(`${signal}: readiness → 503, closing in ${delayMs} ms`, 'Shutdown');
|
||||
setTimeout(() => {
|
||||
app.close().then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1),
|
||||
);
|
||||
app
|
||||
.close()
|
||||
.then(
|
||||
() => 0,
|
||||
() => 1,
|
||||
)
|
||||
.then(async (code) => {
|
||||
await shutdownTelemetry();
|
||||
process.exit(code);
|
||||
});
|
||||
}, delayMs);
|
||||
};
|
||||
process.once('SIGTERM', () => shutdown('SIGTERM'));
|
||||
|
||||
+31
-2
@@ -1,9 +1,18 @@
|
||||
import { context, propagation } from '@opentelemetry/api';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
|
||||
export const PIPELINE_VERSION = 1;
|
||||
export const JOB_TYPE = 'attachment.process.v1';
|
||||
|
||||
export interface JobMessage {
|
||||
const TRACEPARENT = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
|
||||
const TRACESTATE_MAX = 512;
|
||||
|
||||
export interface TraceCarrier {
|
||||
traceparent?: string;
|
||||
tracestate?: string;
|
||||
}
|
||||
|
||||
export interface JobMessage extends TraceCarrier {
|
||||
schema_version: 1;
|
||||
job_id: string;
|
||||
type: typeof JOB_TYPE;
|
||||
@@ -21,6 +30,8 @@ const FIELDS = [
|
||||
'pipeline_version',
|
||||
'attempt',
|
||||
'created_at',
|
||||
'traceparent',
|
||||
'tracestate',
|
||||
];
|
||||
|
||||
export function jobMessage(
|
||||
@@ -35,9 +46,23 @@ export function jobMessage(
|
||||
pipeline_version: job.pipelineVersion,
|
||||
attempt: job.attempt,
|
||||
created_at: createdAt.toISOString(),
|
||||
...currentTraceCarrier(),
|
||||
};
|
||||
}
|
||||
|
||||
export function currentTraceCarrier(): TraceCarrier {
|
||||
const carrier: Record<string, string> = {};
|
||||
propagation.inject(context.active(), carrier);
|
||||
const result: TraceCarrier = {};
|
||||
if (TRACEPARENT.test(carrier.traceparent ?? '')) {
|
||||
result.traceparent = carrier.traceparent;
|
||||
if (carrier.tracestate && carrier.tracestate.length <= TRACESTATE_MAX) {
|
||||
result.tracestate = carrier.tracestate;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function parseJobMessage(raw: Buffer): JobMessage | null {
|
||||
let value: any;
|
||||
try {
|
||||
@@ -61,7 +86,11 @@ export function parseJobMessage(raw: Buffer): JobMessage | null {
|
||||
!Number.isInteger(value.attempt) ||
|
||||
value.attempt < 1 ||
|
||||
typeof value.created_at !== 'string' ||
|
||||
Number.isNaN(Date.parse(value.created_at))
|
||||
Number.isNaN(Date.parse(value.created_at)) ||
|
||||
(value.traceparent !== undefined &&
|
||||
(typeof value.traceparent !== 'string' || !TRACEPARENT.test(value.traceparent))) ||
|
||||
(value.tracestate !== undefined &&
|
||||
(typeof value.tracestate !== 'string' || value.tracestate.length > TRACESTATE_MAX))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+18
-5
@@ -1,4 +1,5 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { SpanStatusCode, trace } from '@opentelemetry/api';
|
||||
import { Attachment, AttachmentJob, PrismaClient } from '@prisma/client';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
import {
|
||||
@@ -50,6 +51,8 @@ class PermanentError extends Error {
|
||||
|
||||
class TimeoutError extends Error {}
|
||||
|
||||
const tracer = trace.getTracer('messenger-worker');
|
||||
|
||||
export class JobProcessor {
|
||||
private readonly logger = new Logger('JobProcessor');
|
||||
|
||||
@@ -141,11 +144,21 @@ export class JobProcessor {
|
||||
}
|
||||
let variants: RenderedVariant[];
|
||||
try {
|
||||
variants = await renderVariants(
|
||||
original,
|
||||
this.options.maxPixels,
|
||||
Math.ceil(this.options.timeoutMs / 1000),
|
||||
);
|
||||
variants = await tracer.startActiveSpan('attachment.render_variants', async (span) => {
|
||||
span.setAttribute('messenger.image.bytes', original.length);
|
||||
try {
|
||||
return await renderVariants(
|
||||
original,
|
||||
this.options.maxPixels,
|
||||
Math.ceil(this.options.timeoutMs / 1000),
|
||||
);
|
||||
} catch (error) {
|
||||
span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.name : 'error' });
|
||||
throw error;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidImageError) {
|
||||
throw new PermanentError('invalid_image', 'image cannot be decoded');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import './telemetry/register';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import {
|
||||
@@ -8,6 +9,8 @@ import { AppModule } from './app.module';
|
||||
import { configureApp } from './configure-app';
|
||||
import { setupSwagger } from './docs/swagger';
|
||||
import { enableGracefulShutdown } from './health/shutdown';
|
||||
import { registerHttpTelemetry } from './telemetry/http';
|
||||
import { JsonLogger } from './telemetry/json-logger';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
@@ -15,10 +18,12 @@ async function bootstrap(): Promise<void> {
|
||||
new FastifyAdapter(),
|
||||
{
|
||||
bufferLogs: true,
|
||||
logger: new JsonLogger(),
|
||||
},
|
||||
);
|
||||
|
||||
configureApp(app);
|
||||
registerHttpTelemetry(app.getHttpAdapter().getInstance());
|
||||
setupSwagger(app);
|
||||
enableGracefulShutdown(app);
|
||||
|
||||
|
||||
+44
-1
@@ -1,9 +1,15 @@
|
||||
import './telemetry/register';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { propagation, ROOT_CONTEXT, Span, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
|
||||
import { ConfirmChannel } from 'amqplib';
|
||||
import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker';
|
||||
import { PrismaService } from './db/prisma.service';
|
||||
import { JobMessage } from './jobs/job-message';
|
||||
import { recoverExpiredLeases, republishStale } from './jobs/job-store';
|
||||
import { JsonLogger } from './telemetry/json-logger';
|
||||
import { shutdownTelemetry } from './telemetry/sdk';
|
||||
|
||||
Logger.overrideLogger(new JsonLogger());
|
||||
|
||||
const BATCH_SIZE = 100;
|
||||
const POLL_MS = Number(process.env.RELAY_POLL_MS ?? 500);
|
||||
@@ -13,8 +19,29 @@ const FAULT = process.env.RELAY_FAULT;
|
||||
|
||||
const logger = new Logger('OutboxRelay');
|
||||
const prisma = new PrismaService();
|
||||
const tracer = trace.getTracer('messenger-relay');
|
||||
let stopping = false;
|
||||
|
||||
function startPublishSpan(payload: JobMessage, headers: Record<string, string>): Span {
|
||||
const parent = propagation.extract(ROOT_CONTEXT, payload);
|
||||
const span = tracer.startSpan(
|
||||
`${JOB_QUEUE} publish`,
|
||||
{
|
||||
kind: SpanKind.PRODUCER,
|
||||
attributes: {
|
||||
'messaging.system': 'rabbitmq',
|
||||
'messaging.operation.type': 'publish',
|
||||
'messaging.destination.name': JOB_QUEUE,
|
||||
'messaging.message.id': payload.job_id,
|
||||
'messaging.job.attempt': payload.attempt,
|
||||
},
|
||||
},
|
||||
parent,
|
||||
);
|
||||
propagation.inject(trace.setSpan(parent, span), headers);
|
||||
return span;
|
||||
}
|
||||
|
||||
async function publishBatch(channel: ConfirmChannel): Promise<number> {
|
||||
return prisma.$transaction(
|
||||
async (tx) => {
|
||||
@@ -27,15 +54,30 @@ async function publishBatch(channel: ConfirmChannel): Promise<number> {
|
||||
if (rows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const spans: Span[] = [];
|
||||
for (const { payload } of rows) {
|
||||
const headers: Record<string, string> = {};
|
||||
spans.push(startPublishSpan(payload, headers));
|
||||
channel.sendToQueue(JOB_QUEUE, Buffer.from(JSON.stringify(payload)), {
|
||||
persistent: true,
|
||||
contentType: 'application/json',
|
||||
messageId: payload.job_id,
|
||||
type: payload.type,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
await channel.waitForConfirms();
|
||||
try {
|
||||
await channel.waitForConfirms();
|
||||
} catch (error) {
|
||||
for (const span of spans) {
|
||||
span.setStatus({ code: SpanStatusCode.ERROR, message: 'broker did not confirm' });
|
||||
span.end();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
for (const span of spans) {
|
||||
span.end();
|
||||
}
|
||||
logger.log(`published ${rows.length} job message(s), broker confirmed`);
|
||||
if (FAULT === 'exit-after-confirm') {
|
||||
logger.warn('fault injection: exit after broker confirm, before outbox is marked');
|
||||
@@ -121,6 +163,7 @@ run()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
logger.log('stopped');
|
||||
await shutdownTelemetry();
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { metrics, trace } from '@opentelemetry/api';
|
||||
import { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
|
||||
export const LATENCY_BUCKETS = [
|
||||
0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 2.5, 5, 10,
|
||||
];
|
||||
|
||||
const METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']);
|
||||
|
||||
const meter = metrics.getMeter('messenger-api');
|
||||
const requests = meter.createCounter('http.server.requests', {
|
||||
description: 'HTTP requests by method, route template and status class',
|
||||
});
|
||||
const duration = meter.createHistogram('http.server.request.duration', {
|
||||
description: 'HTTP request duration',
|
||||
unit: 's',
|
||||
advice: { explicitBucketBoundaries: LATENCY_BUCKETS },
|
||||
});
|
||||
const logger = new Logger('Http');
|
||||
|
||||
export function routeTemplate(request: FastifyRequest): string {
|
||||
const url = request.routeOptions?.url;
|
||||
return url
|
||||
? url.replace(/:([A-Za-z0-9_]+)/g, (_, name: string) => `{${name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)}}`)
|
||||
: 'unmatched';
|
||||
}
|
||||
|
||||
export function registerHttpTelemetry(instance: FastifyInstance): void {
|
||||
instance.addHook('onRequest', (request, _reply, done) => {
|
||||
const span = trace.getActiveSpan();
|
||||
if (span) {
|
||||
const route = routeTemplate(request);
|
||||
span.updateName(`${methodOf(request)} ${route}`);
|
||||
span.setAttribute('http.route', route);
|
||||
span.setAttribute('messenger.request_id', request.requestId);
|
||||
}
|
||||
done();
|
||||
});
|
||||
instance.addHook('onResponse', (request, reply, done) => {
|
||||
const route = routeTemplate(request);
|
||||
const method = methodOf(request);
|
||||
const attributes = {
|
||||
'http.request.method': method,
|
||||
'http.route': route,
|
||||
'http.response.status_class': `${Math.floor(reply.statusCode / 100)}xx`,
|
||||
};
|
||||
requests.add(1, attributes);
|
||||
duration.record(reply.elapsedTime / 1000, attributes);
|
||||
if (!route.startsWith('/health')) {
|
||||
logger.log({
|
||||
event: 'http.request',
|
||||
method,
|
||||
route,
|
||||
status: reply.statusCode,
|
||||
duration_ms: Math.round(reply.elapsedTime * 100) / 100,
|
||||
request_id: request.requestId,
|
||||
});
|
||||
}
|
||||
done();
|
||||
});
|
||||
}
|
||||
|
||||
function methodOf(request: FastifyRequest): string {
|
||||
return METHODS.has(request.method) ? request.method : '_OTHER';
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { LoggerService } from '@nestjs/common';
|
||||
import { trace, TraceFlags } from '@opentelemetry/api';
|
||||
import { AnyValueMap, logs, SeverityNumber } from '@opentelemetry/api-logs';
|
||||
|
||||
type Level = 'fatal' | 'error' | 'warn' | 'log' | 'debug' | 'verbose';
|
||||
|
||||
const SEVERITY: Record<Level, [SeverityNumber, string]> = {
|
||||
fatal: [SeverityNumber.FATAL, 'FATAL'],
|
||||
error: [SeverityNumber.ERROR, 'ERROR'],
|
||||
warn: [SeverityNumber.WARN, 'WARN'],
|
||||
log: [SeverityNumber.INFO, 'INFO'],
|
||||
debug: [SeverityNumber.DEBUG, 'DEBUG'],
|
||||
verbose: [SeverityNumber.TRACE, 'TRACE'],
|
||||
};
|
||||
|
||||
type Field = string | number | boolean;
|
||||
|
||||
export class JsonLogger implements LoggerService {
|
||||
private readonly otel = logs.getLogger('messenger');
|
||||
|
||||
constructor(private readonly service = process.env.OTEL_SERVICE_NAME ?? 'messenger') {}
|
||||
|
||||
fatal(message: unknown, ...params: unknown[]): void {
|
||||
this.write('fatal', message, params);
|
||||
}
|
||||
|
||||
error(message: unknown, ...params: unknown[]): void {
|
||||
this.write('error', message, params);
|
||||
}
|
||||
|
||||
warn(message: unknown, ...params: unknown[]): void {
|
||||
this.write('warn', message, params);
|
||||
}
|
||||
|
||||
log(message: unknown, ...params: unknown[]): void {
|
||||
this.write('log', message, params);
|
||||
}
|
||||
|
||||
debug(message: unknown, ...params: unknown[]): void {
|
||||
this.write('debug', message, params);
|
||||
}
|
||||
|
||||
verbose(message: unknown, ...params: unknown[]): void {
|
||||
this.write('verbose', message, params);
|
||||
}
|
||||
|
||||
private write(level: Level, message: unknown, params: unknown[]): void {
|
||||
const last = params[params.length - 1];
|
||||
const logger = typeof last === 'string' ? last : 'app';
|
||||
const fields = toFields(message);
|
||||
const event = typeof fields.event === 'string' ? fields.event : eventName(logger);
|
||||
delete fields.event;
|
||||
const [severityNumber, severityText] = SEVERITY[level];
|
||||
const active = trace.getActiveSpan()?.spanContext();
|
||||
const span = active && active.traceFlags & TraceFlags.SAMPLED ? active : undefined;
|
||||
const line = JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
severity: severityText,
|
||||
'service.name': this.service,
|
||||
event,
|
||||
logger,
|
||||
...fields,
|
||||
trace_id: span?.traceId,
|
||||
span_id: span?.spanId,
|
||||
});
|
||||
process.stdout.write(line + '\n');
|
||||
const attributes: AnyValueMap = { event, logger };
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
if (key !== 'message') {
|
||||
attributes[key] = value;
|
||||
}
|
||||
}
|
||||
this.otel.emit({
|
||||
severityNumber,
|
||||
severityText,
|
||||
body: line,
|
||||
attributes,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function toFields(message: unknown): Record<string, Field> {
|
||||
if (typeof message === 'object' && message !== null && !(message instanceof Error)) {
|
||||
const fields: Record<string, Field> = {};
|
||||
for (const [key, value] of Object.entries(message)) {
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
fields[key] = value;
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
return { message: message instanceof Error ? message.message : String(message) };
|
||||
}
|
||||
|
||||
function eventName(logger: string): string {
|
||||
return logger
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
||||
.toLowerCase();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { startTelemetry } from './sdk';
|
||||
|
||||
startTelemetry();
|
||||
@@ -0,0 +1,157 @@
|
||||
import { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
|
||||
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';
|
||||
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';
|
||||
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
|
||||
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
|
||||
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
||||
import { envDetectorSync, Resource } from '@opentelemetry/resources';
|
||||
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
|
||||
import {
|
||||
DropAggregation,
|
||||
PeriodicExportingMetricReader,
|
||||
View,
|
||||
} from '@opentelemetry/sdk-metrics';
|
||||
import { NodeSDK } from '@opentelemetry/sdk-node';
|
||||
import {
|
||||
BatchSpanProcessor,
|
||||
ParentBasedSampler,
|
||||
Sampler,
|
||||
SamplingDecision,
|
||||
SamplingResult,
|
||||
} from '@opentelemetry/sdk-trace-base';
|
||||
import { PrismaInstrumentation } from '@prisma/instrumentation';
|
||||
import { readFileSync } from 'fs';
|
||||
import { IncomingMessage } from 'http';
|
||||
import { hostname } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
const EXPORT_TIMEOUT_MS = 5000;
|
||||
|
||||
const NOISY_LEAF_SPANS = new Set([
|
||||
'prisma:client:serialize',
|
||||
'prisma:engine:serialize',
|
||||
'prisma:engine:response_json_serialization',
|
||||
'prisma:engine:connection',
|
||||
]);
|
||||
|
||||
const NOT_RECORDED: SamplingResult = { decision: SamplingDecision.NOT_RECORD };
|
||||
|
||||
class SkipRootDatabaseSpans implements Sampler {
|
||||
shouldSample(
|
||||
_context: Context,
|
||||
_traceId: string,
|
||||
name: string,
|
||||
): SamplingResult {
|
||||
return name.startsWith('prisma:')
|
||||
? NOT_RECORDED
|
||||
: { decision: SamplingDecision.RECORD_AND_SAMPLED };
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return 'SkipRootDatabaseSpans';
|
||||
}
|
||||
}
|
||||
|
||||
class MessengerSampler implements Sampler {
|
||||
private readonly parentBased = new ParentBasedSampler({ root: new SkipRootDatabaseSpans() });
|
||||
|
||||
shouldSample(
|
||||
context: Context,
|
||||
traceId: string,
|
||||
name: string,
|
||||
kind: SpanKind,
|
||||
attributes: Attributes,
|
||||
links: Link[],
|
||||
): SamplingResult {
|
||||
if (NOISY_LEAF_SPANS.has(name)) {
|
||||
return NOT_RECORDED;
|
||||
}
|
||||
return this.parentBased.shouldSample(context, traceId, name, kind, attributes, links);
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return 'MessengerSampler';
|
||||
}
|
||||
}
|
||||
|
||||
let sdk: NodeSDK | null = null;
|
||||
|
||||
export function telemetryEnabled(): boolean {
|
||||
return Boolean(process.env.OTEL_EXPORTER_OTLP_ENDPOINT) && process.env.OTEL_SDK_DISABLED !== 'true';
|
||||
}
|
||||
|
||||
export function startTelemetry(): void {
|
||||
if (!telemetryEnabled() || sdk) {
|
||||
return;
|
||||
}
|
||||
sdk = new NodeSDK({
|
||||
resource: new Resource({
|
||||
'service.version': serviceVersion(),
|
||||
'service.instance.id': process.env.INSTANCE_ID ?? hostname(),
|
||||
}),
|
||||
resourceDetectors: [envDetectorSync],
|
||||
sampler: new MessengerSampler(),
|
||||
spanProcessors: [
|
||||
new BatchSpanProcessor(new OTLPTraceExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }), {
|
||||
maxQueueSize: 2048,
|
||||
maxExportBatchSize: 512,
|
||||
exportTimeoutMillis: EXPORT_TIMEOUT_MS,
|
||||
}),
|
||||
],
|
||||
logRecordProcessors: [
|
||||
new BatchLogRecordProcessor(new OTLPLogExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }), {
|
||||
maxQueueSize: 2048,
|
||||
maxExportBatchSize: 512,
|
||||
exportTimeoutMillis: EXPORT_TIMEOUT_MS,
|
||||
}),
|
||||
],
|
||||
metricReader: new PeriodicExportingMetricReader({
|
||||
exporter: new OTLPMetricExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }),
|
||||
exportIntervalMillis: 10000,
|
||||
exportTimeoutMillis: EXPORT_TIMEOUT_MS,
|
||||
}),
|
||||
views: [
|
||||
new View({
|
||||
meterName: '@opentelemetry/instrumentation-http',
|
||||
aggregation: new DropAggregation(),
|
||||
}),
|
||||
],
|
||||
instrumentations: [
|
||||
new HttpInstrumentation({
|
||||
ignoreIncomingRequestHook: (request) => (request.url ?? '').startsWith('/health'),
|
||||
ignoreOutgoingRequestHook: () => true,
|
||||
requestHook: (span, request) => {
|
||||
if (request instanceof IncomingMessage) {
|
||||
const path = (request.url ?? '/').split('?')[0];
|
||||
span.setAttribute('http.target', path);
|
||||
span.setAttribute('http.url', path);
|
||||
}
|
||||
},
|
||||
}),
|
||||
new AwsInstrumentation({ suppressInternalInstrumentation: true }),
|
||||
new PrismaInstrumentation(),
|
||||
],
|
||||
});
|
||||
sdk.start();
|
||||
}
|
||||
|
||||
export async function shutdownTelemetry(): Promise<void> {
|
||||
if (!sdk) {
|
||||
return;
|
||||
}
|
||||
const current = sdk;
|
||||
sdk = null;
|
||||
await Promise.race([
|
||||
current.shutdown().catch(() => undefined),
|
||||
new Promise((resolve) => setTimeout(resolve, EXPORT_TIMEOUT_MS)),
|
||||
]);
|
||||
}
|
||||
|
||||
function serviceVersion(): string {
|
||||
try {
|
||||
const raw = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8');
|
||||
return String(JSON.parse(raw).version);
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
+95
-15
@@ -1,10 +1,25 @@
|
||||
import './telemetry/register';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import {
|
||||
context,
|
||||
Context,
|
||||
metrics,
|
||||
propagation,
|
||||
ROOT_CONTEXT,
|
||||
SpanKind,
|
||||
SpanStatusCode,
|
||||
trace,
|
||||
} from '@opentelemetry/api';
|
||||
import { Channel, ConsumeMessage } from 'amqplib';
|
||||
import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker';
|
||||
import { PrismaService } from './db/prisma.service';
|
||||
import { parseJobMessage } from './jobs/job-message';
|
||||
import { JOB_TYPE, JobMessage, parseJobMessage } from './jobs/job-message';
|
||||
import { JobProcessor, ProcessorHooks, processorOptions } from './jobs/processor';
|
||||
import { S3Service } from './storage/s3.service';
|
||||
import { JsonLogger } from './telemetry/json-logger';
|
||||
import { shutdownTelemetry } from './telemetry/sdk';
|
||||
|
||||
Logger.overrideLogger(new JsonLogger());
|
||||
|
||||
const CONCURRENCY = Number(process.env.WORKER_CONCURRENCY ?? 2);
|
||||
const INFRA_RETRY_MS = Number(process.env.WORKER_INFRA_RETRY_MS ?? 5000);
|
||||
@@ -18,6 +33,27 @@ const processor = new JobProcessor(prisma, s3, processorOptions(), faultHooks())
|
||||
let stopping = false;
|
||||
let inFlight = 0;
|
||||
|
||||
const JOB_BUCKETS = [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 2.5, 5, 10, 30, 60, 120];
|
||||
|
||||
const tracer = trace.getTracer('messenger-worker');
|
||||
const meter = metrics.getMeter('messenger-worker');
|
||||
const jobsProcessed = meter.createCounter('jobs.processed', {
|
||||
description: 'Job deliveries handled by the worker, by job type and outcome',
|
||||
});
|
||||
const jobDuration = meter.createHistogram('jobs.duration', {
|
||||
description: 'Job delivery handling duration',
|
||||
unit: 's',
|
||||
advice: { explicitBucketBoundaries: JOB_BUCKETS },
|
||||
});
|
||||
|
||||
function parentContext(delivery: ConsumeMessage, message: JobMessage | null): Context {
|
||||
const headers = delivery.properties.headers ?? {};
|
||||
if (typeof headers.traceparent === 'string') {
|
||||
return propagation.extract(ROOT_CONTEXT, headers);
|
||||
}
|
||||
return message ? propagation.extract(ROOT_CONTEXT, message) : ROOT_CONTEXT;
|
||||
}
|
||||
|
||||
function faultHooks(): ProcessorHooks {
|
||||
const crash = (point: string) => async () => {
|
||||
logger.warn(`fault injection: worker killed ${point}`);
|
||||
@@ -34,31 +70,74 @@ function faultHooks(): ProcessorHooks {
|
||||
|
||||
async function handle(channel: Channel, delivery: ConsumeMessage): Promise<void> {
|
||||
inFlight++;
|
||||
const started = performance.now();
|
||||
const message = parseJobMessage(delivery.content);
|
||||
const span = tracer.startSpan(
|
||||
`${JOB_QUEUE} process`,
|
||||
{
|
||||
kind: SpanKind.CONSUMER,
|
||||
attributes: {
|
||||
'messaging.system': 'rabbitmq',
|
||||
'messaging.operation.type': 'process',
|
||||
'messaging.destination.name': JOB_QUEUE,
|
||||
'messaging.message.id': message?.job_id ?? 'malformed',
|
||||
'messaging.rabbitmq.redelivered': delivery.fields.redelivered,
|
||||
'messaging.job.attempt': message?.attempt ?? 0,
|
||||
},
|
||||
},
|
||||
parentContext(delivery, message),
|
||||
);
|
||||
const active = trace.setSpan(context.active(), span);
|
||||
let outcome = 'interrupted';
|
||||
let requeue = false;
|
||||
try {
|
||||
const message = parseJobMessage(delivery.content);
|
||||
if (!message) {
|
||||
logger.warn('malformed job message moved to dead letter queue');
|
||||
channel.nack(delivery, false, false);
|
||||
return;
|
||||
await context.with(active, async () => {
|
||||
if (!message) {
|
||||
outcome = 'malformed';
|
||||
logger.warn('malformed job message moved to dead letter queue');
|
||||
channel.nack(delivery, false, false);
|
||||
return;
|
||||
}
|
||||
const result = await processor.handle(message);
|
||||
outcome = result === 'ready' ? 'success' : result;
|
||||
logger.log({
|
||||
event: 'job.handled',
|
||||
job_id: message.job_id,
|
||||
attachment_id: message.attachment_id,
|
||||
attempt: message.attempt,
|
||||
redelivered: delivery.fields.redelivered,
|
||||
outcome,
|
||||
duration_ms: Math.round(performance.now() - started),
|
||||
});
|
||||
channel.ack(delivery);
|
||||
});
|
||||
span.setAttribute('messenger.job.outcome', outcome);
|
||||
if (outcome === 'failed' || outcome === 'malformed') {
|
||||
span.setStatus({ code: SpanStatusCode.ERROR, message: outcome });
|
||||
}
|
||||
const outcome = await processor.handle(message);
|
||||
logger.log(
|
||||
`job ${message.job_id} attempt ${message.attempt}` +
|
||||
`${delivery.fields.redelivered ? ' (redelivered)' : ''}: ${outcome}`,
|
||||
);
|
||||
channel.ack(delivery);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`);
|
||||
span.setAttribute('messenger.job.outcome', outcome);
|
||||
span.setStatus({ code: SpanStatusCode.ERROR, message: reason });
|
||||
context.with(active, () =>
|
||||
logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`),
|
||||
);
|
||||
requeue = true;
|
||||
} finally {
|
||||
span.end();
|
||||
const attributes = { 'job.type': JOB_TYPE, outcome };
|
||||
jobsProcessed.add(1, attributes);
|
||||
jobDuration.record((performance.now() - started) / 1000, attributes);
|
||||
}
|
||||
if (requeue) {
|
||||
await sleep(INFRA_RETRY_MS);
|
||||
try {
|
||||
channel.nack(delivery, false, true);
|
||||
} catch {
|
||||
logger.warn('channel closed, broker will redeliver unacked message');
|
||||
}
|
||||
} finally {
|
||||
inFlight--;
|
||||
}
|
||||
inFlight--;
|
||||
}
|
||||
|
||||
async function run(): Promise<void> {
|
||||
@@ -129,6 +208,7 @@ run()
|
||||
await prisma.$disconnect();
|
||||
s3.onModuleDestroy();
|
||||
logger.log('stopped');
|
||||
await shutdownTelemetry();
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
Reference in New Issue
Block a user