Skip to content
Merged
Show file tree
Hide file tree
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
8 changes: 7 additions & 1 deletion src/js/node/fs.promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1446,6 +1446,12 @@ async function writeFileAsyncIteratorInner(fd, iterable, encoding, signal: Abort
return totalBytesWritten;
}

// The only flag spellings whose `open` truncates. `r+` & co. overwrite in place,
// so resizing the file down to the bytes we wrote would destroy the rest of it.
function flagTruncates(flag): boolean {
return flag === "w" || flag === "w+" || flag === "wx" || flag === "wx+" || flag === "xw" || flag === "xw+";
}

async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, flag, mode) {
let encoding;
let signal: AbortSignal | null = null;
Expand Down Expand Up @@ -1491,7 +1497,7 @@ async function writeFileAsyncIterator(fdOrPath, iterable, optionsOrEncoding, fla

// Handle cleanup outside of try-catch
if (mustClose) {
if (typeof flag === "string" && !flag.includes("a")) {
if (flagTruncates(flag)) {
try {
await fs.ftruncate(fdOrPath, totalBytesWritten);
} catch {}
Expand Down
50 changes: 42 additions & 8 deletions src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7430,7 +7430,14 @@ impl NodeFS {
let fd = match &args.file {
PathOrFileDescriptor::Path(p) => {
let path = p.slice_z_with_force_copy::<true>(pathbuf);
match sys::openat(args.dirfd, path, args.flag.as_int(), args.mode) {
// O_TRUNC is dropped on purpose: keeping the existing blocks
// allocated makes rewriting a large file cheaper, and the resize
// below sets the final size. O_APPEND writes at EOF, so it keeps it.
let mut flags = args.flag.as_int();
if (flags & sys::O::APPEND) == 0 {
flags &= !sys::O::TRUNC;
}
match sys::openat(args.dirfd, path, flags, args.mode) {
Err(err) => return Err(err.with_path(p.slice())),
Ok(fd) => fd,
}
Expand Down Expand Up @@ -7458,11 +7465,25 @@ impl NodeFS {
// Worthwhile after 6 MB at least on ext4 linux
if PREALLOCATE_SUPPORTED && buf.len() >= PREALLOCATE_LENGTH {
'preallocate: {
let offset: usize = if matches!(args.file, PathOrFileDescriptor::Path(_)) {
// on mac, it's relatively positioned
let is_path = matches!(args.file, PathOrFileDescriptor::Path(_));
// Preallocating grows the file, so skip it when the kernel picks
// the write offset at write() time: an O_APPEND write would land
// after the grown end, leaving a hole where the data belongs.
let appends = if is_path {
(args.flag.as_int() & sys::O::APPEND) != 0
} else {
// `flag` is the option, not how the caller opened this fd.
match sys::get_fcntl_flags(fd) {
Ok(open_flags) => (open_flags as c_int & sys::O::APPEND) != 0,
Err(_) => break 'preallocate,
}
};
if appends {
break 'preallocate;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
let offset: usize = if is_path {
0
} else {
// on linux, it's absolutely positioned
match Syscall::lseek(fd, 0, libc::SEEK_CUR) {
Err(_) => break 'preallocate,
Ok(pos) => usize::try_from(pos).expect("int cast"),
Expand All @@ -7476,9 +7497,16 @@ impl NodeFS {
}
}

// A write error is held back rather than returned, so the resize below
// still runs: a partial write must not leave the old tail sitting behind
// the bytes that did land.
let mut write_err: Option<sys::Error> = None;
while !buf.is_empty() {
match sys::write(fd, buf) {
Err(err) => return Err(err),
Err(err) => {
write_err = Some(err);
break;
}
Ok(amt) => {
buf = &buf[amt..];
#[cfg(not(windows))]
Expand All @@ -7494,9 +7522,11 @@ impl NodeFS {

// https://github.com/oven-sh/bun/issues/2931
// https://github.com/oven-sh/bun/issues/10222
// Only truncate if we're not appending and writing to a path
if (args.flag.as_int() & sys::O::APPEND) == 0
&& !matches!(args.file, PathOrFileDescriptor::Fd(_))
// Resize only when the flags asked to truncate (the open above dropped
// O_TRUNC): `r+` & co. overwrite in place, and Node never resizes a
// descriptor it was handed.
if (args.flag.as_int() & sys::O::TRUNC) != 0
&& matches!(args.file, PathOrFileDescriptor::Path(_))
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
{
// If this errors, we silently ignore it.
// Not all files are seekable (and thus, not all files can be truncated).
Expand All @@ -7510,6 +7540,10 @@ impl NodeFS {
}
}

if let Some(err) = write_err {
return Err(err);
}

if args.flush {
#[cfg(windows)]
{
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1702,7 +1702,7 @@ impl FileSystemFlags {
/// Open file for reading. An exception occurs if the file does not exist.
pub const R: Self = Self(O::RDONLY);
/// Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
pub const W: Self = Self(O::WRONLY | O::CREAT);
pub const W: Self = Self(O::TRUNC | O::CREAT | O::WRONLY);

#[inline]
pub fn as_int(self) -> c_int {
Expand Down
23 changes: 23 additions & 0 deletions test/js/node/fs/fs-writeFile-write-error-fixture.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

188 changes: 188 additions & 0 deletions test/js/node/fs/fs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,194 @@ it("writeFileSync NOT in append SHOULD truncate the file", () => {
}
});

describe("writeFile with a non-truncating flag", () => {
const flags = ["r+", "rs+", constants.O_RDWR];

it.each(flags)("writeFileSync with flag %p overwrites in place", flag => {
const path = join(tmpdirSync(), "in-place.txt");
writeFileSync(path, "0123456789");
writeFileSync(path, "ZZ", { flag });
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

it.each(flags)("promises.writeFile with flag %p overwrites in place", async flag => {
const path = join(tmpdirSync(), "in-place.txt");
writeFileSync(path, "0123456789");
await promises.writeFile(path, "ZZ", { flag });
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

it.each(flags)("fs.writeFile with flag %p overwrites in place", async flag => {
const path = join(tmpdirSync(), "in-place.txt");
writeFileSync(path, "0123456789");
const { promise, resolve, reject } = Promise.withResolvers<void>();
fs.writeFile(path, "ZZ", { flag }, err => (err ? reject(err) : resolve()));
await promise;
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

// An iterable `data` takes a separate slow path in fs.promises, with its own
// truncate.
it.each(["r+", "rs+"])("promises.writeFile of an async iterable with flag %p overwrites in place", async flag => {
const path = join(tmpdirSync(), "in-place-async-iter.txt");
writeFileSync(path, "0123456789");
await promises.writeFile(
path,
(async function* () {
yield "ZZ";
})(),
{ flag },
);
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

it.each(["r+", "rs+"])("promises.writeFile of a sync iterable with flag %p overwrites in place", async flag => {
const path = join(tmpdirSync(), "in-place-sync-iter.txt");
writeFileSync(path, "0123456789");
await promises.writeFile(
path,
(function* () {
yield "ZZ";
})(),
{ flag },
);
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

it.each(["w", "w+"])("promises.writeFile of an async iterable with flag %p still truncates", async flag => {
const path = join(tmpdirSync(), "truncating-async-iter.txt");
writeFileSync(path, "0123456789");
await promises.writeFile(
path,
(async function* () {
yield "ZZ";
})(),
{ flag },
);
expect(readFileSync(path, "utf8")).toBe("ZZ");
});

it("writeFileSync on a file descriptor does not truncate", () => {
const path = join(tmpdirSync(), "in-place-fd.txt");
writeFileSync(path, "0123456789");
const fd = openSync(path, "r+");
try {
writeFileSync(fd, "ZZ");
} finally {
closeSync(fd);
}
expect(readFileSync(path, "utf8")).toBe("ZZ23456789");
});

it.each(["w", "w+"])("writeFileSync with flag %p still truncates", flag => {
const path = join(tmpdirSync(), "truncating.txt");
writeFileSync(path, "0123456789");
writeFileSync(path, "ZZ", { flag });
expect(readFileSync(path, "utf8")).toBe("ZZ");
});

// O_APPEND writes land at the end of the file, so O_TRUNC has to empty it at
// open rather than afterwards. Skipped on Windows: openat() there picks its
// NtCreateFile disposition from O_WRONLY and ignores O_TRUNC, so this already
// yields "0123456789ZZ" on main. Separate bug, separate fix.
it.skipIf(isWindows)("writeFileSync with a numeric O_APPEND|O_TRUNC flag empties the file first", () => {
const path = join(tmpdirSync(), "append-truncating.txt");
writeFileSync(path, "0123456789");
writeFileSync(path, "ZZ", {
flag: constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_TRUNC,
});
expect(readFileSync(path, "utf8")).toBe("ZZ");
});
});

// A write that dies partway through must not leave the old tail sitting behind
// the bytes that did land. `ulimit -f 1` gives the child a 512 byte RLIMIT_FSIZE,
// and Linux's generic_write_checks() then clamps the write to the limit and fails
// the next one with EFBIG. Linux-only: BSD kernels reject the whole write instead,
// so the byte split is not portable.
describe.skipIf(!isLinux)("writeFileSync when the write fails partway", () => {
const fixture = join(import.meta.dir, "fs-writeFile-write-error-fixture.js");

async function runUnderFileSizeLimit(path: string, flag: string) {
writeFileSync(path, Buffer.alloc(2000, "B"));
await using proc = Bun.spawn({
cmd: ["/bin/sh", "-c", `ulimit -f 1; exec "$0" "$1" "$2" "$3"`, bunExe(), fixture, path, flag],
env: bunEnv,
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stderrHasError: stderr.includes("error:"), exitCode }).toEqual({ stderrHasError: false, exitCode: 0 });
return JSON.parse(stdout);
}

it.each(["default", "w", "w+"])("with flag %p the file holds only what was written", async flag => {
const path = join(tmpdirSync(), "write-error.bin");
const { code, size, written, stale } = await runUnderFileSizeLimit(path, flag);
expect({ code, stale, sizeIsOnlyWrittenBytes: size === written }).toEqual({
code: "EFBIG",
stale: 0,
sizeIsOnlyWrittenBytes: true,
});
});

// 512 new bytes over the head, the other 1488 untouched, and no resize.
it("with flag 'r+' the rest of the file survives", async () => {
const path = join(tmpdirSync(), "write-error-in-place.bin");
const { code, size, written, stale } = await runUnderFileSizeLimit(path, "r+");
expect({ code, size, written, stale }).toEqual({ code: "EFBIG", size: 2000, written: 512, stale: 1488 });
});
});

// Writes at or above the preallocate threshold take the fallocate() path, which
// grows the file before the data lands. O_APPEND then writes past the grown end,
// leaving a hole of zeroes where the data belongs.
describe("writeFile with a preallocate-sized buffer", () => {
const big = Buffer.alloc(3 * 1024 * 1024, "A");

it("appends with flag 'a'", () => {
const path = join(tmpdirSync(), "append-big.bin");
writeFileSync(path, "HEADER");
writeFileSync(path, big, { flag: "a" });
const out = readFileSync(path);
expect(out.subarray(0, 6).toString()).toBe("HEADER");
expect(out.indexOf(0)).toBe(-1);
expect(out.length).toBe(6 + big.length);
});

it("appends through a file descriptor opened with 'a'", () => {
const path = join(tmpdirSync(), "append-big-fd.bin");
writeFileSync(path, "HEADER");
const fd = openSync(path, "a");
try {
writeFileSync(fd, big);
} finally {
closeSync(fd);
}
const out = readFileSync(path);
expect(out.subarray(0, 6).toString()).toBe("HEADER");
expect(out.indexOf(0)).toBe(-1);
expect(out.length).toBe(6 + big.length);
});

it("keeps the tail of a larger file with flag 'r+'", () => {
const path = join(tmpdirSync(), "in-place-big.bin");
writeFileSync(path, Buffer.alloc(4 * 1024 * 1024, "B"));
writeFileSync(path, big, { flag: "r+" });
const out = readFileSync(path);
expect(out.subarray(0, big.length).equals(big)).toBe(true);
expect(out.indexOf("B")).toBe(big.length);
expect(out.length).toBe(4 * 1024 * 1024);
});

it("truncates a larger file with the default flag", () => {
const path = join(tmpdirSync(), "truncating-big.bin");
writeFileSync(path, Buffer.alloc(4 * 1024 * 1024, "B"));
writeFileSync(path, big);
const out = readFileSync(path);
expect(out.equals(big)).toBe(true);
});
});

describe("copyFileSync", () => {
it("should work for files < 128 KB", () => {
const tempdir = tmpdirTestMkdir();
Expand Down
Loading