//! Sizes of item folders on disk, for the library lists. //! //! Adding up a big library is slow on a NAS, so sizes are cached in the store //! and worked out by a single background worker, one folder at a time. Listing //! a library returns whatever is cached straight away and queues every folder //! for checking; the UI asks again until every size has arrived. //! //! A cached size is trusted until the folder's *signature* changes (the //! modified times of the folder and its direct subfolders, which change when //! files are added, removed or renamed in them), and is measured again anyway //! after [`MAX_AGE`] to catch changes deeper down. The signature itself is //! only re-read every [`RECHECK`], so opening a library doesn't touch every //! folder on disk each time. use std::collections::{HashSet, VecDeque}; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; use crate::state::{AppState, Shared}; /// How often a cached size's signature is checked against the disk. pub const RECHECK: time::Duration = time::Duration::hours(1); /// How long a size is trusted even if the signature hasn't changed. pub const MAX_AGE: time::Duration = time::Duration::days(7); /// Size of an item folder: what a move would copy. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FolderSize { pub bytes: u64, pub files: u64, /// Direct subfolders, e.g. a show's seasons or a movie's extras. Bytes in /// files directly inside the folder are `bytes` minus these. pub parts: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartSize { pub name: String, pub bytes: u64, pub files: u64, } #[derive(Debug, Clone, Serialize, Deserialize)] struct Record { size: FolderSize, signature: u64, #[serde(with = "time::serde::rfc3339")] measured_at: OffsetDateTime, #[serde(with = "time::serde::rfc3339")] checked_at: OffsetDateTime, } #[derive(Default)] pub struct SizeQueue { inner: Mutex, } #[derive(Default)] struct QueueState { queue: VecDeque, queued: HashSet, running: bool, } /// Cached sizes for these local folders, in the same order (`None` where /// nothing is cached yet). Every folder is queued for checking. pub async fn lookup(state: &Shared, folders: &[PathBuf]) -> anyhow::Result>> { let keys: Vec = folders.iter().map(|p| key(p)).collect(); let mut cached: std::collections::HashMap = state.store.get_folder_sizes(keys.clone()).await?; enqueue(state, folders.iter().cloned()); Ok(keys .iter() .map(|k| cached.remove(k).map(|r| r.size)) .collect()) } fn enqueue(state: &Shared, folders: impl IntoIterator) { let mut q = state.sizes.inner.lock().expect("size queue"); for f in folders { if q.queued.insert(f.clone()) { q.queue.push_back(f); } } if !q.running && !q.queue.is_empty() { q.running = true; tokio::spawn(worker(state.clone())); } } /// One folder at a time, so a NAS isn't asked to walk several at once. async fn worker(state: Shared) { loop { let next = { let mut q = state.sizes.inner.lock().expect("size queue"); match q.queue.pop_front() { Some(p) => { q.queued.remove(&p); p } None => { q.running = false; return; } } }; if let Err(e) = refresh(&state, &next).await { tracing::warn!(folder = %next.display(), error = %format!("{e:#}"), "could not measure folder"); } } } async fn refresh(state: &Shared, folder: &Path) -> anyhow::Result<()> { let k = key(folder); let cached: Option = state .store .get_folder_sizes(vec![k.clone()]) .await? .remove(&k); let now = OffsetDateTime::now_utc(); if cached.as_ref().is_some_and(|r| now - r.checked_at < RECHECK) { return Ok(()); } let f = folder.to_path_buf(); let Some(sig) = tokio::task::spawn_blocking(move || signature(&f)).await? else { // Gone, e.g. moved away. Forget it. state.store.delete_folder_size(&k).await?; return Ok(()); }; let record = match cached { Some(mut r) if r.signature == sig && now - r.measured_at < MAX_AGE => { r.checked_at = now; r } _ => { let f = folder.to_path_buf(); let size = tokio::task::spawn_blocking(move || measure(&f)).await?; Record { size, signature: sig, measured_at: now, checked_at: now, } } }; state.store.put_folder_size(&k, &record).await?; Ok(()) } /// Drop the cached size of a folder a move has just changed, so the next /// listing measures it again instead of waiting for the hourly check. pub async fn forget(state: &AppState, folder: &Path) { if let Err(e) = state.store.delete_folder_size(&key(folder)).await { tracing::warn!(folder = %folder.display(), error = %e, "could not forget folder size"); } } fn key(p: &Path) -> String { p.to_string_lossy().into_owned() } fn skipped(name: &std::ffi::OsStr) -> bool { name.to_string_lossy().starts_with(jm_transfer::HIDDEN_PREFIX) } /// Modified times of the folder and its direct subfolders, hashed. `None` if /// the folder doesn't exist. pub fn signature(folder: &Path) -> Option { let meta = std::fs::symlink_metadata(folder).ok()?; if !meta.is_dir() { return None; } let mut h = std::collections::hash_map::DefaultHasher::new(); meta.modified().ok().hash(&mut h); let mut subdirs: Vec<(std::ffi::OsString, Option)> = std::fs::read_dir(folder) .ok()? .flatten() .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !skipped(&e.file_name())) .map(|e| (e.file_name(), e.metadata().and_then(|m| m.modified()).ok())) .collect(); subdirs.sort(); subdirs.hash(&mut h); Some(h.finish()) } /// Add up every regular file below `folder`, counting the same files a move /// copies: links and jellymove's own `.jellymove-*` entries are skipped. pub fn measure(folder: &Path) -> FolderSize { let mut total = PartSize { name: String::new(), bytes: 0, files: 0, }; let mut parts = Vec::new(); for e in std::fs::read_dir(folder).into_iter().flatten().flatten() { if skipped(&e.file_name()) { continue; } let Ok(t) = e.file_type() else { continue }; if t.is_dir() { let (bytes, files) = tree(&e.path()); parts.push(PartSize { name: e.file_name().to_string_lossy().into_owned(), bytes, files, }); total.bytes += bytes; total.files += files; } else if t.is_file() { total.bytes += e.metadata().map(|m| m.len()).unwrap_or(0); total.files += 1; } } parts.sort_by_key(|p| natural_key(&p.name)); FolderSize { bytes: total.bytes, files: total.files, parts, } } fn tree(dir: &Path) -> (u64, u64) { let mut bytes = 0; let mut files = 0; let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { if skipped(&e.file_name()) { continue; } let Ok(t) = e.file_type() else { continue }; if t.is_dir() { stack.push(e.path()); } else if t.is_file() { bytes += e.metadata().map(|m| m.len()).unwrap_or(0); files += 1; } } } (bytes, files) } /// Sort "Season 2" before "Season 10". fn natural_key(s: &str) -> Vec<(String, u64)> { let mut out = Vec::new(); let mut text = String::new(); let mut num = String::new(); for c in s.chars() { if c.is_ascii_digit() { num.push(c); } else { if !num.is_empty() { out.push((std::mem::take(&mut text), num.parse().unwrap_or(u64::MAX))); num.clear(); } text.extend(c.to_lowercase()); } } out.push((text, num.parse().unwrap_or(0))); out } #[cfg(test)] mod tests { use super::*; fn write(p: &Path, len: usize) { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, vec![0u8; len]).unwrap(); } #[test] fn measures_files_and_direct_subfolders() { let tmp = tempfile::tempdir().unwrap(); let show = tmp.path().join("Severance"); write(&show.join("tvshow.nfo"), 10); write(&show.join("Season 10/e.mkv"), 300); write(&show.join("Season 2/e1.mkv"), 100); write(&show.join("Season 2/e2.mkv"), 200); write(&show.join("Season 2/subs/e1.srt"), 5); write(&show.join(".jellymove-partial/x.part"), 999); #[cfg(unix)] std::os::unix::fs::symlink(show.join("Season 2/e1.mkv"), show.join("link.mkv")).unwrap(); let s = measure(&show); assert_eq!((s.bytes, s.files), (615, 5)); let parts: Vec<_> = s.parts.iter().map(|p| (p.name.as_str(), p.bytes, p.files)).collect(); assert_eq!(parts, [("Season 2", 305, 3), ("Season 10", 300, 1)]); } #[test] fn signature_changes_when_a_season_changes() { let tmp = tempfile::tempdir().unwrap(); let show = tmp.path().join("Show"); write(&show.join("Season 1/e1.mkv"), 1); let before = signature(&show).unwrap(); assert_eq!(signature(&show), Some(before)); // Adding an episode changes the season folder's modified time. let s1 = show.join("Season 1"); let old = std::fs::metadata(&s1).unwrap().modified().unwrap(); write(&s1.join("e2.mkv"), 1); let file = std::fs::File::open(&s1).unwrap(); file.set_modified(old + std::time::Duration::from_secs(5)).unwrap(); assert_ne!(signature(&show), Some(before)); assert_eq!(signature(&tmp.path().join("missing")), None); } #[test] fn natural_order() { let mut v = vec!["Season 10", "Specials", "Season 2", "Season 1"]; v.sort_by_key(|s| natural_key(s)); assert_eq!(v, ["Season 1", "Season 2", "Season 10", "Specials"]); } }