Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/vuio-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
179 changes: 179 additions & 0 deletions crates/vuio-core/src/lifecycle/media/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,185 @@ mod tests {
}
}

async fn browse_video(state: &AppState<SqliteDatabase>) -> 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,
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>\
<u:Browse xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">\
<ObjectID>video</ObjectID><BrowseFlag>BrowseDirectChildren</BrowseFlag>\
<Filter>*</Filter><StartingIndex>0</StartingIndex><RequestedCount>0</RequestedCount>\
<SortCriteria></SortCriteria></u:Browse></s:Body></s:Envelope>"
.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("<TotalMatches>1</TotalMatches>"));
assert!(after.contains("<UpdateID>2</UpdateID>"));
}
}

#[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("<TotalMatches>1</TotalMatches>"));
assert!(after.contains("<UpdateID>2</UpdateID>"));
}
}

/// An AIFF carrying an ID3v2.3 tag: a title, one tag with no column of its
/// own, and `frames` samples at 44.1 kHz.
///
Expand Down
41 changes: 17 additions & 24 deletions crates/vuio-core/src/lifecycle/media/monitoring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,30 +188,23 @@ pub(in crate::lifecycle) async fn start_file_monitoring<D: DatabaseManager + 'st
if let Err(error) = refresh_unavailable_roots(&app_state_clone).await {
error!("Failed to refresh unavailable-root visibility: {}", error);
}
// Only alongside a sweep. This walks the whole index and asks
// the filesystem about every path in it, which on a large
// library is the most expensive thing the tick can do — and
// a deletion inside a watched root already arrives as an
// event and is handled per-path. Like the sweep above, this
// is the backstop for what the watcher missed, so it runs on
// the backstop's cadence rather than every five minutes.
//
// Gated on the setting, and read live so it can be changed
// without a restart. Ungated, `cleanup_deleted_files = false`
// did not prevent deletions at all — the startup scan honoured
// it and this tick then removed the same files five minutes later.
if full_sweep_due || !dirty_roots.is_empty() {
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),
}
// 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),
}
}
}
Expand Down
99 changes: 97 additions & 2 deletions crates/vuio-core/src/lifecycle/media/scanning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ pub(in crate::lifecycle) async fn validate_and_cleanup_deleted_files<D: Database
for media_file in page {
total_checked += 1;

// Radio URLs share this table with local files, but cannot be
// checked against the filesystem or assigned to a library root.
let location = media_file.path.to_string_lossy();
if location
.get(..7)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("http://"))
|| location
.get(..8)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://"))
{
continue;
}

let Some(root_index) =
owning_root_index(&media_file.path, monitored_roots, &canonical_roots)
else {
Expand All @@ -134,11 +147,12 @@ pub(in crate::lifecycle) async fn validate_and_cleanup_deleted_files<D: Database
}
}

// `exists()` blocks. One hop to the blocking pool per page beats one per
// `try_exists()` blocks. One hop to the blocking pool per page beats one per
// file on an async worker, which is what a library-sized index used to do.
if !to_probe.is_empty() {
let missing = tokio::task::spawn_blocking(move || {
to_probe.retain(|path| !path.exists());
// Permission and I/O errors mean unreachable, not deleted.
to_probe.retain(|path| matches!(path.try_exists(), Ok(false)));
to_probe
})
.await?;
Expand Down Expand Up @@ -343,6 +357,26 @@ pub(crate) async fn refresh_unavailable_roots<D: DatabaseManager>(
Ok(())
}

/// Refresh the startup library and retire responses served while it was loading.
pub(in crate::lifecycle) async fn initialize_media_library<D: DatabaseManager + 'static>(
app_state: &AppState<D>,
) -> 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<D: DatabaseManager + 'static>(
config: &AppConfig,
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading