@datadog/pprof 5.20.0 → 5.21.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.
Files changed (86) hide show
  1. package/out/src/heap-profiler-bindings.d.ts +1 -0
  2. package/out/src/heap-profiler-bindings.js +4 -0
  3. package/out/src/heap-profiler-bindings.js.map +1 -1
  4. package/out/src/heap-profiler.d.ts +13 -3
  5. package/out/src/heap-profiler.js +81 -50
  6. package/out/src/heap-profiler.js.map +1 -1
  7. package/out/src/index.d.ts +7 -1
  8. package/out/src/index.js +7 -1
  9. package/out/src/index.js.map +1 -1
  10. package/out/src/otel-serializer.d.ts +164 -0
  11. package/out/src/otel-serializer.js +431 -0
  12. package/out/src/otel-serializer.js.map +1 -0
  13. package/out/src/profile-normalizer.d.ts +182 -0
  14. package/out/src/profile-normalizer.js +425 -0
  15. package/out/src/profile-normalizer.js.map +1 -0
  16. package/out/src/profile-serializer.d.ts +37 -7
  17. package/out/src/profile-serializer.js +158 -399
  18. package/out/src/profile-serializer.js.map +1 -1
  19. package/out/src/time-profiler.d.ts +13 -2
  20. package/out/src/time-profiler.js +67 -18
  21. package/out/src/time-profiler.js.map +1 -1
  22. package/out/src/v8-types.d.ts +8 -2
  23. package/package.json +7 -7
  24. package/prebuilds/darwin-arm64/dd_pprof.node.abi108.node +0 -0
  25. package/prebuilds/darwin-arm64/dd_pprof.node.abi111.node +0 -0
  26. package/prebuilds/darwin-arm64/dd_pprof.node.abi115.node +0 -0
  27. package/prebuilds/darwin-arm64/dd_pprof.node.abi120.node +0 -0
  28. package/prebuilds/darwin-arm64/dd_pprof.node.abi127.node +0 -0
  29. package/prebuilds/darwin-arm64/dd_pprof.node.abi131.node +0 -0
  30. package/prebuilds/darwin-arm64/dd_pprof.node.abi137.node +0 -0
  31. package/prebuilds/darwin-arm64/dd_pprof.node.abi141.node +0 -0
  32. package/prebuilds/darwin-arm64/dd_pprof.node.abi147.node +0 -0
  33. package/prebuilds/darwin-x64/dd_pprof.node.abi108.node +0 -0
  34. package/prebuilds/darwin-x64/dd_pprof.node.abi111.node +0 -0
  35. package/prebuilds/darwin-x64/dd_pprof.node.abi115.node +0 -0
  36. package/prebuilds/darwin-x64/dd_pprof.node.abi120.node +0 -0
  37. package/prebuilds/darwin-x64/dd_pprof.node.abi127.node +0 -0
  38. package/prebuilds/darwin-x64/dd_pprof.node.abi131.node +0 -0
  39. package/prebuilds/darwin-x64/dd_pprof.node.abi137.node +0 -0
  40. package/prebuilds/darwin-x64/dd_pprof.node.abi141.node +0 -0
  41. package/prebuilds/darwin-x64/dd_pprof.node.abi147.node +0 -0
  42. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi108.node +0 -0
  43. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi111.node +0 -0
  44. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi115.node +0 -0
  45. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi120.node +0 -0
  46. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi127.node +0 -0
  47. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi131.node +0 -0
  48. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi137.node +0 -0
  49. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi141.node +0 -0
  50. package/prebuilds/linux-arm64/dd_pprof.musl.node.abi147.node +0 -0
  51. package/prebuilds/linux-arm64/dd_pprof.node.abi108.node +0 -0
  52. package/prebuilds/linux-arm64/dd_pprof.node.abi111.node +0 -0
  53. package/prebuilds/linux-arm64/dd_pprof.node.abi115.node +0 -0
  54. package/prebuilds/linux-arm64/dd_pprof.node.abi120.node +0 -0
  55. package/prebuilds/linux-arm64/dd_pprof.node.abi127.node +0 -0
  56. package/prebuilds/linux-arm64/dd_pprof.node.abi131.node +0 -0
  57. package/prebuilds/linux-arm64/dd_pprof.node.abi137.node +0 -0
  58. package/prebuilds/linux-arm64/dd_pprof.node.abi141.node +0 -0
  59. package/prebuilds/linux-arm64/dd_pprof.node.abi147.node +0 -0
  60. package/prebuilds/linux-x64/dd_pprof.musl.node.abi108.node +0 -0
  61. package/prebuilds/linux-x64/dd_pprof.musl.node.abi111.node +0 -0
  62. package/prebuilds/linux-x64/dd_pprof.musl.node.abi115.node +0 -0
  63. package/prebuilds/linux-x64/dd_pprof.musl.node.abi120.node +0 -0
  64. package/prebuilds/linux-x64/dd_pprof.musl.node.abi127.node +0 -0
  65. package/prebuilds/linux-x64/dd_pprof.musl.node.abi131.node +0 -0
  66. package/prebuilds/linux-x64/dd_pprof.musl.node.abi137.node +0 -0
  67. package/prebuilds/linux-x64/dd_pprof.musl.node.abi141.node +0 -0
  68. package/prebuilds/linux-x64/dd_pprof.musl.node.abi147.node +0 -0
  69. package/prebuilds/linux-x64/dd_pprof.node.abi108.node +0 -0
  70. package/prebuilds/linux-x64/dd_pprof.node.abi111.node +0 -0
  71. package/prebuilds/linux-x64/dd_pprof.node.abi115.node +0 -0
  72. package/prebuilds/linux-x64/dd_pprof.node.abi120.node +0 -0
  73. package/prebuilds/linux-x64/dd_pprof.node.abi127.node +0 -0
  74. package/prebuilds/linux-x64/dd_pprof.node.abi131.node +0 -0
  75. package/prebuilds/linux-x64/dd_pprof.node.abi137.node +0 -0
  76. package/prebuilds/linux-x64/dd_pprof.node.abi141.node +0 -0
  77. package/prebuilds/linux-x64/dd_pprof.node.abi147.node +0 -0
  78. package/prebuilds/win32-x64/dd_pprof.node.abi108.node +0 -0
  79. package/prebuilds/win32-x64/dd_pprof.node.abi111.node +0 -0
  80. package/prebuilds/win32-x64/dd_pprof.node.abi115.node +0 -0
  81. package/prebuilds/win32-x64/dd_pprof.node.abi120.node +0 -0
  82. package/prebuilds/win32-x64/dd_pprof.node.abi127.node +0 -0
  83. package/prebuilds/win32-x64/dd_pprof.node.abi131.node +0 -0
  84. package/prebuilds/win32-x64/dd_pprof.node.abi137.node +0 -0
  85. package/prebuilds/win32-x64/dd_pprof.node.abi141.node +0 -0
  86. package/prebuilds/win32-x64/dd_pprof.node.abi147.node +0 -0
