@rsdk/cli.cmd.start 5.15.0-next.8 → 5.15.0-next.9
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.
- package/dist/opentelemetry/opentelemetry.init.js +8 -22
- package/dist/opentelemetry/opentelemetry.init.js.map +1 -1
- package/dist/opentelemetry/profiling.context-manager.d.ts +6 -0
- package/dist/opentelemetry/profiling.context-manager.js +87 -0
- package/dist/opentelemetry/profiling.context-manager.js.map +1 -0
- package/dist/profiling/profiling.d.ts +10 -0
- package/dist/profiling/profiling.js +34 -0
- package/dist/profiling/profiling.js.map +1 -0
- package/dist/start-dev.cmd.d.ts +1 -1
- package/dist/start-dev.cmd.js +17 -3
- package/dist/start-dev.cmd.js.map +1 -1
- package/dist/start.cmd.d.ts +1 -1
- package/dist/start.cmd.js +12 -2
- package/dist/start.cmd.js.map +1 -1
- package/package.json +7 -2
- package/src/opentelemetry/opentelemetry.init.ts +9 -26
- package/src/opentelemetry/profiling.context-manager.spec.ts +93 -0
- package/src/opentelemetry/profiling.context-manager.ts +118 -0
- package/src/profiling/profiling.ts +37 -0
- package/src/start-dev.cmd.ts +24 -2
- package/src/start.cmd.ts +21 -1
|
@@ -14,10 +14,12 @@ const resources_1 = require("@opentelemetry/resources");
|
|
|
14
14
|
const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
|
|
15
15
|
const sdk_node_1 = require("@opentelemetry/sdk-node");
|
|
16
16
|
const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
|
|
17
|
+
const common_node_1 = require("@rsdk/common.node");
|
|
17
18
|
const node_http_1 = require("node:http");
|
|
18
19
|
const node_path_1 = __importDefault(require("node:path"));
|
|
19
20
|
const node_process_1 = require("node:process");
|
|
20
21
|
const exporter_1 = require("./exporter");
|
|
22
|
+
const profiling_context_manager_1 = require("./profiling.context-manager");
|
|
21
23
|
const otelDiagLogLevel = process.env.OTEL_DIAG_LOG_LEVEL;
|
|
22
24
|
if (otelDiagLogLevel) {
|
|
23
25
|
console.log('telemetry diag enabled:', otelDiagLogLevel);
|
|
@@ -121,6 +123,9 @@ const metricReader = new sdk_metrics_1.PeriodicExportingMetricReader({
|
|
|
121
123
|
...(exportTimeoutMillis === undefined ? {} : { exportTimeoutMillis }),
|
|
122
124
|
metricProducers: [new exporter_1.PromClientMetricProducer(appMetricsRegistry)],
|
|
123
125
|
});
|
|
126
|
+
// прелоад профилирования подключается раньше и уже зарегистрировал связь
|
|
127
|
+
// профилей со спанами
|
|
128
|
+
const contextManager = (0, profiling_context_manager_1.createProfilingContextManager)();
|
|
124
129
|
const sdk = new sdk_node_1.NodeSDK({
|
|
125
130
|
serviceName: otelServiceName,
|
|
126
131
|
instrumentations: [autoInstumentationOptions],
|
|
@@ -128,6 +133,7 @@ const sdk = new sdk_node_1.NodeSDK({
|
|
|
128
133
|
traceExporter,
|
|
129
134
|
metricReader,
|
|
130
135
|
textMapPropagator,
|
|
136
|
+
...(contextManager && { contextManager }),
|
|
131
137
|
resourceDetectors: [
|
|
132
138
|
resource_detector_container_1.containerDetector,
|
|
133
139
|
resources_1.envDetector,
|
|
@@ -138,9 +144,7 @@ const sdk = new sdk_node_1.NodeSDK({
|
|
|
138
144
|
});
|
|
139
145
|
sdk.start();
|
|
140
146
|
console.log('Tracing sdk started');
|
|
141
|
-
|
|
142
|
-
let sdkShutdown;
|
|
143
|
-
const shutdownSdk = async (signal) => {
|
|
147
|
+
(0, common_node_1.onProcessShutdown)(async (signal) => {
|
|
144
148
|
try {
|
|
145
149
|
console.log(`[${signal}] Tracing terminating...`);
|
|
146
150
|
await sdk.shutdown();
|
|
@@ -149,23 +153,5 @@ const shutdownSdk = async (signal) => {
|
|
|
149
153
|
catch (error) {
|
|
150
154
|
console.log('Error terminating tracing', error);
|
|
151
155
|
}
|
|
152
|
-
};
|
|
153
|
-
// Процесс завершает Nest (enableShutdownHooks): после своих хуков он повторяет
|
|
154
|
-
// сигнал. process.exit здесь оборвал бы эти хуки, поэтому только останавливаем
|
|
155
|
-
// SDK и снимаем обработчик, чтобы повторный сигнал завершил процесс
|
|
156
|
-
const listener = (signal) => {
|
|
157
|
-
if (!sdkShutdown) {
|
|
158
|
-
sdkShutdown = shutdownSdk(signal).then(() => {
|
|
159
|
-
for (const s of signals)
|
|
160
|
-
process.removeListener(s, listener);
|
|
161
|
-
});
|
|
162
|
-
if (process.listenerCount(signal) > 1)
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
// сигнал повторил Nest раньше, чем остановился SDK, или Nest нет
|
|
166
|
-
void sdkShutdown.then(() => process.kill(process.pid, signal));
|
|
167
|
-
};
|
|
168
|
-
for (const signal of signals) {
|
|
169
|
-
process.on(signal, listener);
|
|
170
|
-
}
|
|
156
|
+
});
|
|
171
157
|
//# sourceMappingURL=opentelemetry.init.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opentelemetry.init.js","sourceRoot":"","sources":["../../src/opentelemetry/opentelemetry.init.ts"],"names":[],"mappings":";;;;;AAEA,4CAA2E;AAC3E,0FAAwF;AACxF,8CAA0D;AAC1D,0FAA+E;AAC/E,sFAA4E;AAC5E,gEAA8E;AAC9E,4FAA+E;AAC/E,wDAMkC;AAClC,4DAA2E;AAC3E,sDAAkD;AAClD,8EAG6C;AAC7C,yCAA2D;AAC3D,0DAA6B;AAC7B,+CAAmC;AAGnC,yCAAsD;
|
|
1
|
+
{"version":3,"file":"opentelemetry.init.js","sourceRoot":"","sources":["../../src/opentelemetry/opentelemetry.init.ts"],"names":[],"mappings":";;;;;AAEA,4CAA2E;AAC3E,0FAAwF;AACxF,8CAA0D;AAC1D,0FAA+E;AAC/E,sFAA4E;AAC5E,gEAA8E;AAC9E,4FAA+E;AAC/E,wDAMkC;AAClC,4DAA2E;AAC3E,sDAAkD;AAClD,8EAG6C;AAC7C,mDAAsD;AACtD,yCAA2D;AAC3D,0DAA6B;AAC7B,+CAAmC;AAGnC,yCAAsD;AACtD,2EAA4E;AAE5E,MAAM,gB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BAAoB,EAAE,CAAC;IACvE,GAAG,CAAC,mBAAmB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC;IACrE,eAAe,EAAE,CAAC,IAAI,mCAAwB,CAAC,kBAAkB,CAAC,CAAC;CACpE,CAAC,CAAC;AAEH,yEAAyE;AACzE,sBAAsB;AACtB,MAAM,cAAc,GAAG,IAAA,yDAA6B,GAAE,CAAC;AAEvD,MAAM,GAAG,GAAG,IAAI,kBAAO,CAAC;IACtB,WAAW,EAAE,eAAe;IAC5B,gBAAgB,EAAE,CAAC,yBAAyB,CAAC;IAC7C,QAAQ;IACR,aAAa;IACb,YAAY;IACZ,iBAAiB;IACjB,GAAG,CAAC,cAAc,IAAI,EAAE,cAAc,EAAE,CAAC;IACzC,iBAAiB,EAAE;QACjB,+CAAiB;QACjB,uBAAW;QACX,wBAAY;QACZ,sBAAU;QACV,2BAAe;KAChB;CACF,CAAC,CAAC;AAEH,GAAG,CAAC,KAAK,EAAE,CAAC;AACZ,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAEnC,IAAA,+BAAiB,EAAC,KAAK,EAAE,MAAM,EAAE,EAAE;IACjC,IAAI,CAAC;QACH,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,0BAA0B,CAAC,CAAC;QAClD,MAAM,GAAG,CAAC,QAAQ,EAAE,CAAC;QACrB,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,GAAG,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,CAAC;AACH,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ContextManager } from '@opentelemetry/api';
|
|
2
|
+
/**
|
|
3
|
+
* Без запущенного профилирования или при ошибке возвращает undefined.
|
|
4
|
+
* Тогда NodeSDK берет свой context manager
|
|
5
|
+
*/
|
|
6
|
+
export declare function createProfilingContextManager(): ContextManager | undefined;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createProfilingContextManager = createProfilingContextManager;
|
|
7
|
+
const api_1 = require("@opentelemetry/api");
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
/**
|
|
10
|
+
* Без запущенного профилирования или при ошибке возвращает undefined.
|
|
11
|
+
* Тогда NodeSDK берет свой context manager
|
|
12
|
+
*/
|
|
13
|
+
function createProfilingContextManager() {
|
|
14
|
+
const runWithSpanProfile = loadSpanProfiling();
|
|
15
|
+
if (!runWithSpanProfile) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return new (profilingContextManager(loadAsyncHooks().AsyncLocalStorageContextManager, runWithSpanProfile))();
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
console.warn(`Profiles are not linked to spans: ${error.message}`);
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Пакет профилирования ищется в приложении, как и его прелоад. Без пакета
|
|
28
|
+
* профили со спанами не связываются
|
|
29
|
+
*/
|
|
30
|
+
function loadSpanProfiling() {
|
|
31
|
+
let resolved;
|
|
32
|
+
try {
|
|
33
|
+
resolved = require.resolve('@rsdk/profiling.common/span-profiling', {
|
|
34
|
+
paths: [process.cwd()],
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
41
|
+
const { getSpanProfilingRunner } = require(resolved);
|
|
42
|
+
return getSpanProfilingRunner();
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Тот же модуль, из которого NodeSDK по умолчанию берет context manager,
|
|
46
|
+
* поэтому приложению не нужно ставить @opentelemetry/context-async-hooks
|
|
47
|
+
*/
|
|
48
|
+
function loadAsyncHooks() {
|
|
49
|
+
const sdkNode = node_path_1.default.dirname(require.resolve('@opentelemetry/sdk-node'));
|
|
50
|
+
const sdkTraceNode = node_path_1.default.dirname(require.resolve('@opentelemetry/sdk-trace-node', { paths: [sdkNode] }));
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
52
|
+
return require(require.resolve('@opentelemetry/context-async-hooks', {
|
|
53
|
+
paths: [sdkTraceNode],
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Профиль привязывается к локальному корневому спану, работа дочерних попадает
|
|
58
|
+
* в него. Связь ставится оберткой вокруг активации спана, потому что
|
|
59
|
+
* профилировщик на pprof с AsyncContextFrame помечает сэмплы только внутри
|
|
60
|
+
* такой обертки
|
|
61
|
+
*/
|
|
62
|
+
function profilingContextManager(Base, runWithSpanProfile) {
|
|
63
|
+
return class ProfilingContextManager extends Base {
|
|
64
|
+
with(context, fn, thisArg, ...args) {
|
|
65
|
+
const span = api_1.trace.getSpan(context);
|
|
66
|
+
if (!span || !isLocalRoot(span, api_1.trace.getSpan(this.active()))) {
|
|
67
|
+
return super.with(context, fn, thisArg, ...args);
|
|
68
|
+
}
|
|
69
|
+
return runWithSpanProfile(span.spanContext().spanId, (attributes) => {
|
|
70
|
+
if (attributes) {
|
|
71
|
+
span.setAttributes(attributes);
|
|
72
|
+
}
|
|
73
|
+
return super.with(context, fn, thisArg, ...args);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Корневой спан активируется, когда активного спана нет
|
|
80
|
+
* или он пришел из другого сервиса
|
|
81
|
+
*/
|
|
82
|
+
function isLocalRoot(span, active) {
|
|
83
|
+
return (span !== active &&
|
|
84
|
+
span.isRecording() &&
|
|
85
|
+
(!active || active.spanContext().isRemote === true));
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=profiling.context-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"profiling.context-manager.js","sourceRoot":"","sources":["../../src/opentelemetry/profiling.context-manager.ts"],"names":[],"mappings":";;;;;AAUA,sEAmBC;AA5BD,4CAA2C;AAG3C,0DAA6B;AAE7B;;;GAGG;AACH,SAAgB,6BAA6B;IAC3C,MAAM,kBAAkB,GAAG,iBAAiB,EAAE,CAAC;IAE/C,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,uBAAuB,CACjC,cAAc,EAAE,CAAC,+BAA+B,EAChD,kBAAkB,CACnB,CAAC,EAAE,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,qCAAsC,KAAe,CAAC,OAAO,EAAE,CAChE,CAAC;QAEF,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAS,iBAAiB;IACxB,IAAI,QAAgB,CAAC;IAErB,IAAI,CAAC;QACH,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,uCAAuC,EAAE;YAClE,KAAK,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;SACvB,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,iEAAiE;IACjE,MAAM,EAAE,sBAAsB,EAAE,GAAG,OAAO,CAAC,QAAQ,CAGlD,CAAC;IAEF,OAAO,sBAAsB,EAAE,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,SAAS,cAAc;IACrB,MAAM,OAAO,GAAG,mBAAI,CAAC,O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AwB;IACvD,OAAO,CACL,IAAI,KAAK,MAAM;QACf,IAAI,CAAC,WAAW,EAAE;QAClB,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC,QAAQ,KAAK,IAAI,CAAC,CACpD,CAAC;AACJ,CAAC"}
|
|
@@ -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"}
|
package/dist/start-dev.cmd.d.ts
CHANGED
package/dist/start-dev.cmd.js
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
1
|
+
{"version":3,"file":"start-dev.cmd.js","sourceRoot":"","sources":["../src/start-dev.cmd.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,iDAA0E;AAC1E,2CAA8C;AAC9C,kDAA0B;AAC1B,0DAA6B;AAE7B,2EAA6E;AAC7E,qDAG+B;AAE/B,MAAa,WAAW;IACtB,MAAM,CAAC,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAG5C,AAAN,KAAK,CAAC,MAAM,CAEV,IAAa,EAGb,MAAe,EAGf,SAAuC;QAEvC,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,4CAAuB,CAAC,CAAC;QACpD,MAAM,GAAG,GAAsB,EAAE,CAAC;QAClC,MAAM,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC;QAE5B,IAAA,gCAAoB,EAAC,SAAS,CAAC,CAAC;QAEhC,MAAM,iBAAiB,GAAG,IAAA,oCAAwB,GAAE,CAAC;QAErD,2EAA2E;QAC3E,mEAAmE;QACnE,0EAA0E;QAC1E,IAAI,iBAAiB,EAAE,CAAC;YACtB,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC;QAClE,CAAC;QAED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C,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;YACH,MAAM,eAAe,CAAC;YACtB,OAAO;QACT,CAAC;QACD,KAAK,CAAC,MAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACnC,KAAK,CAAC,MAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACnC,MAAM,KAAK,CAAC;IACd,CAAC;;AAvEH,kCAwEC;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"}
|
package/dist/start.cmd.d.ts
CHANGED
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
|
package/dist/start.cmd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.cmd.js","sourceRoot":"","sources":["../src/start.cmd.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"start.cmd.js","sourceRoot":"","sources":["../src/start.cmd.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,iDAAiE;AACjE,2CAA8C;AAC9C,0DAA6B;AAE7B,2EAA6E;AAC7E,qDAG+B;AAE/B,MAAa,QAAQ;IACF,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAGnD,AAAN,KAAK,CAAC,MAAM,CAC+C,IAAa,EAGtE,SAAuC;QAEvC,IAAI,CAAC,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AA,IAAA,mBAAM,EAAC,WAAW,EAAE,wCAAwC,EAAE,MAAM,CAAC,CAAA;IACrE,WAAA,IAAA,0BAAa,GAAE,CAAA;;;;sCAuCjB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rsdk/cli.cmd.start",
|
|
3
|
-
"version": "5.15.0-next.
|
|
3
|
+
"version": "5.15.0-next.9",
|
|
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": "
|
|
88
|
+
"gitHead": "f8da4799d92dd62e259de4c774792cf2ae2788a5"
|
|
84
89
|
}
|
|
@@ -20,12 +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';
|
|
26
27
|
import type { Registry } from 'prom-client';
|
|
27
28
|
|
|
28
29
|
import { PromClientMetricProducer } from './exporter';
|
|
30
|
+
import { createProfilingContextManager } from './profiling.context-manager';
|
|
29
31
|
|
|
30
32
|
const otelDiagLogLevel = process.env.OTEL_DIAG_LOG_LEVEL;
|
|
31
33
|
if (otelDiagLogLevel) {
|
|
@@ -148,6 +150,10 @@ const metricReader = new PeriodicExportingMetricReader({
|
|
|
148
150
|
metricProducers: [new PromClientMetricProducer(appMetricsRegistry)],
|
|
149
151
|
});
|
|
150
152
|
|
|
153
|
+
// прелоад профилирования подключается раньше и уже зарегистрировал связь
|
|
154
|
+
// профилей со спанами
|
|
155
|
+
const contextManager = createProfilingContextManager();
|
|
156
|
+
|
|
151
157
|
const sdk = new NodeSDK({
|
|
152
158
|
serviceName: otelServiceName,
|
|
153
159
|
instrumentations: [autoInstumentationOptions],
|
|
@@ -155,6 +161,7 @@ const sdk = new NodeSDK({
|
|
|
155
161
|
traceExporter,
|
|
156
162
|
metricReader,
|
|
157
163
|
textMapPropagator,
|
|
164
|
+
...(contextManager && { contextManager }),
|
|
158
165
|
resourceDetectors: [
|
|
159
166
|
containerDetector,
|
|
160
167
|
envDetector,
|
|
@@ -167,11 +174,7 @@ const sdk = new NodeSDK({
|
|
|
167
174
|
sdk.start();
|
|
168
175
|
console.log('Tracing sdk started');
|
|
169
176
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
let sdkShutdown: Promise<void> | undefined;
|
|
173
|
-
|
|
174
|
-
const shutdownSdk = async (signal: NodeJS.Signals): Promise<void> => {
|
|
177
|
+
onProcessShutdown(async (signal) => {
|
|
175
178
|
try {
|
|
176
179
|
console.log(`[${signal}] Tracing terminating...`);
|
|
177
180
|
await sdk.shutdown();
|
|
@@ -179,24 +182,4 @@ const shutdownSdk = async (signal: NodeJS.Signals): Promise<void> => {
|
|
|
179
182
|
} catch (error) {
|
|
180
183
|
console.log('Error terminating tracing', error);
|
|
181
184
|
}
|
|
182
|
-
};
|
|
183
|
-
|
|
184
|
-
// Процесс завершает Nest (enableShutdownHooks): после своих хуков он повторяет
|
|
185
|
-
// сигнал. process.exit здесь оборвал бы эти хуки, поэтому только останавливаем
|
|
186
|
-
// SDK и снимаем обработчик, чтобы повторный сигнал завершил процесс
|
|
187
|
-
const listener = (signal: NodeJS.Signals): void => {
|
|
188
|
-
if (!sdkShutdown) {
|
|
189
|
-
sdkShutdown = shutdownSdk(signal).then(() => {
|
|
190
|
-
for (const s of signals) process.removeListener(s, listener);
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
if (process.listenerCount(signal) > 1) return;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// сигнал повторил Nest раньше, чем остановился SDK, или Nest нет
|
|
197
|
-
void sdkShutdown.then(() => process.kill(process.pid, signal));
|
|
198
|
-
};
|
|
199
|
-
|
|
200
|
-
for (const signal of signals) {
|
|
201
|
-
process.on(signal, listener);
|
|
202
|
-
}
|
|
185
|
+
});
|
|
@@ -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,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
|
+
}
|
package/src/start-dev.cmd.ts
CHANGED
|
@@ -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
|
-
|
|
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);
|