Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(instr-undici): avoid use of deprecated APIs for diagnostic channels #2457

Merged
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
Loading