Skip to content

Commit

Permalink
diagnostics_channel: fix unsubscribe during publish
Browse files Browse the repository at this point in the history
PR-URL: #55116
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Claudio Wunder <cwunder@gnome.org>
  • Loading branch information
simon-id authored and aduh95 committed Oct 19, 2024
1 parent 8ceefeb commit c028d21
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
13 changes: 10 additions & 3 deletions lib/diagnostics_channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const {
ArrayPrototypeAt,
ArrayPrototypeIndexOf,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeSlice,
ArrayPrototypeSplice,
ObjectDefineProperty,
ObjectGetPrototypeOf,
Expand Down Expand Up @@ -97,6 +99,7 @@ function wrapStoreRun(store, data, next, transform = defaultTransform) {
class ActiveChannel {
subscribe(subscription) {
validateFunction(subscription, 'subscription');
this._subscribers = ArrayPrototypeSlice(this._subscribers);
ArrayPrototypePush(this._subscribers, subscription);
channels.incRef(this.name);
}
Expand All @@ -105,7 +108,10 @@ class ActiveChannel {
const index = ArrayPrototypeIndexOf(this._subscribers, subscription);
if (index === -1) return false;

ArrayPrototypeSplice(this._subscribers, index, 1);
const before = ArrayPrototypeSlice(this._subscribers, 0, index);
const after = ArrayPrototypeSlice(this._subscribers, index + 1);
this._subscribers = before;
ArrayPrototypePushApply(this._subscribers, after);

channels.decRef(this.name);
maybeMarkInactive(this);
Expand Down Expand Up @@ -137,9 +143,10 @@ class ActiveChannel {
}

publish(data) {
for (let i = 0; i < (this._subscribers?.length || 0); i++) {
const subscribers = this._subscribers;
for (let i = 0; i < (subscribers?.length || 0); i++) {
try {
const onMessage = this._subscribers[i];
const onMessage = subscribers[i];
onMessage(data, this.name);
} catch (err) {
process.nextTick(() => {
Expand Down
1 change: 1 addition & 0 deletions test/parallel/test-diagnostics-channel-sync-unsubscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const published_data = 'some message';
const onMessageHandler = common.mustCall(() => dc.unsubscribe(channel_name, onMessageHandler));

dc.subscribe(channel_name, onMessageHandler);
dc.subscribe(channel_name, common.mustCall());

// This must not throw.
dc.channel(channel_name).publish(published_data);

0 comments on commit c028d21

Please sign in to comment.