深入理解 V8 Inspector中幾個關鍵的角色
前言:本文介紹一下 V8 關于 Inspector 的實現,不過不會涉及到具體命令的實現,V8 Inspector 的命令非常多,了解了處理流程后,如果對某個命令感興趣的話,可以單獨去分析。
首先來看一下 V8 Inspector 中幾個關鍵的角色。
V8InspectorSession
- class V8_EXPORT V8InspectorSession {
- public:
- // 收到對端端消息,調用這個方法判斷是否可以分發
- static bool canDispatchMethod(StringView method);
- // 收到對端端消息,調用這個方法判斷分發
- virtual void dispatchProtocolMessage(StringView message) = 0;
- };
V8InspectorSession 是一個基類,本身實現了 canDispatchMethod 方法,由子類實現 dispatchProtocolMessage 方法。看一下 canDispatchMethod 的實現。
- bool V8InspectorSession::canDispatchMethod(StringView method) {
- return stringViewStartsWith(method,
- protocol::Runtime::Metainfo::commandPrefix) ||
- stringViewStartsWith(method,
- protocol::Debugger::Metainfo::commandPrefix) ||
- stringViewStartsWith(method,
- protocol::Profiler::Metainfo::commandPrefix) ||
- stringViewStartsWith(
- method, protocol::HeapProfiler::Metainfo::commandPrefix) ||
- stringViewStartsWith(method,
- protocol::Console::Metainfo::commandPrefix) ||
- stringViewStartsWith(method,
- protocol::Schema::Metainfo::commandPrefix);
- }
canDispatchMethod 決定了 V8 目前支持哪些命令。接著看一下 V8InspectorSession 子類的實現。
- class V8InspectorSessionImpl : public V8InspectorSession,
- public protocol::FrontendChannel {
- public:
- // 靜態方法,用于創建 V8InspectorSessionImpl
- static std::unique_ptr<V8InspectorSessionImpl> create(V8InspectorImpl*,
- int contextGroupId,
- int sessionId,
- V8Inspector::Channel*,
- StringView state);
- // 實現命令的分發
- void dispatchProtocolMessage(StringView message) override;
- // 支持哪些命令
- std::vector<std::unique_ptr<protocol::Schema::API::Domain>> supportedDomains() override;
- private:
- // 發送消息給對端
- void SendProtocolResponse(int callId, std::unique_ptr<protocol::Serializable> message) override;
- void SendProtocolNotification(std::unique_ptr<protocol::Serializable> message) override;
- // 會話 id
- int m_sessionId;
- // 關聯的 V8Inspector 對象
- V8InspectorImpl* m_inspector;
- // 關聯的 channel,channel 表示會話的兩端
- V8Inspector::Channel* m_channel;
- // 處理命令分發對象
- protocol::UberDispatcher m_dispatcher;
- // 處理某種命令的代理對象
- std::unique_ptr<V8RuntimeAgentImpl> m_runtimeAgent;
- std::unique_ptr<V8DebuggerAgentImpl> m_debuggerAgent;
- std::unique_ptr<V8HeapProfilerAgentImpl> m_heapProfilerAgent;
- std::unique_ptr<V8ProfilerAgentImpl> m_profilerAgent;
- std::unique_ptr<V8ConsoleAgentImpl> m_consoleAgent;
- std::unique_ptr<V8SchemaAgentImpl> m_schemaAgent;
- };
下面看一下核心方法的具體實現。
創建 V8InspectorSessionImpl
- V8InspectorSessionImpl::V8InspectorSessionImpl(V8InspectorImpl* inspector,
- int contextGroupId,
- int sessionId,
- V8Inspector::Channel* channel,
- StringView savedState)
- : m_contextGroupId(contextGroupId),
- m_sessionId(sessionId),
- m_inspector(inspector),
- m_channel(channel),
- m_customObjectFormatterEnabled(false),
- m_dispatcher(this),
- m_state(ParseState(savedState)),
- m_runtimeAgent(nullptr),
- m_debuggerAgent(nullptr),
- m_heapProfilerAgent(nullptr),
- m_profilerAgent(nullptr),
- m_consoleAgent(nullptr),
- m_schemaAgent(nullptr) {
- m_runtimeAgent.reset(new V8RuntimeAgentImpl(this, this, agentState(protocol::Runtime::Metainfo::domainName)));
- protocol::Runtime::Dispatcher::wire(&m_dispatcher, m_runtimeAgent.get());
- m_debuggerAgent.reset(new V8DebuggerAgentImpl(this, this, agentState(protocol::Debugger::Metainfo::domainName)));
- protocol::Debugger::Dispatcher::wire(&m_dispatcher, m_debuggerAgent.get());
- m_profilerAgent.reset(new V8ProfilerAgentImpl(this, this, agentState(protocol::Profiler::Metainfo::domainName)));
- protocol::Profiler::Dispatcher::wire(&m_dispatcher, m_profilerAgent.get());
- m_heapProfilerAgent.reset(new V8HeapProfilerAgentImpl(this, this, agentState(protocol::HeapProfiler::Metainfo::domainName)));
- protocol::HeapProfiler::Dispatcher::wire(&m_dispatcher,m_heapProfilerAgent.get());
- m_consoleAgent.reset(new V8ConsoleAgentImpl(this, this, agentState(protocol::Console::Metainfo::domainName)));
- protocol::Console::Dispatcher::wire(&m_dispatcher, m_consoleAgent.get());
- m_schemaAgent.reset(new V8SchemaAgentImpl(this, this, agentState(protocol::Schema::Metainfo::domainName)));
- protocol::Schema::Dispatcher::wire(&m_dispatcher, m_schemaAgent.get());
- }
V8 支持很多種命令,在創建 V8InspectorSessionImpl 對象時,會注冊所有命令和處理該命令的處理器。我們一會單獨分析。
接收請求
- void V8InspectorSessionImpl::dispatchProtocolMessage(StringView message) {
- using v8_crdtp::span;
- using v8_crdtp::SpanFrom;
- span<uint8_t> cbor;
- std::vector<uint8_t> converted_cbor;
- if (IsCBORMessage(message)) {
- use_binary_protocol_ = true;
- m_state->setBoolean("use_binary_protocol", true);
- cbor = span<uint8_t>(message.characters8(), message.length());
- } else {
- auto status = ConvertToCBOR(message, &converted_cbor);
- cbor = SpanFrom(converted_cbor);
- }
- v8_crdtp::Dispatchable dispatchable(cbor);
- // 消息分發
- m_dispatcher.Dispatch(dispatchable).Run();
- }
接收消息后,在內部通過 m_dispatcher.Dispatch 進行分發,這就好比我們在 Node.js 里收到請求后,根據路由分發一樣。具體的分發邏輯一會單獨分析。3. 響應請求
- void V8InspectorSessionImpl::SendProtocolResponse(
- int callId, std::unique_ptr<protocol::Serializable> message) {
- m_channel->sendResponse(callId, serializeForFrontend(std::move(message)));
- }
具體的處理邏輯由 channel 實現,channel 由 V8 的使用者實現,比如 Node.js。
數據推送
- void V8InspectorSessionImpl::SendProtocolNotification(
- std::unique_ptr<protocol::Serializable> message) {
- m_channel->sendNotification(serializeForFrontend(std::move(message)));
- }
除了一個請求對應一個響應,V8 Inspector 還需要主動推送的能力,具體處理邏輯也是由 channel 實現。從上面點分析可以看到 V8InspectorSessionImpl 的概念相當于一個服務器,在啟動的時候注冊了一系列路由,當建立一個連接時,就會創建一個 Channel 對象表示。調用方可以通過 Channel 完成請求和接收響應。結構如下圖所示。
V8Inspector
- class V8_EXPORT V8Inspector {
- public:
- // 靜態方法,用于創建 V8Inspector
- static std::unique_ptr<V8Inspector> create(v8::Isolate*, V8InspectorClient*);
- // 用于創建一個 V8InspectorSession
- virtual std::unique_ptr<V8InspectorSession> connect(int contextGroupId,
- Channel*,
- StringView state) = 0;
- };
V8Inspector 是一個通信的總管,他不負責具體的通信,他只是負責管理通信者,Channel 才是負責通信的角色。下面看一下 V8Inspector 子類的實現 。
- class V8InspectorImpl : public V8Inspector {
- public:
- V8InspectorImpl(v8::Isolate*, V8InspectorClient*);
- // 創建一個會話
- std::unique_ptr<V8InspectorSession> connect(int contextGroupId,
- V8Inspector::Channel*,
- StringView state) override;
- private:
- v8::Isolate* m_isolate;
- // 關聯的 V8InspectorClient 對象,V8InspectorClient 封裝了 V8Inspector,由調用方實現
- V8InspectorClient* m_client;
- // 保存所有的會話
- std::unordered_map<int, std::map<int, V8InspectorSessionImpl*>> m_sessions;
- };
V8InspectorImpl 提供了創建會話的方法并保存了所有創建的會話,看一下創建會話的邏輯。
- std::unique_ptr<V8InspectorSession> V8InspectorImpl::connect(int contextGroupId, V8Inspector::Channel* channel, StringView state) {
- int sessionId = ++m_lastSessionId;
- std::unique_ptr<V8InspectorSessionImpl> session = V8InspectorSessionImpl::create(this, contextGroupId, sessionId, channel, state);
- m_sessions[contextGroupId][sessionId] = session.get();
- return std::move(session);
- }
connect 是創建了一個 V8InspectorSessionImpl 對象,并通過 id 保存到 map中。結構圖如下。
UberDispatcher
UberDispatcher 是一個命令分發器。
- class UberDispatcher {
- public:
- // 表示分發結果的對象
- class DispatchResult {};
- // 分發處理函數
- DispatchResult Dispatch(const Dispatchable& dispatchable) const;
- // 注冊命令和處理器
- void WireBackend(span<uint8_t> domain,
- const std::vector<std::pair<span<uint8_t>, span<uint8_t>>>&,
- std::unique_ptr<DomainDispatcher> dispatcher);
- private:
- // 查找命令對應的處理器,Dispatch 中使用
- DomainDispatcher* findDispatcher(span<uint8_t> method);
- // 關聯的 channel
- FrontendChannel* const frontend_channel_;
- std::vector<std::pair<span<uint8_t>, span<uint8_t>>> redirects_;
- // 命令處理器隊列
- std::vector<std::pair<span<uint8_t>, std::unique_ptr<DomainDispatcher>>>
- dispatchers_;
- };
下面看一下注冊和分發的實現。
注冊
- void UberDispatcher::WireBackend(span<uint8_t> domain, std::unique_ptr<DomainDispatcher> dispatcher) {
- dispatchers_.insert(dispatchers_.end(), std::make_pair(domain, std::move(dispatcher))););
- }
WireBackend 就是在隊列里插入一個新的 domain 和 處理器組合。
分發命令
- UberDispatcher::DispatchResult UberDispatcher::Dispatch(
- const Dispatchable& dispatchable) const {
- span<uint8_t> method = FindByFirst(redirects_, dispatchable.Method(),
- /*default_value=*/dispatchable.Method());
- // 找到 . 的偏移,命令格式是 A.B
- size_t dot_idx = DotIdx(method);
- // 拿到 domain,即命令的第一部分
- span<uint8_t> domain = method.subspan(0, dot_idx);
- // 拿到命令
- span<uint8_t> command = method.subspan(dot_idx + 1);
- // 通過 domain 查找對應的處理器
- DomainDispatcher* dispatcher = FindByFirst(dispatchers_, domain);
- if (dispatcher) {
- // 交給 domain 對應的處理器繼續處理
- std::function<void(const Dispatchable&)> dispatched =
- dispatcher->Dispatch(command);
- if (dispatched) {
- return DispatchResult(
- true, [dispatchable, dispatched = std::move(dispatched)]() {
- dispatched(dispatchable);
- });
- }
- }
- }
DomainDispatcher
剛才分析了 UberDispatcher,UberDispatcher 是一個命令一級分發器,因為命令是 domain.cmd 的格式,UberDispatcher 是根據 domain 進行初步分發,DomainDispatcher 則是找到具體命令對應的處理器。
- class DomainDispatcher {
- // 分發邏輯,子類實現
- virtual std::function<void(const Dispatchable&)> Dispatch(span<uint8_t> command_name) = 0;
- // 處理完后響應
- void sendResponse(int call_id,
- const DispatchResponse&,
- std::unique_ptr<Serializable> result = nullptr);
- private:
- // 關聯的 channel
- FrontendChannel* frontend_channel_;
- };
DomainDispatcher 定義了命令分發和響應的邏輯,不同的 domain 的分發邏輯會有不同的實現,但是響應邏輯是一樣的,所以基類實現了。
- void DomainDispatcher::sendResponse(int call_id,
- const DispatchResponse& response,
- std::unique_ptr<Serializable> result) {
- std::unique_ptr<Serializable> serializable;
- if (response.IsError()) {
- serializable = CreateErrorResponse(call_id, response);
- } else {
- serializable = CreateResponse(call_id, std::move(result));
- }
- frontend_channel_->SendProtocolResponse(call_id, std::move(serializable));
- }
通過 frontend_channel_ 返回響應。接下來看子類的實現,這里以 HeapProfiler 為例。
- class DomainDispatcherImpl : public protocol::DomainDispatcher {
- public:
- DomainDispatcherImpl(FrontendChannel* frontendChannel, Backend* backend)
- : DomainDispatcher(frontendChannel)
- , m_backend(backend) {}
- ~DomainDispatcherImpl() override { }
- using CallHandler = void (DomainDispatcherImpl::*)(const v8_crdtp::Dispatchable& dispatchable);
- // 分發的實現
- std::function<void(const v8_crdtp::Dispatchable&)> Dispatch(v8_crdtp::span<uint8_t> command_name) override;
- // HeapProfiler 支持的命令
- void addInspectedHeapObject(const v8_crdtp::Dispatchable& dispatchable);
- void collectGarbage(const v8_crdtp::Dispatchable& dispatchable);
- void disable(const v8_crdtp::Dispatchable& dispatchable);
- void enable(const v8_crdtp::Dispatchable& dispatchable);
- void getHeapObjectId(const v8_crdtp::Dispatchable& dispatchable);
- void getObjectByHeapObjectId(const v8_crdtp::Dispatchable& dispatchable);
- void getSamplingProfile(const v8_crdtp::Dispatchable& dispatchable);
- void startSampling(const v8_crdtp::Dispatchable& dispatchable);
- void startTrackingHeapObjects(const v8_crdtp::Dispatchable& dispatchable);
- void stopSampling(const v8_crdtp::Dispatchable& dispatchable);
- void stopTrackingHeapObjects(const v8_crdtp::Dispatchable& dispatchable);
- void takeHeapSnapshot(const v8_crdtp::Dispatchable& dispatchable);
- protected:
- Backend* m_backend;
- };
DomainDispatcherImpl 定義了 HeapProfiler 支持的命令,下面分析一下命令的注冊和分發的處理邏輯。下面是 HeapProfiler 注冊 domain 和 處理器的邏輯(創建 V8InspectorSessionImpl 時)
- // backend 是處理命令的具體對象,對于 HeapProfiler domain 是 V8HeapProfilerAgentImpl
- void Dispatcher::wire(UberDispatcher* uber, Backend* backend){
- // channel 是通信的對端
- auto dispatcher = std::make_unique<DomainDispatcherImpl>(uber->channel(), backend);
- // 注冊 domain 對應的處理器
- uber->WireBackend(v8_crdtp::SpanFrom("HeapProfiler"), std::move(dispatcher));
- }
接下來看一下收到命令時具體的分發邏輯。
- std::function<void(const v8_crdtp::Dispatchable&)> DomainDispatcherImpl::Dispatch(v8_crdtp::span<uint8_t> command_name) {
- // 根據命令查找處理函數
- CallHandler handler = CommandByName(command_name);
- // 返回個函數,外層執行
- return [this, handler](const v8_crdtp::Dispatchable& dispatchable) {
- (this->*handler)(dispatchable);
- };
- }
看一下查找的邏輯。
- DomainDispatcherImpl::CallHandler CommandByName(v8_crdtp::span<uint8_t> command_name) {
- static auto* commands = [](){
- auto* commands = new std::vector<std::pair<v8_crdtp::span<uint8_t>, DomainDispatcherImpl::CallHandler>>{
- // 太多,不一一列舉
- {
- v8_crdtp::SpanFrom("enable"),
- &DomainDispatcherImpl::enable
- },
- };
- return commands;
- }();
- return v8_crdtp::FindByFirst<DomainDispatcherImpl::CallHandler>(*commands, command_name, nullptr);
- }
再看一下 DomainDispatcherImpl::enable 的實現。
- void DomainDispatcherImpl::enable(const v8_crdtp::Dispatchable& dispatchable){
- std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr();
- // 調用 m_backend 也就是 V8HeapProfilerAgentImpl 的 enable
- DispatchResponse response = m_backend->enable();
- if (response.IsFallThrough()) {
- channel()->FallThrough(dispatchable.CallId(), v8_crdtp::SpanFrom("HeapProfiler.enable"), dispatchable.Serialized());
- return;
- }
- if (weak->get())
- weak->get()->sendResponse(dispatchable.CallId(), response);
- return;
- }
DomainDispatcherImpl 只是封裝,具體的命令處理交給 m_backend 所指向的對象,這里是 V8HeapProfilerAgentImpl。下面是 V8HeapProfilerAgentImpl enable 的實現。
- Response V8HeapProfilerAgentImpl::enable() {
- m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, true);
- return Response::Success();
- }
結構圖如下。
V8HeapProfilerAgentImpl
剛才分析了 V8HeapProfilerAgentImpl 的 enable 函數,這里以 V8HeapProfilerAgentImpl 為例子分析一下命令處理器類的邏輯。
- class V8HeapProfilerAgentImpl : public protocol::HeapProfiler::Backend {
- public:
- V8HeapProfilerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*,
- protocol::DictionaryValue* state);
- private:
- V8InspectorSessionImpl* m_session;
- v8::Isolate* m_isolate;
- // protocol::HeapProfiler::Frontend 定義了支持哪些事件
- protocol::HeapProfiler::Frontend m_frontend;
- protocol::DictionaryValue* m_state;
- };
V8HeapProfilerAgentImpl 通過 protocol::HeapProfiler::Frontend 定義了支持的事件,因為 Inspector 不僅可以處理調用方發送的命令,還可以主動給調用方推送消息,這種推送就是以事件的方式觸發的。
- class Frontend {
- public:
- explicit Frontend(FrontendChannel* frontend_channel) : frontend_channel_(frontend_channel) {}
- void addHeapSnapshotChunk(const String& chunk);
- void heapStatsUpdate(std::unique_ptr<protocol::Array<int>> statsUpdate);
- void lastSeenObjectId(int lastSeenObjectId, double timestamp);
- void reportHeapSnapshotProgress(int done, int total, Maybe<bool> finished = Maybe<bool>());
- void resetProfiles();
- void flush();
- void sendRawNotification(std::unique_ptr<Serializable>);
- private:
- // 指向 V8InspectorSessionImpl 對象
- FrontendChannel* frontend_channel_;
- };
下面看一下 addHeapSnapshotChunk,這是獲取堆快照時用到的邏輯。
- void Frontend::addHeapSnapshotChunk(const String& chunk){
- v8_crdtp::ObjectSerializer serializer;
- serializer.AddField(v8_crdtp::MakeSpan("chunk"), chunk);
- frontend_channel_->SendProtocolNotification(v8_crdtp::CreateNotification("HeapProfiler.addHeapSnapshotChunk", serializer.Finish()));
- }
最終觸發了 HeapProfiler.addHeapSnapshotChunk 事件。另外 V8HeapProfilerAgentImpl 繼承了 Backend 定義了支持哪些請求命令和 DomainDispatcherImpl 中的函數對應,比如獲取堆快照。
- class Backend {
- public:
- virtual ~Backend() { }
- // 不一一列舉
- virtual DispatchResponse takeHeapSnapshot(Maybe<bool> in_reportProgress, Maybe<bool> in_treatGlobalObjectsAsRoots, Maybe<bool> in_captureNumericValue) = 0;
- };
結構圖如下。
Node.js 對 V8 Inspector 的封裝
接下來看一下 Node.js 中是如何使用 V8 Inspector 的,V8 Inspector 的使用方需要實現 V8InspectorClient 和 V8Inspector::Channel。下面看一下 Node.js 的實現。
- class NodeInspectorClient : public V8InspectorClient {
- public:
- explicit NodeInspectorClient() {
- // 創建一個 V8Inspector
- client_ = V8Inspector::create(env->isolate(), this);
- }
- int connectFrontend(std::unique_ptr<InspectorSessionDelegate> delegate,
- bool prevent_shutdown) {
- int session_id = next_session_id_++;
- channels_[session_id] = std::make_unique<ChannelImpl>(env_,
- client_,
- getWorkerManager(),
- // 收到數據后由 delegate 處理
- std::move(delegate),
- getThreadHandle(),
- prevent_shutdown);
- return session_id;
- }
- std::unique_ptr<V8Inspector> client_;
- std::unordered_map<int, std::unique_ptr<ChannelImpl>> channels_;
- };
NodeInspectorClient 封裝了 V8Inspector,并且維護了多個 channel。Node.js 的上層代碼可以通過 connectFrontend 連接到 V8 Inspector,并拿到 session_id,這個連接用 ChannelImpl 來實現,來看一下 ChannelImpl 的實現。
- explicit ChannelImpl(const std::unique_ptr<V8Inspector>& inspector,
- std::unique_ptr<InspectorSessionDelegate> delegate):
- // delegate_ 負責處理 V8 發過來的數據
- delegate_(std::move(delegate)) {
- session_ = inspector->connect(CONTEXT_GROUP_ID, this, StringView());
- }
ChannelImpl 是對 V8InspectorSession 的封裝,通過 V8InspectorSession 實現發送命令,ChannelImpl 自己實現了接收響應和接收 V8 推送數據的邏輯。了解了封裝 V8 Inspector 的能力后,通過一個例子看一下整個處理過程。通常我們通過以下方式和 V8 Inspector 通信。
- const { Session } = require('inspector');
- new Session().connect();
我們從 connect 開始分析。
- connect() {
- this[connectionSymbol] = new Connection((message) => this[onMessageSymbol](message));
- }
新建一個 C++ 層的對象 JSBindingsConnection。
- JSBindingsConnection(Environment* env,
- Local<Object> wrap,
- Local<Function> callback)
- : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING),
- callback_(env->isolate(), callback) {
- Agent* inspector = env->inspector_agent();
- session_ = LocalConnection::Connect(inspector, std::make_unique<JSBindingsSessionDelegate>(env, this));}static std::unique_ptr<InspectorSession> Connect(
- Agent* inspector, std::unique_ptr<InspectorSessionDelegate> delegate) {
- return inspector->Connect(std::move(delegate), false);
- }
- std::unique_ptr<InspectorSession> Agent::Connect(
- std::unique_ptr<InspectorSessionDelegate> delegate,
- bool prevent_shutdown) {
- int session_id = client_->connectFrontend(std::move(delegate),
- prevent_shutdown);
- return std::unique_ptr<InspectorSession>(
- new SameThreadInspectorSession(session_id, client_));
- }
JSBindingsConnection 初始化時會通過 agent->Connect 最終調用 Agent::Connect 建立到 V8 的通道,并傳入 JSBindingsSessionDelegate 作為數據處理的代理(channel 中使用)。最后返回一個 SameThreadInspectorSession 對象保存到 session_ 中,后續就可以開始通信了,繼續看一下 通過 JS 層的 post 發送請求時的邏輯。
- post(method, params, callback) {
- const id = this[nextIdSymbol]++;
- const message = { id, method };
- if (params) {
- message.params = params;
- }
- if (callback) {
- this[messageCallbacksSymbol].set(id, callback);
- }
- this[connectionSymbol].dispatch(JSONStringify(message));
- }
為每一個請求生成一個 id,因為是異步返回的,最后調用 dispatch 函數。
- static void Dispatch(const FunctionCallbackInfo<Value>& info) {
- Environment* env = Environment::GetCurrent(info);
- JSBindingsConnection* session;
- ASSIGN_OR_RETURN_UNWRAP(&session, info.Holder());
- if (session->session_) {
- session->session_->Dispatch(
- ToProtocolString(env->isolate(), info[0])->string());
- }
- }
看一下 SameThreadInspectorSession::Dispatch (即session->session_->Dispatch)。
- void SameThreadInspectorSession::Dispatch(
- const v8_inspector::StringView& message) {
- auto client = client_.lock();
- if (client)
- client->dispatchMessageFromFrontend(session_id_, message);
- }
SameThreadInspectorSession 中維護了一個sessionId,繼續調用 client->dispatchMessageFromFrontend, client 是 NodeInspectorClient 對象。
- void dispatchMessageFromFrontend(int session_id, const StringView& message) {
- channels_[session_id]->dispatchProtocolMessage(message);
- }
dispatchMessageFromFrontend 通過 sessionId 找到對應的 channel。繼續調 channel 的 dispatchProtocolMessage。
- void dispatchProtocolMessage(const StringView& message) {
- std::string raw_message = protocol::StringUtil::StringViewToUtf8(message);
- std::unique_ptr<protocol::DictionaryValue> value =
- protocol::DictionaryValue::cast(protocol::StringUtil::parseMessage(
- raw_message, false));
- int call_id;
- std::string method;
- node_dispatcher_->parseCommand(value.get(), &call_id, &method);
- if (v8_inspector::V8InspectorSession::canDispatchMethod(
- Utf8ToStringView(method)->string())) {
- session_->dispatchProtocolMessage(message);
- }
- }
最終調用 V8InspectorSessionImpl 的 session_->dispatchProtocolMessage(message),后面的內容前面就講過了,就不再分析。最后看一下數據響應或者推送時的邏輯。下面代碼來自 ChannelImpl。
- void sendResponse(
- int callId,
- std::unique_ptr<v8_inspector::StringBuffer> message) override {
- sendMessageToFrontend(message->string());
- }
- void sendNotification(
- std::unique_ptr<v8_inspector::StringBuffer> message) override {
- sendMessageToFrontend(message->string());
- }
- void sendMessageToFrontend(const StringView& message) {
- delegate_->SendMessageToFrontend(message);
- }
我們看到最終調用了 delegate_->SendMessageToFrontend, delegate 是 JSBindingsSessionDelegate對象。
- void SendMessageToFrontend(const v8_inspector::StringView& message)
- override {
- Isolate* isolate = env_->isolate();
- HandleScope handle_scope(isolate);
- Context::Scope context_scope(env_->context());
- MaybeLocal<String> v8string = String::NewFromTwoByte(isolate, message.characters16(),
- NewStringType::kNormal, message.length());
- Local<Value> argument = v8string.ToLocalChecked().As<Value>();
- connection_->OnMessage(argument);
- }
接著調用 connection_->OnMessage(argument),connection 是 JSBindingsConnection 對象。
- void OnMessage(Local<Value> value) {
- MakeCallback(callback_.Get(env()->isolate()), 1, &value);
- }
C++ 層回調 JS 層。
- [onMessageSymbol](message) {
- const parsed = JSONParse(message);
- try {
- // 通過有沒有 id 判斷是響應還是推送
- if (parsed.id) {
- const callback = this[messageCallbacksSymbol].get(parsed.id);
- this[messageCallbacksSymbol].delete(parsed.id);
- if (callback) {
- if (parsed.error) {
- return callback(new ERR_INSPECTOR_COMMAND(parsed.error.code,
- parsed.error.message));
- }
- callback(null, parsed.result);
- }
- } else {
- this.emit(parsed.method, parsed);
- this.emit('inspectorNotification', parsed);
- }
- } catch (error) {
- process.emitWarning(error);
- }
- }
以上就完成了整個鏈路的分析。整體結構圖如下。
總結
V8 Inspector 的設計和實現上比較復雜,對象間關系錯綜復雜。因為 V8 提供調試和診斷 JS 的文檔似乎不多,也不是很完善,就是簡單描述一下命令是干啥的,很多時候不一定夠用,了解了具體實現后,后續碰到問題,可以自己去看具體實現。