@rsdk/cli.cmd.start 5.11.5 → 5.11.6-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/opentelemetry/exporter.d.ts +8 -0
  2. package/dist/opentelemetry/exporter.js +69 -0
  3. package/dist/opentelemetry/exporter.js.map +1 -0
  4. package/dist/opentelemetry/opentelemetry.init.js +49 -26
  5. package/dist/opentelemetry/opentelemetry.init.js.map +1 -1
  6. package/dist/opentelemetry/otlp-exporter.d.ts +6 -0
  7. package/dist/opentelemetry/otlp-exporter.js +21 -0
  8. package/dist/opentelemetry/otlp-exporter.js.map +1 -0
  9. package/dist/opentelemetry/profiling.context-manager.d.ts +6 -0
  10. package/dist/opentelemetry/profiling.context-manager.js +87 -0
  11. package/dist/opentelemetry/profiling.context-manager.js.map +1 -0
  12. package/dist/opentelemetry/prom-metrics.type.d.ts +2 -0
  13. package/dist/opentelemetry/prom-metrics.type.js +3 -0
  14. package/dist/opentelemetry/prom-metrics.type.js.map +1 -0
  15. package/dist/opentelemetry/propagators.d.ts +5 -0
  16. package/dist/opentelemetry/propagators.js +34 -0
  17. package/dist/opentelemetry/propagators.js.map +1 -0
  18. package/dist/otel-convertors/counter.convertor.d.ts +6 -0
  19. package/dist/otel-convertors/counter.convertor.js +25 -0
  20. package/dist/otel-convertors/counter.convertor.js.map +1 -0
  21. package/dist/otel-convertors/data-points.d.ts +4 -0
  22. package/dist/otel-convertors/data-points.js +15 -0
  23. package/dist/otel-convertors/data-points.js.map +1 -0
  24. package/dist/otel-convertors/gauge.convertor.d.ts +6 -0
  25. package/dist/otel-convertors/gauge.convertor.js +24 -0
  26. package/dist/otel-convertors/gauge.convertor.js.map +1 -0
  27. package/dist/otel-convertors/histogram.convertor.d.ts +6 -0
  28. package/dist/otel-convertors/histogram.convertor.js +81 -0
  29. package/dist/otel-convertors/histogram.convertor.js.map +1 -0
  30. package/dist/otel-convertors/index.d.ts +4 -0
  31. package/dist/otel-convertors/index.js +21 -0
  32. package/dist/otel-convertors/index.js.map +1 -0
  33. package/dist/otel-convertors/summary.convertor.d.ts +6 -0
  34. package/dist/otel-convertors/summary.convertor.js +69 -0
  35. package/dist/otel-convertors/summary.convertor.js.map +1 -0
  36. package/dist/profiling/profiling.d.ts +10 -0
  37. package/dist/profiling/profiling.js +34 -0
  38. package/dist/profiling/profiling.js.map +1 -0
  39. package/dist/start-dev.cmd.d.ts +1 -1
  40. package/dist/start-dev.cmd.js +17 -3
  41. package/dist/start-dev.cmd.js.map +1 -1
  42. package/dist/start.cmd.d.ts +1 -1
  43. package/dist/start.cmd.js +12 -2
  44. package/dist/start.cmd.js.map +1 -1
  45. package/jest.config.js +1 -0
  46. package/package.json +21 -4
  47. package/src/opentelemetry/exporter.spec.ts +220 -0
  48. package/src/opentelemetry/exporter.ts +88 -0
  49. package/src/opentelemetry/opentelemetry.init.ts +60 -29
  50. package/src/opentelemetry/otlp-exporter.spec.ts +66 -0
  51. package/src/opentelemetry/otlp-exporter.ts +28 -0
  52. package/src/opentelemetry/profiling.context-manager.spec.ts +93 -0
  53. package/src/opentelemetry/profiling.context-manager.ts +118 -0
  54. package/src/opentelemetry/prom-metrics.type.ts +9 -0
  55. package/src/opentelemetry/propagators.spec.ts +67 -0
  56. package/src/opentelemetry/propagators.ts +35 -0
  57. package/src/otel-convertors/counter.convertor.ts +34 -0
  58. package/src/otel-convertors/data-points.ts +19 -0
  59. package/src/otel-convertors/gauge.convertor.ts +33 -0
  60. package/src/otel-convertors/histogram.convertor.ts +121 -0
  61. package/src/otel-convertors/index.ts +4 -0
  62. package/src/otel-convertors/summary.convertor.ts +86 -0
  63. package/src/profiling/profiling.ts +37 -0
  64. package/src/start-dev.cmd.ts +24 -2
  65. package/src/start.cmd.ts +21 -1
