Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,13 @@ file in chunks.
The number of file system events queued without being handled exceeded the size specified in
`maxQueue` in `fs.watch()`.

<a id="ERR_HEAP_PROFILE_NOT_STARTED"></a>

### `ERR_HEAP_PROFILE_NOT_STARTED`

An operation was attempted on a heap profile that has not been started or has
already been stopped or disposed.

<a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a>

### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN`
Expand Down
95 changes: 94 additions & 1 deletion doc/api/v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -1618,6 +1618,62 @@ added: v26.1.0

> Stability: 1 - Experimental

### `syncHeapProfileHandle.getSamples()`

<!-- YAML
added: REPLACEME
-->

* Returns: {Object\[]}
* `size` {number} Estimated total allocation size in bytes, equal to
`objectSize * objectCount`.
* `objectSize` {number} Size of the sampled object in bytes.
* `objectCount` {number} Estimated number of objects represented by the sample.
* `nodeId` {number} Identifier of the allocation's node in the profile call tree.
* `ordinal` {number} Unique, time-ordered identifier of the sample.
* `isLive` {boolean} Whether the sampled object is still live.
* `sampleInterval` {number} Sampling interval in bytes used when the sample
was selected.

Returns the currently retained allocation samples without stopping profiling or
building the full profile call tree and resolving its script metadata. The sample
fields match those in the JSON returned by `stop()`. Use `ordinal` to identify
samples across calls; array order is unspecified.

Live allocation samples are available with the default profiling options.
To also retain samples after their objects are collected, enable
`includeObjectsCollectedByMajorGC` or `includeObjectsCollectedByMinorGC` when
starting the profile. These samples have `isLive` set to `false`. The `forceGC`
option also applies to `getSamples()`.

Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.

### `syncHeapProfileHandle.setSampleInterval(sampleInterval)`

<!-- YAML
added: REPLACEME
-->

* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
`1` and `Number.MAX_SAFE_INTEGER`, inclusive.

Updates the sampling interval for future sample scheduling without restarting
profiling or discarding existing samples. A larger interval reduces sampling
frequency. Each sample retains the `sampleInterval` used when it was selected.

Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.

```cjs
const v8 = require('node:v8');

const handle = v8.startHeapProfile({ sampleInterval: 1024 });
// Run the workload to profile.
const samples = handle.getSamples();
handle.setSampleInterval(4096);
// Continue profiling with less frequent sampling.
const profile = handle.stop();
```

### `syncHeapProfileHandle.stop()`

<!-- YAML
Expand All @@ -1634,7 +1690,9 @@ fields, the following are added:

* Each node reports `selfCount`, the number of sampled objects allocated by the
node (`selfSize` is the existing total in bytes).
* Each sample reports `objectSize`, `objectCount`, and `isLive`.
* Each sample reports `objectSize`, `objectCount`, `isLive`, and `sampleInterval`.
`sampleInterval` records the sampling interval in bytes used when the sample
was selected, even if the interval was subsequently changed.

The DevTools `size` field stays `objectSize * objectCount` for compatibility.

Expand Down Expand Up @@ -1679,6 +1737,40 @@ Stopping collecting the profile and the profile will be discarded.
added: v24.9.0
-->

### `heapProfileHandle.getSamples()`

<!-- YAML
added: REPLACEME
-->

* Returns: {Promise} Fulfills with an {Object\[]} of allocation samples.

Asynchronously retrieves the worker's retained allocation samples without
stopping profiling or building the full profile call tree. The sample fields and
profiling options are described in
[`syncHeapProfileHandle.getSamples()`][].

Rejects with `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or
disposed, or `ERR_WORKER_NOT_RUNNING` if the worker is no longer running.

### `heapProfileHandle.setSampleInterval(sampleInterval)`

<!-- YAML
added: REPLACEME
-->

* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
`1` and `Number.MAX_SAFE_INTEGER`, inclusive.
* Returns: {Promise} Fulfills with `undefined` after the interval is updated.

Asynchronously updates the worker's sampling interval for future sample
scheduling without restarting profiling or discarding existing samples. Each
sample retains the `sampleInterval` used when it was selected.

Invalid arguments throw synchronously. The returned promise rejects with
`ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed, or
`ERR_WORKER_NOT_RUNNING` if the worker is no longer running.

### `heapProfileHandle.stop()`

