diff --git a/plugins/node/instrumentation-undici/src/internal-types.ts b/plugins/node/instrumentation-undici/src/internal-types.ts index 67c7fd6ce3..e6b2fff535 100644 --- a/plugins/node/instrumentation-undici/src/internal-types.ts +++ b/plugins/node/instrumentation-undici/src/internal-types.ts @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import type { Channel } from 'diagnostics_channel'; import { UndiciRequest, UndiciResponse } from './types'; export interface ListenerRecord { name: string; - channel: Channel; - onMessage: (message: any, name: string | symbol) => void; + unsubscribe: () => void; } export interface RequestMessage { diff --git a/plugins/node/instrumentation-undici/src/undici.ts b/plugins/node/instrumentation-undici/src/undici.ts index 0d8ebedc73..1755b7417b 100644 --- a/plugins/node/instrumentation-undici/src/undici.ts +++ b/plugins/node/instrumentation-undici/src/undici.ts @@ -77,7 +77,7 @@ export class UndiciInstrumentation extends InstrumentationBase sub.channel.unsubscribe(sub.onMessage)); + this._channelSubs.forEach(sub => sub.unsubscribe()); this._channelSubs.length = 0; } @@ -137,14 +137,29 @@ export class UndiciInstrumentation extends InstrumentationBase void ) { - const channel = diagch.channel(diagnosticChannel); - channel.subscribe(onMessage); + // `diagnostics_channel` had a ref counting bug until v18.19.0. + // https://github.com/nodejs/node/pull/47520 + const [major, minor] = process.version + .replace('v', '') + .split('.') + .map(n => Number(n)); + const useNewSubscribe = major > 18 || (major === 18 && minor >= 19); + + let unsubscribe: () => void; + if (useNewSubscribe) { + diagch.subscribe?.(diagnosticChannel, onMessage); + unsubscribe = () => diagch.unsubscribe?.(diagnosticChannel, onMessage); + } else { + const channel = diagch.channel(diagnosticChannel); + channel.subscribe(onMessage); + unsubscribe = () => channel.unsubscribe(onMessage); + } + this._channelSubs.push({ name: diagnosticChannel, - channel, - onMessage, + unsubscribe, }); }