Flush a saved workbook to disk before replacing the old one (#3178)

* Flush a saved workbook to disk before the rename

write_file renamed the temporary file over the workbook without sync_all, so a power loss right after a save could leave an empty or truncated file under the workbook's name. Sync the file before the rename and, on unix, sync the folder after it (best effort).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Tolerate file systems that cannot flush when saving

On Apple targets std's sync_all asks for F_FULLFSYNC, which network mounts refuse with ENOTTY or ENOTSUP. Treat exactly those errors (and ErrorKind::Unsupported) from the temp file's sync as 'cannot flush here' and carry on with the rename, as before the flush was added. All other errors still fail the save.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Treat raw error 25 as unsupported-flush only on Unix

On Windows 25 is ERROR_SEEK, a real failure that must not be skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Save: treat Apple's ENOTSUP from F_FULLFSYNC as unsupported flush

On Apple targets ENOTSUP is 45 and std leaves it uncategorized (only
EOPNOTSUPP, 102, and ENOSYS map to ErrorKind::Unsupported), so a volume
refusing F_FULLFSYNC with ENOTSUP failed the save and deleted the
temporary file. The raw code is now matched on Apple targets only;
elsewhere 45 is a different errno and stays a failed save. The check is
split into a platform-parameterised helper so each platform's codes are
tested on any host, plus an Apple-only test on the real helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Valentin KleinandClaude Opus 5.5 authored and GitHub committed 2026-11-18 08:44:04 +07:00
1 parent 807cf23b02
commit 4c388df949
2 files changed
+95 -2

No files matched your search

+36 -2
View File
@@ -1085,16 +1085,50 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
if let Some(p) = &prior {
let _ = f.set_permissions(p.clone());
}
f.write_all(bytes).and_then(|()| f.flush()).map_err(|e| {
// `sync_all` before the rename: without it a power loss right after the rename can leave
// the new name pointing at an empty or truncated file while the old workbook is gone.
// A file system that cannot flush at all (some network mounts; on Apple targets std asks
// for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename.
let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) });
f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})?;
drop(f);
std::fs::rename(&tmp, path).map_err(|e| {
// A write or rename that fails (full disk, the workbook locked by another app) leaves
// no temporary file beside the user's workbook.
let _ = std::fs::remove_file(&tmp);
EngineError::Other(format!("{path}: {e}"))
})
})?;
// Make the rename itself durable. Best effort: the workbook is already in place, so a
// directory that can't be opened or synced (some file systems) is not a failed save.
#[cfg(unix)]
{
let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
}
}
Ok(())
}
/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what
/// `fcntl(F_FULLFSYNC)` returns on such volumes; on Windows 25 is ERROR_SEEK, a real failure), on
/// Apple targets ENOTSUP (45, which std leaves uncategorized there), or an unsupported-operation
/// error (EOPNOTSUPP/ENOSYS, and ENOTSUP where it equals EOPNOTSUPP). Any other error is a real
/// failure.
#[cfg(not(target_arch = "wasm32"))]
fn full_sync_unsupported(e: &std::io::Error) -> bool {
flush_unsupported_on(e, cfg!(unix), cfg!(target_vendor = "apple"))
}
/// [`full_sync_unsupported`] for a given platform, so each platform's raw codes can be tested
/// on any host.
#[cfg(not(target_arch = "wasm32"))]
fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool {
let raw = e.raw_os_error();
(unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported
}
/// The mode a saved file gets from the file it replaces (`old`): all of it when its group was
+59
View File
@@ -344,6 +344,65 @@ fn failed_save_leaves_no_temporary_file() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A save replaces an existing workbook with exactly the new bytes, and a save into a folder
/// that doesn't exist fails without creating anything. The flush to disk before the rename is
/// not covered: a power loss can't be simulated in a unit test.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn save_writes_exact_bytes_and_fails_cleanly_without_a_folder() {
let dir = std::env::temp_dir().join(format!("gridcraft-write-exact-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dest = dir.join("Book.xlsx");
std::fs::write(&dest, b"old workbook that is longer than the new one").unwrap();
let bytes: Vec<u8> = (0..=255u8).cycle().take(100_000).collect();
write_file(dest.to_str().unwrap(), &bytes).unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), bytes);
assert!(!dir.join("Book.xlsx.sctmp").exists());
let missing = dir.join("no-such-folder").join("Book.xlsx");
assert!(write_file(missing.to_str().unwrap(), b"x").is_err());
assert!(!dir.join("no-such-folder").exists());
assert_eq!(std::fs::read(&dest).unwrap(), bytes, "the existing workbook is untouched");
let _ = std::fs::remove_dir_all(&dir);
}
/// Only "this file system cannot flush" errors are tolerated when syncing a saved file.
/// The fallback on a real network mount is not tested.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn full_sync_tolerates_only_unsupported_errors() {
use std::io::{Error, ErrorKind};
assert_eq!(full_sync_unsupported(&Error::from_raw_os_error(25)), cfg!(unix));
assert!(full_sync_unsupported(&Error::from(ErrorKind::Unsupported)));
assert!(!full_sync_unsupported(&Error::from(ErrorKind::PermissionDenied)));
assert!(!full_sync_unsupported(&Error::from(ErrorKind::StorageFull)));
assert!(!full_sync_unsupported(&Error::from_raw_os_error(28)), "ENOSPC on Linux");
assert!(!full_sync_unsupported(&Error::from_raw_os_error(5)), "EIO");
}
/// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to
/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is
/// another error (EL2NSYNC on Linux) and stays a failed save.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn full_sync_tolerates_apple_enotsup() {
use std::io::Error;
let enotsup = Error::from_raw_os_error(45);
assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple");
assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix");
assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows");
assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple");
assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple");
assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple");
}
/// The real helper on an Apple host: a raw ENOTSUP from F_FULLFSYNC is tolerated.
#[cfg(target_vendor = "apple")]
#[test]
fn full_sync_tolerates_raw_enotsup_on_apple() {
assert!(full_sync_unsupported(&std::io::Error::from_raw_os_error(45)));
}
/// While a script runs (#2178), file reads and writes are refused whatever command or
/// parameter asked for them; nesting and dropping the sandbox restore access.
#[cfg(not(target_arch = "wasm32"))]