Skip to content

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

The window never waits for the disk to log or to save the RSS feeds (part of #513) (#525)

Ahmed Nefzaoui3ff3ead57b3f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 199997f4..58a2b9a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- The window no longer waits for the disk to write MDM's log or to save the RSS feeds: while Windows held every write on the disk to make a snapshot of it (a restore point or a backup), the window could stop answering until the writes were let go. Both are now written beside the window, as the download list already was (part of [#513](https://github.com/anefzaoui/misterdownloadmanager/issues/513)).
- Windows: video and gallery look-ups no longer fail with "[WinError 448] The path cannot be traversed because it contains an untrusted mount point" when a folder on PATH goes through a junction Windows won't let yt-dlp cross (one an app installed for itself, Codex's for example): yt-dlp, gallery-dl and the ffmpeg they start get that folder's real place instead, and no folder that can't be opened ([#508](https://github.com/anefzaoui/misterdownloadmanager/issues/508)).
- **Download video** from Dailymotion's player embedded in another site: the look-up no longer sends that site as the Referer, which Dailymotion refused with 403, so its formats are found as with the video's own address ([#359](https://github.com/anefzaoui/misterdownloadmanager/issues/359)).
- The video button fades again after a click on the player, in fullscreen too, and stays while you use the keyboard ([#480](https://github.com/anefzaoui/misterdownloadmanager/issues/480)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 2cd7b18e..78cc59c5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -520,6 +520,10 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- 🔄 The window not answering for a few seconds while Windows makes a snapshot of the disk
+ (a restore point or a backup) ([#513](https://github.com/anefzaoui/misterdownloadmanager/issues/513)):
+ the log and the RSS feeds are now written beside the window, as the list already was; fix in
+ review, to confirm on the reporter's computer
- 🔄 Video look-ups failing with "WinError 448 ... untrusted mount point" when a folder on PATH
goes through a junction Windows won't let yt-dlp cross
([#508](https://github.com/anefzaoui/misterdownloadmanager/issues/508)): fix in review
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 1195f594..f6114d43 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -623,6 +623,8 @@ pub struct App {
last_save: Instant,
/// Writes the list off the window's thread.
saver: store::Saver,
+ /// Writes `rss.json` off the window's thread: the feeds' timer saves it by itself (#513).
+ rss_saver: store::Saver,
/// When the light/dark mode was last checked against Windows' app mode.
theme_checked: Option<Instant>,
/// The zoom (View → Interface size, #262) the windows were last drawn at: a change is saved,
@@ -1182,6 +1184,7 @@ impl App {
secrets_confirmed: 0,
last_save: Instant::now(),
saver: store::Saver::new(),
+ rss_saver: store::Saver::writing("rss saver", crate::rss::write),
theme_checked: None,
zoom,
fitted: false,
@@ -3983,13 +3986,19 @@ impl App {
if save {
self.save_rss();
}
+ if let Some(Err(e)) = self.rss_saver.outcome() {
+ tracing::warn!("rss: not saved: {e}");
+ }
}
+ /// On the RSS saver's thread; how it went is logged at the next tick (`rss_tick`).
fn save_rss(&self) {
- if let Some(path) = crate::rss::Store::path()
- && let Err(e) = self.rss.save(&path)
- {
- tracing::warn!("rss: {} not saved: {e}", path.display());
+ let Some(path) = crate::rss::Store::path() else {
+ return;
+ };
+ match self.rss.encode() {
+ Ok(json) => self.rss_saver.queue(path, json),
+ Err(e) => tracing::warn!("rss: {} not saved: {e}", path.display()),
}
}
@@ -8860,6 +8869,8 @@ impl Drop for App {
// No wake for a queue MDM won't be there to start (Linux's alarm would outlive it).
self.wake.clear();
self.keep_unseen();
+ // The feeds as last handed to their saver.
+ self.rss_saver.flush();
// What the saver has in hand first, then the last state, written here and now.
self.saver.flush();
let _ = store::save(
diff --git a/crates/app/src/crash.rs b/crates/app/src/crash.rs
index 0f2c2058..3dbef4c9 100644
--- a/crates/app/src/crash.rs
+++ b/crates/app/src/crash.rs
@@ -121,6 +121,8 @@ fn hook_panics() {
backtrace: std::backtrace::Backtrace::force_capture().to_string(),
};
tracing::error!("panic: {} at {} ({})", p.message, p.location, p.thread);
+ // In the file before the report reads the log's end (the log writes on its own thread).
+ mdm_crash::logs::flush(LOG_FOR_A_REPORT);
if !panic_reported(CLOSING.load(Ordering::Acquire), &p.thread) {
default(info);
return;
@@ -225,8 +227,14 @@ pub fn clean_exit() {
tracing::info!("closing");
r.clean();
}
+ // Some ends exit at once after this: the log's last lines first.
+ mdm_crash::logs::flush(LOG_FOR_A_REPORT);
}
+/// How long a report (or an exit) waits for the log's last lines to be in the file: the log
+/// writes on its own thread (#513), and a disk held longer than this leaves them out.
+const LOG_FOR_A_REPORT: Duration = Duration::from_secs(1);
+
/// Watch the window's frames: a stretch of one (its logic or its UI) running past FREEZE_AFTER
/// is reported once. Time the computer spent asleep (this loop's own tick much longer than
/// asked) isn't counted, nor the waits between frames (no stretch runs then).
@@ -289,6 +297,7 @@ fn watchdog() {
b.faults
);
}
+ mdm_crash::logs::flush(LOG_FOR_A_REPORT);
if let Some(r) = REPORTER.get() {
r.freeze(&Freeze {
ui_thread: ui,
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index 12ee797d..5ce76e04 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -225,19 +225,26 @@ fn main() -> std::process::ExitCode {
}
// A server (#157): the app without a window.
let all: Vec<String> = std::env::args().skip(1).collect();
- if headless::asked(&all) {
- return headless::main(all);
- }
- match app() {
- Ok(()) => std::process::ExitCode::SUCCESS,
- // As `main` returning the error would.
- Err(e) => {
- eprintln!("Error: {e:?}");
- std::process::ExitCode::FAILURE
+ let code = if headless::asked(&all) {
+ headless::main(all)
+ } else {
+ match app() {
+ Ok(()) => std::process::ExitCode::SUCCESS,
+ // As `main` returning the error would.
+ Err(e) => {
+ eprintln!("Error: {e:?}");
+ std::process::ExitCode::FAILURE
+ }
}
- }
+ };
+ // The log's last lines, still on their way to the file (its own thread, #513).
+ mdm_crash::logs::flush(LOG_AT_THE_END);
+ code
}
+/// How long MDM's end waits for its log's last lines (a disk that holds them longer loses them).
+const LOG_AT_THE_END: std::time::Duration = std::time::Duration::from_secs(2);
+
fn app() -> eframe::Result {
// MDM's crash monitor (crash.rs started it): the report window when the app crashes or
// freezes; it never becomes MDM's instance.
diff --git a/crates/app/src/rss.rs b/crates/app/src/rss.rs
index d8e97646..c75a6f47 100644
--- a/crates/app/src/rss.rs
+++ b/crates/app/src/rss.rs
@@ -504,6 +504,16 @@ fn default_minutes() -> u32 {
DEFAULT_MINUTES
}
+/// `rss.json` written as `json` through a temporary file ([`Store::encode`]).
+pub fn write(path: &Path, json: &[u8]) -> std::io::Result<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, json)?;
+ std::fs::rename(&tmp, path)
+}
+
impl Default for Store {
fn default() -> Self {
Store {
@@ -547,17 +557,9 @@ impl Store {
}
}
- /// Written through a temporary file.
- pub fn save(&self, path: &Path) -> std::io::Result<()> {
- if let Some(dir) = path.parent() {
- std::fs::create_dir_all(dir)?;
- }
- let tmp = path.with_extension("json.tmp");
- std::fs::write(
- &tmp,
- serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?,
- )?;
- std::fs::rename(&tmp, path)
+ /// As `rss.json` holds it ([`write`]; the window hands it to a saver thread: app.rs).
+ pub fn encode(&self) -> std::io::Result<Vec<u8>> {
+ serde_json::to_vec_pretty(self).map_err(std::io::Error::other)
}
pub fn new_id(&mut self) -> u64 {
@@ -826,7 +828,7 @@ mod tests {
// Saved and read back; removing a feed takes it out of the rules.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("rss.json");
- s.save(&path).unwrap();
+ write(&path, &s.encode().unwrap()).unwrap();
let back = Store::load(&path);
assert_eq!(back, s);
let mut back = back;
diff --git a/crates/app/src/store.rs b/crates/app/src/store.rs
index 085c2fb1..7ea9d010 100644
--- a/crates/app/src/store.rs
+++ b/crates/app/src/store.rs
@@ -303,7 +303,9 @@ fn write(p: &Path, json: &[u8]) -> std::io::Result<()> {
/// Saves the list on a thread of its own. The write ends with a flush to the disk, which waited
/// for every byte a big download had written meanwhile: on the window's thread it froze MDM for
/// seconds (a crash report caught it: "freeze in store::save"). The newest list waiting replaces
-/// an older one not yet written.
+/// an older one not yet written. Any file the window keeps saving goes the same way
+/// ([`Saver::writing`]): Windows holding every write on C: for a shadow copy held the window
+/// with it (#513).
pub struct Saver {
shared: std::sync::Arc<(std::sync::Mutex<SaverState>, std::sync::Condvar)>,
}
@@ -317,14 +319,21 @@ struct SaverState {
}
impl Saver {
+ /// The download list's.
pub fn new() -> Saver {
+ Saver::writing("list saver", write)
+ }
+
+ /// A saver thread of its own, `name`, writing what it is handed with `write` (the RSS feeds',
+ /// rss.rs).
+ pub fn writing(name: &str, write: fn(&Path, &[u8]) -> std::io::Result<()>) -> Saver {
let shared = std::sync::Arc::new((
std::sync::Mutex::new(SaverState::default()),
std::sync::Condvar::new(),
));
let worker = shared.clone();
let _ = std::thread::Builder::new()
- .name("list saver".into())
+ .name(name.into())
.spawn(move || {
let (lock, cv) = &*worker;
loop {
@@ -361,7 +370,8 @@ impl Saver {
Ok(())
}
- fn queue(&self, p: std::path::PathBuf, json: Vec<u8>) {
+ /// Hand `json` to the saver thread, to be written as `p`.
+ pub fn queue(&self, p: std::path::PathBuf, json: Vec<u8>) {
let (lock, cv) = &*self.shared;
lock.lock().unwrap_or_else(|e| e.into_inner()).waiting = Some((p, json));
cv.notify_all();
@@ -416,6 +426,40 @@ mod tests {
assert_eq!(load_from(&p, empty()).next_id, 5);
}
+ /// #513: handing a file to a saver never waits for the disk (Windows held every write on C:
+ /// for 8 s while it made a shadow copy, and the window with them when it wrote itself); it
+ /// is written once the disk lets go, the newest handed over.
+ #[test]
+ fn a_saver_hands_over_at_once_while_the_disk_holds_its_writes() {
+ use std::sync::{Condvar, Mutex};
+ static HELD: (Mutex<bool>, Condvar) = (Mutex::new(true), Condvar::new());
+ fn held_write(p: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ let (held, cv) = &HELD;
+ let mut held = held.lock().unwrap();
+ while *held {
+ held = cv.wait(held).unwrap();
+ }
+ crate::rss::write(p, bytes)
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("rss.json");
+ let saver = Saver::writing("test saver", held_write);
+ let start = std::time::Instant::now();
+ for n in 0..50u8 {
+ saver.queue(p.clone(), vec![b'0' + n % 10]);
+ }
+ assert!(start.elapsed() < Duration::from_secs(1));
+ assert!(
+ !p.exists() && saver.outcome().is_none(),
+ "the disk holds it"
+ );
+ *HELD.0.lock().unwrap() = false;
+ HELD.1.notify_all();
+ saver.flush();
+ assert_eq!(saver.outcome(), Some(Ok(())));
+ assert_eq!(std::fs::read(&p).unwrap(), b"9");
+ }
+
#[test]
fn a_damaged_list_falls_back_to_the_previous_generation() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/crash/src/logs.rs b/crates/crash/src/logs.rs
index 63f810c9..3c7a3d22 100644
--- a/crates/crash/src/logs.rs
+++ b/crates/crash/src/logs.rs
@@ -1,12 +1,17 @@
//! The log MDM keeps in release builds too: `<data>/logs/mdm.log`, rolled over at a size into
//! `mdm.1.log` … `mdm.3.log` (the crash monitor keeps `monitor.log` the same way). Each line is
-//! written through at once (a crash loses nothing that was logged), and a report takes the last
-//! lines of MDM's.
+//! handed to the log's own thread, which writes it at once; a report takes the last lines of
+//! MDM's ([`flush`] first, so it has them all).
+//!
+//! The window's thread never writes the file itself (#513): while Windows held every write on
+//! C: for a shadow copy, a line logged there (or one waiting behind another thread's held write)
+//! kept the window from answering until the writes were let go.
-use std::fs::{self, File, OpenOptions};
+use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
+use std::sync::mpsc;
+use std::time::Duration;
/// A log file grows to this, then rolls over.
pub const MAX_BYTES: u64 = 2 * 1024 * 1024;
@@ -30,16 +35,25 @@ fn rolled(dir: &Path, name: &str, n: usize) -> PathBuf {
dir.join(format!("{name}.{n}.log"))
}
-/// The writer behind the log: appends to `mdm.log`, rolling it over past [`MAX_BYTES`].
+/// What the log's thread is handed.
+enum Msg {
+ Line(Vec<u8>),
+ /// Answered once everything handed over before it is written.
+ Flush(mpsc::Sender<()>),
+}
+
+/// The writer behind the log: hands each line to the log's thread, which appends it to
+/// `mdm.log`, rolling it over past [`MAX_BYTES`]. Writing never waits for the disk.
#[derive(Clone)]
pub struct Rolling {
- inner: Arc<Mutex<Inner>>,
+ tx: mpsc::Sender<Msg>,
}
struct Inner {
dir: PathBuf,
name: &'static str,
- file: Option<File>,
+ /// The open log file (another writer in a test).
+ file: Option<Box<dyn Write + Send>>,
size: u64,
}
@@ -49,15 +63,42 @@ impl Rolling {
let path = current(&dir, name);
let file = OpenOptions::new().create(true).append(true).open(&path)?;
let size = file.metadata().map(|m| m.len()).unwrap_or(0);
- Ok(Rolling {
- inner: Arc::new(Mutex::new(Inner {
- dir,
- name,
- file: Some(file),
- size,
- })),
+ Rolling::over(Inner {
+ dir,
+ name,
+ file: Some(Box::new(file)),
+ size,
})
}
+
+ /// The log's thread, writing into `inner`.
+ fn over(mut inner: Inner) -> io::Result<Rolling> {
+ let name = inner.name;
+ let (tx, rx) = mpsc::channel();
+ std::thread::Builder::new()
+ .name(format!("{name} log"))
+ .spawn(move || {
+ for msg in rx {
+ match msg {
+ Msg::Line(line) => inner.append(&line),
+ Msg::Flush(done) => {
+ if let Some(f) = inner.file.as_mut() {
+ let _ = f.flush();
+ }
+ let _ = done.send(());
+ }
+ }
+ }
+ })?;
+ Ok(Rolling { tx })
+ }
+
+ /// Wait, up to `within`, until every line handed over so far is written. False when it
+ /// wasn't (the disk held, or the log's thread gone).
+ pub fn flush_within(&self, within: Duration) -> bool {
+ let (done, written) = mpsc::channel();
+ self.tx.send(Msg::Flush(done)).is_ok() && written.recv_timeout(within).is_ok()
+ }
}
impl Inner {
@@ -72,34 +113,52 @@ impl Inner {
.create(true)
.append(true)
.open(current(dir, name))
- .ok();
+ .ok()
+ .map(|f| Box::new(f) as Box<dyn Write + Send>);
self.size = 0;
}
+
+ fn append(&mut self, line: &[u8]) {
+ if self.size + line.len() as u64 > MAX_BYTES {
+ self.roll();
+ }
+ if let Some(f) = self.file.as_mut()
+ && f.write_all(line).is_ok()
+ {
+ self.size += line.len() as u64;
+ }
+ }
}
impl Write for Rolling {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- // A poisoned lock (a panic while logging) must not stop the log: take it back.
- let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
- if inner.size + buf.len() as u64 > MAX_BYTES {
- inner.roll();
- }
- if let Some(f) = inner.file.as_mut() {
- f.write_all(buf)?;
- inner.size += buf.len() as u64;
- }
+ self.tx
+ .send(Msg::Line(buf.to_vec()))
+ .map_err(|_| io::Error::other("the log's thread is gone"))?;
Ok(buf.len())
}
+ /// Waits for the log's thread to have written everything (tests, [`flush`]).
fn flush(&mut self) -> io::Result<()> {
- let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
- match inner.file.as_mut() {
- Some(f) => f.flush(),
- None => Ok(()),
- }
+ let (done, written) = mpsc::channel();
+ self.tx
+ .send(Msg::Flush(done))
+ .ok()
+ .and_then(|()| written.recv().ok())
+ .ok_or_else(|| io::Error::other("the log's thread is gone"))
}
}
+/// The log [`init`] started in this process.
+static LOG: std::sync::OnceLock<Rolling> = std::sync::OnceLock::new();
+
+/// Wait, up to `within`, until every line logged so far is in the file: before a report reads
+/// the log's end, and as MDM ends (lines still on their way would be lost with the process).
+/// True when they are, or when there is no log.
+pub fn flush(within: Duration) -> bool {
+ LOG.get().is_none_or(|log| log.flush_within(within))
+}
+
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Rolling {
type Writer = Rolling;
fn make_writer(&'a self) -> Rolling {
@@ -115,6 +174,7 @@ pub fn init(data: &Path, name: &'static str) -> bool {
let Ok(writer) = Rolling::new(dir(data), name) else {
return false;
};
+ let _ = LOG.set(writer.clone());
let filter = std::env::var("MDM_LOG")
.ok()
.and_then(|f| EnvFilter::try_new(f).ok())
@@ -162,9 +222,77 @@ mod tests {
w.write_all(line.as_bytes()).unwrap();
}
writeln!(w, "last").unwrap();
+ w.flush().unwrap();
assert!(rolled(&dir(tmp.path()), APP, 1).exists());
let t = tail(tmp.path(), 20);
assert_eq!(t.len(), 20);
assert_eq!(t.last().unwrap(), "last");
}
+
+ /// #513: a line is logged at once while the disk holds the log's writes (Windows making a
+ /// shadow copy held every write on C: for 8 s, and the window with them): only the log's
+ /// own thread waits, and the lines are all written, in order, once the disk lets go.
+ #[test]
+ fn logging_never_waits_for_the_disk() {
+ use std::sync::{Arc, Condvar, Mutex};
+ use std::time::Instant;
+
+ /// A file whose writes wait until it is let go, then land in `out`.
+ struct Held {
+ gate: Arc<(Mutex<bool>, Condvar)>,
+ out: Arc<Mutex<Vec<u8>>>,
+ }
+ impl Write for Held {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ let (open, cv) = &*self.gate;
+ let mut open = open.lock().unwrap();
+ while !*open {
+ open = cv.wait(open).unwrap();
+ }
+ self.out.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+ let gate = Arc::new((Mutex::new(false), Condvar::new()));
+ let out = Arc::new(Mutex::new(Vec::new()));
+ let tmp = tempfile::tempdir().unwrap();
+ let log = Rolling::over(Inner {
+ dir: tmp.path().to_owned(),
+ name: APP,
+ file: Some(Box::new(Held {
+ gate: gate.clone(),
+ out: out.clone(),
+ })),
+ size: 0,
+ })
+ .unwrap();
+
+ // The window's thread logs while the disk holds the first line.
+ let (said, done) = mpsc::channel();
+ let mut w = log.clone();
+ let window = std::thread::spawn(move || {
+ let start = Instant::now();
+ for n in 0..100 {
+ writeln!(w, "line {n}").unwrap();
+ }
+ said.send(start.elapsed()).unwrap();
+ });
+ let took = done
+ .recv_timeout(Duration::from_secs(5))
+ .expect("logging waited for the held disk");
+ assert!(took < Duration::from_secs(1), "{took:?}");
+ window.join().unwrap();
+ assert!(!log.flush_within(Duration::from_millis(100)), "still held");
+
+ *gate.0.lock().unwrap() = true;
+ gate.1.notify_all();
+ assert!(log.flush_within(Duration::from_secs(5)));
+ let text = String::from_utf8(out.lock().unwrap().clone()).unwrap();
+ let lines: Vec<&str> = text.lines().collect();
+ assert_eq!(lines.len(), 100);
+ assert_eq!((lines[0], lines[99]), ("line 0", "line 99"));
+ }
}