diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index ed6faae9..ca4347e8 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -29,7 +29,16 @@ //! file if the source never had one), and a new book appears in the //! root only whole: every stored file re-hashed against its name, //! every file the books name present, verified end to end, synced to -//! disk, and its head equal to the source's. +//! disk, and its head equal to the source's. The original is left as it +//! was: a lock file the adoption made in the source is removed again, +//! exactly that file and no other, on every way out but its success +//! (stopped by the books server's close, refused, or a panic); one the +//! source already had is never removed. A success leaves the one it +//! made, and says so (`source_lock_created`). Books are made, adopted +//! and restored one at a time across processes (`run/books.lock`), and +//! a job waiting for its turn looks at its stop every few milliseconds +//! and leaves at once when asked, so a close of the books is never held +//! up by a job that is only queued. //! 6. No error names the root or a path inside it: nothing an agent is //! shown names the books' folder. //! 7. Restoring a backup (plan 3.7) is proven before use, as an adoption @@ -816,8 +825,11 @@ impl Root { } /// Take the lock under which books are made: one at a time, across - /// processes. - fn books_lock(&self) -> Result { + /// processes. A job that has to wait for another's turn looks at `stop` + /// while it waits (every few milliseconds), and gives up with `Stopped` + /// if asked: a close of the books can't be held up by a job that is + /// only waiting its turn behind another. + fn books_lock(&self, stop: &JobStop, undone: &str) -> Result { let (run, _) = self.private_subdir(RUN_DIR, false)?; let path = run.join(BOOKS_LOCK); let file = std::fs::OpenOptions::new() @@ -826,8 +838,22 @@ impl Root { .write(true) .open(&path)?; set_mode(&path, 0o600)?; - file.lock()?; - Ok(file) + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::WouldBlock) => { + // The flag alone: the phase watch is told of phases, not + // of every turn of this wait. + if stop.requested() { + return Err(RootError::Stopped(format!( + "stopped because the books are closing: nothing was {undone}" + ))); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Err(std::fs::TryLockError::Error(e)) => return Err(e.into()), + } + } } /// Start new, empty books called `id` in `base_currency`. Refused if @@ -855,7 +881,7 @@ impl Root { base_currency: Currency, stop: &JobStop, ) -> Result { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "created")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dir = books.join(id.as_str()); if std::fs::symlink_metadata(&dir).is_ok() { @@ -921,7 +947,7 @@ impl Root { options: &AdoptOptions, stop: &JobStop, ) -> Result { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "adopted")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dest = books.join(id.as_str()); if std::fs::symlink_metadata(&dest).is_ok() { @@ -943,7 +969,8 @@ impl Root { } // Step 1: the source's writer lock, held to the end, so nothing // writes it while it is copied. - let (_source_lock, source_lock_created) = lock_source(&source)?; + let mut source_lock = lock_source(&source)?; + let source_lock_created = source_lock.created(); // Step 2: verify the chain and record the head. (The chain's check // looks at the stop once per journal line.) let scope = crate::cancel::scope(stop.flag()); @@ -1081,6 +1108,10 @@ impl Root { }); if renamed.is_err() { let _ = std::fs::remove_dir_all(&staging); + } else { + // Adopted: a lock file made in the source stays and is reported + // (`source_lock_created`). Any other way out, it goes. + source_lock.keep(); } renamed } @@ -1185,7 +1216,7 @@ impl Root { ) -> Result { let _scope = crate::cancel::scope(stop.flag()); (|| { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?; let vault = scratch.join(VAULT_DIR); @@ -1260,7 +1291,7 @@ impl Root { replace: bool, stop: &JobStop, ) -> Result { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dest = books.join(id.as_str()); let exists = std::fs::symlink_metadata(&dest).is_ok(); @@ -1275,12 +1306,16 @@ impl Root { } // Books being replaced are moved only while nothing holds them. let _held = if exists { - Some(lock_source(&dest).map_err(|_| { + let mut held = lock_source(&dest).map_err(|_| { RootError::Adopt(format!( "the books called {:?} are open: close them first; nothing was restored", id.as_str() )) - })?) + })?; + // The root's own folder: its lock file is the books', whoever + // made it. + held.keep(); + Some(held) } else { None }; @@ -1585,7 +1620,10 @@ impl Root { // Held for writing: nothing is moved from under it. A preview // only looks; the move holds the lock to the end. let _lock = if confirm { - Some(lock_source(source)?.0) + let mut lock = lock_source(source)?; + // The old copy is moved whole, lock file and all. + lock.keep(); + Some(lock) } else { if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE)) && let Err(std::fs::TryLockError::WouldBlock) = lock.try_lock_shared() @@ -2034,9 +2072,63 @@ pub struct AdoptReport { /// The source's writer lock: its lock file opened read-only (so a /// read-only source can be adopted and nothing in it changes), or, for -/// books that never had one, created. Returns the lock and whether the -/// file was made. -fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { +/// books that never had one, created. +/// +/// A lock file this made is the adoption's own, not the source's: unless +/// the adoption succeeds (the caller says so with [`SourceLock::keep`]), +/// it is removed when this is dropped, whatever way out the adoption took +/// (stopped by a close, failed, or a panic): the original is left as it +/// was. A lock file that was there already is never removed, nor is a +/// file this didn't make: the path must still name the very file this +/// holds, on systems that can tell. +struct SourceLock { + file: Option, + path: PathBuf, + created: bool, + keep: bool, +} + +impl SourceLock { + /// The source had no lock file, so taking its lock made one. + fn created(&self) -> bool { + self.created + } + + /// The lock file stays, whatever this made: the adoption is done (and + /// reports it), or the folder is the root's own. + fn keep(&mut self) { + self.keep = true; + } +} + +impl Drop for SourceLock { + fn drop(&mut self) { + if !self.created || self.keep { + return; + } + let Some(file) = self.file.take() else { + return; + }; + // Still the file this made? (Never one another process put there.) + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let same = match (file.metadata(), std::fs::symlink_metadata(&self.path)) { + (Ok(mine), Ok(there)) => mine.dev() == there.dev() && mine.ino() == there.ino(), + _ => false, + }; + if !same { + return; + } + } + // Let go of the lock first (a file that is open can't be removed on + // every system), then remove exactly that file. + drop(file); + let _ = std::fs::remove_file(&self.path); + } +} + +fn lock_source(source: &Path) -> Result { let path = source.join(crate::store::LOCK_FILE); let (file, created) = match std::fs::File::open(&path) { Ok(file) => (file, false), @@ -2045,7 +2137,15 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { } Err(e) => return Err(e.into()), }; - if !created { + // From here the guard owns the file this may have made, so a refusal + // below removes it too. + let held = SourceLock { + file: Some(file), + path, + created, + keep: false, + }; + if !created && let Some(file) = &held.file { match file.try_lock() { Ok(()) => {} Err(std::fs::TryLockError::WouldBlock) => { @@ -2058,7 +2158,7 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { Err(std::fs::TryLockError::Error(e)) => return Err(e.into()), } } - Ok((file, created)) + Ok(held) } /// The head of a verified journal: the last line's seq and the hash the diff --git a/crates/ledger-store/tests/root.rs b/crates/ledger-store/tests/root.rs index 84d28509..dc220c7f 100644 --- a/crates/ledger-store/tests/root.rs +++ b/crates/ledger-store/tests/root.rs @@ -1876,3 +1876,201 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i Some("place") ); } + +/// A folder, name for name and byte for byte: every file and every folder +/// in it, with its bytes and its mode. +fn tree_exact(dir: &Path) -> Vec<(PathBuf, Option>, u32)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap() { + let p = e.unwrap().path(); + let is_dir = std::fs::symlink_metadata(&p).unwrap().is_dir(); + out.push(( + p.strip_prefix(dir).unwrap().to_path_buf(), + (!is_dir).then(|| std::fs::read(&p).unwrap()), + mode(&p), + )); + if is_dir { + stack.push(p); + } + } + } + out.sort(); + out +} + +/// An adoption makes the source's lock file when the source has none (INVARIANT +/// 5), and the original is to be left as it was: so a lock file the adoption +/// itself made is removed on every way out but its success (stopped by a close +/// at any phase, refused, or a panic), exactly that file and nothing else; one +/// the source already had is never removed, and a success leaves the one it +/// made and says so. +#[test] +fn an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source() { + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + let home = tmp("adopt-lock"); + let (root, _) = Root::setup(home.path(), None, None).unwrap(); + let old = tmp("adopt-lock-src"); + drop(source_books(old.path(), true)); + let lock = old.path().join(ledger_store::LOCK_FILE); + std::fs::remove_file(&lock).unwrap(); + let before = tree_exact(old.path()); + assert!( + before + .iter() + .all(|(n, ..)| n != Path::new(ledger_store::LOCK_FILE)) + ); + let options = AdoptOptions::default(); + // Stopped at every phase, before the lock is taken and after. + for phase in [ + "start", "journal", "copy", "file", "open", "verify", "place", + ] { + let (stop, _) = stopping_at(phase); + let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert_eq!( + tree_exact(old.path()), + before, + "the source after an adoption stopped at {phase}" + ); + } + // Refused after the lock: the books changed since the preview. + let wrong = AdoptOptions { + expect_head: Some((999, "not the head".into())), + ..AdoptOptions::default() + }; + let e = refused(root.adopt(old.path(), &id("adopted"), &wrong)); + assert!(e.to_string().contains("changed since the preview"), "{e}"); + assert_eq!(tree_exact(old.path()), before, "after a refusal"); + // A panic, in the middle of the copy. + let flag = Arc::new(AtomicBool::new(false)); + let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(|p: &str| { + if p == "verify" { + panic!("a panic in the middle of an adoption"); + } + })); + let gone = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop) + .map(|_| ()) + })); + assert!(gone.is_err(), "the adoption panicked"); + assert_eq!(tree_exact(old.path()), before, "after a panic"); + assert!(root.list_books().unwrap().is_empty()); + // The lock held while the adoption runs is gone with it: the source can + // be taken for writing at once. + drop(Store::open(old.path()).unwrap()); + std::fs::remove_file(&lock).unwrap(); + // Not removed when it isn't the file the adoption made: a lock file put + // there by someone else while the adoption ran (it was swapped at the + // last phase) stays. + let flag = Arc::new(AtomicBool::new(false)); + let swap = lock.clone(); + let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(move |p: &str| { + if p == "verify" { + std::fs::remove_file(&swap).unwrap(); + std::fs::write(&swap, b"someone else's").unwrap(); + panic!("stopped after the swap"); + } + })); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop) + .map(|_| ()) + })); + assert_eq!( + std::fs::read(&lock).unwrap(), + b"someone else's", + "a lock file the adoption did not make was removed" + ); + std::fs::remove_file(&lock).unwrap(); + assert_eq!(tree_exact(old.path()), before); + // A source that had its lock file keeps it, stopped or not: the folder + // is as it was, and the adoption reports it made none. + drop(Store::open(old.path()).unwrap()); + let had = tree_exact(old.path()); + assert!( + had.iter() + .any(|(n, ..)| n == Path::new(ledger_store::LOCK_FILE)) + ); + for phase in ["copy", "verify", "place"] { + let (stop, _) = stopping_at(phase); + let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert_eq!(tree_exact(old.path()), had, "a lock it had, at {phase}"); + } + let report = root.adopt(old.path(), &id("adopted"), &options).unwrap(); + assert!(!report.source_lock_created); + assert_eq!(tree_exact(old.path()), had); + // And a success of a source with none leaves the one it made, as before. + let fresh = tmp("adopt-lock-src2"); + drop(source_books(fresh.path(), true)); + std::fs::remove_file(fresh.path().join(ledger_store::LOCK_FILE)).unwrap(); + let report = root.adopt(fresh.path(), &id("second"), &options).unwrap(); + assert!(report.source_lock_created); + assert!(fresh.path().join(ledger_store::LOCK_FILE).is_file()); +} + +/// A job waiting for another's turn at making books (they are made one at a +/// time, across processes) gives up when it is asked to stop, whatever the +/// job holding the turn does: a close can't be held up by a job that is only +/// queued. A job that isn't asked to stop waits its turn, and goes through +/// when it comes. +#[test] +fn a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let home = tmp("turn"); + let (root, _) = Root::setup(home.path(), None, None).unwrap(); + // Another process's turn: the lock file is held. + let turn = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(root.path().join("run/books.lock")) + .unwrap(); + turn.lock().unwrap(); + let flag = Arc::new(AtomicBool::new(false)); + let waiting = { + let flag = flag.clone(); + let root = root.clone(); + std::thread::spawn(move || { + root.create_book_stoppable( + &id("queued"), + Currency::USD, + &ledger_store::root::JobStop::new(flag), + ) + .map(|_| ()) + }) + }; + // Queued: it has not made its folder, nor stopped, while the turn is + // held and nothing asks it to. + let by = std::time::Instant::now() + std::time::Duration::from_millis(400); + while std::time::Instant::now() < by { + assert!(!waiting.is_finished(), "it didn't wait for its turn"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + flag.store(true, Ordering::SeqCst); + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !waiting.is_finished() { + assert!( + std::time::Instant::now() < by, + "a job waiting for its turn didn't stop when asked" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let e = refused(waiting.join().unwrap()); + assert!(matches!(e, RootError::Stopped(_)), "{e:?}"); + assert!(e.to_string().contains("nothing was created"), "{e}"); + assert!(!root.book_dir(&id("queued")).exists()); + // Not asked: it waits, and goes through when the turn is let go. + let other = { + let root = root.clone(); + std::thread::spawn(move || root.create_book(&id("patient"), Currency::USD).map(|_| ())) + }; + std::thread::sleep(std::time::Duration::from_millis(150)); + assert!(!other.is_finished()); + drop(turn); + other.join().unwrap().unwrap(); + assert_eq!(root.list_books().unwrap(), vec![id("patient")]); +}