0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-28 14:33:11 +01:00
nodejs/lib/trace_events.js
Jungku Lee 9fe0424baa
trace_events: use private fields instead of symbols for Tracing
PR-URL: https://github.com/nodejs/node/pull/51180
Refs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz.nizipli@sentry.io>
2023-12-28 23:20:22 +00:00

97 lines
2.1 KiB
JavaScript

'use strict';
const {
ArrayPrototypeJoin,
SafeSet,
} = primordials;
const { hasTracing } = internalBinding('config');
const kMaxTracingCount = 10;
const {
ERR_TRACE_EVENTS_CATEGORY_REQUIRED,
ERR_TRACE_EVENTS_UNAVAILABLE,
} = require('internal/errors').codes;
const { ownsProcessState } = require('internal/worker');
if (!hasTracing || !ownsProcessState)
throw new ERR_TRACE_EVENTS_UNAVAILABLE();
const { CategorySet, getEnabledCategories } = internalBinding('trace_events');
const { customInspectSymbol } = require('internal/util');
const { format } = require('internal/util/inspect');
const {
validateObject,
validateStringArray,
} = require('internal/validators');
const enabledTracingObjects = new SafeSet();
class Tracing {
#handle;
#categories;
#enabled = false;
constructor(categories) {
this.#handle = new CategorySet(categories);
this.#categories = categories;
}
enable() {
if (!this.#enabled) {
this.#enabled = true;
this.#handle.enable();
enabledTracingObjects.add(this);
if (enabledTracingObjects.size > kMaxTracingCount) {
process.emitWarning(
'Possible trace_events memory leak detected. There are more than ' +
`${kMaxTracingCount} enabled Tracing objects.`,
);
}
}
}
disable() {
if (this.#enabled) {
this.#enabled = false;
this.#handle.disable();
enabledTracingObjects.delete(this);
}
}
get enabled() {
return this.#enabled;
}
get categories() {
return ArrayPrototypeJoin(this.#categories, ',');
}
[customInspectSymbol](depth, opts) {
if (typeof depth === 'number' && depth < 0)
return this;
const obj = {
enabled: this.enabled,
categories: this.categories,
};
return `Tracing ${format(obj)}`;
}
}
function createTracing(options) {
validateObject(options, 'options');
validateStringArray(options.categories, 'options.categories');
if (options.categories.length <= 0)
throw new ERR_TRACE_EVENTS_CATEGORY_REQUIRED();
return new Tracing(options.categories);
}
module.exports = {
createTracing,
getEnabledCategories,
};