Skip to content

Commit 3a93557

Browse files
authored
perf(runtime): skip unread BroadcastChannel deliveries and let idle channels be collected (#543)
Every open BroadcastChannel deserialized every message posted on its name and dispatched two MessageEvents (one on the hidden port, one re-wrapped by a relay onto the channel), whether or not anything listened. A channel was also held until close(), so fire-and-forget senders accumulated as group members that each paid that cost on every later post. - The channel reports its own 'message'/'messageerror' listener count through the kListenerChanged hook. While it has one, native holds the channel strongly as the port's delivery target and dispatches a single MessageEvent on it; without one, a drained message is discarded unread. The decision is made per message at delivery, so a listener attached in the same turn as the post still receives it. - That strong reference is the only one, matching HTML's GC rule: an open channel with no listener is collectable, and a FinalizationRegistry closes its port so it leaves the group. - Group members are kept in join order, so destinations on one isolate are served in channel creation order as HTML specifies, rather than pointer order. - A port that has not been started is no longer woken for each incoming burst; only its close sentinel wakes it. - Drops a stale MessagingState comment describing a removed field.
1 parent 5a186cf commit 3a93557

5 files changed

Lines changed: 350 additions & 55 deletions

File tree

‎NativeScript/runtime/Messaging.cpp‎

Lines changed: 64 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22

33
#include <algorithm>
44
#include <initializer_list>
5-
#include <set>
65
#include <shared_mutex>
76
#include <unordered_map>
87
#include <unordered_set>
98
#include <utility>
9+
#include <vector>
1010

1111
#include "BuiltinLoader.h"
1212
#include "Caches.h"
@@ -40,10 +40,6 @@ struct MessagingState {
4040
Global<v8::Function> adoptPort;
4141
Global<Private> untransferableBrand;
4242
Global<Private> uncloneableBrand;
43-
// Gates the serializer's host-object claim, which costs a delegate call per
44-
// plain object in every graph. An isolate that has neither created a port
45-
// nor stamped a brand cannot be holding either, so it keeps serializing on
46-
// the cheap path.
4743
};
4844

4945
// The isolate's Caches is invalidated long before ~Runtime reaches the point
@@ -213,7 +209,10 @@ class SiblingGroup final : public std::enable_shared_from_this<SiblingGroup> {
213209
// group is one channel's two ends.
214210
const bool named_ = false;
215211
std::shared_mutex mutex_;
216-
std::set<PortData*> ports_;
212+
// In join order: HTML delivers a broadcast to its destinations in the order
213+
// the channels were created, and a burst that finds none of them already
214+
// scheduled posts their drains in that order.
215+
std::vector<PortData*> ports_;
217216
};
218217

219218
namespace {
@@ -253,7 +252,8 @@ DispatchResult SiblingGroup::Dispatch(PortData* source,
253252
std::string* error) {
254253
std::shared_lock<std::shared_mutex> lock(this->mutex_);
255254

256-
if (this->ports_.find(source) == this->ports_.end()) {
255+
if (std::find(this->ports_.begin(), this->ports_.end(), source) ==
256+
this->ports_.end()) {
257257
if (error != nullptr) {
258258
*error = "Source MessagePort is not entangled with this group.";
259259
}
@@ -296,7 +296,7 @@ void SiblingGroup::Entangle(PortData* port) { this->Entangle({port}); }
296296
void SiblingGroup::Entangle(std::initializer_list<PortData*> ports) {
297297
std::unique_lock<std::shared_mutex> lock(this->mutex_);
298298
for (PortData* data : ports) {
299-
this->ports_.insert(data);
299+
this->ports_.push_back(data);
300300
// group_ is written under the port's own mutex, which is what lets
301301
// PortData::Dispatch read it without racing a disentangle. Taken here in
302302
// the only legal order: this group's lock is already held.
@@ -310,7 +310,9 @@ void SiblingGroup::Disentangle(PortData* data) {
310310
// Keeps the group alive past the last member dropping its reference.
311311
std::shared_ptr<SiblingGroup> self = this->shared_from_this();
312312
std::unique_lock<std::shared_mutex> lock(this->mutex_);
313-
this->ports_.erase(data);
313+
this->ports_.erase(
314+
std::remove(this->ports_.begin(), this->ports_.end(), data),
315+
this->ports_.end());
314316
{
315317
std::lock_guard<std::mutex> dataLock(data->mutex_);
316318
data->group_.reset();
@@ -335,10 +337,11 @@ PortData::~PortData() {
335337

336338
void PortData::AddToIncomingQueue(std::shared_ptr<Message> message) {
337339
std::lock_guard<std::mutex> lock(this->mutex_);
340+
// Still holding the mutex: an owner read outside it could be detached by
341+
// the time the wake reaches it, and Start() checks the backlog under it.
342+
bool wake = this->owner_ != nullptr && this->owner_->WantsDrainFor(*message);
338343
this->incoming_.push_back(std::move(message));
339-
if (this->owner_ != nullptr) {
340-
// Still holding the mutex: an owner read outside it could be detached by
341-
// the time the wake reaches it.
344+
if (wake) {
342345
this->owner_->TriggerAsync();
343346
}
344347
}
@@ -417,6 +420,7 @@ std::shared_ptr<NativeMessagePort> NativeMessagePort::New(
417420
} else {
418421
port->data_ = std::make_unique<PortData>(port.get());
419422
if (group != nullptr) {
423+
port->broadcast_ = true;
420424
group->Entangle(port->data_.get());
421425
}
422426
}
@@ -469,6 +473,19 @@ void NativeMessagePort::Start() {
469473

470474
void NativeMessagePort::Stop() { this->receiving_ = false; }
471475

476+
bool NativeMessagePort::WantsDrainFor(const Message& message) const {
477+
// A port that was never started still learns that its sibling died.
478+
return this->receiving_ || message.IsCloseMessage();
479+
}
480+
481+
void NativeMessagePort::SetBroadcastTarget(Local<Object> target) {
482+
if (target.IsEmpty()) {
483+
this->broadcastTarget_.Reset();
484+
} else {
485+
this->broadcastTarget_.Reset(this->isolateWrapper_.Isolate(), target);
486+
}
487+
}
488+
472489
std::unique_ptr<PortData> NativeMessagePort::Detach() {
473490
// owner_ drops under the data mutex, so a producer either wakes this port
474491
// before the detach or never sees an owner at all. Node carries a separate
@@ -490,6 +507,7 @@ void NativeMessagePort::CloseHandle() {
490507
0, nullptr, v8::kEmbedderDataTypeTagDefault);
491508
this->wrapper_.Reset();
492509
}
510+
this->broadcastTarget_.Reset();
493511
MessagingState* state = State(isolate);
494512
if (state != nullptr) {
495513
state->livePorts.erase(this->shared_from_this());
@@ -519,8 +537,9 @@ void NativeMessagePort::Close() {
519537
}
520538
// Last, on the wrapper the port has just let go of, so a listener finds an
521539
// already-detached port and a close() from inside one is a no-op rather than
522-
// a recursion.
523-
if (!wrapper.IsEmpty()) {
540+
// a recursion. A broadcast port's wrapper never reaches app code, so there
541+
// is no one to tell.
542+
if (!wrapper.IsEmpty() && !this->broadcast_) {
524543
this->EmitClose(wrapper);
525544
}
526545
}
@@ -674,6 +693,17 @@ void NativeMessagePort::Drain() {
674693
return;
675694
}
676695

696+
Local<Object> receiver = wrapper;
697+
if (this->broadcast_) {
698+
// Per message: a listener can add or remove the channel's last listener.
699+
// With none, the event would reach no one and reading the value has no
700+
// other observable effect, so it is never read.
701+
if (this->broadcastTarget_.IsEmpty()) {
702+
continue;
703+
}
704+
receiver = this->broadcastTarget_.Get(isolate);
705+
}
706+
677707
Local<Value> payload;
678708
Local<Value> ports = v8::Undefined(isolate);
679709
bool read;
@@ -698,12 +728,13 @@ void NativeMessagePort::Drain() {
698728
}
699729
}
700730
if (!read) {
701-
this->Emit(context, wrapper, emitMessage, payload, v8::Undefined(isolate),
702-
"messageerror");
731+
this->Emit(context, receiver, emitMessage, payload,
732+
v8::Undefined(isolate), "messageerror");
703733
reschedule = true;
704734
break;
705735
}
706-
if (!this->Emit(context, wrapper, emitMessage, payload, ports, "message")) {
736+
if (!this->Emit(context, receiver, emitMessage, payload, ports,
737+
"message")) {
707738
reschedule = true;
708739
break;
709740
}
@@ -899,6 +930,20 @@ void StopCallback(const FunctionCallbackInfo<Value>& info) {
899930
}
900931
}
901932

933+
void SetBroadcastTargetCallback(const FunctionCallbackInfo<Value>& info) {
934+
Local<Object> wrapper;
935+
if (!PortArg(info, 0, &wrapper)) {
936+
return;
937+
}
938+
NativeMessagePort* port = PortFromWrapper(info.GetIsolate(), wrapper);
939+
if (port == nullptr) {
940+
return;
941+
}
942+
port->SetBroadcastTarget(info.Length() > 1 && info[1]->IsObject()
943+
? info[1].As<Object>()
944+
: Local<Object>());
945+
}
946+
902947
void CloseCallback(const FunctionCallbackInfo<Value>& info) {
903948
Local<Object> wrapper;
904949
if (!PortArg(info, 0, &wrapper)) {
@@ -1058,6 +1103,8 @@ MaybeLocal<Object> CreateBinding(Local<Context> context) {
10581103
tns::SetMethod(context, binding, "postMessage", PostMessageCallback);
10591104
tns::SetMethod(context, binding, "start", StartCallback);
10601105
tns::SetMethod(context, binding, "stop", StopCallback);
1106+
tns::SetMethod(context, binding, "setBroadcastTarget",
1107+
SetBroadcastTargetCallback);
10611108
tns::SetMethod(context, binding, "close", CloseCallback);
10621109
tns::SetMethod(context, binding, "drainOne", DrainOneCallback);
10631110
tns::SetMethodNoSideEffect(context, binding, "isDetached",

‎NativeScript/runtime/Messaging.h‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,9 @@ class NativeMessagePort
9595
// Creates a port and its JS wrapper. With `data` the port adopts an
9696
// in-flight port — the group travels with the data — and schedules a drain
9797
// of whatever queued up while it was in transit; with `group` it joins that
98-
// named group; with neither it is one unentangled end of a new channel.
99-
// Null with an exception pending when the wrapper or the JS tier could not
100-
// be built.
98+
// named group as a BroadcastChannel's port; with neither it is one
99+
// unentangled end of a new channel. Null with an exception pending when the
100+
// wrapper or the JS tier could not be built.
101101
static std::shared_ptr<NativeMessagePort> New(
102102
v8::Local<v8::Context> context, std::unique_ptr<PortData> data = nullptr,
103103
std::shared_ptr<SiblingGroup> group = nullptr);
@@ -111,6 +111,16 @@ class NativeMessagePort
111111
void Start();
112112
void Stop();
113113

114+
// Any thread, under this port's data mutex: whether a message queued now
115+
// would be taken by a drain, so a producer can skip waking a port that
116+
// would only find it has nothing it may deliver.
117+
bool WantsDrainFor(const serialization::SerializedValue& message) const;
118+
119+
// A BroadcastChannel port's delivery target: the channel, held strongly,
120+
// while it has a 'message' or 'messageerror' listener; empty otherwise, and
121+
// a message drained with no target is discarded without being read.
122+
void SetBroadcastTarget(v8::Local<v8::Object> target);
123+
114124
// Detaches the data, sentinels the sibling, drops the JS wrapper and fires
115125
// the tier's close event on it. Safe to call on an already-closed port, and
116126
// safe to call from inside that event.
@@ -153,14 +163,19 @@ class NativeMessagePort
153163
v8::Local<v8::Value> ports, const char* type);
154164

155165
std::unique_ptr<PortData> data_;
156-
bool receiving_ = false;
166+
// Written on the home thread only; producers read it in WantsDrainFor.
167+
std::atomic<bool> receiving_{false};
168+
// Set once, at creation. A broadcast port always receives; whether a message
169+
// is delivered or discarded is decided per message by broadcastTarget_.
170+
bool broadcast_ = false;
157171
// Set while a drain is queued, so a burst of messages costs one post.
158172
// Atomic because producers flip it from their own threads.
159173
std::atomic<bool> scheduled_{false};
160174
// Strong on purpose: a port and its JS wrapper stay alive until the port is
161175
// closed, which is the lifetime model HTML and Node specify — reachability
162176
// plays no part in it.
163177
v8::Global<v8::Object> wrapper_;
178+
v8::Global<v8::Object> broadcastTarget_;
164179
IsolateWrapper isolateWrapper_;
165180
// Held by shared_ptr so a drain posted from a foreign thread can never race
166181
// the loop's own teardown.

‎NativeScript/runtime/js/broadcast-channel.js‎

Lines changed: 65 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,34 @@
33
// same name joins one process-wide group, workers included — "same user agent"
44
// is the app process here.
55
//
6-
// A channel owns a hidden MessagePort in that named group. The port is started
7-
// and strongly held from construction (native holds the wrapper, the wrapper
8-
// holds the relay listener, the relay holds the channel), so an unclosed
9-
// channel stays deliverable whether or not app code keeps a reference — and
10-
// close() is what ends that.
11-
const { createBroadcastPort, postMessage: postMessageToPort, close: closePort } =
12-
binding;
6+
// A channel owns a hidden port in that named group, and native delivers
7+
// straight to the channel: one MessageEvent per message, nothing dispatched on
8+
// the port.
9+
//
10+
// Lifetime follows the spec's GC rule. While the channel is open and has a
11+
// 'message' or 'messageerror' listener, native holds it strongly as the port's
12+
// delivery target; that is the only strong path to a channel app code dropped.
13+
// Without such a listener nothing native reaches it, a message arriving is
14+
// discarded unread, and once app code lets go the channel is collected and the
15+
// registry below takes its port out of the group.
16+
const {
17+
createBroadcastPort,
18+
postMessage: postMessageToPort,
19+
close: closePort,
20+
setBroadcastTarget,
21+
} = binding;
1322

1423
const {
15-
FunctionPrototypeCall,
24+
FinalizationRegistry,
25+
FinalizationRegistryPrototypeRegister,
26+
FinalizationRegistryPrototypeUnregister,
1627
ObjectDefineProperty,
1728
SymbolToStringTag,
1829
TypeError,
1930
} = primordials;
2031

21-
const { EventTarget, defineEventHandler } = require("internal/events");
22-
const { adoptPort } = require("internal/message-channel");
23-
24-
const addEventListener = EventTarget.prototype.addEventListener;
25-
const dispatchEvent = EventTarget.prototype.dispatchEvent;
26-
27-
let createMessageEvent;
28-
function getCreateMessageEvent() {
29-
if (createMessageEvent === undefined) {
30-
({ createMessageEvent } = require("internal/message-event"));
31-
}
32-
return createMessageEvent;
33-
}
32+
const { EventTarget, defineEventHandler, kListenerChanged } =
33+
require("internal/events");
3434

3535
let DOMException;
3636
function getDOMException() {
@@ -40,9 +40,18 @@ function getDOMException() {
4040
return DOMException;
4141
}
4242

43+
const portRegistry = new FinalizationRegistry(closePort);
44+
45+
const kHeardMessage = 1;
46+
const kHeardMessageError = 2;
47+
48+
let listenerChanged;
49+
4350
class BroadcastChannel extends EventTarget {
4451
#name;
4552
#port;
53+
// kHeardMessage | kHeardMessageError, for whichever has a listener.
54+
#heard = 0;
4655

4756
constructor(name) {
4857
if (arguments.length < 1) {
@@ -57,18 +66,8 @@ class BroadcastChannel extends EventTarget {
5766
configurable: true,
5867
});
5968
this.#name = `${name}`;
60-
const port = adoptPort(createBroadcastPort(this.#name));
61-
this.#port = port;
62-
const channel = this;
63-
const relay = function (event) {
64-
FunctionPrototypeCall(
65-
dispatchEvent,
66-
channel,
67-
getCreateMessageEvent()(event.type, event.data)
68-
);
69-
};
70-
FunctionPrototypeCall(addEventListener, port, "message", relay);
71-
FunctionPrototypeCall(addEventListener, port, "messageerror", relay);
69+
this.#port = createBroadcastPort(this.#name);
70+
FinalizationRegistryPrototypeRegister(portRegistry, this, this.#port, this);
7271
}
7372

7473
get name() {
@@ -96,13 +95,46 @@ class BroadcastChannel extends EventTarget {
9695
}
9796
const port = this.#port;
9897
this.#port = undefined;
98+
FinalizationRegistryPrototypeUnregister(portRegistry, this);
9999
closePort(port);
100100
}
101+
102+
static {
103+
listenerChanged = (channel, type, count) => {
104+
// The hook is found through the prototype, so it also runs for objects
105+
// that merely inherit from it.
106+
if (!(#port in channel) || channel.#port === undefined) {
107+
return;
108+
}
109+
let bit;
110+
if (type === "message") {
111+
bit = kHeardMessage;
112+
} else if (type === "messageerror") {
113+
bit = kHeardMessageError;
114+
} else {
115+
return;
116+
}
117+
const before = channel.#heard;
118+
const after = count > 0 ? before | bit : before & ~bit;
119+
channel.#heard = after;
120+
if ((before === 0) !== (after === 0)) {
121+
setBroadcastTarget(channel.#port, after === 0 ? undefined : channel);
122+
}
123+
};
124+
}
101125
}
102126

103127
defineEventHandler(BroadcastChannel.prototype, "message");
104128
defineEventHandler(BroadcastChannel.prototype, "messageerror");
105129

130+
ObjectDefineProperty(BroadcastChannel.prototype, kListenerChanged, {
131+
__proto__: null,
132+
value: listenerChanged,
133+
writable: false,
134+
enumerable: false,
135+
configurable: false,
136+
});
137+
106138
for (const key of ["name", "postMessage", "close"]) {
107139
ObjectDefineProperty(BroadcastChannel.prototype, key, {
108140
__proto__: null,

‎NativeScript/runtime/js/message-channel.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,8 @@ function receiveMessageOnPort(port) {
241241
}
242242

243243
// The per-isolate delivery callout. Native invokes it with the receiving port
244-
// wrapper as the receiver; `type` is "message", "messageerror" or "close".
244+
// wrapper as the receiver — or, for a BroadcastChannel's port, the channel
245+
// itself; `type` is "message", "messageerror" or "close".
245246
function emitMessage(data, ports, type) {
246247
if (type === "close") {
247248
FunctionPrototypeCall(dispatchEvent, this, new Event("close"));

0 commit comments

Comments
 (0)