@@ -77,7 +77,7 @@ export class UndiciInstrumentation extends InstrumentationBase<UndiciInstrumenta
77
77
78
78
override disable ( ) : void {
79
79
super . disable ( ) ;
80
- this . _channelSubs . forEach ( sub => sub . channel . unsubscribe ( sub . onMessage ) ) ;
80
+ this . _channelSubs . forEach ( sub => sub . unsubscribe ( ) ) ;
81
81
this . _channelSubs . length = 0 ;
82
82
}
83
83
@@ -137,14 +137,29 @@ export class UndiciInstrumentation extends InstrumentationBase<UndiciInstrumenta
137
137
138
138
private subscribeToChannel (
139
139
diagnosticChannel : string ,
140
- onMessage : ListenerRecord [ 'onMessage' ]
140
+ onMessage : ( message : any , name : string | symbol ) => void
141
141
) {
142
- const channel = diagch . channel ( diagnosticChannel ) ;
143
- channel . subscribe ( onMessage ) ;
142
+ // `diagnostics_channel` had a ref counting bug until v18.19.0.
143
+ // https://github.com/nodejs/node/pull/47520
144
+ const [ major , minor ] = process . version
145
+ . replace ( 'v' , '' )
146
+ . split ( '.' )
147
+ . map ( n => Number ( n ) ) ;
148
+ const useNewSubscribe = major > 18 || ( major === 18 && minor >= 19 ) ;
149
+
150
+ let unsubscribe : ( ) => void ;
151
+ if ( useNewSubscribe ) {
152
+ diagch . subscribe ?.( diagnosticChannel , onMessage ) ;
153
+ unsubscribe = ( ) => diagch . unsubscribe ?.( diagnosticChannel , onMessage ) ;
154
+ } else {
155
+ const channel = diagch . channel ( diagnosticChannel ) ;
156
+ channel . subscribe ( onMessage ) ;
157
+ unsubscribe = ( ) => channel . unsubscribe ( onMessage ) ;
158
+ }
159
+
144
160
this . _channelSubs . push ( {
145
161
name : diagnosticChannel ,
146
- channel,
147
- onMessage,
162
+ unsubscribe,
148
163
} ) ;
149
164
}
150
165
0 commit comments