Skip to content

Commit 73da163

Browse files
committed
feat(inspector): serve multiple DevTools clients at once
Each connection now gets its own V8InspectorSession on the main isolate and on every worker, and sees only replies to its own commands, as with Chrome and Node. InspectorSessions keeps the per-connection sessions for one isolate; connect, disconnect and messages share one queue, so a client's session exists before its first message and outlives its last. A departing client's session is destroyed, which disables its agents: a pause ends only if no other client still has the debugger enabled. A session dispatching when its client leaves (the pause loop can run under its own Runtime.evaluate) gets Debugger.disable at once and is destroyed when that dispatch returns. Per-client state: Target auto-attach and announced workers, IO streams, and tracing (one owner at a time). @nativescript/core's JS domains are global, so their events go to every client and a <Domain>.disable only reaches the handler once no other client has the domain enabled. The server no longer closes the previous client. It drops a message read just before a write error closed its connection, closes a client more than 256 MB behind on writes, and no longer logs connection resets and broken pipes. Also fix a trap in libdispatch when a message dispatched by the drain pauses (e.g. evaluating `debugger` in the console): the drain held messageLoopQueue_ while dispatching and the pause loop dispatch_sync'd onto it. The drain now only reads the pause-loop flag under that queue. This replaces the single-client sync sentinel, session rebinding and frontend generations.
1 parent 600f903 commit 73da163

9 files changed

Lines changed: 700 additions & 604 deletions

