Skip to content

Commit

Permalink
fetch: fix leak
Browse files Browse the repository at this point in the history
Fixes: #1823
  • Loading branch information
ronag committed Apr 7, 2023
1 parent f0271d4 commit deef31e
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/fetch/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const { setMaxListeners, getEventListeners, defaultMaxListeners } = require('eve
let TransformStream = globalThis.TransformStream

const kInit = Symbol('init')
const kAbortController = Symbol('abortController')

const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
signal.removeEventListener('abort', abort)
Expand Down Expand Up @@ -354,8 +355,14 @@ class Request {
if (signal.aborted) {
ac.abort(signal.reason)
} else {
// Keep a strong ref to ac while request object
// is alive. This is needed to prevent AbortController
// from being prematurely garbage collected.
this[kAbortController] = ac

const weakAc = new WeakRef(ac)
const abort = function () {
ac.abort(this.reason)
weakAc.deref()?.abort(this.reason)
}

// Third-party AbortControllers may not work with these.
Expand All @@ -367,7 +374,7 @@ class Request {
} catch {}

signal.addEventListener('abort', abort, { once: true })
requestFinalizer.register(this, { signal, abort })
requestFinalizer.register(ac, { signal, abort })
}
}

Expand Down

0 comments on commit deef31e

Please sign in to comment.