Repository navigation
feat(inspector): serve multiple DevTools clients at once #526
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| #ifndef InspectorQueue_h | ||
| #define InspectorQueue_h | ||
|
|
||
| #include <dispatch/dispatch.h> | ||
|
|
||
| #include <cstdint> | ||
| #include <deque> | ||
| #include <mutex> | ||
| #include <string> | ||
| #include <vector> | ||
|
|
||
| namespace v8_inspector { | ||
|
|
||
| // Frontend messages waiting for an isolate, in arrival order. Push from any | ||
| // thread; take only while holding the isolate's Locker, so that a pause loop | ||
| // on another thread (which holds it throughout) and the isolate's own drain | ||
| // never split a frontend's messages between them. | ||
| class InspectorQueue { | ||
| public: | ||
| struct Item { | ||
| enum class Kind { kConnect, kDisconnect, kMessage }; | ||
| uint64_t connectionId; | ||
| Kind kind; | ||
| std::string method; | ||
| std::string message; | ||
| // See Interrupts and IsBarrier. | ||
| bool interrupting = false; | ||
| bool barrier = false; | ||
| }; | ||
|
|
||
| InspectorQueue(); | ||
|
|
||
| // Whether a command runs no JS, so it may be dispatched from an interrupt | ||
| // in the middle of the isolate's JS and ahead of the frontend's earlier | ||
| // commands. Chromium's list (ShouldInterruptForMethod), without the domains | ||
| // V8 does not implement and without Runtime.terminateExecution, which would | ||
| // unwind the app's own frames. | ||
| static bool Interrupts(const std::string& method); | ||
|
|
||
| // Whether an interrupting command must stay behind this one: it creates or | ||
| // destroys what the command acts on. | ||
| static bool IsBarrier(const std::string& method); | ||
|
|
||
| static Item Message(uint64_t connectionId, const std::string& method, | ||
| std::string message); | ||
|
|
||
| void Push(Item item); | ||
|
|
||
| // Takes the oldest item. Returns false when there is none. | ||
| bool Take(Item& item); | ||
|
|
||
| // Takes the interrupting commands that no barrier of their frontend | ||
| // precedes. | ||
| std::vector<Item> TakeInterrupting(); | ||
|
|
||
| // Waits briefly for a Push. | ||
| void Wait(); | ||
|
|
||
| // Ends a Wait in progress. | ||
| void Wake(); | ||
|
|
||
| private: | ||
| std::mutex mutex_; | ||
| std::deque<Item> items_; | ||
| dispatch_semaphore_t pushed_; | ||
| }; | ||
|
|
||
| } // namespace v8_inspector | ||
|
|
||
| #endif /* InspectorQueue_h */ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| #include "InspectorQueue.h" | ||
|
|
||
| #include <algorithm> | ||
| #include <iterator> | ||
| #include <set> | ||
|
|
||
| namespace v8_inspector { | ||
|
|
||
| InspectorQueue::InspectorQueue() : pushed_(dispatch_semaphore_create(0)) {} | ||
|
|
||
| bool InspectorQueue::Interrupts(const std::string& method) { | ||
| static constexpr const char* kMethods[] = { | ||
| "Debugger.getPossibleBreakpoints", "Debugger.getScriptSource", | ||
| "Debugger.getStackTrace", "Debugger.pause", | ||
| "Debugger.removeBreakpoint", "Debugger.resume", | ||
| "Debugger.setBreakpoint", "Debugger.setBreakpointByUrl", | ||
| "Debugger.setBreakpointsActive", | ||
| }; | ||
| return std::any_of(std::begin(kMethods), std::end(kMethods), | ||
| [&](const char* name) { return method == name; }); | ||
| } | ||
|
|
||
| bool InspectorQueue::IsBarrier(const std::string& method) { | ||
| return method == "Debugger.enable" || method == "Debugger.disable"; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let a busy isolate process debugger prerequisites. If an enabled frontend sends Provide a V8-safe way to advance the prerequisite on a busy isolate. Keep connect and enable ahead of commands that need them; removing the barrier alone would let those commands reach a missing or disabled session.
|
||
| } | ||
|
|
||
| InspectorQueue::Item InspectorQueue::Message(uint64_t connectionId, const std::string& method, | ||
| std::string message) { | ||
| return {connectionId, Item::Kind::kMessage, method, | ||
| std::move(message), Interrupts(method), IsBarrier(method)}; | ||
| } | ||
|
|
||
| void InspectorQueue::Push(Item item) { | ||
| if (item.kind != Item::Kind::kMessage) { | ||
| item.barrier = true; | ||
| } | ||
| { | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
| items_.push_back(std::move(item)); | ||
| } | ||
| dispatch_semaphore_signal(pushed_); | ||
| } | ||
|
|
||
| bool InspectorQueue::Take(Item& item) { | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
| if (items_.empty()) { | ||
| return false; | ||
| } | ||
| item = std::move(items_.front()); | ||
| items_.pop_front(); | ||
| return true; | ||
| } | ||
|
|
||
| std::vector<InspectorQueue::Item> InspectorQueue::TakeInterrupting() { | ||
| std::vector<Item> taken; | ||
| std::set<uint64_t> blocked; | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
| for (auto it = items_.begin(); it != items_.end();) { | ||
| if (it->barrier) { | ||
| blocked.insert(it->connectionId); | ||
| } | ||
| if (it->interrupting && blocked.count(it->connectionId) == 0) { | ||
| taken.push_back(std::move(*it)); | ||
| it = items_.erase(it); | ||
| } else { | ||
| ++it; | ||
| } | ||
| } | ||
| return taken; | ||
| } | ||
|
|
||
| void InspectorQueue::Wait() { | ||
| dispatch_semaphore_wait(pushed_, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC)); | ||
| } | ||
|
|
||
| void InspectorQueue::Wake() { dispatch_semaphore_signal(pushed_); } | ||
|
|
||
| } // namespace v8_inspector | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,15 +12,36 @@ | |
|
|
||
| std::atomic<uint64_t> gLastConnectionId{0}; | ||
|
|
||
| // A client this far behind that has also read nothing for this long is | ||
| // assumed gone (e.g. a half-open socket whose peer vanished without a FIN): | ||
| // every client receives broadcast events, so its unsent output would otherwise | ||
| // grow without bound. Size alone does not tell: V8 produces a heap snapshot | ||
| // much faster than a slow link takes it. | ||
| constexpr size_t kMaxPendingWriteBytes = 256 * 1024 * 1024; | ||
| constexpr uint64_t kWriteStallNs = 30 * NSEC_PER_SEC; | ||
|
|
||
| // How often a write in progress reports back, so that one large message on a | ||
| // slow link still counts as progress. | ||
| constexpr size_t kWriteProgressBytes = 256 * 1024; | ||
|
|
||
| struct Connection { | ||
| uint64_t id; | ||
| dispatch_queue_t queue; | ||
| dispatch_io_t channel; | ||
| // Only changes on `queue`. | ||
| std::atomic<bool> open{true}; | ||
| std::atomic<size_t> pendingWriteBytes{0}; | ||
| std::atomic<uint64_t> lastWriteProgressNs{0}; | ||
| std::function<void(uint64_t)> onDisconnected; | ||
| std::function<void(uint64_t, const std::string&)> onMessage; | ||
| }; | ||
|
|
||
| // The peer went away or we closed the channel ourselves (ECANCELED: an | ||
| // operation was still queued at close time); routine, not worth a log line. | ||
| bool IsDisconnectError(int error) { | ||
| return error == ECANCELED || error == ECONNRESET || error == EPIPE; | ||
| } | ||
|
|
||
| void CloseConnection(const std::shared_ptr<Connection>& connection) { | ||
| if (!connection->open.exchange(false)) { | ||
| return; | ||
|
|
@@ -46,7 +67,7 @@ void ReadExactly(std::shared_ptr<Connection> connection, size_t length, | |
| return; | ||
| } | ||
| if (error != 0 || dispatch_data_get_size(received) < length) { | ||
| if (error != 0 && error != ECANCELED) { | ||
| if (error != 0 && !IsDisconnectError(error)) { | ||
| NSLog(@"InspectorServer read error: %s", strerror(error)); | ||
| } | ||
| CloseConnection(connection); | ||
|
|
@@ -70,6 +91,11 @@ void ReadNextMessage(std::shared_ptr<Connection> connection) { | |
| ReadExactly(connection, length, ^(dispatch_data_t body) { | ||
| NSString* payload = [[NSString alloc] initWithData:(NSData*)body | ||
| encoding:NSUTF16LittleEndianStringEncoding]; | ||
| // A write error may have closed the connection after this read | ||
| // completed; onMessage must never follow onDisconnected. | ||
| if (!connection->open.load()) { | ||
| return; | ||
| } | ||
| const char* utf8 = [payload UTF8String]; | ||
| if (utf8 != nullptr) { | ||
| connection->onMessage(connection->id, utf8); | ||
|
|
@@ -99,19 +125,38 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) { | |
| range:NSMakeRange(0, str.length) | ||
| remainingRange:NULL]; | ||
|
|
||
| dispatch_data_t data = | ||
| dispatch_data_create(buffer, length + sizeof(uint32_t), connection->queue, ^{ | ||
| free(buffer); | ||
| }); | ||
| size_t size = length + sizeof(uint32_t); | ||
| dispatch_data_t data = dispatch_data_create(buffer, size, connection->queue, ^{ | ||
| free(buffer); | ||
| }); | ||
|
|
||
| uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); | ||
| size_t pending = connection->pendingWriteBytes.fetch_add(size); | ||
| if (pending == 0) { | ||
| connection->lastWriteProgressNs = now; | ||
| } | ||
| uint64_t progress = connection->lastWriteProgressNs; | ||
| if (pending + size > kMaxPendingWriteBytes && now > progress && now - progress > kWriteStallNs) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check stalled connections without requiring another message. If a heap snapshot queues more than 256 MiB before 30 seconds elapse, this check keeps the connection open. If output then stops, no code checks the timeout again. A half-open client can retain the queued buffers indefinitely. Reconnecting no longer releases that connection because this change removes the previous-client close. The merge-base implementation did close the previous connection on reconnect. (raw.githubusercontent.com) Schedule a timeout on
|
||
| NSLog(@"InspectorServer: closing a client that stopped reading"); | ||
| // Closed on its own queue to keep onDisconnected ordered after onMessage. | ||
| dispatch_async(connection->queue, ^{ | ||
| CloseConnection(connection); | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| dispatch_io_write(connection->channel, 0, data, connection->queue, | ||
| ^(bool done, dispatch_data_t data, int error) { | ||
| // ECANCELED: the write was still queued when the | ||
| // connection closed. | ||
| if (error == 0 || error == ECANCELED) { | ||
| if (done) { | ||
| connection->pendingWriteBytes.fetch_sub(size); | ||
| } | ||
| connection->lastWriteProgressNs = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); | ||
| if (error == 0) { | ||
| return; | ||
| } | ||
| NSLog(@"InspectorServer::Send error: %s", strerror(error)); | ||
| if (!IsDisconnectError(error)) { | ||
| NSLog(@"InspectorServer::Send error: %s", strerror(error)); | ||
| } | ||
| CloseConnection(connection); | ||
| }); | ||
| } | ||
|
|
@@ -145,10 +190,6 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) { | |
| assert(false); | ||
| } | ||
|
|
||
| // Only touched by the accept handler, which libdispatch never runs | ||
| // concurrently with itself. | ||
| __block std::weak_ptr<Connection> activeConnection; | ||
|
|
||
| // Set up the dispatch source that will alert us to new incoming connections | ||
| dispatch_queue_t q = dispatch_queue_create("server_queue", DISPATCH_QUEUE_CONCURRENT); | ||
| dispatch_source_t acceptSource = | ||
|
|
@@ -189,14 +230,10 @@ void Send(std::shared_ptr<Connection> connection, const std::string& message) { | |
| close(clientSocket); | ||
| continue; | ||
| } | ||
| dispatch_io_set_high_water(connection->channel, kWriteProgressBytes); | ||
|
|
||
| // The accept handler is serial, so back-to-back accepts take over in | ||
| // order and the newest client stays active. | ||
| std::shared_ptr<Connection> previous = activeConnection.lock(); | ||
| activeConnection = connection; | ||
| if (previous != nullptr) { | ||
| CloseConnection(previous); | ||
| } | ||
| // Reads start only after this returns, so the client's first message | ||
| // cannot overtake its own connect. | ||
| onClientConnected(connection->id, | ||
| [connection](const std::string& message) { Send(connection, message); }); | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Release the semaphore when
InspectorQueueis destroyed.dispatch_semaphore_createreturns an owned semaphore. The NativeScript target buildsInspectorQueue.mmwithout ARC, and the implicit destructor does not release it. Each debug worker that starts and stops leaves one semaphore allocated. Add an out-of-line destructor that releasespushed_after the queue's users have stopped. (raw.githubusercontent.com)