Medlar/crates/core/tests/queues.rs

252 lines
9.6 KiB
Rust

//! S041: queues, hours and after-chains against the testserver (docs/tests/S021 checks 1 to 7).
use medlar_core::adapt::Timing;
use medlar_core::events::Event;
use medlar_core::host::{self, Caps, Hosts};
use medlar_core::http::{ClientOptions, OVERLAP, Options, Shared, client};
use medlar_core::manager::*;
use medlar_core::model::*;
use medlar_core::segment::Rules;
use medlar_core::settings::Limits;
use medlar_core::snapshot::{Snapshot, TaskView};
use medlar_core::store::{self, Store};
use medlar_testserver::{Faults, TestServer, expected};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::broadcast::error::TryRecvError;
use tokio::time::sleep;
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
const LIMITS: Limits = Limits { speed: 0, max_active: 2, max_connections: 32, parts_per_download: 4, connections_per_host: 16 };
fn config(dir: &Path, limits: Limits) -> Config {
let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap());
let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap();
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
let options = Options {
rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) },
timing: Timing { settle: ms(200), window: ms(600), hold: ms(2000), refused: ms(60_000) },
tick: ms(25),
stall: ms(1000),
patience: ms(500),
tries: 2,
backoff: ms(20),
max_wait: ms(2000),
checkpoint: ms(50),
};
let mut config = Config::new(Shared { client, store, hosts }, limits);
(config.options, config.bin, config.tick) = (options, Bin::at(dir.join("Trash")), ms(20));
config
}
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
store: Arc<Store>,
manager: Manager,
}
impl Bench {
async fn new(limits: Limits) -> Bench {
let dir = tempfile::tempdir().unwrap();
let config = config(dir.path(), limits);
let store = config.shared.store.clone();
Bench { server: TestServer::start().await, dir, store, manager: Manager::open(config).unwrap() }
}
/// Ends the program and starts it again.
fn restart(self, limits: Limits) -> Bench {
let Bench { server, dir, store, manager } = self;
drop((manager, store));
let config = config(dir.path(), limits);
Bench { server, store: config.shared.store.clone(), manager: Manager::open(config).unwrap(), dir }
}
fn files(&self) -> PathBuf {
self.dir.path().join("files")
}
fn task(&self, path: &str) -> Task {
Task { url: self.server.url(path), folder: self.files(), ..Task::default() }
}
async fn add(&self, path: &str) -> TaskId {
self.manager.send(Command::Add(Box::new(self.task(path)))).await.unwrap()
}
/// A file that takes several seconds.
fn slow(&self, seed: u64) -> String {
let path = TestServer::data_path(seed, 1 << 20);
self.server.set_faults(&path, Faults { throttle_conn: Some(20_000), ..Faults::default() });
path
}
async fn run(&self, command: Command) {
self.manager.send(command).await.unwrap();
}
fn view(&self, id: TaskId) -> Arc<TaskView> {
self.manager.snapshot().get(id).unwrap_or_else(|| panic!("{id} is not in the list")).clone()
}
fn states(&self) -> Vec<State> {
self.manager.snapshot().iter().map(|v| v.state()).collect()
}
async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) {
let end = Instant::now() + Duration::from_secs(20);
while !is(&self.manager.snapshot()) {
let states: Vec<_> = self.manager.snapshot().iter().map(|v| (v.id(), v.state(), v.task.error.clone())).collect();
assert!(Instant::now() < end, "never {what}: {states:?}");
sleep(ms(5)).await;
}
}
async fn until_state(&self, id: TaskId, state: State) {
self.until(state.name(), |s| s.get(id).is_some_and(|v| v.state() == state)).await;
}
async fn until_bytes(&self, id: TaskId) {
self.until("under way", |s| s.get(id).is_some_and(|v| v.downloaded > 0 && v.state() == State::Running)).await;
}
fn check(&self, id: TaskId, seed: u64, len: usize) {
let task = self.view(id).task.clone();
let (is, should) = (std::fs::read(task.folder.join(&task.name)), expected(seed, 0, len));
let is = is.unwrap_or_else(|e| panic!("{e}: {task:?}, {:#?}", self.view(id).log));
let same = is.iter().zip(&should).take_while(|(a, b)| a == b).count();
assert!(is == should, "{} bytes, right until {same}: {task:?}, {:#?}", is.len(), self.view(id).log);
}
}
use medlar_core::schedule::ManualClock;
fn at(h: u32, m: u32) -> i64 {
// 2026-11-23 is a Monday.
chrono::NaiveDate::from_ymd_opt(2026, 11, 23).unwrap().and_hms_opt(h, m, 0).unwrap().and_utc().timestamp_millis()
}
async fn bench_with(limits: Limits, clock: Option<Arc<ManualClock>>) -> Bench {
let dir = tempfile::tempdir().unwrap();
let mut config = config(dir.path(), limits);
if let Some(c) = clock {
config.clock = c;
}
let store = config.shared.store.clone();
Bench { server: TestServer::start().await, dir, store, manager: Manager::open(config).unwrap() }
}
fn queue(b: &Bench, f: impl FnOnce(&mut Queue)) -> QueueId {
let mut q = Queue { id: 0, name: "q".into(), folder: None, speed_limit: None, max_active: None, position: 5.0, paused: false, schedule: vec![] };
f(&mut q);
b.store.save_queue(q).unwrap()
}
async fn add_in(b: &Bench, path: &str, q: QueueId) -> TaskId {
let mut t = b.task(path);
t.queue = q;
b.manager.send(Command::Add(Box::new(t))).await.unwrap()
}
fn fast(b: &Bench, seed: u64) -> String {
TestServer::data_path(seed, 64 * 1024)
}
#[tokio::test(flavor = "multi_thread")]
async fn paused_queue_1_and_forced_5() {
let b = Bench::new(LIMITS).await;
let q = queue(&b, |q| q.paused = true);
let id = add_in(&b, &fast(&b, 1), q).await;
sleep(ms(500)).await;
assert_eq!(b.view(id).state(), State::Queued);
// 5: by hand
b.run(Command::Start(id)).await;
b.until_state(id, State::Done).await;
// 1: unpause starts the next one
let id2 = add_in(&b, &fast(&b, 2), q).await;
sleep(ms(300)).await;
assert_eq!(b.view(id2).state(), State::Queued);
let mut p = b.store.queues().unwrap().into_iter().find(|x| x.id == q).unwrap();
p.paused = false;
b.store.save_queue(p).unwrap();
b.run(Command::Edit { id: id2, edit: Box::new(|_| {}) }).await;
b.until_state(id2, State::Done).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn queue_max_active_2() {
let b = Bench::new(Limits { max_active: 4, ..LIMITS }).await;
let q = queue(&b, |q| q.max_active = Some(1));
let mut ids = vec![];
for s in 1..=3 {
ids.push(add_in(&b, &b.slow(s), q).await);
}
sleep(ms(400)).await;
let states = b.states();
assert_eq!(states.iter().filter(|s| **s == State::Running).count(), 1, "{states:?}");
assert_eq!(b.view(ids[0]).state(), State::Running, "in order");
}
#[tokio::test(flavor = "multi_thread")]
async fn hours_3_and_4() {
let clock = Arc::new(ManualClock::new(at(21, 59), |_| 0));
let b = bench_with(LIMITS, Some(clock.clone())).await;
let q = queue(&b, |q| q.schedule = vec![Schedule { days: 0b1, from: 22 * 60, to: 6 * 60 }]);
let id = add_in(&b, &b.slow(1), q).await;
sleep(ms(500)).await;
assert_eq!(b.view(id).state(), State::Queued);
clock.advance(2 * 60_000);
let end = Instant::now() + Duration::from_secs(25);
while b.view(id).state() != State::Running {
assert!(Instant::now() < end, "never started: {:?}", b.view(id).state());
sleep(ms(200)).await;
}
// 4: leaves the window
clock.set(at(6, 1) + 24 * 3_600_000);
let end = Instant::now() + Duration::from_secs(25);
while b.view(id).state() == State::Running {
assert!(Instant::now() < end, "never left");
sleep(ms(200)).await;
}
assert_eq!(b.view(id).state(), State::Queued, "back to Queued, not Failed");
clock.set(at(22, 30));
let end = Instant::now() + Duration::from_secs(25);
while b.view(id).state() != State::Running {
assert!(Instant::now() < end, "never came back");
sleep(ms(200)).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn after_6_and_7() {
let b = Bench::new(Limits { max_active: 4, ..LIMITS }).await;
let a = b.add(&b.slow(1)).await;
let mut t = b.task(&fast(&b, 2));
t.after = Some(a);
let bb = b.manager.send(Command::Add(Box::new(t))).await.unwrap();
sleep(ms(400)).await;
assert_eq!(b.view(a).state(), State::Running);
assert_eq!(b.view(bb).state(), State::Queued, "held while A runs");
b.run(Command::Edit { id: a, edit: Box::new(|t| t.speed_limit = None) }).await;
// 7: loops are refused, nothing saved
let r = b.manager.send(Command::Edit { id: a, edit: Box::new(move |t| t.after = Some(a)) }).await;
assert!(matches!(r, Err(Error::Cycle)), "{r:?}");
let r = b.manager.send(Command::Edit { id: a, edit: Box::new(move |t| t.after = Some(bb)) }).await;
assert!(matches!(r, Err(Error::Cycle)), "{r:?}");
assert_eq!(b.view(a).task.after, None);
// a removed one does not hold
let mut t = b.task(&fast(&b, 3));
t.after = Some(a);
let c = b.manager.send(Command::Add(Box::new(t))).await.unwrap();
b.run(Command::Remove { id: a, files: Files::Keep }).await;
b.until_state(c, State::Done).await;
b.until_state(bb, State::Done).await;
}