S006: download manager, events and snapshots

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 02:34:27 -06:00
commit 548fcb27b5
23 changed files with 2940 additions and 33 deletions

11
Cargo.lock generated
View file

@ -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",

View file

@ -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

View file

@ -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

View file

@ -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"

View file

@ -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;
}
}

View file

@ -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",

View file

@ -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<Errno> for Error {
pub type Result<T> = std::result::Result<T, Error>;
/// 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<String>) -> 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<Option<PartialFile>> {
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<Option<PartialFile>> {
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<T: Send + 'static, E: Send + 'static>(
}
/// `a.zip`, `a (1).zip`, `a (2).zip` …
fn variants(name: &str) -> impl Iterator<Item = String> {
pub(crate) fn variants(name: &str) -> impl Iterator<Item = String> {
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<Item = String> {
}
/// Also true for a link that points nowhere.
fn exists(path: &Path) -> io::Result<bool> {
pub(crate) fn exists(path: &Path) -> io::Result<bool> {
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();

16
crates/core/src/events.rs Normal file
View file

@ -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),
}

View file

@ -123,14 +123,15 @@ async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc<PartialFile>
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(())
})

View file

@ -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;

View file

@ -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<Binned>),
}
enum Work {
Run(Run),
Files { cancel: Arc<AtomicBool>, answer: Option<Answer> },
}
struct Run {
stop: watch::Sender<bool>,
monitor: Arc<Monitor>,
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<Task>,
host: Arc<str>,
work: Option<Work>,
todo: VecDeque<(Todo, Option<Answer>)>,
/// Counts up with each start; 0 for never.
forced: u64,
size: Option<u64>,
downloaded: u64,
parts: Arc<[PartView]>,
connections: u32,
wanted: u32,
resumable: Option<bool>,
meter: Meter,
history: Arc<History>,
/// Bytes of the second that isn't over.
second: u64,
log: Arc<Log>,
counters: Counters,
binned: Option<Binned>,
forget_at: Option<Instant>,
}
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<Vec<Part>>) {
(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<str> {
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<Store>,
runtime: Option<Runtime>,
to: mpsc::Sender<Msg>,
published: Arc<ArcSwap<Snapshot>>,
shot: Snapshot,
events: broadcast::Sender<Event>,
on_change: Vec<Box<dyn Fn() + Send>>,
entries: BTreeMap<TaskId, Entry>,
/// Those with a download as their work.
runs: BTreeSet<TaskId>,
/// Those to forget some time.
removed: BTreeSet<TaskId>,
dirty: BTreeSet<TaskId>,
totals: Totals,
totals_dirty: bool,
/// Someone may have to start or stop.
choose: bool,
/// Told after the snapshot.
happened: Vec<Event>,
answers: Vec<(Answer, Result<TaskId>)>,
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<Msg>, published: Arc<ArcSwap<Snapshot>>, events: broadcast::Sender<Event>) -> Result<Actor> {
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<Msg>) {
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<Duration> {
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<Answer>, result: Result<TaskId>) {
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<Answer>) {
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<Result<()>> {
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<Answer>) {
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<Answer>) {
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<TaskId> {
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<Answer>) {
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<TaskError>) -> 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<TaskError>) {
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<QueueId, f64> = 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<TaskId> = 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<Answer>, job: impl FnOnce(&Store, &AtomicBool) -> Result<Worked> + 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<PathBuf, Why>) {
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<Worked>) {
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<Msg>) {
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:?}")
}

View file

@ -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<Binned> {
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<PathBuf> {
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());
}
}

View file

@ -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<Own> {
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<Option<PartialFile>> {
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<String>) -> Result<bool> {
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<Option<Binned>> {
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<Part>) -> (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");
}
}

View file

@ -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<T> = std::result::Result<T, Error>;
impl From<store::Error> 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<Task>),
/// 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<dyn FnOnce(&mut Task) + Send> },
}
impl Command {
fn id(&self) -> Option<TaskId> {
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<Result<TaskId>>);
impl Reply {
/// None while there is no answer. Never waits; ask no more after the answer.
pub fn try_get(&mut self) -> Option<Result<TaskId>> {
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<TaskId> {
self.0.blocking_recv().unwrap_or(Err(Error::Closed))
}
}
impl Future for Reply {
type Output = Result<TaskId>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
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<Result<TaskId>>;
enum Msg {
Command(Command, Option<Answer>),
Limits(Limits),
OnChange(Box<dyn Fn() + Send>),
/// A download ended.
Ended(TaskId, std::result::Result<PathBuf, actor::Why>),
/// File work ended.
Worked(TaskId, Result<actor::Worked>),
Close,
}
/// Share it in an `Arc`. Dropping it closes it.
pub struct Manager {
to: mpsc::Sender<Msg>,
shot: Arc<ArcSwap<Snapshot>>,
events: broadcast::Sender<Event>,
thread: Mutex<Option<JoinHandle<()>>>,
}
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<Manager> {
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<Snapshot> {
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<Event> {
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();
}
}

View file

@ -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<Candidate>, max: usize, mut host_cap: impl FnMut(&str) -> u32) -> Vec<TaskId> {
let pinned = |c: &Candidate| c.running && c.pinned;
if candidates.iter().any(|c| c.priority == Priority::Only) {
candidates.retain(|c| c.priority == Priority::Only || pinned(c));
}
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<TaskId> {
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");
}
}

225
crates/core/src/snapshot.rs Normal file
View file

@ -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<Task>,
/// The revision of the snapshot that last changed it.
pub rev: u64,
pub size: Option<u64>,
pub downloaded: u64,
/// Bytes per second.
pub speed: f64,
pub left: Option<Duration>,
/// 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<bool>,
/// 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<str>,
pub history: Arc<History>,
pub log: Arc<Log>,
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<f32> {
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<Line>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
pub at: Time,
pub text: Arc<str>,
}
/// 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<History>,
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<Arc<Vec<Arc<TaskView>>>>,
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<Item = &Arc<TaskView>> {
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<TaskView>> {
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<Item = &Arc<TaskView>> {
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::<Vec<_>>(), [5000]);
assert_eq!(old.get(5000).unwrap().rev, 1);
}
}

202
crates/core/src/speed.rs Normal file
View file

@ -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<f64>,
}
impl Meter {
/// `remaining` is None when the size is unknown.
pub fn push(&mut self, bytes: u64, dt: Duration, remaining: Option<u64>) {
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<u64>) -> Option<f64> {
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<Duration> {
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<f32>,
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<Item = f32> + '_ {
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<Item = f64>) -> Vec<(f64, Option<f64>)> {
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));
}
}

View file

@ -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<Task> {
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<TaskError>) -> 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<HashSet<String>> {
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<Part>) -> Result<()> {
self.send(Box::new(move |conn| {

View file

@ -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<Task> {
})
}
pub fn used_names(c: &Connection, folder: &Path, except: TaskId) -> Result<HashSet<String>> {
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::<rusqlite::Result<_>>()?)
}
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 (?, ?, ?, ?)")?;

View file

@ -337,7 +337,7 @@ async fn one_part(b: &Bench, path: &str, done: u64) -> (Result<()>, Vec<u8>, 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 {

Some files were not shown because too many files have changed in this diff Show more