@@ -15,18 +15,15 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.DEFAULT_COLUMN_NUMBERS = exports.GARBAGE_COLLECTION_FUNCTION_NAME = exports.NON_JS_THREADS_FUNCTION_NAME = void 0;
19
- exports.computeTotalHitCount = computeTotalHitCount;
18
+ exports.PprofProfileBuilder = exports.DEFAULT_COLUMN_NUMBERS = exports.NON_JS_THREADS_FUNCTION_NAME = exports.GARBAGE_COLLECTION_FUNCTION_NAME = exports.computeTotalHitCount = void 0;
20
19
  exports.serializeTimeProfile = serializeTimeProfile;
21
20
  exports.serializeHeapProfile = serializeHeapProfile;
22
21
  const pprof_format_1 = require("pprof-format");
23
- exports.NON_JS_THREADS_FUNCTION_NAME = 'Non JS threads activity';
24
- exports.GARBAGE_COLLECTION_FUNCTION_NAME = 'Garbage Collection';
25
- function isGeneratedLocation(location) {
26
- return (location.column !== undefined &&
27
- location.line !== undefined &&
28
- location.line > 0);
29
- }
22
+ const profile_normalizer_1 = require("./profile-normalizer");
23
+ var profile_normalizer_2 = require("./profile-normalizer");
24
+ Object.defineProperty(exports, "computeTotalHitCount", { enumerable: true, get: function () { return profile_normalizer_2.computeTotalHitCount; } });
25
+ Object.defineProperty(exports, "GARBAGE_COLLECTION_FUNCTION_NAME", { enumerable: true, get: function () { return profile_normalizer_2.GARBAGE_COLLECTION_FUNCTION_NAME; } });
26
+ Object.defineProperty(exports, "NON_JS_THREADS_FUNCTION_NAME", { enumerable: true, get: function () { return profile_normalizer_2.NON_JS_THREADS_FUNCTION_NAME; } });
30
27
  exports.DEFAULT_COLUMN_NUMBERS = 'drop';
