深入理解 V8 Inspector中几个关键的角色

开发 前端
本文介绍一下 V8 关于 Inspector 的实现,不过不会涉及到具体命令的实现,V8 Inspector 的命令非常多,了解了处理流程后,如果对某个命令感兴趣的话,可以单独去分析。

[[430568]]

前言:本文介绍一下 V8 关于 Inspector 的实现,不过不会涉及到具体命令的实现,V8 Inspector 的命令非常多,了解了处理流程后,如果对某个命令感兴趣的话,可以单独去分析。

首先来看一下 V8 Inspector 中几个关键的角色。

 V8InspectorSession

  1. class V8_EXPORT V8InspectorSession { 
  2.  public
  3.   // 收到对端端消息,调用这个方法判断是否可以分发 
  4.   static bool canDispatchMethod(StringView method); 
  5.   // 收到对端端消息,调用这个方法判断分发 
  6.   virtual void dispatchProtocolMessage(StringView message) = 0; 
  7.  
  8. }; 

V8InspectorSession 是一个基类,本身实现了 canDispatchMethod 方法,由子类实现 dispatchProtocolMessage 方法。看一下 canDispatchMethod 的实现。

  1. bool V8InspectorSession::canDispatchMethod(StringView method) { 
  2.   return stringViewStartsWith(method, 
  3.                               protocol::Runtime::Metainfo::commandPrefix) || 
  4.          stringViewStartsWith(method, 
  5.                               protocol::Debugger::Metainfo::commandPrefix) || 
  6.          stringViewStartsWith(method, 
  7.                               protocol::Profiler::Metainfo::commandPrefix) || 
  8.          stringViewStartsWith( 
  9.              method, protocol::HeapProfiler::Metainfo::commandPrefix) || 
  10.          stringViewStartsWith(method, 
  11.                               protocol::Console::Metainfo::commandPrefix) || 
  12.          stringViewStartsWith(method, 
  13.                               protocol::Schema::Metainfo::commandPrefix); 
  14.  

canDispatchMethod 决定了 V8 目前支持哪些命令。接着看一下 V8InspectorSession 子类的实现。

  1. class V8InspectorSessionImpl : public V8InspectorSession, 
  2.                                public protocol::FrontendChannel { 
  3.  public
  4.   // 静态方法,用于创建 V8InspectorSessionImpl 
  5.   static std::unique_ptr<V8InspectorSessionImpl> create(V8InspectorImpl*, 
  6.                                                         int contextGroupId, 
  7.                                                         int sessionId, 
  8.                                                         V8Inspector::Channel*, 
  9.                                                         StringView state); 
  10.   // 实现命令的分发 
  11.   void dispatchProtocolMessage(StringView message) override; 
  12.   // 支持哪些命令 
  13.   std::vector<std::unique_ptr<protocol::Schema::API::Domain>> supportedDomains() override; 
  14.  
  15.  private: 
  16.   // 发送消息给对端 
  17.   void SendProtocolResponse(int callId, std::unique_ptr<protocol::Serializable> message) override; 
  18.   void SendProtocolNotification(std::unique_ptr<protocol::Serializable> message) override; 
  19.  
  20.   // 会话 id 
  21.   int m_sessionId; 
  22.   // 关联的 V8Inspector 对象 
  23.   V8InspectorImpl* m_inspector; 
  24.   // 关联的 channel,channel 表示会话的两端 
  25.   V8Inspector::Channel* m_channel; 
  26.   // 处理命令分发对象 
  27.   protocol::UberDispatcher m_dispatcher; 
  28.   // 处理某种命令的代理对象 
  29.   std::unique_ptr<V8RuntimeAgentImpl> m_runtimeAgent; 
  30.   std::unique_ptr<V8DebuggerAgentImpl> m_debuggerAgent; 
  31.   std::unique_ptr<V8HeapProfilerAgentImpl> m_heapProfilerAgent; 
  32.   std::unique_ptr<V8ProfilerAgentImpl> m_profilerAgent; 
  33.   std::unique_ptr<V8ConsoleAgentImpl> m_consoleAgent; 
  34.   std::unique_ptr<V8SchemaAgentImpl> m_schemaAgent; 
  35.  
  36. }; 

下面看一下核心方法的具体实现。

创建 V8InspectorSessionImpl

  1. V8InspectorSessionImpl::V8InspectorSessionImpl(V8InspectorImpl* inspector, 
  2.                                                int contextGroupId, 
  3.                                                int sessionId, 
  4.                                                V8Inspector::Channel* channel, 
  5.                                                StringView savedState) 
  6.     : m_contextGroupId(contextGroupId), 
  7.       m_sessionId(sessionId), 
  8.       m_inspector(inspector), 
  9.       m_channel(channel), 
  10.       m_customObjectFormatterEnabled(false), 
  11.       m_dispatcher(this), 
  12.       m_state(ParseState(savedState)), 
  13.       m_runtimeAgent(nullptr), 
  14.       m_debuggerAgent(nullptr), 
  15.       m_heapProfilerAgent(nullptr), 
  16.       m_profilerAgent(nullptr), 
  17.       m_consoleAgent(nullptr), 
  18.       m_schemaAgent(nullptr) { 
  19.  
  20.   m_runtimeAgent.reset(new V8RuntimeAgentImpl(this, this, agentState(protocol::Runtime::Metainfo::domainName))); 
  21.   protocol::Runtime::Dispatcher::wire(&m_dispatcher, m_runtimeAgent.get()); 
  22.  
  23.   m_debuggerAgent.reset(new V8DebuggerAgentImpl(this, this, agentState(protocol::Debugger::Metainfo::domainName))); 
  24.   protocol::Debugger::Dispatcher::wire(&m_dispatcher, m_debuggerAgent.get()); 
  25.  
  26.   m_profilerAgent.reset(new V8ProfilerAgentImpl(this, this, agentState(protocol::Profiler::Metainfo::domainName))); 
  27.   protocol::Profiler::Dispatcher::wire(&m_dispatcher, m_profilerAgent.get()); 
  28.  
  29.   m_heapProfilerAgent.reset(new V8HeapProfilerAgentImpl(this, this, agentState(protocol::HeapProfiler::Metainfo::domainName))); 
  30.   protocol::HeapProfiler::Dispatcher::wire(&m_dispatcher,m_heapProfilerAgent.get()); 
  31.  
  32.   m_consoleAgent.reset(new V8ConsoleAgentImpl(this, this, agentState(protocol::Console::Metainfo::domainName))); 
  33.   protocol::Console::Dispatcher::wire(&m_dispatcher, m_consoleAgent.get()); 
  34.  
  35.   m_schemaAgent.reset(new V8SchemaAgentImpl(this, this, agentState(protocol::Schema::Metainfo::domainName))); 
  36.   protocol::Schema::Dispatcher::wire(&m_dispatcher, m_schemaAgent.get()); 
  37.  

V8 支持很多种命令,在创建 V8InspectorSessionImpl 对象时,会注册所有命令和处理该命令的处理器。我们一会单独分析。

 接收请求

  1. void V8InspectorSessionImpl::dispatchProtocolMessage(StringView message) { 
  2.   using v8_crdtp::span; 
  3.   using v8_crdtp::SpanFrom; 
  4.   span<uint8_t> cbor; 
  5.   std::vector<uint8_t> converted_cbor; 
  6.   if (IsCBORMessage(message)) { 
  7.     use_binary_protocol_ = true
  8.     m_state->setBoolean("use_binary_protocol"true); 
  9.     cbor = span<uint8_t>(message.characters8(), message.length()); 
  10.   } else { 
  11.     auto status = ConvertToCBOR(message, &converted_cbor); 
  12.     cbor = SpanFrom(converted_cbor); 
  13.   } 
  14.   v8_crdtp::Dispatchable dispatchable(cbor); 
  15.   // 消息分发 
  16.   m_dispatcher.Dispatch(dispatchable).Run(); 
  17.  

接收消息后,在内部通过 m_dispatcher.Dispatch 进行分发,这就好比我们在 Node.js 里收到请求后,根据路由分发一样。具体的分发逻辑一会单独分析。3. 响应请求

  1. void V8InspectorSessionImpl::SendProtocolResponse( 
  2.     int callId, std::unique_ptr<protocol::Serializable> message) { 
  3.   m_channel->sendResponse(callId, serializeForFrontend(std::move(message))); 
  4.  

具体的处理逻辑由 channel 实现,channel 由 V8 的使用者实现,比如 Node.js。

数据推送

  1. void V8InspectorSessionImpl::SendProtocolNotification( 
  2.     std::unique_ptr<protocol::Serializable> message) { 
  3.   m_channel->sendNotification(serializeForFrontend(std::move(message))); 
  4.  

除了一个请求对应一个响应,V8 Inspector 还需要主动推送的能力,具体处理逻辑也是由 channel 实现。从上面点分析可以看到 V8InspectorSessionImpl 的概念相当于一个服务器,在启动的时候注册了一系列路由,当建立一个连接时,就会创建一个 Channel 对象表示。调用方可以通过 Channel 完成请求和接收响应。结构如下图所示。

 V8Inspector

  1. class V8_EXPORT V8Inspector { 
  2.  public
  3.   // 静态方法,用于创建 V8Inspector 
  4.   static std::unique_ptr<V8Inspector> create(v8::Isolate*, V8InspectorClient*); 
  5.   // 用于创建一个 V8InspectorSession 
  6.   virtual std::unique_ptr<V8InspectorSession> connect(int contextGroupId, 
  7.                                                       Channel*, 
  8.                                                       StringView state) = 0; 
  9.  
  10. }; 

V8Inspector 是一个通信的总管,他不负责具体的通信,他只是负责管理通信者,Channel 才是负责通信的角色。下面看一下 V8Inspector 子类的实现 。

  1. class V8InspectorImpl : public V8Inspector { 
  2.  public
  3.   V8InspectorImpl(v8::Isolate*, V8InspectorClient*); 
  4.   // 创建一个会话 
  5.   std::unique_ptr<V8InspectorSession> connect(int contextGroupId, 
  6.                                               V8Inspector::Channel*, 
  7.                                               StringView state) override; 
  8.  
  9.  private: 
  10.   v8::Isolate* m_isolate; 
  11.   // 关联的 V8InspectorClient 对象,V8InspectorClient 封装了 V8Inspector,由调用方实现 
  12.   V8InspectorClient* m_client; 
  13.   // 保存所有的会话 
  14.   std::unordered_map<int, std::map<int, V8InspectorSessionImpl*>> m_sessions; 
  15.  
  16. }; 

V8InspectorImpl 提供了创建会话的方法并保存了所有创建的会话,看一下创建会话的逻辑。

  1. std::unique_ptr<V8InspectorSession> V8InspectorImpl::connect(int contextGroupId, V8Inspector::Channel* channel, StringView state) { 
  2.   int sessionId = ++m_lastSessionId; 
  3.   std::unique_ptr<V8InspectorSessionImpl> session = V8InspectorSessionImpl::create(this, contextGroupId, sessionId, channel, state); 
  4.   m_sessions[contextGroupId][sessionId] = session.get(); 
  5.   return std::move(session); 
  6.  

connect 是创建了一个 V8InspectorSessionImpl 对象,并通过 id 保存到 map中。结构图如下。

UberDispatcher

UberDispatcher 是一个命令分发器。

  1. class UberDispatcher { 
  2.  public
  3.   // 表示分发结果的对象 
  4.   class DispatchResult {}; 
  5.   // 分发处理函数 
  6.   DispatchResult Dispatch(const Dispatchable& dispatchable) const; 
  7.   // 注册命令和处理器  
  8.   void WireBackend(span<uint8_t> domain, 
  9.                    const std::vector<std::pair<span<uint8_t>, span<uint8_t>>>&, 
  10.                    std::unique_ptr<DomainDispatcher> dispatcher); 
  11.  
  12.  private: 
  13.   // 查找命令对应的处理器,Dispatch 中使用 
  14.   DomainDispatcher* findDispatcher(span<uint8_t> method); 
  15.   // 关联的 channel 
  16.   FrontendChannel* const frontend_channel_; 
  17.   std::vector<std::pair<span<uint8_t>, span<uint8_t>>> redirects_; 
  18.   // 命令处理器队列 
  19.   std::vector<std::pair<span<uint8_t>, std::unique_ptr<DomainDispatcher>>> 
  20.       dispatchers_; 
  21.  
  22. }; 

下面看一下注册和分发的实现。

注册

  1. void UberDispatcher::WireBackend(span<uint8_t> domain, std::unique_ptr<DomainDispatcher> dispatcher) { 
  2.   dispatchers_.insert(dispatchers_.end(), std::make_pair(domain, std::move(dispatcher)));); 
  3.  

WireBackend 就是在队列里插入一个新的 domain 和 处理器组合。

分发命令

  1. UberDispatcher::DispatchResult UberDispatcher::Dispatch( 
  2.     const Dispatchable& dispatchable) const { 
  3.   span<uint8_t> method = FindByFirst(redirects_, dispatchable.Method(), 
  4.                                      /*default_value=*/dispatchable.Method()); 
  5.   // 找到 . 的偏移,命令格式是 A.B                                    
  6.   size_t dot_idx = DotIdx(method); 
  7.   // 拿到 domain,即命令的第一部分 
  8.   span<uint8_t> domain = method.subspan(0, dot_idx); 
  9.   // 拿到命令 
  10.   span<uint8_t> command = method.subspan(dot_idx + 1); 
  11.   // 通过 domain 查找对应的处理器 
  12.   DomainDispatcher* dispatcher = FindByFirst(dispatchers_, domain); 
  13.   if (dispatcher) { 
  14.     // 交给 domain 对应的处理器继续处理 
  15.     std::function<void(const Dispatchable&)> dispatched = 
  16.         dispatcher->Dispatch(command); 
  17.     if (dispatched) { 
  18.       return DispatchResult( 
  19.           true, [dispatchable, dispatched = std::move(dispatched)]() { 
  20.             dispatched(dispatchable); 
  21.           }); 
  22.     } 
  23.   } 
  24.  

 DomainDispatcher

刚才分析了 UberDispatcher,UberDispatcher 是一个命令一级分发器,因为命令是 domain.cmd 的格式,UberDispatcher 是根据 domain 进行初步分发,DomainDispatcher 则是找到具体命令对应的处理器。

  1. class DomainDispatcher { 
  2.   // 分发逻辑,子类实现 
  3.   virtual std::function<void(const Dispatchable&)> Dispatch(span<uint8_t> command_name) = 0; 
  4.  
  5.   // 处理完后响应 
  6.   void sendResponse(int call_id, 
  7.                     const DispatchResponse&, 
  8.                     std::unique_ptr<Serializable> result = nullptr); 
  9.  private: 
  10.   // 关联的 channel 
  11.   FrontendChannel* frontend_channel_; 
  12.  
  13. }; 

DomainDispatcher 定义了命令分发和响应的逻辑,不同的 domain 的分发逻辑会有不同的实现,但是响应逻辑是一样的,所以基类实现了。

  1. void DomainDispatcher::sendResponse(int call_id, 
  2.                                     const DispatchResponse& response, 
  3.                                     std::unique_ptr<Serializable> result) { 
  4.   std::unique_ptr<Serializableserializable
  5.   if (response.IsError()) { 
  6.     serializable = CreateErrorResponse(call_id, response); 
  7.   } else { 
  8.     serializable = CreateResponse(call_id, std::move(result)); 
  9.   } 
  10.   frontend_channel_->SendProtocolResponse(call_id, std::move(serializable)); 
  11.  

通过 frontend_channel_ 返回响应。接下来看子类的实现,这里以 HeapProfiler 为例。

  1. class DomainDispatcherImpl : public protocol::DomainDispatcher { 
  2. public
  3.     DomainDispatcherImpl(FrontendChannel* frontendChannel, Backend* backend) 
  4.         : DomainDispatcher(frontendChannel) 
  5.         , m_backend(backend) {} 
  6.     ~DomainDispatcherImpl() override { } 
  7.  
  8.     using CallHandler = void (DomainDispatcherImpl::*)(const v8_crdtp::Dispatchable& dispatchable); 
  9.     // 分发的实现 
  10.     std::function<void(const v8_crdtp::Dispatchable&)> Dispatch(v8_crdtp::span<uint8_t> command_name) override; 
  11.     // HeapProfiler 支持的命令 
  12.     void addInspectedHeapObject(const v8_crdtp::Dispatchable& dispatchable); 
  13.     void collectGarbage(const v8_crdtp::Dispatchable& dispatchable); 
  14.     void disable(const v8_crdtp::Dispatchable& dispatchable); 
  15.     void enable(const v8_crdtp::Dispatchable& dispatchable); 
  16.     void getHeapObjectId(const v8_crdtp::Dispatchable& dispatchable); 
  17.     void getObjectByHeapObjectId(const v8_crdtp::Dispatchable& dispatchable); 
  18.     void getSamplingProfile(const v8_crdtp::Dispatchable& dispatchable); 
  19.     void startSampling(const v8_crdtp::Dispatchable& dispatchable); 
  20.     void startTrackingHeapObjects(const v8_crdtp::Dispatchable& dispatchable); 
  21.     void stopSampling(const v8_crdtp::Dispatchable& dispatchable); 
  22.     void stopTrackingHeapObjects(const v8_crdtp::Dispatchable& dispatchable); 
  23.     void takeHeapSnapshot(const v8_crdtp::Dispatchable& dispatchable); 
  24.  protected: 
  25.     Backend* m_backend; 
  26.  
  27. }; 

DomainDispatcherImpl 定义了 HeapProfiler 支持的命令,下面分析一下命令的注册和分发的处理逻辑。下面是 HeapProfiler 注册 domain 和 处理器的逻辑(创建 V8InspectorSessionImpl 时)

  1. // backend 是处理命令的具体对象,对于 HeapProfiler domain 是 V8HeapProfilerAgentImpl 
  2.  
  3. void Dispatcher::wire(UberDispatcher* uber, Backend* backend){    
  4.      
  5.  
  6.     // channel 是通信的对端 
  7.     auto dispatcher = std::make_unique<DomainDispatcherImpl>(uber->channel(), backend); 
  8.     // 注册 domain 对应的处理器 
  9.     uber->WireBackend(v8_crdtp::SpanFrom("HeapProfiler"), std::move(dispatcher)); 
  10.  

接下来看一下收到命令时具体的分发逻辑。

  1. std::function<void(const v8_crdtp::Dispatchable&)> DomainDispatcherImpl::Dispatch(v8_crdtp::span<uint8_t> command_name) { 
  2.   // 根据命令查找处理函数 
  3.   CallHandler handler = CommandByName(command_name); 
  4.   // 返回个函数,外层执行 
  5.   return [this, handler](const v8_crdtp::Dispatchable& dispatchable) { 
  6.     (this->*handler)(dispatchable); 
  7.   }; 
  8.  

看一下查找的逻辑。

  1. DomainDispatcherImpl::CallHandler CommandByName(v8_crdtp::span<uint8_t> command_name) { 
  2.   static auto* commands = [](){ 
  3.     auto* commands = new std::vector<std::pair<v8_crdtp::span<uint8_t>, DomainDispatcherImpl::CallHandler>>{ 
  4.         // 太多,不一一列举 
  5.         { 
  6.           v8_crdtp::SpanFrom("enable"), 
  7.           &DomainDispatcherImpl::enable 
  8.         }, 
  9.     }; 
  10.     return commands; 
  11.   }(); 
  12.   return v8_crdtp::FindByFirst<DomainDispatcherImpl::CallHandler>(*commands, command_name, nullptr); 
  13.  

再看一下 DomainDispatcherImpl::enable 的实现。

  1. void DomainDispatcherImpl::enable(const v8_crdtp::Dispatchable& dispatchable){ 
  2.     std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr(); 
  3.     // 调用 m_backend 也就是 V8HeapProfilerAgentImpl 的 enable 
  4.     DispatchResponse response = m_backend->enable(); 
  5.     if (response.IsFallThrough()) { 
  6.         channel()->FallThrough(dispatchable.CallId(), v8_crdtp::SpanFrom("HeapProfiler.enable"), dispatchable.Serialized()); 
  7.         return
  8.     } 
  9.     if (weak->get()) 
  10.         weak->get()->sendResponse(dispatchable.CallId(), response); 
  11.     return
  12.  

DomainDispatcherImpl 只是封装,具体的命令处理交给 m_backend 所指向的对象,这里是 V8HeapProfilerAgentImpl。下面是 V8HeapProfilerAgentImpl enable 的实现。

  1. Response V8HeapProfilerAgentImpl::enable() { 
  2.   m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, true); 
  3.   return Response::Success(); 
  4.  

结构图如下。

V8HeapProfilerAgentImpl

刚才分析了 V8HeapProfilerAgentImpl 的 enable 函数,这里以 V8HeapProfilerAgentImpl 为例子分析一下命令处理器类的逻辑。

  1. class V8HeapProfilerAgentImpl : public protocol::HeapProfiler::Backend { 
  2.  public
  3.   V8HeapProfilerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, 
  4.                           protocol::DictionaryValue* state); 
  5.  
  6.  private: 
  7.  
  8.   V8InspectorSessionImpl* m_session; 
  9.   v8::Isolate* m_isolate; 
  10.   // protocol::HeapProfiler::Frontend 定义了支持哪些事件 
  11.   protocol::HeapProfiler::Frontend m_frontend; 
  12.   protocol::DictionaryValue* m_state; 
  13.  
  14. }; 

V8HeapProfilerAgentImpl 通过 protocol::HeapProfiler::Frontend 定义了支持的事件,因为 Inspector 不仅可以处理调用方发送的命令,还可以主动给调用方推送消息,这种推送就是以事件的方式触发的。

  1. class  Frontend { 
  2. public
  3.   explicit Frontend(FrontendChannel* frontend_channel) : frontend_channel_(frontend_channel) {} 
  4.     void addHeapSnapshotChunk(const String& chunk); 
  5.     void heapStatsUpdate(std::unique_ptr<protocol::Array<int>> statsUpdate); 
  6.     void lastSeenObjectId(int lastSeenObjectId, double timestamp); 
  7.     void reportHeapSnapshotProgress(int done, int total, Maybe<bool> finished = Maybe<bool>()); 
  8.     void resetProfiles(); 
  9.  
  10.   void flush(); 
  11.   void sendRawNotification(std::unique_ptr<Serializable>); 
  12.  private: 
  13.   // 指向 V8InspectorSessionImpl 对象 
  14.   FrontendChannel* frontend_channel_; 
  15.  
  16. }; 

下面看一下 addHeapSnapshotChunk,这是获取堆快照时用到的逻辑。

  1. void Frontend::addHeapSnapshotChunk(const String& chunk){ 
  2.     v8_crdtp::ObjectSerializer serializer; 
  3.     serializer.AddField(v8_crdtp::MakeSpan("chunk"), chunk); 
  4.     frontend_channel_->SendProtocolNotification(v8_crdtp::CreateNotification("HeapProfiler.addHeapSnapshotChunk", serializer.Finish())); 
  5.  

最终触发了 HeapProfiler.addHeapSnapshotChunk 事件。另外 V8HeapProfilerAgentImpl 继承了 Backend 定义了支持哪些请求命令和 DomainDispatcherImpl 中的函数对应,比如获取堆快照。

  1. class  Backend { 
  2. public
  3.     virtual ~Backend() { } 
  4.     // 不一一列举 
  5.     virtual DispatchResponse takeHeapSnapshot(Maybe<bool> in_reportProgress, Maybe<bool> in_treatGlobalObjectsAsRoots, Maybe<bool> in_captureNumericValue) = 0; 
  6.  
  7. }; 

结构图如下。

Node.js 对 V8 Inspector 的封装

接下来看一下 Node.js 中是如何使用 V8 Inspector 的,V8 Inspector 的使用方需要实现 V8InspectorClient 和 V8Inspector::Channel。下面看一下 Node.js 的实现。

  1. class NodeInspectorClient : public V8InspectorClient { 
  2.  public
  3.   explicit NodeInspectorClient() { 
  4.     // 创建一个 V8Inspector 
  5.     client_ = V8Inspector::create(env->isolate(), this); 
  6.   } 
  7.  
  8.   int connectFrontend(std::unique_ptr<InspectorSessionDelegate> delegate, 
  9.                       bool prevent_shutdown) { 
  10.     int session_id = next_session_id_++; 
  11.     channels_[session_id] = std::make_unique<ChannelImpl>(env_, 
  12.                                                           client_, 
  13.                                                           getWorkerManager(), 
  14.                                                           // 收到数据后由 delegate 处理 
  15.                                                           std::move(delegate), 
  16.                                                           getThreadHandle(), 
  17.                                                           prevent_shutdown); 
  18.     return session_id; 
  19.   } 
  20.  
  21.   std::unique_ptr<V8Inspector> client_; 
  22.   std::unordered_map<int, std::unique_ptr<ChannelImpl>> channels_; 
  23.  
  24. }; 

NodeInspectorClient 封装了 V8Inspector,并且维护了多个 channel。Node.js 的上层代码可以通过 connectFrontend 连接到 V8 Inspector,并拿到 session_id,这个连接用 ChannelImpl 来实现,来看一下 ChannelImpl 的实现。

  1. explicit ChannelImpl(const std::unique_ptr<V8Inspector>& inspector,  
  2.                      std::unique_ptr<InspectorSessionDelegate> delegate):  
  3.                      // delegate_ 负责处理 V8 发过来的数据 
  4.                      delegate_(std::move(delegate)) { 
  5.     session_ = inspector->connect(CONTEXT_GROUP_ID, this, StringView()); 
  6.  

ChannelImpl 是对 V8InspectorSession 的封装,通过 V8InspectorSession 实现发送命令,ChannelImpl 自己实现了接收响应和接收 V8 推送数据的逻辑。了解了封装 V8 Inspector 的能力后,通过一个例子看一下整个处理过程。通常我们通过以下方式和 V8 Inspector 通信。

  1. const { Session } = require('inspector'); 
  2. new Session().connect(); 

我们从 connect 开始分析。

  1. connect() { 
  2.     this[connectionSymbol] = new Connection((message) => this[onMessageSymbol](message)); 

新建一个 C++ 层的对象 JSBindingsConnection。

  1. JSBindingsConnection(Environment* env, 
  2.                        Local<Object> wrap, 
  3.                        Local<Function> callback) 
  4.                        : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING), 
  5.                          callback_(env->isolate(), callback) { 
  6.     Agent* inspector = env->inspector_agent(); 
  7.     session_ = LocalConnection::Connect(inspector, std::make_unique<JSBindingsSessionDelegate>(env, this));}static std::unique_ptr<InspectorSession> Connect
  8.      Agent* inspector, std::unique_ptr<InspectorSessionDelegate> delegate) { 
  9.    return inspector->Connect(std::move(delegate), false); 
  10.  
  11.  
  12.  
  13. std::unique_ptr<InspectorSession> Agent::Connect
  14.     std::unique_ptr<InspectorSessionDelegate> delegate, 
  15.     bool prevent_shutdown) { 
  16.   int session_id = client_->connectFrontend(std::move(delegate), 
  17.                                             prevent_shutdown); 
  18.   return std::unique_ptr<InspectorSession>( 
  19.       new SameThreadInspectorSession(session_id, client_)); 
  20.  

JSBindingsConnection 初始化时会通过 agent->Connect 最终调用 Agent::Connect 建立到 V8 的通道,并传入 JSBindingsSessionDelegate 作为数据处理的代理(channel 中使用)。最后返回一个 SameThreadInspectorSession 对象保存到 session_ 中,后续就可以开始通信了,继续看一下 通过 JS 层的 post 发送请求时的逻辑。

  1. post(method, params, callback) { 
  2.     const id = this[nextIdSymbol]++; 
  3.     const message = { id, method }; 
  4.     if (params) { 
  5.       message.params = params; 
  6.     } 
  7.     if (callback) { 
  8.       this[messageCallbacksSymbol].set(id, callback); 
  9.     } 
  10.     this[connectionSymbol].dispatch(JSONStringify(message)); 

为每一个请求生成一个 id,因为是异步返回的,最后调用 dispatch 函数。

  1. static void Dispatch(const FunctionCallbackInfo<Value>& info) { 
  2.     Environment* env = Environment::GetCurrent(info); 
  3.     JSBindingsConnection* session; 
  4.     ASSIGN_OR_RETURN_UNWRAP(&session, info.Holder()); 
  5.  
  6.     if (session->session_) { 
  7.       session->session_->Dispatch( 
  8.           ToProtocolString(env->isolate(), info[0])->string()); 
  9.     } 

看一下 SameThreadInspectorSession::Dispatch (即session->session_->Dispatch)。

  1. void SameThreadInspectorSession::Dispatch( 
  2.     const v8_inspector::StringView& message) { 
  3.   auto client = client_.lock(); 
  4.   if (client) 
  5.     client->dispatchMessageFromFrontend(session_id_, message); 
  6.  

SameThreadInspectorSession 中维护了一个sessionId,继续调用 client->dispatchMessageFromFrontend, client 是 NodeInspectorClient 对象。

  1. void dispatchMessageFromFrontend(int session_id, const StringView& message) { 
  2.    channels_[session_id]->dispatchProtocolMessage(message); 

dispatchMessageFromFrontend 通过 sessionId 找到对应的 channel。继续调 channel 的 dispatchProtocolMessage。

  1. void dispatchProtocolMessage(const StringView& message) { 
  2.     std::string raw_message = protocol::StringUtil::StringViewToUtf8(message); 
  3.     std::unique_ptr<protocol::DictionaryValue> value = 
  4.         protocol::DictionaryValue::cast(protocol::StringUtil::parseMessage( 
  5.             raw_message, false)); 
  6.     int call_id; 
  7.     std::string method; 
  8.     node_dispatcher_->parseCommand(value.get(), &call_id, &method); 
  9.     if (v8_inspector::V8InspectorSession::canDispatchMethod( 
  10.             Utf8ToStringView(method)->string())) { 
  11.       session_->dispatchProtocolMessage(message); 
  12.     } 

最终调用 V8InspectorSessionImpl 的 session_->dispatchProtocolMessage(message),后面的内容前面就讲过了,就不再分析。最后看一下数据响应或者推送时的逻辑。下面代码来自 ChannelImpl。

  1. void sendResponse( 
  2.   int callId, 
  3.     std::unique_ptr<v8_inspector::StringBuffer> message) override { 
  4.   sendMessageToFrontend(message->string()); 
  5.  
  6.  
  7.  
  8.  
  9. void sendNotification( 
  10.  
  11.     std::unique_ptr<v8_inspector::StringBuffer> message) override { 
  12.   sendMessageToFrontend(message->string()); 
  13.  
  14.  
  15.  
  16.  
  17. void sendMessageToFrontend(const StringView& message) { 
  18.  
  19.   delegate_->SendMessageToFrontend(message); 
  20.  

我们看到最终调用了 delegate_->SendMessageToFrontend, delegate 是 JSBindingsSessionDelegate对象。

  1. void SendMessageToFrontend(const v8_inspector::StringView& message) 
  2.         override { 
  3.   Isolate* isolate = env_->isolate(); 
  4.   HandleScope handle_scope(isolate); 
  5.   Context::Scope context_scope(env_->context()); 
  6.   MaybeLocal<String> v8string = String::NewFromTwoByte(isolate, message.characters16(), 
  7.                              NewStringType::kNormal, message.length()); 
  8.   Local<Value> argument = v8string.ToLocalChecked().As<Value>(); 
  9.   connection_->OnMessage(argument); 
  10.  

接着调用 connection_->OnMessage(argument),connection 是 JSBindingsConnection 对象。

  1. void OnMessage(Local<Value> value) { 
  2.   MakeCallback(callback_.Get(env()->isolate()), 1, &value); 
  3.  

C++ 层回调 JS 层。

  1. [onMessageSymbol](message) { 
  2.     const parsed = JSONParse(message); 
  3.     try { 
  4.       // 通过有没有 id 判断是响应还是推送 
  5.       if (parsed.id) { 
  6.         const callback = this[messageCallbacksSymbol].get(parsed.id); 
  7.         this[messageCallbacksSymbol].delete(parsed.id); 
  8.         if (callback) { 
  9.           if (parsed.error) { 
  10.             return callback(new ERR_INSPECTOR_COMMAND(parsed.error.code, 
  11.                                                       parsed.error.message)); 
  12.           } 
  13.  
  14.           callback(null, parsed.result); 
  15.         } 
  16.       } else { 
  17.         this.emit(parsed.method, parsed); 
  18.         this.emit('inspectorNotification', parsed); 
  19.       } 
  20.     } catch (error) { 
  21.       process.emitWarning(error); 
  22.     } 

以上就完成了整个链路的分析。整体结构图如下。

总结

V8 Inspector 的设计和实现上比较复杂,对象间关系错综复杂。因为 V8 提供调试和诊断 JS 的文档似乎不多,也不是很完善,就是简单描述一下命令是干啥的,很多时候不一定够用,了解了具体实现后,后续碰到问题,可以自己去看具体实现。

 

责任编辑:姜华 来源: 编程杂技
相关推荐

2020-09-27 07:32:18

V8

2021-08-05 05:46:06

Node.jsInspector工具

2022-06-29 08:05:25

Volatile关键字类型

2023-10-04 00:04:00

C++extern

2024-03-15 09:44:17

WPFDispatcherUI线程

2019-09-04 14:14:52

Java编程数据

2021-05-28 05:30:55

HandleV8代码

2016-08-31 15:50:50

PythonThreadLocal变量

2023-10-08 08:53:36

数据库MySQL算法

2010-06-28 10:12:01

PHP匿名函数

2014-06-23 10:42:56

iOS开发UIScrollVie

2018-07-09 15:11:14

Java逃逸JVM

2020-12-16 09:47:01

JavaScript箭头函数开发

2015-09-17 10:51:35

修改hostnameLinux

2023-09-24 13:58:20

C++1auto

2024-02-26 10:36:59

C++开发关键字

2013-06-20 10:25:56

2013-11-05 13:29:04

JavaScriptreplace

2016-12-08 15:36:59

HashMap数据结构hash函数

2010-06-01 15:25:27

JavaCLASSPATH
点赞
收藏

51CTO技术栈公众号