Skip to content

Commit 1ef4444

Browse files
authored
src: skip the async id stack when nobody sees it
With no async hook and no executionAsyncResource() user, every InternalCallbackScope pushed and popped the async ids on the stack, only for executionAsyncId() and triggerAsyncId() to read the top. Swap the two ids in place instead: they are all that those two and process.nextTick() read. executionAsyncResource() is the only reader of the stack: the scopes that skip it form a chain in AsyncHooks, counted in a new field, kLazyScopes, and JS asks C++ for the innermost one only while that count is not zero. The checks for a corrupted stack stay. Refs: nodejs/performance#24 Signed-off-by: Nigro Simone <nigro.simone@gmail.com> PR-URL: #66511 Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 45d1554 commit 1ef4444

8 files changed

Lines changed: 171 additions & 5 deletions

File tree

‎lib/internal/async_hooks.js‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ const {
5252
pushAsyncContext: pushAsyncContext_,
5353
popAsyncContext: popAsyncContext_,
5454
executionAsyncResource: executionAsyncResource_,
55+
lazyExecutionAsyncResource,
5556
clearAsyncIdStack,
5657
} = async_wrap;
5758
// Properties in active_hooks are used to keep track of the set of hooks being
@@ -91,6 +92,7 @@ const {
9192
kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
9293
kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId,
9394
kDefaultTriggerAsyncId, kStackLength, kUsesExecutionAsyncResource,
95+
kLazyScopes,
9496
} = async_wrap.constants;
9597

