From e00226fd59d5fe2373431dff1f06e588874f30ef Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:04:55 -0800 Subject: [PATCH] Unpack slots: a bounded pool of extractions instead of one global unpack lock (#735) One global unpack lock serialized every direct unpack, live extraction and post-processing unpack. On 6790 (about 1000 groups) a paused item's direct unpack held it while it waited for volumes: a new download's live extraction never started, a weak primary failed over and downloaded its backup whole (XB copy 02/05, X54), and finished jobs sat in PP_QUEUED. - unpackslots: up to UnpackSlots extractions at once (0 = min(4, CPUs/2)). Slots go to an active download first, then a finished job's unpack, then a paused or fleet-held download; oldest first within a class; a waiter moves up one class per 30 s waited. - An extraction holds its slot only while it extracts: direct unpack gives it back while it waits for a volume (RAR session on_wait, log-line waits, live 7z/ZIP sets on their own download's writes). - Direct unpack starts whatever else extracts (no has_active_unpack / PostStrategy check), except while another copy of the release extracts or passed the post gate. Past max(4, 2 x slots) sessions a warning is logged; nothing is stopped. - The post-processing unpack gate asks the pool for room. - A direct unpack waiting for a slot is Running, so the failover keep rule keeps a weak primary whose backup's video is confirmed. - Removes #734's prepost::stop_stalled_direct_unpacks and its yield marks: a waiting direct unpack holds no slot, so a paused download's live extraction is no longer stopped for a finished job's unpack. dupausedunpack now expects no stop (RelB unpacks, RelA keeps waiting). - A direct unpack stop deletes the dead volumes it borrowed only when the download was deleted. A stop for a failure (password, damage, missing volume) or a failover hold leaves them for post-processing, so a download that goes on never fetches a dead volume twice (#734's rule, now for every stop path). - Scenarios dupausedlive and failcont_alt25busy (both fail on main); unit tests for capacity, admission order, aging, classes. Real XB rerun X55 on 6790 (deploy 36fa42c5): SUCCESS/UNPACK, primary kept and continued from its alt, backup DownloadedSizeMB 0, mkv sha256 0fccd3f5... as expected. Working history: origin/backup/unpack-slots-4c648cf5 and origin/backup/unpack-slots-227899ff (reviewed head). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/lib.rs | 1 + rust/src/livefeed.rs | 21 +- rust/src/livewrite.rs | 16 + rust/src/options.rs | 6 +- rust/src/postproc.rs | 214 +++++++++--- rust/src/prepost.rs | 171 ++++------ rust/src/progressive_unpack.rs | 6 + rust/src/queuecoord.rs | 4 + rust/src/unpackslots.rs | 395 +++++++++++++++++++++++ rustyget.conf | 19 ++ site/content/settings-processing.md | 4 +- tests/functional/dupefallback/harness.py | 130 +++++++- webui/config.js | 3 +- webui/locales.source.json | 4 + 14 files changed, 818 insertions(+), 176 deletions(-) create mode 100644 rust/src/unpackslots.rs diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 4bcfe88ac..f043fac62 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -105,6 +105,7 @@ pub mod twin; pub(crate) mod twinfields; pub mod unpack; pub(crate) mod unpacklimits; +pub(crate) mod unpackslots; pub(crate) mod url; pub mod urlcoord; pub mod util; diff --git a/rust/src/livefeed.rs b/rust/src/livefeed.rs index 483871a54..c32da626f 100644 --- a/rust/src/livefeed.rs +++ b/rust/src/livefeed.rs @@ -145,6 +145,8 @@ struct Waiting<'a> { waiting: bool, /// Article writes reported when the extraction last looked (see `crate::livewrite`). writes: u64, + /// The feed's own write count when it last looked (`VolumeFeed::writes`). + own: u64, } impl Waiting<'_> { @@ -153,17 +155,28 @@ impl Waiting<'_> { on_wait, waiting: false, writes: crate::livewrite::write_count(), + own: 0, } } /// Waits for anything new: a volume, or an article written into a volume being read. - fn idle(&mut self) { + /// When something of the feed's own set was written meanwhile (`feed.writes()`), the + /// caller is told it works again before its next step decodes it (a direct unpack takes + /// its unpack slot back then: it decodes only while it holds one). Writes of other + /// downloads wake it to look, but do not take a slot. + fn idle(&mut self, feed: &dyn VolumeFeed) { if !self.waiting { self.waiting = true; + self.own = feed.writes(); (self.on_wait)(true); } crate::livewrite::wait_any(self.writes, IDLE); self.writes = crate::livewrite::write_count(); + let own = feed.writes(); + if own != self.own { + self.own = own; + self.busy(); + } } fn busy(&mut self) { if self.waiting { @@ -911,7 +924,7 @@ pub fn extract( } } } - waiting.idle(); + waiting.idle(&*vols.feed); }; waiting.busy(); vols.expect = lens; @@ -1167,7 +1180,7 @@ fn feed_members( log(1, &why); return fail(&members, &empties, why); } else { - waiting.idle(); + waiting.idle(&*vols.feed); } } remove_temp_dir(&dest); @@ -1377,7 +1390,7 @@ fn join_live( log(1, &why); return fail(why); } else { - waiting.idle(); + waiting.idle(&*vols.feed); } } let size = piece_len.unwrap_or(0) * (n as u64 - 1) + last_len; diff --git a/rust/src/livewrite.rs b/rust/src/livewrite.rs index 2814d06a5..d2514b655 100644 --- a/rust/src/livewrite.rs +++ b/rust/src/livewrite.rs @@ -189,6 +189,20 @@ static VOLUMES: std::sync::LazyLock>>>> = /// Bumped on every reported write, for live extractions that poll (see [`wait_any`]). static WRITES: (Mutex, Condvar) = (Mutex::new(0), Condvar::new()); +/// Writes (and forgets) reported per download, so an extraction can tell whether anything +/// of its own download was written (see [`nzb_write_count`]). +static NZB_WRITES: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + +fn bump_nzb(nzb_id: i32) { + *lock(&NZB_WRITES).entry(nzb_id).or_insert(0) += 1; +} + +/// How many writes (and forgets) download `nzb_id` reported so far. +pub fn nzb_write_count(nzb_id: i32) -> u64 { + lock(&NZB_WRITES).get(&nzb_id).copied().unwrap_or(0) +} + /// Where a live extraction read packed bytes from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ReadKind { @@ -396,6 +410,7 @@ fn report(nzb_id: i32, file_id: i32, path: Option<&Path>, offset: u64, len: u64) if first_head { note_head(nzb_id); } + bump_nzb(nzb_id); let (m, cv) = &WRITES; *lock(m) += 1; cv.notify_all(); @@ -422,6 +437,7 @@ pub fn forget(nzb_id: i32) { w.wake(); } } + bump_nzb(nzb_id); let (m, cv) = &WRITES; *lock(m) += 1; cv.notify_all(); diff --git a/rust/src/options.rs b/rust/src/options.rs index 722a2fec5..e3391bbb6 100644 --- a/rust/src/options.rs +++ b/rust/src/options.rs @@ -1784,7 +1784,7 @@ pub(crate) fn known_enum_names(option: &str) -> Option<&'static [&'static CStr]> /// Emits all default option `(name, value)` pairs for `Options::InitDefaults`. pub fn init_defaults_with(disable_curses: bool, mut set_opt: impl FnMut(&CStr, &CStr)) { let output_mode = if disable_curses { c"color" } else { c"curses" }; - let defaults: [(&CStr, &CStr); 134] = [ + let defaults: [(&CStr, &CStr); 135] = [ (c"MainDir", c"~/downloads"), (c"WebDir", c""), (c"ConfigTemplate", c""), @@ -1897,6 +1897,7 @@ pub fn init_defaults_with(disable_curses: bool, mut set_opt: impl FnMut(&CStr, & (c"Unpack", c"yes"), (c"DirectUnpack", c"yes"), (c"FeedThreads", c"0"), + (c"UnpackSlots", c"0"), (c"UseTempUnpackDir", c"yes"), (c"UnpackCleanupDisk", c"yes"), (c"UnrarCmd", c""), @@ -2180,6 +2181,8 @@ pub struct NzbgetRsParsedOptions { /// Worker threads for a 7z LZMA2 member's independent blocks in live extraction /// (`livefeed::feed_threads`): 0 picks, 1 is none, more is that many (at most 64). pub feed_threads: i32, + /// Extractions that run at once (`unpackslots::capacity_for`): 0 picks, n is n (at most 64). + pub unpack_slots: i32, } impl NzbgetRsParsedOptions { @@ -2708,6 +2711,7 @@ pub fn init_scalar_options_host( .parse_int_value(c"LightConnections", 10) .clamp(0, crate::light_pool::LIGHT_MAX); s.feed_threads = host.parse_int_value(c"FeedThreads", 10).clamp(0, 64); + s.unpack_slots = host.parse_int_value(c"UnpackSlots", 10).clamp(0, 64); s.url_force = i32::from(host.parse_bool_value(c"UrlForce")); s.cert_check = i32::from(host.parse_bool_value(c"CertCheck")); s.reorder_files = i32::from(host.parse_bool_value(c"ReorderFiles")); diff --git a/rust/src/postproc.rs b/rust/src/postproc.rs index 5a4033362..a0c1d8e44 100644 --- a/rust/src/postproc.rs +++ b/rust/src/postproc.rs @@ -32,11 +32,40 @@ pub const PAR_SCAN_EXTENDED: i32 = 1; pub const PAR_SCAN_FULL: i32 = 2; pub const PAR_SCAN_DUPE: i32 = 3; -static UNPACK_MUTEX: Mutex<()> = Mutex::new(()); - -/// An extraction (unrar, 7-Zip, direct unpack) holds the unpack lock right now. +/// An extraction (unrar, 7-Zip, direct unpack) holds an unpack slot right now. pub(crate) fn extraction_running() -> bool { - matches!(UNPACK_MUTEX.try_lock(), Err(std::sync::TryLockError::WouldBlock)) + crate::unpackslots::in_use() > 0 +} + +/// The unpack-slot class of download `n`'s direct unpack (`unpackslots::download_class`): +/// paused when the files other than par2 it still needs are all paused, every download is +/// paused for it, or its fleet holds it. The caller holds the queue lock. +pub(crate) fn direct_unpack_class( + host: &QueueSubsysHost, + opts: &crate::queuesubsys_host::GlobalOptsSnap, + n: NzbRef, +) -> crate::unpackslots::Class { + let ns = host.nzb_snap(n, false); + let (mut data, mut paused) = (0, 0); + for i in 0..host.nzb_file_len(n) { + let f = host.file_snap(host.nzb_file_at(n, i)); + if f.deleted || f.par_file { + continue; + } + data += 1; + paused += usize::from(f.paused); + } + crate::unpackslots::download_class( + data, + paused, + (opts.pause_download || opts.quota_reached) && !ns.force_priority, + crate::fleethold::is_held(host, n), + ) +} + +/// The message logged once when an extraction waits for an unpack slot. +fn slot_wait_message(in_use: usize, cap: usize) -> Vec { + format!("Waiting for an unpack slot ({in_use} of {cap} in use, option UnpackSlots)").into_bytes() } #[inline] @@ -1487,6 +1516,8 @@ pub(crate) fn quick_info_from_status( #[derive(Default)] struct UnpackRunState { + /// "Waiting for an unpack slot" was logged for this job. + slot_wait_told: bool, name: Vec, info_name: Vec, info_name_up: Vec, @@ -2214,7 +2245,21 @@ impl NzbgetRsUnpackController { } q.set_progress_label(b""); - let _unpack_guard = UNPACK_MUTEX.lock().unwrap_or_else(|e| e.into_inner()); + let Some(_unpack_slot) = crate::unpackslots::acquire( + crate::unpackslots::Kind::Post, + &mut || crate::unpackslots::Class::Finished, + &mut || q.is_stopped(), + &mut |in_use, cap| { + if !st.slot_wait_told { + st.slot_wait_told = true; + self.print_message(q, st, MK_INFO, &slot_wait_message(in_use, cap)); + } + }, + ) else { + st.log_prefix = None; + q.set_progress_label(b""); + return; + }; self.exec_thread_key .store(current_thread_key(), Ordering::Release); self.unpacking.store(true, Ordering::Release); @@ -2275,7 +2320,7 @@ impl NzbgetRsUnpackController { self.unpacking.store(false, Ordering::Release); self.exec_thread_key.store(0, Ordering::Release); - drop(_unpack_guard); + drop(_unpack_slot); st.log_prefix = None; q.set_progress_label(b""); @@ -2567,6 +2612,10 @@ struct DirectUnpackFeed { } impl crate::progressive_unpack::VolumeFeed for DirectUnpackFeed { + fn writes(&self) -> u64 { + crate::livewrite::nzb_write_count(self.nzb_id) + } + fn volume(&mut self, path: &std::path::Path) -> crate::progressive_unpack::VolumeView { use crate::progressive_unpack::VolumeView; #[cfg(unix)] @@ -4310,37 +4359,6 @@ fn kept_borrows() -> std::sync::MutexGuard< KEPT_BORROWS.lock().unwrap_or_else(|e| e.into_inner()) } -/// Downloads whose direct unpack was stopped only to free the unpack slot -/// (`prepost::stop_stalled_direct_unpacks`): the download goes on, and post-processing -/// still needs the dead volumes it borrowed, so its stop keeps them. -static YIELDED_DIRECT_UNPACKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -/// Marks download `nzb_id`'s direct unpack as stopped to free the unpack slot: when it -/// ends, its borrowed dead volumes are kept for post-processing. -pub(crate) fn note_direct_unpack_yield(nzb_id: i32) { - let mut y = YIELDED_DIRECT_UNPACKS.lock().unwrap_or_else(|e| e.into_inner()); - if !y.contains(&nzb_id) { - y.push(nzb_id); - } -} - -/// Forgets the yield marks of downloads not in `with_thread` (their direct unpack ended). -pub(crate) fn retain_direct_unpack_yields(with_thread: &[i32]) { - YIELDED_DIRECT_UNPACKS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|id| with_thread.contains(id)); -} - -/// Takes download `nzb_id`'s yield mark: true when its direct unpack was stopped to free -/// the unpack slot. -fn take_direct_unpack_yield(nzb_id: i32) -> bool { - let mut y = YIELDED_DIRECT_UNPACKS.lock().unwrap_or_else(|e| e.into_inner()); - let had = y.contains(&nzb_id); - y.retain(|id| *id != nzb_id); - had -} - /// Forgets download `nzb_id`'s holds and deletes the scratch files of its borrowed dead /// volumes: the download is done with them (it left post-processing, was deleted, or /// direct unpack extracted them). @@ -4532,10 +4550,29 @@ pub struct NzbgetRsDirectUnpack { busy: Mutex, processed: AtomicBool, cancelled: AtomicBool, + /// The download was deleted (`nzb_deleted`): only then does a stop delete the dead + /// volumes it borrowed. Any other stop (a failure, a hold) leaves them for + /// post-processing, so no dead volume is fetched twice. + deleted: AtomicBool, waiting_volume: AtomicBool, unpacking: AtomicBool, terminated: AtomicBool, exec_thread_key: AtomicUsize, + /// The unpack slot this extraction holds while it extracts (`unpackslots`): given back + /// while it waits for a volume, taken again when it goes on. + slot: Mutex>, + /// "Waiting for an unpack slot" was logged for this download. + slot_wait_told: AtomicBool, +} + +/// Gives the direct unpack's slot back when the extraction step that took it ends, however it +/// ends. +struct SlotBack<'a>(&'a NzbgetRsDirectUnpack); + +impl Drop for SlotBack<'_> { + fn drop(&mut self) { + self.0.yield_slot(); + } } impl NzbgetRsDirectUnpack { @@ -4548,13 +4585,81 @@ impl NzbgetRsDirectUnpack { busy: Mutex::new(BusyTime::default()), processed: AtomicBool::new(false), cancelled: AtomicBool::new(false), + deleted: AtomicBool::new(false), waiting_volume: AtomicBool::new(false), unpacking: AtomicBool::new(false), terminated: AtomicBool::new(false), exec_thread_key: AtomicUsize::new(0), + slot: Mutex::new(None), + slot_wait_told: AtomicBool::new(false), } } + /// Takes an unpack slot for this extraction unless it holds one, waiting while none is + /// free for it (see `unpackslots`); false when the download was stopped meanwhile. Called + /// on the extraction's own thread only, never with the queue locked. + fn take_slot(&self, host: &QueueSubsysHost) -> bool { + if self.slot.lock().unwrap_or_else(|e| e.into_inner()).is_some() { + return true; + } + let slot = crate::unpackslots::acquire( + crate::unpackslots::Kind::Direct, + &mut || self.slot_class(host), + &mut || self.is_stopped_or_terminated(host), + &mut |in_use, cap| { + if self.slot_wait_told.swap(true, Ordering::AcqRel) { + return; + } + let msg = cstr::nul_terminated(&slot_wait_message(in_use, cap)); + host.with_locked_queue(|dq_ptr| { + let n = host.queue_find_by_id(dq_ptr, self.nzb_id); + if n.is_some() { + Self::nzb_message(host, n, MK_INFO, &msg); + } + }); + }, + ); + match slot { + Some(slot) => { + *self.slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(slot); + true + } + None => false, + } + } + + /// Gives the unpack slot back (the extraction waits for a volume, or ended). + fn yield_slot(&self) { + let slot = self.slot.lock().unwrap_or_else(|e| e.into_inner()).take(); + drop(slot); + } + + /// The session tells the extraction it waits for a volume (`wait`) or goes on, on the + /// extraction's own thread: waiting, it gives its unpack slot back; going on, it takes one + /// again first (waiting for it while none is free), and only then counts as unpacking. + fn session_wait(&self, host: &QueueSubsysHost, wait: bool) { + if wait { + self.set_waiting(true); + self.yield_slot(); + } else { + // (stopped meanwhile: it goes on without one, and ends at its next look) + let _ = self.take_slot(host); + self.set_waiting(false); + } + } + + /// Where this download's extraction stands in the queue for a slot. + fn slot_class(&self, host: &QueueSubsysHost) -> crate::unpackslots::Class { + let opts = host.opts(); + host.with_locked_queue(|dq_ptr| { + let n = host.queue_find_by_id(dq_ptr, self.nzb_id); + if n.is_none() { + return crate::unpackslots::Class::Paused; + } + direct_unpack_class(host, &opts, n) + }) + } + fn lock_vol(&self) -> std::sync::MutexGuard<'_, DirectUnpackVolumeState> { self.vol.lock().unwrap_or_else(|e| e.into_inner()) } @@ -4935,6 +5040,7 @@ impl NzbgetRsDirectUnpack { &[b"NzbDeleted for ", nzb_name.as_slice()].concat(), ); Self::finish_nzb(host, nzb_ptr, DirectUnpackStatus::Failure); + self.deleted.store(true, Ordering::Release); self.stop_with_nzb(host, nzb_ptr); } @@ -5188,8 +5294,8 @@ impl NzbgetRsDirectUnpack { // asked for by offset while it waits for them (`livefeed::try_map`). crate::liveorder::set_order(self.nzb_id, &set.volumes); - let _unpack_guard = UNPACK_MUTEX.lock().unwrap_or_else(|e| e.into_inner()); - if self.is_stopped(host) { + let _slot_back = SlotBack(self); + if !self.take_slot(host) || self.is_stopped(host) { return; } self.set_waiting(false); @@ -5257,7 +5363,7 @@ impl NzbgetRsDirectUnpack { self.apply_releases(host); self.is_stopped_or_terminated(host) }, - &|waiting| self.set_waiting(waiting), + &|waiting| self.session_wait(host, waiting), ); drop(cell); if let Some(summary) = crate::livewrite::read_summary(reads, crate::livewrite::read_counts()) { @@ -5320,8 +5426,8 @@ impl NzbgetRsDirectUnpack { ) { local.all_ok_received = false; - let _unpack_guard = UNPACK_MUTEX.lock().unwrap_or_else(|e| e.into_inner()); - if self.is_stopped(host) { + let _slot_back = SlotBack(self); + if !self.take_slot(host) || self.is_stopped(host) { return; } self.set_waiting(false); @@ -5384,6 +5490,11 @@ impl NzbgetRsDirectUnpack { self.add_message(host, msg_kind, msg.as_bytes(), local); // A volume wait signalled through a log line holds the extractor here; RAR sets // read by the progressive session wait in the session and never block here. + let log_wait = self.waiting_volume.load(Ordering::Acquire) + && !session_parked.load(Ordering::Acquire); + if log_wait { + self.yield_slot(); + } while self.waiting_volume.load(Ordering::Acquire) && !session_parked.load(Ordering::Acquire) && !self.is_stopped_or_terminated(host) @@ -5391,6 +5502,9 @@ impl NzbgetRsDirectUnpack { std::thread::sleep(Duration::from_millis(20)); self.apply_releases(host); } + if log_wait { + let _ = self.take_slot(host); + } }, &mut || { self.apply_releases(host); @@ -5403,7 +5517,7 @@ impl NzbgetRsDirectUnpack { // are not deferred behind it. on_wait: Some(&|waiting| { session_parked.store(waiting, Ordering::Release); - self.set_waiting(waiting); + self.session_wait(host, waiting); }), guard: Some(&guard), }, @@ -5424,7 +5538,7 @@ impl NzbgetRsDirectUnpack { self.set_unpacking(false); self.exec_thread_key.store(0, Ordering::Release); self.set_waiting(false); - drop(_unpack_guard); + drop(_slot_back); local.unpack_ok = res.is_ok() && local.all_ok_received @@ -5601,14 +5715,10 @@ impl NzbgetRsDirectUnpack { } let mut extracted = false; - let mut yielded = false; let valid_owner = host.with_locked_queue(|dq_ptr| { let Some(nzb) = self.find_nzb(host, dq_ptr).filter(|n| n.owned) else { return false; }; - // (taken under the queue lock, before the thread mark is cleared, so the post - // queue's scan cannot forget it first) - yielded = take_direct_unpack_yield(self.nzb_id); let nzb_ptr = nzb.ptr; let processed = self.processed.load(Ordering::Acquire); @@ -5659,10 +5769,10 @@ impl NzbgetRsDirectUnpack { return; } - if extracted || (cancelled && !yielded) { - // Direct unpack read the borrowed dead volumes, or the download is going away: - // nothing else needs them. (One stopped only to free the unpack slot keeps them: - // its download goes on.) + if extracted || self.deleted.load(Ordering::Acquire) { + // Direct unpack read the borrowed dead volumes, or the download was deleted: + // nothing else needs them. (A stop for a failure or a hold leaves them: the + // download goes on to post-processing, or downloads again when released.) direct_unpack_forget_holds(self.nzb_id); } else { // Post-processing repairs and unpacks the download: its borrowed dead volumes diff --git a/rust/src/prepost.rs b/rust/src/prepost.rs index 4b9826e6e..2f86615bd 100644 --- a/rust/src/prepost.rs +++ b/rust/src/prepost.rs @@ -308,14 +308,6 @@ pub fn can_run_more_jobs( } } -/// Whether a download's remaining files cannot arrive for now: it has files left and every -/// one is paused, or downloads are paused for it (`downloads_paused`: every download paused -/// or the quota reached, and the item not forced). Its direct unpack waiting for a volume -/// is stopped when a finished job waits to unpack (`stop_stalled_direct_unpacks`). -pub fn download_stands_still(remaining_files: usize, paused_files: i32, downloads_paused: bool) -> bool { - downloads_paused || (remaining_files > 0 && remaining_files as i64 == i64::from(paused_files)) -} - /// `PrePostProcessor::PickNextJob` candidate selector. /// Returns the selected index or `-1`. pub fn pick_next_post_job( @@ -1405,77 +1397,6 @@ impl NzbgetRsPrePostProcessor { false } - /// Stops the direct unpack of a download that stands still ([`download_stands_still`]: - /// paused whole, or every download paused) while it waits for a volume, when a finished - /// job waits to unpack. An extraction holds the one unpack slot (`UNPACK_MUTEX`) all - /// through its wait, so the finished job's unpack waited for as long as the pause lasted - /// (6790: a finished job sat in PP_QUEUED for 36 minutes behind a paused download's - /// direct unpack). The stopped one is unpacked after its download instead, as when its - /// direct unpack fails. - fn stop_stalled_direct_unpacks(&self, host: &crate::queuesubsys_host::QueueSubsysHost, dq_ptr: usize) { - static STOPPED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - let opts = host.opts(); - let active = self.active_jobs.lock().unwrap().clone(); - let qlen = host.queue_len(dq_ptr); - let mut waiting_job: Option> = None; - let mut stalled: Vec = Vec::new(); - let mut with_thread: Vec = Vec::new(); - for qi in 0..qlen { - let nzb_ptr = host.queue_at(dq_ptr, qi); - let nzb = host.nzb_snap(nzb_ptr, false); - if nzb.has_unpack_thread { - with_thread.push(nzb.id); - if host.direct_unpack_is_active(nzb_ptr, true) - && !host.direct_unpack_is_active(nzb_ptr, false) - && download_stands_still( - host.nzb_file_len(nzb_ptr), - nzb.paused_file_count, - (opts.pause_download || opts.quota_reached) && !nzb.force_priority, - ) - { - stalled.push(nzb); - } - continue; - } - // (only a job the post queue would start were the slot free: not one paused by - // PausePostProcess, nor one held at its duplicate key's post gate) - if waiting_job.is_none() - && nzb.post_info_ptr.is_some() - && nzb.is_download_completed - && !active.contains(&nzb_ptr) - && (!opts.pause_post_process || nzb.force_priority) - && !(dupe_gate_has(&DUPE_GATE_HELD, nzb.id) - && dupe_post_gate_host(host, dq_ptr, &nzb).0 != GateVerdict::Pass) - { - let ps = host.post_snap(nzb.post_info_ptr); - if ps.need_unpack && !ps.working && ps.stage == PostStage::Queued { - waiting_job = Some(nzb.name.clone()); - } - } - } - let mut stopped = STOPPED.lock().unwrap_or_else(|e| e.into_inner()); - stopped.retain(|id| with_thread.contains(id)); - crate::postproc::retain_direct_unpack_yields(&with_thread); - let Some(waiting) = waiting_job else { - return; - }; - for nzb in stalled { - if stopped.contains(&nzb.id) { - continue; - } - stopped.push(nzb.id); - let mut msg = b"Stopping the direct unpack of ".to_vec(); - msg.extend_from_slice(&nzb.name); - msg.extend_from_slice(b": its download is paused while it waits for a volume, and "); - msg.extend_from_slice(&waiting); - msg.extend_from_slice(b" waits to unpack; it is unpacked after its download instead"); - host.nzb_print_message(nzb.ptr, crate::queuesubsys_host::MK_WARNING, &msg); - // Its download goes on: the dead volumes it borrowed stay for post-processing. - crate::postproc::note_direct_unpack_yield(nzb.id); - host.direct_unpack_stop(dq_ptr, nzb.ptr); - } - } - pub(crate) fn nzb_added( &self, host: &crate::queuesubsys_host::QueueSubsysHost, @@ -1953,6 +1874,61 @@ impl NzbgetRsPrePostProcessor { stages } + /// Whether direct unpack of download `nzb_ptr` may start now: not while another copy of its + /// release (its duplicate key) extracts or went past the post gate (`dupe_post_gate`), so + /// only one copy extracts into the destination. (Under the one global unpack lock a second + /// copy's direct unpack never started while the first one's ran; it reached the post gate + /// instead, and still does.) + /// + /// Direct unpack sessions waiting for volumes hold no slot but keep their decoder state + /// and open volumes; past `unpackslots::session_limit` sessions this is logged (once per + /// limit crossing) but the new one still starts: the download that downloads now goes + /// first, and stopping another session (a cancel) would delete its borrowed volumes. + fn room_for_direct_unpack( + &self, + host: &crate::queuesubsys_host::QueueSubsysHost, + dq_ptr: usize, + nzb_ptr: NzbRef, + ) -> bool { + if dupe_post_gate_host(host, dq_ptr, &host.nzb_snap(nzb_ptr, false)).0 != GateVerdict::Pass { + return false; + } + static OVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let limit = crate::unpackslots::session_limit(); + let sessions = (0..host.queue_len(dq_ptr)) + .filter(|&qi| host.nzb_snap(host.queue_at(dq_ptr, qi), false).has_unpack_thread) + .count(); + let over = sessions >= limit; + if over && !OVER.swap(true, std::sync::atomic::Ordering::AcqRel) { + let mut msg = b"Starting the direct unpack of ".to_vec(); + msg.extend_from_slice(crate::cstr::until_nul(&host.nzb_snap(nzb_ptr, false).name)); + msg.extend_from_slice( + format!( + " although {sessions} direct unpacks exist (UnpackSlots suggests at most {limit}); paused ones waiting for volumes keep their state" + ) + .as_bytes(), + ); + host.nzb_print_message(nzb_ptr, crate::queuesubsys_host::MK_WARNING, &msg); + } else if !over { + OVER.store(false, std::sync::atomic::Ordering::Release); + } + true + } + + /// Whether a finished job's unpack would find no unpack slot now (`unpackslots`): slots + /// held, an active download's extraction waiting for one, and jobs already in their unpack + /// stage leave none. A direct unpack waiting for a volume (a paused download's, say) holds + /// none and keeps no job waiting. + fn unpack_slot_lacking(&self, host: &crate::queuesubsys_host::QueueSubsysHost) -> bool { + let unpacking = self + .active_job_stages(host) + .iter() + .filter(|&&s| s == PostStage::Unpacking) + .count(); + let starting = unpacking.saturating_sub(crate::unpackslots::post_users()); + !crate::unpackslots::room_for_finished(starting) + } + fn can_run_more_jobs(&self, host: &crate::queuesubsys_host::QueueSubsysHost) -> (bool, bool) { let stages = self.active_job_stages(host); let opts = host.opts(); @@ -2014,7 +1990,7 @@ impl NzbgetRsPrePostProcessor { }); } - let has_active_unpack = self.has_active_unpack(host, dq_ptr, true); + let has_active_unpack = self.unpack_slot_lacking(host); let pause_post = host.opts().pause_post_process; let idx = pick_next_post_job(&cands, allow_par, has_active_unpack, pause_post); if idx >= 0 { @@ -2030,7 +2006,6 @@ impl NzbgetRsPrePostProcessor { let count_before = self.active_jobs.lock().unwrap().len(); self.check_request_par(host, dq_ptr); self.cleanup_jobs(host, dq_ptr); - self.stop_stalled_direct_unpacks(host, dq_ptr); let mut changed = self.active_jobs.lock().unwrap().len() != count_before; loop { @@ -2495,7 +2470,7 @@ impl NzbgetRsPrePostProcessor { } if dec.unpack != 0 { - if self.has_active_unpack(host, dq_ptr, true) { + if self.unpack_slot_lacking(host) { host.post_set_int(post_ptr, POST_INT_NEED_UNPACK, 1); return; } @@ -2648,15 +2623,15 @@ impl NzbgetRsPrePostProcessor { nzb.direct_rename_status, nzb.has_unpack_thread, ); - if act != 1 || !self.can_run_more_jobs(host).0 || self.has_active_unpack(host, dq_ptr, true) - { + // (direct unpack waits for an unpack slot itself, see `unpackslots`) + if act != 1 { return; } let want_unpack = host .nzb_get_param(nzb_ptr, b"*Unpack:") .as_ref() .map_or(true, |v| v.eq_ignore_ascii_case(b"yes")); - if want_unpack { + if want_unpack && self.room_for_direct_unpack(host, dq_ptr, nzb_ptr) { host.direct_unpack_start_job(nzb_ptr); } } @@ -2750,16 +2725,18 @@ impl NzbgetRsPrePostProcessor { ); if act == 1 { let file = host.file_snap(file_ptr); - if (crate::filetypes::is_rar_file(&file.filename) - || crate::livefeed::is_live_volume(&file.filename)) - && self.can_run_more_jobs(host).0 - && !self.has_active_unpack(host, dq_ptr, true) + if crate::filetypes::is_rar_file(&file.filename) + || crate::livefeed::is_live_volume(&file.filename) { + // It starts whatever else extracts or post-processes: the extraction waits for + // an unpack slot itself (`unpackslots`), an active download's first. A paused + // download's extraction waiting for a volume holds none, so it never keeps a + // new download from extracting while it downloads. let unpack_param = host.nzb_get_param(nzb_ptr, b"*Unpack:"); let want_unpack = unpack_param .as_ref() .map_or(true, |v| v.eq_ignore_ascii_case(b"yes")); - if want_unpack { + if want_unpack && self.room_for_direct_unpack(host, dq_ptr, nzb_ptr) { host.direct_unpack_start_job(nzb_ptr); } } @@ -2788,20 +2765,6 @@ mod tests { assert_eq!(gate(copy(false, false), &[]), Pass); } - #[test] - fn a_waiting_direct_unpack_holds_unpacks_back_only_while_its_volumes_can_arrive() { - use super::download_stands_still as still; - // paused whole: its volumes cannot arrive - assert!(still(5, 5, false)); - // some files still download (a paused par2 among them is no stop) - assert!(!still(5, 1, false)); - assert!(!still(5, 0, false)); - // every file arrived: nothing left to wait for, it finishes on its own - assert!(!still(0, 0, false)); - // every download paused (or the quota reached) for it - assert!(still(5, 0, true)); - } - #[test] fn par_failure_is_overridden_only_for_borrowed_volume_damage() { use super::damage_is_borrowed_volumes as ok; diff --git a/rust/src/progressive_unpack.rs b/rust/src/progressive_unpack.rs index 176eba476..64cbf5b1d 100644 --- a/rust/src/progressive_unpack.rs +++ b/rust/src/progressive_unpack.rs @@ -63,6 +63,12 @@ pub enum VolumeView { /// The download side of a session: which volumes exist and which bytes in them are lost. pub trait VolumeFeed: Send + 'static { fn volume(&mut self, path: &Path) -> VolumeView; + /// A count that changes when something of this feed's set may have been written (a live + /// extraction waiting for data looks again, and a direct unpack takes its unpack slot back, + /// only then). By default every live write of any download. + fn writes(&self) -> u64 { + crate::livewrite::write_count() + } /// Blocks (polling `is_cancelled`) until every damaged volume this feed handed out has been /// repaired in place. Returns false when the repair was given up or cancelled. fn wait_repaired(&mut self, _is_cancelled: &mut dyn FnMut() -> bool) -> bool { diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index f390a5ef6..29e2277ec 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -465,6 +465,10 @@ pub fn eval_dead_download( /// delete it and download and extract the backup from its first byte. A download whose /// articles are mostly gone (`dead_rate`) still fails over, unless direct unpack of it runs /// (`extracting`): the backup then feeds the rest of that extraction, however much is gone. +/// A direct unpack still waiting for an unpack slot counts as running (its status is Running +/// from its start; see `unpackslots`, where an active download goes first): another download's +/// extraction holding the slots never makes a weak primary fail over and its backup download +/// whole (6790 XB copy 02/05, X54: a paused download's direct unpack held the one unpack lock). /// /// A backup whose kind is not known yet (an alt nested in another container, say: its first /// file is an archive, not the video) lends too once a borrow from it is underway, or while diff --git a/rust/src/unpackslots.rs b/rust/src/unpackslots.rs new file mode 100644 index 000000000..fecf2d19c --- /dev/null +++ b/rust/src/unpackslots.rs @@ -0,0 +1,395 @@ +//! Unpack slots: how many extractions (direct unpack, live extraction, post-processing unpack) +//! run at once, and which goes first. +//! +//! One global unpack lock used to serialize every extraction. On a busy queue (6790: about +//! 1000 groups) a paused or slow download's direct unpack held it while it waited for volumes +//! that would not come, so a new download's live extraction never started, a weak primary +//! could not be kept for its backup (the keep rule needs a running extraction) and finished +//! jobs waited in PP_QUEUED. Now: +//! +//! - up to [`capacity`] extractions run at once (option `UnpackSlots`; 0 picks +//! `min(4, logical CPUs / 2)`, at least one); +//! - an extraction holds its slot only while it extracts: one waiting for a volume gives it +//! back (`yield` in the direct unpack's wait callbacks) and asks again when the volume is +//! there, so a paused download's extraction never keeps a slot from anyone; +//! - a waiter for a slot is admitted in [`Class`] order (an active download first, then a +//! finished job's unpack, then a paused or held download), oldest first within a class. +//! The class is asked again while waiting, so a download resumed meanwhile moves up. + +use std::sync::{Condvar, Mutex, MutexGuard}; +use std::time::Duration; + +/// Who waits for a slot, in the order slots are handed out (a greater class goes first). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Class { + /// A download that is paused (whole, or every download is), or held by its fleet: it may + /// extract what has arrived when no one else wants the slot. + Paused = 0, + /// A finished download's post-processing unpack. + Finished = 1, + /// A download that downloads now (a fleet's primary among them): its live extraction keeps + /// up with the line, and a weak primary is kept for its backup only while it extracts. + Active = 2, +} + +/// What kind of extraction holds or waits for a slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// Direct unpack (a RAR set read while it downloads, or a live 7z/ZIP set). + Direct, + /// Post-processing unpack of a finished download. + Post, +} + +struct Waiter { + ticket: u64, + class: Class, + kind: Kind, +} + +struct Holder { + ticket: u64, + kind: Kind, +} + +struct State { + next_ticket: u64, + holders: Vec, + waiters: Vec, +} + +static STATE: Mutex = Mutex::new(State { + next_ticket: 1, + holders: Vec::new(), + waiters: Vec::new(), +}); +static CHANGED: Condvar = Condvar::new(); + +/// How often a waiter looks at its class and whether it was stopped. +const RECHECK: Duration = Duration::from_millis(250); + +fn lock() -> MutexGuard<'static, State> { + STATE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Slots for option `UnpackSlots` on a computer with `cores` logical CPUs: 0 (the default) +/// picks half the CPUs, at least one and at most four (each extraction may use several +/// threads of its own, see `FeedThreads`); n is n (at most 64). +pub fn capacity_for(option: i32, cores: usize) -> usize { + if option > 0 { + (option as usize).min(64) + } else { + (cores / 2).clamp(1, 4) + } +} + +/// Direct unpack sessions (threads, with their decoder state and open volumes) expected at +/// once for `capacity` slots: twice the slots, at least four. Sessions waiting for volumes +/// hold no slot, so there may be more of them than slots; more than this is logged. +pub fn session_limit_for(capacity: usize) -> usize { + (capacity * 2).max(4) +} + +/// [`session_limit_for`] the slots now. +pub fn session_limit() -> usize { + session_limit_for(capacity()) +} + +/// Slots now, from the active options (read each time, so a reload applies). +pub fn capacity() -> usize { + let option = crate::options::active_options().map_or(0, |o| o.scalars().unpack_slots); + let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); + capacity_for(option, cores) +} + +/// The class of a download's direct unpack: [`Class::Paused`] when the files it still needs +/// cannot arrive for now (`remaining_data` files other than par2 left and every one of them +/// paused, `paused_data`; or `downloads_paused`: every download paused or the quota reached, +/// and it is not forced) or its fleet holds it (`held`), else [`Class::Active`]. Paused extra +/// par2 files left over do not count: such a download has everything to extract. +pub fn download_class(remaining_data: usize, paused_data: usize, downloads_paused: bool, held: bool) -> Class { + let all_paused = remaining_data > 0 && paused_data >= remaining_data; + if downloads_paused || all_paused || held { + Class::Paused + } else { + Class::Active + } +} + +/// Whether the waiter `me` (class, ticket) gets one of `free` slots: fewer than `free` +/// waiters in `waiters` (`me` among them or not) go before it, a greater class first and an +/// older ticket first within a class. +pub fn admitted(free: usize, waiters: &[(Class, u64)], me: (Class, u64)) -> bool { + if free == 0 { + return false; + } + let ahead = waiters + .iter() + .filter(|&&(class, ticket)| { + ticket != me.1 && (class > me.0 || (class == me.0 && ticket < me.1)) + }) + .count(); + ahead < free +} + +/// Whether a finished job's unpack (class [`Class::Finished`]) finds a slot now: slots held, +/// waiters that go before it, and `starting` post jobs already in their unpack stage but not +/// yet holding or waiting for a slot leave one free. +pub fn room_for_finished(starting: usize) -> bool { + room_for_finished_in(capacity(), &lock(), starting) +} + +fn room_for_finished_in(cap: usize, st: &State, starting: usize) -> bool { + let ahead = st + .waiters + .iter() + .filter(|w| w.class >= Class::Finished) + .count(); + st.holders.len() + ahead + starting < cap +} + +/// Number of post jobs holding or waiting for a slot (to tell which jobs in their unpack +/// stage the pool already counts). +pub fn post_users() -> usize { + let st = lock(); + st.holders.iter().filter(|h| h.kind == Kind::Post).count() + + st.waiters.iter().filter(|w| w.kind == Kind::Post).count() +} + +/// Slots held now. +pub fn in_use() -> usize { + lock().holders.len() +} + +/// A held slot; dropping it hands it to the next waiter. +#[must_use] +pub struct Slot { + ticket: u64, +} + +impl Drop for Slot { + fn drop(&mut self) { + let mut st = lock(); + st.holders.retain(|h| h.ticket != self.ticket); + drop(st); + CHANGED.notify_all(); + } +} + +/// How long a waiter waits before it goes up one class: a finished job's unpack (or a paused +/// download's extraction) is not held back for ever by active downloads coming and going. +const AGE_STEP: Duration = Duration::from_secs(30); + +/// `class` raised one step for every [`AGE_STEP`] waited (`waited`), up to [`Class::Active`]. +pub fn aged(class: Class, waited: Duration) -> Class { + let steps = (waited.as_secs() / AGE_STEP.as_secs()) as u8; + match (class as u8).saturating_add(steps) { + 0 => Class::Paused, + 1 => Class::Finished, + _ => Class::Active, + } +} + +/// Removes a waiter from the pool however its wait ends (given up, admitted, or a panic in +/// a callback), so no stale waiter holds others back. +struct WaiterGuard(u64); + +impl Drop for WaiterGuard { + fn drop(&mut self) { + let mut st = lock(); + st.waiters.retain(|w| w.ticket != self.0); + drop(st); + CHANGED.notify_all(); + } +} + +/// Takes a slot for an extraction, waiting while none is free for it. `class` is asked +/// before the first wait and again every quarter second while waiting (it may lock the queue: +/// it is never called with the pool's lock held); a waiter goes up one class for every +/// [`AGE_STEP`] it waited ([`aged`]) in this call (a direct unpack asks again after each +/// volume wait, so its aging starts over; a finished job's unpack asks once). `stopped` is asked as often: true gives up (None). +/// `on_wait(in_use, capacity)` is called once, when the first look found no slot. +pub fn acquire( + kind: Kind, + class: &mut dyn FnMut() -> Class, + stopped: &mut dyn FnMut() -> bool, + on_wait: &mut dyn FnMut(usize, usize), +) -> Option { + // Fast path: a free slot and no one waiting. + let cap = capacity(); + let ticket = { + let mut st = lock(); + let ticket = st.next_ticket; + st.next_ticket += 1; + if st.waiters.is_empty() && st.holders.len() < cap { + st.holders.push(Holder { ticket, kind }); + return Some(Slot { ticket }); + } + ticket + }; + let _guard = WaiterGuard(ticket); + let since = std::time::Instant::now(); + let mut told = false; + loop { + if stopped() { + return None; + } + let my_class = aged(class(), since.elapsed()); + let cap = capacity(); + let mut st = lock(); + match st.waiters.iter_mut().find(|w| w.ticket == ticket) { + Some(w) => w.class = my_class, + None => st.waiters.push(Waiter { ticket, class: my_class, kind }), + } + let free = cap.saturating_sub(st.holders.len()); + let order: Vec<(Class, u64)> = st.waiters.iter().map(|w| (w.class, w.ticket)).collect(); + if admitted(free, &order, (my_class, ticket)) { + st.waiters.retain(|w| w.ticket != ticket); + st.holders.push(Holder { ticket, kind }); + return Some(Slot { ticket }); + } + if !told { + told = true; + let in_use = st.holders.len(); + drop(st); + on_wait(in_use, cap); + continue; + } + let _ = CHANGED + .wait_timeout(st, RECHECK) + .unwrap_or_else(std::sync::PoisonError::into_inner); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn capacity_is_half_the_cpus_between_one_and_four_unless_set() { + assert_eq!(capacity_for(0, 1), 1); + assert_eq!(capacity_for(0, 2), 1); + assert_eq!(capacity_for(0, 6), 3); + assert_eq!(capacity_for(0, 12), 4); + assert_eq!(capacity_for(0, 64), 4); + assert_eq!(capacity_for(-1, 12), 4); + assert_eq!(capacity_for(1, 12), 1); + assert_eq!(capacity_for(8, 2), 8); + assert_eq!(capacity_for(1000, 2), 64); + } + + #[test] + fn sessions_are_bounded_at_twice_the_slots_at_least_four() { + assert_eq!(session_limit_for(1), 4); + assert_eq!(session_limit_for(2), 4); + assert_eq!(session_limit_for(4), 8); + assert_eq!(session_limit_for(64), 128); + } + + #[test] + fn an_active_download_goes_before_a_finished_job_and_both_before_a_paused_one() { + use Class::*; + // one free slot; a paused download asked first, a finished job next, an active + // download last: the active download gets it + let waiters = [(Paused, 1), (Finished, 2), (Active, 3)]; + assert!(admitted(1, &waiters, (Active, 3))); + assert!(!admitted(1, &waiters, (Finished, 2))); + assert!(!admitted(1, &waiters, (Paused, 1))); + // two free: the finished job too, still not the paused one + assert!(admitted(2, &waiters, (Finished, 2))); + assert!(!admitted(2, &waiters, (Paused, 1))); + // a paused download alone takes a free slot (it extracts what has arrived) + assert!(admitted(1, &[(Paused, 1)], (Paused, 1))); + // no free slot: no one + assert!(!admitted(0, &waiters, (Active, 3))); + } + + #[test] + fn within_a_class_the_oldest_waiter_goes_first() { + use Class::*; + let waiters = [(Active, 7), (Active, 4), (Active, 9)]; + assert!(admitted(1, &waiters, (Active, 4))); + assert!(!admitted(1, &waiters, (Active, 7))); + assert!(admitted(2, &waiters, (Active, 7))); + assert!(!admitted(2, &waiters, (Active, 9))); + // a waiter not listed yet counts the listed ones ahead of it + assert!(!admitted(1, &[(Active, 1)], (Active, 2))); + assert!(admitted(1, &[(Paused, 1)], (Active, 2))); + } + + #[test] + fn a_resumed_download_moves_ahead_of_older_finished_jobs() { + use Class::*; + // ticket 1 waited as paused; resumed, it is active and goes first + assert!(!admitted(1, &[(Paused, 1), (Finished, 2)], (Paused, 1))); + assert!(admitted(1, &[(Active, 1), (Finished, 2)], (Active, 1))); + } + + #[test] + fn a_paused_or_held_download_waits_behind_the_others() { + use Class::*; + // paused whole + assert_eq!(download_class(5, 5, false, false), Paused); + // some data files still download + assert_eq!(download_class(5, 1, false, false), Active); + assert_eq!(download_class(5, 0, false, false), Active); + // every data file arrived (paused extra par2 files are not counted): it finishes what + // it has, as an active download + assert_eq!(download_class(0, 0, false, false), Active); + // every download paused (or the quota reached), and it is not forced + assert_eq!(download_class(5, 0, true, false), Paused); + // held by its fleet + assert_eq!(download_class(5, 0, false, true), Paused); + } + + #[test] + fn a_long_wait_raises_a_waiter_one_class_every_half_minute() { + use Class::*; + let s = Duration::from_secs; + assert_eq!(aged(Finished, s(0)), Finished); + assert_eq!(aged(Finished, s(29)), Finished); + assert_eq!(aged(Finished, s(30)), Active); + assert_eq!(aged(Paused, s(30)), Finished); + assert_eq!(aged(Paused, s(60)), Active); + assert_eq!(aged(Active, s(600)), Active); + // a finished job that waited goes before an active download asking now (older ticket) + assert!(admitted(1, &[(aged(Finished, s(31)), 1), (Active, 9)], (Active, 1))); + } + + fn state(holders: usize, waiters: &[Class]) -> State { + State { + next_ticket: 100, + holders: (0..holders) + .map(|i| Holder { + ticket: i as u64, + kind: Kind::Direct, + }) + .collect(), + waiters: waiters + .iter() + .enumerate() + .map(|(i, &class)| Waiter { + ticket: 50 + i as u64, + class, + kind: Kind::Direct, + }) + .collect(), + } + } + + #[test] + fn a_finished_job_starts_unpacking_only_with_a_slot_left_for_it() { + use Class::*; + assert!(room_for_finished_in(2, &state(0, &[]), 0)); + assert!(room_for_finished_in(2, &state(1, &[]), 0)); + assert!(!room_for_finished_in(2, &state(2, &[]), 0)); + // a paused download waiting for a slot holds no finished job back + assert!(room_for_finished_in(2, &state(1, &[Paused, Paused]), 0)); + // an active download waiting goes first + assert!(!room_for_finished_in(2, &state(1, &[Active]), 0)); + // a job already entering its unpack counts + assert!(!room_for_finished_in(2, &state(1, &[]), 1)); + } +} diff --git a/rustyget.conf b/rustyget.conf index 5e51b8041..8c8106b76 100644 --- a/rustyget.conf +++ b/rustyget.conf @@ -1997,6 +1997,25 @@ DirectUnpack=yes # (uncompressed) archives and RAR archives are not affected. FeedThreads=0 +# Extractions that run at once (0-64). +# +# Direct unpack, live extraction and the unpack of finished downloads share +# these slots. An extraction holds a slot only while it extracts: one waiting +# for a volume (a paused or slow download's, say) gives its slot back. A +# download that is downloading goes first, then finished downloads, then +# paused downloads and copies a fleet holds. +# +# 0 - automatic: half the logical CPUs, at least 1 and at most 4. +# The default. +# 1 - one extraction at a time. +# 2 or up - that many at once. +# +# A finished download or a paused one that waited long moves up. Direct +# unpack starts whatever allows post-processing to run; these +# slots bound it instead. Each extraction may use several threads of its own +# (see ). +UnpackSlots=0 + # Use a temporary _unpack directory during unpacking (yes, no). # # Enabled - Files are unpacked to a temporary subdirectory and then moved to the destination. diff --git a/site/content/settings-processing.md b/site/content/settings-processing.md index ab3cd7891..58e34f8c7 100644 --- a/site/content/settings-processing.md +++ b/site/content/settings-processing.md @@ -35,7 +35,7 @@ Key options: [`ParCheck`](options.md#parcheck), [`ParRepair`](options.md#parrepa ## Unpack -Turn `Unpack` on when you want archive extraction. RustyGet extracts RAR, 7-Zip, ZIP, and tar archives itself, so it needs no external tools. `DirectUnpack` extracts RAR archives while articles arrive and pauses at a damaged volume until it's repaired; `UseTempUnpackDir` controls temporary extraction folders. `FeedThreads` sets how many threads decode a 7-Zip LZMA2 archive during live extraction. +Turn `Unpack` on when you want archive extraction. RustyGet extracts RAR, 7-Zip, ZIP, and tar archives itself, so it needs no external tools. `DirectUnpack` extracts RAR archives while articles arrive and pauses at a damaged volume until it's repaired; `UseTempUnpackDir` controls temporary extraction folders. `FeedThreads` sets how many threads decode a 7-Zip LZMA2 archive during live extraction. `UnpackSlots` sets how many extractions run at once (half the CPUs, at most 4, by default); an extraction waiting for a volume gives its slot back, and a downloading download goes before finished, paused or held ones. `UnpackCleanupDisk` removes archive files after successful extraction. Choose it according to what you want the completed folder to retain. `UnpackIgnoreExt` lists nonstandard RAR extensions, such as `.cbr`, that should keep their names during RAR renaming. It also suppresses the failure for finding only nonstandard RAR archives with those extensions. Recognized `.rar` and `.7z` archives still follow normal extraction. `UnpackPassFile` supplies a password-list file when needed. @@ -43,7 +43,7 @@ A category can override the global unpack setting. Nested archives are unpacked Every unpack is checked before each file or folder is created. Unpacked names are made ASCII: accents are dropped, other characters become `_`, and upper and lower case are kept. `../` and absolute paths are refused. Names and paths must fit the file systems of both the unpack folder and the final folder. A download may unpack at most `UnpackMaxFiles` files (default 100), `UnpackMaxFolders` folders (default 10) and `UnpackMaxDepth` levels of folders (default 2; `Release/Sample/sample.mkv` is 2 deep). The volumes of an archive inside an archive are unpacked further and, when `UnpackCleanupDisk` deletes them, do not count; only what comes out does. A download over a limit stops unpacking and fails post-processing, with a message that names the limit and the file. No par repair is tried. Set a limit to 0 to turn it off. -Key options: [`Unpack`](options.md#unpack), [`DirectUnpack`](options.md#directunpack), [`UseTempUnpackDir`](options.md#usetempunpackdir), [`FeedThreads`](options.md#feedthreads), [`UnpackCleanupDisk`](options.md#unpackcleanupdisk), [`UnpackIgnoreExt`](options.md#unpackignoreext), [`UnpackMaxFiles`](options.md#unpackmaxfiles), [`UnpackMaxDepth`](options.md#unpackmaxdepth), [`UnpackMaxFolders`](options.md#unpackmaxfolders). +Key options: [`Unpack`](options.md#unpack), [`DirectUnpack`](options.md#directunpack), [`UseTempUnpackDir`](options.md#usetempunpackdir), [`FeedThreads`](options.md#feedthreads), [`UnpackSlots`](options.md#unpackslots), [`UnpackCleanupDisk`](options.md#unpackcleanupdisk), [`UnpackIgnoreExt`](options.md#unpackignoreext), [`UnpackMaxFiles`](options.md#unpackmaxfiles), [`UnpackMaxDepth`](options.md#unpackmaxdepth), [`UnpackMaxFolders`](options.md#unpackmaxfolders).
Archive extraction and cleanup settings diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index 1ed140c17..e1023467e 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -4312,7 +4312,7 @@ def _log_text(t): def _failcont(daemon, t, name, backup, die, fleet=False, twin_label='DupeCopyKind', need_live=False, - primary='store'): + primary='store', blocker=False): """The ultimate goal (extract while downloading, 2026-11-25): a stored rar set of movie.mkv extracts while it downloads, and the primary dies at ``die`` (a fraction of its data: every article from there on is gone). Its @@ -4362,7 +4362,13 @@ def _failcont(daemon, t, name, backup, die, fleet=False, twin_label='DupeCopyKin With ``fleet`` the two copies are one fleet (a ``dupes:`` key, F16): the backup waits held in the queue, not in history. ``twin_label='DupeKind'`` - labels a twin the way TwinCheck does, with no fleet kind.""" + labels a twin the way TwinCheck does, with no fleet kind. + + With ``blocker`` another download (Blocker, a rar set) starts its direct unpack first + and is paused while its last volume is on the way (``_paused_blocker``), with one unpack + slot (UnpackSlots=1): its waiting extraction must hold no slot, or the primary's direct + unpack never runs and the primary fails over to its backup, downloaded whole (6790 XB + copy 02/05, X54).""" if not generators.HAVE_RAR: return (name, None, 'SKIP: rar not installed') if backup in ('lzma2', 'norestart') and not generators.HAVE_7Z: @@ -4475,6 +4481,9 @@ def _failcont(daemon, t, name, backup, die, fleet=False, twin_label='DupeCopyKin _failcont_before.offsets[vname] = off off += len(data) api = daemon.wait_ready() + blocked = _paused_blocker(daemon, t, api, 'Blocker', 'fcBlk', _blocker_members(t, 'fcBlk')) if blocker else None + if blocker and blocked is not True: + return (name, False, 'the blocker was not set up: %s' % blocked) key = 'dupes:show.failcont.' + tag if fleet else tag + '-key' daemon.append(api, 'Primary', build_multi_nzb(members, password=primary_password), True, key, 100) if backup == 'rar5m3other': @@ -4582,6 +4591,11 @@ def _failcont(daemon, t, name, backup, die, fleet=False, twin_label='DupeCopyKin and du_ok == 1 and used_direct == 1 and a_again == 0 and b_again <= b_again_ok and b_bytes <= b_budget and b_before == 0 and restarts == 0 and (not need_live or as_written > 0)) + if blocker: + # the blocker stayed paused in the queue all through, its direct unpack not stopped + blocker_state = _paused_state(api, 'Blocker') + ok = ok and blocker_state.startswith('paused') and _grep_log(t, 'Stopping the direct unpack of Blocker') == 0 + name = '%s (blocker %s)' % (name, blocker_state) return (name, ok, 'winner=%s primary=%s backup=%s secs=%.1f primary_served=%d/%d B (%d articles, %d again, ' 'par2 %d again) backup_served=%d B of %d (budget %d, %d articles, %d again, par2 %d again) ' @@ -4604,6 +4618,91 @@ def scenario_failcont_twin90(daemon, t): return _failcont(daemon, t, 'failcont_twin90', 'twin', 0.90) +def _blocker_members(t, tag): + """A stored RAR5 set of three volumes of 50 kB articles under ``tag``/Blk.partNN.rar: + every first article arrives (so direct rename has the names), and SCENARIO_DELAY_PROXY + holds back the second article of the last volume (marker ``tag/Blk.part03.rar?2=``).""" + seg = 50_000 + with tempfile.TemporaryDirectory(prefix='blk-') as workdir: + vols = generators.rar5_store_volumes_hp('blocker.bin', _payload(2_500_000, 31337), 1_000_000, None, workdir) + members = [] + for i, data in enumerate(vols): + vname = 'Blk.part%02d.rar' % (i + 1) + rel = '%s/%s' % (tag, vname) + t.write_file(os.path.join('data', rel), data) + members.append((rel, vname, len(data), seg, set())) + return members + + +def _paused_blocker(daemon, t, api, nzb_name, tag, members=None): + """Queues ``nzb_name``, a rar set of three volumes whose last one the news server holds + back (SCENARIO_DELAY_PROXY), waits until its direct unpack starts and pauses it: its + extraction then waits for a volume that does not come. True, or why not.""" + if members is None: + members = [m[:5] for m in _rarrenamer_members(t, tag, ['testfile3'])] + daemon.append(api, nzb_name, build_multi_nzb(members), False, tag + '-key', 100) + deadline = time.time() + 60 + while time.time() < deadline and _grep_log(t, 'Directly unpacking ' + nzb_name) == 0: + time.sleep(0.2) + if _grep_log(t, 'Directly unpacking ' + nzb_name) == 0: + return 'its direct unpack did not start' + g = next((g for g in api.listgroups() if g['NZBName'] == nzb_name), None) + if g is None: + return 'it left the queue before it could be paused' + api.editqueue('GroupPause', 0, '', [g['NZBID']]) + return True + + +def _paused_state(api, nzb_name): + """'paused ' while ``nzb_name`` is in the queue with its files paused (its Status + may read DOWNLOADING while an article it asked for before the pause is on the way), else + its Status or 'gone'.""" + g = next((g for g in api.listgroups() if g['NZBName'] == nzb_name), None) + if g is None: + return 'gone' + paused = g.get('PausedSizeLo', 0) or g.get('PausedSizeHi', 0) + return ('paused ' if paused else '') + g.get('Status', '?') + + +def scenario_failcont_alt25busy(daemon, t): + """failcont_alt25 with one unpack slot and another download's direct unpack waiting for a + volume while it is paused: the primary is kept and continued from its alt, not failed + over with the alt downloaded whole.""" + return _failcont(daemon, t, 'failcont_alt25busy', 'alt', 0.25, blocker=True) + + +def scenario_dupausedlive(daemon, t): + """A paused download's waiting direct unpack keeps no slot from a new download's live + extraction (UnpackSlots=1). RelA's direct unpack starts, then RelA is paused while its + last volume is on the way (the news server holds it back); RelB, added after, extracts + while it downloads: its direct unpack starts and succeeds, and post-processing takes its + files. RelA stays paused in the queue with its direct unpack running (not stopped). + Before, one global unpack lock (and the direct-unpack start check) kept RelB from + extracting until RelA was resumed (6790: a paused item's direct unpack held it).""" + api = daemon.wait_ready() + blocked = _paused_blocker(daemon, t, api, 'RelA', 'dplA') + if blocked is not True: + return ('dupausedlive', False, 'RelA: %s' % blocked) + members_b = _rarrenamer_members(t, 'dplB', ['testfile5']) + daemon.append(api, 'RelB', build_multi_nzb([m[:5] for m in members_b]), False, 'dpl-b', 100) + try: + h = daemon.wait_history(api, 'RelB', timeout=60) + status, unpack = h['Status'], h['UnpackStatus'] + except RuntimeError: + g = next((g for g in api.listgroups() if g['NZBName'] == 'RelB'), {}) + status, unpack = 'still queued: %s' % g.get('Status'), '-' + rel_a = _paused_state(api, 'RelA') + du_b = _grep_log(t, 'Directly unpacking RelB') + du_b_ok = _grep_log(t, 'Direct unpack for RelB successful') + used = _grep_log(t, 'Using directly unpacked files') + stopped_a = _grep_log(t, 'Stopping the direct unpack of RelA') + _grep_log(t, 'Cancelling direct unpack for RelA') + files = _main_basenames(t) + ok = (du_b == 1 and du_b_ok == 1 and used >= 1 and status.startswith('SUCCESS') and unpack == 'SUCCESS' + and 'testfile5.dat' in files and rel_a.startswith('paused') and stopped_a == 0) + return ('dupausedlive', ok, 'relB=%s unpack=%s du_b=%d du_b_ok=%d used_direct=%d relA=%s stopped_a=%d files=%s' % ( + status, unpack, du_b, du_b_ok, used, rel_a, stopped_a, files)) + + def scenario_failcont_alt25(daemon, t): return _failcont(daemon, t, 'failcont_alt25', 'alt', 0.25) @@ -15079,12 +15178,13 @@ def listgroups_secs(): def scenario_dupausedunpack(daemon, t): """A direct unpack waiting for a volume of a download paused whole holds no other job's - unpack back. RelA's direct unpack starts on its first volumes, then RelA is paused while - its last volume is still on the way (the news server holds it); RelB, a whole rar set - added after, needs the unpack slot: RelA's direct unpack is stopped (RelA is unpacked - after its download instead) and RelB goes to history as SUCCESS. Before, RelB sat in - PP_QUEUED for as long as RelA stayed paused (6790: a finished job waited 36 minutes - behind a paused download's direct unpack).""" + unpack back, and is not stopped for it. RelA's direct unpack starts on its first volumes, + then RelA is paused while its last volume is still on the way (the news server holds it); + RelB, a whole rar set added after, unpacks in a free unpack slot (a waiting extraction + holds none) and goes to history as SUCCESS, while RelA's direct unpack keeps waiting: + it is neither stopped nor cancelled, so its live extraction is not thrown away. Before + unpack slots, RelB sat in PP_QUEUED for as long as RelA stayed paused (6790: a finished + job waited 36 minutes behind a paused download's direct unpack).""" api = daemon.wait_ready() members_a = _rarrenamer_members(t, 'dpuA', ['testfile3']) daemon.append(api, 'RelA', build_multi_nzb([m[:5] for m in members_a]), False, 'dpu-a', 100) @@ -15107,9 +15207,10 @@ def scenario_dupausedunpack(daemon, t): g = next((g for g in api.listgroups() if g['NZBName'] == 'RelB'), {}) status, unpack = 'still queued: %s' % g.get('Status'), '-' a_now = next((g['Status'] for g in api.listgroups() if g['NZBName'] == 'RelA'), 'gone') - stopped = _grep_log(t, 'Stopping the direct unpack of RelA') + stopped = _grep_log(t, 'Stopping the direct unpack of RelA') + _grep_log(t, 'Cancelling direct unpack for RelA') files = _main_basenames(t) - ok = started and stopped == 1 and status.startswith('SUCCESS') and unpack == 'SUCCESS' and 'testfile5.dat' in files + ok = (started and stopped == 0 and a_now != 'gone' and status.startswith('SUCCESS') and unpack == 'SUCCESS' and + 'testfile5.dat' in files) return ('dupausedunpack', ok, 'du_started=%s stopped=%d relB=%s unpack=%s relA=%s files=%s' % ( started, stopped, status, unpack, a_now, files)) @@ -15520,6 +15621,8 @@ def scenario_dupausedunpack(daemon, t): 'failcont_norestart': scenario_failcont_norestart, 'failcont_othervideo': scenario_failcont_othervideo, 'failcont_aescontainer': scenario_failcont_aescontainer, + 'failcont_alt25busy': scenario_failcont_alt25busy, + 'dupausedlive': scenario_dupausedlive, 'failcont_twinlabel': scenario_failcont_twinlabel, 'failcont_fleettwin': scenario_failcont_fleettwin, 'failcont_fleetalt': scenario_failcont_fleetalt, @@ -16000,6 +16103,9 @@ def scenario_dupausedunpack(daemon, t): 'failcont_norestart': PROD_OPTIONS + ['DownloadRate=4000'], 'failcont_othervideo': PROD_OPTIONS + ['DownloadRate=4000'], 'failcont_aescontainer': PROD_OPTIONS + ['DownloadRate=4000'], + 'failcont_alt25busy': PROD_OPTIONS + ['DownloadRate=4000', 'UnpackSlots=1', 'ArticleTimeout=1200'], + 'dupausedlive': ['Unpack=yes', 'DirectUnpack=yes', 'ParCheck=auto', 'ParRepair=yes', 'DupeCheck=no', 'KeepHistory=1', + 'ArticleTimeout=1200', 'UnpackSlots=1'], 'failcont_twinlabel': PROD_OPTIONS + ['DownloadRate=4000'], 'failcont_fleettwin': PROD_OPTIONS + ['DownloadRate=4000'], 'failcont_fleetalt': PROD_OPTIONS + ['DownloadRate=4000'], @@ -16066,7 +16172,7 @@ def _promote_fallback(options, mode): FALLBACK_MODE_BOUND = {'livegate', 'streamrestartcredit', 'wholefilerestart', 'wholefilestale'} # scenarios that read nserv's request log (nserv.log) CAPTURE_REQUESTS = {'repost', 'wholefileproofcost', 'dropnzbdir', 'fleetstaysqueued', 'fleetprimaryfirst'} | { - 'failcont_twin25', 'failcont_twin50', 'failcont_twin90', 'failcont_alt25', 'failcont_alt50', 'failcont_altlive', 'failcont_alt90', 'failcont_aes25', 'failcont_aes50', 'failcont_aes90', 'failcont_compressed', 'failcont_othervideo', 'failcont_twinlabel', 'failcont_fleettwin', 'failcont_fleetalt', 'failcont_fleetaes', 'failcont_aestwin', 'failcont_aesalt', 'failcont_rar5m3', 'failcont_rar5m3aes', 'failcont_rar5m3other', 'failcont_lzma2', 'failcont_norestart', 'weakswitchalt', 'weakswitchtwin', 'weakswitchaes', 'weakswitchm3', 'failcont_aescontainer'} + 'failcont_twin25', 'failcont_twin50', 'failcont_twin90', 'failcont_alt25', 'failcont_alt50', 'failcont_altlive', 'failcont_alt90', 'failcont_aes25', 'failcont_aes50', 'failcont_aes90', 'failcont_compressed', 'failcont_othervideo', 'failcont_twinlabel', 'failcont_fleettwin', 'failcont_fleetalt', 'failcont_fleetaes', 'failcont_aestwin', 'failcont_aesalt', 'failcont_rar5m3', 'failcont_rar5m3aes', 'failcont_rar5m3other', 'failcont_lzma2', 'failcont_norestart', 'weakswitchalt', 'weakswitchtwin', 'weakswitchaes', 'weakswitchm3', 'failcont_aescontainer', 'failcont_alt25busy'} # extra nserv arguments per scenario (-w: response latency in ms) SCENARIO_NSERV_ARGS = {'streamtimeoutwrites': ['-w', '800'], 'fleetslowprobe': ['-x', '2000'], 'fleetprobespeed': ['-w', '300'], 'fleetprobebusy': ['-w', '300'], 'fleetprobehealthfail': ['-w', '800'], 'finaldeletemidway': ['-w', '300'], 'finaldeleterestart': ['-w', '300'], 'restartmidway': ['-w', '300'], 'xpacklatency': ['-w', '1000'], 'deadpickprobe': ['-w', '500'], 'deadpickafterreload': ['-w', '500'], 'deadpickpartial': ['-w', '100'], 'deadpickstray': ['-w', '500'], 'forcefailover': ['-w', '500'], 'copybackup': ['-w', '500'], 'copyoffailed': ['-w', '500'], 'deaddownloadstray2': ['-w', '300'], 'deaddownloadrestart': ['-w', '300'], 'deadbackupsonly': ['-w', '500'], 'backuporder': ['-w', '500'], 'deaddownloadlate': ['-w', '300'], 'deadpickservers': ['-w', '200'], @@ -16099,7 +16205,7 @@ def _promote_fallback(options, mode): 'pathtraversalarticle': (b'name=aaaaaaaa.bin', b'name=../../ab.bin'), 'rejectnextserver': (b'=ypart begin=', b'=ypart begxn=')} # scenarios with a DelayingNntpProxy in front of Server1: [(message-id marker, delay in s)] -SCENARIO_DELAY_PROXY = {'fleetbigqueue': [(b'-0-', 600.0)], 'dupausedunpack': [(b'dpuA/testfile3.part03', 200.0)], 'livestraggler': LIVE_STRAGGLERS, 'lightburst': [(b'lbLoad', 0.25)], 'clientthreads': [(b'ctA/', 3.0)], 'xdecomp_slow': [(b'xdzB/', 0.7)], 'damagedfilestate': [(b'?6=500000:', 20.0, True)], 'articledecoyparrestart': [(b'?9=4000000:', 15.0, True), (b'?10=4500000:', 15.0, True)], 'directrenamesubdir': [(b'drA/obf', 0.4)], 'directrenamesubdirjoin': [(b'drA/obf', 0.4)], 'slowprobe': [(b'STAT ', 5.0), (b'spA/', 0.2)], +SCENARIO_DELAY_PROXY = {'fleetbigqueue': [(b'-0-', 600.0)], 'dupausedunpack': [(b'dpuA/testfile3.part03', 200.0)], 'dupausedlive': [(b'dplA/testfile3.part03', 900.0)], 'failcont_alt25busy': [(b'fcBlk/Blk.part03.rar?2=', 900.0)], 'livestraggler': LIVE_STRAGGLERS, 'lightburst': [(b'lbLoad', 0.25)], 'clientthreads': [(b'ctA/', 3.0)], 'xdecomp_slow': [(b'xdzB/', 0.7)], 'damagedfilestate': [(b'?6=500000:', 20.0, True)], 'articledecoyparrestart': [(b'?9=4000000:', 15.0, True), (b'?10=4500000:', 15.0, True)], 'directrenamesubdir': [(b'drA/obf', 0.4)], 'directrenamesubdirjoin': [(b'drA/obf', 0.4)], 'slowprobe': [(b'STAT ', 5.0), (b'spA/', 0.2)], 'directunpackkeep': [(b'rel.part03', 2.0)], 'directunpackkeepnointer': [(b'rel.part03', 2.0)], 'truncatedstate': [(b'tsA/', 0.5)], diff --git a/webui/config.js b/webui/config.js index 3a155e7fc..d735a62ef 100644 --- a/webui/config.js +++ b/webui/config.js @@ -1685,7 +1685,7 @@ var Config = (new function($) ], UNPACK: [ { key: 'unpack', title: 'Unpack', options: ['Unpack', 'DirectUnpack', 'UnpackPassFile', 'UseTempUnpackDir', 'UnpackPauseQueue'], - advanced: ['FeedThreads', 'UnpackMaxFiles', 'UnpackMaxDepth', 'UnpackMaxFolders'] }, + advanced: ['UnpackSlots', 'FeedThreads', 'UnpackMaxFiles', 'UnpackMaxDepth', 'UnpackMaxFolders'] }, { key: 'cleanup', title: 'Cleanup', options: ['UnpackCleanupDisk', 'ExtCleanupDisk', 'UnpackIgnoreExt'] } ], PATHS: [ @@ -3279,6 +3279,7 @@ var Config = (new function($) { option: 'UseTempUnpackDir', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, { option: 'UnpackPauseQueue', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, { option: 'FeedThreads', when: { name: 'DirectUnpack', values: ['yes'] } }, + { option: 'UnpackSlots', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, { option: 'UnpackMaxFiles', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, { option: 'UnpackMaxDepth', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, { option: 'UnpackMaxFolders', when: { name: 'Unpack', values: ['yes'], orCategory: 'Unpack' } }, diff --git a/webui/locales.source.json b/webui/locales.source.json index a8afe7b38..ac83c6192 100644 --- a/webui/locales.source.json +++ b/webui/locales.source.json @@ -4406,6 +4406,10 @@ "message": "Threads that decode a 7z LZMA2 archive during live extraction.\n\n7-Zip writes a large LZMA2 archive in independent blocks; RustyGet decodes\nblocks whose data has arrived on extra threads, ahead of the extraction.\n\n 0 - automatic: 4 threads on computers with 8 or more logical CPUs,\n otherwise a third of them (at least one). The default.\n 1 - decode on the extraction's own thread only.\n 2 or up - that many extra threads.\n\nOne thread decodes about 75-90 MB/s; 4 threads decode several times that,\nbut leave less CPU for downloading, decoding articles and par2. Stored\n(uncompressed) archives and RAR archives are not affected.", "description": "Description for the option FeedThreads" }, + "config_desc_unpackslots": { + "message": "Extractions that run at once (0-64).\n\nDirect unpack, live extraction and the unpack of finished downloads share\nthese slots. An extraction holds a slot only while it extracts: one waiting\nfor a volume (a paused or slow download's, say) gives its slot back. A\ndownload that is downloading goes first, then finished downloads, then\npaused downloads and copies a fleet holds.\n\n 0 - automatic: half the logical CPUs, at least 1 and at most 4.\n The default.\n 1 - one extraction at a time.\n 2 or up - that many at once.\n\nA finished download or a paused one that waited long moves up. Direct\nunpack starts whatever allows post-processing to run; these\nslots bound it instead. Each extraction may use several threads of its own\n(see ).", + "description": "Description for the option UnpackSlots DO NOT translate option names enclosed in angle brackets (e.g., )." + }, "config_desc_usetempunpackdir": { "message": "Use a temporary _unpack directory during unpacking.\n\n Enabled - Files are unpacked to a temporary subdirectory and then moved to the destination.\n This guarantees integrity and preventing partial files in the final location.\n Disabled - Files are unpacked directly into the destination directory.\n This allows for immediate access to files during the unpacking process.", "description": "Description for the option UseTempUnpackDir DO NOT translate configuration option values (Disabled, Enabled) as they are fixed configuration values."