@rsdk/cli.cmd.start 5.11.5 → 5.11.6

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 (66) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/opentelemetry/exporter.d.ts +8 -0
  3. package/dist/opentelemetry/exporter.js +69 -0
  4. package/dist/opentelemetry/exporter.js.map +1 -0
  5. package/dist/opentelemetry/opentelemetry.init.js +49 -26
  6. package/dist/opentelemetry/opentelemetry.init.js.map +1 -1
  7. package/dist/opentelemetry/otlp-exporter.d.ts +6 -0
  8. package/dist/opentelemetry/otlp-exporter.js +21 -0
  9. package/dist/opentelemetry/otlp-exporter.js.map +1 -0
  10. package/dist/opentelemetry/profiling.context-manager.d.ts +6 -0
  11. package/dist/opentelemetry/profiling.context-manager.js +87 -0
  12. package/dist/opentelemetry/profiling.context-manager.js.map +1 -0
  13. package/dist/opentelemetry/prom-metrics.type.d.ts +2 -0
  14. package/dist/opentelemetry/prom-metrics.type.js +3 -0
  15. package/dist/opentelemetry/prom-metrics.type.js.map +1 -0
  16. package/dist/opentelemetry/propagators.d.ts +5 -0
  17. package/dist/opentelemetry/propagators.js +34 -0
  18. package/dist/opentelemetry/propagators.js.map +1 -0
  19. package/dist/otel-convertors/counter.convertor.d.ts +6 -0
  20. package/dist/otel-convertors/counter.convertor.js +25 -0
  21. package/dist/otel-convertors/counter.convertor.js.map +1 -0
  22. package/dist/otel-convertors/data-points.d.ts +4 -0
  23. package/dist/otel-convertors/data-points.js +15 -0
  24. package/dist/otel-convertors/data-points.js.map +1 -0
  25. package/dist/otel-convertors/gauge.convertor.d.ts +6 -0
  26. package/dist/otel-convertors/gauge.convertor.js +24 -0
  27. package/dist/otel-convertors/gauge.convertor.js.map +1 -0
  28. package/dist/otel-convertors/histogram.convertor.d.ts +6 -0
  29. package/dist/otel-convertors/histogram.convertor.js +81 -0
  30. package/dist/otel-convertors/histogram.convertor.js.map +1 -0
  31. package/dist/otel-convertors/index.d.ts +4 -0
  32. package/dist/otel-convertors/index.js +21 -0
  33. package/dist/otel-convertors/index.js.map +1 -0
  34. package/dist/otel-convertors/summary.convertor.d.ts +6 -0
  35. package/dist/otel-convertors/summary.convertor.js +69 -0
  36. package/dist/otel-convertors/summary.convertor.js.map +1 -0
  37. package/dist/profiling/profiling.d.ts +10 -0
  38. package/dist/profiling/profiling.js +34 -0
  39. package/dist/profiling/profiling.js.map +1 -0
  40. package/dist/start-dev.cmd.d.ts +1 -1
  41. package/dist/start-dev.cmd.js +17 -3
  42. package/dist/start-dev.cmd.js.map +1 -1
  43. package/dist/start.cmd.d.ts +1 -1
  44. package/dist/start.cmd.js +12 -2
  45. package/dist/start.cmd.js.map +1 -1
  46. package/jest.config.js +1 -0
  47. package/package.json +21 -4
  48. package/src/opentelemetry/exporter.spec.ts +220 -0
  49. package/src/opentelemetry/exporter.ts +88 -0
  50. package/src/opentelemetry/opentelemetry.init.ts +60 -29
  51. package/src/opentelemetry/otlp-exporter.spec.ts +66 -0
  52. package/src/opentelemetry/otlp-exporter.ts +28 -0
  53. package/src/opentelemetry/profiling.context-manager.spec.ts +93 -0
  54. package/src/opentelemetry/profiling.context-manager.ts +118 -0
  55. package/src/opentelemetry/prom-metrics.type.ts +9 -0
  56. package/src/opentelemetry/propagators.spec.ts +67 -0
  57. package/src/opentelemetry/propagators.ts +35 -0
  58. package/src/otel-convertors/counter.convertor.ts +34 -0
  59. package/src/otel-convertors/data-points.ts +19 -0
  60. package/src/otel-convertors/gauge.convertor.ts +33 -0
  61. package/src/otel-convertors/histogram.convertor.ts +121 -0
  62. package/src/otel-convertors/index.ts +4 -0
  63. package/src/otel-convertors/summary.convertor.ts +86 -0
  64. package/src/profiling/profiling.ts +37 -0
  65. package/src/start-dev.cmd.ts +24 -2
  66. package/src/start.cmd.ts +21 -1
