perf_hooks: add CBOR export/import for histogram exchange · nodejs/node@72d1b40 · GitHub
Skip to content

Commit 72d1b40

Browse files
jasnelladuh95
authored andcommitted
perf_hooks: add CBOR export/import for histogram exchange
Provide a binary export/import mechanism for histograms. Since there is no standard interchange format for histograms, using CBOR is meant to make the format as platform/runtime agnostic as possible while producing a compact/efficient result. No new dependency is introduced, we just encode the CBOR directly. Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus PR-URL: #65434 Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 3e4fc50 commit 72d1b40

6 files changed

Lines changed: 769 additions & 20 deletions

File tree

‎doc/api/perf_hooks.md‎

Lines changed: 68 additions & 0 deletions

‎lib/internal/histogram.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ const {
3838
validateObject,
3939
} = require('internal/validators');
4040

41+
const {
42+
isUint8Array,
43+
} = require('internal/util/types');
44+
4145
const kDestroy = Symbol('kDestroy');
4246
const kHandle = Symbol('kHandle');
4347
const kRecordable = Symbol('kRecordable');
@@ -213,6 +217,18 @@ class Histogram {
213217
return this[kHandle]?.exceedsBigInt();
214218
}
215219

220+
/**
221+
* Serializes the histogram to a CBOR-encoded Uint8Array suitable for
222+
* transmission or storage. The data can be reconstructed into a new
223+
* histogram using `importHistogram()`.
224+
* @returns {Uint8Array}
225+
*/
226+
export() {
227+
if (!isHistogram(this))
228+
throw new ERR_INVALID_THIS('Histogram');
229+
return this[kHandle]?.export();
230+
}
231+
216232
/**
217233
* Returns the exponentially weighted moving average of recorded values.
218234
* Only active when the histogram was created with a `halfLife` option.
@@ -755,6 +771,18 @@ function createHistogram(options = kEmptyObject) {
755771
new _Histogram(lowest, highest, figures, halfLife, threshold));
756772
}
757773

774+
/**
775+
* Reconstructs a histogram from a CBOR-encoded Uint8Array previously
776+
* produced by `histogram.export()`.
777+
* @param {Uint8Array} data
778+
* @returns {RecordableHistogram}
779+
*/
780+
function importHistogram(data) {
781+
if (!isUint8Array(data))
782+
throw new ERR_INVALID_ARG_TYPE('data', 'Uint8Array', data);
783+
return createRecordableHistogram(_Histogram.import(data));
784+
}
785+
758786
module.exports = {
759787
Histogram,
760788
RecordableHistogram,
@@ -765,4 +793,5 @@ module.exports = {
765793
kHandle,
766794
kSkipThrow,
767795
createHistogram,
796+
importHistogram,
768797
};

‎lib/perf_hooks.js‎

Lines changed: 2 additions & 0 deletions

0 commit comments

Comments
 (0)