mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 23:36:04 +00:00
Store engines: every thread they create runs at nice +10
On the device the menus' animations and controller navigation slowed for as long as an Epic or GOG download ran: the engine's threads competed with the UI at nice 0. Each thread the library starts now lowers itself first - the run's worker (all three stores), the inflate/hash/write pool, the throughput reporter, GOG's verify pass, the Epic assembler, and through on_thread_start the tokio runtime's blocking pool (DNS). The JNI calling thread is the app's and is left alone. Behaviour is otherwise unchanged; any process-worker count from 1 up was and is accepted. The plan/start line of every run logs the worker's actual nice value (priority=nice10). libc becomes a direct dependency; it was already in the tree through tokio at the pinned version.
This commit is contained in:
1 parent
1a527e8ed1
commit
37b6f336a7
12 files changed
+124
-45
No files matched your search
Generated
+1
@@ -170,6 +170,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"jni",
|
||||
"libc",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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()
|
||||
));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<usize, (u32, String)> = 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) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user