31
28
  /**
32
29
  * Packs a frame's line and column into the single value carried by the pprof
@@ -49,114 +46,146 @@ function packLineAndColumn(line, column) {
49
46
  }
50
47
  return (BigInt(column) << 32n) | BigInt(line);
51
48
  }
52
- function requireAllocationStat(value, field) {
53
- if (value === undefined) {
54
- throw new Error(`Allocation profile is missing ${field}.`);
49
+ /**
50
+ * Builds a pprof profile from one normalized profile, delivered to the
51
+ * visitor from visitor(): by the normalizer, or by a profiler emitting
52
+ * samples itself. pprof samples have no timestamps, so sample timestamps are
53
+ * encoded as a label if the options name one, and not at all otherwise.
54
+ *
55
+ * The visit runs synchronously; call build() after it ends.
56
+ */
57
+ class PprofProfileBuilder {
58
+ constructor(options = {}) {
59
+ this.visited = false;
60
+ [this.profileVisitor, this.buildProfile] = createPprofVisitor(options.lowCardinalityLabels ?? [], options.columnNumbers ?? exports.DEFAULT_COLUMN_NUMBERS, options.timestampLabel);
61
+ }
62
+ /** Returns the visitor for the profile. A builder takes a single visit. */
63
+ visitor() {
64
+ if (this.visited) {
65
+ throw new Error('A PprofProfileBuilder builds a single profile.');
66
+ }
67
+ this.visited = true;
68
+ return this.profileVisitor;
69
+ }
70
+ /** Builds the profile from the visit. */
71
+ build() {
72
+ return this.buildProfile();
55
73
  }
56
- return value;
57
74
  }
75
+ exports.PprofProfileBuilder = PprofProfileBuilder;
58
76
  /**
59
- * Takes v8 profile and populates sample, location, and function fields of
60
- * profile.proto.
77
+ * Encodes a normalized profile as a profile proto.
61
78
  *
62
- * @param profile - profile.proto with empty sample, location, and function
63
- * fields.
64
- * @param root - root of v8 profile tree describing samples to be appended
65
- * to profile.
66
- * @param appendToSamples - function which converts entry to sample(s) and
67
- * appends these to end of an array of samples.
68
- * @param stringTable - string table for the existing profile.
79
+ * @param visit - function that delivers the normalized profile to a visitor.
69
80
  */
