Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: destroy sockets to stop memory leaking when stream errors #2336

Merged
merged 1 commit into from
Oct 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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