diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 184c4fdb0..b1fc08845 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -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 diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index ad8ca40f2..626d0f952 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -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 = (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"))]