Skip to content

Commit f973722

Browse files
committed
fix(cp): prevent WriteStream error handler from orphaning subsequent file's stream
When a WriteStream error fires asynchronously after we've moved on to processing the next file, only nullify currentFile if it still points to the errored stream. This prevents a race condition where a late-firing error could orphan the new file's stream.
1 parent 4d5d2b1 commit f973722

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/lib/cp.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,10 +428,15 @@ export async function cpFromInstance(cfg: CpConfig, opts: CpFromInstanceOptions)
428428
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
429429
currentFile = fs.createWriteStream(targetPath, { mode: currentHeader.mode });
430430
// Add error handler to prevent unhandled 'error' events from crashing
431+
// Capture reference to avoid race condition if error fires after we've moved to next file
431432
const fileBeingWritten = currentFile;
432433
currentFile.on('error', (err) => {
433434
fileBeingWritten.destroy();
434-
currentFile = null;
435+
// Only nullify currentFile if it's still pointing to this stream
436+
// This prevents orphaning a subsequent file's stream if this error fires late
437+
if (currentFile === fileBeingWritten) {
438+
currentFile = null;
439+
}
435440
doReject(new Error(`Failed to write file ${targetPath}: ${err.message}`));
436441
ws.close();
437442
});

0 commit comments

Comments
 (0)