S005: dynamic parts and adaptive connections

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 01:18:06 -06:00
commit 2ecac7b119
16 changed files with 2005 additions and 110 deletions

View file

@ -11,14 +11,14 @@ Parts split, hand over and merge while running; connections follow what helps. F
- docs/FEATURES.md §1
## Steps
- [ ] Pure scheduler (no I/O) that decides splits from part positions and speeds: take half of the part with the longest time left, aligned, never under the minimum size; property tests for no gap and no overlap
- [ ] Live split and steal without reconnecting the donor; neighbouring finished ranges merge in the journal
- [ ] Adaptive controller: start at 2, add while total throughput grows beyond noise, step down on 429/503/refusals; per-host memory in the store with expiry
- [ ] Caps per download, host and total, changed live up and down
- [ ] Per-part errors stay local: backoff with jitter, Retry-After, reconnect, hand the range to another connection
- [ ] Stall and slow-part detection: the tail of a file never waits on one crawling connection
- [ ] Event stream of part changes (born, split, stolen, merged, done) for the parts map
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S005: …`, push
- [x] Pure scheduler (no I/O) that decides splits from part positions and speeds: take half of the part with the longest time left, aligned, never under the minimum size; property tests for no gap and no overlap
- [x] Live split and steal without reconnecting the donor; neighbouring finished ranges merge in the journal
- [x] Adaptive controller: start at 2, add while total throughput grows beyond noise, step down on 429/503/refusals; per-host memory in the store with expiry
- [x] Caps per download, host and total, changed live up and down
- [x] Per-part errors stay local: backoff with jitter, Retry-After, reconnect, hand the range to another connection
- [x] Stall and slow-part detection: the tail of a file never waits on one crawling connection
- [x] Event stream of part changes (born, split, stolen, merged, done) for the parts map
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S005: …`, push
## End criteria
- `nice cargo test -j 2 -p medlar-core --test parts` green

View file

