自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

深入理解 V8 Inspector中幾個(gè)關(guān)鍵的角色

開發(fā) 前端
本文介紹一下 V8 關(guān)于 Inspector 的實(shí)現(xiàn),不過不會(huì)涉及到具體命令的實(shí)現(xiàn),V8 Inspector 的命令非常多,了解了處理流程后,如果對(duì)某個(gè)命令感興趣的話,可以單獨(dú)去分析。

[[430568]]

前言:本文介紹一下 V8 關(guān)于 Inspector 的實(shí)現(xiàn),不過不會(huì)涉及到具體命令的實(shí)現(xiàn),V8 Inspector 的命令非常多,了解了處理流程后,如果對(duì)某個(gè)命令感興趣的話,可以單獨(dú)去分析。

首先來看一下 V8 Inspector 中幾個(gè)關(guān)鍵的角色。

 V8InspectorSession

  1. class V8_EXPORT V8InspectorSession { 
  2.  public
  3.   // 收到對(duì)端端消息,調(diào)用這個(gè)方法判斷是否可以分發(fā) 
  4.   static bool canDispatchMethod(StringView method); 
  5.   // 收到對(duì)端端消息,調(diào)用這個(gè)方法判斷分發(fā) 
  6.   virtual void dispatchProtocolMessage(StringView message) = 0; 
  7.  
  8. }; 

V8InspectorSession 是一個(gè)基類,本身實(shí)現(xiàn)了 canDispatchMethod 方法,由子類實(shí)現(xiàn) dispatchProtocolMessage 方法。看一下 canDispatchMethod 的實(shí)現(xiàn)。

  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 子類的實(shí)現(xiàn)。

  1. class V8InspectorSessionImpl : public V8InspectorSession, 
  2.                                public protocol::FrontendChannel { 
  3.  public
  4.   // 靜態(tài)方法,用于創(chuàng)建 V8InspectorSessionImpl 
  5.   static std::unique_ptr<V8InspectorSessionImpl> create(V8InspectorImpl*, 
  6.                                                         int contextGroupId, 
  7.                                                         int sessionId, 
  8.                                                         V8Inspector::Channel*, 
  9.                                                         StringView state); 
  10.   // 實(shí)現(xiàn)命令的分發(fā) 
  11.   void dispatchProtocolMessage(StringView message) override; 
  12.   // 支持哪些命令 
  13.   std::vector<std::unique_ptr<protocol::Schema::API::Domain>> supportedDomains() override; 
  14.  
  15.  private: 
  16.   // 發(fā)送消息給對(duì)端 
  17.   void SendProtocolResponse(int callId, std::unique_ptr<protocol::Serializable> message) override; 
  18.   void SendProtocolNotification(std::unique_ptr<protocol::Serializable> message) override; 
  19.  
  20.   // 會(huì)話 id 
  21.   int m_sessionId; 
  22.   // 關(guān)聯(lián)的 V8Inspector 對(duì)象 
  23.   V8InspectorImpl* m_inspector; 
  24.   // 關(guān)聯(lián)的 channel,channel 表示會(huì)話的兩端 
  25.   V8Inspector::Channel* m_channel; 
  26.   // 處理命令分發(fā)對(duì)象 
  27.   protocol::UberDispatcher m_dispatcher; 
  28.   // 處理某種命令的代理對(duì)象 
  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. }; 

下面看一下核心方法的具體實(shí)現(xiàn)。

創(chuàng)建 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 支持很多種命令,在創(chuàng)建 V8InspectorSessionImpl 對(duì)象時(shí),會(huì)注冊所有命令和處理該命令的處理器。我們一會(huì)單獨(dú)分析。

 接收請(qǐng)求

  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.   // 消息分發(fā) 
  16.   m_dispatcher.Dispatch(dispatchable).Run(); 
  17.  

接收消息后,在內(nèi)部通過 m_dispatcher.Dispatch 進(jìn)行分發(fā),這就好比我們在 Node.js 里收到請(qǐng)求后,根據(jù)路由分發(fā)一樣。具體的分發(fā)邏輯一會(huì)單獨(dú)分析。3. 響應(yīng)請(qǐng)求

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

具體的處理邏輯由 channel 實(shí)現(xiàn),channel 由 V8 的使用者實(shí)現(xiàn),比如 Node.js。

數(shù)據(jù)推送

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

