• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef SRC_NODE_WORKER_H_
2 #define SRC_NODE_WORKER_H_
3 
4 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
5 
6 #include <optional>
7 #include <unordered_map>
8 #include "node_messaging.h"
9 #include "uv.h"
10 
11 namespace node {
12 
13 struct SnapshotData;
14 namespace worker {
15 
16 class WorkerThreadData;
17 
18 enum ResourceLimits {
19   kMaxYoungGenerationSizeMb,
20   kMaxOldGenerationSizeMb,
21   kCodeRangeSizeMb,
22   kStackSizeMb,
23   kTotalResourceLimitCount
24 };
25 
26 // A worker thread, as represented in its parent thread.
27 class Worker : public AsyncWrap {
28  public:
29   Worker(Environment* env,
30          v8::Local<v8::Object> wrap,
31          const std::string& url,
32          const std::string& name,
33          std::shared_ptr<PerIsolateOptions> per_isolate_opts,
34          std::vector<std::string>&& exec_argv,
35          std::shared_ptr<KVStore> env_vars,
36          const SnapshotData* snapshot_data);
37   ~Worker() override;
38 
39   // Run the worker. This is only called from the worker thread.
40   void Run();
41 
42   // Forcibly exit the thread with a specified exit code. This may be called
43   // from any thread. `error_code` and `error_message` can be used to create
44   // a custom `'error'` event before emitting `'exit'`.
45   void Exit(int code,
46             const char* error_code = nullptr,
47             const char* error_message = nullptr);
48 
49   // Wait for the worker thread to stop (in a blocking manner).
50   void JoinThread();
51 
52   template <typename Fn>
53   inline bool RequestInterrupt(Fn&& cb);
54 
55   SET_NO_MEMORY_INFO()
56   SET_MEMORY_INFO_NAME(Worker)
57   SET_SELF_SIZE(Worker)
58   bool IsNotIndicativeOfMemoryLeakAtExit() const override;
59 
60   bool is_stopped() const;
snapshot_data()61   const SnapshotData* snapshot_data() const { return snapshot_data_; }
62 
63   static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
64   static void CloneParentEnvVars(
65       const v8::FunctionCallbackInfo<v8::Value>& args);
66   static void SetEnvVars(const v8::FunctionCallbackInfo<v8::Value>& args);
67   static void StartThread(const v8::FunctionCallbackInfo<v8::Value>& args);
68   static void StopThread(const v8::FunctionCallbackInfo<v8::Value>& args);
69   static void HasRef(const v8::FunctionCallbackInfo<v8::Value>& args);
70   static void Ref(const v8::FunctionCallbackInfo<v8::Value>& args);
71   static void Unref(const v8::FunctionCallbackInfo<v8::Value>& args);
72   static void GetResourceLimits(
73       const v8::FunctionCallbackInfo<v8::Value>& args);
74   v8::Local<v8::Float64Array> GetResourceLimits(v8::Isolate* isolate) const;
75   static void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args);
76   static void LoopIdleTime(const v8::FunctionCallbackInfo<v8::Value>& args);
77   static void LoopStartTime(const v8::FunctionCallbackInfo<v8::Value>& args);
78 
79  private:
80   bool CreateEnvMessagePort(Environment* env);
81   static size_t NearHeapLimit(void* data, size_t current_heap_limit,
82                               size_t initial_heap_limit);
83 
84   std::shared_ptr<PerIsolateOptions> per_isolate_opts_;
85   std::vector<std::string> exec_argv_;
86   std::vector<std::string> argv_;
87 
88   MultiIsolatePlatform* platform_;
89   v8::Isolate* isolate_ = nullptr;
90   std::optional<uv_thread_t> tid_;  // Set while the thread is running
91 
92   std::unique_ptr<InspectorParentHandle> inspector_parent_handle_;
93 
94   // This mutex protects access to all variables listed below it.
95   mutable Mutex mutex_;
96 
97   const char* custom_error_ = nullptr;
98   std::string custom_error_str_;
99   int exit_code_ = 0;
100   ThreadId thread_id_;
101   uintptr_t stack_base_ = 0;
102   // Optional name used for debugging in inspector and trace events.
103   std::string name_;
104 
105   // Custom resource constraints:
106   double resource_limits_[kTotalResourceLimitCount];
107   void UpdateResourceConstraints(v8::ResourceConstraints* constraints);
108 
109   // Full size of the thread's stack.
110   size_t stack_size_ = 4 * 1024 * 1024;
111   // Stack buffer size that is not available to the JS engine.
112   static constexpr size_t kStackBufferSize = 192 * 1024;
113 
114   std::unique_ptr<MessagePortData> child_port_data_;
115   std::shared_ptr<KVStore> env_vars_;
116 
117   // A raw flag that is used by creator and worker threads to
118   // sync up on pre-mature termination of worker  - while in the
119   // warmup phase.  Once the worker is fully warmed up, use the
120   // async handle of the worker's Environment for the same purpose.
121   bool stopped_ = true;
122 
123   bool has_ref_ = true;
124   uint64_t environment_flags_ = EnvironmentFlags::kNoFlags;
125 
126   // The real Environment of the worker object. It has a lesser
127   // lifespan than the worker object itself - comes to life
128   // when the worker thread creates a new Environment, and gets
129   // destroyed alongwith the worker thread.
130   Environment* env_ = nullptr;
131 
132   const SnapshotData* snapshot_data_ = nullptr;
133   friend class WorkerThreadData;
134 };
135 
136 template <typename Fn>
RequestInterrupt(Fn && cb)137 bool Worker::RequestInterrupt(Fn&& cb) {
138   Mutex::ScopedLock lock(mutex_);
139   if (env_ == nullptr) return false;
140   env_->RequestInterrupt(std::move(cb));
141   return true;
142 }
143 
144 }  // namespace worker
145 }  // namespace node
146 
147 #endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
148 
149 
150 #endif  // SRC_NODE_WORKER_H_
151