@ -13,7 +13,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
## 02 Engine
- [x] [S004](02%20Engine/S004-http-core.md) HTTP core with resume and crash-safe files
- [ ] [S005](02%20Engine/S005-dynamic-parts.md) Dynamic parts and adaptive connections
- [x] [S005](02%20Engine/S005-dynamic-parts.md) Dynamic parts and adaptive connections
- [ ] [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

341
crates/core/src/adapt.rs Normal file
View file

@ -0,0 +1,341 @@
//! How many connections a download should use. Every connection has to prove that it helps.
use std::time::{Duration, Instant};
/// Connections of a download to a host nobody knows.
pub const START: u32 = 2;
/// What a connection must add, as a share of what the others bring on average.
const WORTH: f64 = 0.3;
/// A jump that brings less of that share went too far.
const FULL: f64 = 0.7;
#[derive(Debug, Clone, Copy)]
pub struct Timing {
/// Left out after a change: connections start slowly.
pub settle: Duration,
/// Measured before deciding.
pub window: Duration,
/// Until the next try after one that brought nothing. Doubles each time, up to eight times this.
pub hold: Duration,
/// Until more is tried again after the server refused a connection.
pub refused: Duration,
}
impl Default for Timing {
fn default() -> Self {
Timing {
settle: Duration::from_secs(1),
window: Duration::from_secs(3),
hold: Duration::from_secs(30),
refused: Duration::from_secs(600),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Measure {
mean: f64,
/// Standard error of the mean.
error: f64,
}
#[derive(Debug, Clone, Copy)]
enum Phase {
Base,
/// Trying more or fewer than `n`, which measured `at_n`.
Try { n: u32, at_n: Measure },
Hold { until: Instant },
}
#[derive(Debug)]
pub struct Adapt {
n: u32,
cap: u32,
timing: Timing,
phase: Phase,
/// Doubling, until that fails.
fast: bool,
/// `n` was measured to be better than less.
proven: bool,
learned: bool,
hold: Duration,
window: Window,
}
#[derive(Debug, Default)]
struct Window {
/// All connections have delivered since the last change.
since: Option<Instant>,
last: Option<(Instant, u64)>,
rates: Vec<f64>,
}
impl Adapt {
pub fn new(start: u32, cap: u32, timing: Timing) -> Adapt {
let cap = cap.max(1);
Adapt {
n: start.clamp(1, cap),
cap,
timing,
phase: Phase::Base,
fast: true,
proven: false,
learned: false,
hold: timing.hold,
window: Window::default(),
}
}
pub fn target(&self) -> u32 {
self.n
}
/// The count to remember for this host, if something was found out.
pub fn learned(&self) -> Option<u32> {
match self.phase {
_ if !self.learned => None,
Phase::Try { n, .. } => Some(n),
_ => Some(self.n),
}
}
pub fn set_cap(&mut self, cap: u32) {
let cap = cap.max(1);
if cap == self.cap {
return;
}
if cap > self.cap || cap < self.n {
self.phase = Phase::Base;
self.window = Window::default();
self.fast = true;
}
self.cap = cap;
self.n = self.n.min(cap);
}
/// The server turned a connection away. With `others` there, and if they `work`, that says what it stands.
pub fn refused(&mut self, now: Instant, others: u32, work: bool) {
self.window = Window::default();
self.fast = !work;
self.proven = true;
self.n = self.n.min(others).max(1);
self.learned |= work;
let wait = if work { self.timing.refused } else { self.timing.window * 3 };
self.phase = Phase::Hold { until: now + wait };
}
/// To be called regularly. `running` connections exist, `delivering` of them have brought something, `received` bytes in all.
pub fn tick(&mut self, now: Instant, running: u32, delivering: u32, received: u64) {
if let Phase::Hold { until } = self.phase {
if now < until {
return;
}
self.phase = Phase::Base;
self.proven = false;
self.window = Window::default();
}
if running != self.n {
self.window = Window::default();
return;
}
let w = &mut self.window;
let Some(since) = w.since else {
if delivering == running {
w.since = Some(now);
}
return;
};
if now < since + self.timing.settle {
return;
}
if let Some((then, before)) = w.last {
let secs = (now - then).as_secs_f64();
if secs <= 0.0 {
return;
}
w.rates.push(received.saturating_sub(before) as f64 / secs);
}
w.last = Some((now, received));
if w.rates.len() >= 4 && now >= since + self.timing.settle + self.timing.window {
let found = measure(&w.rates);
self.window = Window::default();
self.decide(now, found);
}
}
fn decide(&mut self, now: Instant, found: Measure) {
match self.phase {
Phase::Hold { .. } => {}
Phase::Base => {
let more = if self.fast { self.n.saturating_mul(2) } else { self.n + 1 }.min(self.cap);
if more > self.n { self.try_count(more, found) } else { self.less(now, found) }
}
Phase::Try { n, at_n } if self.n > n => {
self.learned = true;
if helps((n, at_n), (self.n, found), WORTH) {
self.proven = helps((n, at_n), (self.n, found), FULL) || self.n == n + 1;
self.fast &= self.proven;
self.hold = self.timing.hold;
self.phase = Phase::Base;
// Already measured: go on at once.
self.decide(now, found);
} else if self.n > n + 1 {
self.fast = false;
self.try_count(n + 1, at_n);
} else {
self.fast = false;
self.n = n;
self.less(now, at_n);
}
}
Phase::Try { n, at_n } => {
self.learned = true;
if helps((self.n, found), (n, at_n), WORTH) {
self.n = n;
self.proven = true;
self.rest(now);
} else {
self.less(now, found);
}
}
}
}
/// Tries fewer connections, unless all are known to help.
fn less(&mut self, now: Instant, found: Measure) {
let fewer = (self.n - (self.n / 4).max(1)).max(START);
if self.proven || fewer >= self.n { self.rest(now) } else { self.try_count(fewer, found) }
}
fn try_count(&mut self, count: u32, at_n: Measure) {
// After a failed jump `self.n` is the failed count, not the base.
let n = match self.phase {
Phase::Try { n, .. } if self.n > n && count > n => n,
_ => self.n,
};
self.phase = Phase::Try { n, at_n };
self.n = count.min(self.cap);
}
fn rest(&mut self, now: Instant) {
self.phase = Phase::Hold { until: now + self.hold };
self.hold = (self.hold * 2).min(self.timing.hold * 8);
}
}
fn measure(rates: &[f64]) -> Measure {
let n = rates.len() as f64;
let mean = rates.iter().sum::<f64>() / n;
let variance = rates.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0);
Measure { mean, error: (variance / n).sqrt() }
}
/// Whether the additional connections add `share` of what one brings on average, beyond noise.
fn helps((few, a): (u32, Measure), (many, b): (u32, Measure), share: f64) -> bool {
let fair = a.mean * f64::from(many - few) / f64::from(few);
let noise = 2.0 * a.error.hypot(b.error);
b.mean - a.mean > (share * fair).max(noise)
}
#[cfg(test)]
mod tests {
use super::*;
struct Sim {
adapt: Adapt,
now: Instant,
received: u64,
seed: u64,
most: u32,
}
impl Sim {
fn new(start: u32, cap: u32) -> Sim {
Sim { adapt: Adapt::new(start, cap, Timing::default()), now: Instant::now(), received: 0, seed: 0x2545_f491_4f6c_dd1d, most: 0 }
}
/// `rate(n)` bytes per second, give or take `noise` of it.
fn run(&mut self, secs: u64, noise: f64, rate: impl Fn(u32) -> f64) -> u32 {
for _ in 0..secs * 4 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
let swing = (self.seed % 2001) as f64 / 1000.0 - 1.0;
let n = self.adapt.target();
self.most = self.most.max(n);
self.received += (rate(n) * (1.0 + swing * noise) / 4.0) as u64;
self.now += Duration::from_millis(250);
self.adapt.tick(self.now, n, n, self.received);
}
self.adapt.learned().unwrap_or(self.adapt.target())
}
}
#[test]
fn grows_while_it_helps() {
let mut sim = Sim::new(START, 16);
assert_eq!(sim.run(20, 0.1, |n| f64::from(n) * 1e6), 16);
assert_eq!(Sim::new(START, 7).run(20, 0.1, |n| f64::from(n) * 1e6), 7);
// Until six, which doubling jumps over.
let six = Sim::new(START, 32).run(40, 0.02, |n| f64::from(n.min(6)) * 1e6);
assert!((5..=7).contains(&six), "{six}");
}
#[test]
fn stays_low_when_it_does_not() {
for noise in [0.0, 0.1, 0.4] {
let mut sim = Sim::new(START, 16);
assert_eq!(sim.run(300, noise, |_| 1e6), 2, "{noise}");
assert!(sim.most <= 4);
}
// A line that gets worse with more.
assert_eq!(Sim::new(START, 16).run(60, 0.1, |n| 1e6 / f64::from(n)), 2);
}
#[test]
fn a_remembered_count_is_checked() {
assert_eq!(Sim::new(12, 16).run(90, 0.05, |_| 1e6), 2);
let mut sim = Sim::new(8, 8);
sim.run(200, 0.05, |n| f64::from(n) * 1e6);
assert_eq!(sim.adapt.learned(), Some(8));
}
#[test]
fn conditions_change_during_a_download() {
let mut sim = Sim::new(START, 8);
assert_eq!(sim.run(60, 0.05, |_| 1e6), 2);
assert_eq!(sim.run(400, 0.05, |n| f64::from(n) * 1e6), 8);
}
#[test]
fn refusals_and_caps() {
let mut sim = Sim::new(START, 16);
sim.run(20, 0.05, |n| f64::from(n) * 1e6);
sim.adapt.refused(sim.now, 5, true);
assert_eq!(sim.run(300, 0.05, |n| f64::from(n) * 1e6), 5);
sim.adapt.set_cap(3);
assert_eq!(sim.adapt.target(), 3);
sim.run(60, 0.05, |n| f64::from(n) * 1e6);
sim.adapt.set_cap(0);
assert_eq!(sim.adapt.target(), 1);
sim.adapt.set_cap(9);
assert_eq!(sim.run(60, 0.05, |n| f64::from(n) * 1e6), 9);
// Nothing else was running: no lesson.
let mut sim = Sim::new(START, 16);
sim.adapt.refused(sim.now, 0, false);
assert_eq!((sim.adapt.target(), sim.adapt.learned()), (1, None));
assert_eq!(sim.run(60, 0.05, |n| f64::from(n) * 1e6), 16);
}
#[test]
fn nothing_is_measured_while_connections_come_and_go() {
let mut adapt = Adapt::new(START, 16, Timing::default());
let mut now = Instant::now();
for i in 0..400 {
now += Duration::from_millis(250);
adapt.tick(now, 1 + i % 2, 1, u64::from(i) * 1000);
}
assert_eq!((adapt.target(), adapt.learned()), (START, None));
}
}

292
crates/core/src/host.rs Normal file
View file

@ -0,0 +1,292 @@
//! Connections to each host: how many are open, how many may be, and what hosts tolerated before.
use crate::model::{HostProfile, Time};
use crate::store::{self, Store};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use url::Url;
/// What a host tolerated is forgotten after this many milliseconds.
const REMEMBERED: Time = 7 * 24 * 3600 * 1000;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Caps {
pub total: u32,
pub per_host: u32,
/// New requests to one host: this many at once, then so many a second.
pub burst: u32,
pub per_second: f64,
}
impl Default for Caps {
fn default() -> Self {
Caps { total: 64, per_host: 16, burst: 16, per_second: 4.0 }
}
}
/// A host that turned connections away may count one that was closed for this long.
const LINGER: Duration = Duration::from_millis(300);
/// Shared by all downloads.
#[derive(Debug)]
pub struct Hosts {
inner: Mutex<Inner>,
changed: watch::Sender<()>,
}
#[derive(Debug)]
struct Inner {
caps: Caps,
next: u64,
open: BTreeMap<u64, Open>,
hosts: HashMap<String, Host>,
}
#[derive(Debug)]
struct Open {
host: String,
revoked: bool,
}
#[derive(Debug, Default)]
struct Host {
/// Set by the user.
cap: Option<u32>,
/// What it refused to go beyond, and until when that counts.
ceiling: Option<(u32, Instant)>,
rest_until: Option<Instant>,
/// When connections ended, while there is a ceiling.
closed: Vec<Instant>,
/// Requests in the bucket, as of then.
bucket: Option<(f64, Instant)>,
}
/// One connection. Gives its place back when dropped.
#[derive(Debug)]
pub struct Permit {
hosts: Arc<Hosts>,
id: u64,
}
impl Permit {
/// The caps went down: end this connection.
pub fn revoked(&self) -> bool {
self.hosts.inner.lock().unwrap().open[&self.id].revoked
}
}
impl Drop for Permit {
fn drop(&mut self) {
self.hosts.inner.lock().unwrap().close(self.id, Instant::now());
self.hosts.changed.send_replace(());
}
}
impl Inner {
fn count(&self, host: &str) -> u32 {
self.open.values().filter(|o| o.host == host).count() as u32
}
fn cap(&self, host: &str, now: Instant) -> u32 {
let known = self.hosts.get(host);
let own = known.and_then(|h| h.cap).unwrap_or(self.caps.per_host);
let ceiling = known.and_then(|h| h.ceiling).filter(|(_, until)| now < *until);
own.min(ceiling.map_or(u32::MAX, |c| c.0)).max(1)
}
fn close(&mut self, id: u64, now: Instant) {
let Some(o) = self.open.remove(&id) else { return };
if let Some(h) = self.hosts.get_mut(&o.host)
&& h.ceiling.is_some_and(|(_, until)| now < until)
{
h.closed.push(now);
}
}
/// Marks the newest connections over the caps.
fn revoke(&mut self, now: Instant) {
let caps: HashMap<String, u32> = self.open.values().map(|o| (o.host.clone(), self.cap(&o.host, now))).collect();
let (total_cap, mut total, mut each) = (self.caps.total.max(1), 0, HashMap::new());
for o in self.open.values_mut().filter(|o| !o.revoked) {
let n: &mut u32 = each.entry(o.host.clone()).or_default();
o.revoked = total >= total_cap || *n >= caps[&o.host];
if !o.revoked {
total += 1;
*n += 1;
}
}
}
}
impl Hosts {
pub fn new(caps: Caps) -> Arc<Hosts> {
let inner = Inner { caps, next: 0, open: BTreeMap::new(), hosts: HashMap::new() };
Arc::new(Hosts { inner: Mutex::new(inner), changed: watch::Sender::new(()) })
}
/// Takes a place for a connection, if there is one now.
pub fn open(self: &Arc<Hosts>, host: &str, now: Instant) -> Option<Permit> {
let mut i = self.inner.lock().unwrap();
let (count, cap, caps) = (i.count(host), i.cap(host, now), i.caps);
if i.open.len() as u32 >= caps.total.max(1) || count >= cap {
return None;
}
let h = i.hosts.entry(host.into()).or_default();
h.closed.retain(|at| now < *at + LINGER);
if count + h.closed.len() as u32 >= cap {
return None;
}
if h.rest_until.is_some_and(|until| now < until) {
return None;
}
let burst = f64::from(caps.burst.max(1));
let (had, then) = h.bucket.unwrap_or((burst, now));
let has = (had + now.saturating_duration_since(then).as_secs_f64() * caps.per_second).min(burst);
if has < 1.0 {
return None;
}
h.bucket = Some((has - 1.0, now));
let id = i.next;
i.next += 1;
i.open.insert(id, Open { host: host.into(), revoked: false });
drop(i);
Some(Permit { hosts: self.clone(), id })
}
pub fn caps(&self) -> Caps {
self.inner.lock().unwrap().caps
}
pub fn set_caps(&self, caps: Caps) {
self.change(|i| i.caps = caps);
}
/// The user's cap for one host; None for the general one.
pub fn set_host_cap(&self, host: &str, cap: Option<u32>) {
self.change(|i| i.hosts.entry(host.into()).or_default().cap = cap);
}
/// The host turned one connection away while others work. Counts for all downloads, until then.
pub fn refused(&self, host: &str, until: Instant) {
let mut i = self.inner.lock().unwrap();
let ceiling = i.count(host).saturating_sub(1).max(1);
i.hosts.entry(host.into()).or_default().ceiling = Some((ceiling, until));
}
/// The host asked for a pause.
pub fn rest(&self, host: &str, until: Instant) {
let mut i = self.inner.lock().unwrap();
let rest = &mut i.hosts.entry(host.into()).or_default().rest_until;
*rest = (*rest).max(Some(until));
}
pub fn open_to(&self, host: &str) -> u32 {
self.inner.lock().unwrap().count(host)
}
/// Tells when a place may have become free or a connection must end.
pub(crate) fn watch(&self) -> watch::Receiver<()> {
self.changed.subscribe()
}
fn change(&self, what: impl FnOnce(&mut Inner)) {
let mut i = self.inner.lock().unwrap();
what(&mut i);
i.revoke(Instant::now());
drop(i);
self.changed.send_replace(());
}
}
/// Name and port: what counts as one host.
pub fn key(url: &Url) -> String {
let name = url.host_str().unwrap_or_default().to_ascii_lowercase();
url.port().map_or(name.clone(), |port| format!("{name}:{port}"))
}
/// What the host tolerated, unless that is too long ago.
pub fn tolerated(profile: &HostProfile, now: Time) -> Option<u32> {
profile.good_connections.filter(|n| *n > 0 && now.saturating_sub(profile.seen_at) < REMEMBERED)
}
/// Blocks.
pub fn remember(store: &Store, host: &str, connections: u32, now: Time) -> store::Result<()> {
let known = store.host(host)?.unwrap_or_default();
store.save_host(HostProfile { host: host.into(), good_connections: Some(connections), seen_at: now, ..known })
}
#[cfg(test)]
mod tests {
use super::*;
const FREE: Caps = Caps { total: 5, per_host: 3, burst: 100, per_second: 100.0 };
#[test]
fn caps_hold_and_places_come_back() {
let (hosts, now) = (Hosts::new(FREE), Instant::now());
let mut a: Vec<_> = (0..4).filter_map(|_| hosts.open("a", now)).collect();
assert_eq!(a.len(), 3);
let b: Vec<_> = (0..4).filter_map(|_| hosts.open("b", now)).collect();
assert_eq!(b.len(), 2, "five in total");
a.pop();
assert!(hosts.open("a", now).is_some());
}
#[test]
fn lower_caps_revoke_the_newest() {
let (hosts, now) = (Hosts::new(FREE), Instant::now());
let a: Vec<_> = (0..3).filter_map(|_| hosts.open("a", now)).collect();
let b: Vec<_> = (0..2).filter_map(|_| hosts.open("b", now)).collect();
let revoked = |p: &[Permit]| p.iter().map(Permit::revoked).collect::<Vec<_>>();
hosts.set_host_cap("a", Some(2));
assert_eq!((revoked(&a), revoked(&b)), (vec![false, false, true], vec![false, false]));
hosts.set_caps(Caps { total: 3, ..FREE });
assert_eq!((revoked(&a), revoked(&b)), (vec![false, false, true], vec![false, true]));
assert!(hosts.open("c", now).is_none());
drop((a, b));
hosts.set_caps(FREE);
let a: Vec<_> = (0..3).filter_map(|_| hosts.open("a", now)).collect();
assert_eq!(a.len(), 2);
}
#[test]
fn refusals_rests_and_bursts() {
let (hosts, now) = (Hosts::new(FREE), Instant::now());
let one = hosts.open("a", now);
let two = hosts.open("a", now);
let later = now + Duration::from_secs(10);
hosts.refused("a", later);
drop(two);
assert!(hosts.open("a", now).is_none(), "one is what it stands");
drop(one);
assert!(hosts.open("a", now).is_none(), "it may not have noticed the end");
let one = hosts.open("a", Instant::now() + LINGER);
assert!(one.is_some());
assert!(hosts.open("a", later).is_some());
hosts.rest("b", later);
hosts.rest("b", now);
assert!(hosts.open("b", now).is_none() && hosts.open("b", later).is_some());
drop(one);
hosts.set_caps(Caps { burst: 2, per_second: 2.0, ..FREE });
let open = |at| (0..5).filter(|_| hosts.open("c", at).is_some()).count();
assert_eq!((open(now), open(now), open(now + Duration::from_millis(500)), open(later)), (2, 0, 1, 2));
}
#[test]
fn memory_expires() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(&dir.path().join("m.db")).unwrap();
let known = HostProfile { host: "h".into(), max_connections: Some(9), seen_at: 1, ..HostProfile::default() };
store.save_host(known).unwrap();
remember(&store, "h", 6, 1000).unwrap();
let p = store.host("h").unwrap().unwrap();
assert_eq!((p.max_connections, tolerated(&p, 2000)), (Some(9), Some(6)));
assert_eq!(tolerated(&p, 1000 + REMEMBERED), None);
assert_eq!(tolerated(&HostProfile::default(), 0), None);
assert_eq!(key(&Url::parse("https://H.example/f").unwrap()), "h.example");
assert_eq!(key(&Url::parse("http://h:8080/f").unwrap()), "h:8080");
}
}

View file

@ -1,33 +1,65 @@
//! One file from link to disk, in a fixed set of ranges.
//! One file from link to disk.
use super::fetch::compare;
use super::parts::Run;
use super::*;
use crate::adapt::{self, Timing};
use crate::disk::{PartialFile, blocking};
use crate::model::{Part, Task, TaskId};
use crate::part::{self, LivePart};
use crate::host::{self, Hosts};
use crate::model::{self, Part, Task, TaskId};
use crate::part::LivePart;
use crate::segment::Rules;
use crate::store::Store;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::task::JoinSet;
use tokio::time::{MissedTickBehavior, interval};
/// What all downloads have in common.
#[derive(Clone)]
pub struct Shared {
pub client: Client,
pub store: Arc<Store>,
pub hosts: Arc<Hosts>,
}
#[derive(Debug, Clone)]
pub struct Options {
/// Upper bound; the task may set a lower one.
pub parts: u32,
pub min_part: u64,
pub rules: Rules,
pub timing: Timing,
/// How often speeds are measured and places for connections looked for.
pub tick: Duration,
/// A part that brings nothing for so long gets another connection.
pub stall: Duration,
/// How long a connection may crawl before it is replaced.
pub patience: Duration,
/// Failures in a row of one part, without a byte, before the download fails.
pub tries: u32,
/// Wait after the first failure. Doubles up to `max_wait`.
pub backoff: Duration,
/// The download fails when the server asks for a longer pause.
pub max_wait: Duration,
/// How often finished ranges are made safe on disk and then recorded.
pub checkpoint: Duration,
}
impl Default for Options {
fn default() -> Self {
Options { parts: 4, min_part: 1 << 20, checkpoint: Duration::from_secs(5) }
Options {
rules: Rules { min: 1 << 20, align: 64 << 10, min_time: Duration::from_secs(2) },
timing: Timing::default(),
tick: Duration::from_millis(250),
stall: Duration::from_secs(15),
patience: Duration::from_secs(5),
tries: 5,
backoff: Duration::from_secs(1),
max_wait: Duration::from_secs(60),
checkpoint: Duration::from_secs(5),
}
}
}
/// Starts or continues the task and returns the finished file. Doesn't touch the task's state.
pub async fn download(client: &Client, store: &Arc<Store>, id: TaskId, source: Source, options: &Options, mut stop: Stop) -> Result<PathBuf> {
pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Options, monitor: &Monitor, mut stop: Stop) -> Result<PathBuf> {
let (client, store) = (&shared.client, &shared.store);
let job = Job { store: store.clone(), id };
let (task, parts) = job.run(move |s| Ok((s.task(id)?, s.parts(id)?))).await?;
let file = if parts.is_empty() {
@ -51,53 +83,30 @@ pub async fn download(client: &Client, store: &Arc<Store>, id: TaskId, source: S
}
let mut probe = probe(client, &source, &mut stop).await?;
let mut body = probe.body.take();
let body = probe.body.take();
let link = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version.clone() };
let (file, parts) = match file {
Some(file) => resume(&job, &task, file, parts, &link, &mut stop).await?,
None => start(&job, &task, probe, options).await?,
None => start(&job, &task, probe).await?,
};
if let Some(size) = link.version.size {
let reserving = file.clone();
blocking(move || reserving.reserve(size)).await?;
}
let live: Vec<_> = parts.into_iter().map(LivePart::new).collect();
let (link, (halt, halted)) = (Arc::new(link), watch::channel(false));
let mut running = JoinSet::new();
for part in &live {
let (link, part, file, body, halted) = (link.clone(), part.clone(), file.clone(), body.take(), halted.clone());
running.spawn(async move { fetch(&link, &part, &file, body, halted).await });
}
let mut tick = interval(options.checkpoint);
tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut failed = None;
loop {
let result = tokio::select! {
done = running.join_next() => match done {
None => break,
Some(Ok(result)) => result,
Some(Err(e)) => std::panic::resume_unwind(e.into_panic()),
},
_ = tick.tick() => job.checkpoint(&live, &file).await,
_ = stopped(&mut stop), if failed.is_none() => Err(Error::Stopped),
};
if let Err(e) = result {
failed.get_or_insert(e);
halt.send_replace(true);
}
}
if failed.is_none() {
// The end of a file without a length is known now.
for part in &live {
let p = part.get();
part.set_end(p.end.unwrap_or(p.start + p.done));
}
}
let host = host::key(&link.source.url);
let asked = host.clone();
let known = job.run(move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default();
shared.hosts.set_host_cap(&host, known.max_connections);
let start = host::tolerated(&known, model::now()).unwrap_or(adapt::START);
let mut run = Run::new(shared, link, file.clone(), parts, body, host.clone(), start, task.max_parts, options, monitor);
let result = run.go(&job, &mut stop).await;
let (live, learned) = run.end();
let saved = job.checkpoint(&live, &file).await;
if let Some(e) = failed {
return Err(e);
if let Some(n) = learned {
job.run(move |s| Ok(host::remember(s, &host, n, model::now())?)).await?;
}
result?;
saved?;
let size = live.iter().map(|p| p.get().done).sum();
let file = Arc::into_inner(file).expect("the parts have ended");
@ -108,11 +117,8 @@ fn finished(p: &Part) -> bool {
p.end == Some(p.start + p.done)
}
async fn start(job: &Job, task: &Task, probe: Probe, options: &Options) -> Result<(Arc<PartialFile>, Vec<Part>)> {
let parts = match probe.version.size {
Some(size) if probe.ranges => part::split(size, task.max_parts.unwrap_or(u32::MAX).min(options.parts), options.min_part),
_ => vec![Part { start: 0, end: None, done: 0 }],
};
async fn start(job: &Job, task: &Task, probe: Probe) -> Result<(Arc<PartialFile>, Vec<Part>)> {
let parts = vec![Part { start: 0, end: probe.version.size.filter(|_| probe.ranges), done: 0 }];
let wanted = safe_name(&task.name).unwrap_or(probe.name);
let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone());
let file = job
@ -171,19 +177,20 @@ async fn resume(job: &Job, task: &Task, file: PartialFile, mut parts: Vec<Part>,
Ok((file, parts))
}
struct Job {
#[derive(Clone)]
pub(super) struct Job {
store: Arc<Store>,
id: TaskId,
}
impl Job {
async fn run<T: Send + 'static>(&self, work: impl FnOnce(&Store) -> Result<T> + Send + 'static) -> Result<T> {
pub(super) async fn run<T: Send + 'static>(&self, work: impl FnOnce(&Store) -> Result<T> + Send + 'static) -> Result<T> {
let store = self.store.clone();
blocking(move || work(&store)).await
}
/// Data first, then the record of it: the record never claims bytes that a power cut could take.
async fn checkpoint(&self, live: &[Arc<LivePart>], file: &Arc<PartialFile>) -> Result<()> {
pub(super) async fn checkpoint(&self, live: &[Arc<LivePart>], file: &Arc<PartialFile>) -> Result<()> {
let parts: Vec<Part> = live.iter().map(|p| p.get()).collect();
let (id, file) = (self.id, file.clone());
self.run(move |store| {

View file

@ -37,6 +37,7 @@ pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Optio
} else {
(whole(link, part, body, &mut stop).await?, vec![])
};
part.begin();
let mut buf = Vec::with_capacity(BUFFER);
let mut flushed = Instant::now();
loop {
@ -53,6 +54,7 @@ pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Optio
}
known.drain(..old.len());
buf.extend_from_slice(&chunk);
part.arrive(chunk.len() as u64);
let whole = part.remaining().is_some_and(|left| buf.len() as u64 >= left);
if whole || buf.len() >= BUFFER || flushed.elapsed() >= FLUSH_EVERY {
buf = flush(part, file, buf).await?;

View file

@ -2,11 +2,14 @@
mod download;
mod fetch;
mod monitor;
pub(crate) mod name;
mod parts;
mod probe;
pub use download::{Options, download};
pub use download::{Options, Shared, download};
pub use fetch::{Link, OVERLAP, compare, fetch};
pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
pub use name::safe as safe_name;
pub use probe::{Probe, probe};
@ -93,6 +96,8 @@ pub fn client(options: &ClientOptions) -> Result<Client> {
.referer(false)
.retry(reqwest::retry::never())
.no_proxy()
// Reused at once or not at all: idle ones count against what a host stands.
.pool_idle_timeout(Duration::from_millis(500))
.connect_timeout(options.connect_timeout)
.read_timeout(options.idle_timeout);
if !options.only_certs.is_empty() {

View file

@ -0,0 +1,107 @@
//! What others see of a running download, and its cap on connections.
use crate::part::LivePart;
use std::sync::{Arc, Mutex};
use tokio::sync::{broadcast, watch};
pub type PartId = u32;
/// A change of the parts. Whoever falls behind starts over from a snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartEvent {
/// Here from the start, or left over from before.
Born { id: PartId, start: u64, end: Option<u64> },
/// `from` ends at `at` now; the rest, up to `end`, is `id`, with a connection of its own.
Split { from: PartId, id: PartId, at: u64, end: u64 },
/// What is left of the part goes to another connection.
Stolen { id: PartId },
Done { id: PartId },
/// Both were done; `gone` is a piece of `into` now.
Merged { into: PartId, gone: PartId },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartState {
/// No connection: none free, or a pause after a failure.
Waiting,
Connecting,
Running,
Done,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PartView {
pub id: PartId,
pub start: u64,
/// None when the length is unknown.
pub end: Option<u64>,
/// Arrived, with what is still in memory.
pub done: u64,
pub state: PartState,
/// Bytes per second.
pub speed: f64,
/// Failures in a row.
pub fails: u32,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Snapshot {
pub size: Option<u64>,
/// In the order of the file.
pub parts: Vec<PartView>,
/// Connections now, and how many the download wants.
pub connections: u32,
pub wanted: u32,
/// Bytes that came over the network since the start of this run.
pub received: u64,
/// Bytes per second.
pub speed: f64,
}
/// One per download; outlives its runs.
#[derive(Debug)]
pub struct Monitor {
cap: watch::Sender<u32>,
events: broadcast::Sender<PartEvent>,
state: Mutex<(Snapshot, Vec<Arc<LivePart>>)>,
}
impl Monitor {
/// With a cap on connections.
pub fn new(cap: u32) -> Monitor {
Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default() }
}
/// Takes effect at once, up and down.
pub fn set_cap(&self, cap: u32) {
self.cap.send_replace(cap);
}
pub fn subscribe(&self) -> broadcast::Receiver<PartEvent> {
self.events.subscribe()
}
/// Positions are of this moment, speeds and states of the last tick.
pub fn snapshot(&self) -> Snapshot {
let state = self.state.lock().unwrap();
let mut shot = state.0.clone();
for (view, part) in shot.parts.iter_mut().zip(&state.1) {
let p = part.get();
(view.start, view.end, view.done) = (p.start, p.end, part.pos() - p.start);
}
shot
}
pub(super) fn cap(&self) -> watch::Receiver<u32> {
self.cap.subscribe()
}
/// The snapshot first: whoever sees the events finds them in it.
pub(super) fn publish(&self, shot: Snapshot, parts: Vec<Arc<LivePart>>, events: impl Iterator<Item = PartEvent>) {
*self.state.lock().unwrap() = (shot, parts);
for e in events {
// Nobody has to listen.
let _ = self.events.send(e);
}
}
}

View file

@ -0,0 +1,492 @@
//! The parts of one download while it runs: which connection works on what.
use super::download::Job;
use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
use super::*;
use crate::adapt::Adapt;
use crate::disk::PartialFile;
use crate::host::{Hosts, Permit};
use crate::model::Part;
use crate::part::LivePart;
use crate::segment::{self, Pick, View};
use std::hash::{BuildHasher, RandomState};
use std::sync::Arc;
use std::time::Instant;
use tokio::task::JoinSet;
use tokio::time::{MissedTickBehavior, interval};
/// Speeds are averaged over about this many ticks.
const SMOOTH: u32 = 8;
pub(super) struct Run<'a> {
link: Arc<Link>,
file: Arc<PartialFile>,
body: Option<Response>,
host: String,
hosts: Arc<Hosts>,
max_parts: Option<u32>,
options: &'a Options,
monitor: &'a Monitor,
adapt: Adapt,
/// In the order of the file.
slots: Vec<Slot>,
next_id: PartId,
workers: JoinSet<(PartId, Result<()>)>,
events: Vec<PartEvent>,
failed: Option<Error>,
received: u64,
speed: f64,
/// What one connection usually brings.
usual: f64,
measured: Instant,
/// Connections that delivered at the same time.
worked: u32,
}
struct Slot {
id: PartId,
part: Arc<LivePart>,
worker: Option<Worker>,
/// No connection before this.
rest_until: Option<Instant>,
/// In a row, without a byte.
fails: u32,
/// Connections taken away because they were slow.
swaps: u32,
/// Had a connection before.
used: bool,
}
struct Worker {
stop: watch::Sender<bool>,
permit: Permit,
leaving: bool,
/// `received` of the part at the start and at the last tick.
first: u64,
seen: u64,
/// Since the start, or since it was last more.
quiet_since: Instant,
delivers: Option<Instant>,
speed: Option<f64>,
}
impl Slot {
fn running(&self) -> Option<&Worker> {
self.worker.as_ref().filter(|w| !w.leaving)
}
fn send_away(&mut self) {
if let Some(w) = &mut self.worker {
w.leaving = true;
w.stop.send_replace(true);
}
}
}
/// What an error of one part means for the download.
enum Weight {
Fatal,
/// The server may not want another connection. Fatal if it is the only one and asking again is no use.
Refused { again: bool },
Broken,
}
fn weigh(e: &Error) -> Weight {
match e {
Error::Status { code: 429 | 503, .. } => Weight::Refused { again: true },
Error::Status { code: 408 | 425 | 500..=599, .. } | Error::Cut { .. } => Weight::Broken,
Error::Status { .. } | Error::RangeIgnored => Weight::Refused { again: false },
Error::Net(e) if e.is_redirect() || e.is_builder() => Weight::Fatal,
Error::Net(e) if e.is_connect() => Weight::Refused { again: true },
Error::Net(_) => Weight::Broken,
_ => Weight::Fatal,
}
}
impl<'a> Run<'a> {
#[allow(clippy::too_many_arguments)]
pub(super) fn new(
shared: &Shared,
link: Link,
file: Arc<PartialFile>,
parts: Vec<Part>,
body: Option<Response>,
host: String,
start: u32,
max_parts: Option<u32>,
options: &'a Options,
monitor: &'a Monitor,
) -> Run<'a> {
let cap = *monitor.cap().borrow();
let mut run = Run {
link: Arc::new(link),
file,
body,
host,
hosts: shared.hosts.clone(),
max_parts,
options,
monitor,
adapt: Adapt::new(start, cap.min(max_parts.unwrap_or(u32::MAX)), options.timing),
slots: vec![],
next_id: 0,
workers: JoinSet::new(),
events: vec![],
failed: None,
received: 0,
speed: 0.0,
usual: 0.0,
measured: Instant::now(),
worked: 0,
};
for p in parts {
let slot = run.slot(p);
run.events.push(PartEvent::Born { id: slot.id, start: p.start, end: p.end });
run.slots.push(slot);
}
run.merge();
run
}
/// Until all parts are whole, something breaks for good, or `stop`. All connections have ended by then.
pub(super) async fn go(&mut self, job: &Job, stop: &mut Stop) -> Result<()> {
let (mut cap, mut hosts) = (self.monitor.cap(), self.hosts.watch());
let mut tick = interval(self.options.tick);
let mut checkpoint = interval(self.options.checkpoint);
for i in [&mut tick, &mut checkpoint] {
i.set_missed_tick_behavior(MissedTickBehavior::Delay);
}
let mut saving = JoinSet::new();
loop {
if self.failed.is_none() {
self.adapt.set_cap(cap.borrow_and_update().min(self.max_parts.unwrap_or(u32::MAX)));
self.schedule(Instant::now());
}
self.publish();
if self.workers.is_empty() && (self.failed.is_some() || self.slots.iter().all(|s| s.part.finished())) {
break;
}
tokio::select! {
Some(ended) = self.workers.join_next() => match ended {
Ok((id, result)) => self.ended(id, result, Instant::now()),
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
_ = tick.tick() => self.measure(Instant::now()),
_ = checkpoint.tick(), if saving.is_empty() => {
let (job, live, file) = (job.clone(), self.live(), self.file.clone());
saving.spawn(async move { job.checkpoint(&live, &file).await });
}
Some(saved) = saving.join_next() => match saved {
Ok(Ok(())) => {}
Ok(Err(e)) => self.fail(e),
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
_ = stopped(stop), if self.failed.is_none() => self.fail(Error::Stopped),
_ = cap.changed() => {}
_ = hosts.changed() => {}
}
}
// The caller saves once more; two at a time could end in the wrong order.
while let Some(saved) = saving.join_next().await {
if let Ok(Err(e)) = saved {
self.fail(e);
}
}
self.failed.take().map_or(Ok(()), Err)
}
/// The parts, and the number of connections to remember for the host. Lets go of the file.
pub(super) fn end(self) -> (Vec<Arc<LivePart>>, Option<u32>) {
(self.live(), self.adapt.learned().filter(|_| self.link.ranges))
}
fn live(&self) -> Vec<Arc<LivePart>> {
self.slots.iter().map(|s| s.part.clone()).collect()
}
fn slot(&mut self, part: Part) -> Slot {
self.next_id += 1;
Slot { id: self.next_id, part: LivePart::new(part), worker: None, rest_until: None, fails: 0, swaps: 0, used: false }
}
fn fail(&mut self, e: Error) {
self.failed.get_or_insert(e);
self.slots.iter_mut().for_each(Slot::send_away);
}
fn running(&self) -> u32 {
self.slots.iter().filter(|s| s.running().is_some()).count() as u32
}
fn delivering(&self) -> u32 {
self.slots.iter().filter_map(Slot::running).filter(|w| w.delivers.is_some()).count() as u32
}
fn wanted(&self) -> u32 {
if self.link.ranges { self.adapt.target() } else { 1 }
}
fn schedule(&mut self, now: Instant) {
if !self.link.ranges {
// One part without resume: no cuts, no second connection.
let i = self.slots.iter().position(|s| !s.part.finished());
if let Some(i) = i.filter(|i| self.slots[*i].worker.is_none())
&& let Some(permit) = self.hosts.open(&self.host, now)
{
self.begin(i, permit, now);
}
return;
}
for s in &mut self.slots {
if s.running().is_some_and(|w| w.permit.revoked()) {
s.send_away();
}
}
for _ in self.wanted()..self.running() {
let usual = self.usual;
// A new one is taken for an average one.
let speed = |s: &Slot| s.running().map_or(0.0, |w| w.speed.unwrap_or(usual));
let slowest = self.slots.iter_mut().filter(|s| s.running().is_some()).min_by(|a, b| speed(a).total_cmp(&speed(b)));
slowest.map(Slot::send_away);
}
self.drop_stalled(now);
while self.running() < self.wanted() {
let views: Vec<View> = self.slots.iter().map(|s| view(s, now)).collect();
// A part that waits after a failure keeps its place, or the others would be cut for connections that fail too.
let waiting = views.iter().filter(|v| v.slot == segment::Slot::Resting).count() as u32;
let full = self.running() + waiting >= self.wanted();
let pick = segment::next(&views, &self.options.rules).filter(|p| !full || matches!(p, Pick::Take(_)));
let Some(pick) = pick else {
self.drop_crawling(&views, now);
break;
};
let Some(permit) = self.hosts.open(&self.host, now) else { break };
match pick {
Pick::Take(i) => self.begin(i, permit, now),
Pick::Split { part, at } => {
let end = views[part].end;
// False when it got beyond `at` in the meantime.
if !self.slots[part].part.set_end(at) {
break;
}
let slot = self.slot(Part { start: at, end: Some(end), done: 0 });
self.events.push(PartEvent::Split { from: self.slots[part].id, id: slot.id, at, end });
self.slots.insert(part + 1, slot);
self.begin(part + 1, permit, now);
}
}
}
}
/// A connection that brings nothing is replaced. One that never did only while others do: the server may be slow to answer.
fn drop_stalled(&mut self, now: Instant) {
let others = self.delivering() > 0;
for s in &mut self.slots {
if s.running().is_some_and(|w| now - w.quiet_since >= self.options.stall && (w.delivers.is_some() || others)) {
s.send_away();
}
}
}
/// There is a connection to spare and nothing left to cut: the slowest part gets another one.
fn drop_crawling(&mut self, views: &[View], now: Instant) {
// One at a time.
if self.slots.iter().any(|s| s.worker.as_ref().is_some_and(|w| w.leaving)) {
return;
}
for (s, v) in self.slots.iter_mut().zip(views) {
// Twice as patient after each time that didn't help.
let patience = self.options.patience * (1 << s.swaps.min(8));
let long = s.running().and_then(|w| w.delivers).is_some_and(|since| now - since >= patience);
if long && segment::crawls(v, self.usual, patience) {
s.swaps += 1;
s.send_away();
return;
}
}
}
fn begin(&mut self, i: usize, permit: Permit, now: Instant) {
let s = &mut self.slots[i];
if s.used {
self.events.push(PartEvent::Stolen { id: s.id });
}
let (stop, stopping) = watch::channel(false);
let first = s.part.received();
s.worker = Some(Worker { stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None });
(s.used, s.rest_until) = (true, None);
let (id, link, part, file, body) = (s.id, self.link.clone(), s.part.clone(), self.file.clone(), self.body.take());
self.workers.spawn(async move { (id, fetch(&link, &part, &file, body, stopping).await) });
}
fn ended(&mut self, id: PartId, result: Result<()>, now: Instant) {
let i = self.slots.iter().position(|s| s.id == id).expect("parts with a connection are never merged");
let s = &mut self.slots[i];
let w = s.worker.take().expect("it just ended");
let got = s.part.received();
self.received += got - w.seen;
if got > w.first {
s.fails = 0;
} else if result.is_err() && !w.leaving {
s.fails += 1;
}
match result {
Ok(()) => {
let p = s.part.get();
// The end of a file without a length is known now.
s.part.set_end(p.end.unwrap_or(p.start + p.done));
self.events.push(PartEvent::Done { id });
// This connection works: it may try what others failed at, and they start counting anew.
self.slots.iter_mut().for_each(|s| (s.rest_until, s.fails) = (None, 0));
self.merge();
}
Err(Error::Stopped) if w.leaving => {}
Err(e) if self.failed.is_some() || !self.link.ranges => self.fail(e),
Err(e) => self.broken(i, e, now),
}
}
/// One part failed. The others go on.
fn broken(&mut self, i: usize, e: Error, now: Instant) {
let (others, running) = (self.delivering(), self.running());
let retry_after = if let Error::Status { retry_after, .. } = &e { *retry_after } else { None };
let s = &mut self.slots[i];
let wait = backoff(self.options, s.fails).max(retry_after.unwrap_or_default());
let hopeless = others == 0 && (s.fails >= self.options.tries || retry_after.is_some_and(|d| d > self.options.max_wait));
match weigh(&e) {
Weight::Fatal => return self.fail(e),
Weight::Refused { again: false } if others == 0 => return self.fail(e),
_ if hopeless => return self.fail(e),
// As many worked a moment ago: the server may still count one that was just closed.
Weight::Refused { .. } if others > 0 && running < self.worked && s.fails < 2 => {}
Weight::Refused { .. } => {
self.worked = running;
self.adapt.refused(now, running, others > 0);
if others > 0 {
self.hosts.refused(&self.host, now + self.options.timing.refused);
}
}
Weight::Broken => {}
}
if let Some(pause) = retry_after {
self.hosts.rest(&self.host, now + pause);
}
self.slots[i].rest_until = Some(now + wait);
log::debug!("part {} failed, again in {wait:?}: {e:?}", self.slots[i].id);
}
/// Neighbours that are whole become one.
fn merge(&mut self) {
let whole = |s: &Slot| s.worker.is_none() && s.part.finished();
let mut i = 1;
while i < self.slots.len() {
let (a, b) = (&self.slots[i - 1], &self.slots[i]);
let (p, q) = (a.part.get(), b.part.get());
if whole(a) && whole(b) && p.end == Some(q.start) {
self.events.push(PartEvent::Merged { into: a.id, gone: b.id });
self.slots[i - 1].part = LivePart::new(Part { start: p.start, end: q.end, done: p.done + q.done });
self.slots.remove(i);
} else {
i += 1;
}
}
}
fn measure(&mut self, now: Instant) {
let secs = (now - self.measured).as_secs_f64();
if secs <= 0.0 {
return;
}
self.measured = now;
let share = 1.0 - (-secs / (self.options.tick * SMOOTH).as_secs_f64()).exp();
let smooth = |old: f64, new: f64| old + share * (new - old);
let before = self.received;
let mut speeds = vec![];
for s in &mut self.slots {
let Some(w) = &mut s.worker else { continue };
let got = s.part.received();
let delta = got - w.seen;
w.seen = got;
self.received += delta;
if delta > 0 {
w.quiet_since = now;
}
if w.delivers.is_none() {
// Its first tick is cut short.
w.delivers = (delta > 0).then_some(now);
} else {
let rate = delta as f64 / secs;
let speed = w.speed.map_or(rate, |old| smooth(old, rate));
w.speed = Some(speed);
speeds.push(speed);
}
}
self.speed = smooth(self.speed, (self.received - before) as f64 / secs);
// The last one left is compared with what others brought before.
if speeds.len() > 1 {
speeds.sort_by(f64::total_cmp);
// With two, the better one.
self.usual = smooth(self.usual, speeds[speeds.len() / 2]);
}
let delivering = self.delivering();
self.worked = self.worked.max(delivering);
self.adapt.tick(now, self.running(), delivering, self.received);
}
fn publish(&mut self) {
let parts = self.slots.iter().map(|s| {
let p = s.part.get();
let state = match s.running() {
Some(w) if w.delivers.is_some() => PartState::Running,
Some(_) => PartState::Connecting,
None if s.part.finished() => PartState::Done,
None => PartState::Waiting,
};
let speed = s.running().and_then(|w| w.speed).unwrap_or(0.0);
PartView { id: s.id, start: p.start, end: p.end, done: s.part.pos() - p.start, state, speed, fails: s.fails }
});
let shot = Snapshot {
size: self.link.version.size,
parts: parts.collect(),
connections: self.running(),
wanted: self.wanted(),
received: self.received,
speed: if self.workers.is_empty() { 0.0 } else { self.speed },
};
self.monitor.publish(shot, self.live(), self.events.drain(..));
}
}
fn view(s: &Slot, now: Instant) -> View {
let slot = match &s.worker {
Some(w) if w.leaving => segment::Slot::Resting,
Some(w) => segment::Slot::Busy(w.speed),
None if s.rest_until.is_some_and(|until| now < until) => segment::Slot::Resting,
None => segment::Slot::Free,
};
let pos = s.part.pos();
View { pos, end: s.part.get().end.unwrap_or(pos), slot }
}
/// Doubles with each failure; half of it is chance, so that parts don't come back all at once.
fn backoff(options: &Options, fails: u32) -> Duration {
let full = options.backoff.saturating_mul(1 << fails.saturating_sub(1).min(16)).min(options.max_wait);
let chance = RandomState::new().hash_one(fails) % 1000;
full / 2 + full.mul_f64(chance as f64 / 2000.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backoff_doubles_with_jitter_and_ends() {
let options = Options::default();
for (fails, full) in [(1, 1), (2, 2), (4, 8), (7, 60), (1000, 60)] {
let full = Duration::from_secs(full);
let waits: Vec<_> = (0..200).map(|_| backoff(&options, fails)).collect();
assert!(waits.iter().all(|w| *w >= full / 2 && *w <= full));
assert!(waits.iter().max().unwrap().saturating_sub(*waits.iter().min().unwrap()) > full / 4);
}
}
}

View file

@ -1,12 +1,15 @@
//! Medlar's engine, limits, queues, store and settings. No UI code.
pub mod adapt;
pub mod disk;
pub mod host;
pub mod http;
pub mod logging;
pub mod model;
pub mod part;
pub mod paths;
pub mod redact;
pub mod segment;
pub mod settings;
pub mod store;
pub mod strings;

View file

@ -12,11 +12,15 @@ struct Inner {
part: Part,
/// Bytes now on their way to the disk. `part.done` counts only those that arrived.
claimed: u64,
/// Bytes in memory, the claimed ones too. They may reach beyond the end.
buffered: u64,
/// Bytes that came over the network, overlaps not counted. Never goes down.
received: u64,
}
impl LivePart {
pub fn new(part: Part) -> Arc<LivePart> {
Arc::new(LivePart(Mutex::new(Inner { part, claimed: 0 })))
Arc::new(LivePart(Mutex::new(Inner { part, claimed: 0, buffered: 0, received: 0 })))
}
pub fn get(&self) -> Part {
@ -33,16 +37,39 @@ impl LivePart {
p.end.map(|end| end - p.start - p.done)
}
/// Moves the end. Refused when it would cut bytes already written or being written.
/// The next byte the network has to bring.
pub fn pos(&self) -> u64 {
let i = self.0.lock().unwrap();
let pos = i.part.start + i.part.done + i.buffered;
i.part.end.map_or(pos, |end| pos.min(end))
}
pub fn received(&self) -> u64 {
self.0.lock().unwrap().received
}
/// Moves the end. Refused when it would cut bytes that are here already.
pub fn set_end(&self, end: u64) -> bool {
let mut i = self.0.lock().unwrap();
let ok = end >= i.part.start + i.part.done + i.claimed;
let ok = end >= i.part.start + i.part.done + i.claimed.max(i.buffered);
if ok {
i.part.end = Some(end);
}
ok
}
/// A connection starts with nothing in memory.
pub(crate) fn begin(&self) {
self.0.lock().unwrap().buffered = 0;
}
/// New bytes are in memory.
pub(crate) fn arrive(&self, n: u64) {
let mut i = self.0.lock().unwrap();
i.buffered += n;
i.received += n;
}
/// Reserves the next bytes for writing: where they go, and how many of `n` still belong to this part. One writer at a time.
pub(crate) fn claim(&self, n: u64) -> (u64, u64) {
let mut i = self.0.lock().unwrap();
@ -58,32 +85,14 @@ impl LivePart {
i.part.done += i.claimed;
}
i.claimed = 0;
i.buffered = 0;
}
}
/// `size` bytes in up to `count` ranges of about the same length, none shorter than `min` unless it is the only one.
pub fn split(size: u64, count: u32, min: u64) -> Vec<Part> {
let count = (size / min.max(1)).clamp(1, u64::from(count.max(1)));
let edge = |i: u64| (u128::from(size) * u128::from(i) / u128::from(count)) as u64;
(0..count).map(|i| Part { start: edge(i), end: Some(edge(i + 1)), done: 0 }).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_covers_everything_once() {
for (size, count, min) in [(0, 4, 10), (1, 4, 10), (39, 4, 10), (1000, 7, 1), (u64::MAX / 2, 32, 1 << 20), (5, 0, 0)] {
let parts = split(size, count, min);
assert!(parts.len() <= count.max(1) as usize);
assert_eq!(parts[0].start, 0);
assert_eq!(parts.last().unwrap().end, Some(size));
assert!(parts.windows(2).all(|w| w[0].end == Some(w[1].start)));
}
assert_eq!(split(39, 4, 10).len(), 3);
}
#[test]
fn the_end_never_cuts_written_bytes() {
let part = LivePart::new(Part { start: 100, end: Some(200), done: 10 });
@ -97,4 +106,17 @@ mod tests {
part.settle(false);
assert_eq!(part.remaining(), Some(10));
}
#[test]
fn bytes_in_memory_are_kept_too() {
let part = LivePart::new(Part { start: 100, end: Some(200), done: 10 });
part.arrive(30);
assert_eq!((part.pos(), part.received()), (140, 30));
assert!(!part.set_end(139));
assert!(part.set_end(150));
part.arrive(30);
assert_eq!(part.pos(), 150);
assert_eq!(part.claim(60), (110, 40));
part.settle(true);
assert_eq!((part.pos(), part.received(), part.finished()), (150, 60, true));
}
}

196
crates/core/src/segment.rs Normal file
View file

@ -0,0 +1,196 @@
//! Which range a free connection takes. Decides only: no clock, no network, no disk.
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
pub struct Rules {
/// No cut leaves a range shorter than this.
pub min: u64,
/// Cuts fall on multiples of this.
pub align: u64,
/// A part that ends sooner is left alone.
pub min_time: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Slot {
/// Nobody works on it.
Free,
/// Nobody works on it and nobody should yet.
Resting,
/// Bytes per second, once known.
Busy(Option<f64>),
}
/// What is left of a part: bytes `pos..end`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct View {
pub pos: u64,
pub end: u64,
pub slot: Slot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pick {
/// The whole part, by index.
Take(usize),
/// The part ends at `at` from now on; `at..` its old end is the new one's.
Split { part: usize, at: u64 },
}
impl View {
fn left(&self) -> u64 {
self.end.saturating_sub(self.pos)
}
/// Where to cut it in halves.
fn cut(&self, rules: &Rules) -> Option<u64> {
let (min, align) = (rules.min.max(1), rules.align.max(1));
let mid = self.pos + self.left() / 2;
let down = mid / align * align;
[down, down.saturating_add(align)]
.into_iter()
.filter(|at| *at >= self.pos.saturating_add(min) && self.end >= at.saturating_add(min))
.min_by_key(|at| at.abs_diff(mid))
}
}
/// The best use of one more connection: a part nobody has, else half of the part with the longest time left.
pub fn next(parts: &[View], rules: &Rules) -> Option<Pick> {
if let Some(i) = parts.iter().position(|p| p.slot == Slot::Free && p.left() > 0) {
return Some(Pick::Take(i));
}
let speeds: Vec<f64> = parts.iter().filter_map(|p| if let Slot::Busy(s) = p.slot { s.filter(|s| *s > 0.0) } else { None }).collect();
// A new connection is taken for an average one.
let usual = if speeds.is_empty() { 1.0 } else { speeds.iter().sum::<f64>() / speeds.len() as f64 };
parts
.iter()
.enumerate()
.filter_map(|(part, p)| {
let Slot::Busy(speed) = p.slot else { return None };
let time = p.left() as f64 / speed.unwrap_or(usual);
let worth = speed.is_none() || time >= rules.min_time.as_secs_f64();
p.cut(rules).filter(|_| worth).map(|at| (time, Pick::Split { part, at }))
})
.max_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, pick)| pick)
}
/// Far slower than a connection usually is, and not about to end.
pub fn crawls(part: &View, usual: f64, patience: Duration) -> bool {
match part.slot {
Slot::Busy(Some(speed)) => speed < usual / 4.0 && part.left() as f64 > speed * patience.as_secs_f64(),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
const RULES: Rules = Rules { min: 100, align: 64, min_time: Duration::ZERO };
fn view(pos: u64, end: u64, slot: Slot) -> View {
View { pos, end, slot }
}
#[test]
fn free_parts_come_first_then_the_longest_time() {
use Slot::*;
let mut parts = vec![view(0, 10_000, Busy(Some(1000.0))), view(10_000, 12_000, Busy(Some(10.0))), view(12_000, 20_000, Resting)];
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 1, at: 11_008 }));
parts[1].slot = Busy(None);
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 0, at: 4992 }));
parts[0].slot = Busy(Some(0.0));
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 0, at: 4992 }));
parts[2].slot = Free;
assert_eq!(next(&parts, &RULES), Some(Pick::Take(2)));
}
#[test]
fn small_and_short_parts_are_left_alone() {
let busy = |pos, end, speed| [view(pos, end, Slot::Busy(Some(speed)))];
assert_eq!(next(&busy(0, 199, 1.0), &RULES), None);
// Long enough, but no multiple of 64 fits.
assert_eq!(next(&busy(1, 210, 1.0), &RULES), None);
assert_eq!(next(&busy(0, 256, 1.0), &RULES), Some(Pick::Split { part: 0, at: 128 }));
let patient = Rules { min_time: Duration::from_secs(2), ..RULES };
assert_eq!(next(&busy(0, 10_000, 5001.0), &patient), None);
assert!(next(&busy(0, 10_000, 4999.0), &patient).is_some());
assert_eq!(next(&[], &RULES), None);
assert_eq!(next(&[view(0, 10_000, Slot::Resting)], &RULES), None);
assert!(next(&busy(u64::MAX / 2 - 5000, u64::MAX / 2, 1.0), &RULES).is_some());
}
#[test]
fn crawling() {
let two = Duration::from_secs(2);
assert!(crawls(&view(0, 1000, Slot::Busy(Some(10.0))), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Busy(Some(30.0))), 100.0, two));
assert!(!crawls(&view(0, 19, Slot::Busy(Some(10.0))), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Busy(None)), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Free), 100.0, two));
}
/// Random progress, errors, rests and picks: every byte is in exactly one part, all the time, and the file gets done.
#[test]
fn no_gap_and_no_overlap() {
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut random = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
let mut splits = 0;
for round in 0..400 {
let size = random(200_000) + 1;
let rules = Rules { min: random(5000), align: 1 << random(12), min_time: Duration::ZERO };
// Start of each part, kept apart from its view.
let mut parts = vec![(0, view(0, size, Slot::Free))];
let mut steps = 0;
while parts.iter().any(|(_, p)| p.left() > 0) {
steps += 1;
assert!(steps < 100_000, "round {round} never ends");
let i = random(parts.len() as u64) as usize;
match random(10) {
0 => {
let views: Vec<View> = parts.iter().map(|(_, p)| *p).collect();
match next(&views, &rules) {
Some(Pick::Take(i)) => {
assert_eq!(parts[i].1.slot, Slot::Free);
parts[i].1.slot = Slot::Busy(None);
}
Some(Pick::Split { part, at }) => {
let p = &mut parts[part].1;
assert!(matches!(p.slot, Slot::Busy(_)));
assert!(at - p.pos >= rules.min && p.end - at >= rules.min && at % rules.align == 0);
assert!(at > p.pos && at < p.end);
let new = view(at, p.end, Slot::Busy(None));
p.end = at;
parts.insert(part + 1, (at, new));
splits += 1;
}
None => {}
}
}
1 if parts[i].1.slot != Slot::Free && parts[i].1.left() > 0 => {
parts[i].1.slot = [Slot::Free, Slot::Resting][random(2) as usize];
}
2 if parts[i].1.slot == Slot::Resting => parts[i].1.slot = Slot::Free,
_ => {
let p = &mut parts[i].1;
if let Slot::Busy(_) = p.slot {
p.slot = Slot::Busy(Some(random(1000) as f64));
p.pos += random(2000).min(p.left());
}
}
}
assert_eq!((parts[0].0, parts.last().unwrap().1.end), (0, size));
assert!(parts.windows(2).all(|w| w[0].1.end == w[1].0));
assert!(parts.iter().all(|(start, p)| *start <= p.pos && p.pos <= p.end));
}
}
assert!(splits > 1000, "{splits}");
}
}

View file

@ -1,9 +1,11 @@
//! Downloads against the test server, through every fault, and killed at random moments.
use medlar_core::disk::{self, PartialFile, partial_path};
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::*;
use medlar_core::model::{Part, Task, TaskId};
use medlar_core::part::LivePart;
use medlar_core::segment::Rules;
use medlar_core::store::Store;
use medlar_testserver::{Faults, TestServer, expected};
use reqwest::Client;
@ -20,12 +22,29 @@ fn sha(data: &[u8]) -> Vec<u8> {
Sha256::digest(data).to_vec()
}
fn options() -> Options {
Options {
rules: Rules { min: 64 * 1024, align: 4096, min_time: Duration::ZERO },
tick: Duration::from_millis(20),
stall: Duration::from_millis(500),
backoff: Duration::from_millis(20),
checkpoint: Duration::from_millis(15),
..Options::default()
}
}
fn shared(store: &Arc<Store>, client: &Client) -> Shared {
let hosts = Hosts::new(Caps { burst: 100, per_second: 100.0, ..Caps::default() });
Shared { client: client.clone(), store: store.clone(), hosts }
}
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
store: Arc<Store>,
client: Client,
options: Options,
cap: u32,
}
impl Bench {
@ -38,8 +57,7 @@ impl Bench {
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let only_certs = server.cert_der().into_iter().collect();
let client = client(&ClientOptions { idle_timeout: Duration::from_millis(1500), only_certs, ..ClientOptions::default() }).unwrap();
let options = Options { parts: 4, min_part: 64 * 1024, checkpoint: Duration::from_millis(20) };
Bench { server, dir, store, client, options }
Bench { server, dir, store, client, options: options(), cap: 4 }
}
fn folder(&self) -> PathBuf {
@ -52,7 +70,7 @@ impl Bench {
async fn run_until(&self, id: TaskId, stop: Stop) -> Result<PathBuf> {
let source = Source::new(&self.store.task(id).unwrap().url).unwrap();
download(&self.client, &self.store, id, source, &self.options, stop).await
download(&shared(&self.store, &self.client), id, source, &self.options, &Monitor::new(self.cap), stop).await
}
async fn run(&self, id: TaskId) -> Result<PathBuf> {
@ -97,20 +115,20 @@ fn slow(per_connection: u64) -> Faults {
}
#[tokio::test(flavor = "multi_thread")]
async fn four_ranges_make_one_file() {
async fn ranges_make_one_file() {
let b = Bench::new().await;
let id = b.add("/data/1/5000003/a.bin");
let path = b.run(id).await.unwrap();
assert_eq!(path, b.folder().join("a.bin"));
b.check(&path, 1, 5_000_003);
let requests = b.server.requests_for("/data/1/5000003/a.bin");
assert_eq!(requests.len(), 5, "a probe and four ranges");
assert!(requests.len() >= 3, "a probe and two ranges or more");
for r in &requests {
assert_eq!((r.status, r.header("accept-encoding")), (206, Some("identity")));
// No status: the client hung up, as the rest of the range had gone to another connection.
assert!(matches!(r.status, 206 | 0) && r.header("accept-encoding") == Some("identity"));
assert!(r.header("referer").is_none());
}
assert!(requests[1..].iter().all(|r| r.header("if-range").is_some()));
assert_eq!(b.sent("/data/1/5000003/a.bin"), 5_000_004);
let task = b.store.task(id).unwrap();
assert_eq!((task.size, task.downloaded, task.name.as_str()), (Some(5_000_003), 5_000_003, "a.bin"));
// Asked again after a crash that came before the state was saved.
@ -156,7 +174,7 @@ async fn cookies_do_not_follow_a_redirect_to_another_site() {
let id = b.add(&format!("/redirect/1?to={}", other.url("/data/1/300k/c.bin")));
let source = Source::new(&b.store.task(id).unwrap().url).unwrap().with_headers(&[("Cookie".into(), "secret=1".into())]);
let (_keep, stop) = watch::channel(false);
let path = download(&b.client, &b.store, id, source, &b.options, stop).await.unwrap();
let path = download(&shared(&b.store, &b.client), id, source, &b.options, &Monitor::new(4), stop).await.unwrap();
b.check(&path, 1, 300 * 1024);
assert!(b.server.log().iter().all(|r| r.header("cookie") == Some("secret=1")));
assert!(!other.log().is_empty() && other.log().iter().all(|r| r.header("cookie").is_none()));
@ -164,7 +182,7 @@ async fn cookies_do_not_follow_a_redirect_to_another_site() {
#[tokio::test(flavor = "multi_thread")]
async fn stop_and_continue() {
let b = Bench::new().await;
let mut b = Bench::new().await;
let path = "/data/5/8m/s.bin";
b.server.set_faults(path, slow(4 * MB));
let id = b.add(path);
@ -173,6 +191,8 @@ async fn stop_and_continue() {
assert!(had > 0);
b.server.clear_all_faults();
b.server.clear_log();
// One connection hangs up nowhere, so the server's count is exact.
b.cap = 1;
let done = b.run(id).await.unwrap();
b.check(&done, 5, 8 * MB);
assert!(b.sent(path) <= 8 * MB - had + 4 * OVERLAP + 1, "finished bytes were loaded again");
@ -189,19 +209,8 @@ async fn a_broken_connection_keeps_what_came() {
let path = "/data/6/8m/f.bin";
let id = b.add(path);
b.server.set_faults(path, fault.clone());
let mut rounds = 0;
let done = loop {
let before = b.store.task(id).unwrap().downloaded;
match b.run(id).await {
Ok(done) => break done,
Err(Error::Cut { .. }) => {}
Err(Error::Net(e)) if e.is_timeout() && fault.stall_after.is_some() => {}
Err(e) => panic!("{e:?}"),
}
assert!(b.store.task(id).unwrap().downloaded > before, "nothing gained in round {rounds}");
rounds += 1;
};
assert!(rounds > 0);
let done = b.run(id).await.unwrap();
assert!(b.server.requests_for(path).len() > 8, "each connection broke");
b.check(&done, 6, 8 * MB);
}
}
@ -415,10 +424,10 @@ async fn child() {
let Ok(args) = std::env::var(CHILD) else { return };
let (id, db) = args.split_once(' ').unwrap();
let (id, store) = (id.parse().unwrap(), Arc::new(Store::open(Path::new(db)).unwrap()));
let options = Options { parts: 4, min_part: 64 * 1024, checkpoint: Duration::from_millis(15) };
let source = Source::new(&store.task(id).unwrap().url).unwrap();
let (_keep, stop) = watch::channel(false);
download(&client(&ClientOptions::default()).unwrap(), &store, id, source, &options, stop).await.unwrap();
let shared = shared(&store, &client(&ClientOptions::default()).unwrap());
download(&shared, id, source, &options(), &Monitor::new(4), stop).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]

405
crates/core/tests/parts.rs Normal file
View file

@ -0,0 +1,405 @@
//! Parts that split, pass on and merge while they run, and connections that follow what helps.
use medlar_core::adapt::Timing;
use medlar_core::host::{self, Caps, Hosts};
use medlar_core::http::*;
use medlar_core::model::{Part, Task, TaskId};
use medlar_core::segment::Rules;
use medlar_core::store::Store;
use medlar_testserver::{Faults, TestServer, expected};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tokio::time::sleep;
const MB: u64 = 1 << 20;
/// Speeds are measured: one test at a time.
static ALONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
shared: Shared,
options: Options,
monitor: Arc<Monitor>,
}
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
impl Bench {
async fn new(cap: u32) -> Bench {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap();
let hosts = Hosts::new(Caps { burst: 100, per_second: 100.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: 4,
backoff: ms(20),
max_wait: ms(2000),
checkpoint: ms(20),
};
let shared = Shared { client, store, hosts };
Bench { server: TestServer::start().await, dir, shared, options, monitor: Arc::new(Monitor::new(cap)) }
}
fn add(&self, path: &str) -> TaskId {
let folder = self.dir.path().join("files");
self.shared.store.add_task(Task { url: self.server.url(path), folder, ..Task::default() }).unwrap()
}
async fn run(&self, id: TaskId) -> Result<PathBuf> {
let (_keep, stop) = watch::channel(false);
let source = Source::new(&self.shared.store.task(id).unwrap().url).unwrap();
let run = download(&self.shared, id, source, &self.options, &self.monitor, stop);
tokio::time::timeout(Duration::from_secs(30), run).await.unwrap_or_else(|_| panic!("hangs: {:?}", self.monitor.snapshot()))
}
/// Waits until the snapshot is as wanted.
async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) {
let end = Instant::now() + Duration::from_secs(10);
while !is(&self.monitor.snapshot()) {
assert!(Instant::now() < end, "never {what}: {:?}", self.monitor.snapshot());
sleep(ms(5)).await;
}
}
/// Requests the server has seen after the probe.
fn ranges(&self, path: &str) -> usize {
self.server.requests_for(path).len().saturating_sub(1)
}
async fn until_ranges(&self, path: &str, n: usize) {
let end = Instant::now() + Duration::from_secs(10);
while self.ranges(path) < n {
assert!(Instant::now() < end, "not {n} ranges: {:?}", self.monitor.snapshot());
sleep(ms(1)).await;
}
}
fn host(&self) -> String {
host::key(&self.server.url("/").parse().unwrap())
}
}
fn check(path: &Path, seed: u64, len: u64) {
let data = std::fs::read(path).unwrap();
assert_eq!(data.len() as u64, len);
assert_eq!(Sha256::digest(&data), Sha256::digest(expected(seed, 0, len as usize)));
}
fn slow(per_connection: u64) -> Faults {
Faults { throttle_conn: Some(per_connection), ..Faults::default() }
}
fn covers(parts: &[Part], size: u64) -> bool {
parts.first().is_none_or(|p| p.start == 0)
&& parts.last().is_none_or(|p| p.end == Some(size))
&& parts.windows(2).all(|w| w[0].end == Some(w[1].start))
&& parts.iter().all(|p| p.end.is_some_and(|end| p.start + p.done <= end))
}
/// Parts as a map of the file would keep them: from events alone.
fn replay(events: &[PartEvent]) -> BTreeMap<PartId, (u64, u64, bool)> {
let mut map = BTreeMap::new();
for e in events {
match *e {
PartEvent::Born { id, start, end } => {
assert!(map.insert(id, (start, end.unwrap(), false)).is_none());
}
PartEvent::Split { from, id, at, end } => {
let old = map.get_mut(&from).unwrap();
assert!(old.0 < at && at < end && old.1 == end && !old.2);
old.1 = at;
assert!(map.insert(id, (at, end, false)).is_none());
}
PartEvent::Stolen { id } => assert!(!map[&id].2),
PartEvent::Done { id } => {
let done = &mut map.get_mut(&id).unwrap().2;
assert!(!std::mem::replace(done, true));
}
PartEvent::Merged { into, gone } => {
let gone = map.remove(&gone).unwrap();
let into = map.get_mut(&into).unwrap();
assert!(into.1 == gone.0 && into.2 && gone.2);
into.1 = gone.1;
}
}
}
map
}
#[tokio::test(flavor = "multi_thread")]
async fn parts_split_and_merge_while_they_run() {
let _alone = ALONE.lock().await;
let b = Bench::new(8).await;
let path = "/data/1/12m/s.bin";
b.server.set_faults(path, slow(MB));
let id = b.add(path);
let mut listening = b.monitor.subscribe();
let journal = async {
let mut most = 0;
while b.shared.store.task(id).unwrap().downloaded < 12 * MB {
let parts = b.shared.store.parts(id).unwrap();
assert!(covers(&parts, 12 * MB), "{parts:?}");
let shot = b.monitor.snapshot();
let shown: Vec<_> = shot.parts.iter().map(|p| Part { start: p.start, end: p.end, done: p.done }).collect();
assert!(covers(&shown, 12 * MB), "{shot:?}");
assert!(shot.connections <= 8);
most = most.max(shot.connections);
sleep(ms(10)).await;
}
most
};
let (done, most) = tokio::join!(b.run(id), journal);
check(&done.unwrap(), 1, 12 * MB);
assert_eq!(most, 8);
let events: Vec<_> = std::iter::from_fn(|| listening.try_recv().ok()).collect();
let count = |is: fn(&PartEvent) -> bool| events.iter().filter(|e| is(e)).count();
let splits = count(|e| matches!(e, PartEvent::Split { .. }));
assert!(splits >= 7, "{events:?}");
assert_eq!(count(|e| matches!(e, PartEvent::Stolen { .. })), 0);
assert_eq!(count(|e| matches!(e, PartEvent::Merged { .. })), splits);
// Each range was asked for once: nobody who gave away a half had to ask again.
assert_eq!(b.ranges(path), splits + 1);
let map: Vec<_> = replay(&events).into_values().collect();
assert_eq!(map, [(0, 12 * MB, true)]);
assert_eq!(b.shared.store.parts(id).unwrap(), [Part { start: 0, end: Some(12 * MB), done: 12 * MB }]);
let shot = b.monitor.snapshot();
assert_eq!((shot.connections, shot.parts.len(), shot.parts[0].state), (0, 1, PartState::Done));
}
#[tokio::test(flavor = "multi_thread")]
async fn caps_change_while_it_runs() {
let _alone = ALONE.lock().await;
let b = Bench::new(6).await;
let path = "/data/2/64m/c.bin";
b.server.set_faults(path, slow(MB));
let id = b.add(path);
let turns = async {
b.until("six", |s| s.connections == 6).await;
b.monitor.set_cap(2);
b.until("two", |s| s.connections == 2).await;
b.monitor.set_cap(5);
b.until("five", |s| s.connections == 5).await;
b.shared.hosts.set_host_cap(&b.host(), Some(3));
b.until("three by host", |s| s.connections == 3).await;
while b.shared.hosts.open_to(&b.host()) > 3 {
sleep(ms(5)).await;
}
b.shared.hosts.set_host_cap(&b.host(), None);
b.until("five again", |s| s.connections == 5).await;
b.shared.hosts.set_caps(Caps { total: 1, ..b.shared.hosts.caps() });
b.until("one in total", |s| s.connections == 1).await;
b.server.clear_all_faults();
b.shared.hosts.set_caps(Caps { total: 64, ..b.shared.hosts.caps() });
};
let (done, ()) = tokio::join!(b.run(id), turns);
check(&done.unwrap(), 2, 64 * MB);
assert_eq!(b.shared.hosts.open_to(&b.host()), 0);
// The task's own cap.
let b = Bench::new(6).await;
b.server.set_faults(path, slow(4 * MB));
let id = b.add(path);
b.shared.store.save_task(Task { max_parts: Some(1), url: b.server.url("/data/2/4m/o.bin"), ..b.shared.store.task(id).unwrap() }).unwrap();
check(&b.run(id).await.unwrap(), 2, 4 * MB);
assert_eq!(b.ranges("/data/2/4m/o.bin"), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_refused_connection_steps_down_and_is_remembered() {
let _alone = ALONE.lock().await;
let b = Bench::new(8).await;
let path = "/data/3/12m/r.bin";
b.server.set_faults(path, Faults { max_conns: Some(3), ..slow(MB) });
let start = Instant::now();
check(&b.run(b.add(path)).await.unwrap(), 3, 12 * MB);
let took = start.elapsed();
let refused = || b.server.requests_for(path).iter().filter(|r| r.status == 429).count();
assert!((1..=4).contains(&refused()), "{}", refused());
assert!(took < ms(7000), "three connections did not go on: {took:?}");
let known = b.shared.store.host(&b.host()).unwrap().unwrap();
assert_eq!(known.good_connections, Some(3));
// Next time, also in a new process, it starts there.
let hosts = Hosts::new(b.shared.hosts.caps());
let b = Bench { shared: Shared { hosts, ..b.shared.clone() }, monitor: Arc::new(Monitor::new(3)), ..b };
b.server.clear_log();
let id = b.add(path);
let (done, ()) = tokio::join!(b.run(id), b.until("three", |s| s.connections == 3 && s.received < MB / 2));
check(&done.unwrap(), 3, 12 * MB);
assert!(b.server.requests_for(path)[..4].iter().all(|r| r.status != 429));
}
#[tokio::test(flavor = "multi_thread")]
async fn one_broken_part_does_not_stop_the_others() {
let _alone = ALONE.lock().await;
for later in [
Faults { cut_after: Some(300_000), ..slow(2 * MB) },
Faults { reset_after: Some(300_000), ..slow(2 * MB) },
Faults { stall_after: Some(300_000), ..slow(2 * MB) },
Faults::status(500),
Faults::status(403),
Faults { ignore_range: true, ..Faults::default() },
] {
let b = Bench::new(1).await;
let path = "/data/4/12m/e.bin";
b.server.set_faults(path, slow(2 * MB));
let id = b.add(path);
let turns = async {
b.until_ranges(path, 1).await;
b.server.set_faults(path, later.clone());
b.monitor.set_cap(2);
b.until_ranges(path, 2).await;
sleep(ms(300)).await;
let before = b.monitor.snapshot().received;
sleep(ms(300)).await;
assert!(b.monitor.snapshot().received > before, "{later:?}: the good one stopped");
b.server.clear_all_faults();
};
let (done, ()) = tokio::join!(b.run(id), turns);
check(&done.unwrap_or_else(|e| panic!("{later:?}: {e:?}")), 4, 12 * MB);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn retry_after_is_kept() {
let _alone = ALONE.lock().await;
let b = Bench::new(2).await;
let path = "/data/5/8m/w.bin";
b.server.set_faults(path, Faults { cut_after: Some(MB), ..slow(8 * MB) });
let id = b.add(path);
let (seen, turns) = (std::sync::Mutex::new(None), async {
b.until_ranges(path, 1).await;
b.server.set_faults(path, Faults { retry_after: Some(1), ..Faults::status(503) });
while !b.server.requests_for(path).iter().any(|r| r.status == 503) {
sleep(ms(1)).await;
}
let at = Instant::now();
// Requests that were under way may still come in.
sleep(ms(150)).await;
let asked = b.ranges(path);
sleep(ms(700)).await;
assert_eq!(b.ranges(path), asked, "it asked during the pause");
b.server.clear_all_faults();
at
});
let (done, at) = tokio::join!(b.run(id), turns);
*seen.lock().unwrap() = Some(at.elapsed());
check(&done.unwrap(), 5, 8 * MB);
assert!(at.elapsed() >= ms(900), "{seen:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn it_gives_up_in_the_end_and_keeps_what_came() {
let _alone = ALONE.lock().await;
for (status, retry_after, tries) in [(503, None, 4), (503, Some(60), 1), (404, None, 1)] {
let b = Bench::new(1).await;
let path = "/data/6/8m/g.bin";
b.server.set_faults(path, Faults { cut_after: Some(MB), ..slow(8 * MB) });
let id = b.add(path);
let turns = async {
b.until_ranges(path, 1).await;
b.server.set_faults(path, Faults { retry_after, ..Faults::status(status) });
};
let (result, ()) = tokio::join!(b.run(id), turns);
assert!(matches!(result, Err(Error::Status { code, .. }) if code == status), "{result:?}");
assert_eq!(b.ranges(path), 1 + tries);
assert_eq!(b.shared.store.task(id).unwrap().downloaded, MB);
assert_eq!(b.shared.hosts.open_to(&b.host()), 0);
b.server.clear_all_faults();
check(&b.run(id).await.unwrap(), 6, 8 * MB);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn nothing_waits_for_one_crawling_connection() {
let _alone = ALONE.lock().await;
// The first connection gets 20 kB/s, the others are fine. Alone it would need minutes.
let b = Bench::new(1).await;
let path = "/data/7/6m/t.bin";
b.server.set_faults(path, slow(20_000));
let id = b.add(path);
let turns = async {
b.until_ranges(path, 1).await;
b.server.set_faults(path, slow(2 * MB));
b.monitor.set_cap(2);
};
let start = Instant::now();
let (done, ()) = tokio::join!(b.run(id), turns);
check(&done.unwrap(), 7, 6 * MB);
let took = start.elapsed();
println!("crawling tail: {took:?}, {} ranges", b.ranges(path));
assert!(took < ms(9000), "{took:?}");
assert!(b.ranges(path) < 25, "{}", b.ranges(path));
}
#[tokio::test(flavor = "multi_thread")]
async fn new_connections_come_at_a_limited_rate() {
let _alone = ALONE.lock().await;
let b = Bench::new(8).await;
b.shared.hosts.set_caps(Caps { burst: 2, per_second: 5.0, ..b.shared.hosts.caps() });
let path = "/data/8/4m/l.bin";
// Every connection breaks after a little, so it wants new ones all the time.
b.server.set_faults(path, Faults { cut_after: Some(200_000), ..Faults::default() });
let start = Instant::now();
check(&b.run(b.add(path)).await.unwrap(), 8, 4 * MB);
let most = 2.0 + start.elapsed().as_secs_f64() * 5.0;
assert!(b.ranges(path) as f64 <= most + 1.0, "{} of {most}", b.ranges(path));
}
/// Bytes per second over the whole download, with the connections it ended up with.
async fn speed(cap: u32, faults: Faults, megabytes: u64) -> (f64, u32, u32) {
let b = Bench::new(cap).await;
let path = format!("/data/9/{megabytes}m/b.bin");
b.server.set_faults(&path, faults);
let id = b.add(&path);
let mut wanted = vec![];
let start = Instant::now();
let run = b.run(id);
tokio::pin!(run);
let done = loop {
tokio::select! {
done = &mut run => break done,
_ = sleep(ms(50)) => wanted.push(b.monitor.snapshot().wanted),
}
};
let took = start.elapsed().as_secs_f64();
check(&done.unwrap(), 9, megabytes * MB);
let settled = *wanted.last().unwrap();
((megabytes * MB) as f64 / took, settled, wanted.into_iter().max().unwrap())
}
#[tokio::test(flavor = "multi_thread")]
async fn benchmark() {
let _alone = ALONE.lock().await;
// Each connection gets 512 KiB/s: as many megabytes for each count that it takes the same time.
let mut runs = vec![];
for cap in [1, 2, 4, 8, 16] {
runs.push((cap, tokio::spawn(speed(cap, slow(MB / 2), u64::from(cap) * 4))));
}
let mut one = 0.0;
for (cap, run) in runs {
let (speed, settled, _) = run.await.unwrap();
one = if cap == 1 { speed } else { one };
let gain = speed / one;
println!("throttled per connection, cap {cap}: {:.2} MiB/s, ×{gain:.2}, {settled} connections", speed / MB as f64);
assert!(gain >= 0.7 * f64::from(cap), "{cap}: ×{gain:.2}");
}
// 2 MiB/s for all together.
let (speed, settled, most) = speed(16, Faults { throttle_total: Some(2 * MB), ..Faults::default() }, 20).await;
println!("capped in total: {:.2} MiB/s, settled at {settled}, at most {most} connections", speed / MB as f64);
assert!(settled <= 3 && most <= 4, "settled {settled}, most {most}");
assert!(speed >= 1.4 * MB as f64);
}

View file

@ -21,4 +21,7 @@
- D-017 — 2026-11-24 — HTTP client is reqwest 0.13.5 (pinned exactly), rustls with ring and the system certificates, HTTP/1.1 only, `Accept-Encoding: identity`, no decompression, no Referer of its own, its retries off, ≤ 10 redirects, 20 s connect and 30 s idle timeout, no proxy from the environment. Segments go to the final link; cookies and logins are dropped when its origin differs. — Docs of 0.13.5 checked: `http1_only`, `redirect::Policy`, `connect_timeout`, `read_timeout` (per read), `retry::never`. — 02, 05, 06
- D-018 — 2026-11-24 — HTTP/1.1 everywhere; no HTTP/2 or HTTP/3 (1.14), so reqwest's `http2` feature stays off. — Measured over TLS with netem, mean MB/s of HTTP/1.1 ×1, ×4, ×8 and HTTP/2 ×1: loopback 437, 950, 899, 306; 20 ms 8.7, 8.5, 8.9, 8.6; 20 ms with 0.1 % loss (15 runs) 7.6, 6.0, 7.3, 6.6; 50 ms with 0.5 % loss 1.7, 1.8, 3.2, 0.7. HTTP/2 never won. HTTP/3 was not measured: reqwest's needs an unstable build flag and another TLS stack (quinn). — 02
- D-019 — 2026-11-24 — A stored part with `end: None` means the server had no ranges: it starts over on resume unless the server has ranges by then. A part with an end never starts over by itself (`Error::NoResume`, `Error::Changed` instead). The record of parts is written only after `fdatasync` of the data it names. — No state loses finished bytes. — 02
- D-020 — 2026-11-25 — Connections start at 2 (or what the host stood, kept 7 days) and double, then go up by one, while the new ones bring ≥ 30 % of a fair share and more than twice the noise; measured 3 s after 1 s of settling. A failed try holds 30 s, doubling to 4 min; counts that were not proven are tried lower. Never below 2 without a refusal or cap. — The user's line is slow: a connection has to prove itself. — 02
- D-021 — 2026-11-25 — A refusal (429, 503, any other 4xx, no connection, 200 for a range) while others deliver lowers the count for 10 min for all downloads of that host, and is remembered; alone, 4xx and 200 are final. New requests per host: 16 at once, then 4/s. Idle connections close after 0.5 s; a host that refused gets 0.3 s to notice a closed one. A part that waits after a failure keeps its place, so that failures cause no further cuts. — Must not look like abuse. — 02
- D-022 — 2026-11-25 — A failed part never ends the download while others deliver. It ends after 5 failures in a row without a byte (1 s, doubling, half of it chance, ≤ 60 s) with nothing else delivering, or when Retry-After is longer than 60 s. Changed, disk, store, encoding and contradicting replies end it at once. Longer waits and task retries are S007's. — FEATURES 1.6. — 02
- 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

View file

@ -56,5 +56,16 @@ All take `(ui, &Theme, …)`; the theme is `app.theme.clone()`. The caller keeps
- `toast`: `Toasts<A>` `.info .error .action .undo`, `.show(ctx, t, bottom) -> Option<A>`.
Not done: menus close without a fade; tooltips show on hover only, not on keyboard focus; screen readers untested. Gallery words are not in the catalogue (builders only). Hidden release run of `--gallery`: 4 pages and a menu by real clicks, idle 5 s = 0.00 % CPU. The debug build opened no window in `tools/hidden.sh` (nested niri drops the connection, no panic; also without `--gallery`); the release build does. Cause not found.
## S005 — Dynamic parts and adaptive connections (2026-11-25)
Done: `core::segment` (what a free connection takes), `core::adapt` (how many), `core::host` (caps, pace, memory), `http::parts` (the run), `http::monitor`. Choices: D-020 to D-022.
Verified: `nice cargo test -j 2 -p medlar-core` green (62 unit, 16 http with 50 kills, 9 parts, the last two 3 more times, under load too); clippy clean for the new code.
Numbers (debug build, test timing 0.2 s + 0.6 s): 512 KiB/s per connection, cap 1, 2, 4, 8, 16 → ×1, 2.0, 3.7, 6.9, 12.8 with the ramp counted, settled at the cap; 2 MiB/s in total → 1.99 MiB/s, settled at 2, never over 4. One crawling connection of two (20 kB/s against 2 MiB/s, 6 MiB): 4.5 s and 8 ranges, instead of minutes.
- `http::download(&Shared { client, store, hosts }, id, source, &Options, &Monitor, stop)`: one `Shared` per program, one `Monitor` per task, which outlives runs. Errors of one part stay inside until it was tried `tries` times and nothing else delivers; a longer Retry-After than `max_wait` comes out as `Error::Status`.
- Caps, live: `monitor.set_cap(n)`, `hosts.set_caps(Caps { total, per_host, burst, per_second })`, `hosts.set_host_cap(host::key(&url), n)`. `Task::max_parts` and `HostProfile::max_connections` are read at the start. S006 maps `settings::Limits` to them.
- Events, `monitor.subscribe()` (broadcast of 1024; on `Lagged` take a snapshot): `PartEvent::{Born{id,start,end}, Split{from,id,at,end}, Stolen{id}, Done{id}, Merged{into,gone}}`. `Stolen`: what is left of a part goes to another connection. Ids are new in each run.
- `monitor.snapshot()`: `Snapshot { size, parts, connections, wanted, received, speed }`, parts in file order as `PartView { id, start, end, done, state, speed, fails }`, `PartState::{Waiting, Connecting, Running, Done}`. `done` is of this moment; the rest of the last tick (250 ms).
- `LivePart`: new `pos()` and `received()` (bytes from the network, what S006 limits); `part::split` is gone.
Not done: a lone connection that crawls is replaced only when a second one is wanted (tried after each hold, 30 s to 4 min). Servers without ranges still fail at the first error. Not tried on the real line. In an early build the crawling test ran over 60 s three times while all tests shared the CPU; not seen in 64 runs since, half of them under full load.
## Later
-