Skip to content

Commit

Permalink
refactor(instr-undici): avoid use of deprecated APIs for diagnostic c…
Browse files Browse the repository at this point in the history
…hannels (#2457)
  • Loading branch information
david-luna authored Oct 9, 2024
1 parent 2512c78 commit 23aae01
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
4 changes: 1 addition & 3 deletions plugins/node/instrumentation-undici/src/internal-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
27 changes: 21 additions & 6 deletions plugins/node/instrumentation-undici/src/undici.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class UndiciInstrumentation extends InstrumentationBase<UndiciInstrumenta

override disable(): void {
super.disable();
this._channelSubs.forEach(sub => sub.channel.unsubscribe(sub.onMessage));
this._channelSubs.forEach(sub => sub.unsubscribe());
this._channelSubs.length = 0;
}

Expand Down Expand Up @@ -137,14 +137,29 @@ export class UndiciInstrumentation extends InstrumentationBase<UndiciInstrumenta

private subscribeToChannel(
diagnosticChannel: string,
onMessage: ListenerRecord['onMessage']
onMessage: (message: any, name: string | symbol) => 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,
});
}

Expand Down

0 comments on commit 23aae01

Please sign in to comment.