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