Skip to content

Commit

Permalink
fix: destroy sockets to stop memory leaking when stream errors (#2336)
Browse files Browse the repository at this point in the history
  • Loading branch information
ddelgrosso1 authored Oct 19, 2023
1 parent 00d744d commit 04939ee
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1433,6 +1433,7 @@ class File extends ServiceObject<File, FileMetadata> {
const tailRequest = options.end! < 0;

let validateStream: HashStreamValidator | undefined = undefined;
let request: r.Request | undefined = undefined;

const throughStream = new PassThroughShim();

Expand Down Expand Up @@ -1464,6 +1465,11 @@ class File extends ServiceObject<File, FileMetadata> {

const onComplete = (err: Error | null) => {
if (err) {
// There is an issue with node-fetch 2.x that if the stream errors the underlying socket connection is not closed.
// This causes a memory leak, so cleanup the sockets manually here by destroying the agent.
if (request?.agent) {
request.agent.destroy();
}
throughStream.destroy(err);
}
};
Expand Down Expand Up @@ -1492,6 +1498,7 @@ class File extends ServiceObject<File, FileMetadata> {
return;
}

request = (rawResponseStream as r.Response).request;
const headers = (rawResponseStream as ResponseBody).toJSON().headers;
const isCompressed = headers['content-encoding'] === 'gzip';
const hashes: {crc32c?: string; md5?: string} = {};
Expand Down

0 comments on commit 04939ee

Please sign in to comment.