Skip to content

Commit

Permalink
fix(fetch): fix memory leak when passing keepAlive (#83)
Browse files Browse the repository at this point in the history
* fix: memory leak when using keepAlive

* chore: fix changeset

* remove socket listeners on "abort"

Co-authored-by: Matt Brophy <matt@brophy.org>

* chore: remove obsolete changeset

---------

Co-authored-by: Marwan Fikrat <32395961+marwan38@users.noreply.github.com>
Co-authored-by: Donavon West <github@donavon.com>
Co-authored-by: Matt Brophy <matt@brophy.org>
  • Loading branch information
4 people authored Aug 29, 2023
1 parent dcea779 commit 5fde362
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/giant-taxis-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@web-std/fetch": patch
---

Memory leak caused by unregistered listeners. Solution was copied from a node-fetch pr.
22 changes: 14 additions & 8 deletions packages/fetch/src/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,13 +346,8 @@ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
}
};

socket.prependListener('close', onSocketClose);

request.on('abort', () => {
socket.removeListener('close', onSocketClose);
});

socket.on('data', buf => {
/** @param {Buffer} buf */
const onData = buf => {
properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;

// Sometimes final 0-length chunk and end of message code are in separate packets
Expand All @@ -364,7 +359,18 @@ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
}

previousChunk = buf;
});
};

socket.prependListener('close', onSocketClose);
socket.on('data', onData);

const removeSocketListeners = () => {
socket.removeListener('close', onSocketClose);
socket.removeListener('data', onData);
}

request.on('close', removeSocketListeners);
request.on('abort', removeSocketListeners);
});
}

Expand Down

0 comments on commit 5fde362

Please sign in to comment.