Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Commit 709fc16

Browse files
committed
async-wrap: add event hooks
Call a user-defined callback at specific points in the lifetime of an asynchronous event. Which are on instantiation, just before/after the callback has been run. **If any of these callbacks throws an exception, there is no forgiveness or recovery. A message will be displayed and a core file dumped.** Currently these only tie into AsyncWrap, meaning no call to a hook callback will be made for timers or process.nextTick() events. Though those will be added in a future commit. Here are a few notes on how to make the hooks work: - The "this" of all event hook callbacks is the request object. - The zero field (kCallInitHook) of the flags object passed to setupHooks() must be set != 0 before the init callback will be called. - kCallInitHook only affects the calling of the init callback. If the request object has been run through the create callback it will always run the before/after callbacks. Regardless of kCallInitHook. - In the init callback the property "_asyncQueue" must be attached to the request object. e.g. function initHook() { this._asyncQueue = {}; } - DO NOT inspect the properties of the object in the init callback. Since the object is in the middle of being instantiated there are some cases when a getter is not complete, and doing so will cause Node to crash. PR-URL: #8110 Signed-off-by: Trevor Norris <trev.norris@gmail.com> Reviewed-by: Fedor Indutny <fedor@indutny.com> Reviewed-by: Alexis Campailla <alexis@janeasystems.com> Reviewed-by: Julien Gilli <julien.gilli@joyent.com>
1 parent 419f18d commit 709fc16

File tree

6 files changed

+167
-2
lines changed

6 files changed

+167
-2
lines changed

src/async-wrap-inl.h

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include "base-object-inl.h"
2828
#include "env.h"
2929
#include "env-inl.h"
30+
#include "node_internals.h"
3031
#include "util.h"
3132
#include "util-inl.h"
3233

@@ -39,7 +40,42 @@ inline AsyncWrap::AsyncWrap(Environment* env,
3940
ProviderType provider,
4041
AsyncWrap* parent)
4142
: BaseObject(env, object),
43+
has_async_queue_(false),
4244
provider_type_(provider) {
45+
// Check user controlled flag to see if the init callback should run.
46+
if (!env->call_async_init_hook())
47+
return;
48+
49+
// TODO(trevnorris): Until it's verified all passed object's are not weak,
50+
// add a HandleScope to make sure there's no leak.
51+
v8::HandleScope scope(env->isolate());
52+
53+
v8::Local<v8::Object> parent_obj;
54+
55+
v8::TryCatch try_catch;
56+
57+
// If a parent value was sent then call its pre/post functions to let it know
58+
// a conceptual "child" is being instantiated (e.g. that a server has
59+
// received a connection).
60+
if (parent != NULL) {
61+
parent_obj = parent->object();
62+
env->async_hooks_pre_function()->Call(parent_obj, 0, NULL);
63+
if (try_catch.HasCaught())
64+
FatalError("node::AsyncWrap::AsyncWrap", "parent pre hook threw");
65+
}
66+
67+
env->async_hooks_init_function()->Call(object, 0, NULL);
68+
69+
if (try_catch.HasCaught())
70+
FatalError("node::AsyncWrap::AsyncWrap", "init hook threw");
71+
72+
has_async_queue_ = true;
73+
74+
if (parent != NULL) {
75+
env->async_hooks_post_function()->Call(parent_obj, 0, NULL);
76+
if (try_catch.HasCaught())
77+
FatalError("node::AsyncWrap::AsyncWrap", "parent post hook threw");
78+
}
4379
}
4480

4581

src/async-wrap.cc

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
using v8::Context;
3232
using v8::Function;
33+
using v8::FunctionCallbackInfo;
3334
using v8::Handle;
3435
using v8::HandleScope;
3536
using v8::Integer;
@@ -38,16 +39,48 @@ using v8::Local;
3839
using v8::Object;
3940
using v8::TryCatch;
4041
using v8::Value;
42+
using v8::kExternalUint32Array;
4143

