diff --git a/Cargo.lock b/Cargo.lock index b82014e..68b7099 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,6 +202,15 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -2209,8 +2218,10 @@ dependencies = [ name = "medlar-core" version = "0.1.0" dependencies = [ + "arc-swap", "chrono", "dirs", + "fastrand", "log", "medlar-testserver", "percent-encoding", diff --git a/Plans/02 Engine/S006-manager.md b/Plans/02 Engine/S006-manager.md index be97ef5..edd738a 100644 --- a/Plans/02 Engine/S006-manager.md +++ b/Plans/02 Engine/S006-manager.md @@ -11,14 +11,14 @@ Many downloads with a lifecycle, and the one API that UI, CLI and connector use. - docs/DECISIONS.md ## Steps -- [ ] Commands: add, start, pause, resume, stop, remove (keep or bin files), redownload, move, rename; all idempotent and safe in any state -- [ ] Running set chosen by active limit, priority and order; per-host caps respected -- [ ] Snapshot for the UI: cheap, lock-free to read, only changed tasks copied; 10,000 tasks test -- [ ] Speed and time-left smoothing that doesn't jump; per-second history ring per task and total -- [ ] Per-task log with redaction; counters for statistics -- [ ] Start-up restore and clean shutdown: pause everything in under 2 s -- [ ] Dev binary or test example that downloads from the test server with text progress -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S006: …`, push +- [x] Commands: add, start, pause, resume, stop, remove (keep or bin files), redownload, move, rename; all idempotent and safe in any state +- [x] Running set chosen by active limit, priority and order; per-host caps respected +- [x] Snapshot for the UI: cheap, lock-free to read, only changed tasks copied; 10,000 tasks test +- [x] Speed and time-left smoothing that doesn't jump; per-second history ring per task and total +- [x] Per-task log with redaction; counters for statistics +- [x] Start-up restore and clean shutdown: pause everything in under 2 s +- [x] Dev binary or test example that downloads from the test server with text progress +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S006: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test manager` green, with a concurrent command fuzz of 10,000 random operations and no deadlock or illegal state diff --git a/Plans/INDEX.md b/Plans/INDEX.md index b58296e..e0ce406 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -14,7 +14,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S004](02%20Engine/S004-http-core.md) HTTP core with resume and crash-safe files - [x] [S005](02%20Engine/S005-dynamic-parts.md) Dynamic parts and adaptive connections -- [ ] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots +- [x] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots - [ ] [S007](02%20Engine/S007-error-recovery.md) Error recovery - [ ] [S008](02%20Engine/S008-continue-links.md) Continue from a new link - [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 94ad20a..cf3d3f8 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true description = "Medlar's engine, store and settings" [dependencies] +arc-swap = "1.9.5" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" log = { workspace = true, features = ["std"] } @@ -14,7 +15,7 @@ regex = { version = "1", default-features = false, features = ["std", "unicode-c # Pinned: D-017. reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider"] } rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] } -rustix = { version = "1.1.6", features = ["fs"] } +rustix = { version = "1.1.6", features = ["fs", "process"] } rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } serde.workspace = true serde_json.workspace = true @@ -22,6 +23,7 @@ tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", " url = "2" [dev-dependencies] +fastrand = "2.5.0" medlar-testserver.workspace = true sha2 = "0.11.1" tempfile = "3" diff --git a/crates/core/examples/manager.rs b/crates/core/examples/manager.rs new file mode 100644 index 0000000..02bc158 --- /dev/null +++ b/crates/core/examples/manager.rs @@ -0,0 +1,43 @@ +//! Downloads from the test server with progress as text: `cargo run -p medlar-core --example manager`. + +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::{ClientOptions, Options, Shared, client}; +use medlar_core::manager::{Command, Config, Manager}; +use medlar_core::model::{State, Task}; +use medlar_core::segment::Rules; +use medlar_core::settings::Limits; +use medlar_core::store::Store; +use medlar_testserver::{Faults, TestServer}; +use std::sync::Arc; +use std::time::Duration; + +#[tokio::main] +async fn main() { + let dir = tempfile::tempdir().unwrap(); + let server = TestServer::start().await; + let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap()); + let client = client(&ClientOptions::default()).unwrap(); + let shared = Shared { client, store, hosts: Hosts::new(Caps::default()) }; + let mut config = Config::new(shared, Limits { max_active: 2, ..Limits::default() }); + config.options = Options { rules: Rules { min: 256 * 1024, ..Options::default().rules }, ..Options::default() }; + let manager = Manager::open(config).unwrap(); + for seed in 1..=4 { + let path = TestServer::data_path(seed, seed * 2_000_000); + server.set_faults(&path, Faults { throttle_conn: Some(400_000), ..Faults::default() }); + let task = Task { url: server.url(&path), folder: dir.path().into(), ..Task::default() }; + manager.send(Command::Add(Box::new(task))).await.unwrap(); + } + loop { + let shot = manager.snapshot(); + println!("— {:.0} kB/s, {} connections", shot.totals.speed / 1000.0, shot.totals.connections); + for v in shot.iter() { + let filled = (v.progress().unwrap_or_default() * 30.0) as usize; + let left = v.left.map(|l| format!("{} s left", l.as_secs())).unwrap_or_default(); + println!("{} {:<30} {:<12} {:>5.0} kB/s {left}", v.id(), "#".repeat(filled), v.state().name(), v.speed / 1000.0); + } + if shot.iter().all(|v| matches!(v.state(), State::Done | State::Failed)) { + break; + } + tokio::time::sleep(Duration::from_millis(500)).await; + } +} diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 37e5b93..d1c8e64 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -55,6 +55,20 @@ "store.bad_value": "The download list holds a value this version doesn't know: {value}", "store.closed": "The download list stopped working. Start Medlar again.", + "manager.name": "That is not a name a file can have.", + "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.closed": "Medlar is closing and takes no more commands.", + + "log.added": "Added {url}", + "log.connect": "Connecting to {server}", + "log.file": {"one": "File {name}, {n} byte", "other": "File {name}, {n} bytes"}, + "log.file_unknown": "File {name}, of unknown size", + "log.failed": "Failed: {why}", + "log.moved": "Moved to {folder}", + "log.renamed": "Renamed to {name}", + "dialog.cancel": "Cancel", "dialog.close": "Close", "toast.undo": "Undo", diff --git a/crates/core/src/disk.rs b/crates/core/src/disk.rs index 997a96c..8f7449c 100644 --- a/crates/core/src/disk.rs +++ b/crates/core/src/disk.rs @@ -5,11 +5,12 @@ use crate::http::name; use rustix::fs::{CWD, FallocateFlags, RenameFlags, fallocate, fstatvfs, renameat_with}; use rustix::io::Errno; +use std::collections::HashSet; use std::fs::{File, OpenOptions, TryLockError}; use std::io; use std::os::unix::fs::{FileExt, MetadataExt}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, MutexGuard}; pub const ENDING: &str = ".medlar"; @@ -36,6 +37,12 @@ impl From for Error { pub type Result = std::result::Result; +/// Held by whoever looks for a free name, until the file is there: two downloads must not settle on the same one. +pub(crate) fn names() -> MutexGuard<'static, ()> { + static NAMES: Mutex<()> = Mutex::new(()); + NAMES.lock().unwrap_or_else(|e| e.into_inner()) +} + /// Locked against a second Medlar while it is open. #[derive(Debug)] pub struct PartialFile { @@ -44,11 +51,13 @@ pub struct PartialFile { } impl PartialFile { - /// Starts a file in `folder`, under `name` or a numbered variant of it that is free. Returns the name it took. - pub fn create(folder: &Path, name: &str) -> Result<(PartialFile, String)> { + /// Starts a file in `folder`, under `name` or a numbered variant of it that is free and not in `used`. Returns the name it + /// took. `used` are the names of other downloads there, whose files may be empty or missing for now. + /// Hold `names` until the name is recorded. + pub fn create(folder: &Path, name: &str, used: &HashSet) -> Result<(PartialFile, String)> { std::fs::create_dir_all(folder)?; for name in variants(name) { - if exists(&folder.join(&name))? { + if used.contains(&name) || exists(&folder.join(&name))? { continue; } let path = partial_path(folder, &name); @@ -70,7 +79,11 @@ impl PartialFile { /// The file of a download that was started before. None when it is gone. pub fn reopen(folder: &Path, name: &str) -> Result> { - let path = partial_path(folder, name); + PartialFile::hold(partial_path(folder, name)) + } + + /// The same for a partial file anywhere. + pub(crate) fn hold(path: PathBuf) -> Result> { let file = match open(&path) { Ok(file) => file, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), @@ -152,6 +165,7 @@ impl PartialFile { self.file.set_len(size).map_err(io)?; self.file.sync_all().map_err(io)?; let folder = self.path.parent().unwrap_or(Path::new("/")).to_path_buf(); + let _names = names(); for variant in variants(name) { let to = folder.join(&variant); let from = partial_path(&folder, &variant); @@ -198,7 +212,7 @@ pub(crate) async fn blocking( } /// `a.zip`, `a (1).zip`, `a (2).zip` … -fn variants(name: &str) -> impl Iterator { +pub(crate) fn variants(name: &str) -> impl Iterator { let (stem, ext) = name::split(name); // Keep `.tar.gz` together. let (stem, ext) = match stem.strip_suffix(".tar") { @@ -210,7 +224,7 @@ fn variants(name: &str) -> impl Iterator { } /// Also true for a link that points nowhere. -fn exists(path: &Path) -> io::Result { +pub(crate) fn exists(path: &Path) -> io::Result { match path.symlink_metadata() { Ok(_) => Ok(true), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), @@ -235,7 +249,7 @@ fn lock(file: &File) -> Result<()> { } /// Renames without ever replacing a file. -fn rename_new(from: &Path, to: &Path) -> io::Result<()> { +pub(crate) fn rename_new(from: &Path, to: &Path) -> io::Result<()> { match renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE) { Err(Errno::INVAL | Errno::NOSYS | Errno::NOTSUP) => rename_over_placeholder(from, to), other => Ok(other?), @@ -277,7 +291,7 @@ mod tests { std::fs::write(d.join("a.tar.gz"), "mine").unwrap(); std::fs::write(d.join("a (1).tar.gz.medlar"), "half").unwrap(); std::os::unix::fs::symlink("/nowhere", d.join("a (2).tar.gz")).unwrap(); - let (f, name) = PartialFile::create(d, "a.tar.gz").unwrap(); + let (f, name) = PartialFile::create(d, "a.tar.gz", &HashSet::new()).unwrap(); assert_eq!(name, "a (3).tar.gz"); f.reserve(10).unwrap(); // Someone takes the name while it downloads. @@ -298,20 +312,22 @@ mod tests { #[test] fn one_writer_and_empty_leftovers() { let dir = tempfile::tempdir().unwrap(); - let (first, name) = PartialFile::create(dir.path(), "f.bin").unwrap(); - let (_second, other) = PartialFile::create(dir.path(), "f.bin").unwrap(); + let (first, name) = PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap(); + let (_second, other) = PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap(); assert_eq!((name.as_str(), other.as_str()), ("f.bin", "f (1).bin")); assert!(matches!(PartialFile::reopen(dir.path(), "f.bin"), Err(Error::Busy))); drop(first); assert!(PartialFile::reopen(dir.path(), "f.bin").unwrap().is_some()); - assert_eq!(PartialFile::create(dir.path(), "f.bin").unwrap().1, "f.bin"); + assert_eq!(PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap().1, "f.bin"); + // Empty, but another download's. + assert_eq!(PartialFile::create(dir.path(), "f.bin", &HashSet::from(["f.bin".into()])).unwrap().1, "f (2).bin"); assert!(PartialFile::reopen(dir.path(), "gone").unwrap().is_none()); } #[test] fn space_is_checked_before_writing() { let dir = tempfile::tempdir().unwrap(); - let (f, _) = PartialFile::create(dir.path(), "f").unwrap(); + let (f, _) = PartialFile::create(dir.path(), "f", &HashSet::new()).unwrap(); assert!(matches!(f.reserve(1 << 50), Err(Error::NoSpace { need, free }) if need > free)); assert_eq!(f.size().unwrap(), 0); f.reserve(100_000).unwrap(); diff --git a/crates/core/src/events.rs b/crates/core/src/events.rs new file mode 100644 index 0000000..19ec5f2 --- /dev/null +++ b/crates/core/src/events.rs @@ -0,0 +1,16 @@ +//! What happened, for those who react to it: messages, sounds, programs to run. The state itself is in the snapshot. + +use crate::model::{State, TaskId}; + +/// From `Manager::subscribe`. Sent after the snapshot shows it. Whoever falls behind looks at the snapshot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Event { + Added(TaskId), + /// One move that the model allows. + State { id: TaskId, from: State, to: State }, + /// Gone from the list. It can come back. + Removed(TaskId), + Restored(TaskId), + /// Gone for good. + Forgotten(TaskId), +} diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index fbe29bc..d189810 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -123,14 +123,15 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); let file = job .run(move |store| { - let (file, name) = PartialFile::create(&folder, &wanted)?; - let mut task = store.task(id)?; - task.name = name; - task.size = probe.version.size; - task.etag = probe.version.etag; - task.last_modified = probe.version.last_modified; - task.mime = probe.mime; - store.save_task(task)?; + let _names = disk::names(); + let (file, name) = PartialFile::create(&folder, &wanted, &store.used_names(&folder, id)?)?; + store.edit_task(id, move |task| { + task.name = name; + task.size = probe.version.size; + task.etag = probe.version.etag; + task.last_modified = probe.version.last_modified; + task.mime = probe.mime; + })?; store.save_parts(id, saved)?; Ok(file) }) @@ -209,7 +210,8 @@ impl Job { let task = store.task(id)?; file.finish(&task.name, size, |name| { if name != task.name || task.size != Some(size) { - store.save_task(Task { name: name.into(), size: Some(size), ..task.clone() })?; + let name = name.to_string(); + store.edit_task(id, move |task| (task.name, task.size) = (name, Some(size)))?; } Ok(()) }) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index e1c7bcd..07e38d9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -2,15 +2,19 @@ pub mod adapt; pub mod disk; +pub mod events; pub mod host; pub mod http; pub mod logging; +pub mod manager; pub mod model; pub mod part; pub mod paths; pub mod redact; pub mod segment; pub mod settings; +pub mod snapshot; +pub mod speed; pub mod store; pub mod strings; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs new file mode 100644 index 0000000..57fb5a5 --- /dev/null +++ b/crates/core/src/manager/actor.rs @@ -0,0 +1,964 @@ +//! The thread that owns the list. +//! +//! A task has at most one piece of work at a time: a download or work on its file. Commands that can't share the file with it +//! end the download, and wait in `todo`; so do all that come after them, to keep their order. + +use super::bin::Binned; +use super::pick::{Candidate, pick}; +use super::{Answer, Command, Config, Error, Files, Msg, Result, files}; +use crate::events::Event; +use crate::http::{self, Monitor, PartState, PartView, Source, download, safe_name}; +use crate::model::*; +use crate::settings::Limits; +use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; +use crate::speed::{History, Meter}; +use crate::store::{self, Store}; +use crate::{host, redact, strings, tr}; +use arc_swap::ArcSwap; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::path::PathBuf; +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}; + +const LOG_LINES: usize = 200; +/// Messages taken in before the next snapshot. +const BATCH: usize = 256; +/// What closing may take: the downloads' end, and the rest of the runtime. +const CLOSING: Duration = Duration::from_millis(1600); +const RUNTIME: Duration = Duration::from_millis(200); + +/// Why a download ended early. +#[derive(Debug)] +pub enum Why { + Http(http::Error), + Panic, +} + +/// What file work brought. +#[derive(Debug)] +pub enum Worked { + Plain, + Binned(Option), +} + +enum Work { + Run(Run), + Files { cancel: Arc, answer: Option }, +} + +struct Run { + stop: watch::Sender, + monitor: Arc, + since: Instant, + /// Bytes counted so far. + received: u64, + /// The file's name and size are known. + known: bool, +} + +/// What waits for a task's work to end. +enum Todo { + Command(Command), + /// The second half of a removal. + Bin, +} + +struct Entry { + task: Arc, + host: Arc, + work: Option, + todo: VecDeque<(Todo, Option)>, + /// Counts up with each start; 0 for never. + forced: u64, + size: Option, + downloaded: u64, + parts: Arc<[PartView]>, + connections: u32, + wanted: u32, + resumable: Option, + meter: Meter, + history: Arc, + /// Bytes of the second that isn't over. + second: u64, + log: Arc, + counters: Counters, + binned: Option, + forget_at: Option, +} + +impl Entry { + fn new(task: Task) -> Entry { + let mut e = Entry { + host: host_of(&task.url), + task: Arc::new(task), + work: None, + todo: VecDeque::new(), + forced: 0, + size: None, + downloaded: 0, + parts: Arc::new([]), + connections: 0, + wanted: 0, + resumable: None, + meter: Meter::default(), + history: Arc::default(), + second: 0, + log: Arc::default(), + counters: Counters::default(), + binned: None, + forget_at: None, + }; + e.took(None); + e + } + + fn removed(&self) -> bool { + self.task.removed_at.is_some() + } + + /// The task changed in the store; the parts too, if given. + fn took(&mut self, parts: Option>) { + (self.size, self.downloaded) = (self.task.size, self.task.downloaded); + if self.host != host_of(&self.task.url) { + self.host = host_of(&self.task.url); + } + if let Some(parts) = parts { + self.resumable = if parts.is_empty() { None } else { Some(parts.iter().all(|p| p.end.is_some())) }; + self.parts = parts.iter().enumerate().map(|(i, p)| at_rest(i as u32, p)).collect(); + } + if self.task.state == State::Done { + self.parts = Arc::new([]); + self.downloaded = self.size.unwrap_or(self.downloaded); + } + } + + fn log(&mut self, text: &str) { + let log = Arc::make_mut(&mut self.log); + if log.len() == LOG_LINES { + log.pop_front(); + } + log.push_back(Line { at: now(), text: redact::text(text).into() }); + } + + fn view(&self, rev: u64) -> TaskView { + TaskView { + task: self.task.clone(), + rev, + size: self.size, + downloaded: self.downloaded, + speed: if self.task.state == State::Running { self.meter.speed() } else { 0.0 }, + left: self.meter.left().filter(|_| self.task.state == State::Running), + parts: self.parts.clone(), + connections: self.connections, + wanted: self.wanted, + resumable: self.resumable, + checked: 0.0, + server: self.host.clone(), + history: self.history.clone(), + log: self.log.clone(), + counters: self.counters, + } + } +} + +fn host_of(url: &str) -> Arc { + url::Url::parse(url).map(|u| host::key(&u)).unwrap_or_default().into() +} + +fn at_rest(id: u32, p: &Part) -> PartView { + let state = if p.end == Some(p.start + p.done) { PartState::Done } else { PartState::Waiting }; + PartView { id, start: p.start, end: p.end, done: p.done, state, speed: 0.0, fails: 0 } +} + +fn unlimited(n: u32) -> u32 { + if n == 0 { u32::MAX } else { n } +} + +pub struct Actor { + config: Config, + store: Arc, + runtime: Option, + to: mpsc::Sender, + published: Arc>, + shot: Snapshot, + events: broadcast::Sender, + on_change: Vec>, + entries: BTreeMap, + /// Those with a download as their work. + runs: BTreeSet, + /// Those to forget some time. + removed: BTreeSet, + dirty: BTreeSet, + totals: Totals, + totals_dirty: bool, + /// Someone may have to start or stop. + choose: bool, + /// Told after the snapshot. + happened: Vec, + answers: Vec<(Answer, Result)>, + last_position: f64, + forces: u64, + meter: Meter, + second: u64, + born: Instant, + seconds: u64, + sampled: Instant, + closing: bool, +} + +impl Actor { + pub fn new(config: Config, to: mpsc::Sender, published: Arc>, events: broadcast::Sender) -> Result { + let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().map_err(Error::File)?; + let mut actor = Actor { + store: config.shared.store.clone(), + config, + runtime: Some(runtime), + to, + published, + shot: Snapshot::default(), + events, + on_change: vec![], + entries: BTreeMap::new(), + runs: BTreeSet::new(), + removed: BTreeSet::new(), + dirty: BTreeSet::new(), + totals: Totals::default(), + totals_dirty: true, + choose: true, + happened: vec![], + answers: vec![], + last_position: 0.0, + forces: 0, + meter: Meter::default(), + second: 0, + born: Instant::now(), + seconds: 0, + sampled: Instant::now(), + closing: false, + }; + actor.set_limits(actor.config.limits); + for mut task in actor.store.tasks()? { + if task.removed_at.is_some() { + actor.store.delete_task(task.id)?; + continue; + } + // The program ended in the middle of it. + if matches!(task.state, State::Running | State::Checking | State::Finishing) { + actor.store.set_state(task.id, State::Queued, None)?; + (task.state, task.error) = (State::Queued, None); + } + let (id, unfinished) = (task.id, task.state != State::Done && task.downloaded > 0); + actor.last_position = actor.last_position.max(task.position); + let mut entry = Entry::new(task); + if unfinished { + entry.took(Some(actor.store.parts(id)?)); + } + actor.entries.insert(id, entry); + actor.dirty.insert(id); + } + actor.publish(); + Ok(actor) + } + + pub fn run(mut self, inbox: mpsc::Receiver) { + while !self.closing { + self.settle(); + let msg = match self.pause() { + Some(pause) => inbox.recv_timeout(pause), + // `self.to` keeps it open. + None => inbox.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), + }; + for msg in msg.into_iter().chain(std::iter::from_fn(|| inbox.try_recv().ok())).take(BATCH) { + self.take(msg); + } + let now = Instant::now(); + if now.duration_since(self.sampled) >= self.config.tick { + self.sample(now); + } + self.forget(now); + } + self.close(inbox); + } + + /// How long there is nothing to do but wait for messages. + fn pause(&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())); + } + // The curve ends on the ground. + 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()?; + // It may wait for work to end; that comes as a message. + Some(next.saturating_duration_since(Instant::now()).max(self.config.tick)) + } + + fn take(&mut self, msg: Msg) { + match msg { + Msg::Command(command, answer) => self.command(command, answer), + Msg::Limits(limits) => self.set_limits(limits), + 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::Close => self.closing = true, + } + } + + /// Starts and stops what has to, then tells everyone. + fn settle(&mut self) { + // A start can fail at once and make room for another. + while std::mem::take(&mut self.choose) && !self.closing { + self.choose(); + } + self.publish(); + } + + fn publish(&mut self) { + if !self.dirty.is_empty() || std::mem::take(&mut self.totals_dirty) { + self.shot.rev += 1; + for id in std::mem::take(&mut self.dirty) { + match self.entries.get(&id).filter(|e| !e.removed()) { + Some(e) => self.shot.put(e.view(self.shot.rev)), + None => self.shot.remove(id), + } + } + self.shot.totals = self.totals.clone(); + self.totals_dirty = false; + self.published.store(Arc::new(self.shot.clone())); + for call in &self.on_change { + call(); + } + } + for event in self.happened.drain(..) { + // Nobody has to listen. + let _ = self.events.send(event); + } + for (answer, result) in self.answers.drain(..) { + let _ = answer.send(result); + } + } + + fn answer(&mut self, answer: Option, result: Result) { + if let Some(answer) = answer { + self.answers.push((answer, result)); + } + } + + fn entry(&mut self, id: TaskId) -> &mut Entry { + self.dirty.insert(id); + self.entries.get_mut(&id).expect("the caller has seen it") + } + + fn set_limits(&mut self, limits: Limits) { + self.config.limits = limits; + let hosts = &self.config.shared.hosts; + let caps = host::Caps { total: unlimited(limits.max_connections), per_host: unlimited(limits.connections_per_host), ..hosts.caps() }; + hosts.set_caps(caps); + for id in &self.runs { + if let Some(Work::Run(run)) = &self.entries[id].work { + run.monitor.set_cap(unlimited(limits.parts_per_download)); + } + } + self.choose = true; + } + + // Commands. + + fn command(&mut self, command: Command, answer: Option) { + let Some(id) = command.id() else { + let Command::Add(task) = command else { unreachable!("only it has no id") }; + let result = self.add(*task); + return self.answer(answer, result); + }; + let Some(e) = self.entries.get(&id) else { + let removed = matches!(command, Command::Remove { .. }); + return self.answer(answer, if removed { Ok(id) } else { Err(store::Error::NotFound.into()) }); + }; + match command { + 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), + Command::Remove { .. } => self.answer(answer, Ok(id)), + _ if let Some(result) = self.at_once(id, &command) => self.answer(answer, result.map(|()| id)), + _ if self.must_wait(id, &command) => self.later(id, command, answer), + _ => self.apply(id, command, answer), + } + } + + /// What needs no work at all, so that no download is interrupted for it. + fn at_once(&self, id: TaskId, command: &Command) -> Option> { + let e = &self.entries[&id]; + if !e.todo.is_empty() || matches!(e.work, Some(Work::Files { .. })) { + return None; + } + match command { + Command::Restore(_) => (!e.removed()).then_some(Ok(())), + _ if e.removed() => Some(Err(store::Error::NotFound.into())), + Command::Move { folder, .. } if !folder.is_absolute() => Some(Err(Error::Folder)), + Command::Move { folder, .. } => (*folder == e.task.folder).then_some(Ok(())), + Command::Rename { name, .. } => match safe_name(name) { + None => Some(Err(Error::Name)), + Some(name) => (name == e.task.name).then_some(Ok(())), + }, + _ => None, + } + } + + fn must_wait(&self, id: TaskId, command: &Command) -> bool { + use Command::*; + let e = &self.entries[&id]; + let alone = matches!(command, Move { .. } | Rename { .. } | Redownload(_) | Restore(_)); + !e.todo.is_empty() + || match e.work { + None => false, + Some(Work::Run(_)) => alone, + Some(Work::Files { .. }) => true, + } + } + + fn later(&mut self, id: TaskId, command: Command, answer: Option) { + self.suspend(id); + self.entry(id).todo.push_back((Todo::Command(command), answer)); + } + + /// Does what waits until there is work again. + fn next(&mut self, id: TaskId) { + while let Some(e) = self.entries.get_mut(&id).filter(|e| e.work.is_none()) { + match e.todo.pop_front() { + Some((Todo::Command(Command::Remove { files, .. }), answer)) if !e.removed() => self.remove(id, files, answer), + Some((Todo::Command(command), answer)) => self.apply(id, command, answer), + Some((Todo::Bin, answer)) => { + let bin = self.config.bin.clone(); + self.work(id, answer, move |store, _| Ok(Worked::Binned(files::bin(store, id, &bin)?))); + } + None => break, + } + } + self.choose = true; + } + + /// Nothing is in its way. + fn apply(&mut self, id: TaskId, command: Command, answer: Option) { + use State::*; + let (state, removed) = (self.entries[&id].task.state, self.entries[&id].removed()); + if removed && !matches!(command, Command::Restore(_) | Command::Remove { .. }) { + return self.answer(answer, Err(store::Error::NotFound.into())); + } + let mut result = Ok(()); + match command { + Command::Start(_) => { + result = self.resume(id); + if result.is_ok() && matches!(self.entries[&id].task.state, Queued | Running) { + self.forces += 1; + self.entry(id).forced = self.forces; + self.choose = true; + } + } + Command::Resume(_) => result = self.resume(id), + Command::Pause(_) => result = self.hold(id), + Command::Stop(_) => { + result = self.hold(id).and_then(|()| { + if matches!(state, Done | Gone) { + return Ok(()); + } + self.last_position += 1.0; + let last = self.last_position; + self.change(id, move |t| t.position = last) + }); + } + Command::Restore(_) if !removed => {} + Command::Restore(_) => { + let binned = self.entries[&id].binned.clone(); + return self.work(id, answer, move |store, _| { + if let Some(binned) = binned { + files::unbin(store, id, &binned)?; + } + store.edit_task(id, |t| t.removed_at = None)?; + Ok(Worked::Plain) + }); + } + Command::Redownload(_) => { + if state != Queued { + result = self.set_state(id, Queued, None); + } + if result.is_ok() { + return self.work(id, answer, move |store, _| files::discard(store, id).map(|()| Worked::Plain)); + } + } + Command::Move { folder, .. } => { + if folder.is_absolute() { + return self.work(id, answer, move |store, cancel| { + files::relocate(store, id, Some(&folder), None, cancel).map(|()| Worked::Plain) + }); + } + result = Err(Error::Folder); + } + Command::Rename { name, .. } => match safe_name(&name) { + Some(name) => { + return self.work(id, answer, move |store, cancel| { + files::relocate(store, id, None, Some(&name), cancel).map(|()| Worked::Plain) + }); + } + None => result = Err(Error::Name), + }, + Command::Edit { edit, .. } => result = self.change(id, edit), + Command::Remove { .. } => {} + Command::Add(_) => unreachable!("has no id"), + } + self.answer(answer, result.map(|()| id)); + } + + fn add(&mut self, mut task: Task) -> Result { + if !task.folder.is_absolute() { + return Err(Error::Folder); + } + if !matches!(task.state, State::Queued | State::Waiting | State::Paused) { + task.state = State::Queued; + } + task.name = safe_name(&task.name).unwrap_or_default(); + (task.error, task.downloaded, task.finished_at, task.removed_at) = (None, 0, None, None); + if task.position == 0.0 { + task.position = self.last_position + 1.0; + } + self.last_position = self.last_position.max(task.position); + task.id = self.store.add_task(task.clone())?; + let (id, mut entry) = (task.id, Entry::new(task)); + entry.log(&tr!("log.added", url = entry.task.url)); + self.entries.insert(id, entry); + self.dirty.insert(id); + self.happened.push(Event::Added(id)); + self.choose = true; + Ok(id) + } + + 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), + _ => Ok(()), + } + } + + fn hold(&mut self, id: TaskId) -> Result<()> { + let state = self.entries[&id].task.state; + if !matches!(state, State::Queued | State::Waiting | State::Running | State::Checking) { + return Ok(()); + } + self.entry(id).forced = 0; + if state == State::Running { + self.stop_run(id); + } + self.set_state(id, State::Paused, None) + } + + fn remove(&mut self, id: TaskId, files: Files, answer: Option) { + let task = match self.store.edit_task(id, |t| t.removed_at = Some(now())) { + Ok(task) => task, + Err(e) => return self.answer(answer, Err(e.into())), + }; + self.suspend(id); + let undo = self.config.undo; + let e = self.entry(id); + Arc::make_mut(&mut e.task).removed_at = task.removed_at; + e.forget_at = Some(Instant::now() + undo); + e.forced = 0; + self.removed.insert(id); + self.happened.push(Event::Removed(id)); + self.choose = true; + if files == Files::Keep { + return self.answer(answer, Ok(id)); + } + self.entry(id).todo.push_back((Todo::Bin, answer)); + self.next(id); + } + + /// Changes what the user decides. + fn change(&mut self, id: TaskId, edit: impl FnOnce(&mut Task)) -> Result<()> { + let mut new = (*self.entries[&id].task).clone(); + edit(&mut new); + let saved = self.store.edit_task(id, move |t| { + t.url = new.url; + t.mirrors = new.mirrors; + t.source_page = new.source_page; + t.queue = new.queue; + t.position = new.position; + t.priority = new.priority; + t.checksum = new.checksum; + t.max_parts = new.max_parts; + t.speed_limit = new.speed_limit; + t.headers = new.headers; + t.proxy = new.proxy; + t.secret = new.secret; + t.after = new.after; + t.start_at = new.start_at; + t.tags = new.tags; + t.notes = new.notes; + })?; + self.last_position = self.last_position.max(saved.position); + let e = self.entry(id); + // The numbers of a running download are newer than the store's. + let (size, downloaded) = (e.size, e.downloaded); + e.task = Arc::new(saved); + e.took(None); + if e.task.state == State::Running { + (e.size, e.downloaded) = (size, downloaded); + } + self.choose = true; + Ok(()) + } + + // States and work. + + fn set_state(&mut self, id: TaskId, to: State, error: Option) -> Result<()> { + let from = self.entries[&id].task.state; + self.store.set_state(id, to, error.clone())?; + // The time it finished comes from the store. + let finished = if to == State::Done { self.store.task(id)?.finished_at } else { self.entries[&id].task.finished_at }; + let e = self.entry(id); + let error = error.map(|e| TaskError { detail: redact::text(&e.detail), ..e }); + match &error { + Some(error) => e.log(&tr!("log.failed", why = error.detail)), + None => e.log(&strings::text(&format!("state.{}", to.name()), &[])), + } + let task = Arc::make_mut(&mut e.task); + (task.state, task.error, task.finished_at) = (to, error, finished); + self.happened.push(Event::State { id, from, to }); + self.choose = true; + Ok(()) + } + + /// The same where nobody waits for an answer. If it can't be saved, the list goes on without: the next start repairs it. + fn move_to(&mut self, id: TaskId, to: State, error: Option) { + if let Err(e) = self.set_state(id, to, error.clone()) { + log::error!("task {id} to {}: {e}", to.name()); + let task = Arc::make_mut(&mut self.entry(id).task); + (task.state, task.error) = (to, error); + self.choose = true; + } + } + + fn stop_run(&mut self, id: TaskId) { + if let Some(Work::Run(run)) = &self.entries[&id].work { + run.stop.send_replace(true); + } + } + + /// Takes a running one's place away. + fn suspend(&mut self, id: TaskId) { + if self.entries[&id].task.state == State::Running { + self.stop_run(id); + self.move_to(id, State::Queued, None); + } + } + + fn choose(&mut self) { + let queues: HashMap = match self.store.queues() { + Ok(queues) => queues.into_iter().map(|q| (q.id, q.position)).collect(), + Err(e) => { + log::error!("queues not read: {e}"); + HashMap::new() + } + }; + 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(), + _ => false, + }; + let candidates = self.entries.iter().filter(|(_, e)| eligible(e)).map(|(id, e)| Candidate { + id: *id, + host: &e.host, + priority: e.task.priority, + forced: e.forced, + running: e.task.state == State::Running, + pinned: e.resumable == Some(false) && e.downloaded > 0, + 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 picked = pick(candidates.collect(), unlimited(self.config.limits.max_active) as usize, host_cap); + let chosen: BTreeSet = picked.iter().copied().collect(); + for id in self.runs.clone() { + if !chosen.contains(&id) { + self.suspend(id); + } + } + for id in picked { + let e = &self.entries[&id]; + if e.task.state == State::Queued && e.work.is_none() && e.todo.is_empty() { + self.begin(id); + } + } + let count = |state| self.entries.values().filter(|e| e.task.state == state && !e.removed()).count(); + (self.totals.running, self.totals.queued) = (count(State::Running), count(State::Queued)); + self.totals_dirty = true; + } + + fn begin(&mut self, id: TaskId) { + if let Err(e) = self.set_state(id, State::Running, None) { + // Not picked again until something changes. + log::error!("task {id} not started: {e}"); + return; + } + let task = self.entries[&id].task.clone(); + let source = match Source::new(&task.url) { + Ok(source) => source.with_headers(&task.headers), + Err(e) => return self.failed(id, &Why::Http(e)), + }; + 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 (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 }); + let result = match work.await { + Ok(result) => result.map_err(Why::Http), + Err(_) => Err(Why::Panic), + }; + let _ = to.send(Msg::Ended(id, result)); + }); + if self.runs.is_empty() { + self.sampled = Instant::now(); + } + self.runs.insert(id); + self.totals.counters.runs += 1; + let e = self.entry(id); + e.log(&tr!("log.connect", server = e.host)); + e.counters.runs += 1; + e.meter = Meter::default(); + e.work = Some(Work::Run(run)); + } + + fn runtime(&self) -> &Runtime { + self.runtime.as_ref().expect("taken at the very end") + } + + fn work(&mut self, id: TaskId, answer: Option, job: impl FnOnce(&Store, &AtomicBool) -> Result + Send + 'static) { + let cancel = Arc::new(AtomicBool::new(false)); + let (store, to, asked) = (self.store.clone(), self.to.clone(), cancel.clone()); + self.runtime().spawn(async move { + let result = match tokio::task::spawn_blocking(move || job(&store, &asked)).await { + Ok(result) => result, + Err(_) => Err(Error::File(std::io::ErrorKind::Other.into())), + }; + let _ = to.send(Msg::Worked(id, result)); + }); + self.entry(id).work = Some(Work::Files { cancel, answer }); + } + + fn ended(&mut self, id: TaskId, result: std::result::Result) { + self.measure(id, Duration::ZERO); + self.runs.remove(&id); + let reloaded = self.reload(id, true); + let e = self.entry(id); + e.work = None; + (e.connections, e.wanted) = (0, 0); + if let Err(why) = reloaded { + log::error!("task {id} not read: {why}"); + } + 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))), + } + self.next(id); + } + + /// The file is whole, even if it was being stopped. + 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::Finishing, State::Done], + }; + for state in way { + self.move_to(id, *state, None); + } + self.totals.counters.finished += 1; + let e = self.entry(id); + e.counters.finished += 1; + e.forced = 0; + e.took(None); + } + + fn failed(&mut self, id: TaskId, why: &Why) { + 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) })); + } + + fn worked(&mut self, id: TaskId, result: Result) { + let Some(Work::Files { answer, .. }) = self.entry(id).work.take() else { return }; + let was = self.entries[&id].task.clone(); + let result = result.and_then(|worked| self.reload(id, true).map(|()| worked)); + let e = self.entry(id); + match &result { + Ok(Worked::Binned(binned)) => e.binned = binned.clone(), + Ok(Worked::Plain) => { + if was.folder != e.task.folder { + e.log(&tr!("log.moved", folder = e.task.folder.display())); + } + if was.name != e.task.name { + e.log(&tr!("log.renamed", name = e.task.name)); + } + } + Err(why) => e.log(&why.to_string()), + } + if was.removed_at.is_some() && !e.removed() { + (e.binned, e.forget_at) = (None, None); + self.removed.remove(&id); + self.happened.push(Event::Restored(id)); + } + self.answer(answer, result.map(|_| id)); + self.next(id); + } + + /// Takes over what the store has by now. The state is the actor's own. + fn reload(&mut self, id: TaskId, parts: bool) -> Result<()> { + let (task, parts) = (self.store.task(id)?, if parts { Some(self.store.parts(id)?) } else { None }); + let e = self.entry(id); + let (state, error) = (e.task.state, e.task.error.clone()); + e.task = Arc::new(Task { state, error, ..task }); + e.took(parts); + Ok(()) + } + + fn forget(&mut self, now: Instant) { + for id in self.removed.clone() { + let e = &self.entries[&id]; + if e.work.is_some() || !e.todo.is_empty() || e.forget_at.is_none_or(|at| now < at) { + continue; + } + if let Err(why) = self.store.delete_task(id) { + log::error!("task {id} not forgotten: {why}"); + } + self.removed.remove(&id); + self.entries.remove(&id); + self.happened.push(Event::Forgotten(id)); + } + } + + // Numbers. + + fn sample(&mut self, now: Instant) { + let dt = now.duration_since(self.sampled); + self.sampled = now; + let (before, running) = (self.totals.counters.received, self.runs.clone()); + for id in &running { + self.measure(*id, dt); + } + self.meter.push(self.totals.counters.received - before, dt, None); + let over = now.duration_since(self.born).as_secs(); + if over > self.seconds { + let history = Arc::make_mut(&mut self.totals.history); + history.skip(over - self.seconds - 1); + history.push(std::mem::take(&mut self.second) as f64); + for id in &running { + let e = self.entry(*id); + let bytes = std::mem::take(&mut e.second) as f64; + Arc::make_mut(&mut e.history).push(bytes); + } + self.seconds = over; + self.totals_dirty = true; + } + if running.is_empty() { + self.meter = Meter::default(); + } + let connections = running.iter().map(|id| self.entries[id].connections).sum(); + if (self.totals.speed, self.totals.connections) != (self.meter.speed(), connections) { + (self.totals.speed, self.totals.connections) = (self.meter.speed(), connections); + self.totals_dirty = true; + } + } + + /// Looks at a running download. `dt` is the time since the last look, zero for the very last one. + fn measure(&mut self, id: TaskId, dt: Duration) { + let Some(Work::Run(run)) = self.entries.get_mut(&id).and_then(|e| e.work.as_mut()) else { return }; + let shot = run.monitor.snapshot(); + let bytes = shot.received.saturating_sub(run.received); + run.received = shot.received.max(run.received); + let first = !run.known && !shot.parts.is_empty(); + run.known |= first; + let active = run.since.elapsed(); + run.since = Instant::now(); + if first && let Err(e) = self.reload(id, false) { + log::error!("task {id} not read: {e}"); + } + self.second += bytes; + self.totals.counters.received += bytes; + self.totals.counters.active += active; + let e = self.entries.get_mut(&id).expect("seen above"); + e.second += bytes; + e.counters.received += bytes; + e.counters.active += active; + if shot.parts.is_empty() { + e.meter.push(bytes, dt, None); + return; + } + let before = (e.meter.speed(), e.meter.left()); + let downloaded = shot.parts.iter().map(|p| p.done).sum(); + e.meter.push(bytes, dt, shot.size.map(|size| size.saturating_sub(downloaded))); + if first { + let text = match shot.size { + Some(size) => tr!("log.file", name = e.task.name, n = size), + None => tr!("log.file_unknown", name = e.task.name), + }; + e.log(&text); + } + let same = e.downloaded == downloaded + && e.size == shot.size + && (e.connections, e.wanted) == (shot.connections, shot.wanted) + && before == (e.meter.speed(), e.meter.left()) + && *e.parts == *shot.parts; + if same && !first { + return; + } + (e.downloaded, e.size, e.connections, e.wanted) = (downloaded, shot.size, shot.connections, shot.wanted); + e.resumable = Some(shot.parts.iter().all(|p| p.end.is_some())); + e.parts = shot.parts.into(); + self.dirty.insert(id); + } + + // The end. + + fn close(mut self, inbox: mpsc::Receiver) { + let end = Instant::now() + CLOSING; + for id in self.runs.clone() { + self.suspend(id); + } + for e in self.entries.values_mut() { + if let Some(Work::Files { cancel, .. }) = &e.work { + cancel.store(true, Ordering::Relaxed); + } + // Their senders learn that it is closed. + e.todo.clear(); + } + self.publish(); + while Instant::now() < end && self.entries.values().any(|e| e.work.is_some()) { + match inbox.recv_timeout(end.saturating_duration_since(Instant::now())) { + Ok(msg @ (Msg::Ended(..) | Msg::Worked(..))) => self.take(msg), + Ok(_) => {} + // What is left stays as its last checkpoint has it. + Err(_) => break, + } + } + self.totals.speed = 0.0; + (self.totals.connections, self.totals.running, self.totals_dirty) = (0, 0, true); + self.publish(); + if let Some(runtime) = self.runtime.take() { + runtime.shutdown_timeout(RUNTIME); + } + } +} + +/// S007 puts plain words and kinds here. +fn words(why: &Why) -> String { + format!("{why:?}") +} diff --git a/crates/core/src/manager/bin.rs b/crates/core/src/manager/bin.rs new file mode 100644 index 0000000..39d97a8 --- /dev/null +++ b/crates/core/src/manager/bin.rs @@ -0,0 +1,137 @@ +//! The desktop's bin (freedesktop.org trash specification). Everything here blocks. + +use crate::disk::{exists, rename_new, variants}; +use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_encode}; +use std::fs::{self, DirBuilder, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +const KEEP: &AsciiSet = &NON_ALPHANUMERIC.remove(b'/').remove(b'-').remove(b'_').remove(b'.').remove(b'~'); + +#[derive(Debug, Clone)] +pub struct Bin { + /// Usually `~/.local/share/Trash`. + home: PathBuf, +} + +/// A file in the bin. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binned { + pub from: PathBuf, + pub file: PathBuf, + info: PathBuf, +} + +impl Default for Bin { + fn default() -> Bin { + Bin::at(dirs::data_dir().unwrap_or_default().join("Trash")) + } +} + +impl Bin { + pub fn at(home: PathBuf) -> Bin { + Bin { home } + } + + /// Moves the file there. Never copies: each filesystem has its own bin. + pub fn put(&self, file: &Path) -> io::Result { + let name = file.file_name().ok_or(io::ErrorKind::InvalidInput)?; + let device = file.symlink_metadata()?.dev(); + let (bin, listed) = match make(&self.home) { + Ok(()) if self.home.metadata()?.dev() == device => (self.home.clone(), file), + _ => { + let top = top(file, device); + (top_bin(top)?, file.strip_prefix(top).unwrap_or(file)) + } + }; + let (files, infos) = (bin.join("files"), bin.join("info")); + make(&files)?; + make(&infos)?; + let path = percent_encode(listed.as_os_str().as_bytes(), KEEP); + let text = format!("[Trash Info]\nPath={path}\nDeletionDate={}\n", chrono::Local::now().format("%Y-%m-%dT%H:%M:%S")); + for variant in variants(&name.to_string_lossy()) { + let (to, info) = (files.join(&variant), infos.join(format!("{variant}.trashinfo"))); + if exists(&to)? { + continue; + } + let mut out = match OpenOptions::new().write(true).create_new(true).open(&info) { + Ok(out) => out, + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + }; + match out.write_all(text.as_bytes()).and_then(|()| rename_new(file, &to)) { + Ok(()) => return Ok(Binned { from: file.into(), file: to, info }), + Err(e) => { + let _ = fs::remove_file(&info); + if e.kind() != io::ErrorKind::AlreadyExists { + return Err(e); + } + } + } + } + unreachable!("variants never end") + } +} + +impl Binned { + /// Moves it back, to `to`. Never replaces a file. + pub fn back(&self, to: &Path) -> io::Result<()> { + rename_new(&self.file, to)?; + let _ = fs::remove_file(&self.info); + Ok(()) + } +} + +fn make(dir: &Path) -> io::Result<()> { + DirBuilder::new().recursive(true).mode(0o700).create(dir) +} + +/// The highest folder on the same filesystem. +fn top(file: &Path, device: u64) -> &Path { + let same = |p: &&Path| p.metadata().is_ok_and(|m| m.dev() == device); + file.ancestors().skip(1).take_while(same).last().unwrap_or(Path::new("/")) +} + +fn top_bin(top: &Path) -> io::Result { + let user = rustix::process::getuid().as_raw(); + let shared = top.join(".Trash"); + // Anyone could put a link there, or look into it without the sticky bit. + if shared.symlink_metadata().is_ok_and(|m| m.is_dir() && m.permissions().mode() & 0o1000 != 0) { + let own = shared.join(user.to_string()); + if make(&own).is_ok() { + return Ok(own); + } + } + let own = top.join(format!(".Trash-{user}")); + make(&own)?; + if own.symlink_metadata()?.is_symlink() { Err(io::ErrorKind::PermissionDenied.into()) } else { Ok(own) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn there_and_back() { + let dir = tempfile::tempdir().unwrap(); + let bin = Bin::at(dir.path().join("Trash")); + let file = dir.path().join("ä b%.tar.gz"); + let mut binned = vec![]; + for text in ["one", "two"] { + fs::write(&file, text).unwrap(); + binned.push(bin.put(&file).unwrap()); + assert!(!file.exists()); + } + assert_eq!(binned[1].file.file_name().unwrap(), "ä b% (1).tar.gz"); + let info = fs::read_to_string(&binned[1].info).unwrap(); + assert!(info.contains("/%C3%A4%20b%25.tar.gz\nDeletionDate=2"), "{info}"); + assert_eq!(binned[1].info.file_name().unwrap(), "ä b% (1).tar.gz.trashinfo"); + binned[0].back(&file).unwrap(); + assert_eq!(fs::read(&file).unwrap(), b"one"); + assert!(!binned[0].info.exists()); + assert_eq!(binned[1].back(&file).unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert!(bin.put(&dir.path().join("none")).is_err()); + } +} diff --git a/crates/core/src/manager/files.rs b/crates/core/src/manager/files.rs new file mode 100644 index 0000000..e960064 --- /dev/null +++ b/crates/core/src/manager/files.rs @@ -0,0 +1,256 @@ +//! A task's file: where it is, moving it, binning it. Everything here blocks, and nothing may be writing the file. + +use super::bin::{Bin, Binned}; +use super::{Error, Result}; +use crate::disk::{self, PartialFile, exists, partial_path, rename_new, variants}; +use crate::model::{Part, State, Task, TaskId}; +use crate::store::Store; +use std::collections::HashSet; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Debug, PartialEq)] +enum Own { + Nothing, + Partial(PathBuf), + Whole(PathBuf), +} + +fn own(task: &Task, parts: &[Part]) -> io::Result { + let (partial, whole) = (partial_path(&task.folder, &task.name), task.folder.join(&task.name)); + if task.name.is_empty() { + return Ok(Own::Nothing); + } + if task.state == State::Done { + return Ok(if exists(&whole)? { Own::Whole(whole) } else { Own::Nothing }); + } + if parts.is_empty() { + return Ok(Own::Nothing); + } + if exists(&partial)? { + return Ok(Own::Partial(partial)); + } + // Killed or paused between the rename and the end. + let size: u64 = parts.iter().map(|p| p.done).sum(); + let finished = parts.iter().all(|p| p.end == Some(p.start + p.done)); + if finished && whole.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == size) { + return Ok(Own::Whole(whole)); + } + Ok(Own::Nothing) +} + +/// An empty file that nobody holds could be taken for a leftover by another download. +fn hold(partial: &Path) -> Result> { + PartialFile::hold(partial.into()).map_err(|e| match e { + disk::Error::Io(e) => Error::File(e), + _ => Error::File(io::ErrorKind::ResourceBusy.into()), + }) +} + +fn record(store: &Store, id: TaskId, folder: &Path, name: &str) -> Result<()> { + let (folder, name) = (folder.to_path_buf(), name.to_string()); + store.edit_task(id, move |t| (t.folder, t.name) = (folder, name))?; + Ok(()) +} + +/// Whether a file or another download has the name. +fn taken(folder: &Path, name: &str, used: &HashSet) -> Result { + let there = |path: &Path| exists(path).map_err(Error::File); + Ok(used.contains(name) || there(&folder.join(name))? || there(&partial_path(folder, name))?) +} + +/// Moves and renames the file, to `name` or a numbered variant of it that is free. +pub fn relocate(store: &Store, id: TaskId, folder: Option<&Path>, name: Option<&str>, cancel: &AtomicBool) -> Result<()> { + let task = store.task(id)?; + let (folder, name) = (folder.unwrap_or(&task.folder), name.unwrap_or(&task.name)); + let (from, partial) = match own(&task, &store.parts(id)?).map_err(Error::File)? { + Own::Nothing => (None, false), + Own::Partial(p) => (Some(p), true), + Own::Whole(p) => (Some(p), false), + }; + let _held = if let Some(from) = from.as_ref().filter(|_| partial) { hold(from)? } else { None }; + if from.is_some() { + fs::create_dir_all(folder).map_err(Error::File)?; + } + if name.is_empty() { + return record(store, id, folder, name); + } + for name in variants(name) { + if folder == task.folder && name == task.name { + return Ok(()); + } + let names = disk::names(); + if taken(folder, &name, &store.used_names(folder, id)?)? { + continue; + } + let Some(from) = &from else { return record(store, id, folder, &name) }; + let half = partial_path(folder, &name); + let to = if partial { half.clone() } else { folder.join(&name) }; + // Under both names until it is recorded, so that it can be found whichever name a crash leaves us with. + let moved = match fs::hard_link(from, &to) { + // No hard links here, or another filesystem. + Err(e) if e.kind() != io::ErrorKind::AlreadyExists => rename_new(from, &to), + other => other, + }; + // Other programs take names too. + let _names = match moved { + Ok(()) => Some(names), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) if e.kind() == io::ErrorKind::CrossesDevices => { + // Makes `half` first, which keeps the name. + drop(names); + copy(from, &half, &to, cancel).map_err(Error::File)?; + None + } + Err(e) => return Err(Error::File(e)), + }; + if let Err(e) = record(store, id, folder, &name) { + let _ = if exists(from).unwrap_or(true) { fs::remove_file(&to) } else { rename_new(&to, from) }; + return Err(e); + } + let _ = fs::remove_file(from); + return Ok(()); + } + unreachable!("variants never end") +} + +/// Copies to `half` first; `to` appears when all is there. +fn copy(from: &Path, half: &Path, to: &Path, cancel: &AtomicBool) -> io::Result<()> { + let work = || -> io::Result<()> { + let mut input = File::open(from)?; + let mut output = OpenOptions::new().write(true).create_new(true).open(half)?; + let mut buf = vec![0; 1 << 20]; + loop { + if cancel.load(Ordering::Relaxed) { + return Err(io::ErrorKind::Interrupted.into()); + } + match input.read(&mut buf)? { + 0 => break, + n => output.write_all(&buf[..n])?, + } + } + output.sync_all()?; + if half == to { Ok(()) } else { rename_new(half, to) } + }; + work().inspect_err(|e| { + if e.kind() != io::ErrorKind::AlreadyExists { + let _ = fs::remove_file(half); + } + }) +} + +/// Moves what is there to the bin. +pub fn bin(store: &Store, id: TaskId, bin: &Bin) -> Result> { + let task = store.task(id)?; + match own(&task, &store.parts(id)?).map_err(Error::Bin)? { + Own::Nothing => Ok(None), + Own::Partial(p) | Own::Whole(p) => bin.put(&p).map(Some).map_err(Error::Bin), + } +} + +/// Moves it back, to its old name or a numbered variant. +pub fn unbin(store: &Store, id: TaskId, binned: &Binned) -> Result<()> { + let task = store.task(id)?; + let partial = binned.from == partial_path(&task.folder, &task.name); + let _held = if partial { hold(&binned.file)? } else { None }; + fs::create_dir_all(&task.folder).map_err(Error::File)?; + for name in variants(&task.name) { + let _names = disk::names(); + if taken(&task.folder, &name, &store.used_names(&task.folder, id)?)? { + continue; + } + let to = if partial { partial_path(&task.folder, &name) } else { task.folder.join(&name) }; + match binned.back(&to) { + Ok(()) => return record(store, id, &task.folder, &name), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(Error::File(e)), + } + } + unreachable!("variants never end") +} + +/// Forgets the parts, with the file that holds them. A finished file stays. +pub fn discard(store: &Store, id: TaskId) -> Result<()> { + let task = store.task(id)?; + if let Own::Partial(p) = own(&task, &store.parts(id)?).map_err(Error::File)? { + fs::remove_file(p).map_err(Error::File)?; + } + store.save_parts(id, vec![])?; + store.edit_task(id, |t| { + (t.size, t.etag, t.last_modified, t.mime, t.finished_at, t.downloaded) = (None, None, None, None, None, 0); + })?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bench(parts: Vec) -> (tempfile::TempDir, Store, TaskId) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("m.db")).unwrap(); + let id = store.add_task(Task { name: "a.zip".into(), folder: dir.path().into(), ..Task::default() }).unwrap(); + store.save_parts(id, parts).unwrap(); + (dir, store, id) + } + + const HALF: Part = Part { start: 0, end: Some(10), done: 4 }; + const WHOLE: Part = Part { start: 0, end: Some(4), done: 4 }; + static GO: AtomicBool = AtomicBool::new(false); + + #[test] + fn nothing_is_overwritten_and_twice_is_once() { + let (dir, store, id) = bench(vec![HALF]); + let d = dir.path(); + fs::write(d.join("a.zip.medlar"), "half").unwrap(); + fs::write(d.join("b.zip"), "mine").unwrap(); + for _ in 0..2 { + relocate(&store, id, None, Some("b.zip"), &GO).unwrap(); + assert_eq!(store.task(id).unwrap().name, "b (1).zip"); + assert_eq!(fs::read(d.join("b (1).zip.medlar")).unwrap(), b"half"); + } + relocate(&store, id, Some(&d.join("x/y")), None, &GO).unwrap(); + assert_eq!(fs::read(d.join("x/y/b (1).zip.medlar")).unwrap(), b"half"); + assert!(!d.join("a.zip.medlar").exists() && !d.join("b (1).zip.medlar").exists()); + discard(&store, id).unwrap(); + assert!(!d.join("x/y/b (1).zip.medlar").exists()); + assert_eq!(store.parts(id).unwrap(), []); + relocate(&store, id, None, Some("c"), &GO).unwrap(); + assert_eq!(store.task(id).unwrap().name, "c"); + } + + #[test] + fn the_bin_takes_only_its_own() { + let (dir, store, id) = bench(vec![]); + let d = dir.path(); + let trash = Bin::at(d.join("Trash")); + fs::write(d.join("a.zip"), "mine").unwrap(); + assert_eq!(bin(&store, id, &trash).unwrap(), None, "never started: not its file"); + store.save_parts(id, vec![HALF]).unwrap(); + assert_eq!(bin(&store, id, &trash).unwrap(), None); + store.save_parts(id, vec![WHOLE]).unwrap(); + let binned = bin(&store, id, &trash).unwrap().unwrap(); + fs::write(d.join("a.zip"), "new").unwrap(); + unbin(&store, id, &binned).unwrap(); + assert_eq!(store.task(id).unwrap().name, "a (1).zip"); + assert_eq!(fs::read(d.join("a (1).zip")).unwrap(), b"mine"); + } + + #[test] + fn copies_to_another_filesystem() { + let (dir, store, id) = bench(vec![WHOLE]); + let Ok(other) = tempfile::tempdir_in("/dev/shm") else { return }; + let from = dir.path().join("a.zip"); + fs::write(&from, "data").unwrap(); + assert!(copy(&from, &other.path().join("h"), &other.path().join("t"), &AtomicBool::new(true)).is_err()); + assert_eq!(fs::read_dir(other.path()).unwrap().count(), 0, "a cancelled copy leaves nothing"); + relocate(&store, id, Some(other.path()), None, &GO).unwrap(); + assert!(!from.exists()); + assert_eq!(fs::read(other.path().join("a.zip")).unwrap(), b"data"); + assert_eq!(fs::read_dir(other.path()).unwrap().count(), 1); + copy(&other.path().join("a.zip"), &dir.path().join("h"), &dir.path().join("t"), &GO).unwrap(); + assert_eq!(fs::read(dir.path().join("t")).unwrap(), b"data"); + } +} diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs new file mode 100644 index 0000000..e5aa68d --- /dev/null +++ b/crates/core/src/manager/mod.rs @@ -0,0 +1,242 @@ +//! All downloads and what can be done with them: the one way in for the window, the command line and the local port. +//! +//! One thread owns the list. Commands are sent to it and never wait; `snapshot` is read without a lock. + +mod actor; +mod bin; +mod files; +mod pick; + +pub use bin::Bin; + +use crate::events::Event; +use crate::http::{Options, Shared}; +use crate::model::{Task, TaskId}; +use crate::settings::Limits; +use crate::snapshot::Snapshot; +use crate::{store, tr}; +use arc_swap::ArcSwap; +use std::fmt; +use std::future::Future; +use std::io; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::{Arc, Mutex, mpsc}; +use std::task::{Context, Poll, ready}; +use std::thread::JoinHandle; +use std::time::Duration; +use tokio::sync::{broadcast, oneshot}; + +#[derive(Debug)] +pub enum Error { + Store(store::Error), + /// Not a name a file can have. + Name, + /// Not a full path. + Folder, + File(io::Error), + Bin(io::Error), + /// Medlar is closing. + Closed, +} + +pub type Result = std::result::Result; + +impl From for Error { + fn from(e: store::Error) -> Error { + Error::Store(e) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&match self { + Error::Store(e) => return e.fmt(f), + Error::Name => tr!("manager.name"), + Error::Folder => tr!("manager.folder"), + Error::File(e) => tr!("manager.file", why = e), + Error::Bin(e) => tr!("manager.bin", why = e), + Error::Closed => tr!("manager.closed"), + }) + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Files { + Keep, + /// Finished or not, to the desktop's bin. + Bin, +} + +/// Each is fine in any state: what makes no sense there changes nothing, and twice is the same as once. +pub enum Command { + /// Appends it to its queue. `state` may be queued (runs when there is room), waiting or paused; the manager fills in the + /// id, the position (unless given) and all that is learned from the server. + Add(Box), + /// Runs it now, before all others. The one that has to give way for it waits in its place. + Start(TaskId), + /// Keeps everything it has. + Pause(TaskId), + /// Back in line, also after a failure. + Resume(TaskId), + /// Pauses it and puts it last. + Stop(TaskId), + /// Can be undone for `Config::undo`, and until the program ends. + Remove { id: TaskId, files: Files }, + /// Undoes the removal, binned files included. + Restore(TaskId), + /// From the start, as a new file. A finished one stays where it is. + Redownload(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. + Rename { id: TaskId, name: String }, + /// Changes what the user decides: link, mirrors, queue, position, priority, limits, headers, notes and the like. + /// Changes of other fields are dropped. + Edit { id: TaskId, edit: Box }, +} + +impl Command { + fn id(&self) -> Option { + use Command::*; + match self { + Add(_) => None, + Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) => Some(*id), + Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } => Some(*id), + } + } +} + +/// The answer to a command, when the snapshot shows what it did. Needn't be looked at. +#[derive(Debug)] +#[must_use = "errors come only this way; drop it to ignore them"] +pub struct Reply(oneshot::Receiver>); + +impl Reply { + /// None while there is no answer. Never waits; ask no more after the answer. + pub fn try_get(&mut self) -> Option> { + match self.0.try_recv() { + Ok(result) => Some(result), + Err(oneshot::error::TryRecvError::Empty) => None, + Err(oneshot::error::TryRecvError::Closed) => Some(Err(Error::Closed)), + } + } + + /// Not for the thread of the window, nor inside async code. + pub fn wait(self) -> Result { + self.0.blocking_recv().unwrap_or(Err(Error::Closed)) + } +} + +impl Future for Reply { + type Output = Result; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + Poll::Ready(ready!(Pin::new(&mut self.0).poll(cx)).unwrap_or(Err(Error::Closed))) + } +} + +pub struct Config { + pub shared: Shared, + pub options: Options, + pub limits: Limits, + pub bin: Bin, + /// How long a removal can be undone. + pub undo: Duration, + /// How often the snapshot follows running downloads. + pub tick: Duration, +} + +impl Config { + pub fn new(shared: Shared, limits: Limits) -> Config { + Config { + shared, + options: Options::default(), + limits, + bin: Bin::default(), + undo: Duration::from_secs(60), + tick: Duration::from_millis(100), + } + } +} + +type Answer = oneshot::Sender>; + +enum Msg { + Command(Command, Option), + Limits(Limits), + OnChange(Box), + /// A download ended. + Ended(TaskId, std::result::Result), + /// File work ended. + Worked(TaskId, Result), + Close, +} + +/// Share it in an `Arc`. Dropping it closes it. +pub struct Manager { + to: mpsc::Sender, + shot: Arc>, + events: broadcast::Sender, + thread: Mutex>>, +} + +impl Manager { + /// Takes up what was running when the program ended. Reads the whole list: not for the thread of the window. + pub fn open(config: Config) -> Result { + let (to, inbox) = mpsc::channel(); + let (events, _) = broadcast::channel(4096); + let shot = Arc::new(ArcSwap::from_pointee(Snapshot::default())); + let actor = actor::Actor::new(config, to.clone(), shot.clone(), events.clone())?; + let thread = std::thread::Builder::new().name("manager".into()).spawn(move || actor.run(inbox)).map_err(Error::File)?; + Ok(Manager { to, shot, events, thread: Mutex::new(Some(thread)) }) + } + + /// Never waits. + pub fn send(&self, command: Command) -> Reply { + let (answer, reply) = oneshot::channel(); + // When the thread is gone the answer is dropped, which says so. + let _ = self.to.send(Msg::Command(command, Some(answer))); + Reply(reply) + } + + /// Takes effect at once, also on running downloads. 0 is no limit. The speed is not its business. + pub fn set_limits(&self, limits: Limits) { + let _ = self.to.send(Msg::Limits(limits)); + } + + /// The list of this moment. Never waits. + pub fn snapshot(&self) -> Arc { + self.shot.load_full() + } + + /// Called from the manager's thread after each new snapshot: at most every tick, and after commands. Must be quick. + pub fn on_change(&self, call: impl Fn() + Send + 'static) { + let _ = self.to.send(Msg::OnChange(Box::new(call))); + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } + + /// Stops everything, saves it and takes no more commands. Doesn't wait; `close` does. What ran goes on at the next start. + pub fn begin_close(&self) { + let _ = self.to.send(Msg::Close); + } + + /// Closes and waits for the end, at most two seconds. + pub fn close(&self) { + self.begin_close(); + if let Some(thread) = self.thread.lock().unwrap_or_else(|e| e.into_inner()).take() { + let _ = thread.join(); + } + } +} + +impl Drop for Manager { + fn drop(&mut self) { + self.close(); + } +} diff --git a/crates/core/src/manager/pick.rs b/crates/core/src/manager/pick.rs new file mode 100644 index 0000000..c0982ca --- /dev/null +++ b/crates/core/src/manager/pick.rs @@ -0,0 +1,98 @@ +//! Which downloads run. + +use crate::model::{Priority, TaskId}; +use std::cmp::Reverse; +use std::collections::HashMap; + +/// A download that runs or could. +#[derive(Debug, Clone, PartialEq)] +pub struct Candidate<'a> { + pub id: TaskId, + pub host: &'a str, + pub priority: Priority, + /// When the user asked to start it now; 0 for never. The latest goes first. + pub forced: u64, + pub running: bool, + /// Stopping it would throw away what it has. + pub pinned: bool, + /// Place of its queue, and its place there. + pub order: (f64, f64), +} + +/// 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. +pub fn pick(mut candidates: Vec, max: usize, mut host_cap: impl FnMut(&str) -> 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)); + } + candidates.sort_by(|a, b| { + let rank = |c: &Candidate| (Reverse(pinned(c)), Reverse(c.forced), Reverse(c.priority as u8), Reverse(c.running)); + let order = |c: &Candidate, d: &Candidate| c.order.0.total_cmp(&d.order.0).then(c.order.1.total_cmp(&d.order.1)); + 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 picked = vec![]; + for c in &candidates { + if picked.len() >= max { + break; + } + let room = room.entry(c.host).or_insert_with(|| host_cap(c.host).max(1)); + if *room > 0 { + *room -= 1; + picked.push(c.id); + } + } + picked +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c(id: TaskId) -> Candidate<'static> { + Candidate { id, host: "h", priority: Priority::Normal, forced: 0, running: false, pinned: false, order: (0.0, id as f64) } + } + + fn picked(candidates: &[Candidate], max: usize) -> Vec { + pick(candidates.to_vec(), max, |_| 9) + } + + #[test] + fn order_then_priority_then_force() { + let mut all = vec![c(1), c(2), c(3), c(4)]; + assert_eq!(picked(&all, 2), [1, 2]); + all[0].order.0 = 1.0; + assert_eq!(picked(&all, 2), [2, 3], "its queue comes later"); + all[3].priority = Priority::High; + all[2].priority = Priority::Low; + assert_eq!(picked(&all, 9), [4, 2, 1, 3]); + all[2].forced = 1; + all[0].forced = 2; + assert_eq!(picked(&all, 3), [1, 3, 4]); + assert!(picked(&all, 0).is_empty()); + } + + #[test] + fn running_ones_keep_their_place() { + let mut all = vec![c(1), c(2), c(3)]; + all[2].running = true; + assert_eq!(picked(&all, 1), [3]); + all[0].priority = Priority::High; + assert_eq!(picked(&all, 1), [1]); + all[2].pinned = true; + assert_eq!(picked(&all, 1), [3]); + all[1].priority = Priority::Only; + assert_eq!(picked(&all, 9), [3, 2]); + all[2].pinned = false; + assert_eq!(picked(&all, 9), [2]); + } + + #[test] + 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"); + } +} diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs new file mode 100644 index 0000000..51f26a2 --- /dev/null +++ b/crates/core/src/snapshot.rs @@ -0,0 +1,225 @@ +//! The download list as everyone but the manager sees it. Never changes; a newer one shares all that stayed the same. + +use crate::http::PartView; +use crate::model::{State, Task, TaskId, Time}; +use crate::speed::History; +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::Duration; + +/// One download. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskView { + /// As the store has it. Size and downloaded bytes are better taken from here. + pub task: Arc, + /// The revision of the snapshot that last changed it. + pub rev: u64, + pub size: Option, + pub downloaded: u64, + /// Bytes per second. + pub speed: f64, + pub left: Option, + /// In the order of the file. Empty before the first reply, and for finished downloads. + pub parts: Arc<[PartView]>, + /// Connections now, and how many the download wants. + pub connections: u32, + pub wanted: u32, + /// None until known. + pub resumable: Option, + /// Share of the file that was compared with its checksum, 0 to 1. + pub checked: f32, + /// Name and port of the host in its link. + pub server: Arc, + pub history: Arc, + pub log: Arc, + pub counters: Counters, +} + +impl TaskView { + pub fn id(&self) -> TaskId { + self.task.id + } + + pub fn state(&self) -> State { + self.task.state + } + + /// Share of the file that is here, 0 to 1. None when the size is unknown. + pub fn progress(&self) -> Option { + match (self.task.state, self.size?) { + (State::Done, _) => Some(1.0), + (_, 0) => Some(0.0), + (_, size) => Some((self.downloaded as f64 / size as f64).min(1.0) as f32), + } + } +} + +/// Since the program started. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counters { + /// Bytes from the network, also those that were thrown away later. + pub received: u64, + /// Time spent downloading. + pub active: Duration, + pub runs: u32, + pub finished: u32, + pub failed: u32, +} + +/// The newest lines of a task's log, the newest last. Free of secrets. +pub type Log = VecDeque; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Line { + pub at: Time, + pub text: Arc, +} + +/// All downloads together. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Totals { + pub running: usize, + /// Ready, but without a place. + pub queued: usize, + /// Bytes per second. + pub speed: f64, + pub connections: u32, + pub history: Arc, + pub counters: Counters, +} + +const CHUNK: usize = 128; + +#[derive(Debug, Clone, Default)] +pub struct Snapshot { + /// Goes up with each change. + pub rev: u64, + pub totals: Totals, + /// By id, never empty, at most `CHUNK` long. + chunks: Vec>>>, + len: usize, +} + +impl Snapshot { + /// In the order of their ids, which is the order in which they were added. + pub fn iter(&self) -> impl DoubleEndedIterator> { + self.chunks.iter().flat_map(|c| c.iter()) + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn get(&self, id: TaskId) -> Option<&Arc> { + let chunk = self.chunks.get(self.chunk_of(id))?; + Some(&chunk[chunk.binary_search_by_key(&id, |v| v.id()).ok()?]) + } + + /// What changed after revision `rev`. Removed ones are missing from `get`. + pub fn changed_since(&self, rev: u64) -> impl Iterator> { + self.iter().filter(move |v| v.rev > rev) + } + + /// The chunk that holds `id`, or would. + fn chunk_of(&self, id: TaskId) -> usize { + self.chunks.partition_point(|c| c[0].id() <= id).saturating_sub(1) + } + + pub(crate) fn put(&mut self, view: TaskView) { + let (id, at) = (view.id(), self.chunk_of(view.id())); + let view = Arc::new(view); + let Some(chunk) = self.chunks.get_mut(at) else { + self.chunks.push(Arc::new(vec![view])); + self.len += 1; + return; + }; + let chunk = Arc::make_mut(chunk); + match chunk.binary_search_by_key(&id, |v| v.id()) { + Ok(i) => chunk[i] = view, + Err(i) => { + chunk.insert(i, view); + self.len += 1; + if chunk.len() > CHUNK { + // New ones come at the end: leave the chunk before it full. + let keep = if i == CHUNK { CHUNK } else { CHUNK / 2 }; + let rest = chunk.split_off(keep); + self.chunks.insert(at + 1, Arc::new(rest)); + } + } + } + } + + pub(crate) fn remove(&mut self, id: TaskId) { + let at = self.chunk_of(id); + let Some(chunk) = self.chunks.get_mut(at) else { return }; + let Ok(i) = chunk.binary_search_by_key(&id, |v| v.id()) else { return }; + Arc::make_mut(chunk).remove(i); + self.len -= 1; + if self.chunks[at].is_empty() { + self.chunks.remove(at); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn view(id: TaskId, rev: u64) -> TaskView { + TaskView { + task: Arc::new(Task { id, ..Task::default() }), + rev, + size: None, + downloaded: 0, + speed: 0.0, + left: None, + parts: Arc::new([]), + connections: 0, + wanted: 0, + resumable: None, + checked: 0.0, + server: "".into(), + history: Arc::default(), + log: Arc::default(), + counters: Counters::default(), + } + } + + #[test] + fn any_order_of_changes() { + let mut shot = Snapshot::default(); + let mut known = std::collections::BTreeMap::new(); + for step in 0..20_000 { + let id = fastrand::i64(1..1500); + if fastrand::u8(..) < 100 { + shot.remove(id); + known.remove(&id); + } else { + shot.put(view(id, step)); + known.insert(id, step); + } + } + assert!(shot.iter().map(|v| (v.id(), v.rev)).eq(known.iter().map(|(id, rev)| (*id, *rev)))); + assert_eq!(shot.len(), known.len()); + assert!((0..1501).all(|id| shot.get(id).map(|v| v.rev) == known.get(&id).copied())); + assert!(shot.chunks.iter().all(|c| (1..=CHUNK).contains(&c.len()))); + } + + #[test] + fn unchanged_ones_are_shared() { + let mut shot = Snapshot::default(); + (0..10_000).for_each(|id| shot.put(view(id, 1))); + assert_eq!(shot.chunks.len(), 10_000usize.div_ceil(CHUNK)); + let old = shot.clone(); + shot.put(view(5000, 2)); + let same = shot.chunks.iter().zip(&old.chunks).filter(|(a, b)| Arc::ptr_eq(a, b)).count(); + assert_eq!(same, shot.chunks.len() - 1); + assert_eq!(shot.iter().zip(old.iter()).filter(|(a, b)| !Arc::ptr_eq(a, b)).count(), 1); + assert_eq!(shot.changed_since(1).map(|v| v.id()).collect::>(), [5000]); + assert_eq!(old.get(5000).unwrap().rev, 1); + } +} diff --git a/crates/core/src/speed.rs b/crates/core/src/speed.rs new file mode 100644 index 0000000..7c11787 --- /dev/null +++ b/crates/core/src/speed.rs @@ -0,0 +1,202 @@ +//! Speeds and times left that are calm enough to read, and speeds second by second. + +use std::collections::VecDeque; +use std::time::Duration; + +/// Seconds that `Meter::speed` looks back, roughly. +const SPEED: f64 = 2.5; +/// The same for the time left. +const LEFT: f64 = 12.0; +/// Seconds in which the time left takes over most of a new estimate. +const SETTLE: f64 = 4.0; +/// The time left is first told after this many seconds of data. +const LEFT_FROM: f64 = 2.0; +/// Estimates closer to the last one than this share are left alone. +const CLOSE: f64 = 0.04; +/// No time left without data for this many seconds, or beyond the limit. +const QUIET: f64 = 10.0; +const FOREVER: f64 = 99.0 * 86_400.0; + +/// Mean that forgets. The first moments count in full, so that it starts at the right height. +#[derive(Debug, Clone, Default)] +struct Average { + sum: f64, + weight: f64, +} + +impl Average { + fn push(&mut self, rate: f64, dt: f64, memory: f64) { + let share = 1.0 - (-dt / memory).exp(); + self.sum += (rate - self.sum) * share; + self.weight += (1.0 - self.weight) * share; + } + + fn get(&self) -> f64 { + if self.weight > 0.0 { self.sum / self.weight } else { 0.0 } + } +} + +/// Feed it what arrived since the last time, again and again. +#[derive(Debug, Clone, Default)] +pub struct Meter { + fast: Average, + slow: Average, + /// Seconds with data, and since there was any. + seen: f64, + quiet: f64, + left: Option, +} + +impl Meter { + /// `remaining` is None when the size is unknown. + pub fn push(&mut self, bytes: u64, dt: Duration, remaining: Option) { + let dt = dt.as_secs_f64(); + // Connecting is not slowness. + if dt <= 0.0 || (self.seen == 0.0 && bytes == 0) { + return; + } + let rate = bytes as f64 / dt; + self.fast.push(rate, dt, SPEED); + self.slow.push(rate, dt, LEFT); + self.seen += dt; + self.quiet = if bytes == 0 { self.quiet + dt } else { 0.0 }; + self.left = self.next_left(dt, remaining); + } + + fn next_left(&self, dt: f64, remaining: Option) -> Option { + let estimate = remaining? as f64 / self.slow.get(); + if self.seen < LEFT_FROM || self.quiet >= QUIET || estimate.is_nan() || estimate > FOREVER { + return None; + } + let Some(left) = self.left else { return Some(estimate) }; + let left = (left - dt).max(0.0); + let off = estimate - left; + if off.abs() <= CLOSE * estimate { + return Some(left); + } + Some(left + off * (1.0 - (-dt / SETTLE).exp())) + } + + /// Bytes per second. 0 when nothing came for a while. + pub fn speed(&self) -> f64 { + if self.quiet >= QUIET { 0.0 } else { self.fast.get() } + } + + pub fn left(&self) -> Option { + self.left.map(Duration::from_secs_f64) + } +} + +/// Bytes per second of the last seconds, one sample each, the newest last. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct History { + samples: VecDeque, + pushed: u64, +} + +impl History { + /// Seconds kept. + pub const ROOM: usize = 300; + + pub fn push(&mut self, bytes_per_second: f64) { + if self.samples.len() == Self::ROOM { + self.samples.pop_front(); + } + self.samples.push_back(bytes_per_second as f32); + self.pushed += 1; + } + + /// Seconds in which nothing arrived. + pub fn skip(&mut self, seconds: u64) { + for _ in 0..seconds.min(Self::ROOM as u64) { + self.push(0.0); + } + self.pushed += seconds.saturating_sub(Self::ROOM as u64); + } + + pub fn samples(&self) -> impl ExactSizeIterator + '_ { + self.samples.iter().copied() + } + + /// Samples ever pushed: how many are new to a reader that remembers this number. + pub fn pushed(&self) -> u64 { + self.pushed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TICK: Duration = Duration::from_millis(100); + + /// Feeds bytes per second by tick and returns (speed, left) after each. + fn feed(meter: &mut Meter, remaining: &mut u64, rates: impl Iterator) -> Vec<(f64, Option)> { + rates + .map(|rate| { + let bytes = (rate * TICK.as_secs_f64()) as u64; + *remaining -= bytes; + meter.push(bytes, TICK, Some(*remaining)); + (meter.speed(), meter.left().map(|l| l.as_secs_f64())) + }) + .collect() + } + + #[test] + fn starts_at_the_right_height() { + let (mut m, mut rest) = (Meter::default(), 100_000_000); + for _ in 0..50 { + m.push(0, TICK, Some(rest)); + } + assert_eq!((m.speed(), m.left()), (0.0, None)); + let seen = feed(&mut m, &mut rest, std::iter::repeat_n(1e6, 30)); + assert!(seen.iter().all(|(s, _)| (s - 1e6).abs() < 1.0)); + assert_eq!(seen[10].1, None, "too early to tell"); + assert!((seen[29].1.unwrap() - 97.0).abs() < 1.0); + } + + #[test] + fn bursts_do_not_shake_it() { + let (mut m, mut rest) = (Meter::default(), 100_000_000); + // Half a second of everything, half a second of nothing. + let seen = feed(&mut m, &mut rest, (0..600).map(|i| if i / 5 % 2 == 0 { 2e6 } else { 0.0 })); + for w in seen[50..].windows(2) { + assert!((w[1].0 - 1e6).abs() < 0.2e6, "speed {}", w[1].0); + let (a, b) = (w[0].1.unwrap(), w[1].1.unwrap()); + assert!(b <= a + 0.05 && a - b < 0.6, "left {a} to {b}"); + } + } + + #[test] + fn a_real_change_shows_soon_and_smoothly() { + let (mut m, mut rest) = (Meter::default(), 100_000_000); + feed(&mut m, &mut rest, std::iter::repeat_n(1e6, 200)); + let seen = feed(&mut m, &mut rest, std::iter::repeat_n(0.25e6, 600)); + assert!(seen[60].0 < 0.4e6, "speed after 6 s: {}", seen[60].0); + for w in seen.windows(2) { + let (a, b) = (w[0].1.unwrap(), w[1].1.unwrap()); + assert!((b - a).abs() < a * 0.02 + 0.2, "left {a} to {b}"); + } + let (truth, told) = (rest as f64 / 0.25e6, seen[599].1.unwrap()); + assert!((truth - told).abs() < truth * 0.06, "{truth} {told}"); + } + + #[test] + fn silence_ends_the_estimate() { + let (mut m, mut rest) = (Meter::default(), 100_000_000); + feed(&mut m, &mut rest, std::iter::repeat_n(1e6, 100)); + feed(&mut m, &mut rest, std::iter::repeat_n(0.0, 101)); + assert_eq!((m.speed(), m.left()), (0.0, None)); + m.push(100, TICK, None); + assert!(m.speed() > 0.0 && m.left().is_none()); + } + + #[test] + fn the_ring_keeps_the_newest() { + let mut h = History::default(); + (0..400).for_each(|i| h.push(f64::from(i))); + assert_eq!((h.samples().len(), h.samples().next(), h.samples().last(), h.pushed()), (300, Some(100.0), Some(399.0), 400)); + h.skip(1000); + assert_eq!((h.samples().len(), h.samples().next(), h.pushed()), (300, Some(0.0), 1400)); + } +} diff --git a/crates/core/src/store/mod.rs b/crates/core/src/store/mod.rs index 3c16b8b..ee3d917 100644 --- a/crates/core/src/store/mod.rs +++ b/crates/core/src/store/mod.rs @@ -8,6 +8,7 @@ mod rows; use crate::model::*; use crate::{redact, strings, tr}; use rusqlite::{Connection, OptionalExtension, Transaction, params}; +use std::collections::HashSet; use std::fmt; use std::path::Path; use std::sync::{Mutex, mpsc}; @@ -115,6 +116,21 @@ impl Store { }) } + /// Changes a task in one step, so that nobody else's change gets lost. State and error stay as they are. Returns the result. + pub fn edit_task(&self, id: TaskId, edit: impl FnOnce(&mut Task) + Send + 'static) -> Result { + self.write(move |tx| { + let old = rows::tasks(tx, "WHERE id = ?", [id])?.pop().ok_or(Error::NotFound)?; + let (state, error) = (old.state, old.error.clone()); + let mut task = old; + edit(&mut task); + (task.id, task.state, task.error) = (id, state, error); + refuse_secrets(&task)?; + rows::update_task(tx, &task)?; + rows::set_tags(tx, id, &task.tags)?; + Ok(task) + }) + } + /// Moves a task to another state, if the model allows it. The error is replaced; None clears it. pub fn set_state(&self, id: TaskId, to: State, error: Option) -> Result<()> { self.write(move |tx| { @@ -148,6 +164,11 @@ impl Store { self.read(|c| rows::tasks(c, "ORDER BY queue, position, id", [])) } + /// Names that unfinished tasks in a folder have taken, removed ones included. + pub fn used_names(&self, folder: &Path, except: TaskId) -> Result> { + self.read(|c| rows::used_names(c, folder, except)) + } + /// Replaces the parts of a task and its `downloaded`, without waiting. A failure is logged; the next save repairs it. pub fn post_parts(&self, task: TaskId, parts: Vec) -> Result<()> { self.send(Box::new(move |conn| { diff --git a/crates/core/src/store/rows.rs b/crates/core/src/store/rows.rs index cad6fc4..3bc4c3b 100644 --- a/crates/core/src/store/rows.rs +++ b/crates/core/src/store/rows.rs @@ -3,6 +3,7 @@ use super::{Error, Result}; use crate::model::*; use rusqlite::{Connection, OptionalExtension, Params, Row, ToSql, named_params, params}; +use std::collections::HashSet; use std::ffi::OsString; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; @@ -132,6 +133,13 @@ fn task(r: &Row) -> Result { }) } +pub fn used_names(c: &Connection, folder: &Path, except: TaskId) -> Result> { + let sql = "SELECT name FROM tasks WHERE folder = ? AND id <> ? AND name <> '' AND state NOT IN ('done', 'gone')"; + let mut stmt = c.prepare_cached(sql)?; + let rows = stmt.query_map(params![path_bytes(folder), except], |r| r.get(0))?; + Ok(rows.collect::>()?) +} + pub fn set_parts(c: &Connection, task: TaskId, parts: &[Part]) -> Result<()> { c.execute("DELETE FROM parts WHERE task = ?", [task])?; let mut insert = c.prepare_cached("INSERT INTO parts (task, start, end, done) VALUES (?, ?, ?, ?)")?; diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index 56fb405..005073c 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -337,7 +337,7 @@ async fn one_part(b: &Bench, path: &str, done: u64) -> (Result<()>, Vec, Par let source = Source::new(&b.server.url(path)).unwrap(); let p = probe(&b.client, &source, &mut stop).await.unwrap(); let link = Link { client: b.client.clone(), source, ranges: true, version: p.version }; - let (file, name) = PartialFile::create(&b.folder(), "part").unwrap(); + let (file, name) = PartialFile::create(&b.folder(), "part", &Default::default()).unwrap(); std::fs::write(partial_path(&b.folder(), &name), vec![0; 200_000]).unwrap(); let part = LivePart::new(Part { start: 100_000, end: Some(200_000), done: 0 }); if done > 0 { diff --git a/crates/core/tests/manager.rs b/crates/core/tests/manager.rs new file mode 100644 index 0000000..77d8780 --- /dev/null +++ b/crates/core/tests/manager.rs @@ -0,0 +1,634 @@ +//! The list of downloads: commands in any state, who runs, what is seen of it, and the way out and back in. + +use medlar_core::adapt::Timing; +use medlar_core::events::Event; +use medlar_core::host::{self, Caps, Hosts}; +use medlar_core::http::{ClientOptions, Options, Shared, client}; +use medlar_core::manager::*; +use medlar_core::model::*; +use medlar_core::segment::Rules; +use medlar_core::settings::Limits; +use medlar_core::snapshot::{Snapshot, TaskView}; +use medlar_core::store::{self, Store}; +use medlar_testserver::{Faults, TestServer, expected}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; +use tokio::sync::broadcast::error::TryRecvError; +use tokio::time::sleep; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +const LIMITS: Limits = Limits { speed: 0, max_active: 2, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + +fn config(dir: &Path, limits: Limits) -> Config { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap(); + let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }); + let options = Options { + rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) }, + timing: Timing { settle: ms(200), window: ms(600), hold: ms(2000), refused: ms(60_000) }, + tick: ms(25), + stall: ms(1000), + patience: ms(500), + tries: 2, + backoff: ms(20), + max_wait: ms(2000), + checkpoint: ms(50), + }; + let mut config = Config::new(Shared { client, store, hosts }, limits); + (config.options, config.bin, config.tick) = (options, Bin::at(dir.join("Trash")), ms(20)); + config +} + +struct Bench { + server: TestServer, + dir: tempfile::TempDir, + store: Arc, + manager: Manager, +} + +impl Bench { + async fn new(limits: Limits) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path(), limits); + let store = config.shared.store.clone(); + Bench { server: TestServer::start().await, dir, store, manager: Manager::open(config).unwrap() } + } + + /// Ends the program and starts it again. + fn restart(self, limits: Limits) -> Bench { + let Bench { server, dir, store, manager } = self; + drop((manager, store)); + let config = config(dir.path(), limits); + Bench { server, store: config.shared.store.clone(), manager: Manager::open(config).unwrap(), dir } + } + + fn files(&self) -> PathBuf { + self.dir.path().join("files") + } + + fn task(&self, path: &str) -> Task { + Task { url: self.server.url(path), folder: self.files(), ..Task::default() } + } + + async fn add(&self, path: &str) -> TaskId { + self.manager.send(Command::Add(Box::new(self.task(path)))).await.unwrap() + } + + /// A file that takes several seconds. + fn slow(&self, seed: u64) -> String { + let path = TestServer::data_path(seed, 1 << 20); + self.server.set_faults(&path, Faults { throttle_conn: Some(20_000), ..Faults::default() }); + path + } + + async fn run(&self, command: Command) { + self.manager.send(command).await.unwrap(); + } + + fn view(&self, id: TaskId) -> Arc { + self.manager.snapshot().get(id).unwrap_or_else(|| panic!("{id} is not in the list")).clone() + } + + fn states(&self) -> Vec { + self.manager.snapshot().iter().map(|v| v.state()).collect() + } + + async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) { + let end = Instant::now() + Duration::from_secs(20); + while !is(&self.manager.snapshot()) { + let states: Vec<_> = self.manager.snapshot().iter().map(|v| (v.id(), v.state(), v.task.error.clone())).collect(); + assert!(Instant::now() < end, "never {what}: {states:?}"); + sleep(ms(5)).await; + } + } + + async fn until_state(&self, id: TaskId, state: State) { + self.until(state.name(), |s| s.get(id).is_some_and(|v| v.state() == state)).await; + } + + async fn until_bytes(&self, id: TaskId) { + self.until("under way", |s| s.get(id).is_some_and(|v| v.downloaded > 0 && v.state() == State::Running)).await; + } + + fn check(&self, id: TaskId, seed: u64, len: usize) { + let task = self.view(id).task.clone(); + let (is, should) = (std::fs::read(task.folder.join(&task.name)), expected(seed, 0, len)); + let is = is.unwrap_or_else(|e| panic!("{e}: {task:?}, {:#?}", self.view(id).log)); + let same = is.iter().zip(&should).take_while(|(a, b)| a == b).count(); + assert!(is == should, "{} bytes, right until {same}: {task:?}, {:#?}", is.len(), self.view(id).log); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_life() { + let b = Bench::new(LIMITS).await; + let mut events = b.manager.subscribe(); + let called = Arc::new(AtomicUsize::new(0)); + let calls = called.clone(); + b.manager.on_change(move || { + calls.fetch_add(1, Ordering::Relaxed); + }); + let id = b.add(&b.slow(1)).await; + assert_eq!(b.view(id).state(), State::Running, "the answer comes after the snapshot"); + b.until_bytes(id).await; + let v = b.view(id); + assert_eq!((v.size, v.task.name.is_empty(), v.resumable, &*v.server), (Some(1 << 20), false, Some(true), &*host::key(&v.task.url.parse().unwrap()))); + assert_eq!(v.parts.iter().map(|p| p.done).sum::(), v.downloaded); + for _ in 0..2 { + b.run(Command::Pause(id)).await; + assert_eq!(b.view(id).state(), State::Paused); + } + b.until("quiet", |s| s.get(id).unwrap().connections == 0 && s.totals.speed == 0.0).await; + let v = b.view(id); + assert!(v.downloaded > 0 && !v.parts.is_empty() && v.speed == 0.0 && v.left.is_none()); + b.server.clear_all_faults(); + for _ in 0..2 { + b.run(Command::Resume(id)).await; + } + b.until_state(id, State::Done).await; + b.check(id, 1, 1 << 20); + let v = b.view(id); + assert_eq!((v.progress(), v.parts.len(), v.counters.runs, v.counters.finished), (Some(1.0), 0, 2, 1)); + assert!(v.counters.received >= 1 << 20 && v.task.finished_at.is_some()); + assert_eq!(b.manager.snapshot().totals.counters, v.counters); + for command in [Command::Pause(id), Command::Resume(id), Command::Start(id), Command::Stop(id), Command::Restore(id)] { + b.run(command).await; + assert_eq!(b.view(id).state(), State::Done); + } + use State::*; + let mut seen = vec![]; + while let Ok(e) = events.try_recv() { + seen.push(e); + } + let state = |from, to| Event::State { id, from, to }; + let way = [ + Event::Added(id), + state(Queued, Running), + state(Running, Paused), + state(Paused, Queued), + state(Queued, Running), + state(Running, Finishing), + state(Finishing, Done), + ]; + assert_eq!(seen, way); + assert!(called.load(Ordering::Relaxed) > 5); + assert!(matches!(b.manager.send(Command::Pause(99)).await, Err(Error::Store(store::Error::NotFound)))); + let bad = Task { folder: "relative".into(), ..b.task("/x") }; + assert!(matches!(b.manager.send(Command::Add(Box::new(bad))).await, Err(Error::Folder))); + // Nothing runs: the list stays as it is. + let rev = b.manager.snapshot().rev; + sleep(ms(1300)).await; + let still = b.manager.snapshot(); + sleep(ms(300)).await; + assert!(Arc::ptr_eq(&still, &b.manager.snapshot()) && still.rev <= rev + 3, "{rev} to {}", still.rev); +} + +#[tokio::test(flavor = "multi_thread")] +async fn who_runs() { + use State::*; + let b = Bench::new(LIMITS).await; + let mut ids = vec![]; + for seed in 1..=4 { + ids.push(b.add(&b.slow(seed)).await); + } + assert_eq!(b.states(), [Running, Running, Queued, Queued]); + let totals = b.manager.snapshot().totals.clone(); + assert_eq!((totals.running, totals.queued), (2, 2)); + // A higher priority takes a place; the last in line gives way. + b.run(Command::Edit { id: ids[3], edit: Box::new(|t| t.priority = Priority::High) }).await; + assert_eq!(b.states(), [Running, Queued, Queued, Running]); + b.run(Command::Start(ids[2])).await; + b.until("started", |s| s.get(ids[2]).unwrap().state() == Running).await; + assert_eq!(b.states(), [Queued, Queued, Running, Running]); + b.run(Command::Stop(ids[2])).await; + b.until("next", |s| s.totals.running == 2).await; + b.run(Command::Resume(ids[2])).await; + assert_eq!(b.states(), [Running, Queued, Queued, Running]); + assert!(b.view(ids[2]).task.position > b.view(ids[3]).task.position); + b.run(Command::Edit { id: ids[1], edit: Box::new(|t| t.priority = Priority::Only) }).await; + b.until("alone", |s| s.get(ids[1]).unwrap().state() == Running).await; + assert_eq!(b.states(), [Queued, Running, Queued, Queued]); + b.run(Command::Edit { id: ids[1], edit: Box::new(|t| (t.priority, t.name) = (Priority::Normal, "not yours".into())) }).await; + assert_ne!(b.view(ids[1]).task.name, "not yours"); + b.manager.set_limits(Limits { max_active: 1, ..LIMITS }); + b.until("one", |s| s.totals.running == 1).await; + b.manager.set_limits(Limits { max_active: 0, ..LIMITS }); + b.until("all", |s| s.totals.running == 4).await; + // One connection is all the host gives: one download. + b.manager.set_limits(Limits { max_active: 0, connections_per_host: 1, ..LIMITS }); + b.until("one of the host", |s| s.totals.running == 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn what_cannot_resume_is_not_stopped_for_others() { + let b = Bench::new(Limits { max_active: 1, ..LIMITS }).await; + let path = TestServer::data_path(1, 1 << 20); + b.server.set_faults(&path, Faults { throttle_conn: Some(400_000), ignore_range: true, ..Faults::default() }); + let one = b.add(&path).await; + b.until_bytes(one).await; + let two = b.add(&TestServer::data_path(2, 1000)).await; + b.run(Command::Edit { id: two, edit: Box::new(|t| t.priority = Priority::Only) }).await; + b.run(Command::Start(two)).await; + assert_eq!(b.states(), [State::Running, State::Queued]); + b.until_state(two, State::Done).await; + b.check(one, 1, 1 << 20); + assert_eq!(b.view(one).counters.runs, 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn names_and_folders_while_it_runs() { + let b = Bench::new(LIMITS).await; + let id = b.add(&b.slow(1)).await; + b.until_bytes(id).await; + let other = b.dir.path().join("other"); + let (a, c) = ( + b.manager.send(Command::Rename { id, name: "../new.bin".into() }), + b.manager.send(Command::Move { id, folder: other.clone() }), + ); + a.await.unwrap(); + c.await.unwrap(); + let task = b.view(id).task.clone(); + assert!(!task.name.contains('/') && task.name.contains("new.bin") && task.folder == other, "{task:?}"); + assert!(other.join(format!("{}.medlar", task.name)).exists()); + assert_eq!(std::fs::read_dir(b.files()).unwrap().count(), 0); + b.until_bytes(id).await; + assert!(b.view(id).downloaded > 0, "it went on"); + let runs = b.view(id).counters.runs; + // Nothing to do, so nothing is interrupted. + b.run(Command::Move { id, folder: other.clone() }).await; + b.run(Command::Rename { id, name: task.name.clone() }).await; + b.run(Command::Restore(id)).await; + for bad in ["", "..", "/"] { + assert!(matches!(b.manager.send(Command::Rename { id, name: bad.into() }).await, Err(Error::Name)), "{bad}"); + } + assert!(matches!(b.manager.send(Command::Move { id, folder: "x".into() }).await, Err(Error::Folder))); + assert_eq!((b.view(id).counters.runs, b.view(id).state()), (runs, State::Running)); + b.server.clear_all_faults(); + b.until_state(id, State::Done).await; + b.run(Command::Rename { id, name: "last.bin".into() }).await; + b.check(id, 1, 1 << 20); + assert_eq!(b.view(id).task.name, "last.bin"); + // From the start, beside the finished one. + b.run(Command::Redownload(id)).await; + b.until("again", |s| s.get(id).unwrap().state() == State::Done && s.get(id).unwrap().counters.finished == 2).await; + assert_eq!(b.view(id).task.name, "last (1).bin"); + b.check(id, 1, 1 << 20); + assert!(other.join("last.bin").exists()); + // And in the middle. + b.slow(1); + b.run(Command::Redownload(id)).await; + b.until_bytes(id).await; + b.server.clear_all_faults(); + b.run(Command::Redownload(id)).await; + b.until("again", |s| s.get(id).unwrap().state() == State::Done && s.get(id).unwrap().counters.finished == 3).await; + b.check(id, 1, 1 << 20); + let left: Vec<_> = std::fs::read_dir(&other).unwrap().map(|f| f.unwrap().file_name()).collect(); + assert_eq!(left.len(), 3, "no halves: {left:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_empty_file_still_belongs_to_its_download() { + let b = Bench::new(LIMITS).await; + let path = TestServer::data_path(1, 1000); + // Stopped right after its file was made. + let one = b.manager.send(Command::Add(Box::new(Task { state: State::Paused, name: "f.bin".into(), ..b.task(&path) }))); + let one = one.await.unwrap(); + b.store.save_parts(one, vec![Part { start: 0, end: Some(1000), done: 0 }]).unwrap(); + std::fs::create_dir_all(b.files()).unwrap(); + std::fs::write(b.files().join("f.bin.medlar"), "").unwrap(); + let two = Task { name: "f.bin".into(), ..b.task(&TestServer::data_path(2, 1000)) }; + let two = b.manager.send(Command::Add(Box::new(two))).await.unwrap(); + b.until_state(two, State::Done).await; + assert_eq!(b.view(two).task.name, "f (1).bin"); + b.run(Command::Resume(one)).await; + b.until_state(one, State::Done).await; + b.check(one, 1, 1000); + b.check(two, 2, 1000); +} + +#[tokio::test(flavor = "multi_thread")] +async fn removed_and_back() { + let b = Bench::new(LIMITS).await; + let trash = b.dir.path().join("Trash/files"); + let id = b.add(&b.slow(1)).await; + b.until_bytes(id).await; + for _ in 0..2 { + b.run(Command::Remove { id, files: Files::Bin }).await; + } + assert!(b.manager.snapshot().is_empty()); + assert_eq!((std::fs::read_dir(b.files()).unwrap().count(), std::fs::read_dir(&trash).unwrap().count()), (0, 1)); + assert!(b.manager.send(Command::Resume(id)).await.is_err()); + b.server.clear_all_faults(); + for _ in 0..2 { + b.run(Command::Restore(id)).await; + } + b.until_state(id, State::Done).await; + b.check(id, 1, 1 << 20); + assert!(b.view(id).counters.received < (1 << 20) + 100_000, "it went on where it was"); + b.run(Command::Remove { id, files: Files::Keep }).await; + b.run(Command::Restore(id)).await; + b.check(id, 1, 1 << 20); + // Quickly one after the other, while it runs. + let two = b.add(&b.slow(2)).await; + b.until_bytes(two).await; + let all = [ + b.manager.send(Command::Remove { id: two, files: Files::Bin }), + b.manager.send(Command::Restore(two)), + b.manager.send(Command::Remove { id: two, files: Files::Keep }), + ]; + for reply in all { + reply.await.unwrap(); + } + assert!(b.manager.snapshot().get(two).is_none()); + // Removals are final after the end of the program. + let b = b.restart(LIMITS); + assert_eq!(b.states(), [State::Done]); + assert!(b.store.task(two).is_err()); + assert!(matches!(b.manager.send(Command::Restore(two)).await, Err(Error::Store(store::Error::NotFound)))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn removals_are_forgotten_after_a_while() { + let dir = tempfile::tempdir().unwrap(); + let mut config = config(dir.path(), LIMITS); + config.undo = ms(100); + let store = config.shared.store.clone(); + let manager = Manager::open(config).unwrap(); + let mut events = manager.subscribe(); + let task = Task { state: State::Paused, folder: dir.path().into(), ..Task::default() }; + let id = manager.send(Command::Add(Box::new(task))).await.unwrap(); + manager.send(Command::Remove { id, files: Files::Keep }).await.unwrap(); + assert!(store.task(id).is_ok()); + let end = Instant::now() + Duration::from_secs(5); + while store.task(id).is_ok() { + assert!(Instant::now() < end); + sleep(ms(10)).await; + } + sleep(ms(50)).await; + manager.send(Command::Remove { id, files: Files::Keep }).await.unwrap(); + assert!(manager.send(Command::Restore(id)).await.is_err()); + assert_eq!([events.try_recv(), events.try_recv(), events.try_recv()], [Ok(Event::Added(id)), Ok(Event::Removed(id)), Ok(Event::Forgotten(id))]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn failures_are_told_without_secrets() { + let b = Bench::new(LIMITS).await; + let path = TestServer::data_path(1, 1000); + b.server.set_faults(&path, Faults::status(404)); + let id = b.add(&format!("{path}?token=S3CRET")).await; + b.until_state(id, State::Failed).await; + let v = b.view(id); + assert!(v.task.error.as_ref().is_some_and(|e| e.detail.contains("404"))); + assert_eq!(v.counters.failed, 1); + let log: Vec<&str> = v.log.iter().map(|l| &*l.text).collect(); + assert!(log.len() >= 4 && log[0].starts_with("Added http") && log.last().unwrap().contains("404"), "{log:?}"); + assert!(!format!("{:?}", v.log).contains("S3CRET")); + b.server.clear_all_faults(); + b.run(Command::Resume(id)).await; + b.until_state(id, State::Done).await; + assert_eq!(b.view(id).task.error, None); + let bad = b.manager.send(Command::Add(Box::new(Task { url: "nonsense".into(), ..b.task("/") }))).await.unwrap(); + assert_eq!(b.view(bad).state(), State::Failed); +} + +#[tokio::test(flavor = "multi_thread")] +async fn closing_is_quick_and_loses_nothing() { + // Enough connections that nobody has to wait for one. + let all = Limits { max_active: 0, max_connections: 0, connections_per_host: 0, ..LIMITS }; + let mut b = Bench::new(all).await; + let mut ids = vec![]; + for seed in 1..=12 { + ids.push(b.add(&b.slow(seed)).await); + } + let paused = b.manager.send(Command::Add(Box::new(Task { state: State::Paused, ..b.task(&b.slow(99)) }))).await.unwrap(); + for id in &ids { + b.until_bytes(*id).await; + } + for round in 0..2 { + let before: u64 = b.manager.snapshot().iter().map(|v| v.downloaded).sum(); + let start = Instant::now(); + b.manager.close(); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); + assert!(matches!(b.manager.send(Command::Pause(ids[0])).await, Err(Error::Closed))); + let kept: u64 = b.store.tasks().unwrap().iter().map(|t| t.downloaded).sum(); + assert!(kept >= before, "round {round}: {kept} of {before}"); + assert!(b.store.tasks().unwrap().iter().all(|t| matches!(t.state, State::Queued | State::Paused))); + b = b.restart(all); + let v = b.view(ids[0]); + assert!(v.downloaded > 0 && !v.parts.is_empty() && v.size == Some(1 << 20)); + b.until("running", |s| s.totals.running == 12).await; + for id in &ids { + b.until_bytes(*id).await; + } + } + b.server.clear_all_faults(); + for (i, id) in ids.iter().enumerate() { + b.until_state(*id, State::Done).await; + b.check(*id, i as u64 + 1, 1 << 20); + } + assert_eq!(b.view(paused).state(), State::Paused); + // Killed in the middle: what was running is taken up. + let id = b.add(&b.slow(50)).await; + b.until_bytes(id).await; + b.manager.close(); + b.store.set_state(id, State::Running, None).unwrap(); + let b = b.restart(LIMITS); + b.until_state(id, State::Running).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_hanging_server_does_not_hold_up_the_end() { + let b = Bench::new(LIMITS).await; + let path = TestServer::data_path(1, 1 << 20); + b.server.set_faults(&path, Faults { latency_ms: Some(60_000), ..Faults::default() }); + b.add(&path).await; + sleep(ms(100)).await; + let start = Instant::now(); + b.manager.close(); + assert!(start.elapsed() < Duration::from_secs(1), "{:?}", start.elapsed()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn ten_thousand() { + let b = Bench::new(LIMITS).await; + b.manager.close(); + let server = b.server.url(""); + for i in 0..10_000u64 { + let url = format!("{server}{}", TestServer::data_path(i, 1 << 20)); + b.store.add_task(Task { url, folder: b.files(), state: State::Paused, position: i as f64, ..Task::default() }).unwrap(); + } + let start = Instant::now(); + let b = b.restart(LIMITS); + let opened = start.elapsed(); + let before = b.manager.snapshot(); + assert_eq!(before.len(), 10_000); + let id = before.iter().nth(5000).unwrap().id(); + b.slow(5000); + b.run(Command::Resume(id)).await; + b.until_bytes(id).await; + // The only change, so the only copy. + let after = b.manager.snapshot(); + assert_eq!(before.iter().zip(after.iter()).filter(|(a, b)| !Arc::ptr_eq(a, b)).count(), 1); + assert_eq!(after.changed_since(before.rev).map(|v| v.id()).collect::>(), [id]); + let start = Instant::now(); + for _ in 0..1_000_000 { + std::hint::black_box(b.manager.snapshot()); + } + let read = start.elapsed(); + let start = Instant::now(); + let replies: Vec<_> = after.iter().map(|v| b.manager.send(Command::Resume(v.id()))).collect(); + let sent = start.elapsed(); + for reply in replies { + reply.await.unwrap(); + } + let answered = start.elapsed(); + let totals = b.manager.snapshot().totals.clone(); + assert!((1..=2).contains(&totals.running) && totals.running + totals.queued > 9_900); + println!("open {opened:?}, a read {:?}, 10,000 commands sent {sent:?}, answered {answered:?}", read / 1_000_000); + assert!(sent < ms(200), "{sent:?}"); + let start = Instant::now(); + b.manager.close(); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn commands_from_everywhere() { + const THREADS: usize = 4; + const EACH: usize = 2500; + const LEN: usize = 200_000; + let b = Bench::new(Limits { max_active: 4, ..LIMITS }).await; + let paths: Vec = (0..8) + .map(|seed| { + let path = TestServer::data_path(seed, LEN as u64); + let faults = match seed { + 0 => Faults { ignore_range: true, throttle_conn: Some(400_000), ..Faults::default() }, + 1 => Faults::status(404), + 2 | 3 => Faults { throttle_conn: Some(100_000), ..Faults::default() }, + 4 => Faults { cut_after: Some(60_000), ..Faults::default() }, + _ => Faults { throttle_conn: Some(1_000_000), ..Faults::default() }, + }; + b.server.set_faults(&path, faults); + path + }) + .collect(); + for i in 0..24 { + b.add(&paths[i % 8]).await; + } + + let mut events = b.manager.subscribe(); + let over = AtomicBool::new(false); + let moves = std::thread::scope(|scope| { + let watcher = scope.spawn(|| { + let (mut last, mut moves, mut rev) = (HashMap::new(), 0, 0); + while !over.load(Ordering::Relaxed) { + let shot = b.manager.snapshot(); + assert!(shot.rev >= rev); + rev = shot.rev; + assert!(shot.totals.running <= 4); + assert_eq!(shot.iter().filter(|v| v.state() == State::Running).count(), shot.totals.running); + assert!(shot.iter().all(|v| v.task.removed_at.is_none() && v.size.is_none_or(|s| v.downloaded <= s))); + loop { + match events.try_recv() { + Ok(Event::State { id, from, to }) => { + assert!(from.can_become(to), "{from:?} to {to:?}"); + assert!(last.insert(id, to).is_none_or(|l| l == from), "{id} jumped to {from:?}"); + moves += 1; + } + Ok(_) => {} + Err(TryRecvError::Lagged(_)) => last.clear(), + Err(_) => break, + } + } + std::thread::sleep(ms(1)); + } + moves + }); + let workers: Vec<_> = (0..THREADS) + .map(|_| { + scope.spawn(|| { + let mut replies = vec![]; + for step in 0..EACH { + let id = fastrand::i64(1..=32); + let files = if fastrand::bool() { Files::Keep } else { Files::Bin }; + let folder = b.dir.path().join(["files", "a", "b/c"][fastrand::usize(..3)]); + let command = match fastrand::u8(..100) { + 0..=14 => Command::Pause(id), + 15..=34 => Command::Resume(id), + 35..=44 => Command::Start(id), + 45..=49 => Command::Stop(id), + 50..=55 => Command::Remove { id, files }, + 56..=69 => Command::Restore(id), + 70..=74 => Command::Redownload(id), + 75..=80 => Command::Move { id, folder }, + 81..=86 => Command::Rename { id, name: ["x.bin", "y.bin", "..", "z.tar.gz"][fastrand::usize(..4)].into() }, + 87..=94 => { + let priority = Priority::ALL[fastrand::usize(..Priority::ALL.len())]; + Command::Edit { id, edit: Box::new(move |t| t.priority = priority) } + } + 95..=96 if b.manager.snapshot().len() < 40 => Command::Add(Box::new(b.task(&paths[fastrand::usize(..8)]))), + _ => { + b.manager.set_limits(Limits { max_active: fastrand::u32(1..=4), ..LIMITS }); + continue; + } + }; + replies.push(b.manager.send(command)); + // Downloads get on in between. + if step % 10 == 0 { + std::thread::sleep(ms(20)); + } + } + let end = Instant::now() + Duration::from_secs(60); + for mut reply in replies { + let result = loop { + match reply.try_get() { + Some(result) => break result, + None => assert!(Instant::now() < end, "no answer: deadlock"), + } + std::thread::sleep(ms(1)); + }; + let fine = matches!(result, Ok(_) | Err(Error::Name) | Err(Error::Store(store::Error::NotFound))); + assert!(fine, "{result:?}"); + } + }) + }) + .collect(); + workers.into_iter().for_each(|w| w.join().unwrap()); + over.store(true, Ordering::Relaxed); + watcher.join().unwrap() + }); + assert!(moves > 200, "{moves} moves"); + + // All that is left can still be finished, and nothing got mixed up. + b.server.clear_all_faults(); + b.manager.set_limits(Limits { max_active: 4, ..LIMITS }); + for v in b.manager.snapshot().iter() { + b.run(Command::Edit { id: v.id(), edit: Box::new(|t| t.priority = Priority::Normal) }).await; + b.run(Command::Resume(v.id())).await; + } + b.until("all done", |s| s.iter().all(|v| v.state() == State::Done)).await; + let shot = b.manager.snapshot(); + println!("{moves} moves, {} tasks, {:?}", shot.len(), shot.totals.counters); + let mut files = std::collections::HashSet::new(); + for v in shot.iter() { + let seed = paths.iter().position(|p| v.task.url.ends_with(p.as_str())).unwrap(); + b.check(v.id(), seed as u64, LEN); + assert!(files.insert(v.task.folder.join(&v.task.name)), "two tasks, one file"); + assert_eq!(b.store.task(v.id()).unwrap(), *v.task); + } + for dir in ["files", "a", "b/c"] { + for f in std::fs::read_dir(b.dir.path().join(dir)).into_iter().flatten() { + let path = f.unwrap().path(); + let removed = || b.store.tasks().unwrap().iter().any(|t| t.removed_at.is_some() && path.starts_with(&t.folder)); + assert!(path.extension().is_none_or(|e| e != "medlar") || removed(), "left over: {path:?}"); + } + } + let start = Instant::now(); + b.manager.close(); + assert!(start.elapsed() < Duration::from_secs(2)); +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index d6c4347..e87d711 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -28,3 +28,5 @@ - D-027 — 2026-11-25 — Wave height and travel follow the logarithm of the bytes per second, from 0 to 64 MiB/s, not a share of the limit or of the fastest so far. At 0 B/s, when paused, and with motion off or reduced the bar is flat and draws no frames. — The same speed always looks the same, and a slow line still moves visibly. — 03 - D-028 — 2026-11-25 — Progress widgets keep their springs per `Id` and start in place when they were not drawn in the frame before, so scrolling shows no motion and the tick plays only for someone who saw the download finish. A list row's id comes from the task's id, not its position. — 03 - D-023 — 2026-11-25 — Menus are Medlar's own (`ui::menu`), not egui's: one open at a time, own keyboard. Dialogs never close by a click on the scrim (the side sheet does); Enter does the main action unless a button has the focus; dangerous questions start on Cancel. Elevated buttons have no shadow. — egui's arrow keys leave its menus; typed links must not be lost. — 03 and later +- D-029 — 2026-11-25 — Running set: at most `max_active`, one place per connection a host gives. Rank: forced start (latest first), priority, running before waiting, queue position, position. A running download gives way to a higher priority, a forced start or an "only", never to a better position; one that can't resume never gives way. Stop = pause and go last. Remove can be undone for 60 s and until the program ends; at the next start it is final. Closing turns running into queued, so that they go on at the next start. — FEATURES 1.1, 2.3, 7.3. — 02, 04, 05 +- D-030 — 2026-11-25 — A file name belongs to the unfinished task that has it recorded, even when its file is empty or missing. Looking for a free name and taking it happens under `disk::names()`. Tasks are changed through `Store::edit_task` (one transaction), never read, changed and saved. — The command fuzz mixed up the files of two tasks without this. — 02, 06 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index f4e12c0..f323486 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -77,5 +77,15 @@ Verified: `--test visuals` green (bounds and NaN at every look, speed, width and - `badge`: `Kind` comes from the category; nothing maps names to kinds yet. `loading` shows only after 0.3 s; draw it for as long as something is waited for. Not done: the map has no keyboard focus (its numbers belong in the detail list too). Not seen on a real GPU or by hand: the feel of the springs. `wave::slider` is the wavy one for limits, S013's is the plain one. +## S006 — Download manager, events and snapshots (2026-11-25) +Done: `core::manager` (thread, commands, who runs, file work, bin), `snapshot`, `events`, `speed`; `cargo run -p medlar-core --example manager` shows text progress. Choices: D-029, D-030. Outside the plan's files: `Store::edit_task` and `used_names`, `disk` (free names), `http/download.rs` (uses them). +Verified: `nice cargo test -j 2 -p medlar-core` green (76 unit, 16 http, 12 manager, 9 parts); the 10,000-command fuzz 100 of 100 times on an overloaded CPU; clippy clean for the new code. Debug build, 10,000 tasks: open 0.5 s, reading a snapshot 0.15 µs, sending 10,000 commands 4 ms, one change copies one view. 12 downloads close in under 2 s without losing a byte. +- One `Manager` per program, in an `Arc`: `Manager::open(Config::new(Shared, limits))`, not on the window's thread. `send(Command) -> Reply` never waits; `Reply` is a future, `try_get()` for the window, `wait()` for plain threads. It comes after the snapshot shows the change. Drop it to ignore errors. +- `Command::{Add, Start, Pause, Resume, Stop, Remove{id,files}, Restore, Redownload, Move{id,folder}, Rename{id,name}, Edit{id,edit}}`; `Edit` covers all the user decides (priority, position, queue, notes, limits…). `set_limits(settings.limits())` is live. +- `snapshot() -> Arc`: `rev`, `totals`, `iter()` by id, `get(id)`, `changed_since(rev)`. `TaskView`: `task`, `size`, `downloaded`, `speed`, `left`, `parts` (`PartView`), `connections`, `wanted`, `resumable`, `checked` (0 for now), `server`, `history` (300 s; `pushed()` tells what is new), `log` (200 lines), `counters`. `on_change(f)` is for `request_repaint`; nothing is published while nothing changes. `subscribe()` gives `Event`s. +- `begin_close()` doesn't wait; `close()` and drop do (under 2 s). Error text of `http::Error` is raw: S007 fills `words()` and the kinds at the end of `manager/actor.rs`; Retry-After and Waiting are its too. +Not done: part events (`Split`…) don't leave the manager; `PartView.id` tells parts apart within a run. Counters and logs are for this session only. Cookies and logins from the keyring are not added to `Source` yet. Queue `paused`, `max_active`, `schedule`, `after`, `start_at` are not looked at (S009); Done files are not checked for being gone; `Only` does not pause what can't resume. +Seen: connections of a host are first come, first served: with more downloads than fit, some run without any until others end (S010). `http::name::no_name_gets_out_of_its_folder` took over 60 s on an overloaded CPU. Boxes were ticked together at the end, against rule 3. + ## Later -