Medlar/crates/core/tests/farm.rs

172 lines
6.8 KiB
Rust

//! Links served by a farm: servers with the same bytes but their own dates and tags (S048), and liars among them.
use medlar_core::disk::partial_path;
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::*;
use medlar_core::model::{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::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;
const MB: u64 = 1 << 20;
const PATH: &str = "/data/31/8m/output.bin";
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
store: Arc<Store>,
client: Client,
options: Options,
}
impl Bench {
async fn new() -> Bench {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let client = client(&ClientOptions { idle_timeout: Duration::from_millis(1500), ..ClientOptions::default() }).unwrap();
let 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()
};
Bench { server: TestServer::start().await, dir, store, client, options }
}
fn add(&self) -> TaskId {
self.store.add_task(Task { url: self.server.url(PATH), folder: self.dir.path().join("files"), ..Task::default() }).unwrap()
}
async fn run_until(&self, id: TaskId, stop: Stop) -> Result<PathBuf> {
let source = Source::new(&self.store.task(id).unwrap().url).unwrap();
let hosts = Hosts::new(Caps { burst: 100, per_second: 100.0, ..Caps::default() });
let shared = Shared { client: self.client.clone(), store: self.store.clone(), hosts };
let monitor = Monitor::new(4);
let run = download(&shared, id, source, &self.options, &monitor, stop);
tokio::time::timeout(Duration::from_secs(30), run).await.expect("hangs")
}
async fn run(&self, id: TaskId) -> Result<PathBuf> {
let (_keep, stop) = watch::channel(false);
self.run_until(id, stop).await
}
/// Stops it once every part has something.
async fn half(&self, id: TaskId) {
let (halt, stop) = watch::channel(false);
let watching = async {
while self.store.parts(id).unwrap().len() < 2 || self.store.parts(id).unwrap().iter().any(|p| p.done == 0) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
halt.send_replace(true);
};
let running = self.run_until(id, stop);
tokio::pin!(running);
let result = tokio::select! {
result = &mut running => result,
() = watching => running.await,
};
assert!(matches!(result, Err(Error::Stopped)), "{result:?}");
}
fn partial(&self, id: TaskId) -> PathBuf {
let task = self.store.task(id).unwrap();
partial_path(&task.folder, &task.name)
}
fn farm(&self, nodes: u32, liar: bool, throttle: Option<u64>) {
self.server.set_faults(PATH, Faults { farm: Some(nodes), liar, throttle_conn: throttle, ..Faults::default() });
}
}
fn check(path: &Path) {
let data = std::fs::read(path).unwrap();
assert_eq!(data.len() as u64, 8 * MB);
assert_eq!(Sha256::digest(&data), Sha256::digest(expected(31, 0, 8 * MB as usize)));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_farm_downloads_in_parts() {
let b = Bench::new().await;
b.farm(3, false, Some(MB));
let id = b.add();
let done = b.run(id).await.unwrap();
check(&done);
let log = b.server.requests_for(PATH);
let range = |r: &&medlar_testserver::Request| r.header("range")?.strip_prefix("bytes=")?.split('-').next()?.parse::<u64>().ok();
let starts: BTreeSet<_> = log.iter().filter(|r| r.status == 206).filter_map(|r| range(&r)).collect();
assert!(starts.len() >= 3, "parts in parallel: {starts:?}");
assert!(b.store.task(id).unwrap().farm, "the farm is kept");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_farm_goes_on_after_a_stop() {
// With the farm known from before, and without (found again by the bytes).
for stored in [true, false] {
let b = Bench::new().await;
b.farm(3, false, Some(MB));
let id = b.add();
b.half(id).await;
let mut task = b.store.task(id).unwrap();
assert!(task.farm, "found while it ran");
let first = (task.etag.clone(), task.last_modified.clone());
task.farm = stored;
b.store.save_task(task).unwrap();
b.farm(3, false, None);
b.server.clear_log();
let done = b.run(id).await.unwrap();
check(&done);
let task = b.store.task(id).unwrap();
// Without the flag the parts may well find replies of the first version, and nothing has to be proven again.
assert!(task.farm || !stored, "the farm is kept");
assert_eq!((task.etag, task.last_modified), first, "the first validators stay");
if stored {
let asked: Vec<_> = b.server.requests_for(PATH).into_iter().filter(|r| r.header("if-range").is_some()).collect();
assert!(asked.is_empty(), "If-Range on a farm: {asked:?}");
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_liar_of_the_same_size_is_another_file() {
let b = Bench::new().await;
b.farm(2, true, None);
let id = b.add();
// Changed, or by chance all from one of them: never mixed.
match b.run(id).await {
Err(Error::Changed) => assert!(!b.store.task(id).unwrap().farm),
Ok(done) => {
let data = std::fs::read(done).unwrap();
let liar = 31 ^ 7u64.wrapping_mul(0x1234_5678_9ABC_DEF1);
let whole = |seed| Sha256::digest(expected(seed, 0, 8 * MB as usize));
assert!([whole(31), whole(liar)].contains(&Sha256::digest(&data)), "two files were mixed");
}
other => panic!("{other:?}"),
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_liar_on_the_way_keeps_what_is_there() {
let b = Bench::new().await;
b.farm(2, false, Some(MB));
let id = b.add();
b.half(id).await;
let before = std::fs::read(b.partial(id)).unwrap();
b.farm(2, true, None);
let result = b.run(id).await;
assert!(matches!(result, Err(Error::Changed)), "{result:?}");
let after = std::fs::read(b.partial(id)).unwrap();
for p in b.store.parts(id).unwrap() {
let range = p.start as usize..(p.start + p.done) as usize;
assert!(before[range.clone()] == after[range.clone()], "finished bytes were touched");
assert!(after[range.clone()] == expected(31, p.start, p.done as usize)[..], "other bytes were kept as done");
}
}