@@ -0,0 +1,88 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import { millisToHrTime } from '@opentelemetry/core';
3
+ import { Resource } from '@opentelemetry/resources';
4
+ import type {
5
+ CollectionResult,
6
+ MetricData,
7
+ MetricProducer,
8
+ } from '@opentelemetry/sdk-metrics';
9
+ import { type Registry } from 'prom-client';
10
+
11
+ import {
12
+ CounterConvertor,
13
+ GaugeConvertor,
14
+ HistogramConvertor,
15
+ SummaryConvertor,
16
+ } from '../otel-convertors';
17
+
18
+ import type { PromMetricWithValues } from './prom-metrics.type';
19
+
20
+ // prom-client не хранит время старта серий, все они считаются со старта процесса
21
+ const PROCESS_START_TIME = millisToHrTime(Date.now() - process.uptime() * 1000);
22
+
23
+ export class PromClientMetricProducer implements MetricProducer {
24
+ constructor(private readonly registry: () => Registry) {}
25
+
26
+ async collect(): Promise<CollectionResult> {
27
+ const metrics: MetricData[] = [];
28
+ const errors: unknown[] = [];
29
+
30
+ try {
31
+ const promMetrics = await this.registry().getMetricsAsJSON();
32
+ const endTime = millisToHrTime(Date.now());
33
+
34
+ for (const pm of promMetrics) {
35
+ try {
36
+ metrics.push(...this.convertPromMetricsToOtel(pm, endTime));
37
+ } catch (error) {
38
+ errors.push(error);
39
+ }
40
+ }
41
+ } catch (error) {
42
+ // если бросить, reader не отправит и метрики SDK: он собирает их в одном Promise.all
43
+ errors.push(error);
44
+ }
45
+
46
+ return {
47
+ resourceMetrics: {
48
+ // SDK игнорирует ресурс producer и подставляет свой
49
+ resource: Resource.empty(),
50
+ scopeMetrics: [
51
+ {
52
+ scope: { name: 'prom-client' },
53
+ metrics: metrics.filter((m) => m.dataPoints.length > 0),
54
+ },
55
+ ],
56
+ },
57
+ errors,
58
+ };
59
+ }
60
+
61
+ private convertPromMetricsToOtel(
62
+ promMetrics: PromMetricWithValues,
63
+ endTime: HrTime,
64
+ ): MetricData[] {
65
+ switch (promMetrics.type as unknown as string) {
66
+ case 'counter':
67
+ return [
68
+ CounterConvertor.toOtel(promMetrics, PROCESS_START_TIME, endTime),
69
+ ];
70
+ case 'gauge':
71
+ return [
72
+ GaugeConvertor.toOtel(promMetrics, PROCESS_START_TIME, endTime),
73
+ ];
74
+ case 'histogram':
75
+ return [
76
+ HistogramConvertor.toOtel(promMetrics, PROCESS_START_TIME, endTime),
77
+ ];
78
+ case 'summary':
79
+ return SummaryConvertor.toOtel(
80
+ promMetrics,
81
+ PROCESS_START_TIME,
82
+ endTime,
83
+ );
84
+ default:
85
+ return [];
86
+ }
87
+ }
88
+ }
@@ -2,10 +2,12 @@
2
2
  import type { Span } from '@opentelemetry/api';
3
3
  import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
4
4
  import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