70
- function serialize(profile, root, appendToSamples, stringTable, ignoreSamplesPath, sourceMapper, columnNumbers = exports.DEFAULT_COLUMN_NUMBERS) {
81
+ function serialize(visit, lowCardinalityLabels = [], columnNumbers = exports.DEFAULT_COLUMN_NUMBERS) {
82
+ const builder = new PprofProfileBuilder({
83
+ lowCardinalityLabels,
84
+ columnNumbers,
85
+ });
86
+ visit(builder.visitor());
87
+ return builder.build();
88
+ }
89
+ /** Returns a visitor that collects a pprof profile, and a function to build it. */
90
+ function createPprofVisitor(lowCardinalityLabels, columnNumbers, timestampLabel) {
91
+ const stringTable = new pprof_format_1.StringTable();
92
+ const timestampKey = timestampLabel === undefined
93
+ ? undefined
94
+ : stringTable.dedup(timestampLabel);
71
95
  const samples = [];
72
96
  const locations = [];
97
+ const stacks = [];
73
98
  const functions = [];
74
99
  const functionIdMap = new Map();
75
- const locationIdMap = new Map();
76
100
  const packColumns = columnNumbers === 'pack';
77
101
  const emitColumns = columnNumbers === 'emit';
78
- let hasMissingMapFiles = false;
79
- const entries = root.children.map((n) => ({
80
- node: n,
81
- stack: [],
82
- }));
83
- while (entries.length > 0) {
84
- const entry = entries.pop();
85
- const node = entry.node;
86
- // mjs files have a `file://` prefix in the scriptName -> remove it
87
- const scriptName = node.scriptName.startsWith('file://')
88
- ? node.scriptName.slice(7)
89
- : node.scriptName;
90
- if (ignoreSamplesPath && scriptName.indexOf(ignoreSamplesPath) > -1) {
91
- continue;
92
- }
93
- const stack = entry.stack;
94
- const location = getLocation(node, scriptName, sourceMapper);
95
- stack.unshift(location.id);
96
- appendToSamples(entry, samples);
97
- for (const child of node.children) {
98
- entries.push({ node: child, stack: stack.slice() });
99
- }
100
- }
101
- profile.sample = samples;
102
- profile.location = locations;
103
- profile.function = functions;
104
- profile.stringTable = stringTable;
105
- if (hasMissingMapFiles) {
106
- profile.comment = [stringTable.dedup('dd:has-missing-map-files')];
102
+ const labelCaches = [];
103
+ for (const l of lowCardinalityLabels) {
104
+ labelCaches[stringTable.dedup(l)] = new Map();
107
105
  }
108
- function getLocation(node, scriptName, sourceMapper) {
109
- let profLoc = {
110
- file: scriptName || '',
111
- line: node.lineNumber,
112
- column: node.columnNumber,
113
- name: node.name,
114
- };
115
- if (profLoc.line) {
116
- if (sourceMapper && isGeneratedLocation(profLoc)) {
117
- profLoc = sourceMapper.mappingInfo(profLoc);
118
- if (profLoc.missingMapFile) {
119
- hasMissingMapFiles = true;
120
- }
121
- }
122
- }
123
- const keyStr = `${node.scriptId}:${profLoc.line}:${profLoc.column}:${profLoc.name}`;
124
- let id = locationIdMap.get(keyStr);
125
- if (id !== undefined) {
106
+ let profile = {};
107
+ let hasMissingMapFiles = false;
108
+ const visitor = {
109
+ metadata: metadata => {
110
+ const valueType = (t) => new pprof_format_1.ValueType({
111
+ type: stringTable.dedup(t.type),
112
+ unit: stringTable.dedup(t.unit),
113
+ });
114
+ profile = {
115
+ sampleType: metadata.sampleTypes.map(valueType),
116
+ // pprof Profile objects have always had a number here; keep it one.
117
+ // It rounds the time to a double, like Date.now() * 1000 * 1000 did.
118
+ timeNanos: Number(metadata.timeNanos),
119
+ durationNanos: metadata.durationNanos,
120
+ periodType: valueType(metadata.periodType),
121
+ period: metadata.period,
122
+ };
123
+ },
124
+ frame: frame => {
126
125
  // id is index+1, since 0 is not valid id.
127
- return locations[id - 1];
126
+ const id = locations.length + 1;
127
+ locations.push(new pprof_format_1.Location({ id, line: [getLine(frame)] }));
128
+ return id;
129
+ },
130
+ stack: frameIds => stacks.push(frameIds) - 1,
131
+ sample: sample => {
132
+ const labels = dedupLabels(buildLabels(sample.labels));
133
+ if (timestampKey !== undefined && sample.timestamp !== undefined) {
134
+ // A timestamp is unique to its sample, so its Label isn't shared
135
+ labels.push(new pprof_format_1.Label({ key: timestampKey, num: sample.timestamp }));
136
+ }
137
+ samples.push(new pprof_format_1.Sample({
138
+ locationId: stacks[sample.stackId],
139
+ value: sample.values,
140
+ label: labels,
141
+ }));
142
+ },
143
+ end: result => {
144
+ hasMissingMapFiles = result.hasMissingMapFiles;
145
+ },
146
+ };
147
+ const build = () => {
148
+ const input = {
149
+ ...profile,
150
+ sample: samples,
151
+ location: locations,
152
+ function: functions,
153
+ stringTable,
154
+ };
155
+ if (hasMissingMapFiles) {
156
+ input.comment = [stringTable.dedup('dd:has-missing-map-files')];
128
157
  }
129
- id = locations.length + 1;
130
- locationIdMap.set(keyStr, id);
131
- const line = getLine(profLoc, node.scriptId);
132
- const location = new pprof_format_1.Location({ id, line: [line] });
133
- locations.push(location);
134
- return location;
135
- }
136
- function getLine(loc, scriptId) {
158
+ return new pprof_format_1.Profile(input);
159
+ };
160
+ return [visitor, build];
161
+ function getLine(frame) {
137
162
  // Both 'pack' and 'emit' carry the column only for frames whose source map
138
163
  // was declared but missing locally — i.e. exactly the frames bound for
139
164
  // server-side unminification (the same condition that sets
140
165
  // dd:has-missing-map-files). Locally-resolved frames keep a plain line and
141
166
  // no column, so column data never reaches profiles that skip server-side
142
167
  // unminification.
143
- const carryColumn = loc.missingMapFile === true;
168
+ const carryColumn = frame.missingMapFile;
144
169
  return new pprof_format_1.Line({
145
- functionId: getFunction(loc, scriptId).id,
170
+ functionId: getFunction(frame).id,
146
171
  // 'pack' encodes the column into the high 32 bits of the line field.
147
172
  line: packColumns && carryColumn
148
- ? packLineAndColumn(loc.line, loc.column)
149
- : loc.line,
173
+ ? packLineAndColumn(frame.line, frame.column)
174
+ : frame.line,
150
175
  // 'emit' records the column in the dedicated pprof Line.column field
151
176
  // instead; the backend does the line/column packing itself.
152
- column: emitColumns && carryColumn ? loc.column : undefined,
177
+ column: emitColumns && carryColumn ? frame.column : undefined,
153
178
  });
154
179
  }
155
- function getFunction(loc, scriptId) {
156
- let name = loc.name;
157
- const keyStr = name
158
- ? `${scriptId}:${name}`
159
- : `${scriptId}:${loc.line}:${loc.column}`;
180
+ function getFunction(frame) {
181
+ // A function is identified by script, file and name, or by script, file
182
+ // and position for anonymous functions; the prefixes keep the two kinds
183
+ // apart. The file matters because after source mapping, one script can
184
+ // map to several original files.
185
+ const file = frame.file;
186
+ const keyStr = frame.name
187
+ ? `n:${frame.scriptId}:${file.length}:${file}:${frame.name}`
188
+ : `a:${frame.scriptId}:${frame.line}:${frame.column}:${file}`;
160
189
  let id = functionIdMap.get(keyStr);
161
190
  if (id !== undefined) {
162
191
  // id is index+1, since 0 is not valid id.
@@ -164,186 +193,32 @@ function serialize(profile, root, appendToSamples, stringTable, ignoreSamplesPat
164
193
  }
165
194
  id = functions.length + 1;
166
195
  functionIdMap.set(keyStr, id);
167
- if (!name) {
168
- if (loc.line) {
169
- if (loc.column) {
170
- name = `(anonymous:L#${loc.line}:C#${loc.column})`;
171
- }
172
- else {
173
- name = `(anonymous:L#${loc.line})`;
174
- }
175
- }
176
- else {
177
- name = '(anonymous)';
178
- }
179
- }
180
- const nameId = stringTable.dedup(name);
196
+ const nameId = stringTable.dedup((0, profile_normalizer_1.frameFunctionName)(frame));
181
197
  const f = new pprof_format_1.Function({
182
198
  id,
183
199
  name: nameId,
184
200
  systemName: nameId,
185
- filename: stringTable.dedup(loc.file || ''),
201
+ filename: stringTable.dedup(frame.file),
186
202
  });
187
203
  functions.push(f);
188
204
  return f;
189
205
  }
190
- }
191
- /**
192
- * @return value type for sample counts (type:sample, units:count), and
193
- * adds strings used in this value type to the table.
194
- */
195
- function createSampleCountValueType(table) {
196
- return new pprof_format_1.ValueType({
197
- type: table.dedup('sample'),
198
- unit: table.dedup('count'),
199
- });
200
- }
201
- /**
202
- * @return value type for time samples (type:wall, units:nanoseconds), and
203
- * adds strings used in this value type to the table.
204
- */
205
- function createTimeValueType(table) {
206
- return new pprof_format_1.ValueType({
207
- type: table.dedup('wall'),
208
- unit: table.dedup('nanoseconds'),
209
- });
210
- }
211
- /**
212
- * @return value type for cpu samples (type:cpu, units:nanoseconds), and
213
- * adds strings used in this value type to the table.
214
- */
215
- function createCpuValueType(table) {
216
- return new pprof_format_1.ValueType({
217
- type: table.dedup('cpu'),
218
- unit: table.dedup('nanoseconds'),
219
- });
220
- }
221
- function createInUseObjectCountValueType(table) {
222
- return new pprof_format_1.ValueType({
223
- type: table.dedup('inuse_objects'),
224
- unit: table.dedup('count'),
225
- });
226
- }
227
- function createAllocatedObjectCountValueType(table) {
228
- return new pprof_format_1.ValueType({
229
- type: table.dedup('alloc_objects'),
230
- unit: table.dedup('count'),
231
- });
232
- }
233
- function createInUseSpaceValueType(table) {
234
- return new pprof_format_1.ValueType({
235
- type: table.dedup('inuse_space'),
236
- unit: table.dedup('bytes'),
237
- });
238
- }
239
- function createAllocatedSpaceValueType(table) {
240
- return new pprof_format_1.ValueType({
241
- type: table.dedup('alloc_space'),
242
- unit: table.dedup('bytes'),
243
- });
244
- }
245
- function computeTotalHitCount(root) {
246
- return (root.hitCount +
247
- root.children.reduce((sum, node) => sum + computeTotalHitCount(node), 0));
248
- }
249
- /** Perform some modifications on time profile:
250
- * - Add non-JS thread activity node if available
251
- * - remove `(program)` nodes
252
- * - remove `(idle)` nodes with no context
253
- * - set `(idle)` nodes' wall time to zero when they have a context
254
- * - Convert `(garbage collector)` node to `Garbage Collection`
255
- * - Put `non-JS thread activity` node and `Garbage Collection` under a top level `Node.js` node
256
- * This function does not change the input profile.
257
- */
258
- function updateTimeProfile(prof) {
259
- const newTopLevelChildren = [];
260
- let runtimeNode;
261
- function getRuntimeNode() {
262
- if (!runtimeNode) {
263
- runtimeNode = {
264
- name: 'Node.js',
265
- scriptName: '',
266
- scriptId: 0,
267
- lineNumber: 0,
268
- columnNumber: 0,
269
- children: [],
270
- hitCount: 0,
271
- };
272
- newTopLevelChildren.push(runtimeNode);
273
- }
274
- return runtimeNode;
275
- }
276
- for (const child of prof.topDownRoot.children) {
277
- if (child.name === '(program)') {
278
- continue;
279
- }
280
- if (child.name === '(idle)' && child.contexts?.length === 0) {
281
- continue;
282
- }
283
- if (child.name === '(garbage collector)') {
284
- // Create a new node to avoid modifying the input one
285
- const newChild = {
286
- ...child,
287
- name: exports.GARBAGE_COLLECTION_FUNCTION_NAME,
288
- };
289
- getRuntimeNode().children.push(newChild);
290
- }
291
- else {
292
- newTopLevelChildren.push(child);
293
- }
294
- }
295
- if (prof.hasCpuTime && prof.nonJSThreadsCpuTime) {
296
- const node = {
297
- name: exports.NON_JS_THREADS_FUNCTION_NAME,
298
- scriptName: '',
299
- scriptId: 0,
300
- lineNumber: 0,
301
- columnNumber: 0,
302
- children: [],
303
- hitCount: 0, // 0 because this should not be accounted for wall time
304
- contexts: [
305
- {
306
- context: {},
307
- timestamp: BigInt(0),
308
- cpuTime: prof.nonJSThreadsCpuTime,
309
- asyncId: -1,
310
- },
311
- ],
312
- };
313
- getRuntimeNode().children.push(node);
314
- }
315
- return {
316
- ...prof,
317
- topDownRoot: { ...prof.topDownRoot, children: newTopLevelChildren },
318
- };
319
- }
320
- /**
321
- * Converts v8 time profile into into a profile proto.
322
- * (https://github.com/google/pprof/blob/master/proto/profile.proto)
323
- *
324
- * @param prof - profile to be converted.
325
- * @param intervalMicros - average time (microseconds) between samples.
326
- */
327
- function serializeTimeProfile(prof, intervalMicros, sourceMapper, recomputeSamplingInterval = false, generateLabels, lowCardinalityLabels = [], columnNumbers = exports.DEFAULT_COLUMN_NUMBERS) {
328
- // If requested, recompute sampling interval from profile duration and total number of hits,
329
- // since profile duration should be #hits x interval.
330
- // Recomputing an average interval is more accurate, since in practice intervals between
331
- // samples are larger than the requested sampling interval (eg. 12.5ms vs 10ms requested).
332
- // For very short durations, computation becomes meaningless (eg. if there is only one hit),
333
- // therefore keep intervalMicros as a lower bound and 2 * intervalMicros as upper bound.
334
- if (recomputeSamplingInterval) {
335
- const totalHitCount = prof.totalHitCount ?? computeTotalHitCount(prof.topDownRoot);
336
- if (totalHitCount > 0) {
337
- intervalMicros = Math.min(Math.max(Math.floor((prof.endTime - prof.startTime) / totalHitCount), intervalMicros), 2 * intervalMicros);
206
+ function buildLabels(sampleLabels) {
207
+ const labels = new Array(sampleLabels.length);
208
+ for (let i = 0; i < sampleLabels.length; i++) {
209
+ const [key, value] = sampleLabels[i];
210
+ const labelInput = { key: stringTable.dedup(key) };
211
+ if (typeof value === 'string') {
212
+ labelInput.str = stringTable.dedup(value);
213
+ }
214
+ else {
215
+ labelInput.num = value;
216
+ }
217
+ labels[i] = new pprof_format_1.Label(labelInput);
338
218
  }
219
+ return labels;
339
220
  }
340
- const intervalNanos = intervalMicros * 1000;
341
- const stringTable = new pprof_format_1.StringTable();
342
- const labelCaches = [];
343
- for (const l of lowCardinalityLabels) {
344
- labelCaches[stringTable.dedup(l)] = new Map();
345
- }
346
- const dedupLabels = (labels) => {
221
+ function dedupLabels(labels) {
347
222
  for (let i = 0; i < labels.length; i++) {
348
223
  const label = labels[i];
349
224
  const cache = labelCaches[Number(label.key)];
@@ -361,90 +236,23 @@ function serializeTimeProfile(prof, intervalMicros, sourceMapper, recomputeSampl
361
236
  }
362
237
  }
363
238
  return labels;
364
- };
365
- const appendTimeEntryToSamples = (entry, samples) => {
366
- let unlabelledHits = entry.node.hitCount;
367
- let unlabelledCpuTime = 0;
368
- const isIdle = entry.node.name === '(idle)';
369
- for (const context of entry.node.contexts || []) {
370
- const labels = generateLabels
371
- ? generateLabels({ node: entry.node, context })
372
- : (context.context ?? {});
373
- const labelsArr = buildLabels(labels, stringTable);
374
- if (labelsArr.length > 0) {
375
- // Only assign wall time if there are hits, some special nodes such as `(Non-JS threads)`
376
- // have zero hit count (since they do not count as wall time) and should not be assigned any
377
- // wall time. Also, `(idle)` nodes should be assigned zero wall time.
378
- const values = unlabelledHits > 0 ? [1, isIdle ? 0 : intervalNanos] : [0, 0];
379
- if (prof.hasCpuTime) {
380
- values.push(context.cpuTime ?? 0);
381
- }
382
- const sample = new pprof_format_1.Sample({
383
- locationId: entry.stack,
384
- value: values,
385
- label: dedupLabels(labelsArr),
386
- });
387
- samples.push(sample);
388
- unlabelledHits--;
389
- }
390
- else if (prof.hasCpuTime) {
391
- unlabelledCpuTime += context.cpuTime ?? 0;
392
- }
393
- }
394
- if ((!isIdle && unlabelledHits > 0) || unlabelledCpuTime > 0) {
395
- const labels = generateLabels ? generateLabels({ node: entry.node }) : {};
396
- const values = unlabelledHits > 0
397
- ? [unlabelledHits, isIdle ? 0 : unlabelledHits * intervalNanos]
398
- : [0, 0];
399
- if (prof.hasCpuTime) {
400
- values.push(unlabelledCpuTime);
401
- }
402
- const sample = new pprof_format_1.Sample({
403
- locationId: entry.stack,
404
- value: values,
405
- label: buildLabels(labels, stringTable),
406
- });
407
- samples.push(sample);
408
- }
409
- };
410
- const sampleValueType = createSampleCountValueType(stringTable);
411
- const timeValueType = createTimeValueType(stringTable);
412
- const sampleTypes = [sampleValueType, timeValueType];
413
- if (prof.hasCpuTime) {
414
- const cpuValueType = createCpuValueType(stringTable);
415
- sampleTypes.push(cpuValueType);
416
239
  }
417
- const profile = {
418
- sampleType: sampleTypes,
419
- timeNanos: Date.now() * 1000 * 1000,
420
- durationNanos: (prof.endTime - prof.startTime) * 1000,
421
- periodType: timeValueType,
422
- period: intervalNanos,
423
- };
424
- const updatedProf = updateTimeProfile(prof);
425
- serialize(profile, updatedProf.topDownRoot, appendTimeEntryToSamples, stringTable, undefined, sourceMapper, columnNumbers);
426
- return new pprof_format_1.Profile(profile);
427
240
  }
428
- function buildLabels(labelSet, stringTable) {
429
- const labels = [];
430
- for (const [key, value] of Object.entries(labelSet)) {
431
- const labelInput = {
432
- key: stringTable.dedup(key),
433
- };
434
- switch (typeof value) {
435
- case 'string':
436
- labelInput.str = stringTable.dedup(value);
437
- break;
438
- case 'number':
439
- case 'bigint':
440
- labelInput.num = value;
441
- break;
442
- default:
443
- continue;
444
- }
445
- labels.push(new pprof_format_1.Label(labelInput));
446
- }
447
- return labels;
241
+ /**
242
+ * Converts v8 time profile into into a profile proto.
243
+ * (https://github.com/google/pprof/blob/master/proto/profile.proto)
244
+ *
245
+ * @param prof - profile to be converted.
246
+ * @param intervalMicros - average time (microseconds) between samples.
247
+ */
248
+ function serializeTimeProfile(prof, intervalMicros, sourceMapper, recomputeSamplingInterval = false, generateLabels, lowCardinalityLabels = [], columnNumbers = exports.DEFAULT_COLUMN_NUMBERS) {
249
+ const options = {
250
+ intervalMicros,
251
+ sourceMapper,
252
+ recomputeSamplingInterval,
253
+ generateLabels,
254
+ };
255
+ return serialize(visitor => (0, profile_normalizer_1.visitTimeProfile)(prof, visitor, options), lowCardinalityLabels, columnNumbers);
448
256
  }
449
257
  /**
450
258
  * Converts v8 heap profile into into a profile proto.
@@ -452,66 +260,17 @@ function buildLabels(labelSet, stringTable) {
452
260
  *
453
261
  * @param prof - profile to be converted.
454
262
  * @param startTimeNanos - start time of profile, in nanoseconds (POSIX time).
455
- * @param durationsNanos - duration of the profile (wall clock time) in
456
- * nanoseconds.
457
263
  * @param intervalBytes - bytes allocated between samples.
458
264
  */
459
265
  function serializeHeapProfile(prof, startTimeNanos, intervalBytes, ignoreSamplesPath, sourceMapper, generateLabels, allocations = false, columnNumbers = exports.DEFAULT_COLUMN_NUMBERS) {
460
- const appendHeapEntryToSamples = (entry, samples) => {
461
- if (entry.node.allocations.length > 0) {
462
- const labels = generateLabels
463
- ? buildLabels(generateLabels({ node: entry.node }), stringTable)
464
- : [];
465
- for (const alloc of entry.node.allocations) {
466
- // Live heap only
467
- if (!allocations) {
468
- const heapAllocation = alloc;
469
- const sample = new pprof_format_1.Sample({
470
- locationId: entry.stack,
471
- value: [
472
- heapAllocation.count,
473
- heapAllocation.sizeBytes * heapAllocation.count,
474
- ],
475
- label: labels,
476
- // TODO: add tag for allocation size
477
- });
478
- samples.push(sample);
479
- continue;
480
- }
481
- const stats = alloc;
482
- const inuseObjects = requireAllocationStat(stats.inuseObjects, 'inuseObjects');
483
- const inuseSpaceBytes = requireAllocationStat(stats.inuseSpaceBytes, 'inuseSpaceBytes');
484
- const allocObjects = requireAllocationStat(stats.allocObjects, 'allocObjects');
485
- const allocSpaceBytes = requireAllocationStat(stats.allocSpaceBytes, 'allocSpaceBytes');
486
- const sample = new pprof_format_1.Sample({
487
- locationId: entry.stack,
488
- value: [inuseObjects, allocObjects, inuseSpaceBytes, allocSpaceBytes],
489
- label: labels,
490
- // TODO: add tag for allocation size
491
- });
492
- samples.push(sample);
493
- }
494
- }
495
- };
496
- const stringTable = new pprof_format_1.StringTable();
497
- const sampleTypes = allocations
498
- ? [
499
- createInUseObjectCountValueType(stringTable),
500
- createAllocatedObjectCountValueType(stringTable),
501
- createInUseSpaceValueType(stringTable),
502
- createAllocatedSpaceValueType(stringTable),
503
- ]
504
- : [
505
- createInUseObjectCountValueType(stringTable),
506
- createInUseSpaceValueType(stringTable),
507
- ];
508
- const profile = {
509
- sampleType: sampleTypes,
510
- timeNanos: startTimeNanos,
511
- periodType: sampleTypes[sampleTypes.length - 1],
512
- period: intervalBytes,
266
+ const options = {
267
+ startTimeNanos: BigInt(startTimeNanos),
268
+ intervalBytes,
269
+ ignoreSamplesPath,
270
+ sourceMapper,
271
+ generateLabels,
272
+ allocations,
513
273
  };
514
- serialize(profile, prof, appendHeapEntryToSamples, stringTable, ignoreSamplesPath, sourceMapper, columnNumbers);
515
- return new pprof_format_1.Profile(profile);
274
+ return serialize(visitor => (0, profile_normalizer_1.visitHeapProfile)(prof, visitor, options), [], columnNumbers);
516
275
  }
517
276
  //# sourceMappingURL=profile-serializer.js.map