Remove partial downloads when the stream is cut mid-write

When the connection drops while the body is being written, the pipe
destroys the file stream with an error before it has closed.
events.once then rejects on that error, so the temporary file was
never unlinked. A save upload cancelled from the web UI left a
<name>.tmp.zip in the instance saves folder, listed as a save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-21 02:50:22 +00:00
1 parent 8692ea3941
commit faf214e2a1
2 files changed
+16 -2

No files matched your search

+2 -2
View File
@@ -2,7 +2,6 @@
* @module lib/file_ops
*/
import crypto from "crypto";
import events from "events";
import fs from "node:fs/promises";
import path from "path";
import stream from "stream";
@@ -258,7 +257,8 @@ export async function createTempWriteStream(filePath: string) {
async function discardPartialDownload(writeStream: stream.Writable, tempFilePath: string) {
if (!writeStream.closed) {
writeStream.destroy();
await events.once(writeStream, "close");
// Not events.once, it rejects if the stream is still erroring from the aborted pipe.
await new Promise(resolve => writeStream.once("close", resolve));
}
try {
await fs.unlink(tempFilePath);
+14
View File
@@ -412,6 +412,20 @@ describe("lib/file_ops", function() {
await assert.rejects(fs.readFile(downloadPath), { code: "ENOENT" });
});
it("should not leave a temporary file behind if interrupted while writing", async function () {
const downloadPath = path.join(downloadDir, "interrupted-writing.txt");
onStream = (res) => {
res.write(Buffer.alloc(1024 * 1024));
setTimeout(() => res.destroy(), 100);
};
await assert.rejects(lib.downloadFile(new URL("/stream", baseUrl), downloadPath, "rename"));
await assert.rejects(
fs.readFile(path.join(downloadDir, "interrupted-writing.tmp.txt")),
{ code: "ENOENT" },
);
await assert.rejects(fs.readFile(downloadPath), { code: "ENOENT" });
});
it("should throw if overwriteMode is rename and directory disappeared", async function () {
if (process.platform === "win32") {
// Can't remove the directory while the stream is running on Windows.