fix(downloads): stop libraries mixing, make pause/resume real, reap partials, end bitrate corruption

Four defects behind "downloads still flaky", each with its own cause.

Libraries mixed their media (DR-167). Cached items carry no link back to their
library — library_id and parent_id are NULL on every row — so the library branch
of get_downloaded_items matched `EXISTS (SELECT 1 FROM libraries WHERE id = ?)`,
which asserts only that the library exists and never constrains the item to it.
Opening any downloaded library listed every downloaded top-level item on the
server: films under Music, albums under TV. The query deciding which libraries
appear already had the right rule, so the two disagreed about the same question;
that collection_type <-> item_type mapping is now one constant used by both.

Pause and resume did nothing (DR-168). pause_download wrote status = 'paused'
and stopped there — no cancellation existed anywhere in the download stack, so
the streaming task ran on and overwrote the row with completed/failed when it
finished. The row flicked to "paused" and undid itself. resume_download had the
mirror defect: it flipped the row to 'pending' without pumping, and the pump is
not a poller, so a resumed download sat until some unrelated event pumped the
queue. Adds a per-download stop flag the worker reads between chunks and on
retry, returning Stopped — not retryable, not recorded as a failure, and the
.part file is kept because that is what the resume continues from. Registering
returns a fresh flag so a resumed download does not inherit the pause that
stopped it. Cancel and clear_stale_downloads signal it too, so neither deletes a
file still being written.

Partial files were never reaped (DR-169). The worker named its sidecar with
with_extension("part"), which replaces: movie.mp4 became movie.part. Every
cleanup path deleted "{file_path}.part" — movie.mp4.part. They never matched, so
the partial of every cancelled or failed download stayed on disk forever,
invisible to disk-usage totals because no row pointed at it. One partial_path
helper now serves the writer and the cleaners.

Bitrate downloads corrupted themselves (DR-170). Only `original` asks for
Static=true; every other rung requests a transcode, which Jellyfin serves
chunked with no Content-Length and cannot byte-seek — it ignores Range and
answers 200 with the whole stream, not 206 with the tail. The worker sent the
header whenever a .part existed and appended the body regardless, so each retry
concatenated another full copy onto what was on disk. The file grew past its
real size and would not play, which is why bitrate downloads stayed broken after
the videoBitRate casing fix corrected the request. resume_offset now lets the
response decide: append only on 206, otherwise truncate and take it from the top.

docs/requirements.md also carries DR-171/UT-166, written by a parallel session
working in the same tree; its code lands separately.
This commit is contained in:
2026-08-15 23:52:02 +02:00
parent d49d027020
commit a5535f2941
5 changed files with 422 additions and 39 deletions
+150
View File
@@ -0,0 +1,150 @@
//! Stop signalling for in-flight downloads.
//!
//! TRACES: UR-055 | DR-168
//!
//! Pausing and cancelling used to be database-only: `pause_download` wrote
//! `status = 'paused'` and nothing else. No cancellation existed anywhere in the
//! download stack — no token, no flag, no abort — so the streaming task kept
//! running, kept writing bytes, and on finishing overwrote the row with
//! `completed` or `failed`. The row flicked to "paused" and then undid itself,
//! which is precisely the reported "pause does not work".
//!
//! This is the missing half: a flag per in-flight download that the worker reads
//! between chunks. Setting it makes the worker return [`Stopped`] promptly and
//! leave the `.part` file **intact**, which is what lets a resume pick up from
//! where it stopped via the existing HTTP Range request.
//!
//! Kept as a module-level registry rather than on `DownloadManager` because the
//! two sides never meet: the command handler holds the manager's lock, while the
//! worker runs detached inside `tauri::async_runtime::spawn` with no access to
//! Tauri state. A registry both can reach is the smallest thing that works.
//!
//! [`Stopped`]: crate::download::worker::DownloadError::Stopped
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use crate::utils::lock::MutexSafe;
/// download id → its stop flag, for downloads currently in flight.
fn registry() -> &'static Mutex<HashMap<i64, Arc<AtomicBool>>> {
static REGISTRY: OnceLock<Mutex<HashMap<i64, Arc<AtomicBool>>>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
/// Register `download_id` as in-flight and hand back its stop flag.
///
/// Called by the worker as it starts. A previous flag for the same id is
/// replaced, so a download that is paused and later resumed does not inherit the
/// set flag from its last run and stop immediately.
pub fn register(download_id: i64) -> Arc<AtomicBool> {
let flag = Arc::new(AtomicBool::new(false));
registry().lock_safe().insert(download_id, flag.clone());
flag
}
/// Ask an in-flight download to stop.
///
/// Returns whether one was actually in flight — the caller uses this to tell a
/// running download (which will stop shortly) from a merely queued one (which
/// the database update alone has already handled).
pub fn signal(download_id: i64) -> bool {
match registry().lock_safe().get(&download_id) {
Some(flag) => {
flag.store(true, Ordering::SeqCst);
true
}
None => false,
}
}
/// Forget a download's flag. Called when its task finishes, however it ended.
pub fn clear(download_id: i64) {
registry().lock_safe().remove(&download_id);
}
/// Whether a stop has been requested for `download_id`.
///
/// The worker reads its own `Arc<AtomicBool>` directly rather than looking the id
/// up, so this exists for the tests that assert the registry's behaviour.
#[cfg(test)]
pub fn is_stopping(download_id: i64) -> bool {
registry()
.lock_safe()
.get(&download_id)
.map(|f| f.load(Ordering::SeqCst))
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
/// Ids are per-test so the shared registry cannot leak between them.
fn unique_id(seed: i64) -> i64 {
900_000 + seed
}
#[test]
fn test_a_registered_download_starts_unflagged() {
let id = unique_id(1);
let flag = register(id);
assert!(!flag.load(Ordering::SeqCst));
assert!(!is_stopping(id));
clear(id);
}
#[test]
fn test_signal_sets_the_flag_the_worker_reads() {
let id = unique_id(2);
let flag = register(id);
assert!(signal(id), "a registered download reports as in flight");
assert!(
flag.load(Ordering::SeqCst),
"the worker's own handle sees it"
);
assert!(is_stopping(id));
clear(id);
}
/// The pump only needs to abort a task that exists; a queued row is handled
/// by its database status alone.
#[test]
fn test_signalling_an_unregistered_download_reports_not_in_flight() {
assert!(!signal(unique_id(3)));
}
#[test]
fn test_clear_forgets_the_download() {
let id = unique_id(4);
register(id);
signal(id);
clear(id);
assert!(!is_stopping(id));
assert!(!signal(id), "a cleared download is no longer in flight");
}
/// The bug this guards: pause sets the flag, and resume re-runs the same
/// download id. If registering reused the old flag, the resumed run would see
/// a set flag and stop instantly — a download that could never be resumed.
#[test]
fn test_reregistering_clears_a_previous_stop() {
let id = unique_id(5);
register(id);
signal(id);
assert!(is_stopping(id));
let fresh = register(id);
assert!(!fresh.load(Ordering::SeqCst));
assert!(
!is_stopping(id),
"a resumed download must not inherit the pause"
);
clear(id);
}
}