除了一個(gè)請(qǐng)求對(duì)應(yīng)一個(gè)響應(yīng),V8 Inspector 還需要主動(dòng)推送的能力,具體處理邏輯也是由 channel 實(shí)現(xiàn)。從上面點(diǎn)分析可以看到 V8InspectorSessionImpl 的概念相當(dāng)于一個(gè)服務(wù)器,在啟動(dòng)的時(shí)候注冊了一系列路由,當(dāng)建立一個(gè)連接時(shí),就會(huì)創(chuàng)建一個(gè) Channel 對(duì)象表示。調(diào)用方可以通過 Channel 完成請(qǐng)求和接收響應(yīng)。結(jié)構(gòu)如下圖所示。

 V8Inspector

  1. class V8_EXPORT V8Inspector { 
  2.  public
  3.   // 靜態(tài)方法,用于創(chuàng)建 V8Inspector 
  4.   static std::unique_ptr<V8Inspector> create(v8::Isolate*, V8InspectorClient*); 
  5.   // 用于創(chuàng)建一個(gè) V8InspectorSession 
  6.   virtual std::unique_ptr<V8InspectorSession> connect(int contextGroupId, 
  7.                                                       Channel*, 
  8.                                                       StringView state) = 0; 
  9.  
  10. }; 

V8Inspector 是一個(gè)通信的總管,他不負(fù)責(zé)具體的通信,他只是負(fù)責(zé)管理通信者,Channel 才是負(fù)責(zé)通信的角色。下面看一下 V8Inspector 子類的實(shí)現(xiàn) 。

  1. class V8InspectorImpl : public V8Inspector { 
  2.  public
  3.   V8InspectorImpl(v8::Isolate*, V8InspectorClient*); 
  4.   // 創(chuàng)建一個(gè)會(huì)話 
  5.   std::unique_ptr<V8InspectorSession> connect(int contextGroupId, 
  6.                                               V8Inspector::Channel*, 
  7.                                               StringView state) override; 
  8.  
  9.  private: 
  10.   v8::Isolate* m_isolate; 
  11.   // 關(guān)聯(lián)的 V8InspectorClient 對(duì)象,V8InspectorClient 封裝了 V8Inspector,由調(diào)用方實(shí)現(xiàn) 
  12.   V8InspectorClient* m_client; 
  13.   // 保存所有的會(huì)話 
  14.   std::unordered_map<int, std::map<int, V8InspectorSessionImpl*>> m_sessions; 
  15.  
  16. }; 

V8InspectorImpl 提供了創(chuàng)建會(huì)話的方法并保存了所有創(chuàng)建的會(huì)話,看一下創(chuàng)建會(huì)話的邏輯。

  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 是創(chuàng)建了一個(gè) V8InspectorSessionImpl 對(duì)象,并通過 id 保存到 map中。結(jié)構(gòu)圖如下。

UberDispatcher

UberDispatcher 是一個(gè)命令分發(fā)器。

  1. class UberDispatcher { 
  2.  public
  3.   // 表示分發(fā)結(jié)果的對(duì)象 
  4.   class DispatchResult {}; 
  5.   // 分發(fā)處理函數(shù) 
  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.   // 查找命令對(duì)應(yīng)的處理器,Dispatch 中使用 
  14.   DomainDispatcher* findDispatcher(span<uint8_t> method); 
  15.   // 關(guān)聯(lián)的 channel 
  16.   FrontendChannel* const frontend_channel_; 
  17.   std::vector<std::pair<span<uint8_t>, span<uint8_t>>> redirects_; 
  18.   // 命令處理器隊(duì)列 
  19.   std::vector<std::pair<span<uint8_t>, std::unique_ptr<DomainDispatcher>>> 
  20.       dispatchers_; 
  21.  
  22. }; 

下面看一下注冊和分發(fā)的實(shí)現(xiàn)。

注冊

  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 就是在隊(duì)列里插入一個(gè)新的 domain 和 處理器組合。

分發(fā)命令

  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 查找對(duì)應(yīng)的處理器 
  12.   DomainDispatcher* dispatcher = FindByFirst(dispatchers_, domain); 
  13.   if (dispatcher) { 
  14.     // 交給 domain 對(duì)應(yīng)的處理器繼續(xù)處理 
  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 是一個(gè)命令一級(jí)分發(fā)器,因?yàn)槊钍?domain.cmd 的格式,UberDispatcher 是根據(jù) domain 進(jìn)行初步分發(fā),DomainDispatcher 則是找到具體命令對(duì)應(yīng)的處理器。

  1. class DomainDispatcher { 
  2.   // 分發(fā)邏輯,子類實(shí)現(xiàn) 
  3.   virtual std::function<void(const Dispatchable&)> Dispatch(span<uint8_t> command_name) = 0; 
  4.  
  5.   // 處理完后響應(yīng) 
  6.   void sendResponse(int call_id, 
  7.                     const DispatchResponse&, 
  8.                     std::unique_ptr<Serializable> result = nullptr); 
  9.  private: 
  10.   // 關(guān)聯(lián)的 channel 
  11.   FrontendChannel* frontend_channel_; 
  12.  
  13. }; 

DomainDispatcher 定義了命令分發(fā)和響應(yīng)的邏輯,不同的 domain 的分發(fā)邏輯會(huì)有不同的實(shí)現(xiàn),但是響應(yīng)邏輯是一樣的,所以基類實(shí)現(xiàn)了。

  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_ 返回響應(yīng)。接下來看子類的實(shí)現(xiàn),這里以 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.     // 分發(fā)的實(shí)現(xiàn) 
  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 支持的命令,下面分析一下命令的注冊和分發(fā)的處理邏輯。下面是 HeapProfiler 注冊 domain 和 處理器的邏輯(創(chuàng)建 V8InspectorSessionImpl 時(shí))

  1. // backend 是處理命令的具體對(duì)象,對(duì)于 HeapProfiler domain 是 V8HeapProfilerAgentImpl 
  2.  
  3. void Dispatcher::wire(UberDispatcher* uber, Backend* backend){    
  4.      
  5.  
  6.     // channel 是通信的對(duì)端 
  7.     auto dispatcher = std::make_unique<DomainDispatcherImpl>(uber->channel(), backend); 
  8.     // 注冊 domain 對(duì)應(yīng)的處理器 
  9.     uber->WireBackend(v8_crdtp::SpanFrom("HeapProfiler"), std::move(dispatcher)); 
  10.  

接下來看一下收到命令時(shí)具體的分發(fā)邏輯。

  1. std::function<void(const v8_crdtp::Dispatchable&)> DomainDispatcherImpl::Dispatch(v8_crdtp::span<uint8_t> command_name) { 
  2.   // 根據(jù)命令查找處理函數(shù) 
  3.   CallHandler handler = CommandByName(command_name); 
  4.   // 返回個(gè)函數(shù),外層執(zhí)行 
  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 的實(shí)現(xiàn)。

  1. void DomainDispatcherImpl::enable(const v8_crdtp::Dispatchable& dispatchable){ 
  2.     std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr(); 
  3.     // 調(diào)用 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 所指向的對(duì)象,這里是 V8HeapProfilerAgentImpl。下面是 V8HeapProfilerAgentImpl enable 的實(shí)現(xiàn)。

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

結(jié)構(gòu)圖如下。

V8HeapProfilerAgentImpl

剛才分析了 V8HeapProfilerAgentImpl 的 enable 函數(shù),這里以 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 定義了支持的事件,因?yàn)? Inspector 不僅可以處理調(diào)用方發(fā)送的命令,還可以主動(dòng)給調(diào)用方推送消息,這種推送就是以事件的方式觸發(fā)的。

  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 對(duì)象 
  14.   FrontendChannel* frontend_channel_; 
  15.  
  16. }; 

下面看一下 addHeapSnapshotChunk,這是獲取堆快照時(shí)用到的邏輯。

  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.  

最終觸發(fā)了 HeapProfiler.addHeapSnapshotChunk 事件。另外 V8HeapProfilerAgentImpl 繼承了 Backend 定義了支持哪些請(qǐng)求命令和 DomainDispatcherImpl 中的函數(shù)對(duì)應(yīng),比如獲取堆快照。

  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. }; 

結(jié)構(gòu)圖如下。

Node.js 對(duì) V8 Inspector 的封裝

