From 4407404b85fd809c910aa1adc539ee2fa5be5f63 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 21:23:13 -0600 Subject: [PATCH 01/63] S021: queue schedules, pause and limits, dependencies, power actions Co-Authored-By: Claude Sonnet 5.5 --- .../04 Control/S021-queues-schedule-power.md | 16 +- Plans/INDEX.md | 2 +- crates/core/lang/en.json | 1 + crates/core/src/lib.rs | 3 + crates/core/src/manager/actor.rs | 50 +++- crates/core/src/manager/mod.rs | 6 + crates/core/src/manager/pick.rs | 18 +- crates/core/src/power.rs | 221 ++++++++++++++++++ crates/core/src/run.rs | 89 +++++++ crates/core/src/schedule.rs | 156 +++++++++++++ docs/PROGRESS.md | 5 + docs/tests/S021-queues-schedule-power.md | 45 ++++ 12 files changed, 591 insertions(+), 21 deletions(-) create mode 100644 crates/core/src/power.rs create mode 100644 crates/core/src/run.rs create mode 100644 crates/core/src/schedule.rs create mode 100644 docs/tests/S021-queues-schedule-power.md diff --git a/Plans/04 Control/S021-queues-schedule-power.md b/Plans/04 Control/S021-queues-schedule-power.md index 24a7dd7..3ed304d 100644 --- a/Plans/04 Control/S021-queues-schedule-power.md +++ b/Plans/04 Control/S021-queues-schedule-power.md @@ -11,14 +11,14 @@ FEATURES 2.6–2.9. - docs/FEATURES.md §2 ## Steps -- [ ] Queues: folder, limit, active count, order, schedule, done action; move tasks between them -- [ ] Schedules: times, weekdays, once, mode by time grid; time zone, daylight saving and missed-while-asleep rules; the clock is injectable -- [ ] Dependencies and delayed start; cycles refused -- [ ] When done: shut down, suspend, hibernate, log out, lock, quit, run command, with a cancellable countdown; conditions (all, queue, task) -- [ ] logind through zbus, inhibit suspend while downloading; capabilities checked first -- [ ] Run program: argument list with placeholders, no shell, timeout, output in the log -- [ ] Test file `docs/tests/S021-queues-schedule-power.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S021: …`, push +- [x] Queues: folder, limit, active count, order, schedule, done action; move tasks between them +- [x] Schedules: times, weekdays, once, mode by time grid; time zone, daylight saving and missed-while-asleep rules; the clock is injectable +- [x] Dependencies and delayed start; cycles refused +- [x] When done: shut down, suspend, hibernate, log out, lock, quit, run command, with a cancellable countdown; conditions (all, queue, task) +- [x] logind through zbus, inhibit suspend while downloading; capabilities checked first +- [x] Run program: argument list with placeholders, no shell, timeout, output in the log +- [x] Test file `docs/tests/S021-queues-schedule-power.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S021: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 84571b5..5d9dc4a 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -34,7 +34,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 04 Control - [x] [S019](04%20Control/S019-limiter-priority.md) Limiter, modes and priority shares -- [ ] [S021](04%20Control/S021-queues-schedule-power.md) Queues, scheduler and power actions +- [x] [S021](04%20Control/S021-queues-schedule-power.md) Queues, scheduler and power actions - [ ] [S022](04%20Control/S022-control-screens.md) Control screens ## 05 Connector diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 3a359ce..24d017f 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -262,6 +262,7 @@ "manager.folder": "The folder has to be a full path, such as /home/you/Downloads.", "manager.file": "The file could not be moved or changed: {why}", "manager.bin": "The file could not be moved to the bin: {why}", + "manager.cycle": "A download cannot wait for itself, not even through others.", "manager.closed": "Medlar is closing and takes no more commands.", "log.added": "Added {url}", diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 4773ec6..fffa6b7 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,10 +24,13 @@ pub mod net_state; pub mod part; pub mod paths; pub mod portal; +pub mod power; pub mod proxy; pub mod recover; pub mod redact; pub mod relink; +pub mod run; +pub mod schedule; pub mod secret; pub mod segment; pub mod settings; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index ddedfa7..645a5cd 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -23,7 +23,7 @@ use crate::speed::{History, Meter}; use crate::store::{self, Store}; use crate::stream::{self, Tools}; use crate::verify::Checksum; -use crate::{adopt, disk, host, metalink, redact, site, strings, tr, verify}; +use crate::{schedule, adopt, disk, host, metalink, redact, site, strings, tr, verify}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::path::{Path, PathBuf}; @@ -78,6 +78,9 @@ struct Run { again: bool, } +/// How often the clock is looked at while a queue has hours. +const SCHEDULE_LOOK: Duration = Duration::from_secs(15); + /// What a waiting download waits for. #[derive(Debug, Clone, Copy, PartialEq)] enum Hold { @@ -259,6 +262,10 @@ pub struct Actor { happened: Vec, answers: Vec<(Answer, Result)>, last_position: f64, + /// Some queue has hours. + scheduled: bool, + /// The minute of the clock at the last look. + minute: Time, forces: u64, choices: u64, meter: Meter, @@ -297,6 +304,8 @@ impl Actor { happened: vec![], answers: vec![], last_position: 0.0, + scheduled: false, + minute: 0, forces: 0, choices: 0, meter: Meter::default(), @@ -372,12 +381,22 @@ impl Actor { } self.forget(now); self.wake(now); + let minute = self.config.clock.now() / 60_000; + if std::mem::replace(&mut self.minute, minute) != minute && self.scheduled { + self.choose = true; + } } self.close(inbox); } /// How long there is nothing to do but wait for messages. fn pause(&self) -> Option { + let wait = self.pause_for_work(); + // Hours begin and end by the clock, which sends no message. + if self.scheduled { Some(wait.unwrap_or(SCHEDULE_LOOK).min(SCHEDULE_LOOK)) } else { wait } + } + + fn pause_for_work(&self) -> Option { if !self.runs.is_empty() || self.second > 0 || self.totals.speed > 0.0 { return Some(self.config.tick.saturating_sub(self.sampled.elapsed())); } @@ -884,6 +903,9 @@ impl Actor { fn change(&mut self, id: TaskId, edit: impl FnOnce(&mut Task)) -> Result<()> { let mut new = (*self.entries[&id].task).clone(); edit(&mut new); + if schedule::cycle(|t| self.entries.get(&t).and_then(|e| e.task.after), id, new.after) { + return Err(Error::Cycle); + } let old = self.entries[&id].task.secret.clone(); let saved = self.store.edit_task(id, move |t| { t.url = new.url; @@ -994,23 +1016,35 @@ impl Actor { } fn choose(&mut self) { - let queues: HashMap = match self.store.queues() { + let queues: HashMap = match self.store.queues() { Ok(queues) => { for q in &queues { self.config.limiter.set(&Group::Queue(q.id), q.speed_limit); } - queues.into_iter().map(|q| (q.id, q.position)).collect() + queues.into_iter().map(|q| (q.id, q)).collect() } Err(e) => { log::error!("queues not read: {e}"); HashMap::new() } }; + self.scheduled = queues.values().any(|q| !q.schedule.is_empty()); + let local = self.config.clock.local(self.config.clock.now()); + // A queue that is paused or out of its hours lets nothing begin and takes running ones' place; a start by hand + // (`forced`) is the user's word against both. + let runs = |q: QueueId| queues.get(&q).is_none_or(|q| !q.paused && schedule::open(&q.schedule, local)); let now = Instant::now(); let eligible = |e: &Entry| match e.task.state { - State::Running => true, + State::Running => e.forced > 0 || runs(e.task.queue), // One that is busy keeps its place until it can begin. - State::Queued => !e.removed() && !self.asleep && (e.forced > 0 || !matches!(self.breakers.gate(&e.host, now), Gate::Shut(_))), + State::Queued => { + // After another: it waits until that is done, or gone from the list. + let behind = e.task.after.and_then(|a| self.entries.get(&a)).is_some_and(|a| a.task.state != State::Done && !a.removed()); + !e.removed() + && !self.asleep + && (e.forced > 0 || (runs(e.task.queue) && !behind)) + && (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 { @@ -1021,8 +1055,10 @@ impl Actor { running: e.task.state == State::Running, interrupted: e.interrupted, pinned: e.resumable == Some(false) && e.downloaded > 0, - order: (queues.get(&e.task.queue).copied().unwrap_or_default(), e.task.position), + order: (queues.get(&e.task.queue).map(|q| q.position).unwrap_or_default(), e.task.position), + queue: e.task.queue, }); + let queue_cap = |q: QueueId| queues.get(&q).and_then(|q| q.max_active).map_or(u32::MAX, |n| n.max(1)); let per_host = unlimited(self.config.limits.connections_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); @@ -1034,7 +1070,7 @@ impl Actor { }; // One without any connection would wait for nothing. let max = unlimited(self.config.limits.max_active).min(unlimited(self.config.limits.max_connections)); - let picked = pick(candidates.collect(), max as usize, host_cap); + let picked = pick(candidates.collect(), max as usize, host_cap, queue_cap); let chosen: BTreeSet = picked.iter().copied().collect(); self.choices += 1; for id in self.runs.clone() { diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index 051de6e..553cb91 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -53,6 +53,8 @@ pub enum Error { Partial(String), /// The link could not be checked. Link(Box), + /// The download would wait for itself. + Cycle, /// Medlar is closing. Closed, } @@ -76,6 +78,7 @@ impl fmt::Display for Error { Error::Different => tr!("manager.different"), Error::Partial(why) => tr!("manager.partial", why = why), Error::Link(failure) => failure.text.clone(), + Error::Cycle => tr!("manager.cycle"), Error::Closed => tr!("manager.closed"), }) } @@ -201,6 +204,8 @@ pub struct Config { pub undo: Duration, /// How often the snapshot follows running downloads. pub tick: Duration, + /// Time for queue schedules; tests set their own. + pub clock: Arc, } impl Config { @@ -215,6 +220,7 @@ impl Config { recovery: Recovery::default(), undo: Duration::from_secs(60), tick: Duration::from_millis(100), + clock: Arc::new(crate::schedule::SystemClock), } } } diff --git a/crates/core/src/manager/pick.rs b/crates/core/src/manager/pick.rs index aca0495..ad93c7e 100644 --- a/crates/core/src/manager/pick.rs +++ b/crates/core/src/manager/pick.rs @@ -19,11 +19,13 @@ pub struct Candidate<'a> { pub pinned: bool, /// Place of its queue, and its place there. pub order: (f64, f64), + /// Its queue, which may allow only so many. + pub queue: i64, } /// At most `max` of them, and no more of one host than it takes connections. Running ones give way to a higher priority or /// a forced start, never to a better place, and pinned ones never. Those that gave way go on before others. -pub fn pick(mut candidates: Vec, max: usize, mut host_cap: impl FnMut(&str) -> u32) -> Vec { +pub fn pick(mut candidates: Vec, max: usize, mut host_cap: impl FnMut(&str) -> u32, mut queue_cap: impl FnMut(i64) -> u32) -> Vec { let pinned = |c: &Candidate| c.running && c.pinned; if candidates.iter().any(|c| c.priority == Priority::Only) { candidates.retain(|c| c.priority == Priority::Only || pinned(c)); @@ -34,14 +36,20 @@ pub fn pick(mut candidates: Vec, max: usize, mut host_cap: impl FnMut rank(a).cmp(&rank(b)).then_with(|| order(a, b)).then(a.id.cmp(&b.id)) }); let mut room: HashMap<&str, u32> = HashMap::new(); + let mut in_queue: HashMap = HashMap::new(); let mut picked = vec![]; for c in &candidates { if picked.len() >= max { break; } + let left = in_queue.entry(c.queue).or_insert_with(|| queue_cap(c.queue)); + if *left == 0 { + continue; + } let room = room.entry(c.host).or_insert_with(|| host_cap(c.host).max(1)); if *room > 0 { *room -= 1; + *left -= 1; picked.push(c.id); } } @@ -53,11 +61,11 @@ mod tests { use super::*; fn c(id: TaskId) -> Candidate<'static> { - Candidate { id, host: "h", priority: Priority::Normal, forced: 0, running: false, interrupted: 0, pinned: false, order: (0.0, id as f64) } + Candidate { id, host: "h", priority: Priority::Normal, forced: 0, running: false, interrupted: 0, pinned: false, order: (0.0, id as f64), queue: 1 } } fn picked(candidates: &[Candidate], max: usize) -> Vec { - pick(candidates.to_vec(), max, |_| 9) + pick(candidates.to_vec(), max, |_| 9, |_| u32::MAX) } #[test] @@ -99,7 +107,7 @@ mod tests { fn a_host_gets_no_more_than_its_connections() { let mut all = vec![c(1), c(2), c(3), c(4)]; all[3].host = "other"; - assert_eq!(pick(all.clone(), 3, |h| if h == "h" { 2 } else { 1 }), [1, 2, 4]); - assert_eq!(pick(all, 3, |_| 0), [1, 4], "a host always takes one"); + assert_eq!(pick(all.clone(), 3, |h| if h == "h" { 2 } else { 1 }, |_| u32::MAX), [1, 2, 4]); + assert_eq!(pick(all, 3, |_| 0, |_| u32::MAX), [1, 4], "a host always takes one"); } } diff --git a/crates/core/src/power.rs b/crates/core/src/power.rs new file mode 100644 index 0000000..c0a748c --- /dev/null +++ b/crates/core/src/power.rs @@ -0,0 +1,221 @@ +//! What happens when downloads are done: the action, its condition, a countdown that can be cancelled, and logind. + +use crate::model::{QueueId, State, TaskId, Time}; +use crate::run::RunSpec; +use std::time::Duration; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + Shutdown, + Suspend, + Hibernate, + Logout, + Lock, + /// Medlar closes; the app does it. + Quit, + /// The app runs it (`run::run`). + Run(RunSpec), +} + +/// Which downloads have to be done. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope { + All, + Queue(QueueId), + Task(TaskId), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WhenDone { + pub action: Action, + pub scope: Scope, + /// Without it one failed download of the scope stops the action for good: nothing is shut down for a failure. + pub even_failed: bool, + pub countdown: Duration, +} + +/// A task as the watcher needs it. Removed ones are left out by the caller. +#[derive(Debug, Clone, Copy)] +pub struct Seen { + pub id: TaskId, + pub queue: QueueId, + pub state: State, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Step { + /// Nothing is armed, or the downloads go on. + Idle, + /// Seconds left; the user can cancel. + Counting(u64), + /// Do it now. + Fire(Action), + /// A download failed and the action was not for that: disarmed. + Blocked, +} + +/// One armed action. Call `step` whenever tasks change and about each second while counting. +#[derive(Debug, Default)] +pub struct Watcher { + armed: Option, + due: Option