5
- import { CompositePropagator } from '@opentelemetry/core';
6
- import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
7
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
8
- import { B3InjectEncoding, B3Propagator } from '@opentelemetry/propagator-b3';
5
+ import { OTLPMetricExporter as GrpcMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
6
+ import { OTLPMetricExporter as JsonMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
7
+ import { OTLPMetricExporter as ProtobufMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';
8
+ import { OTLPTraceExporter as GrpcTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
9
+ import { OTLPTraceExporter as JsonTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
10
+ import { OTLPTraceExporter as ProtobufTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
9
11
  import { containerDetector } from '@opentelemetry/resource-detector-container';
10
12
  import {
11
13
  envDetector,
@@ -20,9 +22,16 @@ import {
20
22
  ATTR_SERVICE_NAME,
21
23
  ATTR_SERVICE_VERSION,
22
24
  } from '@opentelemetry/semantic-conventions';
25
+ import { onProcessShutdown } from '@rsdk/common.node';
23
26
  import { ClientRequest, IncomingMessage } from 'node:http';
24
27
  import path from 'node:path';
25
28
  import { cwd } from 'node:process';
29
+ import type { Registry } from 'prom-client';
30
+
31
+ import { PromClientMetricProducer } from './exporter';
32
+ import { otlpExporter } from './otlp-exporter';
33
+ import { createProfilingContextManager } from './profiling.context-manager';
34
+ import { normalizePropagatorsEnv } from './propagators';
26
35
 
27
36
  const otelDiagLogLevel = process.env.OTEL_DIAG_LOG_LEVEL;
28
37
  if (otelDiagLogLevel) {
@@ -85,6 +94,9 @@ const autoInstumentationOptions: any[] = getNodeAutoInstrumentations({
85
94
  },
86
95
  '@opentelemetry/instrumentation-pino': {
87
96
  enabled: true,
97
+
98
+ // логи отправляет transport (LOG_OTEL_ENABLED), иначе они дублируются
99
+ disableLogSending: true,
88
100
  logHook(_span: Span, record: Record<string, any>) {
89
101
  record['resource.service.name'] = otelServiceName;
90
102
  },
@@ -99,33 +111,63 @@ const autoInstumentationOptions: any[] = getNodeAutoInstrumentations({
99
111
 
100
112
  const otelServiceName = process.env.OTEL_SERVICE_NAME ?? manifestData.name;
101
113
 
102
- const textMapPropagator = new CompositePropagator({
103
- propagators: [
104
- new B3Propagator(),
105
- new B3Propagator({
106
- injectEncoding: B3InjectEncoding.MULTI_HEADER,
107
- }),
108
- ],
109
- });
114
+ // без него transport отправляет логи с service.name=unknown_service
115
+ process.env.LOG_OTEL_SERVICE_NAME ??= otelServiceName;
116
+
117
+ normalizePropagatorsEnv(process.env);
110
118
 
111
119
  const resource = new Resource({
112
120
  [ATTR_SERVICE_NAME]: otelServiceName,
113
121
  [ATTR_SERVICE_VERSION]: manifestData.version,
114
122
  });
115
123
 
116
- const traceExporter = new OTLPTraceExporter();
117
- const metricExporter = new OTLPMetricExporter();
124
+ // registry берем у prom-client из @rsdk/core приложения: у копии из CLI он свой
125
+ const appMetricsRegistry = (): Registry => {
126
+ const corePath = require.resolve('@rsdk/core', { paths: [cwd()] });
127
+ const promClientPath = require.resolve('prom-client', {
128
+ paths: [path.dirname(corePath)],
129
+ });
130
+
131
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
132
+ return require(promClientPath).register;
133
+ };
134
+
135
+ // NodeSDK читает OTEL_METRIC_EXPORT_* только для своего reader'а, а этот создан вручную
136
+ const envMillis = (name: string): number | undefined =>
137
+ Number.parseInt(process.env[name] ?? '') || undefined;
138
+ const exportIntervalMillis = envMillis('OTEL_METRIC_EXPORT_INTERVAL');
139
+ const exportTimeoutMillis = envMillis('OTEL_METRIC_EXPORT_TIMEOUT');
140
+
141
+ // exporter метрик NodeSDK выбирает по протоколу только для своего reader'а, а наш
142
+ // создан вручную. Exporter трейсов выбирается тем же кодом
143
+ const traceExporter = otlpExporter('TRACES', {
144
+ grpc: GrpcTraceExporter,
145
+ 'http/json': JsonTraceExporter,
146
+ 'http/protobuf': ProtobufTraceExporter,
147
+ });
148
+ const metricExporter = otlpExporter('METRICS', {
149
+ grpc: GrpcMetricExporter,
150
+ 'http/json': JsonMetricExporter,
151
+ 'http/protobuf': ProtobufMetricExporter,
152
+ });
118
153
  const metricReader = new PeriodicExportingMetricReader({
119
154
  exporter: metricExporter,
155
+ ...(exportIntervalMillis === undefined ? {} : { exportIntervalMillis }),
156
+ ...(exportTimeoutMillis === undefined ? {} : { exportTimeoutMillis }),
157
+ metricProducers: [new PromClientMetricProducer(appMetricsRegistry)],
120
158
  });
121
159
 
160
+ // прелоад профилирования подключается раньше и уже зарегистрировал связь
161
+ // профилей со спанами
162
+ const contextManager = createProfilingContextManager();
163
+
122
164
  const sdk = new NodeSDK({
123
165
  serviceName: otelServiceName,
124
166
  instrumentations: [autoInstumentationOptions],
125
167
  resource,
126
168
  traceExporter,
127
169
  metricReader,
128
- textMapPropagator,
170
+ ...(contextManager && { contextManager }),
129
171
  resourceDetectors: [
130
172
  containerDetector,
131
173
  envDetector,
@@ -138,23 +180,12 @@ const sdk = new NodeSDK({
138
180
  sdk.start();
139
181
  console.log('Tracing sdk started');
140
182
 
141
- const signals = ['SIGTERM', 'SIGINT'] as const;
142
-
143
- const listener: any = async () => {
183
+ onProcessShutdown(async (signal) => {
144
184
  try {
145
- console.log('[SIGTERM] Tracing terminating...');
185
+ console.log(`[${signal}] Tracing terminating...`);
146
186
  await sdk.shutdown();
147
187
  console.log('Tracing terminated');
148
188
  } catch (error) {
149
189
  console.log('Error terminating tracing', error);
150
- // eslint-disable-next-line unicorn/no-process-exit
151
- process.exit(1);
152
- } finally {
153
- // eslint-disable-next-line unicorn/no-process-exit
154
- process.exit(0);
155
190
  }
156
- };
157
-
158
- for (const signal of signals) {
159
- process.on(signal, listener);
160
- }
191
+ });
@@ -0,0 +1,66 @@
1
+ import { otlpExporter } from './otlp-exporter';
2
+
3
+ class GrpcExporter {}
4
+ class JsonExporter {}
5
+ class ProtobufExporter {}
6
+
7
+ const exporters = {
8
+ grpc: GrpcExporter,
9
+ 'http/json': JsonExporter,
10
+ 'http/protobuf': ProtobufExporter,
11
+ };
12
+
13
+ describe('otlpExporter', () => {
14
+ const env = { ...process.env };
15
+
16
+ afterEach(() => {
17
+ process.env = { ...env };
18
+ jest.restoreAllMocks();
19
+ });
20
+
21
+ it('uses http/protobuf by default', () => {
22
+ delete process.env.OTEL_EXPORTER_OTLP_PROTOCOL;
23
+ delete process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL;
24
+
25
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(ProtobufExporter);
26
+ });
27
+
28
+ it('takes protocol from OTEL_EXPORTER_OTLP_PROTOCOL', () => {
29
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL = 'grpc';
30
+
31
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(GrpcExporter);
32
+ expect(otlpExporter('METRICS', exporters)).toBeInstanceOf(GrpcExporter);
33
+ });
34
+
35
+ it('prefers the signal variable over the common one', () => {
36
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL = 'grpc';
37
+ process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL = 'http/json';
38
+
39
+ expect(otlpExporter('METRICS', exporters)).toBeInstanceOf(JsonExporter);
40
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(GrpcExporter);
41
+ });
42
+
43
+ it('treats blank values as unset', () => {
44
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL = 'http/json';
45
+ process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = ' ';
46
+
47
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(JsonExporter);
48
+ });
49
+
50
+ it('falls back to http/protobuf with a warning on unknown protocol', () => {
51
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
52
+ process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = 'http';
53
+
54
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(ProtobufExporter);
55
+ expect(warn).toHaveBeenCalledWith(
56
+ 'Unsupported OTLP protocol for traces: http. Using http/protobuf',
57
+ );
58
+ });
59
+
60
+ it('does not take protocol from inherited object keys', () => {
61
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
62
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL = 'constructor';
63
+
64
+ expect(otlpExporter('TRACES', exporters)).toBeInstanceOf(ProtobufExporter);
65
+ });
66
+ });
@@ -0,0 +1,28 @@
1
+ export type OtlpProtocol = 'grpc' | 'http/json' | 'http/protobuf';
2
+
3
+ const DEFAULT_PROTOCOL: OtlpProtocol = 'http/protobuf';
4
+
5
+ /**
6
+ * Exporter сигнала по OTEL_EXPORTER_OTLP_<SIGNAL>_PROTOCOL или
7
+ * OTEL_EXPORTER_OTLP_PROTOCOL, как в спецификации OpenTelemetry
8
+ */
9
+ export const otlpExporter = <T>(
10
+ signal: 'TRACES' | 'METRICS',
11
+ exporters: Record<OtlpProtocol, new () => T>,
12
+ ): T => {
13
+ const protocol =
14
+ process.env[`OTEL_EXPORTER_OTLP_${signal}_PROTOCOL`]?.trim() ||
15
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim() ||
16
+ DEFAULT_PROTOCOL;
17
+
18
+ if (!Object.hasOwn(exporters, protocol)) {
19
+ // diag без OTEL_DIAG_LOG_LEVEL молчит, а опечатку в протоколе надо увидеть
20
+ console.warn(
21
+ `Unsupported OTLP protocol for ${signal.toLowerCase()}: ${protocol}. Using ${DEFAULT_PROTOCOL}`,
22
+ );
23
+
24
+ return new exporters[DEFAULT_PROTOCOL]();
25
+ }
26
+
27
+ return new exporters[protocol as OtlpProtocol]();
28
+ };
@@ -0,0 +1,93 @@
1
+ import type { Context, ContextManager, Span } from '@opentelemetry/api';
2
+ import { ROOT_CONTEXT, trace, TraceFlags } from '@opentelemetry/api';
3
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace-node';
4
+ import { BasicTracerProvider } from '@opentelemetry/sdk-trace-node';
5
+ import { registerSpanProfiling } from '@rsdk/profiling.common';
6
+
7
+ import { createProfilingContextManager } from './profiling.context-manager';
8
+
9
+ const PROFILE_ID_ATTRIBUTE = 'profile.id';
10
+
11
+ const tracer = new BasicTracerProvider().getTracer('test');
12
+
13
+ const attributes = (span: Span): ReadableSpan['attributes'] =>
14
+ (span as unknown as ReadableSpan).attributes;
15
+
16
+ describe('createProfilingContextManager', () => {
17
+ afterEach(() => {
18
+ registerSpanProfiling();
19
+ });
20
+
21
+ it('без профилирования не подменяет context manager', () => {
22
+ expect(createProfilingContextManager()).toBeUndefined();
23
+ });
24
+
25
+ describe('с профилированием', () => {
26
+ let manager: ContextManager;
27
+ let linked: string[];
28
+ let profiling: boolean;
29
+
30
+ // запускает спан в контексте родителя и активирует его, как инструментации
31
+ const activate = <T>(
32
+ name: string,
33
+ parent: Context,
34
+ fn: (span: Span) => T,
35
+ ): T => {
36
+ const span = tracer.startSpan(name, undefined, parent);
37
+
38
+ return manager.with(trace.setSpan(parent, span), () => fn(span));
39
+ };
40
+
41
+ beforeEach(() => {
42
+ linked = [];
43
+ profiling = true;
44
+ registerSpanProfiling((spanId, fn) => {
45
+ linked.push(spanId);
46
+ return fn(profiling ? { [PROFILE_ID_ATTRIBUTE]: spanId } : undefined);
47
+ });
48
+ manager = createProfilingContextManager()!.enable();
49
+ });
50
+
51
+ afterEach(() => {
52
+ manager.disable();
53
+ });
54
+
55
+ it('помечает только корневой спан, работа дочерних идет в его профиль', () => {
56
+ const [root, child] = activate('root', ROOT_CONTEXT, (rootSpan) => [
57
+ rootSpan,
58
+ activate('child', manager.active(), (childSpan) => childSpan),
59
+ ]);
60
+ const rootId = root!.spanContext().spanId;
61
+
62
+ expect(linked).toEqual([rootId]);
63
+ expect(attributes(root!)[PROFILE_ID_ATTRIBUTE]).toBe(rootId);
64
+ expect(attributes(child!)[PROFILE_ID_ATTRIBUTE]).toBeUndefined();
65
+ });
66
+
67
+ it('считает корневым спан с родителем из другого сервиса', () => {
68
+ const remote = trace.setSpanContext(ROOT_CONTEXT, {
69
+ traceId: '0af7651916cd43dd8448eb211c80319c',
70
+ spanId: 'b7ad6b7169203331',
71
+ traceFlags: TraceFlags.SAMPLED,
72
+ isRemote: true,
73
+ });
74
+ const server = manager.with(remote, () =>
75
+ activate('server', manager.active(), (span) => span),
76
+ );
77
+
78
+ expect(linked).toEqual([server.spanContext().spanId]);
79
+ });
80
+
81
+ it('не ставит атрибут, когда профилировщик не пишет сэмплы', () => {
82
+ profiling = false;
83
+
84
+ const root = activate('root', ROOT_CONTEXT, (span) => span);
85
+
86
+ expect(attributes(root)[PROFILE_ID_ATTRIBUTE]).toBeUndefined();
87
+ });
88
+
89
+ it('возвращает результат функции', () => {
90
+ expect(activate('root', ROOT_CONTEXT, () => 42)).toBe(42);
91
+ });
92
+ });
93
+ });
@@ -0,0 +1,118 @@
1
+ import type { Context, ContextManager, Span } from '@opentelemetry/api';
2
+ import { trace } from '@opentelemetry/api';
3
+ import type * as ContextAsyncHooks from '@opentelemetry/context-async-hooks';
4
+ import type * as SpanProfiling from '@rsdk/profiling.common';
5
+ import path from 'node:path';
6
+
7
+ /**
8
+ * Без запущенного профилирования или при ошибке возвращает undefined.
9
+ * Тогда NodeSDK берет свой context manager
10
+ */
11
+ export function createProfilingContextManager(): ContextManager | undefined {
12
+ const runWithSpanProfile = loadSpanProfiling();
13
+
14
+ if (!runWithSpanProfile) {
15
+ return undefined;
16
+ }
17
+
18
+ try {
19
+ return new (profilingContextManager(
20
+ loadAsyncHooks().AsyncLocalStorageContextManager,
21
+ runWithSpanProfile,
22
+ ))();
23
+ } catch (error) {
24
+ console.warn(
25
+ `Profiles are not linked to spans: ${(error as Error).message}`,
26
+ );
27
+
28
+ return undefined;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Пакет профилирования ищется в приложении, как и его прелоад. Без пакета
34
+ * профили со спанами не связываются
35
+ */
36
+ function loadSpanProfiling(): SpanProfiling.RunWithSpanProfile | undefined {
37
+ let resolved: string;
38
+
39
+ try {
40
+ resolved = require.resolve('@rsdk/profiling.common/span-profiling', {
41
+ paths: [process.cwd()],
42
+ });
43
+ } catch {
44
+ return undefined;
45
+ }
46
+
47
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
48
+ const { getSpanProfilingRunner } = require(resolved) as Pick<
49
+ typeof SpanProfiling,
50
+ 'getSpanProfilingRunner'
51
+ >;
52
+
53
+ return getSpanProfilingRunner();
54
+ }
55
+
56
+ /**
57
+ * Тот же модуль, из которого NodeSDK по умолчанию берет context manager,
58
+ * поэтому приложению не нужно ставить @opentelemetry/context-async-hooks
59
+ */
60
+ function loadAsyncHooks(): typeof ContextAsyncHooks {
61
+ const sdkNode = path.dirname(require.resolve('@opentelemetry/sdk-node'));
62
+ const sdkTraceNode = path.dirname(
63
+ require.resolve('@opentelemetry/sdk-trace-node', { paths: [sdkNode] }),
64
+ );
65
+
66
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
67
+ return require(
68
+ require.resolve('@opentelemetry/context-async-hooks', {
69
+ paths: [sdkTraceNode],
70
+ }),
71
+ ) as typeof ContextAsyncHooks;
72
+ }
73
+
74
+ /**
75
+ * Профиль привязывается к локальному корневому спану, работа дочерних попадает
76
+ * в него. Связь ставится оберткой вокруг активации спана, потому что
77
+ * профилировщик на pprof с AsyncContextFrame помечает сэмплы только внутри
78
+ * такой обертки
79
+ */
80
+ function profilingContextManager(
81
+ Base: typeof ContextAsyncHooks.AsyncLocalStorageContextManager,
82
+ runWithSpanProfile: SpanProfiling.RunWithSpanProfile,
83
+ ): typeof ContextAsyncHooks.AsyncLocalStorageContextManager {
84
+ return class ProfilingContextManager extends Base {
85
+ override with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(
86
+ context: Context,
87
+ fn: F,
88
+ thisArg?: ThisParameterType<F>,
89
+ ...args: A
90
+ ): ReturnType<F> {
91
+ const span = trace.getSpan(context);
92
+
93
+ if (!span || !isLocalRoot(span, trace.getSpan(this.active()))) {
94
+ return super.with(context, fn, thisArg, ...args);
95
+ }
96
+
97
+ return runWithSpanProfile(span.spanContext().spanId, (attributes) => {
98
+ if (attributes) {
99
+ span.setAttributes(attributes);
100
+ }
101
+
102
+ return super.with(context, fn, thisArg, ...args);
103
+ });
104
+ }
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Корневой спан активируется, когда активного спана нет
110
+ * или он пришел из другого сервиса
111
+ */
112
+ function isLocalRoot(span: Span, active: Span | undefined): boolean {
113
+ return (
114
+ span !== active &&
115
+ span.isRecording() &&
116
+ (!active || active.spanContext().isRemote === true)
117
+ );
118
+ }
@@ -0,0 +1,9 @@
1
+ import {
2
+ type MetricObjectWithValues,
3
+ type MetricValue,
4
+ type MetricValueWithName,
5
+ } from 'prom-client';
6
+
7
+ export type PromMetricWithValues =
8
+ | MetricObjectWithValues<MetricValue<string>>
9
+ | MetricObjectWithValues<MetricValueWithName<string>>;
@@ -0,0 +1,67 @@
1
+ import { normalizePropagatorsEnv } from './propagators';
2
+
3
+ describe('normalizePropagatorsEnv', () => {
4
+ let warn: jest.SpyInstance;
5
+
6
+ beforeEach(() => {
7
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
8
+ });
9
+
10
+ afterEach(() => {
11
+ jest.restoreAllMocks();
12
+ });
13
+
14
+ it.each(['', ' ', ' , '])('treats %j as unset', (value) => {
15
+ const env: NodeJS.ProcessEnv = { OTEL_PROPAGATORS: value };
16
+
17
+ normalizePropagatorsEnv(env);
18
+
19
+ expect(env).not.toHaveProperty('OTEL_PROPAGATORS');
20
+ expect(warn).not.toHaveBeenCalled();
21
+ });
22
+
23
+ it('leaves unset variable as is', () => {
24
+ const env: NodeJS.ProcessEnv = {};
25
+
26
+ normalizePropagatorsEnv(env);
27
+
28
+ expect(env).toEqual({});
29
+ expect(warn).not.toHaveBeenCalled();
30
+ });
31
+
32
+ it('accepts supported values without warning', () => {
33
+ const env: NodeJS.ProcessEnv = {
34
+ OTEL_PROPAGATORS: 'tracecontext, baggage,b3,b3multi,jaeger',
35
+ };
36
+
37
+ normalizePropagatorsEnv(env);
38
+
39
+ expect(env.OTEL_PROPAGATORS).toBe(
40
+ 'tracecontext, baggage,b3,b3multi,jaeger',
41
+ );
42
+ expect(warn).not.toHaveBeenCalled();
43
+ });
44
+
45
+ it('accepts none', () => {
46
+ normalizePropagatorsEnv({ OTEL_PROPAGATORS: 'none' });
47
+
48
+ expect(warn).not.toHaveBeenCalled();
49
+ });
50
+
51
+ it('warns about unknown values only', () => {
52
+ normalizePropagatorsEnv({ OTEL_PROPAGATORS: 'tracecontext,b3mutli,W3C' });
53
+
54
+ expect(warn).toHaveBeenCalledTimes(1);
55
+ expect(warn).toHaveBeenCalledWith(
56
+ 'Unsupported OTEL_PROPAGATORS values: b3mutli, W3C. Supported: tracecontext, baggage, b3, b3multi, jaeger, none',
57
+ );
58
+ });
59
+
60
+ it('treats values as case-sensitive like the SDK', () => {
61
+ normalizePropagatorsEnv({ OTEL_PROPAGATORS: 'TraceContext' });
62
+
63
+ expect(warn).toHaveBeenCalledWith(
64
+ expect.stringContaining('values: TraceContext.'),
65
+ );
66
+ });
67
+ });
@@ -0,0 +1,35 @@
1
+ // что NodeTracerProvider собирает из OTEL_PROPAGATORS, и none из спецификации
2
+ const KNOWN_PROPAGATORS = [
3
+ 'tracecontext',
4
+ 'baggage',
5
+ 'b3',
6
+ 'b3multi',
7
+ 'jaeger',
8
+ 'none',
9
+ ];
10
+
11
+ /**
12
+ * Готовит OTEL_PROPAGATORS для SDK. Ошибки в значении SDK пишет только в diag,
13
+ * а без OTEL_DIAG_LOG_LEVEL он молчит, и контекст трейса пропадает незаметно
14
+ */
15
+ export const normalizePropagatorsEnv = (env: NodeJS.ProcessEnv): void => {
16
+ const names = (env.OTEL_PROPAGATORS ?? '')
17
+ .split(',')
18
+ .map((name) => name.trim())
19
+ .filter(Boolean);
20
+
21
+ // пустой OTEL_PROPAGATORS SDK читает как список из '' и не передаёт контекст вовсе,
22
+ // а по спецификации пустое значение равно незаданному
23
+ if (names.length === 0) {
24
+ delete env.OTEL_PROPAGATORS;
25
+ return;
26
+ }
27
+
28
+ const unknown = names.filter((name) => !KNOWN_PROPAGATORS.includes(name));
29
+
30
+ if (unknown.length > 0) {
31
+ console.warn(
32
+ `Unsupported OTEL_PROPAGATORS values: ${unknown.join(', ')}. Supported: ${KNOWN_PROPAGATORS.join(', ')}`,
33
+ );
34
+ }
35
+ };
@@ -0,0 +1,34 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import { ValueType } from '@opentelemetry/api';
3
+ import type { SumMetricData } from '@opentelemetry/sdk-metrics';
4
+ import {
5
+ AggregationTemporality,
6
+ DataPointType,
7
+ InstrumentType,
8
+ } from '@opentelemetry/sdk-metrics';
9
+
10
+ import type { PromMetricWithValues } from '../opentelemetry/prom-metrics.type';
11
+
12
+ import { toDataPoints } from './data-points';
13
+
14
+ export class CounterConvertor {
15
+ static toOtel(
16
+ promMetrics: PromMetricWithValues,
17
+ startTime: HrTime,
18
+ endTime: HrTime,
19
+ ): SumMetricData {
20
+ return {
21
+ descriptor: {
22
+ name: promMetrics.name,
23
+ description: promMetrics.help,
24
+ unit: '',
25
+ type: InstrumentType.COUNTER,
26
+ valueType: ValueType.DOUBLE,
27
+ },
28
+ dataPoints: toDataPoints(promMetrics.values, startTime, endTime),
29
+ dataPointType: DataPointType.SUM,
30
+ isMonotonic: true,
31
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
32
+ };
33
+ }
34
+ }