接下來看一下 Node.js 中是如何使用 V8 Inspector 的,V8 Inspector 的使用方需要實(shí)現(xiàn) V8InspectorClient 和 V8Inspector::Channel。下面看一下 Node.js 的實(shí)現(xiàn)。

  1. class NodeInspectorClient : public V8InspectorClient { 
  2.  public
  3.   explicit NodeInspectorClient() { 
  4.     // 創(chuàng)建一個(gè) 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.                                                           // 收到數(shù)據(jù)后由 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,并且維護(hù)了多個(gè) channel。Node.js 的上層代碼可以通過 connectFrontend 連接到 V8 Inspector,并拿到 session_id,這個(gè)連接用 ChannelImpl 來實(shí)現(xiàn),來看一下 ChannelImpl 的實(shí)現(xiàn)。

  1. explicit ChannelImpl(const std::unique_ptr<V8Inspector>& inspector,  
  2.                      std::unique_ptr<InspectorSessionDelegate> delegate):  
  3.                      // delegate_ 負(fù)責(zé)處理 V8 發(fā)過來的數(shù)據(jù) 
  4.                      delegate_(std::move(delegate)) { 
  5.     session_ = inspector->connect(CONTEXT_GROUP_ID, this, StringView()); 
  6.  

ChannelImpl 是對(duì) V8InspectorSession 的封裝,通過 V8InspectorSession 實(shí)現(xiàn)發(fā)送命令,ChannelImpl 自己實(shí)現(xiàn)了接收響應(yīng)和接收 V8 推送數(shù)據(jù)的邏輯。了解了封裝 V8 Inspector 的能力后,通過一個(gè)例子看一下整個(gè)處理過程。通常我們通過以下方式和 V8 Inspector 通信。

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

我們從 connect 開始分析。

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

新建一個(gè) C++ 層的對(duì)象 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 初始化時(shí)會(huì)通過 agent->Connect 最終調(diào)用 Agent::Connect 建立到 V8 的通道,并傳入 JSBindingsSessionDelegate 作為數(shù)據(jù)處理的代理(channel 中使用)。最后返回一個(gè) SameThreadInspectorSession 對(duì)象保存到 session_ 中,后續(xù)就可以開始通信了,繼續(xù)看一下 通過 JS 層的 post 發(fā)送請(qǐng)求時(shí)的邏輯。

  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)); 

為每一個(gè)請(qǐng)求生成一個(gè) id,因?yàn)槭钱惒椒祷氐?,最后調(diào)用 dispatch 函數(shù)。

  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 中維護(hù)了一個(gè)sessionId,繼續(xù)調(diào)用 client->dispatchMessageFromFrontend, client 是 NodeInspectorClient 對(duì)象。

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

dispatchMessageFromFrontend 通過 sessionId 找到對(duì)應(yīng)的 channel。繼續(xù)調(diào) 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.     } 

最終調(diào)用 V8InspectorSessionImpl 的 session_->dispatchProtocolMessage(message),后面的內(nèi)容前面就講過了,就不再分析。最后看一下數(shù)據(jù)響應(yīng)或者推送時(shí)的邏輯。下面代碼來自 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.  

我們看到最終調(diào)用了 delegate_->SendMessageToFrontend, delegate 是 JSBindingsSessionDelegate對(duì)象。

  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.  

接著調(diào)用 connection_->OnMessage(argument),connection 是 JSBindingsConnection 對(duì)象。

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

C++ 層回調(diào) JS 層。

  1. [onMessageSymbol](message) { 
  2.     const parsed = JSONParse(message); 
  3.     try { 
  4.       // 通過有沒有 id 判斷是響應(yīng)還是推送 
  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.     } 

以上就完成了整個(gè)鏈路的分析。整體結(jié)構(gòu)圖如下。

總結(jié)

V8 Inspector 的設(shè)計(jì)和實(shí)現(xiàn)上比較復(fù)雜,對(duì)象間關(guān)系錯(cuò)綜復(fù)雜。因?yàn)?V8 提供調(diào)試和診斷 JS 的文檔似乎不多,也不是很完善,就是簡單描述一下命令是干啥的,很多時(shí)候不一定夠用,了解了具體實(shí)現(xiàn)后,后續(xù)碰到問題,可以自己去看具體實(shí)現(xiàn)。

 

責(zé)任編輯:姜華 來源: 編程雜技
相關(guān)推薦

2020-09-27 07:32:18

V8

2021-08-05 05:46:06

Node.jsInspector工具

2022-06-29 08:05:25

Volatile關(guān)鍵字類型

2023-10-04 00:04:00

C++extern

2024-03-15 09:44:17

WPFDispatcherUI線程

2019-09-04 14:14:52

Java編程數(shù)據(jù)

2024-07-18 10:12:04

2021-05-28 05:30:55

HandleV8代碼

2015-09-17 10:51:35

修改hostnameLinux

2016-08-31 15:50:50

PythonThreadLocal變量

2018-07-09 15:11:14

Java逃逸JVM

2020-12-16 09:47:01

JavaScript箭頭函數(shù)開發(fā)

2023-10-08 08:53:36

數(shù)據(jù)庫MySQL算法

2010-06-28 10:12:01

PHP匿名函數(shù)

2014-06-23 10:42:56

iOS開發(fā)UIScrollVie

2010-06-01 15:25:27

JavaCLASSPATH

2016-12-08 15:36:59

HashMap數(shù)據(jù)結(jié)構(gòu)hash函數(shù)

2020-07-21 08:26:08

SpringSecurity過濾器

2013-11-05 13:29:04

JavaScriptreplace

2013-06-20 10:25:56

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)