Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/diagnostics_channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ const { WeakReference } = require('internal/util');
// Only GC can be used as a valid time to clean up the channels map.
class WeakRefMap extends SafeMap {
#finalizers = new SafeFinalizationRegistry((key) => {
this.delete(key);
// Check that the key doesn't have any value before deleting, as the WeakRef for the key
// may have been replaced since finalization callbacks aren't synchronous with GC.
if (!this.has(key)) this.delete(key);
});

set(key, value) {
Expand All @@ -49,6 +51,10 @@ class WeakRefMap extends SafeMap {
return super.get(key)?.get();
}

has(key) {
return !!this.get(key);
}

incRef(key) {
return super.get(key)?.incRef();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
*
*
*
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at TracingChannel.traceSync (node:diagnostics_channel:328:14)
*
*
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Flags: --expose-gc
'use strict';

require('../common');
const assert = require('assert');
const { channel } = require('diagnostics_channel');

function test() {
function subscribe() {
channel('test-gc').subscribe(function noop() {});
}

subscribe();

setTimeout(() => {
global.gc();
assert.ok(channel('test-gc').hasSubscribers, 'Channel must have subscribers');
});
}

test();
23 changes: 23 additions & 0 deletions test/parallel/test-diagnostics-channel-gc-race-condition.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Flags: --expose-gc
'use strict';

require('../common');
const assert = require('assert');
const { channel } = require('diagnostics_channel');

function test() {
const testChannel = channel('test-gc');

setTimeout(() => {
const testChannel2 = channel('test-gc');

assert.ok(testChannel === testChannel2, 'Channel instances must be the same');
});
}

test();

setTimeout(() => {
global.gc();
test();
}, 10);
Loading