‎NativeScript/inspector/InspectorServer.h‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@ class InspectorServer {
1818
// process-unique connection id: onClientConnected hands out its sender,
1919
// and onClientDisconnected fires once with the same id when the
2020
// connection closes, after which that sender drops every message.
21-
// One client at a time: accepting a client closes the previous one, and
22-
// that close reports onClientDisconnected before the new onClientConnected.
23-
// A client that closed itself (EOF, read or write error) reports from its
24-
// own queue, which can interleave with a new onClientConnected. A message
25-
// the previous client had already read may reach onMessage after the
26-
// takeover, so callers must check the connection id.
21+
// Any number of clients may be connected at once. For one connection the
22+
// callbacks are ordered: onClientConnected returns before its first
23+
// onMessage, and onClientDisconnected comes after its last. Callbacks for
24+
// different connections run concurrently.
2725
static in_port_t Init(
2826
std::function<void(uint64_t connectionId, Sender sender)>
2927
onClientConnected,

‎NativeScript/inspector/InspectorServer.mm‎

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,29 @@
1212

1313
std::atomic<uint64_t> gLastConnectionId{0};
1414

15+
// A client this far behind is assumed gone (e.g. a half-open socket whose
16+
// peer vanished without a FIN): every client receives broadcast events, so
17+
// its unsent output would otherwise grow without bound. Large enough for a
18+
// heap snapshot streamed over a slow link.
19+
constexpr size_t kMaxPendingWriteBytes = 256 * 1024 * 1024;
20+
1521
struct Connection {
1622
uint64_t id;
1723
dispatch_queue_t queue;
1824
dispatch_io_t channel;
25+
// Only changes on `queue`.
1926
std::atomic<bool> open{true};
27+
std::atomic<size_t> pendingWriteBytes{0};
2028
std::function<void(uint64_t)> onDisconnected;
2129
std::function<void(uint64_t, const std::string&)> onMessage;
2230
};
2331

32+
// The peer went away or we closed the channel ourselves (ECANCELED: an
33+
// operation was still queued at close time); routine, not worth a log line.
34+
bool IsDisconnectError(int error) {
35+
return error == ECANCELED || error == ECONNRESET || error == EPIPE;
36+
}
37+
2438
void CloseConnection(const std::shared_ptr<Connection>& connection) {
2539
if (!connection->open.exchange(false)) {
2640
return;
@@ -46,7 +60,7 @@ void ReadExactly(std::shared_ptr<Connection> connection, size_t length,
4660
return;
4761
}
4862
if (error != 0 || dispatch_data_get_size(received) < length) {
49-
if (error != 0 && error != ECANCELED) {
63+
if (error != 0 && !IsDisconnectError(error)) {
5064
NSLog(@"InspectorServer read error: %s", strerror(error));
5165
}
5266
CloseConnection(connection);
@@ -70,6 +84,11 @@ void ReadNextMessage(std::shared_ptr<Connection> connection) {
7084
ReadExactly(connection, length, ^(dispatch_data_t body) {
7185
NSString* payload = [[NSString alloc] initWithData:(NSData*)body
7286
encoding:NSUTF16LittleEndianStringEncoding];
87+
// A write error may have closed the connection after this read
88+
// completed; onMessage must never follow onDisconnected.
89+
if (!connection->open.load()) {
90+
return;
91+
}
7392
const char* utf8 = [payload UTF8String];
7493
if (utf8 != nullptr) {
7594
connection->onMessage(connection->id, utf8);
@@ -99,19 +118,31 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
99118
range:NSMakeRange(0, str.length)
100119
remainingRange:NULL];
101120

102-
dispatch_data_t data =
103-
dispatch_data_create(buffer, length + sizeof(uint32_t), connection->queue, ^{
104-
free(buffer);
105-
});
121+
size_t size = length + sizeof(uint32_t);
122+
dispatch_data_t data = dispatch_data_create(buffer, size, connection->queue, ^{
123+
free(buffer);
124+
});
125+
126+
if (connection->pendingWriteBytes.fetch_add(size) + size > kMaxPendingWriteBytes) {
127+
NSLog(@"InspectorServer: closing a client that stopped reading");
128+
// Closed on its own queue to keep onDisconnected ordered after onMessage.
129+
dispatch_async(connection->queue, ^{
130+
CloseConnection(connection);
131+
});
132+
return;
133+
}
106134

107135
dispatch_io_write(connection->channel, 0, data, connection->queue,
108136
^(bool done, dispatch_data_t data, int error) {
109-
// ECANCELED: the write was still queued when the
110-
// connection closed.
111-
if (error == 0 || error == ECANCELED) {
137+
if (done) {
138+
connection->pendingWriteBytes.fetch_sub(size);
139+
}
140+
if (error == 0) {
112141
return;
113142
}
114-
NSLog(@"InspectorServer::Send error: %s", strerror(error));
143+
if (!IsDisconnectError(error)) {
144+
NSLog(@"InspectorServer::Send error: %s", strerror(error));
145+
}
115146
CloseConnection(connection);
116147
});
117148
}
@@ -145,10 +176,6 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
145176
assert(false);
146177
}
147178

148-
// Only touched by the accept handler, which libdispatch never runs
149-
// concurrently with itself.
150-
__block std::weak_ptr<Connection> activeConnection;
151-
152179
// Set up the dispatch source that will alert us to new incoming connections
153180
dispatch_queue_t q = dispatch_queue_create("server_queue", DISPATCH_QUEUE_CONCURRENT);
154181
dispatch_source_t acceptSource =
@@ -190,13 +217,8 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) {
190217
continue;
191218
}
192219

193-
// The accept handler is serial, so back-to-back accepts take over in
194-
// order and the newest client stays active.
195-
std::shared_ptr<Connection> previous = activeConnection.lock();
196-
activeConnection = connection;
197-
if (previous != nullptr) {
198-
CloseConnection(previous);
199-
}
220+
// Reads start only after this returns, so the client's first message
221+
// cannot overtake its own connect.
200222
onClientConnected(connection->id,
201223
[connection](const std::string& message) { Send(connection, message); });
202224

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#ifndef InspectorSessions_h
2+
#define InspectorSessions_h
3+
4+
#include <cstdint>
5+
#include <functional>
6+
#include <map>
7+
#include <memory>
8+
#include <mutex>
9+
#include <string>
10+
#include <vector>
11+
12+
#include "include/v8-inspector.h"
13+
14+
namespace v8_inspector {
15+
16+
// One V8InspectorSession per connected frontend, all on one isolate and
17+
// context group. Each session's output goes only to its own frontend.
18+
//
19+
// Except for RequestPause and ClearPauseRequests, call only from the one
20+
// thread at a time that feeds the isolate's inspector messages (its message
21+
// drain or pause loop), or from an interrupt on the thread running its JS.
22+
// The methods take the isolate's Locker themselves (v8::Locker is reentrant).
23+
class InspectorSessions {
24+
public:
25+
using Output =
26+
std::function<void(uint64_t connectionId, const std::string& message)>;
27+
28+
InspectorSessions(v8::Isolate* isolate, int contextGroupId, Output output);
29+
~InspectorSessions();
30+
31+
// Creates the frontend's session unless it already has one.
32+
void Connect(V8Inspector* inspector, uint64_t connectionId);
33+
34+
// Ignored for a frontend without a session or one being closed.
35+
void Dispatch(uint64_t connectionId, const std::string& message);
36+
37+
// Destroys the frontend's session. Its destructor disables its agents, so
38+
// a pause ends only if no other frontend still has the debugger enabled.
39+
// A session cannot be destroyed while it is dispatching (a pause loop can
40+
// sit under its dispatchProtocolMessage); it then gets Debugger.disable
41+
// right away and is destroyed once that dispatch returns.
42+
void Disconnect(uint64_t connectionId);
43+
44+
// Destroys every session. Never while any of them is dispatching.
45+
void DisconnectAll();
46+
47+
bool Has(uint64_t connectionId) const;
48+
49+
// Any thread. Records that the frontend asked to pause; TakePauseRequests,
50+
// called from an isolate interrupt, schedules the pause in its session.
51+
void RequestPause(uint64_t connectionId);
52+
void TakePauseRequests();
53+
// Any thread. Called when a pause starts, so a request whose interrupt is
54+
// still pending cannot pause again after the resume.
55+
void ClearPauseRequests();
56+
57+
void SchedulePauseInAll();
58+
59+
private:
60+
class Channel;
61+
struct Session {
62+
std::unique_ptr<Channel> channel;
63+
std::unique_ptr<V8InspectorSession> session;
64+
int dispatchDepth = 0;
65+
bool closing = false;
66+
};
67+
68+
void DispatchTo(Session* session, const std::string& message);
69+
void Destroy(uint64_t connectionId);
70+
71+
v8::Isolate* isolate_;
72+
int contextGroupId_;
73+
Output output_;
74+
std::map<uint64_t, std::unique_ptr<Session>> sessions_;
75+
76+
std::mutex pauseRequestsMutex_;
77+
std::vector<uint64_t> pauseRequests_; // guarded by pauseRequestsMutex_
78+
};
79+
80+
} // namespace v8_inspector
81+
82+
#endif /* InspectorSessions_h */
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
#include "InspectorSessions.h"
2+
3+
#include "include/v8-locker.h"
4+
#include "utils.h"
5+
6+
using namespace v8;
7+
8+
namespace v8_inspector {
9+
10+
namespace {
11+
StringView Make8BitStringView(const std::string& value) {
12+
return StringView(reinterpret_cast<const uint8_t*>(value.data()), value.size());
13+
}
14+
15+
constexpr const char* kDisableDebugger = "{\"id\":0,\"method\":\"Debugger.disable\"}";
16+
} // namespace
17+
18+
class InspectorSessions::Channel final : public V8Inspector::Channel {
19+
public:
20+
Channel(const Output& output, uint64_t connectionId)
21+
: output_(output), connectionId_(connectionId) {}
22+
23+
void sendResponse(int callId, std::unique_ptr<StringBuffer> message) override {
24+
output_(connectionId_, ToStdString(message->string()));
25+
}
26+
27+
void sendNotification(std::unique_ptr<StringBuffer> message) override {
28+
output_(connectionId_, ToStdString(message->string()));
29+
}
30+
31+
void flushProtocolNotifications() override {}
32+
33+
private:
34+
const Output& output_;
35+
uint64_t connectionId_;
36+
};
37+
38+
InspectorSessions::InspectorSessions(Isolate* isolate, int contextGroupId, Output output)
39+
: isolate_(isolate), contextGroupId_(contextGroupId), output_(std::move(output)) {}
40+
41+
InspectorSessions::~InspectorSessions() { this->DisconnectAll(); }
42+
43+
void InspectorSessions::Connect(V8Inspector* inspector, uint64_t connectionId) {
44+
if (sessions_.count(connectionId) != 0) {
45+
return;
46+
}
47+
48+
Locker locker(isolate_);
49+
Isolate::Scope isolate_scope(isolate_);
50+
HandleScope handle_scope(isolate_);
51+
52+
auto entry = std::make_unique<Session>();
53+
entry->channel = std::make_unique<Channel>(output_, connectionId);
54+
entry->session =
55+
inspector->connect(contextGroupId_, entry->channel.get(), {}, V8Inspector::kFullyTrusted);
56+
sessions_.emplace(connectionId, std::move(entry));
57+
}
58+
59+
void InspectorSessions::Dispatch(uint64_t connectionId, const std::string& message) {
60+
auto it = sessions_.find(connectionId);
61+
if (it == sessions_.end() || it->second->closing) {
62+
return;
63+
}
64+
65+
Session* session = it->second.get();
66+
this->DispatchTo(session, message);
67+
if (session->closing && session->dispatchDepth == 0) {
68+
this->Destroy(connectionId);
69+
}
70+
}
71+
72+
void InspectorSessions::DispatchTo(Session* session, const std::string& message) {
73+
Locker locker(isolate_);
74+
Isolate::Scope isolate_scope(isolate_);
75+
HandleScope handle_scope(isolate_);
76+
77+
// Destroy never runs while this is above zero, so `session` stays valid
78+
// across the call even if the frontend disconnects inside it.
79+
session->dispatchDepth++;
80+
session->session->dispatchProtocolMessage(Make8BitStringView(message));
81+
session->dispatchDepth--;
82+
}
83+
84+
void InspectorSessions::Disconnect(uint64_t connectionId) {
85+
auto it = sessions_.find(connectionId);
86+
if (it == sessions_.end()) {
87+
return;
88+
}
89+
90+
Session* session = it->second.get();
91+
if (session->dispatchDepth == 0) {
92+
this->Destroy(connectionId);
93+
return;
94+
}
95+
96+
if (!session->closing) {
97+
session->closing = true;
98+
this->DispatchTo(session, kDisableDebugger);
99+
}
100+
}
101+
102+
void InspectorSessions::DisconnectAll() {
103+
while (!sessions_.empty()) {
104+
this->Destroy(sessions_.begin()->first);
105+
}
106+
}
107+
108+
bool InspectorSessions::Has(uint64_t connectionId) const {
109+
auto it = sessions_.find(connectionId);
110+
return it != sessions_.end() && !it->second->closing;
111+
}
112+
113+
void InspectorSessions::Destroy(uint64_t connectionId) {
114+
auto node = sessions_.extract(connectionId);
115+
if (node.empty()) {
116+
return;
117+
}
118+
119+
Locker locker(isolate_);
120+
Isolate::Scope isolate_scope(isolate_);
121+
HandleScope handle_scope(isolate_);
122+
// The session uses its channel until its destructor returns.
123+
node.mapped()->session.reset();
124+
node.mapped()->channel.reset();
125+
}
126+
127+
void InspectorSessions::RequestPause(uint64_t connectionId) {
128+
std::lock_guard<std::mutex> lock(pauseRequestsMutex_);
129+
pauseRequests_.push_back(connectionId);
130+
}
131+
132+
void InspectorSessions::TakePauseRequests() {
133+
std::vector<uint64_t> requests;
134+
{
135+
std::lock_guard<std::mutex> lock(pauseRequestsMutex_);
136+
requests.swap(pauseRequests_);
137+
}
138+
139+
for (uint64_t connectionId : requests) {
140+
auto it = sessions_.find(connectionId);
141+
if (it != sessions_.end() && !it->second->closing) {
142+
it->second->session->schedulePauseOnNextStatement({}, {});
143+
}
144+
}
145+
}
146+
147+
void InspectorSessions::ClearPauseRequests() {
148+
std::lock_guard<std::mutex> lock(pauseRequestsMutex_);
149+
pauseRequests_.clear();
150+
}
151+
152+
void InspectorSessions::SchedulePauseInAll() {
153+
for (auto& entry : sessions_) {
154+
if (!entry.second->closing) {
155+
entry.second->session->schedulePauseOnNextStatement({}, {});
156+
}
157+
}
158+
}
159+
160+
} // namespace v8_inspector

0 commit comments

Comments
 (0)