diff --git a/app/src/main/rust/stores/Cargo.lock b/app/src/main/rust/stores/Cargo.lock index 82e939b2eb..b259f7d3b1 100644 --- a/app/src/main/rust/stores/Cargo.lock +++ b/app/src/main/rust/stores/Cargo.lock @@ -170,6 +170,7 @@ dependencies = [ "flate2", "futures-util", "jni", + "libc", "reqwest", "serde_json", "sha1", diff --git a/app/src/main/rust/stores/Cargo.toml b/app/src/main/rust/stores/Cargo.toml index 0c3f7d9910..49c36453ef 100644 --- a/app/src/main/rust/stores/Cargo.toml +++ b/app/src/main/rust/stores/Cargo.toml @@ -14,6 +14,9 @@ crate-type = ["cdylib"] [dependencies] jni = "0.21" +# setpriority/gettid: every engine thread runs at nice +10 (see src/priority.rs). Already in the +# dependency tree through tokio, at the version Cargo.lock pins. +libc = "0.2" # zlib inflate for GOG gen2 chunks and Epic chunk bodies. The pure-Rust backend keeps the .so free # of a C zlib and of the NDK sysroot's libz, which the apk does not ship. flate2 = { version = "1", default-features = false, features = ["rust_backend"] } diff --git a/app/src/main/rust/stores/src/amazon.rs b/app/src/main/rust/stores/src/amazon.rs index 7ca66798b9..55826f9417 100644 --- a/app/src/main/rust/stores/src/amazon.rs +++ b/app/src/main/rust/stores/src/amazon.rs @@ -547,7 +547,7 @@ pub fn run_download( let fetch_bytes: u64 = plan.items.iter().map(|item| item.reserve).sum(); let per_host_cap = per_host_cap_for(max_workers, plan.hosts.len()); log(&format!( - "engine=rust mode=stream plan={} files skip={} ({} bytes) fetch={} ({} bytes) hosts={} workers={} per_host_cap={} process={} dir={}", + "engine=rust mode=stream plan={} files skip={} ({} bytes) fetch={} ({} bytes) hosts={} workers={} per_host_cap={} process={} dir={} {}", files_total, plan.skipped_files, plan.skipped_bytes, @@ -557,7 +557,8 @@ pub fn run_download( max_workers, per_host_cap, process_workers, - install_dir + install_dir, + crate::priority::log_field() )); progress(plan.skipped_bytes, plan.total_bytes, plan.skipped_files, files_total); if plan.items.is_empty() { diff --git a/app/src/main/rust/stores/src/amazon/jni.rs b/app/src/main/rust/stores/src/amazon/jni.rs index 7ce2155585..26797773b8 100644 --- a/app/src/main/rust/stores/src/amazon/jni.rs +++ b/app/src/main/rust/stores/src/amazon/jni.rs @@ -171,6 +171,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_amazon_AmazonNative_na }); thread::spawn(move || { + crate::priority::background(); let log_listener = listener.clone(); let log = move |line: &str| { with_attached_env(&log_listener, |env, obj| call_log(env, obj, line)); diff --git a/app/src/main/rust/stores/src/epic/assemble.rs b/app/src/main/rust/stores/src/epic/assemble.rs index 93cb8629df..580cb8c241 100644 --- a/app/src/main/rust/stores/src/epic/assemble.rs +++ b/app/src/main/rust/stores/src/epic/assemble.rs @@ -234,9 +234,10 @@ pub fn run_assemble( ..AssembleOutcome::default() }; log(&format!( - "assemble cache_dir={} scratch={} files={files_total} bytes={} chunks_referenced={}", + "assemble cache_dir={} scratch={} {} files={files_total} bytes={} chunks_referenced={}", plan.cache_dir.display(), plan.scratch_cache, + crate::priority::log_field(), plan.bytes_total, plan.refs.len() )); diff --git a/app/src/main/rust/stores/src/epic/driver.rs b/app/src/main/rust/stores/src/epic/driver.rs index 35e1f6a08e..1c39f5ac6e 100644 --- a/app/src/main/rust/stores/src/epic/driver.rs +++ b/app/src/main/rust/stores/src/epic/driver.rs @@ -215,10 +215,11 @@ pub fn run_plan( }; let host_cap = per_host_cap(req.max_workers, plan.hosts.len()); log(&format!( - "plan chunk_dir={} cache_dir={} scratch={} files_pending={} chunks={} bytes={} hosts={} workers={} per_host_cap={host_cap} process_workers={}", + "plan chunk_dir={} cache_dir={} scratch={} {} files_pending={} chunks={} bytes={} hosts={} workers={} per_host_cap={host_cap} process_workers={}", plan.manifest.chunk_dir, plan.cache_dir.display(), plan.scratch_cache, + crate::priority::log_field(), req.pending_file_indices.len(), chunks_total, plan.total_bytes, diff --git a/app/src/main/rust/stores/src/epic/jni.rs b/app/src/main/rust/stores/src/epic/jni.rs index 903a17a97f..937d6e42ae 100644 --- a/app/src/main/rust/stores/src/epic/jni.rs +++ b/app/src/main/rust/stores/src/epic/jni.rs @@ -317,6 +317,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native let handle = Box::new(EpicDownloadHandle { cancel }); thread::spawn(move || { + crate::priority::background(); run_on_thread(vm, listener, plan, req, thread_cancel); }); @@ -427,6 +428,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native let handle = Box::new(EpicDownloadHandle { cancel }); thread::spawn(move || { + crate::priority::background(); let progress = |bytes_done: u64, bytes_total: u64, files_done: u64, files_total: u64| { let Ok(mut env) = vm.attach_current_thread_as_daemon() else { return; diff --git a/app/src/main/rust/stores/src/fetch_core.rs b/app/src/main/rust/stores/src/fetch_core.rs index 4cdf4a7278..039f5de711 100644 --- a/app/src/main/rust/stores/src/fetch_core.rs +++ b/app/src/main/rust/stores/src/fetch_core.rs @@ -253,20 +253,23 @@ mode={}", // Periodic throughput reporter — atomics only, never on the fetch hot path. Its samples are // also the `peak_mbps` source. - let reporter = scope.spawn(move || loop { - let mut waited = 0u64; - while waited < THROUGHPUT_SAMPLE_INTERVAL_MS { + let reporter = scope.spawn(move || { + crate::priority::background(); + loop { + let mut waited = 0u64; + while waited < THROUGHPUT_SAMPLE_INTERVAL_MS { + if reporter_done.load(Ordering::Relaxed) { + return; + } + thread::sleep(Duration::from_millis(100)); + waited += 100; + } if reporter_done.load(Ordering::Relaxed) { return; } - thread::sleep(Duration::from_millis(100)); - waited += 100; + meter.sample(); + log(&meter.summary_line(label)); } - if reporter_done.load(Ordering::Relaxed) { - return; - } - meter.sample(); - log(&meter.summary_line(label)); }); // ── Process pool ── @@ -275,6 +278,7 @@ mode={}", let rx = Arc::clone(&rxs[if stream { worker } else { 0 }]); let fb = fb_tx.clone(); proc_handles.push(scope.spawn(move || { + crate::priority::background(); // Stream mode: (item → attempt, message) whose pieces the sink rejected; the rest // of that attempt's pieces are dropped and its Finish becomes a Retry verdict. let mut poisoned: HashMap = HashMap::new(); @@ -430,8 +434,11 @@ mode={}", // ── Async fetch driver on one current-thread runtime. `txs` are moved in and dropped when // the driver returns, which closes the channels so the pool's `blocking_recv` yields // `None`. ── + // The runtime drives on this (already lowered) thread; `on_thread_start` covers the + // blocking pool it starts for DNS lookups. match tokio::runtime::Builder::new_current_thread() .enable_all() + .on_thread_start(crate::priority::background) .build() { Ok(rt) => { diff --git a/app/src/main/rust/stores/src/gog/engine.rs b/app/src/main/rust/stores/src/gog/engine.rs index 0e70fde17f..42bb42a50a 100644 --- a/app/src/main/rust/stores/src/gog/engine.rs +++ b/app/src/main/rust/stores/src/gog/engine.rs @@ -722,7 +722,7 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go let per_host_cap = per_host_cap_for(max_workers, 1); events.on_log(&format!( - "engine=rust kind=gen2 mode=stream label={} files={} chunks={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} sort_largest_first={} host={}", + "engine=rust kind=gen2 mode=stream label={} files={} chunks={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} sort_largest_first={} host={} {}", req.label, files_total, chunk_count, @@ -732,7 +732,8 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go per_host_cap, process_workers, req.sort_largest_first, - host + host, + crate::priority::log_field() )); let files_done = AtomicU32::new(0); @@ -757,33 +758,36 @@ fn run_gen2(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go let verify_threads = process_workers.min(files.len().max(1)); std::thread::scope(|scope| { for _ in 0..verify_threads { - scope.spawn(|| loop { - if cancel.load(Ordering::Relaxed) { - break; - } - let idx = next.fetch_add(1, Ordering::Relaxed); - if idx >= files.len() { - break; - } - let file = &files[idx]; - if skip.contains(file.relative_path.as_str()) { - continue; - } - let out_path = install_dir.join(&file.relative_path); - if file_verified(&out_path, file.total_size, &file.md5) { - files_verified.fetch_add(1, Ordering::Relaxed); - let done = files_done.fetch_add(1, Ordering::Relaxed) + 1; - events.on_file_done( - &file.relative_path, - file.total_size, - true, - done, - files_total, - bytes_done.load(Ordering::Relaxed), - planned_bytes, - ); - } else { - pending[idx].store(true, Ordering::Relaxed); + scope.spawn(|| { + crate::priority::background(); + loop { + if cancel.load(Ordering::Relaxed) { + break; + } + let idx = next.fetch_add(1, Ordering::Relaxed); + if idx >= files.len() { + break; + } + let file = &files[idx]; + if skip.contains(file.relative_path.as_str()) { + continue; + } + let out_path = install_dir.join(&file.relative_path); + if file_verified(&out_path, file.total_size, &file.md5) { + files_verified.fetch_add(1, Ordering::Relaxed); + let done = files_done.fetch_add(1, Ordering::Relaxed) + 1; + events.on_file_done( + &file.relative_path, + file.total_size, + true, + done, + files_total, + bytes_done.load(Ordering::Relaxed), + planned_bytes, + ); + } else { + pending[idx].store(true, Ordering::Relaxed); + } } }); } @@ -1064,7 +1068,7 @@ fn run_gen1(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go let per_host_cap = per_host_cap_for(max_workers, 1); events.on_log(&format!( - "engine=rust kind=gen1 mode=stream label={} files={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} host={}", + "engine=rust kind=gen1 mode=stream label={} files={} planned_bytes={} skip_paths={} workers={} per_host_cap={} process_workers={} host={} {}", req.label, files_total, planned_bytes, @@ -1072,7 +1076,8 @@ fn run_gen1(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Go max_workers, per_host_cap, process_workers, - host + host, + crate::priority::log_field() )); let files_done = AtomicU32::new(0); diff --git a/app/src/main/rust/stores/src/gog/jni.rs b/app/src/main/rust/stores/src/gog/jni.rs index 86f5ba840c..9d3920d0c1 100644 --- a/app/src/main/rust/stores/src/gog/jni.rs +++ b/app/src/main/rust/stores/src/gog/jni.rs @@ -261,6 +261,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativeSt let spawned = thread::Builder::new() .name("gog-dl".to_string()) .spawn(move || { + crate::priority::background(); let events = JniEvents { vm, listener }; let result = engine::run(&request, &worker.cancel, &events); events.complete(&result); diff --git a/app/src/main/rust/stores/src/lib.rs b/app/src/main/rust/stores/src/lib.rs index 8aeb3a6f42..963826c40e 100644 --- a/app/src/main/rust/stores/src/lib.rs +++ b/app/src/main/rust/stores/src/lib.rs @@ -25,4 +25,5 @@ pub mod fetch_core; pub mod fetch_tuning; pub mod gog; pub mod md5_small; +pub mod priority; pub mod stores_jni; diff --git a/app/src/main/rust/stores/src/priority.rs b/app/src/main/rust/stores/src/priority.rs new file mode 100644 index 0000000000..916008face --- /dev/null +++ b/app/src/main/rust/stores/src/priority.rs @@ -0,0 +1,55 @@ +//! Background priority for every thread the store engines create. +//! +//! A download keeps several threads busy at once (the run's worker, the tokio runtime and its +//! blocking pool for DNS, the inflate/hash/write pool, the throughput reporter, GOG's verify pass, +//! the Epic assembler). At the default nice 0 they compete as equals with the app's UI and input +//! threads, and on the device the menus' animations and controller navigation slowed visibly for +//! as long as a store download ran. At nice +10 the scheduler hands them only what the UI leaves, +//! which for a download bound by network and storage costs next to nothing. +//! +//! Linux applies `setpriority(PRIO_PROCESS, tid, …)` to the one thread `tid`, not the process, and +//! a new thread inherits its creator's nice value; every thread is still lowered explicitly at its +//! start so the guarantee does not depend on who spawned it. Only threads this library creates are +//! touched: the JNI calling thread belongs to the app and keeps its priority. + +/// The nice value store-engine threads run at. +pub const BACKGROUND_NICE: i32 = 10; + +/// Lower the calling thread to [`BACKGROUND_NICE`]. Best effort: a refusal leaves the thread at +/// its current priority and the download runs as before. +pub fn background() { + #[cfg(any(target_os = "android", target_os = "linux"))] + unsafe { + let tid = libc::gettid(); + let _ = libc::setpriority(libc::PRIO_PROCESS, tid as libc::id_t, BACKGROUND_NICE); + } +} + +/// The calling thread's nice value as a log field, e.g. `priority=nice10`. +pub fn log_field() -> String { + #[cfg(any(target_os = "android", target_os = "linux"))] + { + let nice = unsafe { libc::getpriority(libc::PRIO_PROCESS, libc::gettid() as libc::id_t) }; + format!("priority=nice{nice}") + } + #[cfg(not(any(target_os = "android", target_os = "linux")))] + { + "priority=default".to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_lowered_thread_reports_nice10() { + let field = std::thread::spawn(|| { + background(); + log_field() + }) + .join() + .unwrap(); + assert_eq!(field, "priority=nice10"); + } +}