1// Copyright 2018 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_D8_ASYNC_HOOKS_WRAPPER_H_
6#define V8_D8_ASYNC_HOOKS_WRAPPER_H_
7
8#include <stack>
9
10#include "include/v8-function-callback.h"
11#include "include/v8-local-handle.h"
12#include "include/v8-promise.h"
13#include "src/objects/objects.h"
14
15namespace v8 {
16
17class Function;
18class Isolate;
19class ObjectTemplate;
20class Value;
21
22using async_id_t = double;
23
24struct AsyncContext {
25  async_id_t execution_async_id;
26  async_id_t trigger_async_id;
27};
28
29class AsyncHooksWrap {
30 public:
31  explicit AsyncHooksWrap(Isolate* isolate)
32      : isolate_(isolate), enabled_(false) {}
33  void Enable();
34  void Disable();
35  bool IsEnabled() const { return enabled_; }
36
37  inline v8::Local<v8::Function> init_function() const;
38  inline void set_init_function(v8::Local<v8::Function> value);
39  inline v8::Local<v8::Function> before_function() const;
40  inline void set_before_function(v8::Local<v8::Function> value);
41  inline v8::Local<v8::Function> after_function() const;
42  inline void set_after_function(v8::Local<v8::Function> value);
43  inline v8::Local<v8::Function> promiseResolve_function() const;
44  inline void set_promiseResolve_function(v8::Local<v8::Function> value);
45
46 private:
47  Isolate* isolate_;
48
49  Persistent<v8::Function> init_function_;
50  Persistent<v8::Function> before_function_;
51  Persistent<v8::Function> after_function_;
52  Persistent<v8::Function> promiseResolve_function_;
53
54  bool enabled_;
55};
56
57class AsyncHooks {
58 public:
59  explicit AsyncHooks(Isolate* isolate);
60  ~AsyncHooks();
61
62  async_id_t GetExecutionAsyncId() const;
63  async_id_t GetTriggerAsyncId() const;
64
65  Local<Object> CreateHook(const v8::FunctionCallbackInfo<v8::Value>& args);
66
67  Persistent<FunctionTemplate> async_hook_ctor;
68
69 private:
70  base::RecursiveMutex async_wraps_mutex_;
71  std::vector<std::shared_ptr<AsyncHooksWrap>> async_wraps_;
72  Isolate* isolate_;
73  Persistent<ObjectTemplate> async_hooks_templ;
74  Persistent<Private> async_id_smb;
75  Persistent<Private> trigger_id_smb;
76
77  static void ShellPromiseHook(PromiseHookType type, Local<Promise> promise,
78                               Local<Value> parent);
79  static void PromiseHookDispatch(PromiseHookType type, Local<Promise> promise,
80                                  Local<Value> parent,
81                                  const AsyncHooksWrap& wrap,
82                                  AsyncHooks* hooks);
83
84  std::stack<AsyncContext> asyncContexts;
85  async_id_t current_async_id;
86};
87
88}  // namespace v8
89
90#endif  // V8_D8_ASYNC_HOOKS_WRAPPER_H_
91