@rsdk/cli.cmd.start 5.15.0-next.0 → 5.15.0-next.10

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,10 @@
1
+ /**
2
+ * Передает --profiling прелоаду через переменную PROFILING.
3
+ * Без значения опция приходит как true
4
+ */
5
+ export declare function applyProfilingOption(value: string | boolean | undefined): void;
6
+ /**
7
+ * Путь к прелоаду из node_modules приложения. Без @rsdk/profiling.common
8
+ * профилирование недоступно, но приложение запускается
9
+ */
10
+ export declare function resolveProfilingRegister(): string | undefined;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyProfilingOption = applyProfilingOption;
4
+ exports.resolveProfilingRegister = resolveProfilingRegister;
5
+ const logging_1 = require("@rsdk/logging");
6
+ const logger = logging_1.LoggerFactory.create('Profiling');
7
+ /**
8
+ * Передает --profiling прелоаду через переменную PROFILING.
9
+ * Без значения опция приходит как true
10
+ */
11
+ function applyProfilingOption(value) {
12
+ if (value !== undefined && value !== false) {
13
+ process.env['PROFILING'] = String(value);
14
+ }
15
+ }
16
+ /**
17
+ * Путь к прелоаду из node_modules приложения. Без @rsdk/profiling.common
18
+ * профилирование недоступно, но приложение запускается
19
+ */
20
+ function resolveProfilingRegister() {
21
+ try {
22
+ return require.resolve('@rsdk/profiling.common/register', {
23
+ paths: [process.cwd()],
24
+ });
25
+ }
26
+ catch {
27
+ const requested = process.env['PROFILING'];
28
+ if (requested && requested !== 'false') {
29
+ logger.error('Profiling is disabled: @rsdk/profiling.common is not installed');
30
+ }
31
+ return undefined;
32
+ }
33
+ }
34
+ //# sourceMappingURL=profiling.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profiling.js","sourceRoot":"","sources":["../../src/profiling/profiling.ts"],"names":[],"mappings":";;AAQA,oDAMC;AAMD,4DAgBC;AApCD,2CAA8C;AAE9C,MAAM,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAEjD;;;GAGG;AACH,SAAgB,oBAAoB,CAClC,KAAmC;IAEnC,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QAC3C,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAgB,wBAAwB;IACtC,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,OAAO,CAAC,iCAAiC,EAAE;YACxD,KAAK,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;SACvB,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAE3C,IAAI,SAAS,IAAI,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,CAAC,KAAK,CACV,gEAAgE,CACjE,CAAC;QACJ,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
@@ -1,4 +1,4 @@
1
1
  export declare class StartDevCmd {
2
2
  static logger: import("@rsdk/logging").ILogger;
3
- handle(otel: boolean, pretty: boolean): Promise<void>;
3
+ handle(otel: boolean, pretty: boolean, profiling: string | boolean | undefined): Promise<void>;
4
4
  }
@@ -21,17 +21,29 @@ const logging_1 = require("@rsdk/logging");
21
21
  const execa_1 = __importDefault(require("execa"));
22
22
  const node_path_1 = __importDefault(require("node:path"));
23
23
  const opentelemetry_path_1 = require("./opentelemetry/opentelemetry.path");
