@rsdk/cli.cmd.start 5.15.0-next.1 → 5.15.0-next.11

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 (55) 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 +30 -13
  5. package/dist/opentelemetry/opentelemetry.init.js.map +1 -1
  6. package/dist/opentelemetry/profiling.context-manager.d.ts +6 -0
  7. package/dist/opentelemetry/profiling.context-manager.js +87 -0
  8. package/dist/opentelemetry/profiling.context-manager.js.map +1 -0
  9. package/dist/opentelemetry/prom-metrics.type.d.ts +2 -0
  10. package/dist/opentelemetry/prom-metrics.type.js +3 -0
  11. package/dist/opentelemetry/prom-metrics.type.js.map +1 -0
  12. package/dist/otel-convertors/counter.convertor.d.ts +6 -0
  13. package/dist/otel-convertors/counter.convertor.js +25 -0
  14. package/dist/otel-convertors/counter.convertor.js.map +1 -0
  15. package/dist/otel-convertors/data-points.d.ts +4 -0
  16. package/dist/otel-convertors/data-points.js +15 -0
  17. package/dist/otel-convertors/data-points.js.map +1 -0
  18. package/dist/otel-convertors/gauge.convertor.d.ts +6 -0
  19. package/dist/otel-convertors/gauge.convertor.js +24 -0
  20. package/dist/otel-convertors/gauge.convertor.js.map +1 -0
  21. package/dist/otel-convertors/histogram.convertor.d.ts +6 -0
  22. package/dist/otel-convertors/histogram.convertor.js +81 -0
  23. package/dist/otel-convertors/histogram.convertor.js.map +1 -0
  24. package/dist/otel-convertors/index.d.ts +4 -0
  25. package/dist/otel-convertors/index.js +21 -0
  26. package/dist/otel-convertors/index.js.map +1 -0
  27. package/dist/otel-convertors/summary.convertor.d.ts +6 -0
  28. package/dist/otel-convertors/summary.convertor.js +69 -0
  29. package/dist/otel-convertors/summary.convertor.js.map +1 -0
  30. package/dist/profiling/profiling.d.ts +10 -0
  31. package/dist/profiling/profiling.js +34 -0
  32. package/dist/profiling/profiling.js.map +1 -0
  33. package/dist/start-dev.cmd.d.ts +1 -1
  34. package/dist/start-dev.cmd.js +17 -3
  35. package/dist/start-dev.cmd.js.map +1 -1
  36. package/dist/start.cmd.d.ts +1 -1
  37. package/dist/start.cmd.js +12 -2
  38. package/dist/start.cmd.js.map +1 -1
  39. package/jest.config.js +1 -0
  40. package/package.json +7 -2
  41. package/src/opentelemetry/exporter.spec.ts +220 -0
  42. package/src/opentelemetry/exporter.ts +88 -0
  43. package/src/opentelemetry/opentelemetry.init.ts +39 -14
  44. package/src/opentelemetry/profiling.context-manager.spec.ts +93 -0
  45. package/src/opentelemetry/profiling.context-manager.ts +118 -0
  46. package/src/opentelemetry/prom-metrics.type.ts +9 -0
  47. package/src/otel-convertors/counter.convertor.ts +34 -0
  48. package/src/otel-convertors/data-points.ts +19 -0
  49. package/src/otel-convertors/gauge.convertor.ts +33 -0
  50. package/src/otel-convertors/histogram.convertor.ts +121 -0
  51. package/src/otel-convertors/index.ts +4 -0
  52. package/src/otel-convertors/summary.convertor.ts +86 -0
  53. package/src/profiling/profiling.ts +37 -0
  54. package/src/start-dev.cmd.ts +24 -2
  55. package/src/start.cmd.ts +21 -1
@@ -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
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
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,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
30
+ const { register } = require(profilingRegister) as {
31
+ register?: () => void;
32
+ };
33
+
34
+ register?.();
35
+ }
36
+
17
37
  if (otel) {
18
38
  // eslint-disable-next-line @typescript-eslint/no-require-imports
19
39
  require(OPENTELEMETRY_INIT_PATH);