// OpenTelemetry SDK для api и worker: node --import ./src/telemetry.ts src/main.ts [worker]. // Загружается до приложения, чтобы инструментации успели перехватить http, pg и AWS SDK (ESM — через // import-in-the-middle). Экспорт traces/metrics/logs — OTLP/HTTP в Collector; адрес, протокол, service.name, // интервалы и OTEL_SDK_DISABLED задаются переменными OTEL_* (compose.yaml). Недоступный Collector не влияет на // обработку запросов: очереди SDK ограничены (BSP/BLRP 2048 записей), при переполнении данные отбрасываются. import { readFileSync } from 'node:fs'; import { register } from 'node:module'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'; import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'; import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'; import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; import { serviceTls } from './security.ts'; import { hostname } from 'node:os'; import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'; import { RuntimeNodeInstrumentation } from '@opentelemetry/instrumentation-runtime-node'; import { NodeSDK, resources } from '@opentelemetry/sdk-node'; // OTEL_SDK_DISABLED=true — ни ESM-hook, ни патчей модулей instrumentations: чистая база для сравнения. if (process.env.OTEL_SDK_DISABLED !== 'true') { register('@opentelemetry/instrumentation/hook.mjs', import.meta.url); const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')); const httpAgentOptions = { ...serviceTls(), keepAlive: true }; const sdk = new NodeSDK({ traceExporter: new OTLPTraceExporter({ httpAgentOptions }), metricReaders: [new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter({ httpAgentOptions }), exportIntervalMillis: Number(process.env.OTEL_METRIC_EXPORT_INTERVAL ?? 10000), })], logRecordProcessors: [new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ httpAgentOptions }) })], // Только явные атрибуты и OTEL_SERVICE_NAME/OTEL_RESOURCE_ATTRIBUTES: host/process detectors добавили бы // аргументы командной строки и пр. в каждую запись. service.instance.id = hostname = X-Instance-Id. resourceDetectors: [resources.envDetector], resource: resources.resourceFromAttributes({ 'service.version': version, 'service.instance.id': hostname() }), instrumentations: [ new HttpInstrumentation({ // Health-проверки HAProxy и Docker (каждую секунду) — не бизнес-трафик: без spans и без метрик. ignoreOutgoingRequestHook: ({ hostname }) => hostname === 'openbao', ignoreIncomingRequestHook: (req) => req.url?.startsWith('/health/') ?? false, // filename (пользовательский текст) и cursor не попадают в url.query server span. redactedQueryParamsServer: ['filename', 'cursor'], }), // requireParentSpan: фоновые опросы outbox/sweeper (каждые 0.5–5 с) не создают отдельных trace. // enhancedDatabaseReporting выключен: значения параметров SQL (текст сообщений, хеши) не записываются. new PgInstrumentation({ requireParentSpan: true, enhancedDatabaseReporting: false }), // Span на операцию S3 (PutObject, GetObject …) вместо дублирующего HTTP-клиентского span. new AwsInstrumentation({ suppressInternalInstrumentation: true }), new RuntimeNodeInstrumentation(), ], }); sdk.start(); // otel.ts загружается только после start(): metrics.getMeter() до регистрации провайдера вернул бы no-op meter. const { meter, onFlush } = await import('./otel.ts'); onFlush(() => sdk.shutdown()); // CPU и RSS процесса (в контейнере один процесс, поэтому это и нагрузка контейнера). meter.createObservableCounter('process.cpu.time', { unit: 's', description: 'CPU time of the process' }) .addCallback((r) => { const { user, system } = process.cpuUsage(); r.observe(user / 1e6, { 'cpu.mode': 'user' }); r.observe(system / 1e6, { 'cpu.mode': 'system' }); }); meter.createObservableGauge('process.memory.usage', { unit: 'By', description: 'Resident set size of the process' }) .addCallback((r) => r.observe(process.memoryUsage.rss())); }