@@ -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
+ }
@@ -0,0 +1,19 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import type { DataPoint } from '@opentelemetry/sdk-metrics';
3
+ import type { MetricValue } from 'prom-client';
4
+
5
+ // OTLP JSON сериализует NaN и Infinity как null, такие точки отбрасываем
6
+ export function toDataPoints(
7
+ values: readonly MetricValue<string>[],
8
+ startTime: HrTime,
9
+ endTime: HrTime,
10
+ ): DataPoint<number>[] {
11
+ return values
12
+ .filter((v) => Number.isFinite(v.value))
13
+ .map((v) => ({
14
+ attributes: v.labels,
15
+ value: v.value,
16
+ startTime,
17
+ endTime,
18
+ }));
19
+ }
@@ -0,0 +1,33 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import { ValueType } from '@opentelemetry/api';
3
+ import type { GaugeMetricData } 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 GaugeConvertor {
15
+ static toOtel(
16
+ promMetrics: PromMetricWithValues,
17
+ startTime: HrTime,
18
+ endTime: HrTime,
19
+ ): GaugeMetricData {
20
+ return {
21
+ descriptor: {
22
+ name: promMetrics.name,
23
+ description: promMetrics.help,
24
+ unit: '',
25
+ type: InstrumentType.GAUGE,
26
+ valueType: ValueType.DOUBLE,
27
+ },
28
+ dataPoints: toDataPoints(promMetrics.values, startTime, endTime),
29
+ dataPointType: DataPointType.GAUGE,
30
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
31
+ };
32
+ }
33
+ }
@@ -0,0 +1,121 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import { ValueType } from '@opentelemetry/api';
3
+ import type {
4
+ DataPoint,
5
+ Histogram,
6
+ HistogramMetricData,
7
+ } from '@opentelemetry/sdk-metrics';
8
+ import {
9
+ AggregationTemporality,
10
+ DataPointType,
11
+ InstrumentType,
12
+ } from '@opentelemetry/sdk-metrics';
13
+ import type { LabelValues, MetricValueWithName } from 'prom-client';
14
+
15
+ import type { PromMetricWithValues } from '../opentelemetry/prom-metrics.type';
16
+
17
+ const BUCKET_SUFFIX = '_bucket';
18
+ const SUM_SUFFIX = '_sum';
19
+ const COUNT_SUFFIX = '_count';
20
+
21
+ interface Series {
22
+ labels: LabelValues<string>;
23
+ buckets: Map<number, number>;
24
+ sum?: number;
25
+ count?: number;
26
+ }
27
+
28
+ export class HistogramConvertor {
29
+ static toOtel(
30
+ promMetrics: PromMetricWithValues,
31
+ startTime: HrTime,
32
+ endTime: HrTime,
33
+ ): HistogramMetricData {
34
+ // prom-client отдает histogram плоским списком: бакеты с меткой le, _sum и _count
35
+ const seriesByLabels = new Map<string, Series>();
36
+
37
+ for (const rec of promMetrics.values as MetricValueWithName<string>[]) {
38
+ const { le, ...labels } = rec.labels;
39
+ const key = JSON.stringify(labels);
40
+ let series = seriesByLabels.get(key);
41
+
42
+ if (!series) {
43
+ series = { labels, buckets: new Map() };
44
+ seriesByLabels.set(key, series);
45
+ }
46
+
47
+ switch (rec.metricName) {
48
+ case promMetrics.name + BUCKET_SUFFIX: {
49
+ const bound = le === '+Inf' ? Number.POSITIVE_INFINITY : Number(le);
50
+
51
+ if (!Number.isNaN(bound)) series.buckets.set(bound, rec.value);
52
+
53
+ break;
54
+ }
55
+ case promMetrics.name + SUM_SUFFIX:
56
+ series.sum = rec.value;
57
+
58
+ break;
59
+
60
+ case promMetrics.name + COUNT_SUFFIX:
61
+ series.count = rec.value;
62
+
63
+ break;
64
+
65
+ // No default
66
+ }
67
+ }
68
+
69
+ const dataPoints: DataPoint<Histogram>[] = [];
70
+
71
+ for (const series of seriesByLabels.values()) {
72
+ const boundaries = [...series.buckets.keys()]
73
+ .filter((b) => Number.isFinite(b))
74
+ .sort((a, b) => a - b);
75
+
76
+ // в prom-client бакеты кумулятивные, в OTLP нужен счетчик каждого бакета
77
+ const counts: number[] = [];
78
+ let prev = 0;
79
+
80
+ for (const bound of boundaries) {
81
+ const cumulative = series.buckets.get(bound) ?? prev;
82
+
83
+ counts.push(cumulative - prev);
84
+ prev = cumulative;
85
+ }
86
+
87
+ const total =
88
+ series.count ?? series.buckets.get(Number.POSITIVE_INFINITY) ?? prev;
89
+
90
+ counts.push(total - prev);
91
+
92
+ dataPoints.push({
93
+ attributes: series.labels,
94
+ startTime,
95
+ endTime,
96
+ value: {
97
+ count: total,
98
+
99
+ // NaN и Infinity не сериализуются в OTLP JSON
100
+ ...(series.sum !== undefined && Number.isFinite(series.sum)
101
+ ? { sum: series.sum }
102
+ : {}),
103
+ buckets: { boundaries, counts },
104
+ },
105
+ });
106
+ }
107
+
108
+ return {
109
+ descriptor: {
110
+ name: promMetrics.name,
111
+ description: promMetrics.help,
112
+ unit: '',
113
+ type: InstrumentType.HISTOGRAM,
114
+ valueType: ValueType.DOUBLE,
115
+ },
116
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
117
+ dataPointType: DataPointType.HISTOGRAM,
118
+ dataPoints,
119
+ };
120
+ }
121
+ }
@@ -0,0 +1,4 @@
1
+ export * from './counter.convertor';
2
+ export * from './gauge.convertor';
3
+ export * from './histogram.convertor';
4
+ export * from './summary.convertor';
@@ -0,0 +1,86 @@
1
+ import type { HrTime } from '@opentelemetry/api';
2
+ import { ValueType } from '@opentelemetry/api';
3
+ import type {
4
+ GaugeMetricData,
5
+ MetricData,
6
+ SumMetricData,
7
+ } from '@opentelemetry/sdk-metrics';
8
+ import {
9
+ AggregationTemporality,
10
+ DataPointType,
11
+ InstrumentType,
12
+ } from '@opentelemetry/sdk-metrics';
13
+ import type { MetricValue, MetricValueWithName } from 'prom-client';
14
+
15
+ import type { PromMetricWithValues } from '../opentelemetry/prom-metrics.type';
16
+
17
+ import { toDataPoints } from './data-points';
18
+
19
+ // В sdk-metrics нет типа Summary: квантили уходят как gauge, _sum и _count как sum
20
+ export class SummaryConvertor {
21
+ static toOtel(
22
+ promMetrics: PromMetricWithValues,
23
+ startTime: HrTime,
24
+ endTime: HrTime,
25
+ ): MetricData[] {
26
+ // prom-client отдает summary плоским списком: квантили с меткой quantile,
27
+ // а _sum и _count отдельными записями с metricName
28
+ const quantileValues: MetricValue<string>[] = [];
29
+ const sumValues: MetricValue<string>[] = [];
30
+ const countValues: MetricValue<string>[] = [];
31
+
32
+ for (const v of promMetrics.values as MetricValueWithName<string>[]) {
33
+ if (v.metricName === `${promMetrics.name}_sum`) {
34
+ sumValues.push(v);
35
+ } else if (v.metricName === `${promMetrics.name}_count`) {
36
+ countValues.push(v);
37
+ } else {
38
+ quantileValues.push(v);
39
+ }
40
+ }
41
+
42
+ const quantiles: GaugeMetricData = {
43
+ descriptor: {
44
+ name: promMetrics.name,
45
+ description: promMetrics.help,
46
+ unit: '',
47
+ type: InstrumentType.GAUGE,
48
+ valueType: ValueType.DOUBLE,
49
+ },
50
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
51
+ dataPointType: DataPointType.GAUGE,
52
+ dataPoints: toDataPoints(quantileValues, startTime, endTime),
53
+ };
54
+
55
+ // наблюдения могут быть отрицательными, поэтому _sum не монотонный
56
+ const sum: SumMetricData = {
57
+ descriptor: {
58
+ name: `${promMetrics.name}_sum`,
59
+ description: `${promMetrics.help} (sum)`,
60
+ unit: '',
61
+ type: InstrumentType.UP_DOWN_COUNTER,
62
+ valueType: ValueType.DOUBLE,
63
+ },
64
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
65
+ dataPointType: DataPointType.SUM,
66
+ isMonotonic: false,
67
+ dataPoints: toDataPoints(sumValues, startTime, endTime),
68
+ };
69
+
70
+ const count: SumMetricData = {
71
+ descriptor: {
72
+ name: `${promMetrics.name}_count`,
73
+ description: `${promMetrics.help} (count)`,
74
+ unit: '',
75
+ type: InstrumentType.COUNTER,
76
+ valueType: ValueType.DOUBLE,
77
+ },
78
+ aggregationTemporality: AggregationTemporality.CUMULATIVE,
79
+ dataPointType: DataPointType.SUM,
80
+ isMonotonic: true,
81
+ dataPoints: toDataPoints(countValues, startTime, endTime),
82
+ };
83
+
84
+ return [quantiles, sum, count];
85
+ }
86
+ }
@@ -0,0 +1,37 @@
1
+ import { LoggerFactory } from '@rsdk/logging';
2
+
3
+ const logger = LoggerFactory.create('Profiling');
4
+
5
+ /**
6
+ * Передает --profiling прелоаду через переменную PROFILING.
7
+ * Без значения опция приходит как true
8
+ */
9
+ export function applyProfilingOption(
10
+ value: string | boolean | undefined,
11
+ ): void {
12
+ if (value !== undefined && value !== false) {
13
+ process.env['PROFILING'] = String(value);
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Путь к прелоаду из node_modules приложения. Без @rsdk/profiling.common
19
+ * профилирование недоступно, но приложение запускается
20
+ */
21
+ export function resolveProfilingRegister(): string | undefined {
22
+ try {
23
+ return require.resolve('@rsdk/profiling.common/register', {
24
+ paths: [process.cwd()],
25
+ });
26
+ } catch {
27
+ const requested = process.env['PROFILING'];
28
+
29
+ if (requested && requested !== 'false') {
30
+ logger.error(
31
+ 'Profiling is disabled: @rsdk/profiling.common is not installed',
32
+ );
33
+ }
34
+
35
+ return undefined;
36
+ }
37
+ }
@@ -1,9 +1,13 @@
1
- import { Default, Option, SubCmd } from '@rsdk/cli.common';
1
+ import { Default, Option, OptionalValue, SubCmd } from '@rsdk/cli.common';
2
2
  import { LoggerFactory } from '@rsdk/logging';
3
3
  import execa from 'execa';
4
4
  import path from 'node:path';
5
5
 
6
6
  import { OPENTELEMETRY_INIT_PATH } from './opentelemetry/opentelemetry.path';
7
+ import {
8
+ applyProfilingOption,
9
+ resolveProfilingRegister,
10
+ } from './profiling/profiling';
7
11
 
8
12
  export class StartDevCmd {
9
13
  static logger = LoggerFactory.create(StartDevCmd);
@@ -15,17 +19,35 @@ export class StartDevCmd {
15
19
  @Option('pretty', 'Enable PinoPretty output', String, (v) => v === 'true')
16
20
  @Default('true')
17
21
  pretty: boolean,
22
+ @Option('profiling', 'Enable profiling, pyroscope by default', String)
23
+ @OptionalValue()
24
+ profiling: string | boolean | undefined,
18
25
  ): Promise<void> {
19
26
  const tracingPart = [`-r`, OPENTELEMETRY_INIT_PATH];
20
27
  const env: NodeJS.ProcessEnv = {};
21
28
  const command = [`--watch`];
22
29
 
30
+ applyProfilingOption(profiling);
31
+
32
+ const profilingRegister = resolveProfilingRegister();
33
+
34
+ // ts-node подключается до профилировщика, потому что по нему профилировщик
35
+ // включает в Node source maps, иначе строки в профиле будут из JS.
36
+ // Профилировщик подключается до OTEL, чтобы тот связал профили со спанами
37
+ if (profilingRegister) {
38
+ command.push('-r', 'ts-node/register', '-r', profilingRegister);
39
+ }
40
+
23
41
  if (otel) {
24
42
  command.push(...tracingPart);
25
43
  env['LOG_OTEL_ENABLED'] = 'true';
26
44
  }
27
45
 
28
- command.push('-r', 'ts-node/register', 'src/main.ts');
46
+ if (!profilingRegister) {
47
+ command.push('-r', 'ts-node/register');
48
+ }
49
+
50
+ command.push('src/main.ts');
29
51
  const bin = 'node';
30
52
 
31
53
  const cmd = [bin, ...command].join(' ');
package/src/start.cmd.ts CHANGED
@@ -1,8 +1,12 @@
1
- import { Option, SubCmd } from '@rsdk/cli.common';
1
+ import { Option, OptionalValue, SubCmd } from '@rsdk/cli.common';
2
2
  import { LoggerFactory } from '@rsdk/logging';
3
3
  import path from 'node:path';
4
4
 
5
5
  import { OPENTELEMETRY_INIT_PATH } from './opentelemetry/opentelemetry.path';
6
+ import {
7
+ applyProfilingOption,
8
+ resolveProfilingRegister,
9
+ } from './profiling/profiling';
6
10
 
7
11
  export class StartCmd {
8
12
  private readonly logger = LoggerFactory.create(StartCmd);
@@ -10,10 +14,26 @@ export class StartCmd {
10
14
  @SubCmd('start', 'Start built app')
11
15
  async handle(
12
16
  @Option('otel', 'Enable opentelemetry tracing', Boolean) otel: boolean,
17
+ @Option('profiling', 'Enable profiling, pyroscope by default', String)
18
+ @OptionalValue()
19
+ profiling: string | boolean | undefined,
13
20
  ): Promise<void> {
14
21
  this.logger.trace('execute start command');
15
22
 
16
23
  try {
24
+ applyProfilingOption(profiling);
25
+
26
+ const profilingRegister = resolveProfilingRegister();
27
+
28
+ if (profilingRegister) {
29
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
30
+ const { register } = require(profilingRegister) as {
31
+ register?: () => void;
32
+ };
33
+
34
+ register?.();
35
+ }
36
+
17
37
  if (otel) {
18
38
  require(OPENTELEMETRY_INIT_PATH);
19
39
  process.env.LOG_OTEL_ENABLED = 'true';