<!-- YAML
Expand Down Expand Up @@ -1930,6 +2022,7 @@ must be a positive integer.
[`serializer.transferArrayBuffer()`]: #serializertransferarraybufferid-arraybuffer
[`serializer.writeRawBytes()`]: #serializerwriterawbytesbuffer
[`settled` callback]: #settledpromise
[`syncHeapProfileHandle.getSamples()`]: #syncheapprofilehandlegetsamples
[`v8.setHeapSnapshotNearHeapLimit()`]: #v8setheapsnapshotnearheaplimitlimit
[`v8.startHeapProfile()`]: #v8startheapprofileoptions
[`v8.stopCoverage()`]: #v8stopcoverage
Expand Down
1 change: 1 addition & 0 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -1257,6 +1257,7 @@ E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type', SystemError);
E('ERR_FS_EISDIR', 'Path is a directory', SystemError, HideStackFramesError);
E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GiB', RangeError);
E('ERR_FS_WATCH_QUEUE_OVERFLOW', 'fs.watch() queued more than %d events', Error);
E('ERR_HEAP_PROFILE_NOT_STARTED', 'Heap profile not started', Error);
E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
'HTTP/2 ALTSVC frames require a valid origin', TypeError);
E('ERR_HTTP2_ALTSVC_LENGTH',
Expand Down
32 changes: 32 additions & 0 deletions lib/internal/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const {
NumberMAX_SAFE_INTEGER,
ObjectEntries,
Promise,
PromiseReject,
PromiseResolve,
PromiseWithResolvers,
ReflectApply,
Expand All @@ -33,6 +34,7 @@ const path = require('path');
const errorCodes = require('internal/errors').codes;
const {
ERR_WORKER_NOT_RUNNING,
ERR_HEAP_PROFILE_NOT_STARTED,
ERR_WORKER_PATH,
ERR_WORKER_UNSERIALIZABLE_ERROR,
ERR_WORKER_INVALID_EXEC_ARGV,
Expand Down Expand Up @@ -65,6 +67,7 @@ const {
validateString,
validateObject,
validateNumber,
validateInteger,
} = require('internal/validators');
const {
throwIfBuildingSnapshot,
Expand Down Expand Up @@ -175,6 +178,35 @@ class HeapProfileHandle {
this.#worker = worker;
}

setSampleInterval(sampleInterval) {
validateInteger(sampleInterval, 'sampleInterval', 1);
if (this.#promise) {
return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
}
const taker = this.#worker[kHandle]?.setHeapProfileSampleInterval(sampleInterval);
return new Promise((resolve, reject) => {
if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
taker.ondone = (err) => {
if (err) return reject(err);
resolve();
};
});
}

getSamples() {
if (this.#promise) {
return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
}
const taker = this.#worker[kHandle]?.getHeapProfileSamples();
return new Promise((resolve, reject) => {
if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
taker.ondone = (err, samples) => {
if (err) return reject(err);
resolve(samples);
};
});
}

stop() {
if (this.#promise) {
return this.#promise;
Expand Down
19 changes: 19 additions & 0 deletions lib/v8.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const {
validateString,
validateOneOf,
validateUint32,
validateInteger,
} = require('internal/validators');
const {
Serializer,
Expand Down Expand Up @@ -70,6 +71,7 @@ if (hasInspector) {
const assert = require('internal/assert');
const {
codes: {
ERR_HEAP_PROFILE_NOT_STARTED,
ERR_INVALID_STATE,
},
} = require('internal/errors');
Expand Down Expand Up @@ -133,6 +135,8 @@ const {
stopCpuProfile: _stopCpuProfile,
startHeapProfile: _startHeapProfile,
stopHeapProfile: _stopHeapProfile,
setHeapProfileSampleInterval: _setHeapProfileSampleInterval,
getHeapProfileSamples: _getHeapProfileSamples,
isStringOneByteRepresentation: _isStringOneByteRepresentation,
updateHeapStatisticsBuffer,
updateHeapSpaceStatisticsBuffer,
Expand Down Expand Up @@ -213,6 +217,21 @@ class SyncCPUProfileHandle {
class SyncHeapProfileHandle {
#stopped = false;

setSampleInterval(sampleInterval) {
validateInteger(sampleInterval, 'sampleInterval', 1);
if (this.#stopped) {
throw new ERR_HEAP_PROFILE_NOT_STARTED();
}
_setHeapProfileSampleInterval(sampleInterval);
}

getSamples() {
if (this.#stopped) {
throw new ERR_HEAP_PROFILE_NOT_STARTED();
}
return _getHeapProfileSamples();
}

stop() {
if (this.#stopped) {
return;
Expand Down
40 changes: 39 additions & 1 deletion src/node_profiling.cc
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#include "node_profiling.h"

#include "json_utils.h"
#include "util.h"
#include "util-inl.h"

#include <memory>
#include <string_view>

namespace node {

Expand Down Expand Up @@ -64,6 +65,7 @@ bool SerializeHeapProfile(Isolate* isolate, std::ostringstream& out_stream) {
writer.json_keyvalue("nodeId", sample.node_id);
writer.json_keyvalue("ordinal", static_cast<double>(sample.sample_id));
writer.json_keyvalue("isLive", sample.is_live);
writer.json_keyvalue("sampleInterval", sample.sample_interval);
writer.json_end();
}
writer.json_arrayend();
Expand All @@ -76,6 +78,42 @@ bool SerializeHeapProfile(Isolate* isolate, std::ostringstream& out_stream) {
return true;
}

v8::MaybeLocal<v8::Array> HeapProfileSamplesToV8Value(
Isolate* isolate,
v8::Local<v8::Context> context,
const std::vector<AllocationProfile::Sample>& samples) {
static constexpr std::string_view names[] = {
"size",
"objectSize",
"objectCount",
"nodeId",
"ordinal",
"isLive",
"sampleInterval",
};
auto tmpl = v8::DictionaryTemplate::New(isolate, names);
v8::LocalVector<Value> result(isolate);
result.reserve(samples.size());
for (const auto& sample : samples) {
v8::MaybeLocal<Value> values[] = {
v8::Number::New(isolate, sample.size * sample.count),
v8::Number::New(isolate, sample.size),
v8::Integer::NewFromUnsigned(isolate, sample.count),
v8::Integer::NewFromUnsigned(isolate, sample.node_id),
v8::Number::New(isolate, static_cast<double>(sample.sample_id)),
v8::Boolean::New(isolate, sample.is_live),
v8::Number::New(isolate, static_cast<double>(sample.sample_interval)),
};
v8::Local<v8::Object> object;
if (!NewDictionaryInstanceNullProto(context, tmpl, values)
.ToLocal(&object)) {
return {};
}
result.emplace_back(object);
}
return v8::Array::New(isolate, result.data(), result.size());
}

HeapProfileOptions ParseHeapProfileOptions(
const v8::FunctionCallbackInfo<Value>& args) {
HeapProfileOptions options;
Expand Down
6 changes: 6 additions & 0 deletions src/node_profiling.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include <cstdint>
#include <sstream>
#include <vector>

namespace node {

Expand All @@ -23,6 +24,11 @@ HeapProfileOptions ParseHeapProfileOptions(

bool SerializeHeapProfile(v8::Isolate* isolate, std::ostringstream& out_stream);

v8::MaybeLocal<v8::Array> HeapProfileSamplesToV8Value(
v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::vector<v8::AllocationProfile::Sample>& samples);

struct CpuProfileOptions {
int sampling_interval_us = 0;
uint32_t max_samples = v8::CpuProfilingOptions::kNoSampleLimit;
Expand Down
27 changes: 27 additions & 0 deletions src/node_v8.cc
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,26 @@ void StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
}
}

void SetHeapProfileSampleInterval(const FunctionCallbackInfo<Value>& args) {
CHECK_EQ(args.Length(), 1);
CHECK(args[0]->IsNumber());
uint64_t sample_interval =
static_cast<uint64_t>(args[0].As<Number>()->Value());
args.GetIsolate()->GetHeapProfiler()->SetSamplingHeapProfilerInterval(
sample_interval);
}

void GetHeapProfileSamples(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
auto samples =
env->isolate()->GetHeapProfiler()->GetSamplingHeapProfilerSamples();
Local<Array> result;
if (HeapProfileSamplesToV8Value(env->isolate(), env->context(), samples)
.ToLocal(&result)) {
args.GetReturnValue().Set(result);
}
}

static void IsStringOneByteRepresentation(
const FunctionCallbackInfo<Value>& args) {
CHECK_EQ(args.Length(), 1);
Expand Down Expand Up @@ -804,6 +824,11 @@ void Initialize(Local<Object> target,
SetMethod(context, target, "stopCpuProfile", StopCpuProfile);
SetMethod(context, target, "startHeapProfile", StartHeapProfile);
SetMethod(context, target, "stopHeapProfile", StopHeapProfile);
SetMethod(context,
target,
"setHeapProfileSampleInterval",
SetHeapProfileSampleInterval);
SetMethod(context, target, "getHeapProfileSamples", GetHeapProfileSamples);

{
constexpr uint32_t kSamplingNoFlags = static_cast<uint32_t>(
Expand Down Expand Up @@ -872,6 +897,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(StopCpuProfile);
registry->Register(StartHeapProfile);
registry->Register(StopHeapProfile);
registry->Register(SetHeapProfileSampleInterval);
registry->Register(GetHeapProfileSamples);
}

} // namespace v8_utils
Expand Down
Loading
Loading