From 402ed7674389aa833575ca6c891b294d5556267c Mon Sep 17 00:00:00 2001 From: vyrti Date: Sat, 10 Oct 2026 23:38:57 +0300 Subject: [PATCH 1/2] Refresh TV listings after startup cleanup and missed deletions --- crates/vuio-core/Cargo.toml | 1 + .../vuio-core/src/lifecycle/media/events.rs | 179 ++++++++++++++++++ .../src/lifecycle/media/monitoring.rs | 41 ++-- .../vuio-core/src/lifecycle/media/scanning.rs | 99 +++++++++- crates/vuio-core/src/lifecycle/runner.rs | 17 +- crates/vuio-core/src/watcher/mod.rs | 26 +-- crates/vuio-core/src/watcher/tests.rs | 35 ++++ 7 files changed, 351 insertions(+), 47 deletions(-) diff --git a/crates/vuio-core/Cargo.toml b/crates/vuio-core/Cargo.toml index eaa52682..d046a836 100644 --- a/crates/vuio-core/Cargo.toml +++ b/crates/vuio-core/Cargo.toml @@ -211,6 +211,7 @@ windows = { version = "0.62", features = [ ] } [dev-dependencies] +tokio = { version = "1.53", features = ["test-util"] } # `default-features = false` is load-bearing. Cargo unifies a package's own # dev-dependency on itself back into the package, so without it every test # build turned the default features back on — `--no-default-features` compiled diff --git a/crates/vuio-core/src/lifecycle/media/events.rs b/crates/vuio-core/src/lifecycle/media/events.rs index 353d3bf3..ad2d1a09 100644 --- a/crates/vuio-core/src/lifecycle/media/events.rs +++ b/crates/vuio-core/src/lifecycle/media/events.rs @@ -607,6 +607,185 @@ mod tests { } } + async fn browse_video(state: &AppState) -> String { + let mut headers = axum::http::HeaderMap::new(); + headers.insert( + "soapaction", + axum::http::HeaderValue::from_static( + "\"urn:schemas-upnp-org:service:ContentDirectory:1#Browse\"", + ), + ); + headers.insert( + "user-agent", + axum::http::HeaderValue::from_static("DLNADOC/1.50 SEC_HHP_[TV]UE40D7000/1.0"), + ); + let response = crate::web::soap::content_directory_control( + axum::extract::State(state.clone()), + headers, + "\ + \ + videoBrowseDirectChildren\ + *00\ + " + .to_owned(), + ) + .await; + assert_eq!(response.status(), axum::http::StatusCode::OK); + String::from_utf8( + axum::body::to_bytes(response.into_body(), 128 * 1024) + .await + .expect("response body") + .to_vec(), + ) + .expect("UTF-8 response") + } + + #[tokio::test] + async fn startup_cleanup_retires_tv_responses_served_before_the_scan() { + for scan_on_startup in [false, true] { + let temp = tempfile::TempDir::new().expect("temp dir"); + let root = std::fs::canonicalize(temp.path()).expect("canonical root"); + let state = state_watching(&root).await; + let mut config = (*state.current_config()).clone(); + config.media.scan_on_startup = scan_on_startup; + config.media.scan_playlists = false; + state.live_config.store(Arc::new(config)); + + let present = root.join("here.mp4"); + let deleted = root.join("gone.mp4"); + std::fs::write(&present, b"video").expect("present file"); + std::fs::write(&deleted, b"video").expect("deleted file"); + for path in [&present, &deleted] { + state + .database + .store_media_file(&database::MediaFile::new( + path.clone(), + 5, + "video/mp4".to_owned(), + )) + .await + .expect("index file"); + } + assert!(browse_video(&state).await.contains("gone.mp4")); + assert!(!state.browse_cache.lock().await.is_empty()); + std::fs::remove_file(&deleted).expect("delete file while server is offline"); + + super::super::scanning::initialize_media_library(&state) + .await + .expect("startup scan"); + + assert!(state + .database + .get_file_by_path(&deleted) + .await + .expect("query") + .is_none()); + assert!(state.browse_cache.lock().await.is_empty()); + assert_eq!(state.content_update_id.load(Ordering::SeqCst), 2); + let after = browse_video(&state).await; + assert!(!after.contains("gone.mp4")); + assert!(after.contains("here.mp4")); + assert!(after.contains("1")); + assert!(after.contains("2")); + } + } + + #[tokio::test(start_paused = true)] + async fn missed_deletions_refresh_tv_browse_without_waiting_for_a_full_rescan() { + for full_rescan_interval_hours in [0, 24] { + let temp = tempfile::TempDir::new().expect("temp dir"); + let root = std::fs::canonicalize(temp.path()).expect("canonical root"); + let state = state_watching(&root).await; + let mut config = (*state.current_config()).clone(); + config.media.full_rescan_interval_hours = full_rescan_interval_hours; + config.media.cleanup_deleted_files = false; + state.live_config.store(Arc::new(config.clone())); + + let present = root.join("here.mp4"); + let deleted = root.join("gone.mp4"); + let deleted_folder = root.join("deleted-folder"); + std::fs::write(&present, b"video").expect("present file"); + std::fs::write(&deleted, b"video").expect("deleted file"); + std::fs::create_dir(&deleted_folder).expect("folder"); + let nested = deleted_folder.join("nested.mp4"); + std::fs::write(&nested, b"video").expect("nested file"); + for path in [&present, &deleted, &nested] { + state + .database + .store_media_file(&database::MediaFile::new( + path.clone(), + 5, + "video/mp4".to_owned(), + )) + .await + .expect("index file"); + } + let before = browse_video(&state).await; + assert!(before.contains("gone.mp4")); + assert!(before.contains("deleted-folder")); + assert!(!state.browse_cache.lock().await.is_empty()); + + // Remove before the watcher starts: no deletion events or dirty roots + // can help the periodic check, just as on a NAS that drops events. + std::fs::remove_file(&deleted).expect("delete file"); + std::fs::remove_dir_all(&deleted_folder).expect("delete folder"); + let watcher = Arc::new(CrossPlatformWatcher::new()); + let cancellation = CancellationToken::new(); + let handle = super::super::monitoring::start_file_monitoring( + watcher.clone(), + state.clone(), + cancellation.clone(), + ) + .await + .expect("monitoring") + .expect("enabled monitoring"); + tokio::task::yield_now().await; + tokio::time::advance(std::time::Duration::from_secs(300)).await; + assert!(state + .database + .get_file_by_path(&deleted) + .await + .expect("query") + .is_some()); + assert_eq!(state.content_update_id.load(Ordering::SeqCst), 1); + + // Honour the live cleanup setting, independently of full discovery. + config.media.cleanup_deleted_files = true; + state.live_config.store(Arc::new(config)); + tokio::time::advance(std::time::Duration::from_secs(300)).await; + let reconciled = tokio::time::timeout(std::time::Duration::from_secs(10), async { + while state.content_update_id.load(Ordering::SeqCst) == 1 { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await; + cancellation.cancel(); + handle.await.expect("monitoring task"); + watcher.stop_watching().await.expect("stop watcher"); + reconciled.expect("missed deletions must be reconciled within one tick"); + + assert!(state + .database + .get_file_by_path(&deleted) + .await + .expect("query") + .is_none()); + assert!(state + .database + .get_file_by_path(&nested) + .await + .expect("query") + .is_none()); + assert!(state.browse_cache.lock().await.is_empty()); + let after = browse_video(&state).await; + assert!(!after.contains("gone.mp4")); + assert!(!after.contains("deleted-folder")); + assert!(after.contains("here.mp4")); + assert!(after.contains("1")); + assert!(after.contains("2")); + } + } + /// An AIFF carrying an ID3v2.3 tag: a title, one tag with no column of its /// own, and `frames` samples at 44.1 kHz. /// diff --git a/crates/vuio-core/src/lifecycle/media/monitoring.rs b/crates/vuio-core/src/lifecycle/media/monitoring.rs index af042fca..1f8cdc3b 100644 --- a/crates/vuio-core/src/lifecycle/media/monitoring.rs +++ b/crates/vuio-core/src/lifecycle/media/monitoring.rs @@ -188,30 +188,23 @@ pub(in crate::lifecycle) async fn start_file_monitoring 0 => increment_content_update_id(&app_state_clone).await, - Ok(_) => {} - Err(error) => error!("Periodic missing-file reconciliation failed: {}", error), - } + // A backend can silently miss a deletion without marking a + // root dirty. Check indexed paths every tick, independently + // of full discovery, so TVs do not retain missing files for + // 24 hours (or forever when full rescans are disabled). + // The check pages through fingerprints without re-walking + // directories or reading media metadata, and honours the + // live cleanup setting and unavailable-root grace period. + match validate_and_cleanup_deleted_files( + app_state_clone.database.clone(), + &configured_directories, + app_state_clone.current_config().media.cleanup_deleted_files, + ) + .await + { + Ok(removed) if removed > 0 => increment_content_update_id(&app_state_clone).await, + Ok(_) => {} + Err(error) => error!("Periodic missing-file reconciliation failed: {}", error), } } } diff --git a/crates/vuio-core/src/lifecycle/media/scanning.rs b/crates/vuio-core/src/lifecycle/media/scanning.rs index edbd7fba..d90960b4 100644 --- a/crates/vuio-core/src/lifecycle/media/scanning.rs +++ b/crates/vuio-core/src/lifecycle/media/scanning.rs @@ -112,6 +112,19 @@ pub(in crate::lifecycle) async fn validate_and_cleanup_deleted_files( Ok(()) } +/// Refresh the startup library and retire responses served while it was loading. +pub(in crate::lifecycle) async fn initialize_media_library( + app_state: &AppState, +) -> anyhow::Result<()> { + let config = app_state.current_config(); + perform_initial_media_scan(&config, &app_state.database).await?; + refresh_unavailable_roots(app_state).await?; + + // Referenced media must be indexed before playlists are imported. + if let Err(error) = perform_initial_playlist_scan(&config, &app_state.database).await { + warn!("Failed to scan playlist files: {}", error); + } + + // Listeners are already serving while the scan runs. A TV may have cached + // files from the previous session before cleanup removed them, so the + // completed scan must invalidate Browse and notify subscribed clients. + increment_content_update_id(app_state).await; + Ok(()) +} + /// Perform initial media scan, using database cache when possible pub(in crate::lifecycle) async fn perform_initial_media_scan( config: &AppConfig, @@ -734,6 +768,67 @@ mod tests { assert_eq!(indexed_paths(&database).await, vec![canonical_root(&present)]); } + #[tokio::test] + async fn missing_file_cleanup_preserves_radio_stream_urls() { + let root = tempfile::TempDir::new().expect("root"); + let present = root.path().join("here.mp4"); + let deleted = root.path().join("gone.mp4"); + let streams = [ + PathBuf::from("HTTP://radio.example/live"), + PathBuf::from("https://radio.example/live"), + ]; + std::fs::write(&present, b"x").expect("write"); + let (database, _temp) = database_with(&[ + present.clone(), + deleted, + streams[0].clone(), + streams[1].clone(), + ]) + .await; + + let removed = validate_and_cleanup_deleted_files( + database.clone(), + &[root.path().to_path_buf()], + true, + ) + .await + .expect("cleanup"); + + assert_eq!(removed, 1); + let paths = indexed_paths(&database).await; + assert_eq!(paths.len(), 3); + assert!(paths.contains(&canonical_root(&present))); + for stream in streams { + assert!(paths.contains(&stream), "radio URLs are not missing files"); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn inaccessible_files_are_not_treated_as_deleted() { + use std::os::unix::fs::PermissionsExt; + + let root = tempfile::TempDir::new().expect("root"); + let folder = root.path().join("restricted"); + std::fs::create_dir(&folder).expect("folder"); + let file = folder.join("keep.mp4"); + std::fs::write(&file, b"x").expect("write"); + let (database, _temp) = database_with(std::slice::from_ref(&file)).await; + let stored = canonical_root(&file); + let original_permissions = std::fs::metadata(&folder).expect("metadata").permissions(); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o000)).expect("restrict"); + let cleanup = validate_and_cleanup_deleted_files( + database.clone(), + &[root.path().to_path_buf()], + true, + ) + .await; + std::fs::set_permissions(&folder, original_permissions).expect("restore permissions"); + + assert_eq!(cleanup.expect("cleanup"), 0); + assert_eq!(indexed_paths(&database).await, vec![stored]); + } + /// The cleanup reads the index a page at a time rather than holding all of it, so /// an index larger than one page is the case where a paging mistake shows: rows /// past the first page silently never get checked, and deleted files stay indexed diff --git a/crates/vuio-core/src/lifecycle/runner.rs b/crates/vuio-core/src/lifecycle/runner.rs index 8857756c..0ccaefbc 100644 --- a/crates/vuio-core/src/lifecycle/runner.rs +++ b/crates/vuio-core/src/lifecycle/runner.rs @@ -166,7 +166,11 @@ where auth: auth.clone(), platform_info: platform_info.clone(), filesystem_manager, - content_update_id: Arc::new(std::sync::atomic::AtomicU32::new(1)), + // A TV may retain its last revision across a server restart. A fresh + // boot revision prevents it from mistaking this library for that cache. + content_update_id: Arc::new(std::sync::atomic::AtomicU32::new( + uuid::Uuid::new_v4().as_u128() as u32, + )), web_metrics: Arc::new(crate::web::diagnostics::WebHandlerMetrics::new()), runtime_diagnostics: Arc::new(crate::platform::diagnostics::SystemDiagnosticsSampler::new()), lifecycle_stats: lifecycle_stats.clone(), @@ -343,17 +347,10 @@ where // Scan only after the watcher and listeners are active. This closes the startup blind // window: a download that lands while the scan is running is either found // by the scan or delivered by the watcher (and duplicate upserts are safe). - if let Err(e) = perform_initial_media_scan(&config, &database).await { - error!("Failed to perform initial media scan: {}", e); + if let Err(e) = initialize_media_library(&app_state).await { + error!("Failed to initialize media library: {}", e); return Err(e); } - refresh_unavailable_roots(&app_state).await?; - - // Perform initial playlist file scan after media scan so referenced files exist. - if let Err(e) = perform_initial_playlist_scan(&config, &database).await { - // Log warning but don't fail startup - playlists are not critical - warn!("Failed to scan playlist files: {}", e); - } // Start runtime platform adaptation services let adaptation_handle = start_platform_adaptation( diff --git a/crates/vuio-core/src/watcher/mod.rs b/crates/vuio-core/src/watcher/mod.rs index 1d8fca47..fe703e3f 100644 --- a/crates/vuio-core/src/watcher/mod.rs +++ b/crates/vuio-core/src/watcher/mod.rs @@ -333,17 +333,21 @@ fn convert_watcher_events( } } notify::EventKind::Other | notify::EventKind::Any => { - // Only process existing media files for generic/other events - let media_paths: Vec<_> = event - .event - .paths - .iter() - .filter(|path| path.is_file() && path_is_relevant(path, policies)) - .collect(); - - for path in media_paths { - debug!("Media file other event: {}", path.display()); - fs_events.push(FileSystemEvent::Modified(path.clone())); + for path in &event.event.paths { + // Some backends cannot classify the change. A missing path + // still needs to remove indexed content, including a folder's + // descendants. An I/O error does not establish a deletion. + if matches!(path.try_exists(), Ok(false)) + && ScanPolicy::for_path(policies, path).is_some() + { + fs_events.push(FileSystemEvent::Deleted { + path: path.clone(), + is_directory: None, + }); + } else if path.is_file() && path_is_relevant(path, policies) { + debug!("Media file other event: {}", path.display()); + fs_events.push(FileSystemEvent::Modified(path.clone())); + } } } } diff --git a/crates/vuio-core/src/watcher/tests.rs b/crates/vuio-core/src/watcher/tests.rs index 964ec397..098fb6ac 100644 --- a/crates/vuio-core/src/watcher/tests.rs +++ b/crates/vuio-core/src/watcher/tests.rs @@ -208,3 +208,38 @@ fn test_convert_watcher_events_handles_modify() { _ => panic!("Expected FileSystemEvent::Modified"), } } + +#[test] +fn generic_events_report_missing_files_and_directories_as_deletions() { + let root = TempDir::new().unwrap(); + let policies = vec![ScanPolicy::platform_default(root.path(), true)]; + let missing_file = root.path().join("gone.mp4"); + let missing_directory = root.path().join("deleted-folder"); + let present = root.path().join("here.mp4"); + let unrelated = root.path().join("notes.txt"); + fs::write(&present, b"video").unwrap(); + fs::write(&unrelated, b"notes").unwrap(); + + for kind in [notify::EventKind::Any, notify::EventKind::Other] { + let event = DebouncedEvent { + event: notify::Event::new(kind) + .add_path(missing_file.clone()) + .add_path(missing_directory.clone()) + .add_path(present.clone()) + .add_path(unrelated.clone()), + time: std::time::Instant::now(), + }; + let converted = convert_watcher_events(vec![event], &policies); + assert_eq!(converted.len(), 3, "event kind {kind:?}"); + for (event, expected) in converted[..2] + .iter() + .zip([&missing_file, &missing_directory]) + { + assert!( + matches!(event, FileSystemEvent::Deleted { path, is_directory: None } if path == expected), + "missing paths must reach index cleanup: {event:?}" + ); + } + assert!(matches!(&converted[2], FileSystemEvent::Modified(path) if path == &present)); + } +} From 388411e2e3b5d50e474eef4d86d8c13d0e29b249 Mon Sep 17 00:00:00 2001 From: vyrti Date: Sat, 17 Oct 2026 05:57:52 +0300 Subject: [PATCH 2/2] Pin the per-boot ContentDirectory revision seeding behind a test --- crates/vuio-core/src/lifecycle/runner.rs | 35 ++++++++++++++++++++---- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/vuio-core/src/lifecycle/runner.rs b/crates/vuio-core/src/lifecycle/runner.rs index 0ccaefbc..d8172ed1 100644 --- a/crates/vuio-core/src/lifecycle/runner.rs +++ b/crates/vuio-core/src/lifecycle/runner.rs @@ -166,11 +166,7 @@ where auth: auth.clone(), platform_info: platform_info.clone(), filesystem_manager, - // A TV may retain its last revision across a server restart. A fresh - // boot revision prevents it from mistaking this library for that cache. - content_update_id: Arc::new(std::sync::atomic::AtomicU32::new( - uuid::Uuid::new_v4().as_u128() as u32, - )), + content_update_id: Arc::new(std::sync::atomic::AtomicU32::new(boot_content_revision())), web_metrics: Arc::new(crate::web::diagnostics::WebHandlerMetrics::new()), runtime_diagnostics: Arc::new(crate::platform::diagnostics::SystemDiagnosticsSampler::new()), lifecycle_stats: lifecycle_stats.clone(), @@ -571,3 +567,32 @@ impl ApplicationRunner { run_application(options).await } } + +/// The ContentDirectory revision a fresh boot starts from. +/// +/// A TV may retain its last revision across a server restart. The revision +/// used to restart at 1 on every boot: a TV that had recorded a revision of 1 +/// before a restart found nothing new about the rebooted server, however much +/// the library had changed underneath it, and kept serving its own cached +/// listing — with files that had been deleted since. A random per-boot value +/// differs from the previous session's revision, so the TV refetches at least +/// once per boot. +fn boot_content_revision() -> u32 { + uuid::Uuid::new_v4().as_u128() as u32 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The revision used to restart at 1 on every boot, which is what let a TV + /// keep deleted files in its listing across a server restart. Reproducing + /// that crash needs an actual TV, but the step that enables it — a boot + /// revision equal to the one every previous session ended on — is checked + /// here. A random seed matches 1 with probability 2^-32, so in practice the + /// assert fires only if the seeding is deliberately replaced. + #[test] + fn a_fresh_boot_does_not_restart_the_revision_at_one() { + assert_ne!(boot_content_revision(), 1); + } +}