From faf214e2a18ad6256a6aa69076b6e123734fde47 Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:50:22 +0000 Subject: [PATCH] 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 .tmp.zip in the instance saves folder, listed as a save. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/file_ops.ts | 4 ++-- test/lib/file_ops.js | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/file_ops.ts b/packages/lib/src/file_ops.ts index 16701808..7aa5d8df 100644 --- a/packages/lib/src/file_ops.ts +++ b/packages/lib/src/file_ops.ts @@ -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); diff --git a/test/lib/file_ops.js b/test/lib/file_ops.js index a44e069f..efd29ced 100644 --- a/test/lib/file_ops.js +++ b/test/lib/file_ops.js @@ -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.