9698
const { async_id_symbol,
@@ -136,6 +138,12 @@ function executionAsyncResource() {
136138
async_hook_fields[kUsesExecutionAsyncResource] = 1;
137139

138140
const index = async_hook_fields[kStackLength] - 1;
141+
// A native callback that started before anybody used this function did not
142+
// push its resource on the stack.
143+
if (async_hook_fields[kLazyScopes] !== 0) {
144+
const lazy = lazyExecutionAsyncResource(index + 1);
145+
if (lazy !== undefined) return lookupPublicResource(lazy);
146+
}
139147
if (index === -1) return topLevelResource;
140148
const resource = execution_async_resources[index] ||
141149
executionAsyncResource_(index);
@@ -550,7 +558,15 @@ function pushAsyncContext(asyncId, triggerAsyncId, resource) {
550558
// This is the equivalent of the native pop_async_ids() call.
551559
function popAsyncContext(asyncId) {
552560
const stackLength = async_hook_fields[kStackLength];
553-
if (stackLength === 0) return false;
561+
if (stackLength === 0) {
562+
// A native callback that skipped the stack still has its id checked.
563+
if (async_hook_fields[kLazyScopes] !== 0 &&
564+
async_hook_fields[kCheck] > 0 &&
565+
async_id_fields[kExecutionAsyncId] !== asyncId) {
566+
return popAsyncContext_(asyncId);
567+
}
568+
return false;
569+
}
554570

555571
if (async_hook_fields[kCheck] > 0 && async_id_fields[kExecutionAsyncId] !== asyncId) {
556572
// Do the same thing as the native code (i.e. crash hard).

‎src/api/callback.cc‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,27 @@ InternalCallbackScope::InternalCallbackScope(
120120
prior_context_frame_.Reset(isolate, prior_context_frame);
121121
}
122122

123-
env->async_hooks()->push_async_context(
124-
async_context_.async_id, async_context_.trigger_async_id, object);
123+
AsyncHooks* hooks = env->async_hooks();
124+
if (hooks->fields()[AsyncHooks::kTotals] == 0 &&
125+
hooks->fields()[AsyncHooks::kUsesExecutionAsyncResource] == 0)
126+
[[likely]] {
127+
// Nobody can see the id stack: swap the ids in place, they are all that
128+
// executionAsyncId() and triggerAsyncId() read.
129+
AliasedFloat64Array& ids = hooks->async_id_fields();
130+
prior_async_id_ = ids[AsyncHooks::kExecutionAsyncId];
131+
prior_trigger_async_id_ = ids[AsyncHooks::kTriggerAsyncId];
132+
ids[AsyncHooks::kExecutionAsyncId] = async_context_.async_id;
133+
ids[AsyncHooks::kTriggerAsyncId] = async_context_.trigger_async_id;
134+
lazy_depth_ = hooks->fields()[AsyncHooks::kStackLength];
135+
lazy_resource_ = object;
136+
lazy_prev_ = hooks->lazy_top_;
137+
hooks->lazy_top_ = this;
138+
hooks->fields()[AsyncHooks::kLazyScopes] += 1;
139+
lazy_ids_ = true;
140+
} else {
141+
hooks->push_async_context(
142+
async_context_.async_id, async_context_.trigger_async_id, object);
143+
}
125144

126145
pushed_ids_ = true;
127146

@@ -132,6 +151,13 @@ InternalCallbackScope::InternalCallbackScope(
132151
}
133152
}
134153

154+
Local<Object> InternalCallbackScope::lazy_resource(Isolate* isolate) const {
155+
if (std::holds_alternative<Local<Object>*>(lazy_resource_)) {
156+
return *std::get<Local<Object>*>(lazy_resource_);
157+
}
158+
return std::get<Global<Object>*>(lazy_resource_)->Get(isolate);
159+
}
160+
135161
InternalCallbackScope::~InternalCallbackScope() {
136162
Close();
137163
env_->PopAsyncCallbackScope();
@@ -162,7 +188,20 @@ void InternalCallbackScope::Close() {
162188
}
163189

164190
if (pushed_ids_) {
165-
env_->async_hooks()->pop_async_context(async_context_.async_id);
191+
AsyncHooks* hooks = env_->async_hooks();
192+
if (lazy_ids_) {
193+
// clear_async_id_stack() may have dropped the chain already.
194+
if (hooks->lazy_top_ == this) {
195+
hooks->CheckLazyClose(async_context_.async_id, lazy_depth_);
196+
hooks->lazy_top_ = lazy_prev_;
197+
hooks->fields()[AsyncHooks::kLazyScopes] -= 1;
198+
}
199+
AliasedFloat64Array& ids = hooks->async_id_fields();
200+
ids[AsyncHooks::kExecutionAsyncId] = prior_async_id_;
201+
ids[AsyncHooks::kTriggerAsyncId] = prior_trigger_async_id_;
202+
} else {
203+
hooks->pop_async_context(async_context_.async_id);
204+
}
166205

167206
async_context_frame::set(env_, prior_context_frame_.Get(isolate));
168207
}

‎src/async_wrap.cc‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "env-inl.h"
2626
#include "node_errors.h"
2727
#include "node_external_reference.h"
28+
#include "node_internals.h"
2829
#include "tracing/traced_value.h"
2930
#include "util-inl.h"
3031

@@ -290,6 +291,17 @@ void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) {
290291
args.GetReturnValue().Set(env->async_hooks()->pop_async_context(async_id));
291292
}
292293

294+
// The resource of the innermost scope that skipped the id stack, if nothing
295+
// was pushed on the stack after it (depth is the stack length JS sees).
296+
static void LazyExecutionAsyncResource(
297+
const v8::FunctionCallbackInfo<v8::Value>& args) {
298+
Environment* env = Environment::GetCurrent(args);
299+
uint32_t depth = args[0].As<v8::Uint32>()->Value();
300+
InternalCallbackScope* scope = env->async_hooks()->lazy_top_;
301+
if (scope != nullptr && scope->lazy_depth() == depth) {
302+
args.GetReturnValue().Set(scope->lazy_resource(env->isolate()));
303+
}
304+
}
293305

294306
void AsyncWrap::ExecutionAsyncResource(
295307
const FunctionCallbackInfo<Value>& args) {
@@ -396,6 +408,10 @@ void AsyncWrap::CreatePerIsolateProperties(IsolateData* isolate_data,
396408
SetMethod(isolate, target, "pushAsyncContext", PushAsyncContext);
397409
SetMethod(isolate, target, "popAsyncContext", PopAsyncContext);
398410
SetMethod(isolate, target, "executionAsyncResource", ExecutionAsyncResource);
411+
SetMethod(isolate,
412+
target,
413+
"lazyExecutionAsyncResource",
414+
LazyExecutionAsyncResource);
399415
SetMethod(isolate, target, "clearAsyncIdStack", ClearAsyncIdStack);
400416
SetMethod(isolate, target, "queueDestroyAsyncId", QueueDestroyAsyncId);
401417
SetMethod(isolate, target, "setPromiseHooks", SetPromiseHooks);
@@ -470,6 +486,7 @@ void AsyncWrap::CreatePerContextProperties(Local<Object> target,
470486
SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
471487
SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
472488
SET_HOOKS_CONSTANT(kStackLength);
489+
SET_HOOKS_CONSTANT(kLazyScopes);
473490
#undef SET_HOOKS_CONSTANT
474491
FORCE_SET_TARGET_FIELD(target, "constants", constants);
475492

@@ -502,6 +519,7 @@ void AsyncWrap::RegisterExternalReferences(
502519
registry->Register(PushAsyncContext);
503520
registry->Register(PopAsyncContext);
504521
registry->Register(ExecutionAsyncResource);
522+
registry->Register(LazyExecutionAsyncResource);
505523
registry->Register(ClearAsyncIdStack);
506524
registry->Register(QueueDestroyAsyncId);
507525
registry->Register(SetPromiseHooks);

‎src/env.cc‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,12 +172,25 @@ void AsyncHooks::push_async_context(
172172
}
173173
}
174174

175+
void AsyncHooks::CheckLazyClose(double async_id, uint32_t depth) {
176+
if (fields_[kCheck] > 0 && (async_id_fields_[kExecutionAsyncId] != async_id ||
177+
fields_[kStackLength] != depth)) [[unlikely]] {
178+
FailWithCorruptedAsyncStack(async_id);
179+
}
180+
}
181+
175182
// Remember to keep this code aligned with popAsyncContext() in JS.
176183
bool AsyncHooks::pop_async_context(double async_id) {
177184
// In case of an exception then this may have already been reset, if the
178185
// stack was multiple MakeCallback()'s deep.
179-
if (fields_[kStackLength] == 0) [[unlikely]]
186+
if (fields_[kStackLength] == 0) [[unlikely]] {
187+
// A scope that skipped the stack still has its id checked.
188+
if (fields_[kLazyScopes] > 0 && fields_[kCheck] > 0 &&
189+
async_id_fields_[kExecutionAsyncId] != async_id) {
190+
FailWithCorruptedAsyncStack(async_id);
191+
}
180192
return false;
193+
}
181194

182195
// Ask for the async_id to be restored as a check that the stack
183196
// hasn't been corrupted.
@@ -235,6 +248,8 @@ void AsyncHooks::clear_async_id_stack() {
235248
async_id_fields_[kExecutionAsyncId] = 0;
236249
async_id_fields_[kTriggerAsyncId] = 0;
237250
fields_[kStackLength] = 0;
251+
lazy_top_ = nullptr;
252+
fields_[kLazyScopes] = 0;
238253
}
239254

240255
void AsyncHooks::InstallPromiseHooks(Local<Context> ctx) {

‎src/env.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,8 @@ extern std::shared_ptr<KVStore> system_environment;
413413

414414
struct EnvSerializeInfo;
415415

416+
class InternalCallbackScope;
417+
416418
class AsyncHooks : public MemoryRetainer {
417419
public:
418420
SET_MEMORY_INFO_NAME(AsyncHooks)
@@ -431,6 +433,7 @@ class AsyncHooks : public MemoryRetainer {
431433
kCheck,
432434
kStackLength,
433435
kUsesExecutionAsyncResource,
436+
kLazyScopes,
434437
kFieldsCount,
435438
};
436439

@@ -547,6 +550,13 @@ class AsyncHooks : public MemoryRetainer {
547550
const SerializeInfo* info_ = nullptr;
548551

549552
std::array<v8::Global<v8::Function>, 4> js_promise_hooks_;
553+
554+
public:
555+
// Innermost InternalCallbackScope that swapped the ids without the stack,
556+
// for executionAsyncResource(). Counted in fields_[kLazyScopes].
557+
InternalCallbackScope* lazy_top_ = nullptr;
558+
// Close of a scope that skipped the stack: the same check as pop.
559+
void CheckLazyClose(double async_id, uint32_t depth);
550560
};
551561

552562
class ImmediateInfo : public MemoryRetainer {

‎src/node_internals.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,10 @@ class InternalCallbackScope {
281281
inline bool Failed() const { return failed_; }
282282
inline void MarkAsFailed() { failed_ = true; }
283283

284+
// For executionAsyncResource() inside a scope that skipped the id stack.
285+
inline uint32_t lazy_depth() const { return lazy_depth_; }
286+
v8::Local<v8::Object> lazy_resource(v8::Isolate* isolate) const;
287+
284288
private:
285289
Environment* env_;
286290
async_context async_context_;
@@ -290,6 +294,12 @@ class InternalCallbackScope {
290294
bool failed_ = false;
291295
bool pushed_ids_ = false;
292296
bool closed_ = false;
297+
bool lazy_ids_ = false;
298+
uint32_t lazy_depth_ = 0;
299+
double prior_async_id_ = 0;
300+
double prior_trigger_async_id_ = 0;
301+
InternalCallbackScope* lazy_prev_ = nullptr;
302+
std::variant<v8::Local<v8::Object>*, v8::Global<v8::Object>*> lazy_resource_;
293303
v8::Global<v8::Value> prior_context_frame_;
294304
std::optional<v8::Isolate::AllowJavascriptExecutionScope> allow_js_;
295305
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict';
2+
3+
const common = require('../../common');
4+
const assert = require('assert');
5+
const binding = require(`./build/${common.buildType}/binding`);
6+
const { executionAsyncId, executionAsyncResource } = require('async_hooks');
7+
8+
// No hook is enabled and executionAsyncResource() was never called, so the
9+
// callback scope of AsyncResource::MakeCallback() skips the async id stack.
10+
// executionAsyncResource() must still find the resource, and executionAsyncId()
11+
// must still be the id of the callback, also around a nested callback.
12+
let calls = 0;
13+
const object = {
14+
methöd: common.mustCall(function() {
15+
assert.strictEqual(executionAsyncId(), uid);
16+
assert.strictEqual(executionAsyncResource(), object);
17+
if (calls++ === 0) {
18+
assert.strictEqual(binding.callViaFunction(resource), 'baz');
19+
assert.strictEqual(executionAsyncId(), uid);
20+
assert.strictEqual(executionAsyncResource(), object);
21+
}
22+
return 'baz';
23+
}, 2),
24+
};
25+
const resource = binding.createAsyncResource(object);
26+
const uid = binding.getAsyncId(resource);
27+
const outerId = executionAsyncId();
28+
29+
assert.strictEqual(binding.callViaFunction(resource), 'baz');
30+
assert.strictEqual(executionAsyncId(), outerId);
31+
binding.destroyAsyncResource(resource);
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const fs = require('fs');
6+
const { AsyncResource, executionAsyncResource } = require('async_hooks');
7+
const { internalBinding } = require('internal/test/binding');
8+
const { FSReqCallback } = internalBinding('fs');
9+
const { async_hook_fields, constants: { kLazyScopes } } = internalBinding('async_wrap');
10+
11+
// No hook and no executionAsyncResource() yet, so the scope of this callback skips the id stack.
12+
// Asked for here, its resource comes off the chain of lazy scopes, and for an AsyncWrap the
13+
// resource is held as a Global.
14+
fs.stat(__filename, common.mustSucceed(() => {
15+
assert.ok(async_hook_fields[kLazyScopes] > 0);
16+
const resource = executionAsyncResource();
17+
assert.ok(resource instanceof FSReqCallback);
18+
assert.strictEqual(executionAsyncResource(), resource);
19+
20+
// A context pushed on the stack while the lazy scope is still open: the stack answers, not the
21+
// chain.
22+
const inner = new AsyncResource('TEST');
23+
inner.runInAsyncScope(common.mustCall(() => {
24+
assert.strictEqual(executionAsyncResource(), inner);
25+
}));
26+
assert.strictEqual(executionAsyncResource(), resource);
27+
}));

0 commit comments

Comments
 (0)