4244
namespace node {
4345

46+
static void SetupHooks(const FunctionCallbackInfo<Value>& args) {
47+
Environment* env = Environment::GetCurrent(args.GetIsolate());
48+
49+
CHECK(args[0]->IsObject());
50+
CHECK(args[1]->IsFunction());
51+
CHECK(args[2]->IsFunction());
52+
CHECK(args[3]->IsFunction());
53+
54+
// Attach Fields enum from Environment::AsyncHooks.
55+
// Flags attached to this object are:
56+
// - kCallInitHook (0): Tells the AsyncWrap constructor whether it should
57+
// make a call to the init JS callback. This is disabled by default, so
58+
// even after setting the callbacks the flag will have to be set to
59+
// non-zero to have those callbacks called. This only affects the init
60+
// callback. If the init callback was called, then the pre/post callbacks
61+
// will automatically be called.
62+
Local<Object> async_hooks_obj = args[0].As<Object>();
63+
Environment::AsyncHooks* async_hooks = env->async_hooks();
64+
async_hooks_obj->SetIndexedPropertiesToExternalArrayData(
65+
async_hooks->fields(),
66+
kExternalUint32Array,
67+
async_hooks->fields_count());
68+
69+
env->set_async_hooks_init_function(args[1].As<Function>());
70+
env->set_async_hooks_pre_function(args[2].As<Function>());
71+
env->set_async_hooks_post_function(args[3].As<Function>());
72+
}
73+
74+
4475
static void Initialize(Handle<Object> target,
4576
Handle<Value> unused,
4677
Handle<Context> context) {
4778
Environment* env = Environment::GetCurrent(context);
4879
Isolate* isolate = env->isolate();
4980
HandleScope scope(isolate);
5081

82+
NODE_SET_METHOD(target, "setupHooks", SetupHooks);
83+
5184
Local<Object> async_providers = Object::New(isolate);
5285
#define V(PROVIDER) \
5386
async_providers->Set(FIXED_ONE_BYTE_STRING(isolate, #PROVIDER), \
@@ -90,12 +123,28 @@ Handle<Value> AsyncWrap::MakeCallback(const Handle<Function> cb,
90123
}
91124
}
92125

126+
if (has_async_queue_) {
127+
try_catch.SetVerbose(false);
128+
env()->async_hooks_pre_function()->Call(context, 0, NULL);
129+
if (try_catch.HasCaught())
130+
FatalError("node::AsyncWrap::MakeCallback", "pre hook threw");
131+
try_catch.SetVerbose(true);
132+
}
133+
93134
Local<Value> ret = cb->Call(context, argc, argv);
94135

95136
if (try_catch.HasCaught()) {
96137
return Undefined(env()->isolate());
97138
}
98139

140+
if (has_async_queue_) {
141+
try_catch.SetVerbose(false);
142+
env()->async_hooks_post_function()->Call(context, 0, NULL);
143+
if (try_catch.HasCaught())
144+
FatalError("node::AsyncWrap::MakeCallback", "post hook threw");
145+
try_catch.SetVerbose(true);
146+
}
147+
99148
if (has_domain) {
100149
Local<Value> exit_v = domain->Get(env()->exit_string());
101150
if (exit_v->IsFunction()) {

src/async-wrap.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,11 @@ class AsyncWrap : public BaseObject {
8484
private:
8585
inline AsyncWrap();
8686

87-
uint32_t provider_type_;
87+
// When the async hooks init JS function is called from the constructor it is
88+
// expected the context object will receive a _asyncQueue object property
89+
// that will be used to call pre/post in MakeCallback.
90+
bool has_async_queue_;
91+
ProviderType provider_type_;
8892
};
8993

9094
} // namespace node

src/env-inl.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,22 @@ inline v8::Isolate* Environment::IsolateData::isolate() const {
111111
return isolate_;
112112
}
113113

114+
inline Environment::AsyncHooks::AsyncHooks() {
115+
for (int i = 0; i < kFieldsCount; i++) fields_[i] = 0;
116+
}
117+
118+
inline uint32_t* Environment::AsyncHooks::fields() {
119+
return fields_;
120+
}
121+
122+
inline int Environment::AsyncHooks::fields_count() const {
123+
return kFieldsCount;
124+
}
125+
126+
inline bool Environment::AsyncHooks::call_init_hook() {
127+
return fields_[kCallInitHook] != 0;
128+
}
129+
114130
inline Environment::DomainFlag::DomainFlag() {
115131
for (int i = 0; i < kFieldsCount; ++i) fields_[i] = 0;
116132
}
@@ -243,6 +259,11 @@ inline v8::Isolate* Environment::isolate() const {
243259
return isolate_;
244260
}
245261

262+
inline bool Environment::call_async_init_hook() const {
263+
// The const_cast is okay, it doesn't violate conceptual const-ness.
264+
return const_cast<Environment*>(this)->async_hooks()->call_init_hook();
265+
}
266+
246267
inline bool Environment::in_domain() const {
247268
// The const_cast is okay, it doesn't violate conceptual const-ness.
248269
return using_domains() &&
@@ -294,6 +315,10 @@ inline uv_loop_t* Environment::event_loop() const {
294315
return isolate_data()->event_loop();
295316
}
296317

318+
inline Environment::AsyncHooks* Environment::async_hooks() {
319+
return &async_hooks_;
320+
}
321+
297322
inline Environment::DomainFlag* Environment::domain_flag() {
298323
return &domain_flag_;
299324
}

src/env.h

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ namespace node {
6565
V(args_string, "args") \
6666
V(argv_string, "argv") \
6767
V(async, "async") \
68+
V(async_queue_string, "_asyncQueue") \
6869
V(atime_string, "atime") \
6970
V(birthtime_string, "birthtime") \
7071
V(blksize_string, "blksize") \
@@ -249,6 +250,9 @@ namespace node {
249250
V(zero_return_string, "ZERO_RETURN") \
250251

251252
#define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) \
253+
V(async_hooks_init_function, v8::Function) \
254+
V(async_hooks_pre_function, v8::Function) \
255+
V(async_hooks_post_function, v8::Function) \
252256
V(binding_cache_object, v8::Object) \
253257
V(buffer_constructor_function, v8::Function) \
254258
V(context, v8::Context) \
@@ -282,6 +286,27 @@ RB_HEAD(ares_task_list, ares_task_t);
282286

283287
class Environment {
284288
public:
289+
class AsyncHooks {
290+
public:
291+
inline uint32_t* fields();
292+
inline int fields_count() const;
293+
inline bool call_init_hook();
294+
295+
private:
296+
friend class Environment; // So we can call the constructor.
297+
inline AsyncHooks();
298+
299+
enum Fields {
300+
// Set this to not zero if the init hook should be called.
301+
kCallInitHook,
302+
kFieldsCount
303+
};
304+
305+
uint32_t fields_[kFieldsCount];
306+
307+
DISALLOW_COPY_AND_ASSIGN(AsyncHooks);
308+
};
309+
285310
class DomainFlag {
286311
public:
287312
inline uint32_t* fields();
@@ -369,6 +394,7 @@ class Environment {
369394

370395
inline v8::Isolate* isolate() const;
371396
inline uv_loop_t* event_loop() const;
397+
inline bool call_async_init_hook() const;
372398
inline bool in_domain() const;
373399
inline uint32_t watched_providers() const;
374400

@@ -388,6 +414,7 @@ class Environment {
388414
void *arg);
389415
inline void FinishHandleCleanup(uv_handle_t* handle);
390416

417+
inline AsyncHooks* async_hooks();
391418
inline DomainFlag* domain_flag();
392419
inline TickInfo* tick_info();
393420

@@ -464,6 +491,7 @@ class Environment {
464491
uv_idle_t immediate_idle_handle_;
465492
uv_prepare_t idle_prepare_handle_;
466493
uv_check_t idle_check_handle_;
494+
AsyncHooks async_hooks_;
467495
DomainFlag domain_flag_;
468496
TickInfo tick_info_;
469497
uv_timer_t cares_timer_handle_;

src/node.cc

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -988,11 +988,18 @@ Handle<Value> MakeCallback(Environment* env,
988988

989989
Local<Object> process = env->process_object();
990990
Local<Object> object, domain;
991+
bool has_async_queue = false;
991992
bool has_domain = false;
992993

994+
if (recv->IsObject()) {
995+
object = recv.As<Object>();
996+
Local<Value> async_queue_v = object->Get(env->async_queue_string());
997+
if (async_queue_v->IsObject())
998+
has_async_queue = true;
999+
}
1000+
9931001
if (env->using_domains()) {
9941002
CHECK(recv->IsObject());
995-
object = recv.As<Object>();
9961003
Local<Value> domain_v = object->Get(env->domain_string());
9971004
has_domain = domain_v->IsObject();
9981005
if (has_domain) {
@@ -1014,8 +1021,24 @@ Handle<Value> MakeCallback(Environment* env,
10141021
}
10151022
}
10161023

1024+
if (has_async_queue) {
1025+
try_catch.SetVerbose(false);
1026+
env->async_hooks_pre_function()->Call(object, 0, NULL);
1027+
if (try_catch.HasCaught())
1028+
FatalError("node:;MakeCallback", "pre hook threw");
1029+
try_catch.SetVerbose(true);
1030+
}
1031+
10171032
Local<Value> ret = callback->Call(recv, argc, argv);
10181033

1034+
if (has_async_queue) {
1035+
try_catch.SetVerbose(false);
1036+
env->async_hooks_post_function()->Call(object, 0, NULL);
1037+
if (try_catch.HasCaught())
1038+
FatalError("node::MakeCallback", "post hook threw");
1039+
try_catch.SetVerbose(true);
1040+
}
1041+
10191042
if (has_domain) {
10201043
Local<Value> exit_v = domain->Get(env->exit_string());
10211044
if (exit_v->IsFunction()) {

0 commit comments

Comments
 (0)