PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(format): report a failed directory flush after a save instead of ignoring it (#5420)
FinnNk0b779b4fecf6
diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rsindex 635bf924a..8cd349eff 100644--- a/crates/format/src/atomic.rs+++ b/crates/format/src/atomic.rs@@ -106,7 +106,7 @@ impl AtomicFs for RealFs {fn sync_dir(&self, dir: &Path) -> io::Result<()> {#[cfg(unix)]{- sync_file(&std::fs::File::open(dir)?)+ open_dir_for_sync(dir)?.map_or(Ok(()), |d| sync_file(&d))}#[cfg(windows)]{@@ -254,14 +254,79 @@ pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &let _ = fs.remove(&tmp);return Err(rename_error(e, path));}+ // The new bytes are in place, but until the directory is flushed the rename may not survive+ // a power loss (#4968). Windows fails the save on any failed flush (#7858). Elsewhere a file+ // system that can't flush directories at all counts as done; any other failure is reported,+ // so the caller keeps the document unsaved and its recovery data instead of discarding them+ // on a save that may not last.#[cfg(windows)]fs.sync_dir(&dir).map_err(|e| publication_error(e, path))?;- // Keep the existing Unix policy here; #5420 separately changes its error handling.#[cfg(not(windows))]- let _ = fs.sync_dir(&dir);+ dir_synced(fs.sync_dir(&dir)).map_err(|e| unconfirmed_error(e, path))?;Ok(())}+/// `dir` opened to flush it, or `None` when it can't be opened for that because it has no read+/// permission (a write-and-search-only folder): no flush can be attempted there, so none failed.+/// Any other error is returned.+#[cfg(unix)]+fn open_dir_for_sync(dir: &Path) -> io::Result<Option<std::fs::File>> {+ match std::fs::File::open(dir) {+ Ok(d) => Ok(Some(d)),+ Err(e) if e.kind() == io::ErrorKind::PermissionDenied => Ok(None),+ Err(e) => Err(e),+ }+}++/// `result` of flushing a directory, with "this file system can't flush directories" counted as+/// success: `EINVAL` (Linux file systems without directory fsync), `ENOTSUP`/`EOPNOTSUPP` and,+/// on Apple platforms, `ENOTTY`, or [`io::ErrorKind::Unsupported`]. Waiting or retrying won't+/// change those, and failing every save there would make saving impossible. Any other error is+/// returned: the flush was attempted and failed.+#[cfg(not(windows))]+pub(crate) fn dir_synced(result: io::Result<()>) -> io::Result<()> {+ match result {+ Err(e) if dir_sync_unsupported(&e) => Ok(()),+ other => other,+ }+}++#[cfg(not(windows))]+fn dir_sync_unsupported(e: &io::Error) -> bool {+ if e.kind() == io::ErrorKind::Unsupported {+ return true;+ }+ // errno values: EINVAL is 22 everywhere; ENOTSUP and EOPNOTSUPP are 95 on Linux and+ // Android, 45 and 102 on Apple platforms, 45 on the BSDs; ENOTTY is 25. Elsewhere 45 means+ // something else (illumos: EDEADLK), so only EINVAL and `Unsupported` count there.+ const EINVAL: i32 = 22;+ let unsupported: &[i32] = if cfg!(any(target_os = "linux", target_os = "android")) {+ &[EINVAL, 95]+ } else if cfg!(target_vendor = "apple") {+ &[EINVAL, 45, 102, 25]+ } else if cfg!(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly")) {+ &[EINVAL, 45]+ } else if cfg!(unix) {+ &[EINVAL]+ } else {+ &[]+ };+ e.raw_os_error().is_some_and(|code| unsupported.contains(&code))+}++/// The error for a file that was published but whose directory flush failed: same kind, saying+/// the file is in place but may not survive a power loss. (Windows reports `publication_error`.)+#[cfg(not(windows))]+fn unconfirmed_error(e: io::Error, path: &Path) -> io::Error {+ context(+ e,+ format!(+ "{} was written, but the folder could not be flushed to disk, so the save may not survive a power loss or crash; save again or to another folder",+ path.display()+ ),+ )+}+/// Run `rename`, retrying with backoff while it fails with `PermissionDenied` (see/// [`RenameRetry`]). For callers that rename through their own handles (capability directories).pub fn retry_rename(retry: RenameRetry, mut rename: impl FnMut() -> io::Result<()>) -> io::Result<()> {diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rsindex d48cf7d9a..bc26ae6d0 100644--- a/crates/format/src/atomic/tests.rs+++ b/crates/format/src/atomic/tests.rs@@ -41,8 +41,9 @@ struct Faulty {/// Fail the first N renames with PermissionDenied (a transient lock), then succeed.locked_renames: Cell<u32>,renames: Cell<u32>,- /// Failure of the durability barrier after publication (#7858).- fail_sync_dir: bool,+ /// Fail the directory flush (the durability barrier after publication, #4968, #7858)+ /// with this raw OS error, or with this kind.+ fail_sync_dir: Option<Result<i32, io::ErrorKind>>,synced: Cell<u32>,}@@ -72,10 +73,11 @@ impl AtomicFs for Faulty {/// Count publication barriers and optionally fail before the real directory flush.fn sync_dir(&self, dir: &Path) -> io::Result<()> {self.synced.set(self.synced.get() + 1);- if self.fail_sync_dir {- return Err(io::Error::other("injected publication flush failure"));+ match self.fail_sync_dir {+ Some(Ok(code)) => Err(io::Error::from_raw_os_error(code)),+ Some(Err(kind)) => Err(io::Error::new(kind, "injected directory flush failure")),+ None => RealFs.sync_dir(dir),}- RealFs.sync_dir(dir)}fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> {RealFs.copy_metadata(from, to)@@ -92,7 +94,7 @@ fn a_failed_publication_flush_is_reported_and_can_be_retried() {let d = TempDir::new("publication-flush");let p = d.0.join("document.pcraft");std::fs::write(&p, ORIGINAL).unwrap();- let fs = Faulty { fail_sync_dir: true, ..Default::default() };+ let fs = Faulty { fail_sync_dir: Some(Err(io::ErrorKind::Other)), ..Default::default() };let error = atomic_write_with(&fs, NO_RETRY, &p, b"new document").unwrap_err();assert_eq!(fs.synced.get(), 1, "{error}");@@ -444,3 +446,38 @@ fn sync_file_flushes_a_local_file() {let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap();sync_file(&file).unwrap();}++/// #4968: the rename succeeded but the directory flush failed. The new bytes are in place, and+/// the save is reported as unconfirmed (same kind, saying so) instead of as a success, so the+/// caller keeps the document unsaved and its recovery data.+#[test]+fn a_failed_directory_flush_is_reported_not_swallowed() {+ let d = TempDir::new("syncdir");+ let p = d.0.join("doc.pcraft");+ std::fs::write(&p, ORIGINAL).unwrap();+ let fs = Faulty { fail_sync_dir: Some(Err(io::ErrorKind::Other)), ..Default::default() };+ let e = atomic_write_with(&fs, NO_RETRY, &p, b"new").unwrap_err();+ assert_eq!(e.kind(), io::ErrorKind::Other);+ let msg = e.to_string();+ assert!(msg.contains("doc.pcraft") && msg.contains("may not survive"), "{msg}");+ assert_eq!(std::fs::read(&p).unwrap(), b"new", "published: the new bytes are in place");+ assert_no_temp(&d.0);+}++/// A file system that can't flush directories at all (Linux's EINVAL, ENOTSUP, or an+/// `Unsupported` error) still saves: failing every save there would make saving impossible.+/// Windows fails the save on any failed flush (#7858), so this is the Unix rule.+#[cfg(not(windows))]+#[test]+fn a_directory_flush_the_file_system_cannot_do_still_saves() {+ let d = TempDir::new("syncdir-unsupported");+ let p = d.0.join("doc.pcraft");+ let fs = Faulty { fail_sync_dir: Some(Err(io::ErrorKind::Unsupported)), ..Default::default() };+ atomic_write_with(&fs, NO_RETRY, &p, b"new").unwrap();+ assert_eq!(std::fs::read(&p).unwrap(), b"new");+ // EINVAL (22) means "can't flush a directory" only on Unix; EIO (5) is a real failure.+ assert_eq!(dir_synced(Err(io::Error::from_raw_os_error(22))).is_ok(), cfg!(unix));+ assert!(dir_synced(Err(io::Error::from_raw_os_error(5))).is_err());+ let fs = Faulty { fail_sync_dir: Some(Ok(5)), ..Default::default() };+ assert!(atomic_write_with(&fs, NO_RETRY, &p, b"newer").is_err());+}diff --git a/crates/format/src/store.rs b/crates/format/src/store.rsindex 18e6a9b43..84124407e 100644--- a/crates/format/src/store.rs+++ b/crates/format/src/store.rs@@ -587,6 +587,50 @@ fn validate_bundle_file(root: &Path, path: &Path) -> Result<()> {plain_file_or_missing(path)}+/// Flush `dir`, the folder `written` was just renamed into, as `atomic_write` does (with the+/// full-flush fallback of `sync_file`, #1336). Windows flushes through the injected `AtomicFs`+/// and fails on any error (#7858).+#[cfg(not(windows))]+fn flush_bundle_dir(dir: &Path, written: &Path) -> std::io::Result<()> {+ use crate::atomic::AtomicFs;+ #[cfg(test)]+ {+ FLUSHED.with(|f| f.borrow_mut().push(dir.to_path_buf()));+ let named = |p: Option<&Path>, name: &str| p.and_then(Path::file_name).is_some_and(|n| n == name);+ if FAIL_DIR_FLUSH.with(|f| {+ let hit = f.get().is_some_and(|name| named(Some(written), name) || named(written.parent(), name));+ if hit {+ f.set(None);+ }+ hit+ }) {+ return Err(std::io::Error::other("injected folder flush failure"));+ }+ }+ let _ = written;+ crate::atomic::RealFs.sync_dir(dir)+}++/// [`flush_bundle_dir`], as the save's error when the flush was attempted and failed: `written`+/// is in place, but may not survive a power loss or crash (#4968).+#[cfg(not(windows))]+fn confirm_flushed(dir: &Path, written: &Path) -> Result<()> {+ crate::atomic::dir_synced(flush_bundle_dir(dir, written)).map_err(|e| {+ FormatError::Io(std::io::Error::new(+ e.kind(),+ format!("{} was written, but its folder could not be flushed to disk, so the save may not survive a power loss or crash: {e}", written.display()),+ ))+ })+}++#[cfg(all(test, not(windows)))]+thread_local! {+ /// Tests: the bundle file, or folder, whose next folder flush fails, once, on this thread.+ static FAIL_DIR_FLUSH: std::cell::Cell<Option<&'static str>> = const { std::cell::Cell::new(None) };+ /// Tests: the folders flushed on this thread, in order.+ static FLUSHED: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };+}+/// Publish a validated bundle entry through a flushed temporary file and replacing rename./// On Windows, propagate a failed directory barrier even though the new entry is already visible.fn write_bundle_file(root: &Path, path: &Path, data: &[u8], fs: &dyn crate::atomic::AtomicFs) -> Result<()> {@@ -639,10 +683,10 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8], fs: &dyn crate::atom{fs.sync_dir(parent).map_err(|e| crate::atomic::publication_error(e, path))?;}- #[cfg(unix)]- {- let _ = std::fs::File::open(parent).and_then(|d| d.sync_all());- }+ // Elsewhere a failed flush is reported too (#4968), but a file system that can't flush a+ // directory at all still saves, as in `atomic_write`.+ #[cfg(not(windows))]+ confirm_flushed(parent, path)?;Ok(())})();if result.is_err() && validate_bundle_file(root, &tmp).is_ok() {@@ -994,6 +1038,13 @@ impl PcraftWriter {fs.sync_dir(&dir.join(sub)).map_err(|e| crate::atomic::publication_error(e, &dir.join(sub)))?;}}+ #[cfg(not(windows))]+ for sub in ["tiles", "blobs"] {+ let folder = dir.join(sub);+ if folder.is_dir() {+ confirm_flushed(&folder, &folder)?;+ }+ }write_bundle_file(dir, &dir.join(MANIFEST), &p.manifest, fs)?;// Omitted previews belong to the previous manifest until the new one commits.// After commit, a locked leftover is only housekeeping, just like unused objects.@@ -1156,6 +1207,72 @@ fn gc_pinned_directory_handles_resist_subdirectory_swap() {std::fs::remove_dir_all(root).unwrap();}+/// #4968: a manifest whose folder can't be flushed fails the save, and the objects the previous+/// manifest references stay in place; the next save that flushes removes what is unreferenced.+#[cfg(all(test, not(windows)))]+#[test]+fn a_failed_manifest_flush_keeps_the_previous_objects() {+ use std::sync::atomic::{AtomicU64, Ordering};++ static NEXT: AtomicU64 = AtomicU64::new(0);+ let dir = std::env::temp_dir().join(format!("pcraft-flush-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));+ std::fs::create_dir_all(&dir).unwrap();+ let dir = std::fs::canonicalize(dir).unwrap();+ let mut doc = Document::new("flush", photocraft_doc::Size::new(64, 64), photocraft_color::ColorMode::Rgb, SampleType::U8);+ let id = doc.insert_above(None, photocraft_doc::Layer::raster("paint", doc.pixel_format()));+ let paint = |doc: &mut Document, red: f32| {+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 64, 64), &[red, 0.5, 0.25, 1.0]);+ };+ paint(&mut doc, 1.0);+ let mut w = PcraftWriter::new();+ w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();+ let old = list_objects(&dir).unwrap();+ paint(&mut doc, 0.0);+ FAIL_DIR_FLUSH.with(|f| f.set(Some(MANIFEST)));+ let e = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap_err();+ assert!(e.to_string().contains("could not be flushed"), "{e}");+ let now = list_objects(&dir).unwrap();+ assert!(old.is_subset(&now), "the previous manifest's objects are kept");+ assert!(now.len() > old.len(), "the new objects were written");+ let stats = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();+ assert!(stats.objects_removed > 0, "the next save removes the unreferenced objects");+ assert_eq!(crate::load_path(&dir).unwrap(), doc);+ std::fs::remove_dir_all(dir).unwrap();+}++/// An object whose folder flush failed is reused by the retried save, which writes no new object+/// there: that save still flushes the object folder before committing a manifest that names it.+#[cfg(all(test, not(windows)))]+#[test]+fn a_retried_save_flushes_the_folder_of_a_reused_object() {+ use std::sync::atomic::{AtomicU64, Ordering};++ static NEXT: AtomicU64 = AtomicU64::new(0);+ let dir = std::env::temp_dir().join(format!("pcraft-retry-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));+ std::fs::create_dir_all(&dir).unwrap();+ let dir = std::fs::canonicalize(dir).unwrap();+ // One layer of one tile: the retry finds its only object already written.+ let mut doc = Document::new("retry", photocraft_doc::Size::new(16, 16), photocraft_color::ColorMode::Rgb, SampleType::U8);+ let id = doc.insert_above(None, photocraft_doc::Layer::raster("paint", doc.pixel_format()));+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 16, 16), &[1.0, 0.5, 0.25, 1.0]);+ let mut w = PcraftWriter::new();+ FAIL_DIR_FLUSH.with(|f| f.set(Some("tiles")));+ let e = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap_err();+ assert!(e.to_string().contains("could not be flushed"), "{e}");+ assert!(!dir.join(MANIFEST).exists(), "nothing committed");+ let written = list_objects(&dir).unwrap();+ assert_eq!(written.iter().filter(|o| o.starts_with("tiles/")).count(), 1, "{written:?}");+ FLUSHED.with(|f| f.borrow_mut().clear());+ let stats = w.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();+ assert_eq!(stats.tiles_written, 0, "the tile is reused");+ let flushed = FLUSHED.with(|f| f.borrow().clone());+ let tiles = flushed.iter().position(|d| *d == dir.join("tiles"));+ let manifest = flushed.iter().rposition(|d| *d == dir);+ assert!(tiles.is_some() && tiles < manifest, "tiles flushed before the manifest: {flushed:?}");+ assert_eq!(crate::load_path(&dir).unwrap(), doc);+ std::fs::remove_dir_all(dir).unwrap();+}+fn list_objects(dir: &Path) -> Result<HashSet<String>> {let mut out = HashSet::new();for sub in ["tiles", "blobs"] {