Skip to content

Commit 3e2e8ae

Browse files
committed
v8: add setHeapSnapshotNearHeapLimit
1 parent ab89024 commit 3e2e8ae

11 files changed

+295
-9
lines changed

doc/api/v8.md

+13
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,18 @@ if (isMainThread) {
356356
}
357357
```
358358

359+
## `v8.setHeapSnapshotNearHeapLimit(limit)`
360+
361+
<!-- YAML
362+
added: REPLACEME
363+
-->
364+
365+
> Stability: 1 - Experimental
366+
367+
Each call to this API make the count reset to 0, and Node.js will write no more
368+
than `limit` snapshots to disk, `limit` must be greater than or equal to 1.
369+
See [`--heapsnapshot-near-heap-limit`][] for more information.
370+
359371
## Serialization API
360372

361373
The serialization API provides means of serializing JavaScript values in a way
@@ -1020,6 +1032,7 @@ Returns true if the Node.js instance is run to build a snapshot.
10201032
[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
10211033
[Hook Callbacks]: #hook-callbacks
10221034
[V8]: https://developers.google.com/v8/
1035+
[`--heapsnapshot-near-heap-limit`]: cli.md#--heapsnapshot-near-heap-limitmax_count
10231036
[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
10241037
[`Buffer`]: buffer.md
10251038
[`DefaultDeserializer`]: #class-v8defaultdeserializer

lib/v8.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const {
3333
} = primordials;
3434

3535
const { Buffer } = require('buffer');
36-
const { validateString } = require('internal/validators');
36+
const { validateString, validateNumber } = require('internal/validators');
3737
const {
3838
Serializer,
3939
Deserializer
@@ -59,7 +59,6 @@ const {
5959
} = internalBinding('heap_utils');
6060
const { HeapSnapshotStream } = require('internal/heap_utils');
6161
const promiseHooks = require('internal/promise_hooks');
62-
6362
/**
6463
* Generates a snapshot of the current V8 heap
6564
* and writes it to a JSON file.
@@ -95,6 +94,7 @@ const {
9594
updateHeapStatisticsBuffer,
9695
updateHeapSpaceStatisticsBuffer,
9796
updateHeapCodeStatisticsBuffer,
97+
setHeapSnapshotNearHeapLimit: _setHeapSnapshotNearHeapLimit,
9898

9999
// Properties for heap statistics buffer extraction.
100100
kTotalHeapSizeIndex,
@@ -226,6 +226,11 @@ function getHeapCodeStatistics() {
226226
};
227227
}
228228

229+
function setHeapSnapshotNearHeapLimit(limit) {
230+
validateNumber(limit, 'limit', 1);
231+
_setHeapSnapshotNearHeapLimit(limit);
232+
}
233+
229234
/* V8 serialization API */
230235

231236
/* JS methods for the base objects */
@@ -387,5 +392,6 @@ module.exports = {
387392
serialize,
388393
writeHeapSnapshot,
389394
promiseHooks,
390-
startupSnapshot
395+
startupSnapshot,
396+
setHeapSnapshotNearHeapLimit,
391397
};

src/env.cc

+9-4
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,8 @@ Environment::Environment(IsolateData* isolate_data,
720720
inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
721721
options_->debug_options().host_port);
722722

723+
set_heap_snapshot_near_heap_limit(options_->heap_snapshot_near_heap_limit);
724+
723725
if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
724726
set_abort_on_uncaught_exception(false);
725727
}
@@ -834,7 +836,8 @@ Environment::~Environment() {
834836
// FreeEnvironment() should have set this.
835837
CHECK(is_stopping());
836838

837-
if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
839+
if (near_heap_callback_is_added()) {
840+
set_near_heap_callback_is_added(false);
838841
isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
839842
0);
840843
}
@@ -1952,6 +1955,7 @@ size_t Environment::NearHeapLimitCallback(void* data,
19521955
Debug(env,
19531956
DebugCategory::DIAGNOSTICS,
19541957
"Not generating snapshots because it's too risky.\n");
1958+
env->set_near_heap_callback_is_added(false);
19551959
env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
19561960
initial_heap_limit);
19571961
// The new limit must be higher than current_heap_limit or V8 might
@@ -1973,16 +1977,17 @@ size_t Environment::NearHeapLimitCallback(void* data,
19731977

19741978
// Remove the callback first in case it's triggered when generating
19751979
// the snapshot.
1980+
env->set_near_heap_callback_is_added(false);
19761981
env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
19771982
initial_heap_limit);
19781983

19791984
heap::WriteSnapshot(env, filename.c_str());
1980-
env->heap_limit_snapshot_taken_ += 1;
1985+
env->set_heap_limit_snapshot_taken(env->heap_limit_snapshot_taken() + 1);
19811986

19821987
// Don't take more snapshots than the number specified by
19831988
// --heapsnapshot-near-heap-limit.
1984-
if (env->heap_limit_snapshot_taken_ <
1985-
env->options_->heap_snapshot_near_heap_limit) {
1989+
if (env->heap_limit_snapshot_taken() < env->heap_snapshot_near_heap_limit()) {
1990+
env->set_near_heap_callback_is_added(true);
19861991
env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
19871992
}
19881993

src/env.h

+26
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,30 @@ class Environment : public MemoryRetainer {
14891489
template <typename T>
14901490
void ForEachBaseObject(T&& iterator);
14911491

1492+
inline int64_t heap_limit_snapshot_taken() {
1493+
return heap_limit_snapshot_taken_;
1494+
}
1495+
1496+
inline int64_t set_heap_limit_snapshot_taken(int64_t count) {
1497+
return heap_limit_snapshot_taken_ = count;
1498+
}
1499+
1500+
inline int64_t heap_snapshot_near_heap_limit() {
1501+
return heap_snapshot_near_heap_limit_;
1502+
}
1503+
1504+
inline void set_heap_snapshot_near_heap_limit(int64_t limit) {
1505+
heap_snapshot_near_heap_limit_ = limit;
1506+
}
1507+
1508+
inline bool near_heap_callback_is_added() {
1509+
return near_heap_callback_is_added_;
1510+
}
1511+
1512+
inline void set_near_heap_callback_is_added(bool added) {
1513+
near_heap_callback_is_added_ = added;
1514+
}
1515+
14921516
private:
14931517
inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
14941518
const char* errmsg);
@@ -1547,6 +1571,8 @@ class Environment : public MemoryRetainer {
15471571

15481572
bool is_processing_heap_limit_callback_ = false;
15491573
int64_t heap_limit_snapshot_taken_ = 0;
1574+
int64_t heap_snapshot_near_heap_limit_ = 0;
1575+
bool near_heap_callback_is_added_ = false;
15501576

15511577
uint32_t module_id_counter_ = 0;
15521578
uint32_t script_id_counter_ = 0;

src/node.cc

+2-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,8 @@ static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
273273
void Environment::InitializeDiagnostics() {
274274
isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
275275
Environment::BuildEmbedderGraph, this);
276-
if (options_->heap_snapshot_near_heap_limit > 0) {
276+
if (heap_snapshot_near_heap_limit() > 0) {
277+
set_near_heap_callback_is_added(true);
277278
isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
278279
this);
279280
}

src/node_v8.cc

+20
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,21 @@ void CachedDataVersionTag(const FunctionCallbackInfo<Value>& args) {
157157
args.GetReturnValue().Set(result);
158158
}
159159

160+
void SetHeapSnapshotNearHeapLimit(const FunctionCallbackInfo<Value>& args) {
161+
CHECK(args[0]->IsNumber());
162+
Environment* env = Environment::GetCurrent(args);
163+
Isolate* const isolate = args.GetIsolate();
164+
int64_t limit = args[0].As<v8::Number>()->Value();
165+
CHECK_GT(limit, 0);
166+
// Do not set twice which will make the process crash.
167+
if (!env->near_heap_callback_is_added()) {
168+
env->set_near_heap_callback_is_added(true);
169+
isolate->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback, env);
170+
}
171+
env->set_heap_snapshot_near_heap_limit(limit);
172+
env->set_heap_limit_snapshot_taken(0);
173+
}
174+
160175
void UpdateHeapStatisticsBuffer(const FunctionCallbackInfo<Value>& args) {
161176
BindingData* data = Environment::GetBindingData<BindingData>(args);
162177
HeapStatistics s;
@@ -212,6 +227,10 @@ void Initialize(Local<Object> target,
212227

213228
SetMethodNoSideEffect(
214229
context, target, "cachedDataVersionTag", CachedDataVersionTag);
230+
SetMethodNoSideEffect(context,
231+
target,
232+
"setHeapSnapshotNearHeapLimit",
233+
SetHeapSnapshotNearHeapLimit);
215234
SetMethod(context,
216235
target,
217236
"updateHeapStatisticsBuffer",
@@ -267,6 +286,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
267286
registry->Register(UpdateHeapCodeStatisticsBuffer);
268287
registry->Register(UpdateHeapSpaceStatisticsBuffer);
269288
registry->Register(SetFlagsFromString);
289+
registry->Register(SetHeapSnapshotNearHeapLimit);
270290
}
271291

272292
} // namespace v8_utils
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
const path = require('path');
3+
const v8 = require('v8');
4+
5+
v8.setHeapSnapshotNearHeapLimit(+process.env.limit);
6+
if (process.env.limit2) {
7+
v8.setHeapSnapshotNearHeapLimit(+process.env.limit2);
8+
}
9+
require(path.resolve(__dirname, 'grow.js'));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
'use strict';
2+
const path = require('path');
3+
const { Worker } = require('worker_threads');
4+
const max_snapshots = parseInt(process.env.TEST_SNAPSHOTS) || 1;
5+
new Worker(path.join(__dirname, 'grow-and-set-near-heap-limit.js'), {
6+
env: {
7+
...process.env,
8+
limit: max_snapshots,
9+
},
10+
resourceLimits: {
11+
maxOldGenerationSizeMb:
12+
parseInt(process.env.TEST_OLD_SPACE_SIZE) || 20
13+
}
14+
});
15+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copy from test-heapsnapshot-near-heap-limit-worker.js
2+
'use strict';
3+
4+
require('../common');
5+
const tmpdir = require('../common/tmpdir');
6+
const assert = require('assert');
7+
const { spawnSync } = require('child_process');
8+
const fixtures = require('../common/fixtures');
9+
const fs = require('fs');
10+
11+
const env = {
12+
...process.env,
13+
NODE_DEBUG_NATIVE: 'diagnostics'
14+
};
15+
16+
{
17+
tmpdir.refresh();
18+
const child = spawnSync(process.execPath, [
19+
fixtures.path('workload', 'grow-worker-and-set-near-heap-limit.js'),
20+
], {
21+
cwd: tmpdir.path,
22+
env: {
23+
TEST_SNAPSHOTS: 1,
24+
TEST_OLD_SPACE_SIZE: 50,
25+
...env
26+
}
27+
});
28+
console.log(child.stdout.toString());
29+
const stderr = child.stderr.toString();
30+
console.log(stderr);
31+
const risky = /Not generating snapshots because it's too risky/.test(stderr);
32+
if (!risky) {
33+
// There should be one snapshot taken and then after the
34+
// snapshot heap limit callback is popped, the OOM callback
35+
// becomes effective.
36+
assert(stderr.includes('ERR_WORKER_OUT_OF_MEMORY'));
37+
const list = fs.readdirSync(tmpdir.path)
38+
.filter((file) => file.endsWith('.heapsnapshot'));
39+
assert.strictEqual(list.length, 1);
40+
}
41+
}

0 commit comments

Comments
 (0)