@rsdk/profiling.pyroscope 0.0.0-stage → 5.11.6-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import type { PprofProfile } from '@rsdk/profiling.common';
2
+ /**
3
+ * Переименовывает функции, как @pyroscope/nodejs: `./src/user.service.ts:findOne:12`.
4
+ * Flame graph в Pyroscope показывает только имена, и без пути одноименные
5
+ * методы разных классов не различить
6
+ */
7
+ export declare function addLocationToFunctionNames(profile: PprofProfile, cwd: string): void;
@@ -0,0 +1,35 @@
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.addLocationToFunctionNames = addLocationToFunctionNames;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ /**
9
+ * Переименовывает функции, как @pyroscope/nodejs: `./src/user.service.ts:findOne:12`.
10
+ * Flame graph в Pyroscope показывает только имена, и без пути одноименные
11
+ * методы разных классов не различить
12
+ */
13
+ function addLocationToFunctionNames(profile, cwd) {
14
+ const { strings } = profile.stringTable;
15
+ const functions = new Map(profile.function.map((fn) => [Number(fn.id), fn]));
16
+ const renamed = new Set();
17
+ for (const location of profile.location) {
18
+ for (const line of location.line) {
19
+ const id = Number(line.functionId);
20
+ const fn = functions.get(id);
21
+ const file = fn && strings[Number(fn.filename)];
22
+ // у (program), (garbage collector) и нативных фреймов файла нет
23
+ if (!fn || !file || renamed.has(id)) {
24
+ continue;
25
+ }
26
+ const name = `${relativeToCwd(file, cwd)}:${strings[Number(fn.name)]}:${line.line}`;
27
+ fn.name = profile.stringTable.dedup(name);
28
+ renamed.add(id);
29
+ }
30
+ }
31
+ }
32
+ function relativeToCwd(file, cwd) {
33
+ return file.startsWith(cwd + node_path_1.default.sep) ? `.${file.slice(cwd.length)}` : file;
34
+ }
35
+ //# sourceMappingUR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C,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,IAAY,EAAE,GAAW;IAC9C,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,GAAG,mBAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC/E,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { ProfilerProvider } from '@rsdk/profiling.common';
2
+ export declare const profiler: ProfilerProvider;
3
+ export { PyroscopeConfig, readPyroscopeConfig } from './pyroscope.config';
4
+ export { PyroscopeExporter } from './pyroscope.exporter';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PyroscopeExporter = exports.readPyroscopeConfig = exports.profiler = void 0;
4
+ const profiling_common_1 = require("@rsdk/profiling.common");
5
+ const function_names_1 = require("./function-names");
6
+ const pyroscope_config_1 = require("./pyroscope.config");
7
+ const pyroscope_exporter_1 = require("./pyroscope.exporter");
8
+ exports.profiler = {
9
+ create({ env, appName, appVersion, settings, logger, sourceMapper, prepareProfile, }) {
10
+ const config = (0, pyroscope_config_1.readPyroscopeConfig)(env, appName, appVersion);
11
+ logger.info(`Profiles are sent to Pyroscope ${config.serverAddress} as ${config.applicationName}`);
12
+ return new profiling_common_1.PprofProfiler(settings, new pyroscope_exporter_1.PyroscopeExporter(config), logger, sourceMapper, prepareProfile);
13
+ },
14
+ // по лейблу Pyroscope отдает профиль спана, а по атрибуту Grafana
15
+ // находит его из трейса
16
+ spanLink: { label: 'span_id', attribute: 'pyroscope.profile.id' },
17
+ prepareProfile: function_names_1.addLocationToFunctionNames,
18
+ };
19
+ var pyroscope_config_2 = require("./pyroscope.config");
20
+ Object.defineProperty(exports, "readPyroscopeConfig", { enumerable: true, get: function () { return pyroscope_config_2.readPyroscopeConfig; } });
21
+ var pyroscope_exporter_2 = require("./pyroscope.exporter");
22
+ Object.defineProperty(exports, "PyroscopeExporter", { enumerable: true, get: function () { return pyroscope_exporter_2.PyroscopeExporter; } });
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AACA,6DAAuD;AAEvD,qDAA8D;AAC9D,yDAAyD;AACzD,6DAAyD;AAE5C,QAAA,QAAQ,GAAqB;IACxC,MAAM,CAAC,EACL,GAAG,EACH,OAAO,EACP,UAAU,EACV,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,cAAc,GACf;QACC,MAAM,MAAM,GAAG,IAAA,sCAAmB,EAAC,GAAG,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAE7D,MAAM,CAAC,IAAI,CACT,kCAAkC,MAAM,CAAC,aAAa,OAAO,MAAM,CAAC,eAAe,EAAE,CACtF,CAAC;QAEF,OAAO,IAAI,gCAAa,CACtB,QAAQ,EACR,IAAI,sCAAiB,CAAC,MAAM,CAAC,EAC7B,MAAM,EACN,YAAY,EACZ,cAAc,CACf,CAAC;IACJ,CAAC;IAED,kEAAkE;IAClE,wBAAwB;IACxB,QAAQ,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,sBAAsB,EAAE;IAEjE,cAAc,EAAE,2CAA0B;CAC3C,CAAC;AAEF,uDAA0E;AAAhD,uHAAA,mBAAmB,OAAA;AAC7C,2DAAyD;AAAhD,uHAAA,iBAAiB,OAAA"}
@@ -0,0 +1,11 @@
1
+ import type { ProfilingEnv } from '@rsdk/profiling.common';
2
+ export interface PyroscopeConfig {
3
+ serverAddress: string;
4
+ applicationName: string;
5
+ tags: Record<string, string>;
6
+ authToken?: string | undefined;
7
+ basicAuthUser?: string | undefined;
8
+ basicAuthPassword?: string | undefined;
9
+ tenantId?: string | undefined;
10
+ }
11
+ export declare function readPyroscopeConfig(env: ProfilingEnv, appName: string, appVersion: string): PyroscopeConfig;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readPyroscopeConfig = readPyroscopeConfig;
4
+ const profiling_common_1 = require("@rsdk/profiling.common");
5
+ // Pyroscope собирает имя профиля как name{key=value,...}
6
+ const INVALID_LABEL_CHARS = /[{},=]/;
7
+ const TAG_NAME = /^[\w.]+$/;
8
+ function readPyroscopeConfig(env, appName, appVersion) {
9
+ const applicationName = env['PYROSCOPE_APPLICATION_NAME'] || appName;
10
+ assertLabel('PYROSCOPE_APPLICATION_NAME', applicationName);
11
+ return {
12
+ serverAddress: parseServerAddress(env['PYROSCOPE_SERVER_ADDRESS']),
13
+ applicationName,
14
+ tags: {
15
+ service_version: appVersion,
16
+ ...parseTags(env['PYROSCOPE_TAGS']),
17
+ },
18
+ authToken: env['PYROSCOPE_AUTH_TOKEN'] || undefined,
19
+ basicAuthUser: env['PYROSCOPE_BASIC_AUTH_USER'] || undefined,
20
+ basicAuthPassword: env['PYROSCOPE_BASIC_AUTH_PASSWORD'] || undefined,
21
+ tenantId: env['PYROSCOPE_TENANT_ID'] || undefined,
22
+ };
23
+ }
24
+ function parseServerAddress(value) {
25
+ if (!value) {
26
+ throw new Error('PYROSCOPE_SERVER_ADDRESS is not set');
27
+ }
28
+ if (!URL.canParse(value)) {
29
+ throw new profiling_common_1.InvalidProfilingSetting('PYROSCOPE_SERVER_ADDRESS', value, 'URL');
30
+ }
31
+ return value.replace(/\/+$/, '');
32
+ }
33
+ function parseTags(value) {
34
+ if (!value) {
35
+ return {};
36
+ }
37
+ let tags;
38
+ try {
39
+ tags = JSON.parse(value);
40
+ }
41
+ catch { }
42
+ if (!tags ||
43
+ typeof tags !== 'object' ||
44
+ Array.isArray(tags) ||
45
+ Object.values(tags).some((v) => typeof v !== 'string')) {
46
+ throw new profiling_common_1.InvalidProfilingSetting('PYROSCOPE_TAGS', value, 'JSON object with string values');
47
+ }
48
+ for (const [key, tag] of Object.entries(tags)) {
49
+ // Pyroscope отвечает 400 на имя лейбла с дефисом и другими символами
50
+ if (!TAG_NAME.test(key)) {
51
+ throw new profiling_common_1.InvalidProfilingSetting('PYROSCOPE_TAGS', key, 'tag name of letters, digits, _ and .');
52
+ }
53
+ assertLabel('PYROSCOPE_TAGS', tag);
54
+ }
55
+ return tags;
56
+ }
57
+ function assertLabel(key, value) {
58
+ if (INVALID_LABEL_CHARS.test(value)) {
59
+ throw new profiling_common_1.InvalidProfilingSetting(key, value, 'no {, }, "," and =');
60
+ }
61
+ }
62
+ //# sourceMappingURL=pyroscope.config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pyroscope.config.js","sourceRoot":"","sources":["../src/pyroscope.config.ts"],"names":[],"mappings":";;AAiBA,kDAqBC;AArCD,6DAAiE;AAEjE,yDAAyD;AACzD,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AACrC,MAAM,QAAQ,GAAG,UAAU,CAAC;AAY5B,SAAgB,mBAAmB,CACjC,GAAiB,EACjB,OAAe,EACf,UAAkB;IAElB,MAAM,eAAe,GAAG,GAAG,CAAC,4BAA4B,CAAC,IAAI,OAAO,CAAC;IAErE,WAAW,CAAC,4BAA4B,EAAE,eAAe,CAAC,CAAC;IAE3D,OAAO;QACL,aAAa,EAAE,kBAAkB,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAClE,eAAe;QACf,IAAI,EAAE;YACJ,eAAe,EAAE,UAAU;YAC3B,GAAG,SAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;SACpC;QACD,SAAS,EAAE,GAAG,CAAC,sBAAsB,CAAC,IAAI,SAAS;QACnD,aAAa,EAAE,GAAG,CAAC,2BAA2B,CAAC,IAAI,SAAS;QAC5D,iBAAiB,EAAE,GAAG,CAAC,+BAA+B,CAAC,IAAI,SAAS;QACpE,QAAQ,EAAE,GAAG,CAAC,qBAAqB,CAAC,IAAI,SAAS;K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AAW,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IACrC,CAAC;IAED,OAAO,IAA8B,CAAC;AACxC,CAAC;AAED,SAAS,WAAW,CAAC,GAAW,EAAE,KAAa;IAC7C,IAAI,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACpC,MAAM,IAAI,0CAAuB,CAAC,GAAG,EAAE,KAAK,EAAE,oBAAoB,CAAC,CAAC;IACtE,CAAC;AACH,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { ProfileExport, ProfileExporter } from '@rsdk/profiling.common';
2
+ import type { PyroscopeConfig } from './pyroscope.config';
3
+ /**
4
+ * Отправляет профили в Pyroscope через /ingest в формате pprof,
5
+ * как @pyroscope/nodejs
6
+ */
7
+ export declare class PyroscopeExporter implements ProfileExporter {
8
+ private readonly config;
9
+ private readonly name;
10
+ private readonly headers;
11
+ constructor(config: PyroscopeConfig);
12
+ export(profile: ProfileExport): Promise<void>;
13
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PyroscopeExporter = void 0;
4
+ const EXPORT_TIMEOUT_MS = 30_000;
5
+ /**
6
+ * Отправляет профили в Pyroscope через /ingest в формате pprof,
7
+ * как @pyroscope/nodejs
8
+ */
9
+ class PyroscopeExporter {
10
+ config;
11
+ name;
12
+ headers;
13
+ constructor(config) {
14
+ this.config = config;
15
+ const tags = Object.entries(config.tags)
16
+ .map(([key, value]) => `${key}=${value}`)
17
+ .join(',');
18
+ this.name = `${config.applicationName}{${tags}}`;
19
+ this.headers = buildHeaders(config);
20
+ }
21
+ async export(profile) {
22
+ const url = new URL(`${this.config.serverAddress}/ingest`);
23
+ url.searchParams.set('name', this.name);
24
+ url.searchParams.set('format', 'pprof');
25
+ url.searchParams.set('spyName', 'nodespy');
26
+ url.searchParams.set('from', unixSeconds(profile.startedAt));
27
+ url.searchParams.set('until', unixSeconds(profile.stoppedAt));
28
+ if (profile.sampleRate !== undefined) {
29
+ url.searchParams.set('sampleRate', String(profile.sampleRate));
30
+ }
31
+ const response = await fetch(url, {
32
+ method: 'POST',
33
+ headers: this.headers,
34
+ body: profile.body,
35
+ signal: AbortSignal.timeout(EXPORT_TIMEOUT_MS),
36
+ });
37
+ if (!response.ok) {
38
+ throw new Error(`Pyroscope responded ${response.status}: ${await response.text()}`);
39
+ }
40
+ // непрочитанное тело держит соединение до сборки мусора
41
+ await response.body?.cancel();
42
+ }
43
+ }
44
+ exports.PyroscopeExporter = PyroscopeExporter;
45
+ function buildHeaders(config) {
46
+ const headers = {
47
+ 'Content-Type': 'application/octet-stream',
48
+ };
49
+ if (config.authToken) {
50
+ headers['Authorization'] = `Bearer ${config.authToken}`;
51
+ }
52
+ else if (config.basicAuthUser && config.basicAuthPassword) {
53
+ const credentials = Buffer.from(`${config.basicAuthUser}:${config.basicAuthPassword}`).toString('base64');
54
+ headers['Authorization'] = `Basic ${credentials}`;
55
+ }
56
+ if (config.tenantId) {
57
+ headers['X-Scope-OrgID'] = config.tenantId;
58
+ }
59
+ return headers;
60
+ }
61
+ function unixSeconds(date) {
62
+ return String(Math.floor(date.getTime() / 1000));
63
+ }
64
+ //# sourceMappingURL=pyroscope.exporter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pyroscope.exporter.js","sourceRoot":"","sources":["../src/pyroscope.exporter.ts"],"names":[],"mappings":";;;AAIA,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAEjC;;;GAGG;AACH,MAAa,iBAAiB;IAIC;IAHZ,IAAI,CAAS;IACb,OAAO,CAAyB;IAEjD,YAA6B,MAAuB;QAAvB,WAAM,GAAN,MAAM,CAAiB;QAClD,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;aACrC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC;aACxC,IAAI,C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CAAC,MAAM,KAAK,MAAM,QAAQ,CAAC,IAAI,EAAE,EAAE,CACnE,CAAC;QACJ,CAAC;QAED,wDAAwD;QACxD,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IAChC,CAAC;CACF;AA1CD,8CA0CC;AAED,SAAS,YAAY,CAAC,MAAuB;IAC3C,MAAM,OAAO,GAA2B;QACtC,cAAc,EAAE,0BAA0B;KAC3C,CAAC;IAEF,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QACrB,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,CAAC,SAAS,EAAE,CAAC;IAC1D,CAAC;SAAM,IAAI,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC5D,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAC7B,GAAG,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,iBAAiB,EAAE,CACtD,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAErB,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,WAAW,EAAE,CAAC;IACpD,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;QACpB,OAAO,CAAC,eAAe,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;IAC7C,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,WAAW,CAAC,IAAU;IAC7B,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;AACnD,CAAC"}
package/jest.config.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('@rsdk/jest/jest.config');
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@rsdk/profiling.pyroscope",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.11.6-next.0",
4
+ "description": "Pyroscope profiler for rsdk applications",
5
+ "license": "Apache License 2.0",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "url": "https://github.com/R-Vision/rsdk"
11
+ },
12
+ "main": "dist/index.js",
13
+ "scripts": {
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "peerDependencies": {
17
+ "@rsdk/common": "*",
18
+ "@rsdk/common.node": "*",
19
+ "@rsdk/logging": "*",
20
+ "@rsdk/profiling.common": "*"
21
+ },
22
+ "gitHead": "36ecf2006c7e322bc53eb12b81de37ac3719180c"
23
+ }
@@ -0,0 +1,95 @@
1
+ import {
2
+ Function as PprofFunction,
3
+ Line,
4
+ Location,
5
+ Profile,
6
+ StringTable,
7
+ } from 'pprof-format';
8
+
9
+ import { addLocationToFunctionNames } from './function-names';
10
+
11
+ type Frame = { name: string; file: string; line: number; functionId?: number };
12
+
13
+ function createProfile(frames: Frame[]): Profile {
14
+ const stringTable = new StringTable();
15
+ const functions = new Map<number, PprofFunction>();
16
+
17
+ for (const [index, frame] of frames.entries()) {
18
+ const id = frame.functionId ?? index + 1;
19
+
20
+ if (!functions.has(id)) {
21
+ functions.set(
22
+ id,
23
+ new PprofFunction({
24
+ id,
25
+ name: stringTable.dedup(frame.name),
26
+ filename: stringTable.dedup(frame.file),
27
+ }),
28
+ );
29
+ }
30
+ }
31
+
32
+ return new Profile({
33
+ stringTable,
34
+ function: [...functions.values()],
35
+ location: frames.map(
36
+ (frame, index) =>
37
+ new Location({
38
+ id: index + 1,
39
+ line: [
40
+ new Line({
41
+ functionId: frame.functionId ?? index + 1,
42
+ line: frame.line,
43
+ }),
44
+ ],
45
+ }),
46
+ ),
47
+ });
48
+ }
49
+
50
+ const names = (profile: Profile): string[] =>
51
+ profile.function.map((fn) => profile.stringTable.strings[Number(fn.name)]!);
52
+
53
+ describe('addLocationToFunctionNames', () => {
54
+ it('добавляет к имени путь от директории приложения и строку', () => {
55
+ const profile = createProfile([
56
+ { name: 'score', file: '/app/src/report.service.ts', line: 39 },
57
+ {
58
+ name: '(anonymous:L#36:C#51)',
59
+ file: '/app/node_modules/@nestjs/core/router/router-execution-context.js',
60
+ line: 36,
61
+ },
62
+ {
63
+ name: 'processTicksAndRejections',
64
+ file: 'node:internal/process/task_queues',
65
+ line: 72,
66
+ },
67
+ { name: '(program)', file: '', line: 0 },
68
+ ]);
69
+
70
+ addLocationToFunctionNames(profile, '/app');
71
+
72
+ expect(names(profile)).toEqual([
73
+ './src/report.service.ts:score:39',
74
+ './node_modules/@nestjs/core/router/router-execution-context.js:(anonymous:L#36:C#51):36',
75
+ 'node:internal/process/task_queues:processTicksAndRejections:72',
76
+ '(program)',
77
+ ]);
78
+ });
79
+
80
+ it('переименовывает функцию из нескольких локаций один раз', () => {
81
+ const profile = createProfile([
82
+ { name: 'score', file: '/app/src/report.service.ts', line: 39 },
83
+ {
84
+ name: 'score',
85
+ file: '/app/src/report.service.ts',
86
+ line: 40,
87
+ functionId: 1,
88
+ },
89
+ ]);
90
+
91
+ addLocationToFunctionNames(profile, '/app');
92
+
93
+ expect(names(profile)).toEqual(['./src/report.service.ts:score:39']);
94
+ });
95
+ });
@@ -0,0 +1,38 @@
1
+ import type { PprofProfile } from '@rsdk/profiling.common';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Переименовывает функции, как @pyroscope/nodejs: `./src/user.service.ts:findOne:12`.
6
+ * Flame graph в Pyroscope показывает только имена, и без пути одноименные
7
+ * методы разных классов не различить
8
+ */
9
+ export function addLocationToFunctionNames(
10
+ profile: PprofProfile,
11
+ cwd: string,
12
+ ): void {
13
+ const { strings } = profile.stringTable;
14
+ const functions = new Map(profile.function.map((fn) => [Number(fn.id), fn]));
15
+ const renamed = new Set<number>();
16
+
17
+ for (const location of profile.location) {
18
+ for (const line of location.line) {
19
+ const id = Number(line.functionId);
20
+ const fn = functions.get(id);
21
+ const file = fn && strings[Number(fn.filename)];
22
+
23
+ // у (program), (garbage collector) и нативных фреймов файла нет
24
+ if (!fn || !file || renamed.has(id)) {
25
+ continue;
26
+ }
27
+
28
+ const name = `${relativeToCwd(file, cwd)}:${strings[Number(fn.name)]}:${line.line}`;
29
+
30
+ fn.name = profile.stringTable.dedup(name);
31
+ renamed.add(id);
32
+ }
33
+ }
34
+ }
35
+
36
+ function relativeToCwd(file: string, cwd: string): string {
37
+ return file.startsWith(cwd + path.sep) ? `.${file.slice(cwd.length)}` : file;
38
+ }
package/src/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { ProfilerProvider } from '@rsdk/profiling.common';
2
+ import { PprofProfiler } from '@rsdk/profiling.common';
3
+
4
+ import { addLocationToFunctionNames } from './function-names';
5
+ import { readPyroscopeConfig } from './pyroscope.config';
6
+ import { PyroscopeExporter } from './pyroscope.exporter';
7
+
8
+ export const profiler: ProfilerProvider = {
9
+ create({
10
+ env,
11
+ appName,
12
+ appVersion,
13
+ settings,
14
+ logger,
15
+ sourceMapper,
16
+ prepareProfile,
17
+ }) {
18
+ const config = readPyroscopeConfig(env, appName, appVersion);
19
+
20
+ logger.info(
21
+ `Profiles are sent to Pyroscope ${config.serverAddress} as ${config.applicationName}`,
22
+ );
23
+
24
+ return new PprofProfiler(
25
+ settings,
26
+ new PyroscopeExporter(config),
27
+ logger,
28
+ sourceMapper,
29
+ prepareProfile,
30
+ );
31
+ },
32
+
33
+ // по лейблу Pyroscope отдает профиль спана, а по атрибуту Grafana
34
+ // находит его из трейса
35
+ spanLink: { label: 'span_id', attribute: 'pyroscope.profile.id' },
36
+
37
+ prepareProfile: addLocationToFunctionNames,
38
+ };
39
+
40
+ export { PyroscopeConfig, readPyroscopeConfig } from './pyroscope.config';
41
+ export { PyroscopeExporter } from './pyroscope.exporter';
@@ -0,0 +1,59 @@
1
+ import { readPyroscopeConfig } from './pyroscope.config';
2
+
3
+ const SERVER = { PYROSCOPE_SERVER_ADDRESS: 'http://pyroscope:4040/' };
4
+
5
+ describe('readPyroscopeConfig', () => {
6
+ it('берет имя из package.json и добавляет версию в теги', () => {
7
+ expect(readPyroscopeConfig(SERVER, 'examples.tracing', '1.2.3')).toEqual({
8
+ serverAddress: 'http://pyroscope:4040',
9
+ applicationName: 'examples.tracing',
10
+ tags: { service_version: '1.2.3' },
11
+ authToken: undefined,
12
+ basicAuthUser: undefined,
13
+ basicAuthPassword: undefined,
14
+ tenantId: undefined,
15
+ });
16
+ });
17
+
18
+ it('читает имя, теги и авторизацию из env', () => {
19
+ const config = readPyroscopeConfig(
20
+ {
21
+ ...SERVER,
22
+ PYROSCOPE_APPLICATION_NAME: 'billing',
23
+ PYROSCOPE_TAGS: '{"env":"prod","service_version":"override"}',
24
+ PYROSCOPE_BASIC_AUTH_USER: 'user',
25
+ PYROSCOPE_BASIC_AUTH_PASSWORD: 'secret',
26
+ PYROSCOPE_TENANT_ID: 'team-a',
27
+ },
28
+ 'app',
29
+ '1.0.0',
30
+ );
31
+
32
+ expect(config).toMatchObject({
33
+ applicationName: 'billing',
34
+ tags: { env: 'prod', service_version: 'override' },
35
+ basicAuthUser: 'user',
36
+ basicAuthPassword: 'secret',
37
+ tenantId: 'team-a',
38
+ });
39
+ });
40
+
41
+ it('требует PYROSCOPE_SERVER_ADDRESS', () => {
42
+ expect(() => readPyroscopeConfig({}, 'app', '1.0.0')).toThrow(
43
+ 'PYROSCOPE_SERVER_ADDRESS',
44
+ );
45
+ });
46
+
47
+ it.each([
48
+ ['PYROSCOPE_SERVER_ADDRESS', 'not a url'],
49
+ ['PYROSCOPE_TAGS', '["prod"]'],
50
+ ['PYROSCOPE_TAGS', '{"env":1}'],
51
+ ['PYROSCOPE_TAGS', '{"env":"a,b"}'],
52
+ ['PYROSCOPE_TAGS', '{"my-tag":"x"}'],
53
+ ['PYROSCOPE_APPLICATION_NAME', 'app{x}'],
54
+ ])('отклоняет %s=%p', (key, value) => {
55
+ expect(() =>
56
+ readPyroscopeConfig({ ...SERVER, [key]: value }, 'app', '1.0.0'),
57
+ ).toThrow(key);
58
+ });
59
+ });
@@ -0,0 +1,97 @@
1
+ import type { ProfilingEnv } from '@rsdk/profiling.common';
2
+ import { InvalidProfilingSetting } from '@rsdk/profiling.common';
3
+
4
+ // Pyroscope собирает имя профиля как name{key=value,...}
5
+ const INVALID_LABEL_CHARS = /[{},=]/;
6
+ const TAG_NAME = /^[\w.]+$/;
7
+
8
+ export interface PyroscopeConfig {
9
+ serverAddress: string;
10
+ applicationName: string;
11
+ tags: Record<string, string>;
12
+ authToken?: string | undefined;
13
+ basicAuthUser?: string | undefined;
14
+ basicAuthPassword?: string | undefined;
15
+ tenantId?: string | undefined;
16
+ }
17
+
18
+ export function readPyroscopeConfig(
19
+ env: ProfilingEnv,
20
+ appName: string,
21
+ appVersion: string,
22
+ ): PyroscopeConfig {
23
+ const applicationName = env['PYROSCOPE_APPLICATION_NAME'] || appName;
24
+
25
+ assertLabel('PYROSCOPE_APPLICATION_NAME', applicationName);
26
+
27
+ return {
28
+ serverAddress: parseServerAddress(env['PYROSCOPE_SERVER_ADDRESS']),
29
+ applicationName,
30
+ tags: {
31
+ service_version: appVersion,
32
+ ...parseTags(env['PYROSCOPE_TAGS']),
33
+ },
34
+ authToken: env['PYROSCOPE_AUTH_TOKEN'] || undefined,
35
+ basicAuthUser: env['PYROSCOPE_BASIC_AUTH_USER'] || undefined,
36
+ basicAuthPassword: env['PYROSCOPE_BASIC_AUTH_PASSWORD'] || undefined,
37
+ tenantId: env['PYROSCOPE_TENANT_ID'] || undefined,
38
+ };
39
+ }
40
+
41
+ function parseServerAddress(value: string | undefined): string {
42
+ if (!value) {
43
+ throw new Error('PYROSCOPE_SERVER_ADDRESS is not set');
44
+ }
45
+
46
+ if (!URL.canParse(value)) {
47
+ throw new InvalidProfilingSetting('PYROSCOPE_SERVER_ADDRESS', value, 'URL');
48
+ }
49
+
50
+ return value.replace(/\/+$/, '');
51
+ }
52
+
53
+ function parseTags(value: string | undefined): Record<string, string> {
54
+ if (!value) {
55
+ return {};
56
+ }
57
+
58
+ let tags: unknown;
59
+
60
+ try {
61
+ tags = JSON.parse(value);
62
+ } catch {}
63
+
64
+ if (
65
+ !tags ||
66
+ typeof tags !== 'object' ||
67
+ Array.isArray(tags) ||
68
+ Object.values(tags).some((v) => typeof v !== 'string')
69
+ ) {
70
+ throw new InvalidProfilingSetting(
71
+ 'PYROSCOPE_TAGS',
72
+ value,
73
+ 'JSON object with string values',
74
+ );
75
+ }
76
+
77
+ for (const [key, tag] of Object.entries(tags as Record<string, string>)) {
78
+ // Pyroscope отвечает 400 на имя лейбла с дефисом и другими символами
79
+ if (!TAG_NAME.test(key)) {
80
+ throw new InvalidProfilingSetting(
81
+ 'PYROSCOPE_TAGS',
82
+ key,
83
+ 'tag name of letters, digits, _ and .',
84
+ );
85
+ }
86
+
87
+ assertLabel('PYROSCOPE_TAGS', tag);
88
+ }
89
+
90
+ return tags as Record<string, string>;
91
+ }
92
+
93
+ function assertLabel(key: string, value: string): void {
94
+ if (INVALID_LABEL_CHARS.test(value)) {
95
+ throw new InvalidProfilingSetting(key, value, 'no {, }, "," and =');
96
+ }
97
+ }
@@ -0,0 +1,106 @@
1
+ import type { ProfileExport } from '@rsdk/profiling.common';
2
+ import { createServer, type IncomingMessage, type Server } from 'node:http';
3
+ import type { AddressInfo } from 'node:net';
4
+
5
+ import type { PyroscopeConfig } from './pyroscope.config';
6
+ import { PyroscopeExporter } from './pyroscope.exporter';
7
+
8
+ type Received = { req: IncomingMessage; body: Buffer };
9
+
10
+ const profile: ProfileExport = {
11
+ type: 'wall',
12
+ body: Buffer.from('1f8b010203', 'hex'),
13
+ startedAt: new Date('2026-10-27T10:00:00Z'),
14
+ stoppedAt: new Date('2026-10-27T10:01:00Z'),
15
+ sampleRate: 100,
16
+ };
17
+
18
+ describe('PyroscopeExporter', () => {
19
+ let server: Server;
20
+ let received: Received[];
21
+ let status: number;
22
+ let address: string;
23
+
24
+ beforeEach(async () => {
25
+ received = [];
26
+ status = 200;
27
+ server = createServer((req, res) => {
28
+ const chunks: Buffer[] = [];
29
+
30
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
31
+ req.on('end', () => {
32
+ received.push({ req, body: Buffer.concat(chunks) });
33
+ res.writeHead(status);
34
+ res.end(status === 200 ? '' : 'invalid profile');
35
+ });
36
+ });
37
+ await new Promise<void>((resolve) =>
38
+ server.listen(0, '127.0.0.1', resolve),
39
+ );
40
+ address = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
41
+ });
42
+
43
+ afterEach(async () => {
44
+ await new Promise((resolve) => server.close(resolve));
45
+ });
46
+
47
+ const createExporter = (
48
+ config: Partial<PyroscopeConfig> = {},
49
+ ): PyroscopeExporter =>
50
+ new PyroscopeExporter({
51
+ serverAddress: address,
52
+ applicationName: 'billing',
53
+ tags: { service_version: '1.0.0', env: 'prod' },
54
+ ...config,
55
+ });
56
+
57
+ it('отправляет pprof в /ingest с именем, тегами и окном профиля', async () => {
58
+ await createExporter().export(profile);
59
+
60
+ const [{ req, body }] = received;
61
+ const url = new URL(req!.url!, address);
62
+
63
+ expect(req!.method).toBe('POST');
64
+ expect(url.pathname).toBe('/ingest');
65
+ expect(Object.fromEntries(url.searchParams)).toEqual({
66
+ name: 'billing{service_version=1.0.0,env=prod}',
67
+ format: 'pprof',
68
+ spyName: 'nodespy',
69
+ from: String(Date.parse('2026-10-27T10:00:00Z') / 1000),
70
+ until: String(Date.parse('2026-10-27T10:01:00Z') / 1000),
71
+ sampleRate: '100',
72
+ });
73
+ expect(req!.headers['content-type']).toBe('application/octet-stream');
74
+ expect(body).toEqual(profile.body);
75
+ });
76
+
77
+ it('передает токен и tenant', async () => {
78
+ await createExporter({ authToken: 'token', tenantId: 'team-a' }).export(
79
+ profile,
80
+ );
81
+
82
+ expect(received[0]!.req.headers).toMatchObject({
83
+ authorization: 'Bearer token',
84
+ 'x-scope-orgid': 'team-a',
85
+ });
86
+ });
87
+
88
+ it('передает basic auth', async () => {
89
+ await createExporter({
90
+ basicAuthUser: 'user',
91
+ basicAuthPassword: 'secret',
92
+ }).export(profile);
93
+
94
+ expect(received[0]!.req.headers.authorization).toBe(
95
+ `Basic ${Buffer.from('user:secret').toString('base64')}`,
96
+ );
97
+ });
98
+
99
+ it('падает с кодом ответа Pyroscope', async () => {
100
+ status = 400;
101
+
102
+ await expect(createExporter().export(profile)).rejects.toThrow(
103
+ 'Pyroscope responded 400: invalid profile',
104
+ );
105
+ });
106
+ });
@@ -0,0 +1,79 @@
1
+ import type { ProfileExport, ProfileExporter } from '@rsdk/profiling.common';
2
+
3
+ import type { PyroscopeConfig } from './pyroscope.config';
4
+
5
+ const EXPORT_TIMEOUT_MS = 30_000;
6
+
7
+ /**
8
+ * Отправляет профили в Pyroscope через /ingest в формате pprof,
9
+ * как @pyroscope/nodejs
10
+ */
11
+ export class PyroscopeExporter implements ProfileExporter {
12
+ private readonly name: string;
13
+ private readonly headers: Record<string, string>;
14
+
15
+ constructor(private readonly config: PyroscopeConfig) {
16
+ const tags = Object.entries(config.tags)
17
+ .map(([key, value]) => `${key}=${value}`)
18
+ .join(',');
19
+
20
+ this.name = `${config.applicationName}{${tags}}`;
21
+ this.headers = buildHeaders(config);
22
+ }
23
+
24
+ async export(profile: ProfileExport): Promise<void> {
25
+ const url = new URL(`${this.config.serverAddress}/ingest`);
26
+
27
+ url.searchParams.set('name', this.name);
28
+ url.searchParams.set('format', 'pprof');
29
+ url.searchParams.set('spyName', 'nodespy');
30
+ url.searchParams.set('from', unixSeconds(profile.startedAt));
31
+ url.searchParams.set('until', unixSeconds(profile.stoppedAt));
32
+
33
+ if (profile.sampleRate !== undefined) {
34
+ url.searchParams.set('sampleRate', String(profile.sampleRate));
35
+ }
36
+
37
+ const response = await fetch(url, {
38
+ method: 'POST',
39
+ headers: this.headers,
40
+ body: profile.body,
41
+ signal: AbortSignal.timeout(EXPORT_TIMEOUT_MS),
42
+ });
43
+
44
+ if (!response.ok) {
45
+ throw new Error(
46
+ `Pyroscope responded ${response.status}: ${await response.text()}`,
47
+ );
48
+ }
49
+
50
+ // непрочитанное тело держит соединение до сборки мусора
51
+ await response.body?.cancel();
52
+ }
53
+ }
54
+
55
+ function buildHeaders(config: PyroscopeConfig): Record<string, string> {
56
+ const headers: Record<string, string> = {
57
+ 'Content-Type': 'application/octet-stream',
58
+ };
59
+
60
+ if (config.authToken) {
61
+ headers['Authorization'] = `Bearer ${config.authToken}`;
62
+ } else if (config.basicAuthUser && config.basicAuthPassword) {
63
+ const credentials = Buffer.from(
64
+ `${config.basicAuthUser}:${config.basicAuthPassword}`,
65
+ ).toString('base64');
66
+
67
+ headers['Authorization'] = `Basic ${credentials}`;
68
+ }
69
+
70
+ if (config.tenantId) {
71
+ headers['X-Scope-OrgID'] = config.tenantId;
72
+ }
73
+
74
+ return headers;
75
+ }
76
+
77
+ function unixSeconds(date: Date): string {
78
+ return String(Math.floor(date.getTime() / 1000));
79
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "node_modules",
5
+ "dist",
6
+ "test",
7
+ "**/*.spec.ts",
8
+ "**/*.test.ts",
9
+ "**/*.test.e2e.ts",
10
+ "**/*.test.manual-e2e.ts",
11
+ ]
12
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "@rsdk/tsconfig/base.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "dist"
6
+ }
7
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.