Skip to content

Commit

Permalink
diagnostics_channel: handle 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.
  • Loading branch information
gabrielschulhof committed Jul 26, 2023
1 parent 14e7bd8 commit f1ec8b4
Show file tree
Hide file tree
Showing 2 changed files with 17 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
16 changes: 16 additions & 0 deletions test/parallel/test-diagnostics-channel-sync-unsubscribe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';

const assert = require('node:assert');
const dc = require('node:diagnostics_channel');

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

function onMessageHandler(data) {
assert.equal(data, published_data)
dc.unsubscribe(channel_name, onMessageHandler)
}

dc.subscribe(channel_name, onMessageHandler)

assert.doesNotThrow(() => dc.channel(channel_name).publish(published_data))

0 comments on commit f1ec8b4

Please sign in to comment.