From fe1b6d178b9f438088482e5e62948d114dc101fc Mon Sep 17 00:00:00 2001 From: Khafra Date: Mon, 3 Feb 2025 16:40:37 -0500 Subject: [PATCH] don't check AbortSignal maxListeners on some node versions --- lib/web/fetch/request.js | 21 ++++++++++++--------- test/fetch/long-lived-abort-controller.js | 3 ++- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/lib/web/fetch/request.js b/lib/web/fetch/request.js index 97fea22cdbd..82a419162fa 100644 --- a/lib/web/fetch/request.js +++ b/lib/web/fetch/request.js @@ -37,6 +37,14 @@ const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { const dependentControllerMap = new WeakMap() +let abortSignalHasEventHandlerLeakWarning + +try { + abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0 +} catch { + abortSignalHasEventHandlerLeakWarning = false +} + function buildAbort (acRef) { return abort @@ -424,15 +432,10 @@ class Request { const acRef = new WeakRef(ac) const abort = buildAbort(acRef) - // Third-party AbortControllers may not work with these. - // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. - try { - // If the max amount of listeners is equal to the default, increase it - // This is only available in node >= v19.9.0 - if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { - setMaxListeners(1500, signal) - } - } catch {} + // If the max amount of listeners is equal to the default, increase it + if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal) + } util.addAbortListener(signal, abort) // The third argument must be a registry key to be unregistered. diff --git a/test/fetch/long-lived-abort-controller.js b/test/fetch/long-lived-abort-controller.js index 819f2580292..561ebee0661 100644 --- a/test/fetch/long-lived-abort-controller.js +++ b/test/fetch/long-lived-abort-controller.js @@ -2,7 +2,7 @@ const http = require('node:http') const { fetch } = require('../../') -const { once } = require('events') +const { once, setMaxListeners } = require('node:events') const { test } = require('node:test') const { closeServerAsPromise } = require('../utils/node-http') const { strictEqual } = require('node:assert') @@ -30,6 +30,7 @@ test('long-lived-abort-controller', { skip: true }, async (t) => { }) const controller = new AbortController() + setMaxListeners(1500, controller.signal) // The maxListener is set to 1500 in request.js. // we set it to 2000 to make sure that we are not leaking event listeners.