From 85a02ec9798097838132d9c0189238f6f2711ebd Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 10 Nov 2021 12:32:09 -0800 Subject: [PATCH] async_hooks: eliminate require side effects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40782 Reviewed-By: Gerhard Stöbich Reviewed-By: Andrey Pechkurov Reviewed-By: Minwoo Jung --- lib/internal/async_hooks.js | 6 ++++-- src/async_wrap.cc | 9 ++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index c25ce5a9ae13f8..8608d6d1a7bed9 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -137,8 +137,6 @@ function callbackTrampoline(asyncId, resource, cb, ...args) { return result; } -setCallbackTrampoline(callbackTrampoline); - const topLevelResource = {}; function executionAsyncResource() { @@ -372,6 +370,8 @@ function promiseResolveHook(promise) { let wantPromiseHook = false; function enableHooks() { async_hook_fields[kCheck] += 1; + + setCallbackTrampoline(callbackTrampoline); } let stopPromiseHook; @@ -398,6 +398,8 @@ function disableHooks() { wantPromiseHook = false; + setCallbackTrampoline(); + // Delay the call to `disablePromiseHook()` because we might currently be // between the `before` and `after` calls of a Promise. enqueueMicrotask(disablePromiseHookIfNecessary); diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 59b842b232517b..8ed8ce11d88b22 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -327,9 +327,11 @@ void AsyncWrap::QueueDestroyAsyncId(const FunctionCallbackInfo& args) { void AsyncWrap::SetCallbackTrampoline(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - CHECK(args[0]->IsFunction()); - - env->set_async_hooks_callback_trampoline(args[0].As()); + if (args[0]->IsFunction()) { + env->set_async_hooks_callback_trampoline(args[0].As()); + } else { + env->set_async_hooks_callback_trampoline(Local()); + } } Local AsyncWrap::GetConstructorTemplate(Environment* env) { @@ -439,6 +441,7 @@ void AsyncWrap::Initialize(Local target, env->set_async_hooks_after_function(Local()); env->set_async_hooks_destroy_function(Local()); env->set_async_hooks_promise_resolve_function(Local()); + env->set_async_hooks_callback_trampoline(Local()); env->set_async_hooks_binding(target); }