From 8df3d87d8b9d2ff1a714f89e01bf5b75d3ee0bd6 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sun, 11 Oct 2026 02:41:47 -0700 Subject: [PATCH 01/15] Add craft-atomic: crash-safe atomic write and document replacement (refs #2, fixes #14) --- Cargo.lock | 180 ++++++++++- Cargo.toml | 1 + README.md | 1 + crates/atomic/Cargo.toml | 17 + crates/atomic/README.md | 77 +++++ crates/atomic/src/lib.rs | 481 ++++++++++++++++++++++++++++ crates/atomic/tests/atomic_tests.rs | 127 ++++++++ 7 files changed, 878 insertions(+), 6 deletions(-) create mode 100644 crates/atomic/Cargo.toml create mode 100644 crates/atomic/README.md create mode 100644 crates/atomic/src/lib.rs create mode 100644 crates/atomic/tests/atomic_tests.rs diff --git a/Cargo.lock b/Cargo.lock index c98fc400b4..e1789dc529 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,7 +144,16 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", ] [[package]] @@ -153,6 +162,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -183,6 +202,30 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -283,6 +326,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -371,6 +425,29 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +dependencies = [ + "proptest", + "rustix 1.1.5", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -772,6 +849,12 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -857,6 +940,7 @@ dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core", ] [[package]] @@ -1307,7 +1391,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -1927,12 +2011,38 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.1", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -1963,6 +2073,31 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -2025,6 +2160,12 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -2113,6 +2254,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "same-file" version = "1.0.6" @@ -2446,7 +2599,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg", ] @@ -2555,6 +2708,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -2640,6 +2799,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -2891,8 +3059,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.10.0", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -2964,7 +3132,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", diff --git a/Cargo.toml b/Cargo.toml index f17a3a252e..e02d853d21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] # internal: add each crate here as `craft- = { path = "crates/" }` +craft-atomic = { path = "crates/atomic" } craft-print = { path = "crates/print" } craft-quit = { path = "crates/quit" } craft-ui = { path = "crates/ui" } diff --git a/README.md b/README.md index c60506917f..0137cfe9d5 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " io::Result<()>; + /// Rename `from` over `to`, replacing it atomically. + fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; + /// Remove a file. + fn remove(&self, path: &Path) -> io::Result<()>; + /// Flush a directory entry change to durable storage (Unix); no-op elsewhere. + fn sync_dir(&self, dir: &Path) -> io::Result<()>; + /// Copy the destination's permissions onto the temporary file before replacement. + fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()>; +} + +/// The production file system implementation. +#[derive(Debug, Clone, Copy, Default)] +pub struct RealFs; + +impl AtomicFs for RealFs { + fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).open(tmp)?; + f.write_all(bytes)?; + sync_file(&f) + } + + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + std::fs::rename(from, to) + } + + fn remove(&self, path: &Path) -> io::Result<()> { + std::fs::remove_file(path) + } + + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_file(&File::open(dir)?) + } + #[cfg(not(unix))] + { + let _ = dir; + Ok(()) + } + } + + fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { + let perms = std::fs::metadata(from)?.permissions(); + std::fs::set_permissions(to, perms) + } +} + +/// Flush `file` to stable storage (`sync_all`). +/// On Apple platforms, this issues an `F_FULLFSYNC`. Where the file system rejects full sync +/// (such as SMB network shares or virtual file systems), it falls back to a plain `fsync`. +pub fn sync_file(file: &File) -> io::Result<()> { + #[cfg(target_vendor = "apple")] + { + or_plain_fsync(file.sync_all(), || rustix::fs::fsync(file).map_err(io::Error::from)) + } + #[cfg(not(target_vendor = "apple"))] + { + file.sync_all() + } +} + +/// Returns `full`, or calls `fsync()` if `full` failed only because `F_FULLFSYNC` is unsupported. +pub fn or_plain_fsync(full: io::Result<()>, fsync: impl FnOnce() -> io::Result<()>) -> io::Result<()> { + match full { + Err(e) if full_flush_unsupported(&e) => fsync(), + other => other, + } +} + +fn full_flush_unsupported(e: &io::Error) -> bool { + const ENOTTY: i32 = 25; + const ENOTSUP: i32 = 45; + cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY)) +} + +/// Retry configuration for renames that encounter transient file locks (`PermissionDenied`). +#[derive(Debug, Clone, Copy)] +pub struct RenameRetry { + /// Number of retries after the initial attempt (0 = no retry). + pub attempts: u32, + /// Delay before the first retry in milliseconds; doubles on each subsequent attempt. + pub first_delay_ms: u64, +} + +impl RenameRetry { + /// Platform default: retry on Windows (7 attempts with 10ms exponential backoff), no-op elsewhere. + pub fn platform() -> Self { + if cfg!(windows) { Self { attempts: 7, first_delay_ms: 10 } } else { Self { attempts: 0, first_delay_ms: 0 } } + } +} + +/// Atomically writes `bytes` to `path`, replacing any existing content. +/// +/// If write or rename fails, the target file is untouched and any temporary staging file is removed. +pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> { + atomic_write_custom(&RealFs, RenameRetry::platform(), path, bytes) +} + +/// Atomically writes to `path` using a streaming writer callback `F`. +pub fn atomic_write_with(path: &Path, write_fn: F) -> io::Result<()> +where + F: FnOnce(&mut File) -> io::Result<()>, +{ + let target = resolve_symlink(path); + let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; + let dir = match target.parent() { + Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), + _ => PathBuf::from("."), + }; + std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; + + let mut tmp = None; + for _ in 0..8 { + let candidate = dir.join(temp_name(&name.to_string_lossy())); + match OpenOptions::new().write(true).create_new(true).open(&candidate) { + Ok(mut f) => { + let res = write_fn(&mut f).and_then(|()| sync_file(&f)); + drop(f); + if let Err(e) = res { + let _ = std::fs::remove_file(&candidate); + return Err(write_error(e, path, &dir)); + } + tmp = Some(candidate); + break; + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(write_error(e, path, &dir)), + } + } + + let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?; + + if target.exists() { + let _ = RealFs.copy_permissions(&target, &tmp); + } + + if let Err(e) = retry_rename(RenameRetry::platform(), || std::fs::rename(&tmp, &target)) { + let _ = std::fs::remove_file(&tmp); + return Err(rename_error(e, path)); + } + + let _ = RealFs.sync_dir(&dir); + Ok(()) +} + +/// Atomically writes `bytes` to `path` through custom [`AtomicFs`] and [`RenameRetry`]. +pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8]) -> io::Result<()> { + let target = resolve_symlink(path); + let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; + let dir = match target.parent() { + Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), + _ => PathBuf::from("."), + }; + std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; + + let mut tmp = None; + for _ in 0..8 { + let candidate = dir.join(temp_name(&name.to_string_lossy())); + match fs.write_new(&candidate, bytes) { + Ok(()) => { + tmp = Some(candidate); + break; + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => { + let _ = fs.remove(&candidate); + return Err(write_error(e, path, &dir)); + } + } + } + let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?; + + if target.exists() { + let _ = fs.copy_permissions(&target, &tmp); + } + + if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { + let _ = fs.remove(&tmp); + return Err(rename_error(e, path)); + } + + let _ = fs.sync_dir(&dir); + Ok(()) +} + +/// Exclusively creates and writes `path` without replacing existing files. +pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_new_with(path, |f| f.write_all(bytes)) +} + +/// Exclusively creates and writes `path` with a streaming writer callback `F`. +pub fn write_new_with(path: &Path, write_fn: F) -> io::Result<()> +where + F: FnOnce(&mut File) -> io::Result<()>, +{ + let target = resolve_symlink(path); + if target.exists() { + return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: file already exists", path.display()))); + } + + let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; + let dir = match target.parent() { + Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), + _ => PathBuf::from("."), + }; + std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; + + let tmp = dir.join(temp_name(&name.to_string_lossy())); + let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; + let filled = write_fn(&mut f).and_then(|()| sync_file(&f)); + drop(f); + + if let Err(e) = filled { + let _ = std::fs::remove_file(&tmp); + return Err(write_error(e, path, &dir)); + } + + #[cfg(unix)] + let placed = std::fs::hard_link(&tmp, &target).or_else(|e| { + if e.kind() == io::ErrorKind::AlreadyExists { + Err(e) + } else { + // Hard link unsupported; fall back to atomic rename if target still missing + std::fs::rename(&tmp, &target) + } + }); + #[cfg(not(unix))] + let placed = std::fs::rename(&tmp, &target); + + let _ = std::fs::remove_file(&tmp); + placed +} + +/// Retries an operation with exponential backoff while it fails with `PermissionDenied`. +pub fn retry_rename(retry: RenameRetry, mut rename: impl FnMut() -> io::Result<()>) -> io::Result<()> { + let mut delay = retry.first_delay_ms; + let mut left = retry.attempts; + loop { + match rename() { + Err(e) if e.kind() == io::ErrorKind::PermissionDenied && left > 0 => { + left -= 1; + sleep_ms(delay); + delay = delay.saturating_mul(2); + } + r => return r, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn sleep_ms(ms: u64) { + if ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(ms)); + } +} +#[cfg(target_arch = "wasm32")] +fn sleep_ms(_ms: u64) {} + +fn resolve_symlink(path: &Path) -> PathBuf { + match std::fs::symlink_metadata(path) { + Ok(m) if m.file_type().is_symlink() => std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), + _ => path.to_path_buf(), + } +} + +/// Generates a unique, hidden temporary file name beside `file`. +pub fn temp_name(file: &str) -> String { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let stem: String = file.chars().take(64).collect(); + format!(".{stem}.{}-{n}.craft_tmp", std::process::id()) +} + +fn context(e: io::Error, msg: String) -> io::Error { + io::Error::new(e.kind(), format!("{msg}: {e}")) +} + +const UNCHANGED: &str = "the original file was not changed"; + +fn write_error(e: io::Error, path: &Path, dir: &Path) -> io::Error { + let msg = match e.kind() { + io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem => { + format!("cannot save {}: the folder {} is not writable ({e}); {UNCHANGED}", path.display(), dir.display()) + } + io::ErrorKind::StorageFull => format!("cannot save {}: the disk is full ({e}); {UNCHANGED}", path.display()), + _ => format!("cannot save {}: {e}; {UNCHANGED}", path.display()), + }; + io::Error::new(e.kind(), msg) +} + +fn rename_error(e: io::Error, path: &Path) -> io::Error { + let msg = if is_cross_device(&e) { + format!("cannot save {}: the temporary file is on a different volume than the destination ({e}); {UNCHANGED}", path.display()) + } else if e.kind() == io::ErrorKind::PermissionDenied { + format!("cannot save {}: the file is locked or read-only ({e}); {UNCHANGED}", path.display()) + } else { + format!("cannot save {}: {e}; {UNCHANGED}", path.display()) + }; + io::Error::new(e.kind(), msg) +} + +fn is_cross_device(e: &io::Error) -> bool { + e.kind() == io::ErrorKind::CrossesDevices || (cfg!(unix) && e.raw_os_error() == Some(18)) || (cfg!(windows) && e.raw_os_error() == Some(17)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let d = std::env::temp_dir().join(format!("craft-atomic-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).ok(); + Self(d) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn assert_no_temp(dir: &Path) { + let leftovers: Vec<_> = std::fs::read_dir(dir) + .ok() + .map(|entries| entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".craft_tmp")).collect()) + .unwrap_or_default(); + assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); + } + + const ORIGINAL: &[u8] = b"the user's precious original document"; + + #[derive(Default)] + struct Faulty { + fail_write_after: Option, + fail_rename: Option, + locked_renames: Cell, + renames: Cell, + } + + impl AtomicFs for Faulty { + fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { + if let Some(n) = self.fail_write_after { + let mut f = OpenOptions::new().write(true).create_new(true).open(tmp)?; + f.write_all(&bytes[..n.min(bytes.len())])?; + return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); + } + RealFs.write_new(tmp, bytes) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + self.renames.set(self.renames.get() + 1); + if let Some(kind) = self.fail_rename { + return Err(io::Error::new(kind, "injected rename failure")); + } + if self.locked_renames.get() > 0 { + self.locked_renames.set(self.locked_renames.get() - 1); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: sharing violation")); + } + RealFs.rename(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.copy_permissions(from, to) + } + } + + const NO_RETRY: RenameRetry = RenameRetry { attempts: 0, first_delay_ms: 0 }; + + #[test] + fn replaces_and_creates() { + let d = TempDir::new("ok"); + let p = d.0.join("doc.craft"); + atomic_write(&p, b"first").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); + atomic_write(&p, b"second, longer").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"second, longer".to_vec())); + assert_no_temp(&d.0); + } + + #[test] + fn creates_missing_parent_folders() { + let d = TempDir::new("parent"); + let p = d.0.join("a/b/out.png"); + atomic_write(&p, b"x").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"x".to_vec())); + } + + #[test] + fn write_failure_halfway_keeps_original() { + let d = TempDir::new("write"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { fail_write_after: Some(5), ..Default::default() }; + let e = atomic_write_custom(&fs, NO_RETRY, &p, &[7u8; 4096]); + assert!(e.is_err()); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_eq!(fs.renames.get(), 0); + assert_no_temp(&d.0); + } + + #[test] + fn rename_failure_keeps_original() { + let d = TempDir::new("rename"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { fail_rename: Some(io::ErrorKind::Other), ..Default::default() }; + assert!(atomic_write_custom(&fs, NO_RETRY, &p, b"new").is_err()); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_no_temp(&d.0); + } + + #[test] + fn locked_target_rename_is_retried() { + let d = TempDir::new("locked"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; + atomic_write_custom(&fs, RenameRetry { attempts: 3, first_delay_ms: 1 }, &p, b"new").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"new".to_vec())); + assert_eq!(fs.renames.get(), 3); + assert_no_temp(&d.0); + } + + #[test] + fn write_new_never_overwrites_existing() { + let d = TempDir::new("new"); + let p = d.0.join("file.craft"); + write_new(&p, b"first").ok(); + assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); + let res = write_new(&p, b"second"); + assert!(res.is_err()); + assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); + assert_no_temp(&d.0); + } +} diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs new file mode 100644 index 0000000000..0fcdf17e3e --- /dev/null +++ b/crates/atomic/tests/atomic_tests.rs @@ -0,0 +1,127 @@ +use craft_atomic::{atomic_write, atomic_write_with, or_plain_fsync, write_new_with}; +use std::cell::Cell; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +struct TempDir(PathBuf); +impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let d = std::env::temp_dir().join(format!("craft-atomic-int-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).ok(); + Self(d) + } +} +impl Drop for TempDir { + fn drop(&mut self) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn assert_no_temp(dir: &Path) { + let leftovers: Vec<_> = std::fs::read_dir(dir) + .ok() + .map(|entries| entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".craft_tmp")).collect()) + .unwrap_or_default(); + assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); +} + +const ORIGINAL: &[u8] = b"original precious document"; + +#[test] +fn atomic_write_with_streaming_writer() { + let d = TempDir::new("stream"); + let p = d.0.join("doc.dat"); + std::fs::write(&p, ORIGINAL).ok(); + + atomic_write_with(&p, |f| { + f.write_all(b"chunk1 ")?; + f.write_all(b"chunk2") + }) + .ok(); + + assert_eq!(std::fs::read(&p).ok(), Some(b"chunk1 chunk2".to_vec())); + assert_no_temp(&d.0); +} + +#[test] +fn write_new_with_streaming_writer() { + let d = TempDir::new("write_new_stream"); + let p = d.0.join("new.dat"); + + write_new_with(&p, |f| f.write_all(b"new content")).ok(); + + assert_eq!(std::fs::read(&p).ok(), Some(b"new content".to_vec())); + assert_no_temp(&d.0); + + // Second write to existing file must fail with AlreadyExists + let res = write_new_with(&p, |f| f.write_all(b"overwritten?")); + assert!(res.is_err()); + assert_eq!(std::fs::read(&p).ok(), Some(b"new content".to_vec())); +} + +#[test] +fn streaming_failure_aborts_and_keeps_original() { + let d = TempDir::new("stream_fail"); + let p = d.0.join("doc.dat"); + std::fs::write(&p, ORIGINAL).ok(); + + let res = atomic_write_with(&p, |f| { + f.write_all(b"half a file")?; + Err(io::Error::new(io::ErrorKind::StorageFull, "disk full")) + }); + + assert!(res.is_err()); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_no_temp(&d.0); +} + +#[test] +fn apple_full_fsync_fallback_behavior() { + let refused = |errno| Err(io::Error::from_raw_os_error(errno)); + for (errno, name) in [(45, "ENOTSUP (SMB)"), (25, "ENOTTY")] { + let fsynced = Cell::new(false); + let r = or_plain_fsync(refused(errno), || { + fsynced.set(true); + Ok(()) + }); + let apple = cfg!(target_vendor = "apple"); + assert_eq!(r.is_ok(), apple, "{name}"); + assert_eq!(fsynced.get(), apple, "{name}: fsync fallback only runs on Apple"); + } + + // Unrelated errors (e.g. EIO = 5) must not fallback + let r = or_plain_fsync(refused(5), || panic!("should not run for EIO")); + assert_eq!(r.map_err(|e| e.raw_os_error()), Err(Some(5))); +} + +#[cfg(unix)] +#[test] +fn mode_and_symlink_preservation() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("mode_symlink"); + + // Permissions + let p = d.0.join("secret.key"); + std::fs::write(&p, ORIGINAL).ok(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).ok(); + atomic_write(&p, b"updated secret").ok(); + let mode = std::fs::metadata(&p).map(|m| m.permissions().mode() & 0o777).ok(); + assert_eq!(mode, Some(0o600)); + + // Symlink + let real = d.0.join("real.txt"); + let link = d.0.join("link.txt"); + std::fs::write(&real, ORIGINAL).ok(); + std::os::unix::fs::symlink(&real, &link).ok(); + atomic_write(&link, b"through symlink").ok(); + assert!(std::fs::symlink_metadata(&link).map(|m| m.file_type().is_symlink()).unwrap_or(false)); + assert_eq!(std::fs::read(&real).ok(), Some(b"through symlink".to_vec())); +} From 818c0c0753b901eee5b8438e58fec1bf61be1b10 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:21:01 +0000 Subject: [PATCH 02/15] Share one replace path between the byte and streaming writers atomic_write, atomic_write_with and atomic_write_custom all run through one internal function that takes the AtomicFs, the RenameRetry and a writer callback, so fault injection also covers streaming writes. AtomicFs creates and flushes the temporary file (create_new, sync) instead of writing a byte slice. --- crates/atomic/src/lib.rs | 159 ++++++++++++++++++++------------------- 1 file changed, 83 insertions(+), 76 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 65d86ce0f0..717808e2bb 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -28,8 +28,10 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// File-system operations performed by atomic writes. /// [`RealFs`] provides the production implementation; test suites implement this to inject faults. pub trait AtomicFs { - /// Create `tmp` (which must not exist), write all `bytes`, and flush to disk. - fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()>; + /// Create `path`, which must not exist, and open it for writing. + fn create_new(&self, path: &Path) -> io::Result; + /// Flush a written file to durable storage. + fn sync(&self, file: &File) -> io::Result<()>; /// Rename `from` over `to`, replacing it atomically. fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; /// Remove a file. @@ -45,10 +47,12 @@ pub trait AtomicFs { pub struct RealFs; impl AtomicFs for RealFs { - fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { - let mut f = OpenOptions::new().write(true).create_new(true).open(tmp)?; - f.write_all(bytes)?; - sync_file(&f) + fn create_new(&self, path: &Path) -> io::Result { + OpenOptions::new().write(true).create_new(true).open(path) + } + + fn sync(&self, file: &File) -> io::Result<()> { + sync_file(file) } fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { @@ -133,74 +137,22 @@ pub fn atomic_write_with(path: &Path, write_fn: F) -> io::Result<()> where F: FnOnce(&mut File) -> io::Result<()>, { - let target = resolve_symlink(path); - let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; - let dir = match target.parent() { - Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), - _ => PathBuf::from("."), - }; - std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; - - let mut tmp = None; - for _ in 0..8 { - let candidate = dir.join(temp_name(&name.to_string_lossy())); - match OpenOptions::new().write(true).create_new(true).open(&candidate) { - Ok(mut f) => { - let res = write_fn(&mut f).and_then(|()| sync_file(&f)); - drop(f); - if let Err(e) = res { - let _ = std::fs::remove_file(&candidate); - return Err(write_error(e, path, &dir)); - } - tmp = Some(candidate); - break; - } - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(write_error(e, path, &dir)), - } - } - - let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?; - - if target.exists() { - let _ = RealFs.copy_permissions(&target, &tmp); - } - - if let Err(e) = retry_rename(RenameRetry::platform(), || std::fs::rename(&tmp, &target)) { - let _ = std::fs::remove_file(&tmp); - return Err(rename_error(e, path)); - } - - let _ = RealFs.sync_dir(&dir); - Ok(()) + replace(&RealFs, RenameRetry::platform(), path, write_fn) } /// Atomically writes `bytes` to `path` through custom [`AtomicFs`] and [`RenameRetry`]. pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8]) -> io::Result<()> { + replace(fs, retry, path, |f| f.write_all(bytes)) +} + +/// The replace path behind every `atomic_write*` function: stage the new content beside the +/// target, then rename it over the target. +fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { let target = resolve_symlink(path); - let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; - let dir = match target.parent() { - Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), - _ => PathBuf::from("."), - }; + let (dir, name) = split(&target, path)?; std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; - let mut tmp = None; - for _ in 0..8 { - let candidate = dir.join(temp_name(&name.to_string_lossy())); - match fs.write_new(&candidate, bytes) { - Ok(()) => { - tmp = Some(candidate); - break; - } - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, - Err(e) => { - let _ = fs.remove(&candidate); - return Err(write_error(e, path, &dir)); - } - } - } - let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?; + let tmp = stage(fs, &dir, &name, path, fill)?; if target.exists() { let _ = fs.copy_permissions(&target, &tmp); @@ -215,6 +167,39 @@ pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, b Ok(()) } +/// The folder `target` is in and its file name. `path` is the caller's path, for the error. +fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { + let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; + let dir = match target.parent() { + Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), + _ => PathBuf::from("."), + }; + Ok((dir, name.to_string_lossy().into_owned())) +} + +/// Create a temporary file in `dir`, fill it with `fill` and flush it. A leftover file with the +/// same name is skipped. When filling or flushing fails, the temporary file is removed. +fn stage(fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result { + for _ in 0..8 { + let tmp = dir.join(temp_name(name)); + let mut file = match fs.create_new(&tmp) { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(write_error(e, path, dir)), + }; + let written = fill(&mut file).and_then(|()| fs.sync(&file)); + drop(file); + return match written { + Ok(()) => Ok(tmp), + Err(e) => { + let _ = fs.remove(&tmp); + Err(write_error(e, path, dir)) + } + }; + } + Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display()))) +} + /// Exclusively creates and writes `path` without replacing existing files. pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { write_new_with(path, |f| f.write_all(bytes)) @@ -373,20 +358,21 @@ mod tests { #[derive(Default)] struct Faulty { - fail_write_after: Option, + fail_sync: bool, fail_rename: Option, locked_renames: Cell, renames: Cell, } impl AtomicFs for Faulty { - fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> { - if let Some(n) = self.fail_write_after { - let mut f = OpenOptions::new().write(true).create_new(true).open(tmp)?; - f.write_all(&bytes[..n.min(bytes.len())])?; + fn create_new(&self, path: &Path) -> io::Result { + RealFs.create_new(path) + } + fn sync(&self, file: &File) -> io::Result<()> { + if self.fail_sync { return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); } - RealFs.write_new(tmp, bytes) + RealFs.sync(file) } fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { self.renames.set(self.renames.get() + 1); @@ -432,18 +418,39 @@ mod tests { } #[test] - fn write_failure_halfway_keeps_original() { + fn failed_flush_keeps_original() { let d = TempDir::new("write"); let p = d.0.join("doc.craft"); std::fs::write(&p, ORIGINAL).ok(); - let fs = Faulty { fail_write_after: Some(5), ..Default::default() }; + let fs = Faulty { fail_sync: true, ..Default::default() }; let e = atomic_write_custom(&fs, NO_RETRY, &p, &[7u8; 4096]); - assert!(e.is_err()); + assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::StorageFull)); assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); assert_eq!(fs.renames.get(), 0); assert_no_temp(&d.0); } + #[test] + fn streaming_writes_go_through_the_injected_fs() { + let d = TempDir::new("stream"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let chunks = |f: &mut File| { + f.write_all(b"chunk1 ")?; + f.write_all(b"chunk2") + }; + let fs = Faulty { fail_sync: true, ..Default::default() }; + assert!(replace(&fs, NO_RETRY, &p, chunks).is_err()); + let fs = Faulty { fail_rename: Some(io::ErrorKind::Other), ..Default::default() }; + assert!(replace(&fs, NO_RETRY, &p, chunks).is_err()); + assert_eq!(fs.renames.get(), 1); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_no_temp(&d.0); + let fs = Faulty::default(); + assert!(replace(&fs, NO_RETRY, &p, chunks).is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"chunk1 chunk2".to_vec())); + } + #[test] fn rename_failure_keeps_original() { let d = TempDir::new("rename"); From 9e160690fcad442641f0012d5e776816dae3b515 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:21:59 +0000 Subject: [PATCH 03/15] Never replace an existing file in write_new write_new_with gives the staged file its name with a hard link on every platform. Where hard links fail for any reason other than an existing target (FAT/exFAT, some SMB and FUSE volumes), it copies the staged content into a file opened with create_new. It shares the temporary-file retry, error context and folder flush with the replace path, and its errors only mention an original file when there is one. --- crates/atomic/src/lib.rs | 182 +++++++++++++++++++++++++++++---------- 1 file changed, 136 insertions(+), 46 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 717808e2bb..2ac001b9a6 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -34,6 +34,8 @@ pub trait AtomicFs { fn sync(&self, file: &File) -> io::Result<()>; /// Rename `from` over `to`, replacing it atomically. fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; + /// Give the file `from` the second name `to`; fails with `AlreadyExists` when `to` exists. + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()>; /// Remove a file. fn remove(&self, path: &Path) -> io::Result<()>; /// Flush a directory entry change to durable storage (Unix); no-op elsewhere. @@ -59,6 +61,10 @@ impl AtomicFs for RealFs { std::fs::rename(from, to) } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + std::fs::hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { std::fs::remove_file(path) } @@ -151,16 +157,17 @@ fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce let target = resolve_symlink(path); let (dir, name) = split(&target, path)?; std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; + let existed = target.exists(); - let tmp = stage(fs, &dir, &name, path, fill)?; + let tmp = stage(fs, &dir, &name, path, existed, fill)?; - if target.exists() { + if existed { let _ = fs.copy_permissions(&target, &tmp); } if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { let _ = fs.remove(&tmp); - return Err(rename_error(e, path)); + return Err(rename_error(e, path, existed)); } let _ = fs.sync_dir(&dir); @@ -178,14 +185,22 @@ fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { } /// Create a temporary file in `dir`, fill it with `fill` and flush it. A leftover file with the -/// same name is skipped. When filling or flushing fails, the temporary file is removed. -fn stage(fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result { +/// same name is skipped. When filling or flushing fails, the temporary file is removed. `existed` +/// says whether the error may report an original file as unchanged. +fn stage( + fs: &dyn AtomicFs, + dir: &Path, + name: &str, + path: &Path, + existed: bool, + fill: impl FnOnce(&mut File) -> io::Result<()>, +) -> io::Result { for _ in 0..8 { let tmp = dir.join(temp_name(name)); let mut file = match fs.create_new(&tmp) { Ok(f) => f, Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(write_error(e, path, dir)), + Err(e) => return Err(write_error(e, path, dir, existed)), }; let written = fill(&mut file).and_then(|()| fs.sync(&file)); drop(file); @@ -193,7 +208,7 @@ fn stage(fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, fill: impl FnOn Ok(()) => Ok(tmp), Err(e) => { let _ = fs.remove(&tmp); - Err(write_error(e, path, dir)) + Err(write_error(e, path, dir, existed)) } }; } @@ -210,42 +225,52 @@ pub fn write_new_with(path: &Path, write_fn: F) -> io::Result<()> where F: FnOnce(&mut File) -> io::Result<()>, { - let target = resolve_symlink(path); - if target.exists() { - return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: file already exists", path.display()))); - } + create(&RealFs, path, write_fn) +} - let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; - let dir = match target.parent() { - Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), - _ => PathBuf::from("."), - }; +/// Exclusively creates and writes `bytes` to `path` through a custom [`AtomicFs`]. +pub fn write_new_custom(fs: &dyn AtomicFs, path: &Path, bytes: &[u8]) -> io::Result<()> { + create(fs, path, |f| f.write_all(bytes)) +} + +/// The create path behind every `write_new*` function: stage the content beside the target, +/// then give it the target's name with a hard link, which fails rather than replace a file that +/// appeared in the meantime. Volumes without hard links get a copy into a newly created file. +fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { + let target = resolve_symlink(path); + let (dir, name) = split(&target, path)?; + if target.exists() { + return Err(write_error(io::Error::from(io::ErrorKind::AlreadyExists), path, &dir, true)); + } std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; - let tmp = dir.join(temp_name(&name.to_string_lossy())); - let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; - let filled = write_fn(&mut f).and_then(|()| sync_file(&f)); - drop(f); + let tmp = stage(fs, &dir, &name, path, false, fill)?; - if let Err(e) = filled { - let _ = std::fs::remove_file(&tmp); - return Err(write_error(e, path, &dir)); + let placed = match fs.hard_link(&tmp, &target) { + Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(fs, &tmp, &target), + linked => linked, + }; + let _ = fs.remove(&tmp); + if let Err(e) = placed { + // A file that appeared in the meantime is someone else's and stays as it is. + let existed = e.kind() == io::ErrorKind::AlreadyExists; + return Err(write_error(e, path, &dir, existed)); } - #[cfg(unix)] - let placed = std::fs::hard_link(&tmp, &target).or_else(|e| { - if e.kind() == io::ErrorKind::AlreadyExists { - Err(e) - } else { - // Hard link unsupported; fall back to atomic rename if target still missing - std::fs::rename(&tmp, &target) - } - }); - #[cfg(not(unix))] - let placed = std::fs::rename(&tmp, &target); + let _ = fs.sync_dir(&dir); + Ok(()) +} - let _ = std::fs::remove_file(&tmp); - placed +/// Copy `tmp` into `target`, which must not exist yet, and flush it. A partly written `target` is +/// removed. +fn copy_new(fs: &dyn AtomicFs, tmp: &Path, target: &Path) -> io::Result<()> { + let mut to = fs.create_new(target)?; + let copied = File::open(tmp).and_then(|mut from| io::copy(&mut from, &mut to)).and_then(|_| fs.sync(&to)); + drop(to); + if copied.is_err() { + let _ = fs.remove(target); + } + copied } /// Retries an operation with exponential backoff while it fails with `PermissionDenied`. @@ -292,26 +317,32 @@ fn context(e: io::Error, msg: String) -> io::Error { io::Error::new(e.kind(), format!("{msg}: {e}")) } -const UNCHANGED: &str = "the original file was not changed"; +/// The end of an error message: whether an original file was left as it was. +fn unchanged(existed: bool) -> &'static str { + if existed { "; the original file was not changed" } else { "" } +} -fn write_error(e: io::Error, path: &Path, dir: &Path) -> io::Error { +fn write_error(e: io::Error, path: &Path, dir: &Path, existed: bool) -> io::Error { + let kept = unchanged(existed); let msg = match e.kind() { + io::ErrorKind::AlreadyExists => format!("cannot save {}: the file already exists{kept}", path.display()), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem => { - format!("cannot save {}: the folder {} is not writable ({e}); {UNCHANGED}", path.display(), dir.display()) + format!("cannot save {}: the folder {} is not writable ({e}){kept}", path.display(), dir.display()) } - io::ErrorKind::StorageFull => format!("cannot save {}: the disk is full ({e}); {UNCHANGED}", path.display()), - _ => format!("cannot save {}: {e}; {UNCHANGED}", path.display()), + io::ErrorKind::StorageFull => format!("cannot save {}: the disk is full ({e}){kept}", path.display()), + _ => format!("cannot save {}: {e}{kept}", path.display()), }; io::Error::new(e.kind(), msg) } -fn rename_error(e: io::Error, path: &Path) -> io::Error { +fn rename_error(e: io::Error, path: &Path, existed: bool) -> io::Error { + let kept = unchanged(existed); let msg = if is_cross_device(&e) { - format!("cannot save {}: the temporary file is on a different volume than the destination ({e}); {UNCHANGED}", path.display()) + format!("cannot save {}: the temporary file is on a different volume than the destination ({e}){kept}", path.display()) } else if e.kind() == io::ErrorKind::PermissionDenied { - format!("cannot save {}: the file is locked or read-only ({e}); {UNCHANGED}", path.display()) + format!("cannot save {}: the file is locked or read-only ({e}){kept}", path.display()) } else { - format!("cannot save {}: {e}; {UNCHANGED}", path.display()) + format!("cannot save {}: {e}{kept}", path.display()) }; io::Error::new(e.kind(), msg) } @@ -359,9 +390,15 @@ mod tests { #[derive(Default)] struct Faulty { fail_sync: bool, + /// Syncs fail once this many have succeeded. + syncs_before_failure: Option, + syncs: Cell, fail_rename: Option, locked_renames: Cell, renames: Cell, + no_hard_links: bool, + /// Another process creates the target just before the hard link. + created_meanwhile: Option<&'static [u8]>, } impl AtomicFs for Faulty { @@ -369,7 +406,8 @@ mod tests { RealFs.create_new(path) } fn sync(&self, file: &File) -> io::Result<()> { - if self.fail_sync { + let done = self.syncs.replace(self.syncs.get() + 1); + if self.fail_sync || self.syncs_before_failure.is_some_and(|n| done >= n) { return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); } RealFs.sync(file) @@ -385,6 +423,15 @@ mod tests { } RealFs.rename(from, to) } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + if let Some(bytes) = self.created_meanwhile { + std::fs::write(to, bytes)?; + } + if self.no_hard_links { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: hard links not supported")); + } + RealFs.hard_link(from, to) + } fn remove(&self, path: &Path) -> io::Result<()> { RealFs.remove(path) } @@ -485,4 +532,47 @@ mod tests { assert_eq!(std::fs::read(&p).ok(), Some(b"first".to_vec())); assert_no_temp(&d.0); } + + #[test] + fn write_new_copies_where_hard_links_fail_and_never_replaces() { + let d = TempDir::new("new-copy"); + let p = d.0.join("export.png"); + let fs = Faulty { no_hard_links: true, ..Default::default() }; + assert!(create(&fs, &p, |f| f.write_all(b"copied")).is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"copied".to_vec())); + assert_no_temp(&d.0); + + // A file that appears after the existence check is kept, whether the copy or the hard + // link finds it. + for no_hard_links in [true, false] { + let p = d.0.join(format!("raced-{no_hard_links}.png")); + let fs = Faulty { no_hard_links, created_meanwhile: Some(ORIGINAL), ..Default::default() }; + let e = create(&fs, &p, |f| f.write_all(b"mine")); + assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists)); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_eq!(fs.renames.get(), 0); + } + assert_no_temp(&d.0); + + // A failed new file has no original to speak of. + let p = d.0.join("full.png"); + let fs = Faulty { fail_sync: true, ..Default::default() }; + let msg = create(&fs, &p, |f| f.write_all(b"x")).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(msg.contains("disk is full") && !msg.contains("original"), "{msg}"); + assert!(!p.exists()); + assert_no_temp(&d.0); + } + + #[test] + fn a_failed_copy_leaves_no_partial_file() { + let d = TempDir::new("new-copy-fails"); + let p = d.0.join("export.png"); + // The temporary file flushes; the copy made in its place does not. + let fs = Faulty { no_hard_links: true, syncs_before_failure: Some(1), ..Default::default() }; + let e = write_new_custom(&fs, &p, b"copied"); + assert_eq!(e.map_err(|e| e.kind()), Err(io::ErrorKind::StorageFull)); + assert_eq!(fs.syncs.get(), 2); + assert!(!p.exists()); + assert_no_temp(&d.0); + } } From fb26a9f90fb1baf41d6e75a08a236c9be5f9a14e Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:22:08 +0000 Subject: [PATCH 04/15] Report a missing folder instead of creating it A save into a folder that does not exist fails with an error naming the folder, so a save to an unmounted network share does not create a local folder in its place. --- crates/atomic/src/lib.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 2ac001b9a6..79f8aec828 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -156,7 +156,6 @@ pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, b fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { let target = resolve_symlink(path); let (dir, name) = split(&target, path)?; - std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; let existed = target.exists(); let tmp = stage(fs, &dir, &name, path, existed, fill)?; @@ -242,7 +241,6 @@ fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Re if target.exists() { return Err(write_error(io::Error::from(io::ErrorKind::AlreadyExists), path, &dir, true)); } - std::fs::create_dir_all(&dir).map_err(|e| context(e, format!("cannot create the folder {}", dir.display())))?; let tmp = stage(fs, &dir, &name, path, false, fill)?; @@ -313,10 +311,6 @@ pub fn temp_name(file: &str) -> String { format!(".{stem}.{}-{n}.craft_tmp", std::process::id()) } -fn context(e: io::Error, msg: String) -> io::Error { - io::Error::new(e.kind(), format!("{msg}: {e}")) -} - /// The end of an error message: whether an original file was left as it was. fn unchanged(existed: bool) -> &'static str { if existed { "; the original file was not changed" } else { "" } @@ -326,6 +320,7 @@ fn write_error(e: io::Error, path: &Path, dir: &Path, existed: bool) -> io::Erro let kept = unchanged(existed); let msg = match e.kind() { io::ErrorKind::AlreadyExists => format!("cannot save {}: the file already exists{kept}", path.display()), + io::ErrorKind::NotFound => format!("cannot save {}: the folder {} does not exist ({e}){kept}", path.display(), dir.display()), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem => { format!("cannot save {}: the folder {} is not writable ({e}){kept}", path.display(), dir.display()) } @@ -457,11 +452,15 @@ mod tests { } #[test] - fn creates_missing_parent_folders() { + fn a_missing_folder_is_an_error_naming_it() { let d = TempDir::new("parent"); - let p = d.0.join("a/b/out.png"); - atomic_write(&p, b"x").ok(); - assert_eq!(std::fs::read(&p).ok(), Some(b"x".to_vec())); + let folder = d.0.join("a"); + let p = folder.join("b/out.png"); + for r in [atomic_write(&p, b"x"), write_new(&p, b"x")] { + let msg = r.err().map(|e| e.to_string()).unwrap_or_default(); + assert!(msg.contains(&folder.join("b").display().to_string()), "{msg}"); + } + assert!(!folder.exists(), "no folder is created"); } #[test] From 658ca37c8ea74dd2f8e678231d8e674c9d466844 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:22:21 +0000 Subject: [PATCH 05/15] Follow symbolic links without canonicalize The target is found by reading links one hop at a time, resolving relative links against the link's folder. A dangling link writes the file it names and stays a link, and a loop of links is an error. --- crates/atomic/src/lib.rs | 28 ++++++++++++++++++++++------ crates/atomic/tests/atomic_tests.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 79f8aec828..7506d58fba 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -154,7 +154,7 @@ pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, b /// The replace path behind every `atomic_write*` function: stage the new content beside the /// target, then rename it over the target. fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { - let target = resolve_symlink(path); + let target = resolve_links(path)?; let (dir, name) = split(&target, path)?; let existed = target.exists(); @@ -236,7 +236,7 @@ pub fn write_new_custom(fs: &dyn AtomicFs, path: &Path, bytes: &[u8]) -> io::Res /// then give it the target's name with a hard link, which fails rather than replace a file that /// appeared in the meantime. Volumes without hard links get a copy into a newly created file. fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { - let target = resolve_symlink(path); + let target = resolve_links(path)?; let (dir, name) = split(&target, path)?; if target.exists() { return Err(write_error(io::Error::from(io::ErrorKind::AlreadyExists), path, &dir, true)); @@ -296,11 +296,27 @@ fn sleep_ms(ms: u64) { #[cfg(target_arch = "wasm32")] fn sleep_ms(_ms: u64) {} -fn resolve_symlink(path: &Path) -> PathBuf { - match std::fs::symlink_metadata(path) { - Ok(m) if m.file_type().is_symlink() => std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()), - _ => path.to_path_buf(), +/// Symbolic links followed before giving up (a loop, or an absurd chain). +const MAX_LINKS: usize = 40; + +/// The file a chain of symbolic links ends at (`path` itself when it is not a link), so the link +/// is kept and the file it names is written. A dangling link resolves to the missing file it +/// names, which is then created. +fn resolve_links(path: &Path) -> io::Result { + let mut p = path.to_path_buf(); + for _ in 0..MAX_LINKS { + match std::fs::symlink_metadata(&p) { + Ok(m) if m.file_type().is_symlink() => { + let to = std::fs::read_link(&p).map_err(|e| io::Error::new(e.kind(), format!("cannot save {}: {e}", path.display())))?; + p = match p.parent() { + Some(dir) if to.is_relative() => dir.join(to), + _ => to, + }; + } + _ => return Ok(p), + } } + Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } /// Generates a unique, hidden temporary file name beside `file`. diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index 0fcdf17e3e..8f9f3323e0 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -1,4 +1,4 @@ -use craft_atomic::{atomic_write, atomic_write_with, or_plain_fsync, write_new_with}; +use craft_atomic::{atomic_write, atomic_write_with, or_plain_fsync, write_new, write_new_with}; use std::cell::Cell; use std::io::{self, Write}; use std::path::{Path, PathBuf}; @@ -125,3 +125,30 @@ fn mode_and_symlink_preservation() { assert!(std::fs::symlink_metadata(&link).map(|m| m.file_type().is_symlink()).unwrap_or(false)); assert_eq!(std::fs::read(&real).ok(), Some(b"through symlink".to_vec())); } + +#[cfg(unix)] +#[test] +fn dangling_relative_symlink_stays_a_link() { + let d = TempDir::new("dangling"); + std::fs::create_dir(d.0.join("real")).ok(); + let link = d.0.join("link.txt"); + std::os::unix::fs::symlink("real/doc.txt", &link).ok(); + + assert!(atomic_write(&link, b"created through the link").is_ok()); + assert!(std::fs::symlink_metadata(&link).map(|m| m.file_type().is_symlink()).unwrap_or(false)); + assert_eq!(std::fs::read(d.0.join("real/doc.txt")).ok(), Some(b"created through the link".to_vec())); + assert_no_temp(&d.0); + assert_no_temp(&d.0.join("real")); +} + +#[cfg(unix)] +#[test] +fn symlink_loop_is_an_error() { + let d = TempDir::new("loop"); + std::os::unix::fs::symlink("b", d.0.join("a")).ok(); + std::os::unix::fs::symlink("a", d.0.join("b")).ok(); + assert!(atomic_write(&d.0.join("a"), b"x").is_err_and(|e| e.to_string().starts_with("cannot save") && e.to_string().contains("symbolic links"))); + assert!(write_new(&d.0.join("a"), b"x").is_err()); + assert!(std::fs::symlink_metadata(d.0.join("a")).map(|m| m.file_type().is_symlink()).unwrap_or(false)); + assert_no_temp(&d.0); +} From d78b3520042b0f5509d2d3bc17c2c1aab2a50eb3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:22:34 +0000 Subject: [PATCH 06/15] Refuse to replace a file the user cannot write (Unix) A rename needs only a writable folder, so a read-only file would be replaced where writing it in place would fail. Before staging, the existing file is opened for writing without truncating; when that fails the save fails with a read-only error. --- crates/atomic/src/lib.rs | 30 ++++++++++++++++++++++++++++- crates/atomic/tests/atomic_tests.rs | 18 +++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 7506d58fba..e71431342e 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -156,7 +156,11 @@ pub fn atomic_write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, b fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { let target = resolve_links(path)?; let (dir, name) = split(&target, path)?; - let existed = target.exists(); + let existing = std::fs::metadata(&target).ok(); + let existed = existing.is_some(); + if existing.as_ref().is_some_and(|m| m.is_file()) { + check_writable(&target).map_err(|e| read_only_error(e, path))?; + } let tmp = stage(fs, &dir, &name, path, existed, fill)?; @@ -173,6 +177,19 @@ fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce Ok(()) } +/// A rename replaces a file the user can't write (Unix only needs the folder to be writable), so +/// refuse, as writing it in place would. Opening for writing without truncating changes nothing. +#[cfg(unix)] +fn check_writable(target: &Path) -> io::Result<()> { + OpenOptions::new().write(true).open(target).map(drop) +} + +/// Windows refuses to rename over a read-only file by itself. +#[cfg(not(unix))] +fn check_writable(_: &Path) -> io::Result<()> { + Ok(()) +} + /// The folder `target` is in and its file name. `path` is the caller's path, for the error. fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; @@ -346,6 +363,17 @@ fn write_error(e: io::Error, path: &Path, dir: &Path, existed: bool) -> io::Erro io::Error::new(e.kind(), msg) } +fn read_only_error(e: io::Error, path: &Path) -> io::Error { + let kept = unchanged(true); + let msg = match e.kind() { + io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem => { + format!("cannot save {}: the file is read-only ({e}){kept}", path.display()) + } + _ => format!("cannot save {}: {e}{kept}", path.display()), + }; + io::Error::new(e.kind(), msg) +} + fn rename_error(e: io::Error, path: &Path, existed: bool) -> io::Error { let kept = unchanged(existed); let msg = if is_cross_device(&e) { diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index 8f9f3323e0..ba6e27ae67 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -152,3 +152,21 @@ fn symlink_loop_is_an_error() { assert!(std::fs::symlink_metadata(d.0.join("a")).map(|m| m.file_type().is_symlink()).unwrap_or(false)); assert_no_temp(&d.0); } + +#[cfg(unix)] +#[test] +fn read_only_target_is_not_replaced() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("read_only"); + let p = d.0.join("locked.txt"); + std::fs::write(&p, ORIGINAL).ok(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o444)).ok(); + // Root may write the file anyway; the check only means something for an ordinary user. + if std::fs::OpenOptions::new().write(true).open(&p).is_ok() { + return; + } + let msg = atomic_write(&p, b"new").err().map(|e| e.to_string()).unwrap_or_default(); + assert!(msg.contains("read-only"), "{msg}"); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_no_temp(&d.0); +} From 253fd775f0ea48385112a0b3acce27444cfaec72 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:23:10 +0000 Subject: [PATCH 07/15] Set the replaced file's permissions on the open temporary file The original's permissions are applied to the temporary file before it is flushed, and a failure fails the save instead of being ignored. --- crates/atomic/src/lib.rs | 71 ++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 25 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index e71431342e..c1e9375000 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -40,8 +40,8 @@ pub trait AtomicFs { fn remove(&self, path: &Path) -> io::Result<()>; /// Flush a directory entry change to durable storage (Unix); no-op elsewhere. fn sync_dir(&self, dir: &Path) -> io::Result<()>; - /// Copy the destination's permissions onto the temporary file before replacement. - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()>; + /// Give the open temporary file the permissions of the file it replaces. + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()>; } /// The production file system implementation. @@ -81,9 +81,8 @@ impl AtomicFs for RealFs { } } - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { - let perms = std::fs::metadata(from)?.permissions(); - std::fs::set_permissions(to, perms) + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + file.set_permissions(perms) } } @@ -162,11 +161,7 @@ fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce check_writable(&target).map_err(|e| read_only_error(e, path))?; } - let tmp = stage(fs, &dir, &name, path, existed, fill)?; - - if existed { - let _ = fs.copy_permissions(&target, &tmp); - } + let tmp = stage(fs, &dir, &name, path, existing.as_ref(), fill)?; if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { let _ = fs.remove(&tmp); @@ -200,17 +195,20 @@ fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> { Ok((dir, name.to_string_lossy().into_owned())) } -/// Create a temporary file in `dir`, fill it with `fill` and flush it. A leftover file with the -/// same name is skipped. When filling or flushing fails, the temporary file is removed. `existed` -/// says whether the error may report an original file as unchanged. +/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions of the file it +/// replaces (`replaced`, Unix) and flush it. A leftover file with the same name is skipped. When +/// any step fails, the temporary file is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, - existed: bool, + replaced: Option<&std::fs::Metadata>, fill: impl FnOnce(&mut File) -> io::Result<()>, ) -> io::Result { + let existed = replaced.is_some(); + // Windows files carry only a read-only flag, and a read-only file can't be replaced. + let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions()); for _ in 0..8 { let tmp = dir.join(temp_name(name)); let mut file = match fs.create_new(&tmp) { @@ -218,15 +216,15 @@ fn stage( Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(write_error(e, path, dir, existed)), }; - let written = fill(&mut file).and_then(|()| fs.sync(&file)); + let written = fill(&mut file) + .map_err(|e| write_error(e, path, dir, existed)) + .and_then(|()| perms.map_or(Ok(()), |p| fs.set_permissions(&file, p).map_err(|e| permissions_error(e, path)))) + .and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed))); drop(file); - return match written { - Ok(()) => Ok(tmp), - Err(e) => { - let _ = fs.remove(&tmp); - Err(write_error(e, path, dir, existed)) - } - }; + if written.is_err() { + let _ = fs.remove(&tmp); + } + return written.map(|()| tmp); } Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display()))) } @@ -259,7 +257,7 @@ fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Re return Err(write_error(io::Error::from(io::ErrorKind::AlreadyExists), path, &dir, true)); } - let tmp = stage(fs, &dir, &name, path, false, fill)?; + let tmp = stage(fs, &dir, &name, path, None, fill)?; let placed = match fs.hard_link(&tmp, &target) { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(fs, &tmp, &target), @@ -363,6 +361,11 @@ fn write_error(e: io::Error, path: &Path, dir: &Path, existed: bool) -> io::Erro io::Error::new(e.kind(), msg) } +fn permissions_error(e: io::Error, path: &Path) -> io::Error { + let msg = format!("cannot save {}: the new file cannot be given the original's permissions ({e}){}", path.display(), unchanged(true)); + io::Error::new(e.kind(), msg) +} + fn read_only_error(e: io::Error, path: &Path) -> io::Error { let kept = unchanged(true); let msg = match e.kind() { @@ -436,6 +439,7 @@ mod tests { locked_renames: Cell, renames: Cell, no_hard_links: bool, + fail_permissions: bool, /// Another process creates the target just before the hard link. created_meanwhile: Option<&'static [u8]>, } @@ -477,8 +481,11 @@ mod tests { fn sync_dir(&self, dir: &Path) -> io::Result<()> { RealFs.sync_dir(dir) } - fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> { - RealFs.copy_permissions(from, to) + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + if self.fail_permissions { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: operation not permitted")); + } + RealFs.set_permissions(file, perms) } } @@ -618,4 +625,18 @@ mod tests { assert!(!p.exists()); assert_no_temp(&d.0); } + + #[cfg(unix)] + #[test] + fn failing_to_keep_permissions_fails_the_save() { + let d = TempDir::new("perms"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + let fs = Faulty { fail_permissions: true, ..Default::default() }; + let msg = atomic_write_custom(&fs, NO_RETRY, &p, b"new").err().map(|e| e.to_string()).unwrap_or_default(); + assert!(msg.contains("permissions"), "{msg}"); + assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); + assert_eq!(fs.renames.get(), 0); + assert_no_temp(&d.0); + } } From 9d422a18b1474969c9ca70f2d6c3a990c19ea721 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:23:27 +0000 Subject: [PATCH 08/15] Retry Windows sharing and lock violations, with a capped backoff retry_rename also retries ERROR_SHARING_VIOLATION (32) and ERROR_LOCK_VIOLATION (33), which a rename can report while a scanner holds the file, and caps each pause at 200 ms. --- crates/atomic/src/lib.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index c1e9375000..5ea1516503 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -114,12 +114,13 @@ fn full_flush_unsupported(e: &io::Error) -> bool { cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY)) } -/// Retry configuration for renames that encounter transient file locks (`PermissionDenied`). +/// Retry configuration for renames that encounter transient file locks (see [`retry_rename`]). #[derive(Debug, Clone, Copy)] pub struct RenameRetry { /// Number of retries after the initial attempt (0 = no retry). pub attempts: u32, - /// Delay before the first retry in milliseconds; doubles on each subsequent attempt. + /// Delay before the first retry in milliseconds; doubles on each subsequent attempt, up to + /// 200 ms per attempt. pub first_delay_ms: u64, } @@ -286,22 +287,32 @@ fn copy_new(fs: &dyn AtomicFs, tmp: &Path, target: &Path) -> io::Result<()> { copied } -/// Retries an operation with exponential backoff while it fails with `PermissionDenied`. +/// The longest pause between two rename attempts. +const MAX_RETRY_DELAY_MS: u64 = 200; + +/// Retries an operation with exponential backoff while it fails because another process holds +/// the file: `PermissionDenied`, or on Windows a sharing or lock violation. pub fn retry_rename(retry: RenameRetry, mut rename: impl FnMut() -> io::Result<()>) -> io::Result<()> { - let mut delay = retry.first_delay_ms; + let mut delay = retry.first_delay_ms.min(MAX_RETRY_DELAY_MS); let mut left = retry.attempts; loop { match rename() { - Err(e) if e.kind() == io::ErrorKind::PermissionDenied && left > 0 => { + Err(e) if is_transient_lock(&e) && left > 0 => { left -= 1; sleep_ms(delay); - delay = delay.saturating_mul(2); + delay = delay.saturating_mul(2).min(MAX_RETRY_DELAY_MS); } r => return r, } } } +fn is_transient_lock(e: &io::Error) -> bool { + const ERROR_SHARING_VIOLATION: i32 = 32; + const ERROR_LOCK_VIOLATION: i32 = 33; + e.kind() == io::ErrorKind::PermissionDenied || (cfg!(windows) && matches!(e.raw_os_error(), Some(ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION))) +} + #[cfg(not(target_arch = "wasm32"))] fn sleep_ms(ms: u64) { if ms > 0 { @@ -639,4 +650,15 @@ mod tests { assert_eq!(fs.renames.get(), 0); assert_no_temp(&d.0); } + + #[test] + fn retry_delays_are_capped() { + let d = TempDir::new("cap"); + let p = d.0.join("doc.craft"); + let fs = Faulty { locked_renames: Cell::new(2), ..Default::default() }; + let started = std::time::Instant::now(); + assert!(atomic_write_custom(&fs, RenameRetry { attempts: 2, first_delay_ms: 60_000 }, &p, b"new").is_ok()); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + assert_eq!(fs.renames.get(), 3); + } } From 33b393bd88f403a0deae01e6fbb5b70eabc3f50f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:23:36 +0000 Subject: [PATCH 09/15] Remove the unused proptest dev-dependency --- Cargo.lock | 192 ++------------------------------------- crates/atomic/Cargo.toml | 3 - 2 files changed, 6 insertions(+), 189 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e1789dc529..374d6d99fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,16 +144,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec 0.9.1", -] - -[[package]] -name = "bit-set" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" -dependencies = [ - "bit-vec 0.10.1", + "bit-vec", ] [[package]] @@ -162,16 +153,6 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" -[[package]] -name = "bit-vec" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" -dependencies = [ - "borsh", - "serde", -] - [[package]] name = "bitflags" version = "1.3.2" @@ -202,30 +183,6 @@ dependencies = [ "objc2 0.6.5", ] -[[package]] -name = "borsh" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" -dependencies = [ - "borsh-derive", - "bytes", - "cfg_aliases", -] - -[[package]] -name = "borsh-derive" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" -dependencies = [ - "once_cell", - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "bumpalo" version = "3.20.3" @@ -326,17 +283,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures", - "rand_core", -] - [[package]] name = "clipboard-win" version = "5.4.1" @@ -425,26 +371,10 @@ dependencies = [ "libc", ] -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - [[package]] name = "craft-atomic" version = "0.1.0" dependencies = [ - "proptest", "rustix 1.1.5", ] @@ -799,12 +729,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - [[package]] name = "fax" version = "0.2.7" @@ -849,12 +773,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - [[package]] name = "foldhash" version = "0.2.0" @@ -940,7 +858,6 @@ dependencies = [ "cfg-if", "libc", "r-efi", - "rand_core", ] [[package]] @@ -1391,7 +1308,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set 0.10.0", + "bit-set", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -2011,38 +1928,12 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" -[[package]] -name = "proptest" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" -dependencies = [ - "bit-set 0.11.1", - "bit-vec 0.10.1", - "bitflags 2.13.2", - "chacha20", - "core_detect", - "num-traits", - "rand", - "rand_xorshift", - "regex-syntax", - "rusty-fork", - "tempfile", - "unarray", -] - [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quick-error" version = "2.0.1" @@ -2073,31 +1964,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "rand" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" -dependencies = [ - "getrandom", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rand_xorshift" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" -dependencies = [ - "rand_core", -] - [[package]] name = "range-alloc" version = "0.1.5" @@ -2160,12 +2026,6 @@ dependencies = [ "bitflags 2.13.2", ] -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -2254,18 +2114,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" -[[package]] -name = "rusty-fork" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" -dependencies = [ - "fnv", - "quick-error 1.2.3", - "tempfile", - "wait-timeout", -] - [[package]] name = "same-file" version = "1.0.6" @@ -2528,19 +2376,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom", - "once_cell", - "rustix 1.1.5", - "windows-sys 0.61.2", -] - [[package]] name = "termcolor" version = "1.4.1" @@ -2599,7 +2434,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error 2.0.1", + "quick-error", "weezl", "zune-jpeg", ] @@ -2708,12 +2543,6 @@ dependencies = [ "rustc-hash 2.1.3", ] -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - [[package]] name = "unicode-general-category" version = "1.1.0" @@ -2799,15 +2628,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "wait-timeout" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" -dependencies = [ - "libc", -] - [[package]] name = "walkdir" version = "2.5.0" @@ -3059,8 +2879,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set 0.10.0", - "bit-vec 0.9.1", + "bit-set", + "bit-vec", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -3132,7 +2952,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set 0.10.0", + "bit-set", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", diff --git a/crates/atomic/Cargo.toml b/crates/atomic/Cargo.toml index 5bb1e5f49f..cc31d02b18 100644 --- a/crates/atomic/Cargo.toml +++ b/crates/atomic/Cargo.toml @@ -12,6 +12,3 @@ workspace = true [target.'cfg(target_vendor = "apple")'.dependencies] rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } - -[dev-dependencies] -proptest = "1.4" From 6bcd350d490cca9d6f997f06be5f91596cf6b966 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 11 Oct 2026 15:23:52 +0000 Subject: [PATCH 10/15] README: credit PhotoCraft only, document what a replace does not keep The crate holds PhotoCraft's engine, and unsafe code is forbidden by the workspace lint rather than in lib.rs. --- crates/atomic/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index af0d3f7751..0f9552839a 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -2,17 +2,19 @@ `craft-atomic` provides crash-safe atomic file writing and replacement for the Craft suite. -Extracted from the common storage reliability engine in **PhotoCraft**, **VectorCraft**, and **FilmCraft** (refs #2, #14), it guarantees that a failed save or abnormal termination never leaves user documents truncated, corrupted, or missing. +Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantees that a failed save or abnormal termination never leaves user documents truncated, corrupted, or missing. ## Core Guarantees 1. **Non-Destructive Replacement**: `atomic_write` never truncates the destination file in place. It writes a temporary file in the **same directory** as the destination, flushes it to non-volatile storage, renames it over the destination atomically, and flushes the directory so the rename survives power failure. 2. **Guaranteed Same-Directory Staging**: Staging files are allocated beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-filesystem volume rename semantics and eliminating `EXDEV` / `ERROR_NOT_SAME_DEVICE`. -3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied` with exponential backoff. +3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations or lock violations with exponential backoff. 4. **Apple SMB / Network Share Fallback**: On macOS, `sync_all` issues `F_FULLFSYNC`. Where network shares or virtual file systems reject full flush with `ENOTSUP` (45) or `ENOTTY` (25), it falls back to standard `fsync`. 5. **Permission Preservation**: On Unix, replaces files while preserving the original file's mode and permissions (e.g. `0600`). 6. **Fault-Injection Testability**: The `AtomicFs` trait enables unit and integration test suites to simulate disk-full, locked files, and permission failures without physical disk I/O. +A replaced file is a new file (a new inode), so its owner and group, extended attributes and ACLs, Finder tags, alternate data streams and hard links are not kept; a crash between the write and the rename can leave a `..-.craft_tmp` file beside the destination. + ## Usage ### One-Shot Atomic Write @@ -74,4 +76,4 @@ impl AtomicFs for FaultyFs { - **Zero App Code**: Zero dependencies on application crates. - **Never Crash**: `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. -- **Forbid Unsafe**: `#![forbid(unsafe_code)]`. +- **No Unsafe**: the workspace lints forbid `unsafe` code. From f75e9c9bc818e433baf12360d575b1613cc40fc6 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sun, 11 Oct 2026 13:32:53 -0700 Subject: [PATCH 11/15] Document atomicity vs durability guarantees and add sequence verification test --- crates/atomic/README.md | 16 +++++++------ crates/atomic/src/lib.rs | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index 0f9552839a..a620c8e378 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -4,13 +4,15 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantees that a failed save or abnormal termination never leaves user documents truncated, corrupted, or missing. -## Core Guarantees - -1. **Non-Destructive Replacement**: `atomic_write` never truncates the destination file in place. It writes a temporary file in the **same directory** as the destination, flushes it to non-volatile storage, renames it over the destination atomically, and flushes the directory so the rename survives power failure. -2. **Guaranteed Same-Directory Staging**: Staging files are allocated beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-filesystem volume rename semantics and eliminating `EXDEV` / `ERROR_NOT_SAME_DEVICE`. -3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations or lock violations with exponential backoff. -4. **Apple SMB / Network Share Fallback**: On macOS, `sync_all` issues `F_FULLFSYNC`. Where network shares or virtual file systems reject full flush with `ENOTSUP` (45) or `ENOTTY` (25), it falls back to standard `fsync`. -5. **Permission Preservation**: On Unix, replaces files while preserving the original file's mode and permissions (e.g. `0600`). +## Core Guarantees: Atomicity vs. Durability + +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If writing fails, times out, or the process crashes mid-stream, the destination retains its prior bytes and the staging file is unlinked. +2. **Durability (Power-Loss & Crash Persistence)**: + - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). + - **Directory Flush**: After rename, on Unix platforms, the parent directory table is explicitly synced (`sync_dir`) so the new directory entry survives sudden power loss. +3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations (32), or lock violations (33) with exponential backoff capped at 200ms. +4. **Permission & Symlink Invariants**: On Unix, preserves destination permissions (e.g. `0600`). Symlink chains are resolved with a hop limit, writing through the symlink to the ultimate target without replacing the link itself. +5. **Safe Exclusive Creation (`write_new`)**: Uses hard links where supported, or exclusive create (`O_EXCL`), guaranteeing that an existing file is never replaced under race conditions. 6. **Fault-Injection Testability**: The `AtomicFs` trait enables unit and integration test suites to simulate disk-full, locked files, and permission failures without physical disk I/O. A replaced file is a new file (a new inode), so its owner and group, extended attributes and ACLs, Finder tags, alternate data streams and hard links are not kept; a crash between the write and the rename can leave a `..-.craft_tmp` file beside the destination. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 5ea1516503..23b3d2abaf 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -8,6 +8,19 @@ //! survives a power loss. If any step fails, the destination retains its original bytes and //! the temporary staging file is removed. //! +//! ### Guarantees: Atomicity vs. Durability +//! - **Atomicity Guarantee (All-or-Nothing)**: +//! [`atomic_write`] guarantees that external readers never observe a partial write. Either the target +//! file retains its previous bytes, or it is replaced completely with the new contents. If writing fails, +//! times out, or the process terminates prematurely, the target remains unmodified and any staging files +//! are cleaned up. +//! - **Durability Guarantee (Crash & Power-Loss Persistence)**: +//! Data persistence across power failures requires two explicit sync points: +//! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage +//! (`F_FULLFSYNC` on macOS, `sync_all` on Windows/Linux) *before* the atomic rename. +//! 2. **Directory Flush (`sync_dir`)**: On Unix, the containing directory table is synced *after* the +//! rename so the filesystem directory entry survives power loss. +//! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files //! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`). @@ -442,6 +455,7 @@ mod tests { #[derive(Default)] struct Faulty { + events: std::cell::RefCell>, fail_sync: bool, /// Syncs fail once this many have succeeded. syncs_before_failure: Option, @@ -457,9 +471,11 @@ mod tests { impl AtomicFs for Faulty { fn create_new(&self, path: &Path) -> io::Result { + self.events.borrow_mut().push("create_new"); RealFs.create_new(path) } fn sync(&self, file: &File) -> io::Result<()> { + self.events.borrow_mut().push("sync_file"); let done = self.syncs.replace(self.syncs.get() + 1); if self.fail_sync || self.syncs_before_failure.is_some_and(|n| done >= n) { return Err(io::Error::new(io::ErrorKind::StorageFull, "injected: no space left on device")); @@ -467,6 +483,7 @@ mod tests { RealFs.sync(file) } fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + self.events.borrow_mut().push("rename"); self.renames.set(self.renames.get() + 1); if let Some(kind) = self.fail_rename { return Err(io::Error::new(kind, "injected rename failure")); @@ -478,6 +495,7 @@ mod tests { RealFs.rename(from, to) } fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + self.events.borrow_mut().push("hard_link"); if let Some(bytes) = self.created_meanwhile { std::fs::write(to, bytes)?; } @@ -487,12 +505,15 @@ mod tests { RealFs.hard_link(from, to) } fn remove(&self, path: &Path) -> io::Result<()> { + self.events.borrow_mut().push("remove"); RealFs.remove(path) } fn sync_dir(&self, dir: &Path) -> io::Result<()> { + self.events.borrow_mut().push("sync_dir"); RealFs.sync_dir(dir) } fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + self.events.borrow_mut().push("set_permissions"); if self.fail_permissions { return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: operation not permitted")); } @@ -661,4 +682,34 @@ mod tests { assert!(started.elapsed() < std::time::Duration::from_secs(5)); assert_eq!(fs.renames.get(), 3); } + + #[test] + fn distinguishes_atomicity_and_durability_order() { + let d = TempDir::new("durability_order"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL).ok(); + + let fs = Faulty::default(); + atomic_write_custom(&fs, NO_RETRY, &p, b"durable payload").expect("successful atomic write"); + + let events = fs.events.into_inner(); + let sync_file_idx = events.iter().position(|&e| e == "sync_file").expect("file content must be flushed"); + let rename_idx = events.iter().position(|&e| e == "rename").expect("atomic rename must be performed"); + + // 1. Content Durability: staging file must be synced to stable media BEFORE pointer switch (rename) + assert!( + sync_file_idx < rename_idx, + "Durability invariant violated: file content must be flushed to stable storage before rename (sync={sync_file_idx}, rename={rename_idx})" + ); + + // 2. Directory Durability: on Unix, parent directory must be synced AFTER rename to commit directory entry + #[cfg(unix)] + { + let sync_dir_idx = events.iter().position(|&e| e == "sync_dir").expect("directory must be flushed on Unix"); + assert!( + rename_idx < sync_dir_idx, + "Durability invariant violated: parent directory must be flushed after rename (rename={rename_idx}, sync_dir={sync_dir_idx})" + ); + } + } } From 1c9baae1bf1a279ad1129a745d0a357255fb824f Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sun, 11 Oct 2026 16:18:15 -0700 Subject: [PATCH 12/15] Lock tempfile and fastrand dependencies for workspace --- Cargo.lock | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 374d6d99fc..eb2bf1db16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -729,6 +729,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "fax" version = "0.2.7" @@ -2376,6 +2382,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + [[package]] name = "termcolor" version = "1.4.1" From d4a38f90ee5de4f5d0e24b40a17970456f11331e Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sun, 11 Oct 2026 19:10:59 -0700 Subject: [PATCH 13/15] Clarify user-space cleanup semantics and best-effort directory sync in craft-atomic --- crates/atomic/README.md | 6 +++--- crates/atomic/src/lib.rs | 35 +++++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index a620c8e378..b9f64ac4e8 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -6,10 +6,10 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee ## Core Guarantees: Atomicity vs. Durability -1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If writing fails, times out, or the process crashes mid-stream, the destination retains its prior bytes and the staging file is unlinked. +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process crash or power loss leaves the staging file on disk to be swept on startup; the destination is never corrupted. 2. **Durability (Power-Loss & Crash Persistence)**: - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). - - **Directory Flush**: After rename, on Unix platforms, the parent directory table is explicitly synced (`sync_dir`) so the new directory entry survives sudden power loss. + - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. 3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations (32), or lock violations (33) with exponential backoff capped at 200ms. 4. **Permission & Symlink Invariants**: On Unix, preserves destination permissions (e.g. `0600`). Symlink chains are resolved with a hop limit, writing through the symlink to the ultimate target without replacing the link itself. 5. **Safe Exclusive Creation (`write_new`)**: Uses hard links where supported, or exclusive create (`O_EXCL`), guaranteeing that an existing file is never replaced under race conditions. @@ -29,7 +29,7 @@ let path = Path::new("project.craft"); let data = b"precious document state"; // Atomically replaces project.craft. If writing fails, project.craft retains -// its prior bytes and all temporary staging files are unlinked. +// its prior bytes and temporary staging files are unlinked in user space. atomic_write(path, data).expect("safe atomic write"); ``` diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 23b3d2abaf..95403afde3 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -4,22 +4,24 @@ //! //! [`atomic_write`] never truncates the destination file in place. It writes a temporary file //! in the **same directory** as the destination, flushes it to non-volatile storage (`sync_all`), -//! renames it over the destination atomically, and on Unix, flushes the directory so the rename -//! survives a power loss. If any step fails, the destination retains its original bytes and +//! renames it over the destination atomically, and on Unix, attempts to flush the directory so the rename +//! survives a power loss. If write or rename fails, the destination retains its original bytes and //! the temporary staging file is removed. //! //! ### Guarantees: Atomicity vs. Durability //! - **Atomicity Guarantee (All-or-Nothing)**: //! [`atomic_write`] guarantees that external readers never observe a partial write. Either the target -//! file retains its previous bytes, or it is replaced completely with the new contents. If writing fails, -//! times out, or the process terminates prematurely, the target remains unmodified and any staging files -//! are cleaned up. +//! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs +//! during staging or rename, the target remains unmodified and the staging file is removed in user space. +//! Note that an abnormal process crash or power loss leaves the staging file on disk to be swept on startup; +//! it does not corrupt the destination. //! - **Durability Guarantee (Crash & Power-Loss Persistence)**: -//! Data persistence across power failures requires two explicit sync points: +//! Data persistence across power failures involves two sync points: //! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage //! (`F_FULLFSYNC` on macOS, `sync_all` on Windows/Linux) *before* the atomic rename. -//! 2. **Directory Flush (`sync_dir`)**: On Unix, the containing directory table is synced *after* the -//! rename so the filesystem directory entry survives power loss. +//! 2. **Directory Flush (`sync_dir`, Unix only)**: On Unix, flushing the parent directory table is +//! attempted *after* the rename on a best-effort basis. If directory sync fails, the error is ignored +//! because the rename has already committed and the destination has already been replaced. //! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files @@ -182,6 +184,8 @@ fn replace(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, fill: impl FnOnce return Err(rename_error(e, path, existed)); } + // The new bytes are in place; a failed directory fsync can't be undone and must not report + // the save as failed, so it is best effort. let _ = fs.sync_dir(&dir); Ok(()) } @@ -284,6 +288,7 @@ fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Re return Err(write_error(e, path, &dir, existed)); } + // The new file is in place; a failed directory fsync can't be undone and is best effort. let _ = fs.sync_dir(&dir); Ok(()) } @@ -465,6 +470,7 @@ mod tests { renames: Cell, no_hard_links: bool, fail_permissions: bool, + fail_sync_dir: bool, /// Another process creates the target just before the hard link. created_meanwhile: Option<&'static [u8]>, } @@ -510,6 +516,9 @@ mod tests { } fn sync_dir(&self, dir: &Path) -> io::Result<()> { self.events.borrow_mut().push("sync_dir"); + if self.fail_sync_dir { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: directory sync failed")); + } RealFs.sync_dir(dir) } fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { @@ -712,4 +721,14 @@ mod tests { ); } } + + #[test] + fn sync_dir_failure_is_best_effort() { + let d = TempDir::new("best_effort_sync_dir"); + let p = d.0.join("doc.craft"); + let fs = Faulty { fail_sync_dir: true, ..Default::default() }; + assert!(atomic_write_custom(&fs, NO_RETRY, &p, b"best effort data").is_ok()); + assert_eq!(std::fs::read(&p).ok(), Some(b"best effort data".to_vec())); + assert_no_temp(&d.0); + } } From 5b273dd82f4d98e18620d98aff3f87b78d9a0594 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sun, 11 Oct 2026 19:20:26 -0700 Subject: [PATCH 14/15] Clarify application recovery sweep responsibility and hardware durability limits --- crates/atomic/README.md | 5 +++-- crates/atomic/src/lib.rs | 11 ++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index b9f64ac4e8..551f2e9fa3 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -6,10 +6,11 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee ## Core Guarantees: Atomicity vs. Durability -1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process crash or power loss leaves the staging file on disk to be swept on startup; the destination is never corrupted. -2. **Durability (Power-Loss & Crash Persistence)**: +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted. +2. **Durability & Ordering Boundaries**: - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. + - **Hardware Durability Limits**: The sequence `sync_file < rename < sync_dir` proves ordering and kernel dispatch. Software tests do not prove survival across physical power interruption or unbuffered drive controller write caches. 3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations (32), or lock violations (33) with exponential backoff capped at 200ms. 4. **Permission & Symlink Invariants**: On Unix, preserves destination permissions (e.g. `0600`). Symlink chains are resolved with a hop limit, writing through the symlink to the ultimate target without replacing the link itself. 5. **Safe Exclusive Creation (`write_new`)**: Uses hard links where supported, or exclusive create (`O_EXCL`), guaranteeing that an existing file is never replaced under race conditions. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 95403afde3..0030d4e088 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -13,15 +13,20 @@ //! [`atomic_write`] guarantees that external readers never observe a partial write. Either the target //! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs //! during staging or rename, the target remains unmodified and the staging file is removed in user space. -//! Note that an abnormal process crash or power loss leaves the staging file on disk to be swept on startup; -//! it does not corrupt the destination. -//! - **Durability Guarantee (Crash & Power-Loss Persistence)**: +//! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and +//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the +//! consuming application; the library does not perform background sweeping. The destination file itself is +//! never corrupted. +//! - **Durability & Ordering Boundaries**: //! Data persistence across power failures involves two sync points: //! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage //! (`F_FULLFSYNC` on macOS, `sync_all` on Windows/Linux) *before* the atomic rename. //! 2. **Directory Flush (`sync_dir`, Unix only)**: On Unix, flushing the parent directory table is //! attempted *after* the rename on a best-effort basis. If directory sync fails, the error is ignored //! because the rename has already committed and the destination has already been replaced. +//! 3. **Hardware Durability Limits**: While this enforces strict kernel dispatch order +//! (`sync_file < rename < sync_dir`), software flushes cannot guarantee data survival across +//! unbuffered drive controller write-caching or physical power cutoffs. //! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files From 811558a3adf4edb1b6f93883d2dad1bf4bef1a63 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 12 Oct 2026 20:12:56 +0200 Subject: [PATCH 15/15] Create Unix atomic-write staging files with private permissions --- crates/atomic/README.md | 2 +- crates/atomic/src/lib.rs | 60 ++++++++++++++++++++++++-- crates/atomic/tests/atomic_tests.rs | 65 +++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 4 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index 551f2e9fa3..423dc52f74 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -12,7 +12,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. - **Hardware Durability Limits**: The sequence `sync_file < rename < sync_dir` proves ordering and kernel dispatch. Software tests do not prove survival across physical power interruption or unbuffered drive controller write caches. 3. **Transient Lock Backoff (Windows)**: Antivirus scanners and search indexers hold newly written files momentarily. `RenameRetry` automatically retries renames encountering `PermissionDenied`, sharing violations (32), or lock violations (33) with exponential backoff capped at 200ms. -4. **Permission & Symlink Invariants**: On Unix, preserves destination permissions (e.g. `0600`). Symlink chains are resolved with a hop limit, writing through the symlink to the ultimate target without replacing the link itself. +4. **Permission & Symlink Invariants**: On Unix, staging files are created with mode `0600` (restricted by the process umask), so the payload starts private even in a shared folder. Existing destination permissions are restored after the streaming callback. New files remain private by default; a callback may select their final permissions, which are kept both with hard links and the exclusive-copy fallback. Symlink chains are resolved with a hop limit, writing through the symlink to the ultimate target without replacing the link itself. 5. **Safe Exclusive Creation (`write_new`)**: Uses hard links where supported, or exclusive create (`O_EXCL`), guaranteeing that an existing file is never replaced under race conditions. 6. **Fault-Injection Testability**: The `AtomicFs` trait enables unit and integration test suites to simulate disk-full, locked files, and permission failures without physical disk I/O. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 0030d4e088..cc4b9d6ee6 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -49,6 +49,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// [`RealFs`] provides the production implementation; test suites implement this to inject faults. pub trait AtomicFs { /// Create `path`, which must not exist, and open it for writing. + /// On Unix, create it with owner-only permissions so payload written afterward is private. fn create_new(&self, path: &Path) -> io::Result; /// Flush a written file to durable storage. fn sync(&self, file: &File) -> io::Result<()>; @@ -70,7 +71,16 @@ pub struct RealFs; impl AtomicFs for RealFs { fn create_new(&self, path: &Path) -> io::Result { - OpenOptions::new().write(true).create_new(true).open(path) + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // Set the mode at creation: chmod afterward leaves a window in which another + // user can open the stage, including a stage left behind by an abrupt exit. + options.mode(0o600); + } + options.open(path) } fn sync(&self, file: &File) -> io::Result<()> { @@ -159,6 +169,10 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Atomically writes to `path` using a streaming writer callback `F`. +/// +/// On Unix, the staging file starts with mode `0600` (restricted by the process umask). +/// Existing destination permissions are restored after the callback. For a new destination, +/// callback-selected permissions are kept, or the file remains private by default. pub fn atomic_write_with(path: &Path, write_fn: F) -> io::Result<()> where F: FnOnce(&mut File) -> io::Result<()>, @@ -258,6 +272,8 @@ pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Exclusively creates and writes `path` with a streaming writer callback `F`. +/// On Unix, the file starts private (`0600`, restricted by the process umask); the callback +/// may choose its final permissions. pub fn write_new_with(path: &Path, write_fn: F) -> io::Result<()> where F: FnOnce(&mut File) -> io::Result<()>, @@ -302,7 +318,14 @@ fn create(fs: &dyn AtomicFs, path: &Path, fill: impl FnOnce(&mut File) -> io::Re /// removed. fn copy_new(fs: &dyn AtomicFs, tmp: &Path, target: &Path) -> io::Result<()> { let mut to = fs.create_new(target)?; - let copied = File::open(tmp).and_then(|mut from| io::copy(&mut from, &mut to)).and_then(|_| fs.sync(&to)); + let copied = File::open(tmp).and_then(|mut from| { + io::copy(&mut from, &mut to)?; + // Keep callback-selected modes just as hard-link publication does, but only + // after copying the payload into a destination that was created privately. + #[cfg(unix)] + fs.set_permissions(&to, from.metadata()?.permissions())?; + fs.sync(&to) + }); drop(to); if copied.is_err() { let _ = fs.remove(target); @@ -466,6 +489,8 @@ mod tests { #[derive(Default)] struct Faulty { events: std::cell::RefCell>, + #[cfg(unix)] + created_modes: std::cell::RefCell>, fail_sync: bool, /// Syncs fail once this many have succeeded. syncs_before_failure: Option, @@ -483,7 +508,13 @@ mod tests { impl AtomicFs for Faulty { fn create_new(&self, path: &Path) -> io::Result { self.events.borrow_mut().push("create_new"); - RealFs.create_new(path) + let file = RealFs.create_new(path)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + self.created_modes.borrow_mut().push(file.metadata()?.permissions().mode() & 0o777); + } + Ok(file) } fn sync(&self, file: &File) -> io::Result<()> { self.events.borrow_mut().push("sync_file"); @@ -672,6 +703,29 @@ mod tests { assert_no_temp(&d.0); } + #[cfg(unix)] + #[test] + fn exclusive_copy_starts_private_and_keeps_callback_mode() -> io::Result<()> { + use std::fs::Permissions; + use std::os::unix::fs::PermissionsExt; + + let d = TempDir::new("private-copy"); + for mode in [0o600, 0o640] { + let p = d.0.join(format!("export-{mode:o}.craft")); + let fs = Faulty { no_hard_links: true, ..Default::default() }; + create(&fs, &p, |f| { + f.write_all(b"private export")?; + f.set_permissions(Permissions::from_mode(mode)) + })?; + // Check both the staging file and the exclusive-copy destination at creation. + assert_eq!(*fs.created_modes.borrow(), [0o600, 0o600]); + assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); + assert_eq!(std::fs::read(&p)?, b"private export"); + } + assert_no_temp(&d.0); + Ok(()) + } + #[cfg(unix)] #[test] fn failing_to_keep_permissions_fails_the_save() { diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index ba6e27ae67..011002a446 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -170,3 +170,68 @@ fn read_only_target_is_not_replaced() { assert_eq!(std::fs::read(&p).ok(), Some(ORIGINAL.to_vec())); assert_no_temp(&d.0); } + +#[cfg(unix)] +#[test] +fn private_staging_preserves_existing_modes_after_callback() -> io::Result<()> { + use std::fs::Permissions; + use std::os::unix::fs::PermissionsExt; + + let d = TempDir::new("private_staging"); + std::fs::set_permissions(&d.0, Permissions::from_mode(0o755))?; + for mode in [0o600, 0o640, 0o664, 0o200] { + let p = d.0.join(format!("doc-{mode:o}.craft")); + std::fs::write(&p, ORIGINAL)?; + std::fs::set_permissions(&p, Permissions::from_mode(mode))?; + atomic_write_with(&p, |f| { + assert_eq!(f.metadata()?.permissions().mode() & 0o777, 0o600, "stage must be private before the callback, even for a shared destination"); + // Settings writers restrict the stage themselves; this must not change the + // destination mode that atomic replacement promises to preserve. + f.set_permissions(Permissions::from_mode(0o600))?; + f.write_all(b"new private payload")?; + assert_eq!(f.metadata()?.permissions().mode() & 0o777, 0o600, "payload must stay private while writing"); + Ok(()) + })?; + assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode); + std::fs::set_permissions(&p, Permissions::from_mode(0o600))?; + assert_eq!(std::fs::read(&p)?, b"new private payload"); + } + assert_no_temp(&d.0); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn new_files_start_private_and_keep_callback_permissions() -> io::Result<()> { + use std::fs::Permissions; + use std::os::unix::fs::PermissionsExt; + + let d = TempDir::new("private_new"); + for exclusive in [false, true] { + let p = d.0.join(format!("new-{exclusive}.craft")); + let fill = |f: &mut std::fs::File| { + assert_eq!(f.metadata()?.permissions().mode() & 0o777, 0o600); + f.write_all(b"new payload")?; + // A new file has no existing mode to restore, so the callback may select it. + f.set_permissions(Permissions::from_mode(0o640)) + }; + if exclusive { + write_new_with(&p, fill)?; + } else { + atomic_write_with(&p, fill)?; + } + assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, 0o640); + assert_eq!(std::fs::read(&p)?, b"new payload"); + } + for exclusive in [false, true] { + let p = d.0.join(format!("default-{exclusive}.craft")); + if exclusive { + write_new(&p, b"private by default")?; + } else { + atomic_write(&p, b"private by default")?; + } + assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, 0o600); + } + assert_no_temp(&d.0); + Ok(()) +}