Skip to content

Commit

Permalink
diagnostics_channel: fix last subscriber removal
Browse files Browse the repository at this point in the history
When iterating over diagnostics channel subscribers, assume their count
is zero if the list of subscribers becomes undefined, because there may
be only one subscriber which may unsubscribe itself as part of its
onMessage handler.

Signed-off-by: Gabriel Schulhof <gabrielschulhof@gmail.com>
PR-URL: nodejs#48933
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: theanarkh <theratliter@gmail.com>
  • Loading branch information
gabrielschulhof authored and RafaelGSS committed Aug 15, 2023
1 parent 6b6a2c0 commit d128ca1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/diagnostics_channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ class ActiveChannel {
}

publish(data) {
for (let i = 0; i < this._subscribers.length; i++) {
for (let i = 0; i < (this._subscribers?.length || 0); i++) {
try {
const onMessage = this._subscribers[i];
onMessage(data, this.name);
Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-diagnostics-channel-sync-unsubscribe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const common = require('../common');
const dc = require('node:diagnostics_channel');

const channel_name = 'test:channel';
const published_data = 'some message';

const onMessageHandler = common.mustCall(() => dc.unsubscribe(channel_name, onMessageHandler));

dc.subscribe(channel_name, onMessageHandler);

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

0 comments on commit d128ca1

Please sign in to comment.