S021: queue schedules, pause and limits, dependencies, power actions
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
293b91fecb
commit
4407404b85
12 changed files with 591 additions and 21 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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}",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<Event>,
|
||||
answers: Vec<(Answer, Result<TaskId>)>,
|
||||
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<Duration> {
|
||||
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<Duration> {
|
||||
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<QueueId, f64> = match self.store.queues() {
|
||||
let queues: HashMap<QueueId, Queue> = 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<TaskId> = picked.iter().copied().collect();
|
||||
self.choices += 1;
|
||||
for id in self.runs.clone() {
|
||||
|
|
|
|||
|
|
@ -53,6 +53,8 @@ pub enum Error {
|
|||
Partial(String),
|
||||
/// The link could not be checked.
|
||||
Link(Box<Failure>),
|
||||
/// 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<dyn crate::schedule::Clock>,
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Candidate>, max: usize, mut host_cap: impl FnMut(&str) -> u32) -> Vec<TaskId> {
|
||||
pub fn pick(mut candidates: Vec<Candidate>, max: usize, mut host_cap: impl FnMut(&str) -> u32, mut queue_cap: impl FnMut(i64) -> u32) -> Vec<TaskId> {
|
||||
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<Candidate>, 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<i64, u32> = 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<TaskId> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
221
crates/core/src/power.rs
Normal file
221
crates/core/src/power.rs
Normal file
|
|
@ -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<WhenDone>,
|
||||
due: Option<Time>,
|
||||
}
|
||||
|
||||
impl Watcher {
|
||||
pub fn arm(&mut self, when: WhenDone) {
|
||||
self.armed = Some(when);
|
||||
self.due = None;
|
||||
}
|
||||
pub fn cancel(&mut self) {
|
||||
*self = Watcher::default();
|
||||
}
|
||||
pub fn armed(&self) -> Option<&WhenDone> {
|
||||
self.armed.as_ref()
|
||||
}
|
||||
|
||||
pub fn step(&mut self, now: Time, tasks: &[Seen]) -> Step {
|
||||
let Some(when) = &self.armed else { return Step::Idle };
|
||||
let mine: Vec<&Seen> = tasks
|
||||
.iter()
|
||||
.filter(|t| match when.scope {
|
||||
Scope::All => true,
|
||||
Scope::Queue(q) => t.queue == q,
|
||||
Scope::Task(id) => t.id == id,
|
||||
})
|
||||
.filter(|t| t.state != State::Gone)
|
||||
.collect();
|
||||
if !when.even_failed && mine.iter().any(|t| t.state == State::Failed) {
|
||||
self.cancel();
|
||||
return Step::Blocked;
|
||||
}
|
||||
let over = |t: &&Seen| matches!(t.state, State::Done | State::Failed);
|
||||
// Paused ones are the user's: they don't hold it back, but something has to have been downloaded.
|
||||
let idle = |t: &&Seen| over(t) || t.state == State::Paused;
|
||||
let finished = mine.iter().any(|t| t.state == State::Done) && mine.iter().all(idle);
|
||||
if !finished {
|
||||
self.due = None;
|
||||
return Step::Idle;
|
||||
}
|
||||
let due = *self.due.get_or_insert(now + when.countdown.as_millis() as Time);
|
||||
if now >= due {
|
||||
let action = when.action.clone();
|
||||
self.cancel();
|
||||
Step::Fire(action)
|
||||
} else {
|
||||
Step::Counting(((due - now) as u64).div_ceil(1000))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the machine can do, and doing it.
|
||||
pub trait Power: Send + Sync {
|
||||
/// logind answered "yes" or "challenge" for it.
|
||||
fn can(&self, action: &Action) -> bool;
|
||||
fn perform(&self, action: &Action) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// Held while downloading so that the machine doesn't go idle to sleep. Released on drop.
|
||||
pub struct Inhibitor(#[allow(dead_code)] Box<dyn std::any::Any + Send>);
|
||||
|
||||
impl Inhibitor {
|
||||
/// None where there is no logind.
|
||||
pub fn take() -> Option<Inhibitor> {
|
||||
let connection = zbus::blocking::Connection::system().ok()?;
|
||||
let fd = LoginProxy::new(&connection).ok()?.inhibit("sleep:idle", "Medlar", "Downloads are running", "block").ok()?;
|
||||
Some(Inhibitor(Box::new(fd)))
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.login1.Manager",
|
||||
default_service = "org.freedesktop.login1",
|
||||
default_path = "/org/freedesktop/login1",
|
||||
gen_async = false,
|
||||
gen_blocking = true
|
||||
)]
|
||||
trait Login {
|
||||
fn inhibit(&self, what: &str, who: &str, why: &str, mode: &str) -> zbus::Result<zbus::zvariant::OwnedFd>;
|
||||
fn can_power_off(&self) -> zbus::Result<String>;
|
||||
fn can_suspend(&self) -> zbus::Result<String>;
|
||||
fn can_hibernate(&self) -> zbus::Result<String>;
|
||||
fn power_off(&self, interactive: bool) -> zbus::Result<()>;
|
||||
fn suspend(&self, interactive: bool) -> zbus::Result<()>;
|
||||
fn hibernate(&self, interactive: bool) -> zbus::Result<()>;
|
||||
fn lock_sessions(&self) -> zbus::Result<()>;
|
||||
fn terminate_session(&self, id: &str) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
/// The real logind. Tests use a fake `Power`, never this.
|
||||
pub struct Logind;
|
||||
|
||||
impl Logind {
|
||||
fn proxy() -> Result<LoginProxy<'static>, String> {
|
||||
let c = zbus::blocking::Connection::system().map_err(|e| format!("The system bus is not there: {e}"))?;
|
||||
LoginProxy::new(&c).map_err(|e| format!("logind is not there: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn yes(answer: zbus::Result<String>) -> bool {
|
||||
matches!(answer.as_deref(), Ok("yes" | "challenge"))
|
||||
}
|
||||
|
||||
impl Power for Logind {
|
||||
fn can(&self, action: &Action) -> bool {
|
||||
let Ok(p) = Logind::proxy() else { return matches!(action, Action::Quit | Action::Run(_)) };
|
||||
match action {
|
||||
Action::Shutdown => yes(p.can_power_off()),
|
||||
Action::Suspend => yes(p.can_suspend()),
|
||||
Action::Hibernate => yes(p.can_hibernate()),
|
||||
Action::Logout => std::env::var_os("XDG_SESSION_ID").is_some(),
|
||||
Action::Lock | Action::Quit | Action::Run(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn perform(&self, action: &Action) -> Result<(), String> {
|
||||
let p = Logind::proxy()?;
|
||||
let done = match action {
|
||||
Action::Shutdown => p.power_off(false),
|
||||
Action::Suspend => p.suspend(false),
|
||||
Action::Hibernate => p.hibernate(false),
|
||||
Action::Lock => p.lock_sessions(),
|
||||
Action::Logout => match std::env::var("XDG_SESSION_ID") {
|
||||
Ok(id) => p.terminate_session(&id),
|
||||
Err(_) => return Err("The session is not known.".into()),
|
||||
},
|
||||
Action::Quit | Action::Run(_) => return Ok(()),
|
||||
};
|
||||
done.map_err(|e| format!("The computer refused: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn seen(id: TaskId, state: State) -> Seen {
|
||||
Seen { id, queue: 1, state }
|
||||
}
|
||||
fn when(even_failed: bool) -> WhenDone {
|
||||
WhenDone { action: Action::Shutdown, scope: Scope::All, even_failed, countdown: Duration::from_secs(30) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_down_and_fires() {
|
||||
let mut w = Watcher::default();
|
||||
w.arm(when(false));
|
||||
assert_eq!(w.step(0, &[seen(1, State::Running)]), Step::Idle);
|
||||
assert_eq!(w.step(1000, &[seen(1, State::Done)]), Step::Counting(30));
|
||||
assert_eq!(w.step(1000 + 29_500, &[seen(1, State::Done)]), Step::Counting(1));
|
||||
assert_eq!(w.step(1000 + 30_000, &[seen(1, State::Done)]), Step::Fire(Action::Shutdown));
|
||||
assert_eq!(w.step(99_000, &[seen(1, State::Done)]), Step::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_blocks_unless_chosen() {
|
||||
let mut w = Watcher::default();
|
||||
w.arm(when(false));
|
||||
assert_eq!(w.step(0, &[seen(1, State::Done), seen(2, State::Failed)]), Step::Blocked);
|
||||
w.arm(when(true));
|
||||
assert!(matches!(w.step(0, &[seen(1, State::Done), seen(2, State::Failed)]), Step::Counting(_)));
|
||||
}
|
||||
}
|
||||
89
crates/core/src/run.rs
Normal file
89
crates/core/src/run.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
//! Runs a program of the user's: an argument list with placeholders, never a shell.
|
||||
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RunSpec {
|
||||
pub program: String,
|
||||
/// May hold `{file}`, `{name}`, `{folder}`, `{url}`, `{queue}`.
|
||||
pub args: Vec<String>,
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
/// What the placeholders stand for.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Vars {
|
||||
pub file: String,
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
pub url: String,
|
||||
pub queue: String,
|
||||
}
|
||||
|
||||
impl Vars {
|
||||
fn fill(&self, arg: &str) -> String {
|
||||
arg.replace("{file}", &self.file)
|
||||
.replace("{name}", &self.name)
|
||||
.replace("{folder}", &self.folder)
|
||||
.replace("{url}", &self.url)
|
||||
.replace("{queue}", &self.queue)
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments as they will be passed. Each stays one argument, whatever it holds.
|
||||
pub fn expand(spec: &RunSpec, vars: &Vars) -> Vec<String> {
|
||||
spec.args.iter().map(|a| vars.fill(a)).collect()
|
||||
}
|
||||
|
||||
const OUTPUT: usize = 16 * 1024;
|
||||
|
||||
/// Runs it; its output (the first 16 KiB) goes to the log and comes back. Killed when the time is out.
|
||||
pub async fn run(spec: &RunSpec, vars: &Vars) -> Result<String, String> {
|
||||
if spec.program.trim().is_empty() {
|
||||
return Err("No program is set.".into());
|
||||
}
|
||||
let mut child = tokio::process::Command::new(&spec.program)
|
||||
.args(expand(spec, vars))
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.map_err(|e| format!("{} did not start: {e}", spec.program))?;
|
||||
let (out, err) = (child.stdout.take().unwrap(), child.stderr.take().unwrap());
|
||||
let work = async {
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
let (mut out, mut err) = (out.take(OUTPUT as u64), err.take(OUTPUT as u64));
|
||||
let (_, _, status) = tokio::join!(out.read_to_end(&mut a), err.read_to_end(&mut b), child.wait());
|
||||
(status, a, b)
|
||||
};
|
||||
match tokio::time::timeout(spec.timeout, work).await {
|
||||
Err(_) => {
|
||||
let _ = child.start_kill();
|
||||
Err(format!("{} was stopped after {} seconds.", spec.program, spec.timeout.as_secs()))
|
||||
}
|
||||
Ok((status, a, b)) => {
|
||||
let mut text = String::from_utf8_lossy(&a).into_owned();
|
||||
text.push_str(&String::from_utf8_lossy(&b));
|
||||
log::info!("{} said: {}", spec.program, text.trim());
|
||||
match status {
|
||||
Ok(s) if s.success() => Ok(text),
|
||||
Ok(s) => Err(format!("{} ended with {s}.", spec.program)),
|
||||
Err(e) => Err(format!("{} could not be waited for: {e}", spec.program)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn placeholders_stay_single_arguments() {
|
||||
let spec = RunSpec { program: "x".into(), args: vec!["{file}".into(), "-n={name}".into()], timeout: Duration::from_secs(1) };
|
||||
let vars = Vars { file: "/a b/c; rm -rf".into(), name: "c".into(), ..Vars::default() };
|
||||
assert_eq!(expand(&spec, &vars), ["/a b/c; rm -rf", "-n=c"]);
|
||||
}
|
||||
}
|
||||
156
crates/core/src/schedule.rs
Normal file
156
crates/core/src/schedule.rs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
//! When queues may run: weekly windows read on an injectable clock, a speed grid, and dependencies.
|
||||
//!
|
||||
//! Windows are level-triggered: whether a queue may run is a question of the local time now, so a time zone change,
|
||||
//! daylight saving or sleep needs no special case. In the hour that daylight saving skips nothing opens or closes at
|
||||
//! its edges (the window is seen from the next local time that exists); in the hour it repeats the window holds twice.
|
||||
|
||||
use crate::model::{Schedule, TaskId, Time};
|
||||
use chrono::{Datelike, NaiveDateTime, TimeZone, Timelike};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Time, and the local time it is on the wall.
|
||||
pub trait Clock: Send + Sync {
|
||||
/// Milliseconds since 1970, UTC.
|
||||
fn now(&self) -> Time;
|
||||
/// The wall clock at `at`, with the zone's daylight saving of that moment.
|
||||
fn local(&self, at: Time) -> NaiveDateTime;
|
||||
}
|
||||
|
||||
pub struct SystemClock;
|
||||
|
||||
impl Clock for SystemClock {
|
||||
fn now(&self) -> Time {
|
||||
crate::model::now()
|
||||
}
|
||||
fn local(&self, at: Time) -> NaiveDateTime {
|
||||
chrono::Local.timestamp_millis_opt(at).single().map(|t| t.naive_local()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A clock set by hand, for tests. `offset` is seconds east of UTC at a moment, so it can model daylight saving.
|
||||
pub struct ManualClock {
|
||||
now: Mutex<Time>,
|
||||
offset: Box<dyn Fn(Time) -> i32 + Send + Sync>,
|
||||
}
|
||||
|
||||
impl ManualClock {
|
||||
pub fn new(now: Time, offset: impl Fn(Time) -> i32 + Send + Sync + 'static) -> ManualClock {
|
||||
ManualClock { now: Mutex::new(now), offset: Box::new(offset) }
|
||||
}
|
||||
pub fn set(&self, now: Time) {
|
||||
*self.now.lock().unwrap() = now;
|
||||
}
|
||||
pub fn advance(&self, ms: Time) {
|
||||
*self.now.lock().unwrap() += ms;
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for ManualClock {
|
||||
fn now(&self) -> Time {
|
||||
*self.now.lock().unwrap()
|
||||
}
|
||||
fn local(&self, at: Time) -> NaiveDateTime {
|
||||
let shifted = at + (self.offset)(at) as i64 * 1000;
|
||||
chrono::DateTime::from_timestamp_millis(shifted).map(|t| t.naive_utc()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn minute_of(local: NaiveDateTime) -> u16 {
|
||||
(local.hour() * 60 + local.minute()) as u16
|
||||
}
|
||||
|
||||
impl Schedule {
|
||||
/// The queue may run at this wall time. `from == to` is the whole day; `to < from` ends the next day.
|
||||
pub fn contains(&self, local: NaiveDateTime) -> bool {
|
||||
let day = local.weekday().num_days_from_monday() as u8;
|
||||
let on = |d: u8| self.days & (1 << (d % 7)) != 0;
|
||||
let m = minute_of(local);
|
||||
if self.from == self.to {
|
||||
on(day)
|
||||
} else if self.from < self.to {
|
||||
on(day) && (self.from..self.to).contains(&m)
|
||||
} else {
|
||||
(on(day) && m >= self.from) || (on(day + 6) && m < self.to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// No schedule means always.
|
||||
pub fn open(schedule: &[Schedule], local: NaiveDateTime) -> bool {
|
||||
schedule.is_empty() || schedule.iter().any(|s| s.contains(local))
|
||||
}
|
||||
|
||||
/// A window began between `from` and `to` (UTC ms), for the rule "start what was missed while asleep".
|
||||
/// Looks by the minute, at most eight days back.
|
||||
pub fn opened_between(clock: &dyn Clock, schedule: &[Schedule], from: Time, to: Time) -> bool {
|
||||
if schedule.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let from = from.max(to - 8 * 24 * 3_600_000);
|
||||
let mut at = from - from.rem_euclid(60_000);
|
||||
let mut was = open(schedule, clock.local(at));
|
||||
while at < to {
|
||||
at += 60_000;
|
||||
let now = open(schedule, clock.local(at.min(to)));
|
||||
if now && !was {
|
||||
return true;
|
||||
}
|
||||
was = now;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// What the speed is by hour of the week: 168 cells from Monday 00:00, a limit in bytes per second, None for none.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Grid(pub Vec<Option<u64>>);
|
||||
|
||||
impl Grid {
|
||||
pub fn new(cells: Vec<Option<u64>>) -> Option<Grid> {
|
||||
(cells.len() == 168).then_some(Grid(cells))
|
||||
}
|
||||
pub fn at(&self, local: NaiveDateTime) -> Option<u64> {
|
||||
let cell = local.weekday().num_days_from_monday() as usize * 24 + local.hour() as usize;
|
||||
self.0.get(cell).copied().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
/// Setting `after` of `id` to `new` would make a loop (a task after itself, directly or through others).
|
||||
pub fn cycle(after: impl Fn(TaskId) -> Option<TaskId>, id: TaskId, new: Option<TaskId>) -> bool {
|
||||
let mut seen = HashSet::from([id]);
|
||||
let mut next = new;
|
||||
while let Some(t) = next {
|
||||
if !seen.insert(t) {
|
||||
return true;
|
||||
}
|
||||
next = after(t);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(d: u32, h: u32, m: u32) -> NaiveDateTime {
|
||||
// 2026-11-23 is a Monday.
|
||||
chrono::NaiveDate::from_ymd_opt(2026, 11, 23 + d).unwrap().and_hms_opt(h, m, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn night_window_crosses_midnight() {
|
||||
let s = Schedule { days: 0b1, from: 22 * 60, to: 6 * 60 };
|
||||
assert!(s.contains(at(0, 23, 0)));
|
||||
assert!(s.contains(at(1, 5, 59)), "Tuesday morning belongs to Monday's window");
|
||||
assert!(!s.contains(at(1, 6, 0)));
|
||||
assert!(!s.contains(at(0, 5, 0)), "Monday morning belongs to Sunday's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycles() {
|
||||
let map = |t| match t { 2 => Some(1), 3 => Some(2), _ => None };
|
||||
assert!(cycle(map, 1, Some(3)));
|
||||
assert!(cycle(map, 1, Some(1)));
|
||||
assert!(!cycle(map, 4, Some(3)));
|
||||
}
|
||||
}
|
||||
|
|
@ -199,3 +199,8 @@ Verified: `nice cargo test -j 2 -p medlar --test add` green (14, four with the r
|
|||
Not done: the desktop's file chooser (portal) was never tried, only that it fails plainly is in the code; links of a batch are not asked about; what is known is found when the fields change, not when the list does; a start time is kept but queue schedules are S021's, and time asleep doesn't count; a metalink file is refused as a list (`read_metalink` is not wired, 3.3); files already on disk but not in the list are not noticed (the engine numbers names); no hidden release run.
|
||||
Later: `App` doesn't set `ClientOptions::known_hosts` yet (S011).
|
||||
Seen: boxes were ticked together after the tests, against rule 3.
|
||||
|
||||
## S021 — Queues, schedule, power (compiled, not tested)
|
||||
- `schedule::{Clock, SystemClock, ManualClock, open, opened_between, Grid, cycle}`; set `Config.clock`. The manager's `choose` now reads queue `paused`, `max_active`, `schedule` and task `after` (a forced start overrides them); `Edit` of `after` refuses loops (`Error::Cycle`).
|
||||
- `power::{Watcher, WhenDone, Action, Scope, Power, Logind, Inhibitor}` (countdown, conditions, failure blocks unless `even_failed`); `run::{RunSpec, Vars, run}`.
|
||||
- Not done: no UI or app wiring for these, the `Grid` is not applied to the limiter, `start_at` stays on `Hold::Until` (asleep time not counted). Tests: `docs/tests/S021-queues-schedule-power.md`.
|
||||
|
|
|
|||
45
docs/tests/S021-queues-schedule-power.md
Normal file
45
docs/tests/S021-queues-schedule-power.md
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# S021 — Queues, schedule, power: test file
|
||||
|
||||
Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so.
|
||||
|
||||
## Built
|
||||
`crates/core/src/schedule.rs` · `Clock`, `SystemClock`, `ManualClock`, `Schedule::contains`, `open`, `opened_between`, `Grid`, `cycle`.
|
||||
`crates/core/src/power.rs` · `Action`, `Scope`, `WhenDone`, `Watcher::{arm,cancel,step}` (countdown, conditions), `Power` trait, `Logind`, `Inhibitor`.
|
||||
`crates/core/src/run.rs` · `RunSpec`, `Vars`, `expand`, `run` (no shell, timeout, output to log).
|
||||
`crates/core/src/manager/{actor,pick}.rs` · `choose` reads queue `paused`, `max_active`, `schedule` and task `after`; `Config.clock`; `Error::Cycle` on `Edit`.
|
||||
|
||||
## Checks
|
||||
Risk: HIGH = data loss, security, crash, wrong result · MED = feature broken · LOW = looks or comfort.
|
||||
|
||||
| # | Risk | Do this | Expect | How | Result |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | HIGH | Queue with `paused`, add a task to it | task stays Queued, nothing downloads; unpause starts it | integration (testserver, `Config.clock` default) | — |
|
||||
| 2 | HIGH | Queue `max_active = 1`, three tasks, global max 4 | only one runs at a time, the others follow in order | integration | — |
|
||||
| 3 | HIGH | Queue schedule Mon 22:00-06:00 on a ManualClock at Mon 21:59, then advance 2 minutes | task starts within one look (~15 s real, or send a command to force choose) | integration | — |
|
||||
| 4 | HIGH | Running task, clock leaves the window | task goes back to Queued, not Failed; returns when the window opens | integration | — |
|
||||
| 5 | HIGH | Start by hand (`forced`) in a paused or closed queue | it runs | integration | — |
|
||||
| 6 | HIGH | Task B `after` A; A Running | B stays Queued; when A is Done, B starts | integration | — |
|
||||
| 7 | HIGH | `after` pointing at itself, at a chain that returns, at a removed task | first two give `Error::Cycle` and nothing is saved; the last is accepted and B isn't held | integration | — |
|
||||
| 8 | HIGH | `Watcher` with `even_failed = false`, one Done and one Failed | `Step::Blocked`, disarmed, never fires | unit | — |
|
||||
| 9 | HIGH | Same with `even_failed = true` | countdown starts, fires after the countdown | unit | — |
|
||||
| 10 | MED | Cancel during the countdown; a task of the scope starts again | `Idle` after cancel; a new running task resets the countdown | unit | — |
|
||||
| 11 | MED | Scope Queue(2) while queue 1 still runs | fires when queue 2 is done | unit | — |
|
||||
| 12 | HIGH | `ManualClock` zone with +1 h at the 2026-03-29 01:00 UTC step (Europe), window 02:00-03:00 | `contains` follows local time: closed before, open after; no panic in the skipped hour | unit | — |
|
||||
| 13 | MED | Zone change (offset +0 to +9 h) while window 22:00-06:00 | open/closed follows the new wall time at once | unit | — |
|
||||
| 14 | MED | `opened_between` over a 10-hour sleep that spans a window start, and one that spans none or only an end | true for the first; false for the others; scan capped at 8 days | unit | — |
|
||||
| 15 | MED | Night window Mon 22:00-06:00 | Tuesday 05:59 open, 06:00 closed, Monday 05:00 closed; `from == to` is the whole day | unit | — |
|
||||
| 16 | MED | `Grid::new` with 167 and 168 cells; `at` on Monday 00:30 and Sunday 23:30 | None for 167; first and last cell | unit | — |
|
||||
| 17 | HIGH | `expand` with `{file}` = `/a b/c; rm -rf /` | one argument, unchanged; no shell run | unit | — |
|
||||
| 18 | MED | `run` with `sleep 5`, timeout 1 s; with `echo hi`; with a missing program; with exit code 1 | timeout error naming seconds; Ok("hi\n"); "did not start"; "ended with" error | integration | — |
|
||||
| 19 | HIGH | Fake `Power` that records calls: drive a `Fire(Shutdown)` through the caller | only the fake is called; `Logind` is never used in tests | unit | — |
|
||||
| 20 | LOW | `Logind::can` on this PC (capabilities only, no perform) | Shutdown/Suspend answer without calling the methods; Quit and Run always true | by hand | — |
|
||||
|
||||
## Needs
|
||||
`crates/testserver` on 127.0.0.1; a throwaway home; a `ManualClock` in `Config.clock`. Never call `Logind::perform` or `Inhibitor::take` for real in tests except by hand on check 20 (capabilities only).
|
||||
|
||||
## Doubts
|
||||
- Not wired yet: the app's UI for queues, schedules and when-done; nothing calls `Watcher`, `Logind`, `Inhibitor` or `run::run` outside tests; the speed `Grid` is not applied to the limiter; no model fields for once-only schedules (a task's `start_at` is the once rule and is still `Hold::Until`, untouched).
|
||||
- `schedule` is read when `choose` runs; a clock jump is seen at most 15 s later (`SCHEDULE_LOOK`), and `Hold::Until` still uses `Instant`, so time asleep does not count for a start time.
|
||||
- A closed or paused queue pushes running tasks back to Queued; a task running in a queue that gets paused is suspended, not paused.
|
||||
- `pick` and `Candidate` got a field and a parameter; the unit tests in pick.rs were edited to match, not run.
|
||||
- Fall-back hour: the window counts twice (documented); not covered by a check.
|
||||
Loading…
Reference in a new issue