From 9dc3da1b71afbdef3136fa4bf9a3ab40933a6d5b Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 19 Oct 2026 21:39:50 -0700 Subject: [PATCH] fix(notebook): a move or copy tells what happened when its last steps fail A local rename now refuses, without a check beforehand, a name a file takes meanwhile, where the volume can rename so; a mounted share that can't, as macOS's smbfs, renames as before. A section file created in a local folder is flushed with a plain fsync where macOS's smbfs refuses F_FULLFSYNC, as onestore's commits are, so a notebook on a mounted share makes sections again, and a folder that can't sync its entries is not an error. A rename into the recycle bin that landed before a close or a folder's sync failed counts as a move, not as a section kept in both notebooks. A move reads the section's listing before copying, so a listing that changed since refuses it before any copy is made. The moved section's replica is deleted only while nothing holds it. A copy is written under a hidden name of its own, so two clients copying like-named sections into one folder never take each other's. Refs #105 Assisted-by: claude-opus-5.5 --- crates/notebook/src/session.rs | 82 +++++++++++++++++++++------- crates/notebook/src/session/tests.rs | 34 +++++++++++- 2 files changed, 94 insertions(+), 22 deletions(-) diff --git a/crates/notebook/src/session.rs b/crates/notebook/src/session.rs index 65a5c10d23de3a47552eac0977b91d6c4ca39149..eee84a17bdf0981a5cb4141ae84c230c75567385 100644 --- a/crates/notebook/src/session.rs +++ b/crates/notebook/src/session.rs @@ -123,15 +123,31 @@ pub trait Storage: Send + Sync { } } -/// Makes the entry naming `path` in its folder durable, where the system lets a folder sync. -fn synced_folder(path: &Path) -> Result<()> { +/// Makes the entry naming `path` in its folder durable, where the volume lets a folder sync; +/// a mounted share may not. +fn synced_folder(path: &Path) { #[cfg(unix)] - if let Some(folder) = path.parent() { - fs::File::open(folder)?.sync_all()?; + if let Some(folder) = path.parent() + && let Ok(folder) = fs::File::open(folder) + { + let _ = synced(&folder); } #[cfg(not(unix))] let _ = path; - Ok(()) +} + +/// `file.sync_all()`, which on a volume without macOS's F_FULLFSYNC, as an SMB mount is, falls +/// back to a plain fsync, as `onestore`'s commits do. +fn synced(file: &fs::File) -> io::Result<()> { + let result = file.sync_all(); + #[cfg(target_vendor = "apple")] + if result + .as_ref() + .is_err_and(|error| error.raw_os_error() == Some(nix::libc::ENOTSUP)) + { + return nix::unistd::fsync(file).map_err(io::Error::from); + } + result } /// A section that changed while it moved, which stays where it was. @@ -227,8 +243,9 @@ impl Storage for Directory { } let mut file = fs::File::create_new(&path)?; file.write_all(bytes)?; - file.sync_all()?; - synced_folder(&path) + synced(&file)?; + synced_folder(&path); + Ok(()) } fn create_directory(&self, path: &str) -> Result<()> { @@ -286,8 +303,21 @@ impl Storage for Directory { { return Err(io::Error::from(io::ErrorKind::AlreadyExists).into()); } - fs::rename(self.path(from), &to)?; - synced_folder(&to) + // A file takes a name nothing holds even should one appear meanwhile, where the volume + // can rename so; a mounted share that can't (macOS's smbfs refuses with ENOTSUP, and + // links none) takes a plain rename after the check above. + let from = self.path(from); + let renamed = match fs::metadata(&from)?.is_file() { + true => fs::rename_new(&from, &to), + false => fs::rename(&from, &to), + }; + match renamed { + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error.into()), + Err(_) => fs::rename(&from, &to)?, + Ok(()) => {} + } + synced_folder(&to); + Ok(()) } /// A local file system shows no other writer's hold; one that refuses to rename a folder @@ -1192,9 +1222,15 @@ impl Notebook { target = format!("{stem} ({attempt}).{extension}"); } let binned = catalog_path(RECYCLE_BIN, &target); - match base { - Some(base) => self.storage.rename_unchanged(path, &binned, base)?, - None => self.storage.rename(path, &binned)?, + let renamed = match base { + Some(base) => self.storage.rename_unchanged(path, &binned, base), + None => self.storage.rename(path, &binned), + }; + // A rename that landed before what followed it failed, a close or a folder's sync. + if let Err(error) = renamed + && (self.storage.exists(path) || !self.storage.exists(&binned)) + { + return Err(error); } Ok((bin_toc, bin_identity, target)) } @@ -1539,12 +1575,11 @@ impl Notebook { ) -> Result { let replica = Arc::clone(section.replica()); section.close()?; + let (from, name) = split(path); + let (entry, file) = (self.entry(from, name)?, self.replica_path(path)); let (image, stamp) = self.copied(path, &replica)?; let newest = replica.pending()?.last().map(|edit| edit.id); - let copy = target.place_copy(image, split(path).1, folder, after)?; - let (from, name) = split(path); - let entry = self.entry(from, name)?; - let file = self.replica_path(path); + let copy = target.place_copy(image, name, folder, after)?; let left = (|| { if replica.pending()?.last().map(|edit| edit.id) != newest { return Err(changed()); @@ -1570,7 +1605,10 @@ impl Notebook { }); let _ = self.refresh(); drop(replica); - if let Ok(file) = file { + // Unless something else opened it meanwhile. + if let Ok(file) = file + && crate::closed(&file).is_ok() + { let _ = remove_replica(&file); } Ok(Moved { @@ -1641,10 +1679,12 @@ impl Notebook { let (_, ancestor) = self.toc(folder)?; onestore::place_image(&mut image, Some((ancestor, &name(1))))?; let identity = onestore::Store::parse(&image)?.header.file_id; - let written = catalog_path(folder, &format!(".{stem}.one.snowbound")); - if self.storage.exists(&written) { - self.storage.delete(&written)?; - } + // A name of its own, should another client copy a section so named here meanwhile. + let mut unique = [0; 8]; + getrandom::fill(&mut unique) + .map_err(|_| io::Error::other("System random source failed"))?; + let unique: String = unique.iter().map(|byte| format!("{byte:02x}")).collect(); + let written = catalog_path(folder, &format!(".{stem}.one.{unique}.snowbound")); self.storage.create(&written, &image)?; let named = (|| { if self.storage.read(&written)? != image { diff --git a/crates/notebook/src/session/tests.rs b/crates/notebook/src/session/tests.rs index c8d38b9a52b2aa23387bc60e2f8812f375cf1375..3c29c6406cc0815af75cdeda92e78a5dbe7b59d6 100644 --- a/crates/notebook/src/session/tests.rs +++ b/crates/notebook/src/session/tests.rs @@ -196,6 +196,8 @@ struct FaultStorage { receipt: Option>>, /// Placing a section file in its folder fails. misplace: bool, + /// A checked rename lands, then reports a failure, as a close failing after it does. + torn: bool, } #[derive(Default)] @@ -300,7 +302,11 @@ impl Storage for FaultStorage { } fn rename_unchanged(&self, from: &str, to: &str, base: &Stamp) -> Result<()> { self.race(from); - self.inner.rename_unchanged(from, to, base) + self.inner.rename_unchanged(from, to, base)?; + match self.torn { + true => Err(io::Error::from(io::ErrorKind::BrokenPipe).into()), + false => Ok(()), + } } } @@ -354,6 +360,7 @@ fn a_section_changed_while_it_moves_stays_where_it_was() { revision: Mutex::new(revision), receipt: None, misplace: false, + torn: false, }, true, ); @@ -379,6 +386,7 @@ fn a_move_whose_bin_listing_fails_has_still_moved() { revision: Mutex::new(None), receipt: None, misplace: true, + torn: false, }, false, ); @@ -428,6 +436,7 @@ fn a_password_never_overwrites_a_concurrent_revision() { revision: Mutex::new(Some((path.clone(), revision))), receipt: None, misplace: false, + torn: false, }; let mut notebook = Notebook::with(Box::new(storage), Some(root), &cache).unwrap(); let set = notebook.set_password(&path, None, Some("secret")); @@ -467,6 +476,7 @@ fn recycling_confirms_uncertain_toc_and_page_appends_and_undo() { revision: Mutex::new(None), receipt: Some(receipt.clone()), misplace: false, + torn: false, }; let mut notebook = Notebook::with(Box::new(storage), Some(root), &cache).unwrap(); notebook @@ -539,6 +549,7 @@ fn recycling_rejects_unconfirmed_appends_and_can_retry_each_stage() { revision: Mutex::new(None), receipt: Some(receipt.clone()), misplace: false, + torn: false, }; let mut notebook = Notebook::with(Box::new(storage), Some(root), &cache).unwrap(); assert!( @@ -975,3 +986,24 @@ fn a_cache_owned_while_closed_opens_for_nobody_else() { drop(lock); drop(Replica::open(&cache).unwrap()); } + +/// A section whose rename into the bin landed, though what followed it failed, has moved. +#[test] +fn a_move_whose_rename_lands_and_then_fails_has_still_moved() { + let temporary = tempfile::tempdir().unwrap(); + let (mut source, mut target, path) = moving( + temporary.path(), + |inner, _| FaultStorage { + inner, + revision: Mutex::new(None), + receipt: None, + misplace: false, + torn: true, + }, + false, + ); + let section = source.section(&path, false, || {}).unwrap(); + let moved = (source.move_section(&path, section, &mut target, "", None)).unwrap(); + assert!(moved.kept.is_none(), "{:?}", moved.kept); + assert!(source.storage.exists(&catalog_path(RECYCLE_BIN, &path))); +} -- 2.54.1