//! The index of finished downloads (`library.json` in the data directory). //! //! Download engines are the only writers: each records an entry when a job //! finishes. The TUI and `libbui download` run separate engines that may be //! live at the same time, so every change goes through //! [`LibraryIndex::update`], a read-modify-write under an exclusive lock on //! `library.json.lock` that re-reads the file inside the lock. //! //! The UI reads the index to mark titles as downloaded and to offer "open //! folder". A file the user moved or deleted is reported as //! [`Presence::Missing`]; entries are never dropped silently, because //! "downloaded" quietly turning into "not downloaded" would be confusing. use std::path::{Path, PathBuf}; use jiff::Timestamp; use serde::{Deserialize, Serialize}; use crate::StateFileError; use crate::download::FileKind; use crate::fsutil::FormatV1; /// One finished download. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LibraryEntry { /// Libby title id. pub title_id: String, /// Title, for display when the title is no longer on the shelf. pub title: String, /// Where the file is. pub path: PathBuf, /// What kind of file it is. pub kind: FileKind, /// Lowercase hex SHA-256 recorded when it was downloaded. pub sha256: String, /// Size in bytes. pub bytes: u64, /// When the download finished. pub finished_at: Timestamp, } /// Whether an entry's file is still where it was put. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Presence { /// The file exists. Present, /// The file is gone (moved, deleted, or its drive is not mounted). Missing, } impl LibraryEntry { /// Checks the filesystem for the entry's file. pub fn presence(&self) -> Presence { if self.path.is_file() { Presence::Present } else { Presence::Missing } } /// The folder holding the file, for "open folder". pub fn folder(&self) -> Option<&Path> { self.path.parent() } } #[derive(Serialize, Deserialize)] struct OnDisk { version: FormatV1, entries: Vec, } /// The loaded index. #[derive(Debug, Clone, PartialEq, Eq)] pub struct LibraryIndex { path: PathBuf, entries: Vec, } impl LibraryIndex { /// Loads the index at `path` (normally /// [`crate::paths::Paths::library_index_file`]). A missing file is an /// empty index. /// /// # Errors /// [`StateFileError::Io`], [`StateFileError::NewerVersion`] for an /// index written by a newer libbui (left in place), or /// [`StateFileError::Corrupt`] after moving an unreadable file aside. pub fn load(path: impl Into) -> Result { let path = path.into(); let entries = crate::fsutil::read_json_or_quarantine::(&path)? .map(|d| d.entries) .unwrap_or_default(); Ok(Self { path, entries }) } /// Applies `change` to the index at `path` as one locked /// read-modify-write: takes the exclusive lock (waiting up to ten /// seconds for another process), loads the file as it is now, applies /// `change`, writes it atomically, and returns what was written. /// /// There is deliberately no plain `save`: writing back an index loaded /// earlier would drop entries another process recorded in between. /// /// # Errors /// [`StateFileError::Io`] (including a lock that stayed busy, as /// [`std::io::ErrorKind::TimedOut`]), [`StateFileError::Corrupt`] or /// [`StateFileError::Encode`]. Nothing is written without the lock. pub fn update( path: impl Into, change: impl FnOnce(&mut Self), ) -> Result { let path = path.into(); let _lock = crate::fsutil::lock_exclusive(&path, crate::fsutil::LOCK_WAIT).map_err(|source| { StateFileError::Io { path: path.clone(), source, } })?; let mut index = Self::load(path)?; change(&mut index); index.save()?; Ok(index) } /// Writes the index atomically. Only for [`Self::update`], which holds /// the lock. fn save(&self) -> Result<(), StateFileError> { crate::fsutil::write_json( &self.path, &OnDisk { version: FormatV1, entries: self.entries.clone(), }, ) } /// The backing file. pub fn path(&self) -> &Path { &self.path } /// Every entry, oldest first. pub fn entries(&self) -> &[LibraryEntry] { &self.entries } /// Adds `entry`, replacing an existing entry for the same file. pub fn record(&mut self, entry: LibraryEntry) { self.entries.retain(|e| e.path != entry.path); self.entries.push(entry); } /// Forgets the entry for `path`; returns whether there was one. For an /// explicit user action such as "forget missing file". pub fn forget(&mut self, path: &Path) -> bool { let before = self.entries.len(); self.entries.retain(|e| e.path != path); before != self.entries.len() } /// Entries for one title (a title can be downloaded as more than one /// kind, or twice). pub fn for_title<'a>(&'a self, title_id: &'a str) -> impl Iterator { self.entries.iter().filter(move |e| e.title_id == title_id) } /// Whether the title has at least one entry whose file is present. pub fn is_downloaded(&self, title_id: &str) -> bool { self.for_title(title_id) .any(|e| e.presence() == Presence::Present) } /// Entries whose file is gone. pub fn missing(&self) -> Vec<&LibraryEntry> { self.entries .iter() .filter(|e| e.presence() == Presence::Missing) .collect() } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; fn entry(dir: &Path, title_id: &str, name: &str) -> LibraryEntry { LibraryEntry { title_id: title_id.to_owned(), title: "Dune".to_owned(), path: dir.join(name), kind: FileKind::Epub, sha256: "00".repeat(32), bytes: 3, finished_at: Timestamp::from_second(1_700_000_000).unwrap(), } } #[test] fn round_trip_and_presence() { let dir = tempfile::tempdir().unwrap(); let index_path = dir.path().join("data/library.json"); assert!( LibraryIndex::load(&index_path) .unwrap() .entries() .is_empty() ); std::fs::write(dir.path().join("a.epub"), b"abc").unwrap(); let index = LibraryIndex::update(&index_path, |index| { index.record(entry(dir.path(), "1", "a.epub")); index.record(entry(dir.path(), "2", "b.epub")); // Recording the same file again replaces, not duplicates. index.record(entry(dir.path(), "1", "a.epub")); }) .unwrap(); let back = LibraryIndex::load(&index_path).unwrap(); assert_eq!(back, index); assert_eq!(back.entries().len(), 2); assert!(back.is_downloaded("1")); assert!(!back.is_downloaded("2")); assert!(!back.is_downloaded("3")); let missing = back.missing(); assert_eq!(missing.len(), 1); assert_eq!(missing[0].title_id, "2"); // Missing entries stay in the index. assert_eq!(back.for_title("2").count(), 1); assert_eq!(back.entries()[0].folder(), Some(dir.path())); } #[test] fn forget_removes_one_entry() { let dir = tempfile::tempdir().unwrap(); let mut index = LibraryIndex::load(dir.path().join("library.json")).unwrap(); index.record(entry(dir.path(), "1", "a.epub")); assert!(index.forget(&dir.path().join("a.epub"))); assert!(!index.forget(&dir.path().join("a.epub"))); assert!(index.entries().is_empty()); } #[test] fn concurrent_writers_lose_nothing() { // Each thread stands in for a process: its own handles, its own // read-modify-write cycles, all racing on one file. const WRITERS: usize = 8; const EACH: usize = 25; let dir = tempfile::tempdir().unwrap(); let index_path = dir.path().join("data/library.json"); let barrier = std::sync::Barrier::new(WRITERS); std::thread::scope(|scope| { for writer in 0..WRITERS { let (dir, index_path, barrier) = (dir.path(), &index_path, &barrier); scope.spawn(move || { barrier.wait(); for n in 0..EACH { let name = format!("{writer}-{n}.epub"); LibraryIndex::update(index_path, |index| { index.record(entry(dir, &writer.to_string(), &name)); }) .unwrap(); } }); } }); let index = LibraryIndex::load(&index_path).unwrap(); assert_eq!(index.entries().len(), WRITERS * EACH); for writer in 0..WRITERS { assert_eq!(index.for_title(&writer.to_string()).count(), EACH); } } #[test] fn a_busy_lock_is_an_error_not_an_unlocked_write() { let dir = tempfile::tempdir().unwrap(); let index_path = dir.path().join("library.json"); let _held = crate::fsutil::lock_exclusive(&index_path, std::time::Duration::ZERO).unwrap(); let blocked = std::thread::spawn({ let index_path = index_path.clone(); let dir = dir.path().to_path_buf(); move || { let start = std::time::Instant::now(); let result = LibraryIndex::update(&index_path, |index| { index.record(entry(&dir, "1", "a.epub")); }); (result, start.elapsed()) } }); let (result, waited) = blocked.join().unwrap(); let Err(StateFileError::Io { source, .. }) = result else { panic!("{result:?}") }; assert_eq!(source.kind(), std::io::ErrorKind::TimedOut); assert!(waited >= crate::fsutil::LOCK_WAIT, "{waited:?}"); assert!(!index_path.exists(), "nothing was written"); } #[test] fn corrupt_index_is_moved_aside() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("library.json"); std::fs::write(&path, b"{ nope").unwrap(); let err = LibraryIndex::load(&path).unwrap_err(); let StateFileError::Corrupt { moved_to, .. } = err else { panic!("{err:?}") }; assert_eq!(std::fs::read(moved_to).unwrap(), b"{ nope"); assert!(LibraryIndex::load(&path).unwrap().entries().is_empty()); } #[test] fn newer_index_is_an_error_and_stays_put() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("library.json"); let newer = br#"{"version":2,"books":[]}"#; std::fs::write(&path, newer).unwrap(); let err = LibraryIndex::load(&path).unwrap_err(); assert!( matches!(err, StateFileError::NewerVersion { version: 2, .. }), "{err:?}" ); // An update must not replace it with an empty v1 index either. assert!(LibraryIndex::update(&path, |_| {}).is_err()); assert_eq!(std::fs::read(&path).unwrap(), newer); } }