S007: retries, host rests, network, sleep and disk waits
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
73723db690
commit
f85b2509d6
15 changed files with 745 additions and 24 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -2222,6 +2222,7 @@ dependencies = [
|
|||
"chrono",
|
||||
"dirs",
|
||||
"fastrand",
|
||||
"futures-lite",
|
||||
"log",
|
||||
"medlar-testserver",
|
||||
"percent-encoding",
|
||||
|
|
@ -2236,6 +2237,7 @@ dependencies = [
|
|||
"tempfile",
|
||||
"tokio",
|
||||
"url",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ description = "Medlar's engine, store and settings"
|
|||
arc-swap = "1.9.5"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
dirs = "6"
|
||||
futures-lite = "2.6"
|
||||
log = { workspace = true, features = ["std"] }
|
||||
percent-encoding = "2.3.2"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] }
|
||||
|
|
@ -21,6 +22,8 @@ serde.workspace = true
|
|||
serde_json.workspace = true
|
||||
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time"] }
|
||||
url = "2"
|
||||
# Without its tokio feature: the window's accessibility and tray share this build and run outside of tokio.
|
||||
zbus = "5.19"
|
||||
|
||||
[dev-dependencies]
|
||||
fastrand = "2.5.0"
|
||||
|
|
|
|||
|
|
@ -199,6 +199,7 @@ impl Failure {
|
|||
fn of_status(code: u16, begun: bool) -> ErrorKind {
|
||||
match code {
|
||||
401 | 407 => ErrorKind::Login,
|
||||
511 => ErrorKind::Portal,
|
||||
403 | 410 if begun => ErrorKind::Expired,
|
||||
403 => ErrorKind::Forbidden,
|
||||
404 | 410 => ErrorKind::NotFound,
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@ pub mod http;
|
|||
pub mod logging;
|
||||
pub mod manager;
|
||||
pub mod model;
|
||||
pub mod net_state;
|
||||
pub mod part;
|
||||
pub mod paths;
|
||||
pub mod recover;
|
||||
pub mod redact;
|
||||
pub mod segment;
|
||||
pub mod settings;
|
||||
|
|
|
|||
|
|
@ -6,9 +6,13 @@
|
|||
use super::bin::Binned;
|
||||
use super::pick::{Candidate, pick};
|
||||
use super::{Answer, Command, Config, Error, Files, Msg, Result, files};
|
||||
use crate::error::{Failure, Place, Retry};
|
||||
use crate::events::Event;
|
||||
use crate::http::{self, Monitor, PartState, PartView, Source, download, safe_name};
|
||||
use crate::model::*;
|
||||
use crate::net_state::{self, Network};
|
||||
use crate::recover::sleep::{self, Sleep};
|
||||
use crate::recover::{Breakers, DiskNeed, Gate};
|
||||
use crate::settings::Limits;
|
||||
use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals};
|
||||
use crate::speed::{History, Meter};
|
||||
|
|
@ -21,7 +25,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|||
use std::sync::{Arc, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tokio::sync::{broadcast, oneshot, watch};
|
||||
|
||||
const LOG_LINES: usize = 200;
|
||||
/// Messages taken in before the next snapshot.
|
||||
|
|
@ -57,6 +61,18 @@ struct Run {
|
|||
received: u64,
|
||||
/// The file's name and size are known.
|
||||
known: bool,
|
||||
/// What was on disk before it began.
|
||||
had: u64,
|
||||
}
|
||||
|
||||
/// What a waiting download waits for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
enum Hold {
|
||||
Until(Instant, Time),
|
||||
Network,
|
||||
/// For a look at its folder; None while one is under way.
|
||||
Disk(Option<Instant>),
|
||||
Wake,
|
||||
}
|
||||
|
||||
/// What waits for a task's work to end.
|
||||
|
|
@ -70,6 +86,8 @@ struct Entry {
|
|||
task: Arc<Task>,
|
||||
host: Arc<str>,
|
||||
work: Option<Work>,
|
||||
hold: Option<Hold>,
|
||||
fails: u32,
|
||||
todo: VecDeque<(Todo, Option<Answer>)>,
|
||||
/// Counts up with each start; 0 for never.
|
||||
forced: u64,
|
||||
|
|
@ -95,6 +113,8 @@ impl Entry {
|
|||
host: host_of(&task.url),
|
||||
task: Arc::new(task),
|
||||
work: None,
|
||||
hold: None,
|
||||
fails: 0,
|
||||
todo: VecDeque::new(),
|
||||
forced: 0,
|
||||
size: None,
|
||||
|
|
@ -156,6 +176,8 @@ impl Entry {
|
|||
wanted: self.wanted,
|
||||
resumable: self.resumable,
|
||||
checked: 0.0,
|
||||
retry_at: if let Some(Hold::Until(_, at)) = self.hold { Some(at) } else { None },
|
||||
fails: self.fails,
|
||||
server: self.host.clone(),
|
||||
history: self.history.clone(),
|
||||
log: self.log.clone(),
|
||||
|
|
@ -189,6 +211,15 @@ pub struct Actor {
|
|||
entries: BTreeMap<TaskId, Entry>,
|
||||
/// Those with a download as their work.
|
||||
runs: BTreeSet<TaskId>,
|
||||
/// Those with a hold.
|
||||
held: BTreeSet<TaskId>,
|
||||
breakers: Breakers,
|
||||
network: Network,
|
||||
/// When the next host has had its rest, as of the last look.
|
||||
next_gate: Option<Instant>,
|
||||
/// Dropped when everything is saved.
|
||||
going: Option<oneshot::Sender<()>>,
|
||||
asleep: bool,
|
||||
/// Those to forget some time.
|
||||
removed: BTreeSet<TaskId>,
|
||||
dirty: BTreeSet<TaskId>,
|
||||
|
|
@ -223,6 +254,12 @@ impl Actor {
|
|||
on_change: vec![],
|
||||
entries: BTreeMap::new(),
|
||||
runs: BTreeSet::new(),
|
||||
held: BTreeSet::new(),
|
||||
breakers: Breakers::default(),
|
||||
network: Network::default(),
|
||||
next_gate: None,
|
||||
going: None,
|
||||
asleep: false,
|
||||
removed: BTreeSet::new(),
|
||||
dirty: BTreeSet::new(),
|
||||
totals: Totals::default(),
|
||||
|
|
@ -246,9 +283,17 @@ impl Actor {
|
|||
continue;
|
||||
}
|
||||
// The program ended in the middle of it.
|
||||
if matches!(task.state, State::Running | State::Checking | State::Finishing) {
|
||||
let cut = matches!(task.state, State::Running | State::Checking | State::Finishing);
|
||||
// It waited for a retry, the network or a disk: that is found out anew.
|
||||
if cut || (task.state == State::Waiting && task.error.as_ref().is_some_and(|e| e.kind.is_some())) {
|
||||
actor.store.set_state(task.id, State::Queued, None)?;
|
||||
(task.state, task.error) = (State::Queued, None);
|
||||
if !actor.config.recovery.auto_resume {
|
||||
let place = Place { server: &host_of(&task.url), folder: &task.folder, begun: true };
|
||||
let error = Some(Failure::new(ErrorKind::Killed, place).error());
|
||||
actor.store.set_state(task.id, State::Paused, error.clone())?;
|
||||
(task.state, task.error) = (State::Paused, error);
|
||||
}
|
||||
}
|
||||
let (id, unfinished) = (task.id, task.state != State::Done && task.downloaded > 0);
|
||||
actor.last_position = actor.last_position.max(task.position);
|
||||
|
|
@ -259,6 +304,10 @@ impl Actor {
|
|||
actor.entries.insert(id, entry);
|
||||
actor.dirty.insert(id);
|
||||
}
|
||||
let bus = actor.config.recovery.bus.clone();
|
||||
let (net, login) = (actor.to.clone(), actor.to.clone());
|
||||
actor.runtime().spawn(net_state::watch(bus.clone(), move |n| drop(net.send(Msg::Network(n)))));
|
||||
actor.runtime().spawn(sleep::watch(bus, move |s| drop(login.send(Msg::Sleep(s)))));
|
||||
actor.publish();
|
||||
Ok(actor)
|
||||
}
|
||||
|
|
@ -279,6 +328,7 @@ impl Actor {
|
|||
self.sample(now);
|
||||
}
|
||||
self.forget(now);
|
||||
self.wake(now);
|
||||
}
|
||||
self.close(inbox);
|
||||
}
|
||||
|
|
@ -292,9 +342,15 @@ impl Actor {
|
|||
if self.totals.history.samples().last().is_some_and(|s| s > 0.0) {
|
||||
return Some(Duration::from_secs(1));
|
||||
}
|
||||
let next = self.removed.iter().filter_map(|id| self.entries[id].forget_at).min()?;
|
||||
let now = Instant::now();
|
||||
let forget = self.removed.iter().filter_map(|id| self.entries[id].forget_at);
|
||||
let held = self.held.iter().filter_map(|id| match self.entries[id].hold? {
|
||||
Hold::Until(at, _) | Hold::Disk(Some(at)) => Some(at),
|
||||
_ => None,
|
||||
});
|
||||
let next = forget.chain(held).chain(self.breakers.next(now)).min()?;
|
||||
// It may wait for work to end; that comes as a message.
|
||||
Some(next.saturating_duration_since(Instant::now()).max(self.config.tick))
|
||||
Some(next.saturating_duration_since(now).max(self.config.tick))
|
||||
}
|
||||
|
||||
fn take(&mut self, msg: Msg) {
|
||||
|
|
@ -304,6 +360,13 @@ impl Actor {
|
|||
Msg::OnChange(call) => self.on_change.push(call),
|
||||
Msg::Ended(id, result) => self.ended(id, result),
|
||||
Msg::Worked(id, result) => self.worked(id, result),
|
||||
Msg::Looked(id, met) => self.looked(id, met),
|
||||
Msg::Network(network) => self.network(network),
|
||||
Msg::Sleep(Sleep::Going(going)) => self.go_to_sleep(going),
|
||||
Msg::Sleep(Sleep::Awake) => self.wake_up(),
|
||||
Msg::Recovery { tries, auto_resume } => {
|
||||
(self.config.recovery.tries, self.config.recovery.auto_resume) = (tries, auto_resume);
|
||||
}
|
||||
Msg::Close => self.closing = true,
|
||||
}
|
||||
}
|
||||
|
|
@ -379,6 +442,11 @@ impl Actor {
|
|||
return self.answer(answer, if removed { Ok(id) } else { Err(store::Error::NotFound.into()) });
|
||||
};
|
||||
match command {
|
||||
Command::KeepBoth(_) if !e.removed() => {
|
||||
let again = Task { state: State::Queued, size: None, etag: None, last_modified: None, mime: None, position: 0.0, ..(*e.task).clone() };
|
||||
let result = self.add(again);
|
||||
self.answer(answer, result);
|
||||
}
|
||||
Command::Remove { files, .. } if !e.removed() => self.remove(id, files, answer),
|
||||
// Comes after a restoration that waits or works.
|
||||
Command::Remove { .. } if !e.todo.is_empty() || matches!(e.work, Some(Work::Files { .. })) => self.later(id, command, answer),
|
||||
|
|
@ -506,7 +574,7 @@ impl Actor {
|
|||
None => result = Err(Error::Name),
|
||||
},
|
||||
Command::Edit { edit, .. } => result = self.change(id, edit),
|
||||
Command::Remove { .. } => {}
|
||||
Command::Remove { .. } | Command::KeepBoth(_) => {}
|
||||
Command::Add(_) => unreachable!("has no id"),
|
||||
}
|
||||
self.answer(answer, result.map(|()| id));
|
||||
|
|
@ -537,7 +605,17 @@ impl Actor {
|
|||
|
||||
fn resume(&mut self, id: TaskId) -> Result<()> {
|
||||
match self.entries[&id].task.state {
|
||||
State::Paused | State::Waiting | State::Failed => self.set_state(id, State::Queued, None),
|
||||
State::Paused | State::Waiting | State::Failed => {
|
||||
self.entry(id).fails = 0;
|
||||
let host = self.entries[&id].host.clone();
|
||||
self.breakers.reset(&host);
|
||||
self.set_state(id, State::Queued, None)
|
||||
}
|
||||
State::Queued => {
|
||||
let host = self.entries[&id].host.clone();
|
||||
self.choose |= self.breakers.reset(&host);
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
|
@ -588,6 +666,7 @@ impl Actor {
|
|||
t.priority = new.priority;
|
||||
t.checksum = new.checksum;
|
||||
t.max_parts = new.max_parts;
|
||||
t.tries = new.tries;
|
||||
t.speed_limit = new.speed_limit;
|
||||
t.headers = new.headers;
|
||||
t.proxy = new.proxy;
|
||||
|
|
@ -625,6 +704,8 @@ impl Actor {
|
|||
}
|
||||
let task = Arc::make_mut(&mut e.task);
|
||||
(task.state, task.error, task.finished_at) = (to, error, finished);
|
||||
e.hold = None;
|
||||
self.held.remove(&id);
|
||||
self.happened.push(Event::State { id, from, to });
|
||||
self.choose = true;
|
||||
Ok(())
|
||||
|
|
@ -662,10 +743,11 @@ impl Actor {
|
|||
HashMap::new()
|
||||
}
|
||||
};
|
||||
let now = Instant::now();
|
||||
let eligible = |e: &Entry| match e.task.state {
|
||||
State::Running => true,
|
||||
// One that is busy keeps its place until it can begin.
|
||||
State::Queued => !e.removed(),
|
||||
State::Queued => !e.removed() && !self.asleep && (e.forced > 0 || !matches!(self.breakers.gate(&e.host, now), Gate::Shut(_))),
|
||||
_ => false,
|
||||
};
|
||||
let candidates = self.entries.iter().filter(|(_, e)| eligible(e)).map(|(id, e)| Candidate {
|
||||
|
|
@ -678,7 +760,14 @@ impl Actor {
|
|||
order: (queues.get(&e.task.queue).copied().unwrap_or_default(), e.task.position),
|
||||
});
|
||||
let per_host = unlimited(self.config.limits.connections_per_host);
|
||||
let host_cap = |host: &str| self.store.host(host).ok().flatten().and_then(|h| h.max_connections).unwrap_or(per_host);
|
||||
let host_cap = |host: &str| {
|
||||
let cap = self.store.host(host).ok().flatten().and_then(|h| h.max_connections).unwrap_or(per_host);
|
||||
if self.breakers.gate(host, now) != Gate::Trial {
|
||||
return cap;
|
||||
}
|
||||
let running = self.runs.iter().filter(|id| &*self.entries[id].host == host).count() as u32;
|
||||
cap.min(running.max(1))
|
||||
};
|
||||
let picked = pick(candidates.collect(), unlimited(self.config.limits.max_active) as usize, host_cap);
|
||||
let chosen: BTreeSet<TaskId> = picked.iter().copied().collect();
|
||||
for id in self.runs.clone() {
|
||||
|
|
@ -710,7 +799,7 @@ impl Actor {
|
|||
};
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let monitor = Arc::new(Monitor::new(unlimited(self.config.limits.parts_per_download)));
|
||||
let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false };
|
||||
let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded };
|
||||
let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone());
|
||||
self.runtime().spawn(async move {
|
||||
let work = tokio::spawn(async move { download(&shared, id, source, &options, &monitor, stopped).await });
|
||||
|
|
@ -751,6 +840,7 @@ impl Actor {
|
|||
|
||||
fn ended(&mut self, id: TaskId, result: std::result::Result<PathBuf, Why>) {
|
||||
self.measure(id, Duration::ZERO);
|
||||
let had = if let Some(Work::Run(run)) = &self.entries[&id].work { run.had } else { 0 };
|
||||
self.runs.remove(&id);
|
||||
let reloaded = self.reload(id, true);
|
||||
let e = self.entry(id);
|
||||
|
|
@ -759,13 +849,20 @@ impl Actor {
|
|||
if let Err(why) = reloaded {
|
||||
log::error!("task {id} not read: {why}");
|
||||
}
|
||||
if self.entries[&id].downloaded > had {
|
||||
self.entry(id).fails = 0;
|
||||
}
|
||||
match result {
|
||||
Ok(_) => self.finished(id),
|
||||
Err(Why::Http(http::Error::Stopped)) => self.suspend(id),
|
||||
Err(why) if self.entries[&id].task.state == State::Running => self.failed(id, &why),
|
||||
// It was being stopped anyway.
|
||||
Err(why) => self.entry(id).log(&tr!("log.failed", why = words(&why))),
|
||||
Err(why) => {
|
||||
let text = self.failure(id, &why).text;
|
||||
self.entry(id).log(&tr!("log.failed", why = text));
|
||||
}
|
||||
}
|
||||
self.saved();
|
||||
self.next(id);
|
||||
}
|
||||
|
||||
|
|
@ -773,7 +870,7 @@ impl Actor {
|
|||
fn finished(&mut self, id: TaskId) {
|
||||
let way: &[State] = match self.entries[&id].task.state {
|
||||
State::Paused => &[State::Queued, State::Running, State::Finishing, State::Done],
|
||||
State::Queued => &[State::Running, State::Finishing, State::Done],
|
||||
State::Queued | State::Waiting => &[State::Running, State::Finishing, State::Done],
|
||||
_ => &[State::Finishing, State::Done],
|
||||
};
|
||||
for state in way {
|
||||
|
|
@ -782,16 +879,183 @@ impl Actor {
|
|||
self.totals.counters.finished += 1;
|
||||
let e = self.entry(id);
|
||||
e.counters.finished += 1;
|
||||
e.forced = 0;
|
||||
(e.forced, e.fails) = (0, 0);
|
||||
e.took(None);
|
||||
}
|
||||
|
||||
fn failed(&mut self, id: TaskId, why: &Why) {
|
||||
let failure = self.failure(id, why);
|
||||
log::debug!("task {id}: {}: {why:?}", failure.kind.name());
|
||||
let now = Instant::now();
|
||||
self.totals.counters.failed += 1;
|
||||
let e = self.entry(id);
|
||||
e.counters.failed += 1;
|
||||
e.forced = 0;
|
||||
self.move_to(id, State::Failed, Some(TaskError { kind: None, detail: words(why) }));
|
||||
e.fails += 1;
|
||||
let (fails, host) = (e.fails, e.host.clone());
|
||||
let recovery = &self.config.recovery;
|
||||
if failure.kind.of_host() {
|
||||
self.breakers.failed(&host, recovery, now);
|
||||
} else if matches!(why, Why::Http(http::Error::Status { .. })) {
|
||||
self.answers_again(&host);
|
||||
}
|
||||
let recovery = &self.config.recovery;
|
||||
let limit = self.entries[&id].task.tries.unwrap_or(recovery.tries);
|
||||
let hold = match failure.kind.retry() {
|
||||
Retry::Never => None,
|
||||
Retry::Later { .. } if limit > 0 && fails > limit => None,
|
||||
Retry::Later { .. } => recovery.wait(failure.kind, fails, failure.retry_after).map(|wait| {
|
||||
let wait = match self.breakers.gate(&host, now) {
|
||||
Gate::Shut(until) => wait.max(until - now),
|
||||
_ => wait,
|
||||
};
|
||||
Hold::Until(now + wait, crate::model::now() + wait.as_millis() as Time)
|
||||
}),
|
||||
Retry::Network => Some(Hold::Network),
|
||||
Retry::Disk => Some(Hold::Disk(Some(now + recovery.look(fails)))),
|
||||
Retry::Wake => Some(Hold::Wake),
|
||||
};
|
||||
match hold {
|
||||
Some(hold) => self.wait(id, failure.error(), hold),
|
||||
None => self.move_to(id, State::Failed, Some(failure.error())),
|
||||
}
|
||||
}
|
||||
|
||||
fn wait(&mut self, id: TaskId, error: TaskError, hold: Hold) {
|
||||
self.move_to(id, State::Waiting, Some(error));
|
||||
self.held.insert(id);
|
||||
let e = self.entry(id);
|
||||
e.hold = Some(hold);
|
||||
if let Hold::Until(at, _) = hold {
|
||||
let n = at.saturating_duration_since(Instant::now()).as_secs_f64().ceil() as u64;
|
||||
e.log(&tr!("log.retry", n = n));
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(&self, id: TaskId, why: &Why) -> Failure {
|
||||
let place = self.place(id);
|
||||
let failure = match why {
|
||||
Why::Http(e) => Failure::of(e, place),
|
||||
Why::Panic => Failure::new(ErrorKind::Crashed, place),
|
||||
};
|
||||
match self.network {
|
||||
Network::Offline if failure.kind.of_network() => Failure::new(ErrorKind::Offline, place),
|
||||
// Its page comes in place of everything.
|
||||
Network::Portal if failure.kind.of_network() || matches!(failure.kind, ErrorKind::Tls | ErrorKind::WrongContent) => {
|
||||
Failure::new(ErrorKind::Portal, place)
|
||||
}
|
||||
// No way to see the end of it but to try.
|
||||
Network::Unknown if failure.kind == ErrorKind::Portal => Failure::new(ErrorKind::WrongContent, place),
|
||||
_ => failure,
|
||||
}
|
||||
}
|
||||
|
||||
fn place(&self, id: TaskId) -> Place<'_> {
|
||||
let e = &self.entries[&id];
|
||||
Place { server: &e.host, folder: &e.task.folder, begun: e.downloaded > 0 }
|
||||
}
|
||||
|
||||
// Waiting downloads.
|
||||
|
||||
fn release(&mut self, which: impl Fn(&Entry, Hold) -> bool) {
|
||||
for id in self.held.clone() {
|
||||
if self.entries[&id].hold.is_some_and(|hold| which(&self.entries[&id], hold)) {
|
||||
self.move_to(id, State::Queued, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wake(&mut self, now: Instant) {
|
||||
if self.held.is_empty() {
|
||||
self.choose |= self.gates_open(now);
|
||||
return;
|
||||
}
|
||||
self.release(|_, hold| matches!(hold, Hold::Until(at, _) if at <= now));
|
||||
for id in self.held.clone() {
|
||||
let e = &self.entries[&id];
|
||||
if !matches!(e.hold, Some(Hold::Disk(Some(at))) if at <= now) {
|
||||
continue;
|
||||
}
|
||||
let Some(kind) = e.task.error.as_ref().and_then(|e| e.kind) else { continue };
|
||||
let need = DiskNeed::new(kind, &e.task.folder, &e.task.name, e.downloaded > 0, e.size);
|
||||
let to = self.to.clone();
|
||||
self.runtime().spawn_blocking(move || drop(to.send(Msg::Looked(id, need.met()))));
|
||||
self.entry(id).hold = Some(Hold::Disk(None));
|
||||
}
|
||||
self.choose |= self.gates_open(now);
|
||||
}
|
||||
|
||||
/// A host had its rest since the last time.
|
||||
fn gates_open(&mut self, now: Instant) -> bool {
|
||||
let next = self.breakers.next(now);
|
||||
std::mem::replace(&mut self.next_gate, next).is_some_and(|was| was <= now)
|
||||
}
|
||||
|
||||
fn looked(&mut self, id: TaskId, met: bool) {
|
||||
let recovery = &self.config.recovery;
|
||||
let Some(e) = self.entries.get_mut(&id).filter(|e| e.hold == Some(Hold::Disk(None))) else { return };
|
||||
if met {
|
||||
return self.move_to(id, State::Queued, None);
|
||||
}
|
||||
e.hold = Some(Hold::Disk(Some(Instant::now() + recovery.look(e.fails))));
|
||||
}
|
||||
|
||||
/// Bytes came from this host.
|
||||
fn answers_again(&mut self, host: &str) {
|
||||
if self.breakers.reset(host) {
|
||||
self.choose = true;
|
||||
let of_network = |e: &Entry| e.task.error.as_ref().and_then(|e| e.kind).is_some_and(ErrorKind::of_network);
|
||||
self.release(|e, hold| &*e.host == host && matches!(hold, Hold::Until(..)) && of_network(e));
|
||||
}
|
||||
}
|
||||
|
||||
fn network(&mut self, network: Network) {
|
||||
let was = std::mem::replace(&mut self.network, network);
|
||||
if matches!(network, Network::Offline | Network::Portal) {
|
||||
return;
|
||||
}
|
||||
self.breakers.clear();
|
||||
let of_network = |e: &Entry| e.task.error.as_ref().and_then(|e| e.kind).is_some_and(ErrorKind::of_network);
|
||||
self.release(|e, hold| hold == Hold::Network || (matches!(hold, Hold::Until(..)) && of_network(e)));
|
||||
if was == Network::Offline {
|
||||
// Their connections are dead, though nobody told them.
|
||||
for id in self.resumable_runs() {
|
||||
self.suspend(id);
|
||||
}
|
||||
}
|
||||
self.choose = true;
|
||||
}
|
||||
|
||||
/// Those that lose nothing when they are stopped.
|
||||
fn resumable_runs(&self) -> Vec<TaskId> {
|
||||
self.runs.iter().copied().filter(|id| self.entries[id].resumable != Some(false)).collect()
|
||||
}
|
||||
|
||||
fn go_to_sleep(&mut self, going: oneshot::Sender<()>) {
|
||||
self.asleep = true;
|
||||
for id in self.resumable_runs() {
|
||||
if self.entries[&id].task.state == State::Running {
|
||||
self.stop_run(id);
|
||||
let error = Failure::new(ErrorKind::Sleep, self.place(id)).error();
|
||||
self.wait(id, error, Hold::Wake);
|
||||
}
|
||||
}
|
||||
self.going = Some(going);
|
||||
self.saved();
|
||||
}
|
||||
|
||||
/// Lets the computer sleep when no download is being stopped any more.
|
||||
fn saved(&mut self) {
|
||||
if self.runs.iter().all(|id| self.entries[id].task.state == State::Running) {
|
||||
self.going = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn wake_up(&mut self) {
|
||||
(self.asleep, self.going) = (false, None);
|
||||
self.breakers.clear();
|
||||
self.release(|_, hold| hold == Hold::Wake);
|
||||
self.choose = true;
|
||||
}
|
||||
|
||||
fn worked(&mut self, id: TaskId, result: Result<Worked>) {
|
||||
|
|
@ -840,6 +1104,7 @@ impl Actor {
|
|||
log::error!("task {id} not forgotten: {why}");
|
||||
}
|
||||
self.removed.remove(&id);
|
||||
self.held.remove(&id);
|
||||
self.entries.remove(&id);
|
||||
self.happened.push(Event::Forgotten(id));
|
||||
}
|
||||
|
|
@ -898,6 +1163,11 @@ impl Actor {
|
|||
e.second += bytes;
|
||||
e.counters.received += bytes;
|
||||
e.counters.active += active;
|
||||
if bytes > 0 {
|
||||
let host = e.host.clone();
|
||||
self.answers_again(&host);
|
||||
}
|
||||
let e = self.entries.get_mut(&id).expect("seen above");
|
||||
if shot.parts.is_empty() {
|
||||
e.meter.push(bytes, dt, None);
|
||||
return;
|
||||
|
|
@ -932,6 +1202,9 @@ impl Actor {
|
|||
let end = Instant::now() + CLOSING;
|
||||
for id in self.runs.clone() {
|
||||
self.suspend(id);
|
||||
if !self.config.recovery.auto_resume && self.entries[&id].task.state == State::Queued {
|
||||
self.move_to(id, State::Paused, None);
|
||||
}
|
||||
}
|
||||
for e in self.entries.values_mut() {
|
||||
if let Some(Work::Files { cancel, .. }) = &e.work {
|
||||
|
|
@ -957,8 +1230,3 @@ impl Actor {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// S007 puts plain words and kinds here.
|
||||
fn words(why: &Why) -> String {
|
||||
format!("{why:?}")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ pub use bin::Bin;
|
|||
use crate::events::Event;
|
||||
use crate::http::{Options, Shared};
|
||||
use crate::model::{Task, TaskId};
|
||||
use crate::net_state::Network;
|
||||
use crate::recover::Recovery;
|
||||
use crate::recover::sleep::Sleep;
|
||||
use crate::settings::Limits;
|
||||
use crate::snapshot::Snapshot;
|
||||
use crate::{store, tr};
|
||||
|
|
@ -89,6 +92,8 @@ pub enum Command {
|
|||
Restore(TaskId),
|
||||
/// From the start, as a new file. A finished one stays where it is.
|
||||
Redownload(TaskId),
|
||||
/// Leaves it as it is and adds the same download again, as a new file. Answers with the new one.
|
||||
KeepBoth(TaskId),
|
||||
/// Moves the file too. A taken name gets a number.
|
||||
Move { id: TaskId, folder: PathBuf },
|
||||
/// Renames the file too. A taken name gets a number.
|
||||
|
|
@ -103,7 +108,7 @@ impl Command {
|
|||
use Command::*;
|
||||
match self {
|
||||
Add(_) => None,
|
||||
Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) => Some(*id),
|
||||
Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) => Some(*id),
|
||||
Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } => Some(*id),
|
||||
}
|
||||
}
|
||||
|
|
@ -143,6 +148,7 @@ pub struct Config {
|
|||
pub options: Options,
|
||||
pub limits: Limits,
|
||||
pub bin: Bin,
|
||||
pub recovery: Recovery,
|
||||
/// How long a removal can be undone.
|
||||
pub undo: Duration,
|
||||
/// How often the snapshot follows running downloads.
|
||||
|
|
@ -156,6 +162,7 @@ impl Config {
|
|||
options: Options::default(),
|
||||
limits,
|
||||
bin: Bin::default(),
|
||||
recovery: Recovery::default(),
|
||||
undo: Duration::from_secs(60),
|
||||
tick: Duration::from_millis(100),
|
||||
}
|
||||
|
|
@ -172,6 +179,11 @@ enum Msg {
|
|||
Ended(TaskId, std::result::Result<PathBuf, actor::Why>),
|
||||
/// File work ended.
|
||||
Worked(TaskId, Result<actor::Worked>),
|
||||
/// A folder was looked at.
|
||||
Looked(TaskId, bool),
|
||||
Network(Network),
|
||||
Sleep(Sleep),
|
||||
Recovery { tries: u32, auto_resume: bool },
|
||||
Close,
|
||||
}
|
||||
|
||||
|
|
@ -207,6 +219,11 @@ impl Manager {
|
|||
let _ = self.to.send(Msg::Limits(limits));
|
||||
}
|
||||
|
||||
/// From the settings; takes effect at the next failure.
|
||||
pub fn set_recovery(&self, tries: u32, auto_resume: bool) {
|
||||
let _ = self.to.send(Msg::Recovery { tries, auto_resume });
|
||||
}
|
||||
|
||||
/// The list of this moment. Never waits.
|
||||
pub fn snapshot(&self) -> Arc<Snapshot> {
|
||||
self.shot.load_full()
|
||||
|
|
|
|||
|
|
@ -164,6 +164,8 @@ pub struct Task {
|
|||
/// `sha256:…`.
|
||||
pub checksum: Option<String>,
|
||||
pub max_parts: Option<u32>,
|
||||
/// Failures in a row before it fails, 0 for never. None for the setting.
|
||||
pub tries: Option<u32>,
|
||||
/// Bytes per second.
|
||||
pub speed_limit: Option<u64>,
|
||||
/// Cookies and authorization are refused here; they go to the keyring.
|
||||
|
|
@ -202,6 +204,7 @@ impl Default for Task {
|
|||
last_modified: None,
|
||||
checksum: None,
|
||||
max_parts: None,
|
||||
tries: None,
|
||||
speed_limit: None,
|
||||
headers: vec![],
|
||||
proxy: None,
|
||||
|
|
|
|||
143
crates/core/src/net_state.rs
Normal file
143
crates/core/src/net_state.rs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
//! Whether there is a network, from NetworkManager or, without it, from the routes.
|
||||
|
||||
use futures_lite::StreamExt;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Which D-Bus to ask.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum Bus {
|
||||
/// None, and no routes either: the network counts as unknown.
|
||||
#[default]
|
||||
Off,
|
||||
/// The one of the system.
|
||||
System,
|
||||
/// A fake one (tests).
|
||||
At(String),
|
||||
}
|
||||
|
||||
impl Bus {
|
||||
pub(crate) async fn connect(&self) -> zbus::Result<Option<zbus::Connection>> {
|
||||
match self {
|
||||
Bus::Off => Ok(None),
|
||||
Bus::System => zbus::Connection::system().await.map(Some),
|
||||
Bus::At(address) => zbus::connection::Builder::address(address.as_str())?.build().await.map(Some),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Network {
|
||||
#[default]
|
||||
Unknown,
|
||||
Online,
|
||||
Offline,
|
||||
/// Every link leads to the network's own sign-in page.
|
||||
Portal,
|
||||
}
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.NetworkManager",
|
||||
default_service = "org.freedesktop.NetworkManager",
|
||||
default_path = "/org/freedesktop/NetworkManager",
|
||||
gen_blocking = false
|
||||
)]
|
||||
trait Manager {
|
||||
#[zbus(property)]
|
||||
fn state(&self) -> zbus::Result<u32>;
|
||||
|
||||
#[zbus(property)]
|
||||
fn connectivity(&self) -> zbus::Result<u32>;
|
||||
}
|
||||
|
||||
/// NetworkManager's numbers. Less than 50 is no connection; a "limited" one still reaches what is near.
|
||||
fn network(state: u32, connectivity: u32) -> Network {
|
||||
match (state, connectivity) {
|
||||
(0, _) => Network::Unknown,
|
||||
(..50, _) => Network::Offline,
|
||||
(_, 2) => Network::Portal,
|
||||
_ => Network::Online,
|
||||
}
|
||||
}
|
||||
|
||||
const LOOK: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Tells of each change until dropped.
|
||||
pub(crate) async fn watch(bus: Bus, tell: impl Fn(Network) + Send) {
|
||||
if bus == Bus::Off {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = follow(&bus, &tell).await {
|
||||
log::info!("no NetworkManager ({e}): looking at the routes");
|
||||
}
|
||||
let mut last = Network::Unknown;
|
||||
loop {
|
||||
let routes = ["/proc/net/route", "/proc/net/ipv6_route"].map(|f| std::fs::read_to_string(f).unwrap_or_default());
|
||||
let now = if default_route(&routes[0], &routes[1]) { Network::Online } else { Network::Offline };
|
||||
if now != std::mem::replace(&mut last, now) {
|
||||
tell(now);
|
||||
}
|
||||
tokio::time::sleep(LOOK).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn follow(bus: &Bus, tell: &(impl Fn(Network) + Send)) -> zbus::Result<()> {
|
||||
let Some(connection) = bus.connect().await? else { return Ok(()) };
|
||||
let manager = ManagerProxy::new(&connection).await?;
|
||||
let changes = manager.receive_state_changed().await.map(drop).race(manager.receive_connectivity_changed().await.map(drop));
|
||||
futures_lite::pin!(changes);
|
||||
let mut last = Network::Unknown;
|
||||
let mut owner = manager.inner().receive_owner_changed().await?;
|
||||
loop {
|
||||
let now = network(manager.state().await?, manager.connectivity().await.unwrap_or(0));
|
||||
if now != std::mem::replace(&mut last, now) {
|
||||
tell(now);
|
||||
}
|
||||
tokio::select! {
|
||||
Some(()) = changes.next() => {}
|
||||
// It is leaving.
|
||||
Some(None) = owner.next() => return Ok(()),
|
||||
else => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel's tables have a way out of this computer.
|
||||
fn default_route(v4: &str, v6: &str) -> bool {
|
||||
let v4 = v4.lines().skip(1).any(|l| {
|
||||
let f: Vec<&str> = l.split_whitespace().collect();
|
||||
f.len() > 7 && f[1] == "00000000" && f[7] == "00000000" && u32::from_str_radix(f[3], 16).is_ok_and(|flags| flags & 1 == 1)
|
||||
});
|
||||
// The loopback has an unreachable default route.
|
||||
let v6 = v6.lines().any(|l| {
|
||||
let f: Vec<&str> = l.split_whitespace().collect();
|
||||
f.len() > 9 && f[0].bytes().all(|b| b == b'0') && f[1] == "00" && f[9] != "lo"
|
||||
});
|
||||
v4 || v6
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers() {
|
||||
use Network::*;
|
||||
for (state, connectivity, want) in
|
||||
[(0, 0, Unknown), (10, 4, Offline), (20, 1, Offline), (40, 0, Offline), (50, 3, Online), (70, 2, Portal), (70, 4, Online), (70, 0, Online)]
|
||||
{
|
||||
assert_eq!(network(state, connectivity), want, "{state} {connectivity}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes() {
|
||||
let head = "Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\tMTU\tWindow\tIRTT\n";
|
||||
let v4 = |dest, mask| format!("{head}wlan0\t{dest}\t0144A8C0\t0003\t0\t0\t600\t{mask}\t0\t0\t0\n");
|
||||
let (zero, one) = ("0".repeat(32), format!("{}1", "0".repeat(31)));
|
||||
let v6 = |dev| format!("{zero} 00 {zero} 00 {one} 00000400 00000001 00000000 00000003 {dev}\n");
|
||||
assert!(default_route(&v4("00000000", "00000000"), ""));
|
||||
assert!(!default_route(&v4("0044A8C0", "00FFFFFF"), &v6(" lo")));
|
||||
assert!(default_route("", &v6(" wlan0")));
|
||||
assert!(!default_route("", ""));
|
||||
}
|
||||
}
|
||||
213
crates/core/src/recover/mod.rs
Normal file
213
crates/core/src/recover/mod.rs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
//! When a failed download is tried again: waits, hosts that need a rest, folders to look at.
|
||||
|
||||
pub mod sleep;
|
||||
|
||||
use crate::disk;
|
||||
use crate::error::Retry;
|
||||
use crate::model::ErrorKind;
|
||||
use crate::net_state::Bus;
|
||||
use rustix::fs::{Access, StatVfsMountFlags, access, statvfs};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Recovery {
|
||||
/// Failures in a row without a new byte before a download fails; 0 for never. A task can have its own number.
|
||||
pub tries: u32,
|
||||
/// What ran when the program ended runs again at the next start.
|
||||
pub auto_resume: bool,
|
||||
/// All waits are multiplied by this (tests).
|
||||
pub pace: f64,
|
||||
/// Where NetworkManager and logind are. Off unless asked for, so that nothing touches them by accident.
|
||||
pub bus: Bus,
|
||||
}
|
||||
|
||||
impl Default for Recovery {
|
||||
fn default() -> Recovery {
|
||||
Recovery { tries: 10, auto_resume: true, pace: 1.0, bus: Bus::Off }
|
||||
}
|
||||
}
|
||||
|
||||
/// No server may hold a download longer.
|
||||
const LONGEST: Duration = Duration::from_secs(24 * 3600);
|
||||
/// Between two looks at a folder.
|
||||
const LOOK: Duration = Duration::from_secs(3);
|
||||
const REST: Duration = Duration::from_secs(30);
|
||||
const LONGEST_REST: Duration = Duration::from_secs(600);
|
||||
/// Failures in a row, of any download, before a host gets a rest.
|
||||
const PATIENCE: u32 = 3;
|
||||
|
||||
impl Recovery {
|
||||
/// The wait after the `fails`th failure in a row. None when it isn't a matter of time.
|
||||
pub fn wait(&self, kind: ErrorKind, fails: u32, retry_after: Option<Duration>) -> Option<Duration> {
|
||||
let Retry::Later { first, max } = kind.retry() else { return None };
|
||||
let full = first.saturating_mul(1 << fails.saturating_sub(1).min(16)).min(max).mul_f64(self.pace);
|
||||
// A quarter is chance, so that downloads don't come back all at once.
|
||||
let chance = RandomState::new().hash_one(fails) % 1000;
|
||||
let wait = full.mul_f64(0.75 + chance as f64 / 4000.0);
|
||||
Some(wait.max(retry_after.unwrap_or_default()).min(LONGEST))
|
||||
}
|
||||
|
||||
pub fn look(&self, fails: u32) -> Duration {
|
||||
(LOOK * (1 << fails.saturating_sub(1).min(4))).mul_f64(self.pace)
|
||||
}
|
||||
|
||||
fn rest(&self, times: u32) -> Duration {
|
||||
(REST * (1 << times.min(8))).min(LONGEST_REST).mul_f64(self.pace)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Gate {
|
||||
Open,
|
||||
/// One may try.
|
||||
Trial,
|
||||
/// Nobody before that.
|
||||
Shut(Instant),
|
||||
}
|
||||
|
||||
/// Hosts that keep failing get a rest from all downloads.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Breakers(HashMap<String, Breaker>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Breaker {
|
||||
fails: u32,
|
||||
rests: u32,
|
||||
until: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Breakers {
|
||||
pub fn failed(&mut self, host: &str, recovery: &Recovery, now: Instant) {
|
||||
let b = self.0.entry(host.into()).or_default();
|
||||
b.fails += 1;
|
||||
// Those that were under way before the rest say nothing new.
|
||||
if b.fails >= PATIENCE && b.until.is_none_or(|until| now >= until) {
|
||||
b.until = Some(now + recovery.rest(b.rests));
|
||||
b.rests += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// It answers, or the user knows better. True if it was shut.
|
||||
pub fn reset(&mut self, host: &str) -> bool {
|
||||
self.0.remove(host).is_some_and(|b| b.until.is_some())
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.0.clear();
|
||||
}
|
||||
|
||||
pub fn gate(&self, host: &str, now: Instant) -> Gate {
|
||||
match self.0.get(host).and_then(|b| b.until) {
|
||||
None => Gate::Open,
|
||||
Some(until) if now < until => Gate::Shut(until),
|
||||
Some(_) => Gate::Trial,
|
||||
}
|
||||
}
|
||||
|
||||
/// When the next one may be tried again.
|
||||
pub fn next(&self, now: Instant) -> Option<Instant> {
|
||||
self.0.values().filter_map(|b| b.until).filter(|until| *until > now).min()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a disk error needs to be gone.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DiskNeed {
|
||||
pub kind: ErrorKind,
|
||||
pub folder: PathBuf,
|
||||
/// The partial file, if there should be one.
|
||||
pub file: Option<PathBuf>,
|
||||
pub size: Option<u64>,
|
||||
}
|
||||
|
||||
impl DiskNeed {
|
||||
/// Looks whether it is worth another try. Blocks.
|
||||
pub fn met(&self) -> bool {
|
||||
let Some(folder) = self.folder.ancestors().find(|f| f.is_dir()) else { return false };
|
||||
if self.file.is_some() && folder != self.folder || self.file.as_ref().is_some_and(|f| !f.is_file()) {
|
||||
return false;
|
||||
}
|
||||
match self.kind {
|
||||
ErrorKind::FolderGone | ErrorKind::DriveGone if folder != self.folder => false,
|
||||
ErrorKind::DiskFull => self.space(folder),
|
||||
ErrorKind::ReadOnly => statvfs(folder).is_ok_and(|fs| !fs.f_flag.contains(StatVfsMountFlags::RDONLY)),
|
||||
_ => access(folder, Access::WRITE_OK | Access::EXEC_OK).is_ok() && self.file.as_deref().is_none_or(writable),
|
||||
}
|
||||
}
|
||||
|
||||
fn space(&self, folder: &Path) -> bool {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let Ok(fs) = statvfs(folder) else { return false };
|
||||
let has = self.file.as_ref().and_then(|f| f.metadata().ok()).map_or(0, |m| m.blocks() * 512);
|
||||
// Of a file without a known size, some.
|
||||
let need = self.size.unwrap_or(16 << 20).saturating_sub(has).max(1);
|
||||
fs.f_blocks == 0 || fs.f_bavail.saturating_mul(fs.f_frsize) >= need
|
||||
}
|
||||
}
|
||||
|
||||
fn writable(file: &Path) -> bool {
|
||||
access(file, Access::READ_OK | Access::WRITE_OK).is_ok()
|
||||
}
|
||||
|
||||
impl DiskNeed {
|
||||
pub fn new(kind: ErrorKind, folder: &Path, name: &str, begun: bool, size: Option<u64>) -> DiskNeed {
|
||||
DiskNeed { kind, folder: folder.into(), file: begun.then(|| disk::partial_path(folder, name)), size }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn waits_grow_and_end() {
|
||||
let r = Recovery::default();
|
||||
let secs = |kind, fails, after: Option<u64>| r.wait(kind, fails, after.map(Duration::from_secs)).map(|d| d.as_secs_f64());
|
||||
for (fails, full) in [(1, 5.0), (2, 10.0), (4, 40.0), (9, 300.0), (1000, 300.0)] {
|
||||
let wait = secs(ErrorKind::Cut, fails, None).unwrap();
|
||||
assert!(wait <= full && wait >= full * 0.75, "{fails}: {wait}");
|
||||
}
|
||||
assert_eq!(secs(ErrorKind::Busy, 1, Some(7000)), Some(7000.0), "the server's word counts");
|
||||
assert_eq!(secs(ErrorKind::Busy, 1, Some(u64::MAX)), Some(LONGEST.as_secs_f64()));
|
||||
assert!(secs(ErrorKind::Busy, 1, Some(1)).unwrap() >= 22.0);
|
||||
for kind in [ErrorKind::NotFound, ErrorKind::Expired, ErrorKind::Offline, ErrorKind::DiskFull] {
|
||||
assert_eq!(secs(kind, 1, None), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_host_rests_then_one_tries() {
|
||||
let (r, mut b, t) = (Recovery::default(), Breakers::default(), Instant::now());
|
||||
let at = |s| t + Duration::from_secs(s);
|
||||
b.failed("h", &r, t);
|
||||
b.failed("h", &r, t);
|
||||
assert_eq!(b.gate("h", t), Gate::Open);
|
||||
b.failed("h", &r, t);
|
||||
// A fourth that was under way.
|
||||
b.failed("h", &r, at(1));
|
||||
assert_eq!((b.gate("h", at(1)), b.gate("other", t)), (Gate::Shut(at(30)), Gate::Open));
|
||||
assert_eq!((b.next(at(1)), b.next(at(30))), (Some(at(30)), None));
|
||||
assert_eq!(b.gate("h", at(30)), Gate::Trial);
|
||||
b.failed("h", &r, at(31));
|
||||
assert_eq!(b.gate("h", at(31)), Gate::Shut(at(91)));
|
||||
assert!(b.reset("h") && !b.reset("h"));
|
||||
assert_eq!(b.gate("h", at(31)), Gate::Open);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_are_looked_at() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let sub = dir.path().join("sub");
|
||||
let met = |kind, begun| DiskNeed::new(kind, &sub, "f", begun, Some(10)).met();
|
||||
assert!(!met(ErrorKind::FolderGone, false) && met(ErrorKind::Denied, false));
|
||||
assert!(!met(ErrorKind::DiskFull, true));
|
||||
std::fs::create_dir(&sub).unwrap();
|
||||
assert!(met(ErrorKind::FolderGone, false) && !met(ErrorKind::FileGone, true));
|
||||
std::fs::write(sub.join("f.medlar"), "x").unwrap();
|
||||
assert!([ErrorKind::FileGone, ErrorKind::DiskFull, ErrorKind::ReadOnly].iter().all(|k| met(*k, true)));
|
||||
assert!(!DiskNeed::new(ErrorKind::DiskFull, &sub, "f", true, Some(1 << 60)).met());
|
||||
}
|
||||
}
|
||||
54
crates/core/src/recover/sleep.rs
Normal file
54
crates/core/src/recover/sleep.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
//! Sleep and wake, from logind.
|
||||
|
||||
use crate::net_state::Bus;
|
||||
use futures_lite::StreamExt;
|
||||
use tokio::sync::oneshot;
|
||||
use zbus::zvariant::OwnedFd;
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.login1.Manager",
|
||||
default_service = "org.freedesktop.login1",
|
||||
default_path = "/org/freedesktop/login1",
|
||||
gen_blocking = false
|
||||
)]
|
||||
trait Login {
|
||||
fn inhibit(&self, what: &str, who: &str, why: &str, mode: &str) -> zbus::Result<OwnedFd>;
|
||||
|
||||
#[zbus(signal)]
|
||||
fn prepare_for_sleep(&self, start: bool) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Sleep {
|
||||
/// The computer sleeps as soon as this is dropped, or logind loses patience.
|
||||
Going(oneshot::Sender<()>),
|
||||
Awake,
|
||||
}
|
||||
|
||||
/// Tells of sleep until dropped. Ends at once where there is no logind.
|
||||
pub(crate) async fn watch(bus: Bus, tell: impl Fn(Sleep) + Send) {
|
||||
if let Err(e) = follow(bus, tell).await {
|
||||
log::info!("sleep is not seen: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn follow(bus: Bus, tell: impl Fn(Sleep) + Send) -> zbus::Result<()> {
|
||||
let Some(connection) = bus.connect().await? else { return Ok(()) };
|
||||
let login = LoginProxy::new(&connection).await?;
|
||||
let mut signals = login.receive_prepare_for_sleep().await?;
|
||||
// Without it downloads are cut instead of ended, which loses nothing either.
|
||||
let hold = || async { login.inhibit("sleep", "Medlar", "Downloads are saved", "delay").await.ok() };
|
||||
let mut held = hold().await;
|
||||
while let Some(signal) = signals.next().await {
|
||||
if signal.args()?.start {
|
||||
let (going, gone) = oneshot::channel();
|
||||
tell(Sleep::Going(going));
|
||||
let _ = gone.await;
|
||||
drop(held.take());
|
||||
} else {
|
||||
tell(Sleep::Awake);
|
||||
held = hold().await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -21,6 +21,10 @@ pub struct Settings {
|
|||
pub medium: Limits,
|
||||
pub high: Limits,
|
||||
pub snail: Limits,
|
||||
/// Failures in a row before a download fails, 0 for never.
|
||||
pub tries: u32,
|
||||
/// Go on at the next start with what ran when Medlar ended.
|
||||
pub auto_resume: bool,
|
||||
pub connector: bool,
|
||||
pub connector_port: u16,
|
||||
/// Add links from the browser without showing the Add dialog.
|
||||
|
|
@ -116,6 +120,8 @@ impl Default for Settings {
|
|||
medium: Limits::new(1024 * 1024, 3, 24, 8, 8),
|
||||
high: Limits::default(),
|
||||
snail: Limits::new(32 * 1024, 1, 1, 1, 1),
|
||||
tries: 10,
|
||||
auto_resume: true,
|
||||
connector: true,
|
||||
connector_port: 17616,
|
||||
add_without_asking: false,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,10 @@ pub struct TaskView {
|
|||
pub resumable: Option<bool>,
|
||||
/// Share of the file that was compared with its checksum, 0 to 1.
|
||||
pub checked: f32,
|
||||
/// When it is tried again by itself, if it waits for that.
|
||||
pub retry_at: Option<Time>,
|
||||
/// Failures in a row without a new byte.
|
||||
pub fails: u32,
|
||||
/// Name and port of the host in its link.
|
||||
pub server: Arc<str>,
|
||||
pub history: Arc<History>,
|
||||
|
|
@ -182,6 +186,8 @@ mod tests {
|
|||
wanted: 0,
|
||||
resumable: None,
|
||||
checked: 0.0,
|
||||
retry_at: None,
|
||||
fails: 0,
|
||||
server: "".into(),
|
||||
history: Arc::default(),
|
||||
log: Arc::default(),
|
||||
|
|
|
|||
1
crates/core/src/store/002.sql
Normal file
1
crates/core/src/store/002.sql
Normal file
|
|
@ -0,0 +1 @@
|
|||
ALTER TABLE tasks ADD COLUMN tries INTEGER;
|
||||
|
|
@ -16,7 +16,7 @@ use std::thread::JoinHandle;
|
|||
use std::time::Duration;
|
||||
|
||||
/// Never edit one that shipped; add the next number.
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql")];
|
||||
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql")];
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
|
|||
":downloaded": t.downloaded, ":mime": t.mime, ":etag": t.etag, ":last_modified": t.last_modified,
|
||||
":checksum": t.checksum, ":max_parts": t.max_parts, ":speed_limit": t.speed_limit, ":headers": headers,
|
||||
":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at,
|
||||
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes,
|
||||
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries,
|
||||
};
|
||||
Ok(c.execute(sql, columns)?)
|
||||
}
|
||||
|
|
@ -45,10 +45,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result<TaskId> {
|
|||
c,
|
||||
"INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime,
|
||||
etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at,
|
||||
finished_at, removed_at, notes)
|
||||
finished_at, removed_at, notes, tries)
|
||||
VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime,
|
||||
:etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at,
|
||||
:finished_at, :removed_at, :notes)",
|
||||
:finished_at, :removed_at, :notes, :tries)",
|
||||
t,
|
||||
)?;
|
||||
let id = c.last_insert_rowid();
|
||||
|
|
@ -66,7 +66,8 @@ pub fn update_task(c: &Connection, t: &Task) -> Result<usize> {
|
|||
queue = :queue, position = :position, priority = :priority, size = :size, downloaded = :downloaded, mime = :mime,
|
||||
etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts,
|
||||
speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after,
|
||||
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes
|
||||
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes,
|
||||
tries = :tries
|
||||
WHERE id = {}",
|
||||
t.id
|
||||
);
|
||||
|
|
@ -119,6 +120,7 @@ fn task(r: &Row) -> Result<Task> {
|
|||
last_modified: r.get("last_modified")?,
|
||||
checksum: r.get("checksum")?,
|
||||
max_parts: r.get("max_parts")?,
|
||||
tries: r.get("tries")?,
|
||||
speed_limit: r.get("speed_limit")?,
|
||||
headers: from_json(r.get("headers")?)?,
|
||||
proxy: r.get("proxy")?,
|
||||
|
|
|
|||
Loading…
Reference in a new issue