24
+ const profiling_1 = require("./profiling/profiling");
24
25
  class StartDevCmd {
25
26
  static logger = logging_1.LoggerFactory.create(StartDevCmd);
26
- async handle(otel, pretty) {
27
+ async handle(otel, pretty, profiling) {
27
28
  const tracingPart = [`-r`, opentelemetry_path_1.OPENTELEMETRY_INIT_PATH];
28
29
  const env = {};
29
30
  const command = [`--watch`];
31
+ (0, profiling_1.applyProfilingOption)(profiling);
32
+ const profilingRegister = (0, profiling_1.resolveProfilingRegister)();
33
+ // ts-node подключается до профилировщика, потому что по нему профилировщик
34
+ // включает в Node source maps, иначе строки в профиле будут из JS.
35
+ // Профилировщик подключается до OTEL, чтобы тот связал профили со спанами
36
+ if (profilingRegister) {
37
+ command.push('-r', 'ts-node/register', '-r', profilingRegister);
38
+ }
30
39
  if (otel) {
31
40
  command.push(...tracingPart);
32
41
  env['LOG_OTEL_ENABLED'] = 'true';
33
42
  }
34
- command.push('-r', 'ts-node/register', 'src/main.ts');
43
+ if (!profilingRegister) {
44
+ command.push('-r', 'ts-node/register');
45
+ }
46
+ command.push('src/main.ts');
35
47
  const bin = 'node';
36
48
  const cmd = [bin, ...command].join(' ');
37
49
  StartDevCmd.logger.trace('run command: ' + cmd);
@@ -67,8 +79,10 @@ __decorate([
67
79
  __param(0, (0, cli_common_1.Option)('otel', 'Enable opentelemetry tracing', Boolean)),
68
80
  __param(1, (0, cli_common_1.Option)('pretty', 'Enable PinoPretty output', String, (v) => v === 'true')),
69
81
  __param(1, (0, cli_common_1.Default)('true')),
82
+ __param(2, (0, cli_common_1.Option)('profiling', 'Enable profiling, pyroscope by default', String)),
83
+ __param(2, (0, cli_common_1.OptionalValue)()),
70
84
  __metadata("design:type", Function),
71
- __metadata("design:paramtypes", [Boolean, Boolean]),
85
+ __metadata("design:paramtypes", [Boolean, Boolean, Object]),
72
86
  __metadata("design:returntype", Promise)
73
87
  ], StartDevCmd.prototype, "handle", null);
74
88
  //# sourceMappingURL=start-dev.cmd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"start-dev.cmd.js","sourceRoot":"","sources":["../src/start-dev.cmd.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,iDAA2D;AAC3D,2CAA8C;AAC9C,kDAA0B;AAC1B,0DAA6B;AAE7B,2EAA6E;AAE7E,MAAa,WAAW;IACtB,MAAM,CAAC,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAG5C,AAAN,KAAK,CAAC,MAAM,CAEV,IAAa,EAGb,MAAe;QAEf,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,4CAAuB,CAAC,CAAC;QACpD,MAAM,GAAG,GAAsB,EAAE,CAAC;QAClC,MAAM,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QAE5B,IAAI,IAAI,EAAE,CAAC;YACT,OAAO,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;YAC7B,GAAG,CAAC,kBAAkB,CAAC,GAAG,MAAM,CAAC;QACnC,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,kBAAkB,EAAE,aAAa,CAAC,CAAC;QACtD,MAAM,GAAG,GAAG,MAAM,CAAC;QAEnB,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;Q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CAwEC;AApEO;IADL,IAAA,mBAAM,EAAC,WAAW,EAAE,2BAA2B,CAAC;IAE9C,WAAA,IAAA,mBAAM,EAAC,MAAM,EAAE,8BAA8B,EAAE,OAAO,CAAC,CAAA;IAEvD,WAAA,IAAA,mBAAM,EAAC,QAAQ,EAAE,0BAA0B,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,MAAM,CAAC,CAAA;IACzE,WAAA,IAAA,oBAAO,EAAC,MAAM,CAAC,CAAA;IAEf,WAAA,IAAA,mBAAM,EAAC,WAAW,EAAE,wCAAwC,EAAE,MAAM,CAAC,CAAA;IACrE,WAAA,IAAA,0BAAa,GAAE,CAAA;;;;yCA4DjB"}
@@ -1,4 +1,4 @@
1
1
  export declare class StartCmd {
2
2
  private readonly logger;
3
- handle(otel: boolean): Promise<void>;
3
+ handle(otel: boolean, profiling: string | boolean | undefined): Promise<void>;
4
4
  }
package/dist/start.cmd.js CHANGED
@@ -20,11 +20,19 @@ const cli_common_1 = require("@rsdk/cli.common");
20
20
  const logging_1 = require("@rsdk/logging");
21
21
  const node_path_1 = __importDefault(require("node:path"));
22
22
  const opentelemetry_path_1 = require("./opentelemetry/opentelemetry.path");
23
+ const profiling_1 = require("./profiling/profiling");
23
24
  class StartCmd {
24
25
  logger = logging_1.LoggerFactory.create(StartCmd);
25
- async handle(otel) {
26
+ async handle(otel, profiling) {
26
27
  this.logger.trace('execute start command');
27
28
  try {
29
+ (0, profiling_1.applyProfilingOption)(profiling);
30
+ const profilingRegister = (0, profiling_1.resolveProfilingRegister)();
31
+ if (profilingRegister) {
32
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
33
+ const { register } = require(profilingRegister);
34
+ register?.();
35
+ }
28
36
  if (otel) {
29
37
  // eslint-disable-next-line @typescript-eslint/no-require-imports
30
38
  require(opentelemetry_path_1.OPENTELEMETRY_INIT_PATH);
@@ -50,8 +58,10 @@ exports.StartCmd = StartCmd;
50
58
  __decorate([
51
59
  (0, cli_common_1.SubCmd)('start', 'Start built app'),
52
60
  __param(0, (0, cli_common_1.Option)('otel', 'Enable opentelemetry tracing', Boolean)),
61
+ __param(1, (0, cli_common_1.Option)('profiling', 'Enable profiling, pyroscope by default', String)),
62
+ __param(1, (0, cli_common_1.OptionalValue)()),
53
63
  __metadata("design:type", Function),
54
- __metadata("design:paramtypes", [Boolean]),
64
+ __metadata("design:paramtypes", [Boolean, Object]),
55
65
  __metadata("design:returntype", Promise)
56
66
  ], StartCmd.prototype, "handle", null);
57
67
  //# sourceMappingURL=start.cmd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"start.cmd.js","sourceRoot":"","sources":["../src/start.cmd.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,iDAAkD;AAClD,2CAA8C;AAC9C,0DAA6B;AAE7B,2EAA6E;AAE7E,MAAa,QAAQ;IACF,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAGnD,AAAN,KAAK,CAAC,MAAM,CAC+C,IAAa;QAEtE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAE3C,IAAI,CAAC;YACH,IAAI,IAAI,EAAE,CAAC;gBACT,iEAAiE;gBACjE,OAAO,CAAC,4CAAuB,CAAC,CAAC;gBACjC,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,MAAM,CAAC;YACxC,CAAC;YAED,MAAM,OAAO,GAAG,mBAAI,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAE5C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;YACnD,iEAAiE;YACjE,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC;YACjC,iEAAiE;YACjE,IAAI,CAAC,CAAC,GAAG,YAAY,OAAO,CAAC,YAAY,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC;gBACxD,MA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O,GAAG,mBAAI,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAE5C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;YACnD,iEAAiE;YACjE,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC;YACjC,iEAAiE;YACjE,IAAI,CAAC,CAAC,GAAG,YAAY,OAAO,CAAC,YAAY,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC;gBACxD,MAAM,IAAI,SAAS,CAAC,iCAAiC,CAAC,CAAC;YACzD,CAAC;YACD,MAAM,GAAG,CAAC,GAAG,EAAE,CAAC;QAClB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAc,CAAC,CAAC;YAClC,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF;AA/CD,4BA+CC;AA3CO;IADL,IAAA,mBAAM,EAAC,OAAO,EAAE,iBAAiB,CAAC;IAEhC,WAAA,IAAA,mBAAM,EAAC,MAAM,EAAE,8BAA8B,EAAE,OAAO,CAAC,CAAA;IACvD,WAAA,IAAA,mBAAM,EAAC,WAAW,EAAE,wCAAwC,EAAE,MAAM,CAAC,CAAA;IACrE,WAAA,IAAA,0BAAa,GAAE,CAAA;;;;sCAuCjB"}
package/jest.config.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('@rsdk/jest/jest.config');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsdk/cli.cmd.start",
3
- "version": "5.15.0-next.0",
3
+ "version": "5.15.0-next.10",
4
4
  "description": "Start command for rsdk cli",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -37,8 +37,10 @@
37
37
  "@opentelemetry/semantic-conventions": "^1.30.0",
38
38
  "@rsdk/actx": "*",
39
39
  "@rsdk/cli.common": "*",
40
+ "@rsdk/common.node": "*",
40
41
  "@rsdk/core": "*",
41
42
  "@rsdk/logging": "*",
43
+ "@rsdk/profiling.common": "*",
42
44
  "reflect-metadata": "^0.1.12 || ^0.2.0",
43
45
  "rxjs": "^7.1.0"
44
46
  },
@@ -78,7 +80,10 @@
78
80
  },
79
81
  "@opentelemetry/semantic-conventions": {
80
82
  "optional": true
83
+ },
84
+ "@rsdk/profiling.common": {
85
+ "optional": true
81
86
  }
82
87
  },
83
- "gitHead": "73cae60f47c13e668ab69803051724bbc54008af"
88
+ "gitHead": "5c57cb5f847d357896054931b63a2c20094faeca"
84
89
  }
@@ -0,0 +1,220 @@
1
+ import type {
2
+ GaugeMetricData,
3
+ Histogram as OtelHistogram,
4
+ HistogramMetricData,
5
+ MetricData,
6
+ SumMetricData,
7
+ } from '@opentelemetry/sdk-metrics';
8
+ import {
9
+ AggregationTemporality,
10
+ DataPointType,
11
+ InstrumentType,
12
+ } from '@opentelemetry/sdk-metrics';
13
+ import { Counter, Gauge, Histogram, Registry, Summary } from 'prom-client';
14
+
15
+ import { PromClientMetricProducer } from './exporter';
16
+
17
+ async function collect(
18
+ registry: Registry,
19
+ ): Promise<{ metrics: MetricData[]; errors: unknown[] }> {
20
+ const { resourceMetrics, errors } = await new PromClientMetricProducer(
21
+ () => registry,
22
+ ).collect();
23
+
24
+ return { metrics: resourceMetrics.scopeMetrics[0]?.metrics ?? [], errors };
25
+ }
26
+
27
+ function byName<T extends MetricData>(metrics: MetricData[], name: string): T {
28
+ const metric = metrics.find((m) => m.descriptor.name === name);
29
+
30
+ if (!metric) throw new Error(`metric ${name} not found`);
31
+
32
+ return metric as T;
33
+ }
34
+
35
+ describe('PromClientMetricProducer', () => {
36
+ let registry: Registry;
37
+
38
+ beforeEach(() => {
39
+ registry = new Registry();
40
+ });
41
+
42
+ it('конвертирует counter в монотонный кумулятивный sum', async () => {
43
+ const counter = new Counter({
44
+ name: 'calls_total',
45
+ help: 'calls',
46
+ labelNames: ['route'],
47
+ registers: [registry],
48
+ });
49
+
50
+ counter.inc({ route: '/a' }, 2);
51
+ counter.inc({ route: '/b' });
52
+
53
+ const { metrics, errors } = await collect(registry);
54
+ const sum = byName<SumMetricData>(metrics, 'calls_total');
55
+
56
+ expect(errors).toEqual([]);
57
+ expect(sum.descriptor).toMatchObject({
58
+ description: 'calls',
59
+ type: InstrumentType.COUNTER,
60
+ });
61
+ expect(sum.dataPointType).toBe(DataPointType.SUM);
62
+ expect(sum.isMonotonic).toBe(true);
63
+ expect(sum.aggregationTemporality).toBe(AggregationTemporality.CUMULATIVE);
64
+ expect(sum.dataPoints.map((p) => [p.attributes, p.value])).toEqual([
65
+ [{ route: '/a' }, 2],
66
+ [{ route: '/b' }, 1],
67
+ ]);
68
+ });
69
+
70
+ it('отбрасывает точки gauge с NaN и Infinity', async () => {
71
+ const gauge = new Gauge({
72
+ name: 'latency',
73
+ help: 'latency',
74
+ labelNames: ['kind'],
75
+ registers: [registry],
76
+ });
77
+
78
+ gauge.set({ kind: 'ok' }, 5);
79
+ gauge.set({ kind: 'nan' }, Number.NaN);
80
+ gauge.set({ kind: 'inf' }, Number.POSITIVE_INFINITY);
81
+
82
+ const { metrics } = await collect(registry);
83
+ const otel = byName<GaugeMetricData>(metrics, 'latency');
84
+
85
+ expect(otel.dataPointType).toBe(DataPointType.GAUGE);
86
+ expect(otel.dataPoints.map((p) => [p.attributes, p.value])).toEqual([
87
+ [{ kind: 'ok' }, 5],
88
+ ]);
89
+ });
90
+
91
+ it('не экспортирует метрику, у которой не осталось точек', async () => {
92
+ new Gauge({ name: 'empty', help: 'empty', registers: [registry] }).set(
93
+ Number.NaN,
94
+ );
95
+
96
+ const { metrics } = await collect(registry);
97
+
98
+ expect(metrics).toEqual([]);
99
+ });
100
+
101
+ it('переводит кумулятивные бакеты histogram в счетчики бакетов', async () => {
102
+ const histogram = new Histogram({
103
+ name: 'duration',
104
+ help: 'duration',
105
+ labelNames: ['route'],
106
+ buckets: [1, 5, 10],
107
+ registers: [registry],
108
+ });
109
+
110
+ for (const v of [0.5, 3, 4, 7, 20]) histogram.observe({ route: '/a' }, v);
111
+ histogram.observe({ route: '/b' }, 2);
112
+
113
+ const { metrics } = await collect(registry);
114
+ const otel = byName<HistogramMetricData>(metrics, 'duration');
115
+ const [a, b] = otel.dataPoints;
116
+
117
+ expect(metrics.map((m) => m.descriptor.name)).toEqual(['duration']);
118
+ expect(otel.dataPointType).toBe(DataPointType.HISTOGRAM);
119
+ expect(otel.dataPoints).toHaveLength(2);
120
+ expect(a.attributes).toEqual({ route: '/a' });
121
+ expect(a.value).toEqual<OtelHistogram>({
122
+ count: 5,
123
+ sum: 34.5,
124
+ buckets: { boundaries: [1, 5, 10], counts: [1, 2, 1, 1] },
125
+ });
126
+ expect(b.attributes).toEqual({ route: '/b' });
127
+ expect(b.value.buckets.counts).toEqual([0, 1, 0, 0]);
128
+ });
129
+
130
+ it('раскладывает summary на квантили, _sum и _count', async () => {
131
+ const summary = new Summary({
132
+ name: 'request',
133
+ help: 'request',
134
+ labelNames: ['route'],
135
+ percentiles: [0.5, 0.9],
136
+ registers: [registry],
137
+ });
138
+
139
+ for (const v of [1, 2, 3]) summary.observe({ route: '/a' }, v);
140
+
141
+ const { metrics } = await collect(registry);
142
+ const quantiles = byName<GaugeMetricData>(metrics, 'request');
143
+ const sum = byName<SumMetricData>(metrics, 'request_sum');
144
+ const count = byName<SumMetricData>(metrics, 'request_count');
145
+
146
+ expect(quantiles.dataPointType).toBe(DataPointType.GAUGE);
147
+ expect(quantiles.dataPoints.map((p) => p.attributes)).toEqual([
148
+ { quantile: 0.5, route: '/a' },
149
+ { quantile: 0.9, route: '/a' },
150
+ ]);
151
+
152
+ expect(sum.isMonotonic).toBe(false);
153
+ expect(sum.dataPoints.map((p) => [p.attributes, p.value])).toEqual([
154
+ [{ route: '/a' }, 6],
155
+ ]);
156
+
157
+ expect(count.isMonotonic).toBe(true);
158
+ expect(count.dataPoints.map((p) => [p.attributes, p.value])).toEqual([
159
+ [{ route: '/a' }, 3],
160
+ ]);
161
+ });
162
+
163
+ it('добавляет default labels registry', async () => {
164
+ registry.setDefaultLabels({ app: 'example' });
165
+ new Counter({ name: 'c_total', help: 'c', registers: [registry] }).inc();
166
+
167
+ const { metrics } = await collect(registry);
168
+
169
+ expect(metrics[0].dataPoints[0].attributes).toEqual({ app: 'example' });
170
+ });
171
+
172
+ it('ставит всем точкам одно время сбора', async () => {
173
+ new Counter({ name: 'a_total', help: 'a', registers: [registry] }).inc();
174
+ new Gauge({ name: 'b', help: 'b', registers: [registry] }).set(1);
175
+
176
+ const { metrics } = await collect(registry);
177
+ const [first, second] = metrics.map((m) => m.dataPoints[0]);
178
+
179
+ expect(first.endTime).toEqual(second.endTime);
180
+ expect(first.startTime).toEqual(second.startTime);
181
+ expect(first.startTime[0]).toBeLessThanOrEqual(first.endTime[0]);
182
+ });
183
+
184
+ it('не бросает, если сбор метрик в registry упал', async () => {
185
+ new Gauge({
186
+ name: 'broken',
187
+ help: 'broken',
188
+ registers: [registry],
189
+ collect(): void {
190
+ throw new Error('collect failed');
191
+ },
192
+ });
193
+
194
+ const { metrics, errors } = await collect(registry);
195
+
196
+ expect(metrics).toEqual([]);
197
+ expect(errors).toEqual([new Error('collect failed')]);
198
+ });
199
+
200
+ it('экспортирует остальные метрики, если одна не сконвертировалась', async () => {
201
+ const counter = new Counter({
202
+ name: 'ok_total',
203
+ help: 'ok',
204
+ registers: [],
205
+ });
206
+
207
+ counter.inc();
208
+ const fakeRegistry = {
209
+ getMetricsAsJSON: async () => [
210
+ { name: 'broken', help: 'broken', type: 'histogram', values: null },
211
+ await counter.get(),
212
+ ],
213
+ } as unknown as Registry;
214
+
215
+ const { metrics, errors } = await collect(fakeRegistry);
216
+
217
+ expect(metrics.map((m) => m.descriptor.name)).toEqual(['ok_total']);
218
+ expect(errors).toHaveLength(1);
219
+ });
220
+ });
@@ -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
+ }
@@ -20,9 +20,14 @@ import {
20
20
  ATTR_SERVICE_NAME,
21
21
  ATTR_SERVICE_VERSION,
22
22
  } from '@opentelemetry/semantic-conventions';
23
+ import { onProcessShutdown } from '@rsdk/common.node';
23
24
  import { ClientRequest, IncomingMessage } from 'node:http';
24
25
  import path from 'node:path';
25
26
  import { cwd } from 'node:process';
27
+ import type { Registry } from 'prom-client';
28
+
29
+ import { PromClientMetricProducer } from './exporter';
30
+ import { createProfilingContextManager } from './profiling.context-manager';
26
31
 
27
32
  const otelDiagLogLevel = process.env.OTEL_DIAG_LOG_LEVEL;
28
33
  if (otelDiagLogLevel) {
@@ -85,6 +90,9 @@ const autoInstumentationOptions: any[] = getNodeAutoInstrumentations({
85
90
  },
86
91
  '@opentelemetry/instrumentation-pino': {
87
92
  enabled: true,
93
+
94
+ // логи отправляет transport (LOG_OTEL_ENABLED), иначе они дублируются
95
+ disableLogSending: true,
88
96
  logHook(_span: Span, record: Record<string, any>) {
89
97
  record['resource.service.name'] = otelServiceName;
90
98
  },
@@ -99,6 +107,9 @@ const autoInstumentationOptions: any[] = getNodeAutoInstrumentations({
99
107
 
100
108
  const otelServiceName = process.env.OTEL_SERVICE_NAME ?? manifestData.name;
101
109
 
110
+ // без него transport отправляет логи с service.name=unknown_service
111
+ process.env.LOG_OTEL_SERVICE_NAME ??= otelServiceName;
112
+
102
113
  const textMapPropagator = new CompositePropagator({
103
114
  propagators: [
104
115
  new B3Propagator(),
@@ -113,12 +124,36 @@ const resource = new Resource({
113
124
  [ATTR_SERVICE_VERSION]: manifestData.version,
114
125
  });
115
126
 
127
+ // registry берем у prom-client из @rsdk/core приложения: у копии из CLI он свой
128
+ const appMetricsRegistry = (): Registry => {
129
+ const corePath = require.resolve('@rsdk/core', { paths: [cwd()] });
130
+ const promClientPath = require.resolve('prom-client', {
131
+ paths: [path.dirname(corePath)],
132
+ });
133
+
134
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
135
+ return require(promClientPath).register;
136
+ };
137
+
138
+ // NodeSDK читает OTEL_METRIC_EXPORT_* только для своего reader'а, а этот создан вручную
139
+ const envMillis = (name: string): number | undefined =>
140
+ Number.parseInt(process.env[name] ?? '') || undefined;
141
+ const exportIntervalMillis = envMillis('OTEL_METRIC_EXPORT_INTERVAL');
142
+ const exportTimeoutMillis = envMillis('OTEL_METRIC_EXPORT_TIMEOUT');
143
+
116
144
  const traceExporter = new OTLPTraceExporter();
117
145
  const metricExporter = new OTLPMetricExporter();
118
146
  const metricReader = new PeriodicExportingMetricReader({
119
147
  exporter: metricExporter,
148
+ ...(exportIntervalMillis === undefined ? {} : { exportIntervalMillis }),
149
+ ...(exportTimeoutMillis === undefined ? {} : { exportTimeoutMillis }),
150
+ metricProducers: [new PromClientMetricProducer(appMetricsRegistry)],
120
151
  });
121
152
 
153
+ // прелоад профилирования подключается раньше и уже зарегистрировал связь
154
+ // профилей со спанами
155
+ const contextManager = createProfilingContextManager();
156
+
122
157
  const sdk = new NodeSDK({
123
158
  serviceName: otelServiceName,
124
159
  instrumentations: [autoInstumentationOptions],
@@ -126,6 +161,7 @@ const sdk = new NodeSDK({
126
161
  traceExporter,
127
162
  metricReader,
128
163
  textMapPropagator,
164
+ ...(contextManager && { contextManager }),
129
165
  resourceDetectors: [
130
166
  containerDetector,
131
167
  envDetector,
@@ -138,23 +174,12 @@ const sdk = new NodeSDK({
138
174
  sdk.start();
139
175
  console.log('Tracing sdk started');
140
176
 
141
- const signals = ['SIGTERM', 'SIGINT'] as const;
142
-
143
- const listener: any = async () => {
177
+ onProcessShutdown(async (signal) => {
144
178
  try {
145
- console.log('[SIGTERM] Tracing terminating...');
179
+ console.log(`[${signal}] Tracing terminating...`);
146
180
  await sdk.shutdown();
147
181
  console.log('Tracing terminated');
148
182
  } catch (error) {
149
183
  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
184
  }
156
- };
157
-
158
- for (const signal of signals) {
159
- process.on(signal, listener);
160
- }
185
+ });