Skip to content

Commit

Permalink
Api / Assets: Prevent backpressure on sending big files (#22175)
Browse files Browse the repository at this point in the history
Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
  • Loading branch information
joselcvarela and paescuj committed Apr 15, 2024
1 parent 75c03bd commit dfe6cca
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 30 deletions.
5 changes: 5 additions & 0 deletions .changeset/dirty-buttons-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@directus/api": patch
---

Ensured streaming of files to client is properly backpressured, preventing out of memory issues with large files
53 changes: 23 additions & 30 deletions api/src/controllers/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,37 +238,30 @@ router.get(
return res.end();
}

let isDataSent = false;

stream.on('data', (chunk) => {
isDataSent = true;
res.write(chunk);
});

stream.on('end', () => {
res.end();
});

stream.on('error', (e) => {
logger.error(e, `Couldn't stream file ${file.id} to the client`);

if (!isDataSent) {
res.removeHeader('Content-Type');
res.removeHeader('Content-Disposition');
res.removeHeader('Cache-Control');

res.status(500).json({
errors: [
{
message: 'An unexpected error occurred.',
extensions: {
code: 'INTERNAL_SERVER_ERROR',
stream
.on('error', (error) => {
logger.error(error, `Couldn't stream file ${file.id} to the client`);

if (!res.headersSent) {
res.removeHeader('Content-Type');
res.removeHeader('Content-Disposition');
res.removeHeader('Cache-Control');

res.status(500).json({
errors: [
{
message: 'An unexpected error occurred.',
extensions: {
code: 'INTERNAL_SERVER_ERROR',
},
},
},
],
});
}
});
],
});
} else {
res.end();
}
})
.pipe(res);

return undefined;
}),
Expand Down

0 comments on commit dfe6cca

Please sign in to comment.