Skip to content

Commit 73cc285

Browse files
Copilotfengmk2
andauthored
refactor: use net.client.socket diagnostics channel instead of Socket.prototype.emit monkey-patch
Replace the global Socket.prototype.emit monkey-patch with a subscription to Node.js's net.client.socket diagnostics channel. This channel fires when a new TCP/IPC connection is initiated, giving us access to the socket before the 'lookup' event fires, so we can attach a targeted per-socket one-time listener instead of patching the global prototype. Agent-Logs-Url: https://github.com/node-modules/urllib/sessions/d5603429-8e76-46db-bd88-7a315ea660ba Co-authored-by: fengmk2 <[email protected]>
1 parent 4fef0c8 commit 73cc285

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

src/diagnosticsChannel.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,17 @@ Socket.prototype.destroy = function (err?: any) {
6767
return destroySocket.call(this, err);
6868
};
6969

70-
// capture DNS lookup time on socket via 'lookup' event
71-
const originalSocketEmit = Socket.prototype.emit;
72-
Socket.prototype.emit = function (this: SocketExtend, event: string, ...args: any[]) {
73-
if (event === 'lookup') {
74-
this[symbols.kSocketDnsLookupTime] = performance.now();
70+
// capture DNS lookup time on socket via net.client.socket diagnostics channel
71+
// this channel fires when a new TCP/IPC connection is initiated, giving us
72+
// access to the socket before the 'lookup' event fires
73+
diagnosticsChannel.subscribe('net.client.socket', (message: unknown) => {
74+
const socket = (message as { socket: SocketExtend }).socket;
75+
if (socket) {
76+
socket.once('lookup', () => {
77+
socket[symbols.kSocketDnsLookupTime] = performance.now();
78+
});
7579
}
76-
return originalSocketEmit.apply(this, [event, ...args] as any);
77-
} as typeof originalSocketEmit;
80+
});
7881

7982
function getRequestOpaque(request: DiagnosticsChannel.Request, kHandler?: symbol) {
8083
if (!kHandler) return;

0 commit comments

Comments
 (0)