Show folder sizes for movies, shows and seasons. Closes #5
CI / test (push) Successful in 1m12s

The library lists now show how much space each movie and show takes on disk, counting everything a move copies, with a per-season breakdown for shows, a running total and a "Largest first" sort.

- sizes.rs: a single background worker measures one folder at a time. Listing returns cached sizes straight away and queues folders; the UI
  polls until every size has arrived.
- Cached in a new folder_sizes table (store migration v2). A size is kept while the folder's signature (mtimes of the folder and its direct
  subfolders) is unchanged, checked at most hourly and re-measured after 7 days.
- Each agent measures its own folders, so peer listings carry the peer's sizes.
- Tests for measuring, signatures, natural season order, the migration, and an e2e test covering both sides and a moved item.
This commit is contained in:
IxianPixel committed 2026-11-06 16:43:52 +00:00
1 parent 4c6217bd40
commit 25a743b350
11 files changed
+672 -26

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ pub mod export;
pub mod library;
pub mod peer;
pub mod runner;
pub mod sizes;
pub mod state;
pub mod trash;
pub mod ui;
+37 -5
View File
@@ -1,11 +1,12 @@
//! Browsing the local Jellyfin libraries.
use std::path::Path;
use std::path::{Path, PathBuf};
use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize};
use crate::state::AppState;
use crate::sizes::{self, FolderSize};
use crate::state::{AppState, Shared};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Library {
@@ -23,6 +24,9 @@ pub struct LibraryItem {
pub kind: String,
pub year: Option<i32>,
pub path: Option<String>,
/// Size of the item's folder on disk; `None` until it has been measured.
#[serde(default)]
pub size: Option<FolderSize>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -55,8 +59,10 @@ pub async fn libraries(state: &AppState) -> anyhow::Result<Vec<Library>> {
.collect())
}
/// The movies and series in a library, with the size of each one's folder if
/// it's known yet. Sizes still missing are being measured in the background.
pub async fn items(
state: &AppState,
state: &Shared,
library_id: &str,
search: Option<&str>,
) -> anyhow::Result<Vec<LibraryItem>> {
@@ -71,7 +77,7 @@ pub async fn items(
..Default::default()
})
.await?;
Ok(items
let mut out: Vec<LibraryItem> = items
.into_iter()
.map(|i| LibraryItem {
id: i.id,
@@ -79,8 +85,34 @@ pub async fn items(
kind: i.kind,
year: i.production_year,
path: i.path,
size: None,
})
.collect())
.collect();
// Only items whose folder we can place are measured.
let folders: Vec<(usize, PathBuf)> = out
.iter()
.enumerate()
.filter_map(|(n, i)| Some((n, item_folder(state, i)?)))
.collect();
let paths: Vec<PathBuf> = folders.iter().map(|(_, p)| p.clone()).collect();
let sizes = sizes::lookup(state, &paths).await?;
for ((n, _), size) in folders.into_iter().zip(sizes) {
out[n].size = size;
}
Ok(out)
}
/// The folder a move would take, as this agent sees it: a movie's parent
/// folder, or the series folder itself.
fn item_folder(state: &AppState, item: &LibraryItem) -> Option<PathBuf> {
let path = Path::new(item.path.as_deref()?);
let folder = match item.kind.as_str() {
"Movie" => path.parent()?,
"Series" => path,
_ => return None,
};
Some(state.cfg.path_map.to_local(folder))
}
/// Confirm every library location exists and is writable from this agent.
+313
View File
@@ -0,0 +1,313 @@
//! 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::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<PartSize>,
}
#[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<QueueState>,
}
#[derive(Default)]
struct QueueState {
queue: VecDeque<PathBuf>,
queued: HashSet<PathBuf>,
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<Vec<Option<FolderSize>>> {
let keys: Vec<String> = folders.iter().map(|p| key(p)).collect();
let mut cached: std::collections::HashMap<String, Record> =
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<Item = PathBuf>) {
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<Record> = 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(())
}
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<u64> {
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::time::SystemTime>)> =
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"]);
}
}
+3
View File
@@ -21,6 +21,8 @@ pub struct AppState {
pub running: Mutex<HashSet<JobId>>,
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
pub preparing: Mutex<HashSet<String>>,
/// Folders waiting to have their size measured.
pub sizes: crate::sizes::SizeQueue,
}
pub type Shared = Arc<AppState>;
@@ -58,6 +60,7 @@ impl AppState {
job_slots: Arc::new(Semaphore::new(slots)),
running: Mutex::new(HashSet::new()),
preparing: Mutex::new(HashSet::new()),
sizes: Default::default(),
})
}
+50
View File
@@ -517,6 +517,56 @@ async fn an_item_moved_away_twice_gets_two_trash_entries() {
assert_eq!(home_trash[0]["moved_to"], "cloud");
}
/// List a library until every item has a size, like the UI does.
async fn items_with_sizes(base: &str, query: &str) -> Vec<Value> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let items = get(base, &format!("/api/items?{query}")).await;
let items = items.as_array().unwrap().clone();
if !items.is_empty() && items.iter().all(|i| i["size"].is_object()) {
return items;
}
assert!(Instant::now() < deadline, "sizes never arrived: {items:#?}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
#[tokio::test]
async fn lists_folder_sizes_for_movies_shows_and_seasons() {
let (cloud, home) = pair(|root| {
seed_movie(root);
seed_series(root);
})
.await;
// A movie's size is its whole folder: video, subtitles, NFO and extras.
let movies = items_with_sizes(&cloud.url, "node=local&library=lib-movies").await;
let alien = &movies[0]["size"];
assert_eq!(alien["bytes"], tree_size(&cloud.movies().join("Alien (1979)")));
assert_eq!(alien["files"], 4);
// A show has a total plus one part per season folder; loose files such
// as tvshow.nfo count towards the total only.
let shows = items_with_sizes(&home.url, "node=peer&library=lib-tv-shows").await;
let s = &shows[0]["size"];
assert_eq!(shows[0]["name"], "Severance");
assert_eq!(s["bytes"], tree_size(&cloud.tv().join("Severance")));
assert_eq!(s["files"], 4);
assert_eq!(
s["parts"],
json!([
{"name": "Season 01", "bytes": 22, "files": 2},
{"name": "Season 02", "bytes": 13, "files": 1},
])
);
// After a move the item is measured where it now lives.
let movie = cloud.fake.find("Movie", "Alien").unwrap();
move_item(&cloud.url, "local", &movie, "Alien").await;
let on_home = items_with_sizes(&home.url, "node=local&library=lib-movies").await;
assert_eq!(on_home[0]["size"], *alien);
}
#[tokio::test]
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
let (cloud, _home) = pair(|_| {}).await;
+100
View File
@@ -3,6 +3,7 @@
//! Jobs and exports are stored as JSON documents with a few indexed columns.
//! The schema is deliberately small; the job struct is the source of truth.
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -33,6 +34,11 @@ const MIGRATIONS: &[&str] = &[
id TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
// v2: cached sizes of item folders, keyed by local path.
"CREATE TABLE folder_sizes (
path TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
];
#[derive(Clone)]
@@ -161,6 +167,54 @@ impl Store {
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
.transpose()
}
/// Cached folder sizes for `paths`. Paths with no record are left out.
pub async fn get_folder_sizes<T: DeserializeOwned>(
&self,
paths: Vec<String>,
) -> Result<HashMap<String, T>> {
let rows: Vec<(String, String)> = self
.with(move |c| {
let mut out = Vec::new();
let mut stmt = c.prepare_cached("SELECT path, body FROM folder_sizes WHERE path = ?1")?;
for p in &paths {
if let Some(row) = stmt
.query_row([p], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?
{
out.push(row);
}
}
Ok(out)
})
.await?;
rows.into_iter()
.map(|(p, b)| Ok((p, serde_json::from_str(&b)?)))
.collect()
}
pub async fn put_folder_size<T: Serialize>(&self, path: &str, size: &T) -> Result<()> {
let path = path.to_string();
let body = serde_json::to_string(size)?;
self.with(move |c| {
c.execute(
"INSERT INTO folder_sizes (path, body) VALUES (?1, ?2)
ON CONFLICT(path) DO UPDATE SET body = excluded.body",
params![path, body],
)?;
Ok(())
})
.await
}
pub async fn delete_folder_size(&self, path: &str) -> Result<()> {
let path = path.to_string();
self.with(move |c| {
c.execute("DELETE FROM folder_sizes WHERE path = ?1", [path])?;
Ok(())
})
.await
}
}
#[cfg(test)]
@@ -205,4 +259,50 @@ mod tests {
let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap();
assert_eq!(e["x"], 1);
}
#[tokio::test]
async fn folder_sizes_roundtrip() {
let store = Store::in_memory().unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 1}))
.await
.unwrap();
store
.put_folder_size("/m/A", &serde_json::json!({"bytes": 2}))
.await
.unwrap();
store
.put_folder_size("/m/B", &serde_json::json!({"bytes": 3}))
.await
.unwrap();
let got: HashMap<String, serde_json::Value> = store
.get_folder_sizes(vec!["/m/A".into(), "/m/B".into(), "/m/C".into()])
.await
.unwrap();
assert_eq!(got.len(), 2);
assert_eq!(got["/m/A"]["bytes"], 2);
store.delete_folder_size("/m/A").await.unwrap();
let got: HashMap<String, serde_json::Value> =
store.get_folder_sizes(vec!["/m/A".into()]).await.unwrap();
assert!(got.is_empty());
}
#[test]
fn upgrades_a_v1_database() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.db");
{
let c = Connection::open(&path).unwrap();
c.execute_batch(MIGRATIONS[0]).unwrap();
c.pragma_update(None, "user_version", 1).unwrap();
}
Store::open(&path).unwrap();
let c = Connection::open(&path).unwrap();
let v: i64 = c
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v as usize, MIGRATIONS.len());
c.execute("INSERT INTO folder_sizes (path, body) VALUES ('p', '{}')", [])
.unwrap();
}
}