Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Torrents: the window never waits on the torrent engine (#693) (#702)

Ahmed Nefzaoui817a7b4c818d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 892822f3..e8e5f785 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Torrents: the window no longer freezes while torrents run on a busy or slow disk (an antivirus scanning each write, a disk that is full of other work). The window read each torrent's numbers from the torrent engine on every frame, and the engine holds a torrent while it is paused, removed or added until its writes to the disk have ended, seconds on such a disk; the window waited that long ("freeze in mdm_torrent::Torrents::stats"). The numbers are now read beside the window, five times a second and at once after each change, and the list, the progress window's tabs, **Files...** and the right-click menu show the last ones without waiting ([#693](https://github.com/anefzaoui/misterdownloadmanager/issues/693)).
- The window no longer waits for the program that owns the clipboard. A text box's right-click menu (to offer **Paste**) and **Add URL**, **Add batch download**, **Add torrent** and **Download video** (to fill in a copied link) read the clipboard on the window's own thread, so a program that held the clipboard without answering (on Linux, where a read waited up to 4 seconds each time, and while the right-click menu was open at every frame; on Windows, a program that had stopped responding) held up MDM's window too. They now read it beside the window, as the clipboard monitor has since 0.5.1; a link copied just before still fills the box as the window opens (follows [#418](https://github.com/anefzaoui/misterdownloadmanager/issues/418)).
- Linux: freeze and crash reports show MDM's own functions, files and lines again, and the right ones. When MDM's code began a page after the start of the program in memory (as 0.5.0's did), the report read the whole stack at the wrong place: it showed only system libraries (`freeze in libc.so.6+…`), named other functions of MDM once the release's symbols were fetched, and couldn't find an existing issue for the same problem. A `.dmp` from such a report reads right too ([#661](https://github.com/anefzaoui/misterdownloadmanager/issues/661)).
- Windows: a freeze report whose window thread hardly ran and stopped in the C runtime's memory routines (`VCRUNTIME140.dll`, comparing the first bytes of an icon) now says the computer was too busy to run MDM or slow to load it from disk, with the page faults counted meanwhile, instead of a deadlock; those routines never wait ([#663](https://github.com/anefzaoui/misterdownloadmanager/issues/663)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 771bb74e..f1a09a93 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -539,6 +539,10 @@ These ship in a later version, when they're ready.
### Being built
+- 🔄 A freeze of the window while torrents ran on a busy or slow disk: it waited for the torrent
+ engine, which holds a torrent while its writes to the disk end
+ ([#693](https://github.com/anefzaoui/misterdownloadmanager/issues/693)): the torrents' numbers
+ are now read beside the window; fix in review
- 🔄 Sites with bot protection (Cloudflare and similar) refusing MDM: when a site still answers
with a bot check, asking again the way a browser connects
([#668](https://github.com/anefzaoui/misterdownloadmanager/issues/668))
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 99533e76..40df8307 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -1872,7 +1872,8 @@ impl App {
continue;
};
hashes.insert(spec.hash.clone());
- let Ok(st) = t.stats(&spec.hash) else {
+ // As last read: the window's thread never waits on librqbit (#693).
+ let Some(st) = t.seen(&spec.hash) else {
// Out of the session (released when it finished): no check is running.
i.torrent_check = None;
spec.peers = 0;
@@ -6334,7 +6335,7 @@ impl App {
let going = self
.torrent_host
.get()
- .and_then(|t| t.stats(&spec.hash).ok())
+ .and_then(|t| t.seen(&spec.hash))
.is_some_and(|s| {
matches!(
s.phase,
diff --git a/crates/app/src/torrentfiles.rs b/crates/app/src/torrentfiles.rs
index 3e66ebfb..bc1506e4 100644
--- a/crates/app/src/torrentfiles.rs
+++ b/crates/app/src/torrentfiles.rs
@@ -25,10 +25,11 @@ const TABLE_DY: f32 = 36.0 - 273.0;
impl TorrentFiles {
pub fn new(item: &Item, host: &crate::torrents::Host) -> Option<Self> {
let spec = item.torrent.as_ref()?;
+ // As last read: the window's thread never waits on librqbit (#693).
let session = host.get().and_then(|t| {
- let (files, chosen, _) = t.files(&spec.hash)?;
+ let (files, chosen, _) = t.seen_files(&spec.hash)?;
let file_done = t
- .stats(&spec.hash)
+ .seen(&spec.hash)
.map(|stats| stats.file_done)
.unwrap_or_default();
Some((files, chosen, file_done))
diff --git a/crates/app/src/torrents.rs b/crates/app/src/torrents.rs
index 793d2f7e..e4b16f66 100644
--- a/crates/app/src/torrents.rs
+++ b/crates/app/src/torrents.rs
@@ -849,7 +849,7 @@ impl Run {
}
/// Mark its files once librqbit has created them (it leaves Checking) and again once it
- /// finishes, off the window's thread.
+ /// finishes, off the window's thread (reading which files it has waits on librqbit too).
fn mark_when(&self, t: &Arc<Torrents>, phase: Phase) {
use std::sync::atomic::Ordering;
// Paused: perhaps never started, its files not created yet.
@@ -861,11 +861,12 @@ impl Run {
if self.marked.fetch_max(step, Ordering::SeqCst) >= step {
return;
}
- let Some((files, _, _)) = t.files(&self.hash) else {
- return;
- };
- let folder = self.folder.clone();
- self.rt.spawn_blocking(move || mark_files(&folder, &files));
+ let (t, hash, folder) = (t.clone(), self.hash.clone(), self.folder.clone());
+ self.rt.spawn_blocking(move || {
+ if let Some((files, _, _)) = t.files(&hash) {
+ mark_files(&folder, &files);
+ }
+ });
}
fn session(&self) -> Option<Arc<Torrents>> {
@@ -875,6 +876,8 @@ impl Run {
}
}
+ /// What the list shows. On the window's thread: the session's numbers as last read
+ /// (`Torrents::seen`), never waiting on librqbit (#693).
pub fn snapshot(&self) -> Snapshot {
let mut s = Snapshot {
state: State::Probing,
@@ -894,7 +897,7 @@ impl Run {
};
if *self.stopped.lock().unwrap() {
s.state = State::Cancelled;
- if let Some(st) = self.session().and_then(|t| t.stats(&self.hash).ok()) {
+ if let Some(st) = self.session().and_then(|t| t.seen(&self.hash)) {
s.downloaded = st.done;
s.size = Some(st.total);
}
@@ -914,7 +917,7 @@ impl Run {
}
RunState::Ready(t) => t.clone(),
};
- let Ok(st) = t.stats(&self.hash) else {
+ let Some(st) = t.seen(&self.hash) else {
let (done, size) = *self.last.lock().unwrap();
if size.is_some_and(|total| total > 0 && done >= total) {
s.state = State::Done;
@@ -965,8 +968,8 @@ impl Run {
pub fn cancel(&self) {
*self.stopped.lock().unwrap() = true;
if let Some(t) = self.session() {
- if t.stats(&self.hash)
- .is_ok_and(|s| s.phase == Phase::Finished)
+ if t.seen(&self.hash)
+ .is_some_and(|s| s.phase == Phase::Finished)
{
self.remove_in_background(&t);
} else {
@@ -1012,7 +1015,7 @@ impl Run {
/// downloads share with torrents); None until it is in the session.
pub fn fetched(&self) -> Option<u64> {
let t = self.session()?;
- t.stats(&self.hash).ok().map(|s| s.fetched)
+ t.seen(&self.hash).map(|s| s.fetched)
}
pub fn details(&self) -> Details {
@@ -1030,11 +1033,13 @@ impl Run {
}
/// What the progress window's torrent tabs show for `hash`, from the session: a `Run`'s
-/// torrent, or a finished one still shared without a `Run` (None: not in the session).
+/// torrent, or a finished one still shared without a `Run` (None: not in the session). As last
+/// read: the window's thread never waits on librqbit (#693).
pub fn details_of(t: &Torrents, hash: &str) -> Option<Details> {
- let stats = t.stats(hash).ok()?;
+ let stats = t.seen(hash)?;
let done = stats.file_done.clone();
- let (entries, chosen, piece_length) = t.files(hash).unwrap_or_default();
+ let (entries, chosen, piece_length) = t.seen_files(hash).unwrap_or_default();
+ let swarm = t.seen_swarm(hash);
Some(Details {
files: entries
.into_iter()
@@ -1046,9 +1051,9 @@ pub fn details_of(t: &Torrents, hash: &str) -> Option<Details> {
})
.collect(),
piece_length,
- peers: t.peers(hash),
- trackers: t.trackers(hash),
- pieces: t.pieces(hash),
+ peers: swarm.peers,
+ trackers: swarm.trackers,
+ pieces: swarm.pieces,
stats: Some(stats),
})
}
diff --git a/crates/torrent/src/lib.rs b/crates/torrent/src/lib.rs
index e42e6d6d..ff289585 100644
--- a/crates/torrent/src/lib.rs
+++ b/crates/torrent/src/lib.rs
@@ -25,6 +25,7 @@ use librqbit::{
pub mod blocklist;
mod names;
pub mod trackers;
+mod watch;
pub use names::UnsafeName;
#[derive(Debug, thiserror::Error)]
@@ -316,6 +317,16 @@ pub struct Peer {
pub kind: Option<String>,
}
+/// A torrent's peers, trackers and pieces (the progress window's tabs), as last read
+/// ([`Torrents::seen_swarm`]).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Swarm {
+ pub peers: Vec<Peer>,
+ pub trackers: Vec<String>,
+ /// Which pieces are there (empty while it isn't checked yet).
+ pub pieces: Vec<bool>,
+}
+
/// How the session runs (#40: each of these is the person's to choose, Torrent settings).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
@@ -460,12 +471,20 @@ pub struct Torrents {
session_dir: PathBuf,
/// Each checking torrent's bytes checked and when they last moved: librqbit leaves a check
/// it was asked to pause in Initializing, its count frozen, which isn't checking any more.
- checks: std::sync::Mutex<std::collections::HashMap<String, (u64, std::time::Instant)>>,
+ /// Shared with the thread that reads every torrent (`watch`).
+ checks: Arc<Checks>,
+ /// Every torrent as last read, on a thread of its own (#693): what the window's thread
+ /// asks ([`Torrents::seen`] and the rest that never wait).
+ watch: watch::Watch,
/// Torrents waiting for their check to end before they pause ([`Torrents::pause`]); a Start
/// meanwhile takes the pause back ([`Torrents::resume`]).
pause_after_check: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
}
+pub(crate) type Handle = Arc<librqbit::ManagedTorrent>;
+
+type Checks = std::sync::Mutex<std::collections::HashMap<String, (u64, std::time::Instant)>>;
+
/// A paused torrent whose checked bytes haven't moved for this long has stopped checking.
const CHECK_HALTED_AFTER: Duration = Duration::from_secs(5);
@@ -670,13 +689,23 @@ impl Torrents {
let _ = std::fs::write(cfg.state_dir.join(PORT_FILE), addr.port().to_string());
}
let api = Api::new(session.clone(), None);
+ let checks: Arc<Checks> = Default::default();
+ // The first reading here, so the torrents restored are known from the start.
+ let first = read_all(&session, &api, &checks, &HashSet::new());
+ let watch = {
+ let (session, api, checks) = (session.clone(), api.clone(), checks.clone());
+ watch::Watch::start(first, watch::EVERY, move |wanted| {
+ read_all(&session, &api, &checks, wanted)
+ })
+ };
Ok(Torrents {
session,
api,
proxied,
adding: tokio::sync::Mutex::new(()),
session_dir: cfg.state_dir.join("session"),
- checks: Default::default(),
+ checks,
+ watch,
pause_after_check: Default::default(),
})
}
@@ -797,6 +826,7 @@ impl Torrents {
"the session answered with another torrent ({got}) for {wanted}"
)));
}
+ self.refresh(&got);
Ok(got)
}
@@ -805,104 +835,93 @@ impl Torrents {
id(hash).is_ok_and(|i| self.session.get(i).is_some())
}
+ /// Its numbers now, from librqbit: this waits while the torrent's state is held (a pause
+ /// waits for the writes under way, #693), so never on the window's thread, which takes
+ /// [`Self::seen`].
pub fn stats(&self, hash: &str) -> Result<Stats, TorrentError> {
let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
- let s = h.stats();
- let live = s.live.as_ref();
- let mib = |m: f64| m * 1024.0 * 1024.0;
- let phase = match s.state {
- // Paused while checking: librqbit stopped the check (it stays Initializing).
- TorrentStatsState::Initializing { paused } => {
- if paused && self.check_halted(hash, s.progress_bytes) {
- Phase::Paused
- } else {
- Phase::Checking
- }
- }
- TorrentStatsState::Paused => Phase::Paused,
- TorrentStatsState::Error => Phase::Error,
- TorrentStatsState::Live if s.finished => Phase::Finished,
- TorrentStatsState::Live => Phase::Downloading,
- };
- if !matches!(s.state, TorrentStatsState::Initializing { .. }) {
- self.checks.lock().unwrap().remove(hash);
- }
- Ok(Stats {
- phase,
- checked: (phase == Phase::Checking).then_some(s.progress_bytes),
- done: s.progress_bytes,
- total: s.total_bytes,
- uploaded: s.uploaded_bytes,
- fetched: live.map_or(0, |l| l.snapshot.fetched_bytes),
- down_speed: live.map_or(0.0, |l| mib(l.download_speed.mbps)),
- up_speed: live.map_or(0.0, |l| mib(l.upload_speed.mbps)),
- file_done: s.file_progress.clone(),
- peers_live: live.map_or(0, |l| l.snapshot.peer_stats.live as usize),
- peers_seen: live.map_or(0, |l| l.snapshot.peer_stats.seen as usize),
- error: s.error.clone(),
- })
+ Ok(stats_of(&h, hash, &self.checks))
+ }
+
+ /// Read it again now, after a change made here: what the window takes ([`Self::seen`])
+ /// says so at once, not at the next reading. Waits as [`Self::stats`] does.
+ fn refresh(&self, hash: &str) {
+ let seen = id(hash)
+ .ok()
+ .and_then(|i| self.session.get(i))
+ .map(|h| read_one(&h, hash, &self.checks));
+ self.watch.put(hash, seen);
+ }
+
+ /// Its numbers as last read (None: not in the session). They are read every 200 ms on a
+ /// thread of their own, and at once after each change made here (#693). Never waits on
+ /// librqbit: the window's thread asks this.
+ pub fn seen(&self, hash: &str) -> Option<Stats> {
+ self.watch.get(hash).map(|s| s.stats.clone())
+ }
+
+ /// Its files (as in `Meta::files`), which are chosen (None: all), and the piece size, as
+ /// last read. Never waits, as [`Self::seen`].
+ pub fn seen_files(&self, hash: &str) -> Option<(Vec<FileEntry>, Option<Vec<usize>>, u32)> {
+ let seen = self.watch.get(hash)?;
+ let (files, piece) = files_of(seen.handle.as_ref()?)?;
+ Some((files, seen.chosen.clone(), piece))
+ }
+
+ /// Its peers, trackers and pieces as last read; asking keeps them read for 2 s more (the
+ /// first time, they come with the next reading: empty until then). Never waits, as
+ /// [`Self::seen`].
+ pub fn seen_swarm(&self, hash: &str) -> Swarm {
+ self.watch.want(hash);
+ self.watch
+ .get(hash)
+ .and_then(|s| s.swarm.clone())
+ .unwrap_or_default()
+ }
+
+ /// Its librqbit handle as last read: for what doesn't wait on its state (its limits, its
+ /// piece order, its metadata). librqbit's own list waits while an add opens the files.
+ fn handle(&self, hash: &str) -> Option<Handle> {
+ self.watch.get(hash)?.handle.clone()
}
/// The peers it is talking to.
pub fn peers(&self, hash: &str) -> Vec<Peer> {
- let Ok(i) = id(hash) else { return Vec::new() };
- let Ok(snap) = self.api.api_peer_stats(i, Default::default()) else {
- return Vec::new();
- };
- let mut out: Vec<Peer> = snap
- .peers
- .into_iter()
- .map(|(addr, p)| Peer {
- addr,
- client: p.client_name,
- fetched: p.counters.fetched_bytes,
- uploaded: p.counters.uploaded_bytes,
- kind: p.conn_kind.map(|k| format!("{k:?}").to_lowercase()),
- })
- .collect();
- out.sort_by(|a, b| b.fetched.cmp(&a.fetched).then(a.addr.cmp(&b.addr)));
- out
+ match id(hash) {
+ Ok(i) => peers_of(&self.api, i),
+ Err(_) => Vec::new(),
+ }
}
/// Its files (as in `Meta::files`), which are chosen (None: all), and the piece size.
pub fn files(&self, hash: &str) -> Option<(Vec<FileEntry>, Option<Vec<usize>>, u32)> {
let h = self.session.get(id(hash).ok()?)?;
- let (files, piece) = h
- .with_metadata(|m| {
- let files = m
- .info
- .iter_file_details()
- .map(|f| FileEntry {
- path: f.filename.to_pathbuf(),
- size: f.len,
- padding: f.attrs().padding,
- })
- .collect::<Vec<_>>();
- (files, m.info.lengths().default_piece_length())
- })
- .ok()?;
+ let (files, piece) = files_of(&h)?;
Some((files, h.only_files(), piece))
}
pub fn trackers(&self, hash: &str) -> Vec<String> {
- let Some(h) = id(hash).ok().and_then(|i| self.session.get(i)) else {
- return Vec::new();
- };
- let mut t: Vec<String> = h.shared().trackers.iter().map(|u| u.to_string()).collect();
- t.sort();
- t
+ match id(hash).ok().and_then(|i| self.session.get(i)) {
+ Some(h) => trackers_of(&h),
+ None => Vec::new(),
+ }
}
/// Which pieces are there (empty while it isn't checked yet).
pub fn pieces(&self, hash: &str) -> Vec<bool> {
- let Ok(i) = id(hash) else { return Vec::new() };
- match self.api.api_dump_haves(i) {
- Ok((bits, len)) => bits.iter().by_vals().take(len as usize).collect(),
+ match id(hash) {
+ Ok(i) => pieces_of(&self.api, i),
Err(_) => Vec::new(),
}
}
pub async fn pause(&self, hash: &str) -> Result<(), TorrentError> {
+ let res = self.pause_now(hash).await;
+ self.refresh(hash);
+ res
+ }
+
+ async fn pause_now(&self, hash: &str) -> Result<(), TorrentError> {
let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
match h.stats().state {
TorrentStatsState::Paused => Ok(()),
@@ -928,22 +947,16 @@ impl Torrents {
}
}
- /// Whether a paused torrent's check has stopped: its bytes checked haven't moved for
- /// [`CHECK_HALTED_AFTER`].
- fn check_halted(&self, hash: &str, checked: u64) -> bool {
- let now = std::time::Instant::now();
- let mut checks = self.checks.lock().unwrap();
- let seen = checks.entry(hash.to_owned()).or_insert((checked, now));
- if seen.0 != checked {
- *seen = (checked, now);
- }
- now.duration_since(seen.1) >= CHECK_HALTED_AFTER
- }
-
/// Start it again. One still checking its files (added paused, or restored at start) is
/// waited for: it is Paused only once checked, and unpausing it before did nothing, so it
/// stayed paused (seen on Linux, where the check took longer than the call).
pub async fn resume(&self, hash: &str) -> Result<(), TorrentError> {
+ let res = self.resume_now(hash).await;
+ self.refresh(hash);
+ res
+ }
+
+ async fn resume_now(&self, hash: &str) -> Result<(), TorrentError> {
let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
// A pause waiting for the check to end is taken back: the last click wins.
self.pause_after_check.lock().unwrap().remove(hash);
@@ -951,7 +964,7 @@ impl Torrents {
// A check librqbit stopped (paused while checking) never ends by itself: starting the
// torrent starts the check again. One still checking is waited for, as above.
let halted = matches!(st.state, TorrentStatsState::Initializing { paused: true })
- && self.check_halted(hash, st.progress_bytes);
+ && check_halted(&self.checks, hash, st.progress_bytes);
if matches!(st.state, TorrentStatsState::Initializing { .. }) && !halted {
h.wait_until_initialized().await.map_err(engine)?;
}
@@ -961,16 +974,15 @@ impl Torrents {
self.session.unpause(&h).await.map_err(engine)
}
- /// The order its pieces are downloaded in (#39).
+ /// The order its pieces are downloaded in (#39). Never waits, as [`Self::seen`].
pub fn order(&self, hash: &str) -> Option<PieceOrder> {
- let h = self.session.get(id(hash).ok()?)?;
- Some(h.piece_order())
+ Some(self.handle(hash)?.piece_order())
}
/// Change the order its pieces are downloaded in, running or not: the next piece each peer
- /// is asked for follows it (#39).
+ /// is asked for follows it (#39). Never waits, as [`Self::seen`].
pub fn set_order(&self, hash: &str, order: PieceOrder) -> Result<(), TorrentError> {
- let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
+ let h = self.handle(hash).ok_or(TorrentError::Unknown)?;
h.set_piece_order(order);
Ok(())
}
@@ -978,10 +990,13 @@ impl Torrents {
/// Change which files are downloaded.
pub async fn choose(&self, hash: &str, files: &HashSet<usize>) -> Result<(), TorrentError> {
let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
- self.session
+ let res = self
+ .session
.update_only_files(&h, files)
.await
- .map_err(engine)
+ .map_err(engine);
+ self.refresh(hash);
+ res
}
/// Take it out of the session and add it again from `torrent` (its .torrent, perhaps with
@@ -995,6 +1010,17 @@ impl Torrents {
hash: &str,
torrent: &[u8],
recheck: bool,
+ ) -> Result<(), TorrentError> {
+ let res = self.readd_now(hash, torrent, recheck).await;
+ self.refresh(hash);
+ res
+ }
+
+ async fn readd_now(
+ &self,
+ hash: &str,
+ torrent: &[u8],
+ recheck: bool,
) -> Result<(), TorrentError> {
check_bytes(torrent)?;
let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
@@ -1049,16 +1075,23 @@ impl Torrents {
if !matches!(h.stats().state, TorrentStatsState::Live) {
return Ok(());
}
- self.session.pause(&h).await.map_err(engine)?;
- self.session.unpause(&h).await.map_err(engine)
+ let res = match self.session.pause(&h).await {
+ Ok(()) => self.session.unpause(&h).await,
+ Err(e) => Err(e),
+ };
+ self.refresh(hash);
+ res.map_err(engine)
}
/// Take it out of the session; the files stay unless `delete_files`.
pub async fn remove(&self, hash: &str, delete_files: bool) -> Result<(), TorrentError> {
- self.session
+ let res = self
+ .session
.delete(id(hash)?, delete_files)
.await
- .map_err(engine)
+ .map_err(engine);
+ self.refresh(hash);
+ res
}
/// Every torrent the session holds (to forget ones the app no longer lists).
@@ -1100,13 +1133,14 @@ impl Torrents {
/// One torrent's own limits, bytes/s (None: unlimited), on top of the session's. They apply
/// at once, running or paused, and last while the session runs (librqbit doesn't save them).
+ /// Never waits, as [`Self::seen`].
pub fn set_torrent_limits(
&self,
hash: &str,
down: Option<u64>,
up: Option<u64>,
) -> Result<(), TorrentError> {
- let h = self.session.get(id(hash)?).ok_or(TorrentError::Unknown)?;
+ let h = self.handle(hash).ok_or(TorrentError::Unknown)?;
let want = librqbit::limits::LimitsConfig {
download_bps: rate(down),
upload_bps: rate(up),
@@ -1119,9 +1153,9 @@ impl Torrents {
Ok(())
}
- /// One torrent's own limits (down, up), as `set_torrent_limits` stored them.
+ /// One torrent's own limits (down, up), as `set_torrent_limits` stored them. Never waits.
pub fn torrent_limits(&self, hash: &str) -> Option<(Option<u64>, Option<u64>)> {
- let h = self.session.get(id(hash).ok()?)?;
+ let h = self.handle(hash)?;
let c = h.ratelimits();
let get = |v: Option<NonZeroU32>| v.map(|b| u64::from(b.get()));
Some((get(c.download_bps), get(c.upload_bps)))
@@ -1133,10 +1167,150 @@ impl Torrents {
}
pub async fn stop(&self) {
+ self.watch.close();
self.session.stop().await;
}
}
+/// Whether a paused torrent's check has stopped: its bytes checked haven't moved for
+/// [`CHECK_HALTED_AFTER`].
+fn check_halted(checks: &Checks, hash: &str, checked: u64) -> bool {
+ let now = std::time::Instant::now();
+ let mut checks = checks.lock().unwrap();
+ let seen = checks.entry(hash.to_owned()).or_insert((checked, now));
+ if seen.0 != checked {
+ *seen = (checked, now);
+ }
+ now.duration_since(seen.1) >= CHECK_HALTED_AFTER
+}
+
+/// A torrent's numbers now: waits while librqbit holds its state (#693).
+fn stats_of(h: &librqbit::ManagedTorrent, hash: &str, checks: &Checks) -> Stats {
+ let s = h.stats();
+ let live = s.live.as_ref();
+ let mib = |m: f64| m * 1024.0 * 1024.0;
+ let phase = match s.state {
+ // Paused while checking: librqbit stopped the check (it stays Initializing).
+ TorrentStatsState::Initializing { paused } => {
+ if paused && check_halted(checks, hash, s.progress_bytes) {
+ Phase::Paused
+ } else {
+ Phase::Checking
+ }
+ }
+ TorrentStatsState::Paused => Phase::Paused,
+ TorrentStatsState::Error => Phase::Error,
+ TorrentStatsState::Live if s.finished => Phase::Finished,
+ TorrentStatsState::Live => Phase::Downloading,
+ };
+ if !matches!(s.state, TorrentStatsState::Initializing { .. }) {
+ checks.lock().unwrap().remove(hash);
+ }
+ Stats {
+ phase,
+ checked: (phase == Phase::Checking).then_some(s.progress_bytes),
+ done: s.progress_bytes,
+ total: s.total_bytes,
+ uploaded: s.uploaded_bytes,
+ fetched: live.map_or(0, |l| l.snapshot.fetched_bytes),
+ down_speed: live.map_or(0.0, |l| mib(l.download_speed.mbps)),
+ up_speed: live.map_or(0.0, |l| mib(l.upload_speed.mbps)),
+ file_done: s.file_progress.clone(),
+ peers_live: live.map_or(0, |l| l.snapshot.peer_stats.live as usize),
+ peers_seen: live.map_or(0, |l| l.snapshot.peer_stats.seen as usize),
+ error: s.error.clone(),
+ }
+}
+
+/// A torrent's files and piece size, from its metadata (which doesn't wait on its state).
+fn files_of(h: &librqbit::ManagedTorrent) -> Option<(Vec<FileEntry>, u32)> {
+ h.with_metadata(|m| {
+ let files = m
+ .info
+ .iter_file_details()
+ .map(|f| FileEntry {
+ path: f.filename.to_pathbuf(),
+ size: f.len,
+ padding: f.attrs().padding,
+ })
+ .collect::<Vec<_>>();
+ (files, m.info.lengths().default_piece_length())
+ })
+ .ok()
+}
+
+fn trackers_of(h: &librqbit::ManagedTorrent) -> Vec<String> {
+ let mut t: Vec<String> = h.shared().trackers.iter().map(|u| u.to_string()).collect();
+ t.sort();
+ t
+}
+
+fn peers_of(api: &Api, i: TorrentIdOrHash) -> Vec<Peer> {
+ let Ok(snap) = api.api_peer_stats(i, Default::default()) else {
+ return Vec::new();
+ };
+ let mut out: Vec<Peer> = snap
+ .peers
+ .into_iter()
+ .map(|(addr, p)| Peer {
+ addr,
+ client: p.client_name,
+ fetched: p.counters.fetched_bytes,
+ uploaded: p.counters.uploaded_bytes,
+ kind: p.conn_kind.map(|k| format!("{k:?}").to_lowercase()),
+ })
+ .collect();
+ out.sort_by(|a, b| b.fetched.cmp(&a.fetched).then(a.addr.cmp(&b.addr)));
+ out
+}
+
+fn pieces_of(api: &Api, i: TorrentIdOrHash) -> Vec<bool> {
+ match api.api_dump_haves(i) {
+ Ok((bits, len)) => bits.iter().by_vals().take(len as usize).collect(),
+ Err(_) => Vec::new(),
+ }
+}
+
+/// One torrent read now, for the window's [`Torrents::seen`] (its details only when wanted, by
+/// [`read_all`]). Waits as [`stats_of`] does.
+fn read_one(h: &Handle, hash: &str, checks: &Checks) -> watch::Seen {
+ watch::Seen {
+ stats: stats_of(h, hash, checks),
+ chosen: h.only_files(),
+ handle: Some(h.clone()),
+ swarm: None,
+ }
+}
+
+/// Every torrent of the session read now, by info hash; with its peers, trackers and pieces
+/// when `wanted`. On the watch's thread (and once as the session starts): it waits as
+/// [`stats_of`] does.
+fn read_all(
+ session: &Session,
+ api: &Api,
+ checks: &Checks,
+ wanted: &HashSet<String>,
+) -> std::collections::HashMap<String, Arc<watch::Seen>> {
+ let all: Vec<(String, Handle)> = session.with_torrents(|all| {
+ all.map(|(_, h)| (h.info_hash().as_string(), h.clone()))
+ .collect()
+ });
+ all.into_iter()
+ .map(|(hash, h)| {
+ let mut seen = read_one(&h, &hash, checks);
+ if wanted.contains(&hash) {
+ let i = TorrentIdOrHash::Hash(h.info_hash());
+ seen.swarm = Some(Swarm {
+ peers: peers_of(api, i),
+ trackers: trackers_of(&h),
+ pieces: pieces_of(api, i),
+ });
+ }
+ (hash, Arc::new(seen))
+ })
+ .collect()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1945,6 +2119,77 @@ mod tests {
session.stop().await;
}
+ /// #693: what the window reads (`seen` and the rest) follows the session without asking
+ /// librqbit: known from the add on, moving by itself, and changed at once by a pause or a
+ /// removal made here.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn the_window_s_numbers_follow_the_session() {
+ let tmp = tempfile::tempdir().unwrap();
+ let src = tmp.path().join("seed");
+ std::fs::create_dir_all(&src).unwrap();
+ std::fs::write(src.join("a.bin"), vec![7u8; 96 * 1024]).unwrap();
+ std::fs::write(src.join("b.bin"), vec![9u8; 32 * 1024]).unwrap();
+ let torrent = make_torrent(&src).await;
+ let session = Torrents::start(offline(&tmp.path().join("session")))
+ .await
+ .unwrap();
+ let hash = session
+ .add(&torrent, &src, None, Vec::new(), false)
+ .await
+ .unwrap();
+ assert!(session.seen(&hash).is_some(), "known as soon as added");
+ assert!(
+ session.seen(&hash.to_ascii_uppercase()).is_some(),
+ "by its hash in either case"
+ );
+ assert!(
+ session
+ .set_torrent_limits(&hash, Some(1 << 20), None)
+ .is_ok(),
+ "its limits can be set at once"
+ );
+ assert_eq!(session.torrent_limits(&hash), Some((Some(1 << 20), None)));
+ assert_eq!(session.seen_files(&hash), session.files(&hash));
+ // Checked and finished by the watch's own readings.
+ let deadline = std::time::Instant::now() + Duration::from_secs(20);
+ while session.seen(&hash).unwrap().phase != Phase::Finished {
+ assert!(std::time::Instant::now() < deadline, "never seen finished");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let st = session.seen(&hash).unwrap();
+ assert_eq!((st.done, st.total), (128 * 1024, 128 * 1024));
+ // Per file, in the torrent's order (the folder's listing order, which differs by system).
+ let sizes: Vec<u64> = session
+ .seen_files(&hash)
+ .unwrap()
+ .0
+ .iter()
+ .map(|f| f.size)
+ .collect();
+ assert_eq!(st.file_done, sizes);
+ // Its details come with the next reading once asked for.
+ session.seen_swarm(&hash);
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let swarm = loop {
+ let s = session.seen_swarm(&hash);
+ if !s.pieces.is_empty() {
+ break s;
+ }
+ assert!(std::time::Instant::now() < deadline, "details never read");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ };
+ assert_eq!(swarm.pieces, session.pieces(&hash));
+ assert_eq!(swarm.trackers, session.trackers(&hash));
+ // A pause and a removal show at once, not at the next reading.
+ session.pause(&hash).await.unwrap();
+ assert_eq!(session.seen(&hash).unwrap().phase, Phase::Paused);
+ session.remove(&hash, false).await.unwrap();
+ assert!(session.seen(&hash).is_none());
+ tokio::time::sleep(watch::EVERY * 3).await;
+ assert!(session.seen(&hash).is_none(), "still gone after readings");
+ session.stop().await;
+ }
+
/// #39: a torrent's piece order is librqbit's in-order one until set; set, it is kept when
/// the torrent is added again (Add trackers, Recheck).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
diff --git a/crates/torrent/src/watch.rs b/crates/torrent/src/watch.rs
new file mode 100644
index 00000000..1f6d7749
--- /dev/null
+++ b/crates/torrent/src/watch.rs
@@ -0,0 +1,359 @@
+//! The session's numbers, read off the window's thread (#693). librqbit answers a torrent's stats
+//! under its state lock, and a pause holds that lock while the torrent's files finish the writes
+//! under way (an add holds the session's list while it opens the files): on a busy or slow disk,
+//! or with an antivirus scanning each write, that is seconds, and the window, reading the stats
+//! each frame, froze that long.
+//!
+//! One thread reads every torrent for everyone, every [`EVERY`], and after each change made
+//! through [`crate::Torrents`] the one changed is read again at once ([`Watch::put`]). The window
+//! takes the last numbers ([`Watch::get`]) without waiting: a read that hangs holds up nothing
+//! but the next one.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
+use std::time::{Duration, Instant};
+
+use crate::{Handle, Stats, Swarm};
+
+/// How often the thread reads the session again.
+pub(crate) const EVERY: Duration = Duration::from_millis(200);
+
+/// How long a torrent's peers, trackers and pieces are read for after they were last asked for
+/// ([`Watch::want`]): only the progress window shows them, and only for its own torrent.
+const WANTED_FOR: Duration = Duration::from_secs(2);
+
+/// One torrent as last read.
+pub(crate) struct Seen {
+ pub stats: Stats,
+ /// The files chosen (None: all).
+ pub chosen: Option<Vec<usize>>,
+ /// librqbit's handle, for what doesn't wait on its locks (its metadata, its limits, its
+ /// piece order). None only in tests.
+ pub handle: Option<Handle>,
+ /// Its peers, trackers and pieces, while they are wanted.
+ pub swarm: Option<Swarm>,
+}
+
+/// The last reading of every torrent, and the thread that keeps it.
+pub(crate) struct Watch {
+ shared: Arc<Shared>,
+}
+
+struct Shared {
+ state: Mutex<State>,
+ /// Wakes the thread early: closed, or a torrent's details newly wanted.
+ wake: Condvar,
+}
+
+#[derive(Default)]
+struct State {
+ seen: HashMap<String, Arc<Seen>>,
+ /// Counts the puts; each torrent put, with the count when it was. A reading that started
+ /// before a put keeps what the put said about that torrent (it read older numbers).
+ version: u64,
+ put: HashMap<String, u64>,
+ /// The torrents whose details were asked for, and when last.
+ wanted: HashMap<String, Instant>,
+ /// Read again now, not at the next [`EVERY`] (details newly wanted).
+ kicked: bool,
+ closed: bool,
+}
+
+impl Shared {
+ fn lock(&self) -> MutexGuard<'_, State> {
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+}
+
+/// Info hashes as keys: lowercase, as librqbit writes them.
+fn key(hash: &str) -> String {
+ hash.to_ascii_lowercase()
+}
+
+impl Watch {
+ /// Keep `first` (a reading made before), and read again with `read` every `every` on a
+ /// thread of its own. `read` gets the torrents whose details are wanted and returns every
+ /// torrent there is, by info hash; it may wait (for ever).
+ pub(crate) fn start(
+ first: HashMap<String, Arc<Seen>>,
+ every: Duration,
+ mut read: impl FnMut(&HashSet<String>) -> HashMap<String, Arc<Seen>> + Send + 'static,
+ ) -> Watch {
+ let shared = Arc::new(Shared {
+ state: Mutex::new(State {
+ seen: first,
+ ..Default::default()
+ }),
+ wake: Condvar::new(),
+ });
+ let worker = shared.clone();
+ let spawned = std::thread::Builder::new()
+ .name("torrent stats".into())
+ .spawn(move || {
+ loop {
+ let (start, wanted) = {
+ let mut s = worker.lock();
+ if s.closed {
+ return;
+ }
+ s.wanted.retain(|_, at| at.elapsed() < WANTED_FOR);
+ (s.version, s.wanted.keys().cloned().collect::<HashSet<_>>())
+ };
+ // Not under the lock: the window never waits for this.
+ let fresh = read(&wanted);
+ let s = worker.lock();
+ let mut s = publish(s, start, fresh);
+ if s.closed {
+ return;
+ }
+ s = worker
+ .wake
+ .wait_timeout_while(s, every, |s| !s.closed && !s.kicked)
+ .unwrap_or_else(PoisonError::into_inner)
+ .0;
+ s.kicked = false;
+ drop(s);
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!("torrents: can't start the thread that reads their numbers: {e}");
+ }
+ Watch { shared }
+ }
+
+ /// The torrent as last read (None: not in the session). Never waits on the engine.
+ pub(crate) fn get(&self, hash: &str) -> Option<Arc<Seen>> {
+ self.shared.lock().seen.get(&key(hash)).cloned()
+ }
+
+ /// Read its peers, trackers and pieces too, for [`WANTED_FOR`] from now.
+ pub(crate) fn want(&self, hash: &str) {
+ let mut s = self.shared.lock();
+ if s.wanted.insert(key(hash), Instant::now()).is_none() {
+ s.kicked = true;
+ self.shared.wake.notify_all();
+ }
+ }
+
+ /// What a change just made says about the torrent (None: it left the session); its details
+ /// stay as last read until the next reading.
+ pub(crate) fn put(&self, hash: &str, seen: Option<Seen>) {
+ let mut s = self.shared.lock();
+ let k = key(hash);
+ s.version += 1;
+ let v = s.version;
+ s.put.insert(k.clone(), v);
+ match seen {
+ Some(mut new) => {
+ if new.swarm.is_none() {
+ new.swarm = s.seen.get(&k).and_then(|old| old.swarm.clone());
+ }
+ s.seen.insert(k, Arc::new(new));
+ }
+ None => {
+ s.seen.remove(&k);
+ }
+ }
+ }
+
+ /// Stop reading (the session stops).
+ pub(crate) fn close(&self) {
+ self.shared.lock().closed = true;
+ self.shared.wake.notify_all();
+ }
+}
+
+impl Drop for Watch {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+/// Take a reading begun at put count `start`: the torrents put since keep what the put said.
+fn publish(
+ mut s: MutexGuard<'_, State>,
+ start: u64,
+ mut fresh: HashMap<String, Arc<Seen>>,
+) -> MutexGuard<'_, State> {
+ let newer: Vec<String> = s
+ .put
+ .iter()
+ .filter(|(_, at)| **at > start)
+ .map(|(h, _)| h.clone())
+ .collect();
+ for h in newer {
+ match s.seen.get(&h) {
+ Some(kept) => fresh.insert(h, kept.clone()),
+ None => fresh.remove(&h),
+ };
+ }
+ s.put.retain(|_, at| *at > start);
+ s.seen = fresh;
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::Phase;
+ use std::sync::mpsc;
+
+ fn stats(done: u64) -> Stats {
+ Stats {
+ phase: Phase::Downloading,
+ checked: None,
+ done,
+ total: 100,
+ uploaded: 0,
+ fetched: done,
+ down_speed: 0.0,
+ up_speed: 0.0,
+ file_done: vec![done],
+ peers_live: 1,
+ peers_seen: 1,
+ error: None,
+ }
+ }
+
+ fn seen(done: u64) -> Arc<Seen> {
+ Arc::new(Seen {
+ stats: stats(done),
+ chosen: None,
+ handle: None,
+ swarm: None,
+ })
+ }
+
+ /// #693: while the engine holds a torrent's lock (here, a reading that waits until the
+ /// test lets it go), the window's frames keep going: each takes the last numbers at once.
+ #[test]
+ fn a_frame_never_waits_for_the_engine() {
+ let (entered_tx, entered) = mpsc::channel();
+ let (release, released) = mpsc::channel::<()>();
+ let released = Mutex::new(released);
+ let mut reads = 0u64;
+ let w = Watch::start(
+ HashMap::from([("aa".to_owned(), seen(10))]),
+ Duration::from_millis(5),
+ move |_| {
+ reads += 1;
+ if reads == 2 {
+ // The second reading finds the lock held, for as long as the test says.
+ let _ = entered_tx.send(());
+ let _ = released.lock().unwrap().recv();
+ }
+ HashMap::from([("aa".to_owned(), seen(10 + reads))])
+ },
+ );
+ entered
+ .recv_timeout(Duration::from_secs(5))
+ .expect("the reading reached the held lock");
+ // Twenty frames while the lock is held: each takes the last numbers at once (a busy
+ // runner may sleep longer between them; only the frames themselves are timed).
+ for _ in 0..20 {
+ let frame = Instant::now();
+ let got = w.get("AA").expect("the torrent as last read");
+ assert_eq!(got.stats.done, 11, "the reading before the stall");
+ assert!(
+ frame.elapsed() < Duration::from_millis(50),
+ "a frame waited {:?} on the engine",
+ frame.elapsed()
+ );
+ std::thread::sleep(Duration::from_millis(16));
+ }
+ // The lock let go: the numbers move again.
+ release.send(()).unwrap();
+ let at = Instant::now();
+ while w.get("aa").unwrap().stats.done <= 11 {
+ assert!(at.elapsed() < Duration::from_secs(5), "never read again");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+
+ /// A change made meanwhile wins over a reading that began before it (which read older
+ /// numbers); a torrent removed stays removed.
+ #[test]
+ fn a_put_wins_over_an_older_reading() {
+ let s = Mutex::new(State {
+ seen: HashMap::from([("aa".to_owned(), seen(1)), ("bb".to_owned(), seen(1))]),
+ ..Default::default()
+ });
+ let start = s.lock().unwrap().version;
+ // A reading starts; meanwhile aa is paused (put) and bb removed.
+ let w = Watch {
+ shared: Arc::new(Shared {
+ state: s,
+ wake: Condvar::new(),
+ }),
+ };
+ w.shared.lock().closed = true;
+ w.put(
+ "aa",
+ Some(Seen {
+ stats: stats(50),
+ chosen: None,
+ handle: None,
+ swarm: None,
+ }),
+ );
+ w.put("bb", None);
+ let fresh = HashMap::from([
+ ("aa".to_owned(), seen(2)),
+ ("bb".to_owned(), seen(2)),
+ ("cc".to_owned(), seen(2)),
+ ]);
+ drop(publish(w.shared.lock(), start, fresh));
+ assert_eq!(w.get("aa").unwrap().stats.done, 50, "the put's numbers");
+ assert!(w.get("bb").is_none(), "removed meanwhile");
+ assert_eq!(w.get("cc").unwrap().stats.done, 2, "new in the reading");
+ // The next reading began after the puts: it is taken whole.
+ let start = w.shared.lock().version;
+ drop(publish(
+ w.shared.lock(),
+ start,
+ HashMap::from([("aa".to_owned(), seen(60))]),
+ ));
+ assert_eq!(w.get("aa").unwrap().stats.done, 60);
+ assert!(w.get("cc").is_none());
+ }
+
+ /// Details are read only while asked for, and a put keeps the last ones.
+ #[test]
+ fn details_while_wanted() {
+ let (tx, rx) = mpsc::channel();
+ let w = Watch::start(HashMap::new(), Duration::from_millis(5), move |wanted| {
+ let _ = tx.send(wanted.clone());
+ HashMap::from([(
+ "aa".to_owned(),
+ Arc::new(Seen {
+ stats: stats(1),
+ chosen: None,
+ handle: None,
+ swarm: wanted.contains("aa").then(|| Swarm {
+ trackers: vec!["udp://t".into()],
+ ..Default::default()
+ }),
+ }),
+ )])
+ });
+ assert!(rx.recv().unwrap().is_empty());
+ w.want("AA");
+ let at = Instant::now();
+ while w.get("aa").and_then(|s| s.swarm.clone()).is_none() {
+ assert!(at.elapsed() < Duration::from_secs(5), "details never read");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ w.put(
+ "aa",
+ Some(Seen {
+ stats: stats(2),
+ chosen: None,
+ handle: None,
+ swarm: None,
+ }),
+ );
+ let got = w.get("aa").unwrap();
+ assert_eq!(got.stats.done, 2);
+ assert_eq!(got.swarm.as_ref().unwrap().trackers, ["udp://t"]);
+ }
+}