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 <[email protected]>
PR-URL: nodejs#48933
Reviewed-By: Stephen Belanger <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Chengzhong Wu <[email protected]>
Reviewed-By: theanarkh <[email protected]>
  • Loading branch information
gabrielschulhof authored and Ceres6 committed Aug 14, 2023
1 parent b09b6aa commit 6568ac8
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 6568ac8

Please sign in to comment.