S048: farms with differing validators: byte proof, no If-Range, stored flag; testserver farm and liar modes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
astar76 2026-11-26 13:58:03 -06:00
commit ed2f7c67e5
11 changed files with 199 additions and 42 deletions

View file

@ -173,7 +173,11 @@ async fn fetch_whole(
let body = probe.body.take();
// Once on a mirror, its redirects are its own.
let here = if url == task.url { source.at(&probe.url) } else { source.mirror(&url)?.at(&probe.url) };
let link = Link { client: client.clone(), source: here, ranges: probe.ranges, version: probe.version.clone() };
let mut link = Link::new(client.clone(), here, probe.ranges, probe.version.clone(), task.farm);
// The bytes here are of the version first seen; replies of another one with the same size are checked by their bytes.
if !parts.is_empty() && !compared && !old(&task).same_file(&link.version) && old(&task).maybe_same(&link.version) {
link.version = old(&task);
}
let (file, parts) = match file {
Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?,
None => start(shared, job, &task, probe, &link, stop).await?,
@ -193,10 +197,15 @@ async fn fetch_whole(
let task = Arc::new(job.task().await?);
let mirrors = links(&task).into_iter().filter(|u| *u != url && !out.contains(u)).filter_map(|u| Some((u.clone(), source.mirror(&u).ok()?)));
let mirrors = if link.ranges { mirrors.collect() } else { vec![] };
let (farm, was_farm) = (link.farm.clone(), task.farm);
let mut run = Run::new(shared, task, (url, link), mirrors, file.clone(), parts, body, host.clone(), begin, options, monitor);
let result = run.go(job, stop).await;
let Ended { live, learned, gave } = run.end();
let saved = job.checkpoint(&live, &file).await;
// So that a restart doesn't take its servers for another version.
if farm.load(std::sync::atomic::Ordering::Relaxed) && !was_farm {
job.run(move |s| Ok(s.edit_task(id, |t| t.farm = true)?)).await?;
}
if let Some(n) = learned {
job.run(move |s| Ok(host::remember(s, &host, n, model::now())?)).await?;
}
@ -265,7 +274,9 @@ async fn open_one(client: &Client, task: &Task, parts: &[Part], source: Source,
return Ok((probe, false));
}
if first {
return if old(task).same_file(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) };
// Another server of a farm differs in dates only; the bytes tell when the parts go on.
let old = old(task);
return if old.same_file(&probe.version) || old.maybe_same(&probe.version) { Ok((probe, false)) } else { Err(Error::Changed) };
}
let link = NewLink { url: source.url.to_string(), ..NewLink::default() };
let checked = relink::check(client, task, parts, link, source, stop).await?;
@ -354,7 +365,7 @@ async fn resume(
compared: bool,
stop: &mut Stop,
) -> Result<(Arc<PartialFile>, Vec<Part>)> {
if !compared && !old(task).same_file(&link.version) {
if !compared && !old(task).same_file(&link.version) && !old(task).maybe_same(&link.version) {
return Err(Error::Changed);
}
let file = Arc::new(file);

View file

@ -6,10 +6,16 @@ use crate::disk::PartialFile;
use crate::limit::Flow;
use crate::part::LivePart;
use bytes::Bytes;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
/// Finished bytes read again and compared when a part goes on.
pub const OVERLAP: u64 = 4096;
/// Finished bytes compared with a reply of another version of the same size, and on a farm when a part goes on.
pub const SAMPLE: u64 = 64 * 1024;
/// Replies asked for until one of the known version and one of another can be compared.
const PROOF_TRIES: u32 = 8;
/// Held in memory for each part.
const BUFFER: usize = 512 * 1024;
/// A slow part writes what it has this often.
@ -22,7 +28,26 @@ pub struct Link {
/// At the final link.
pub source: Source,
pub ranges: bool,
/// The first version seen, kept for display and as the one the bytes on disk are of.
pub version: Validators,
/// Its servers differ in dates and tags but were shown to have the same bytes: only size and bytes count. Shared by clones.
pub farm: Arc<AtomicBool>,
}
impl Link {
pub fn new(client: Client, source: Source, ranges: bool, version: Validators, farm: bool) -> Link {
Link { client, source, ranges, version, farm: Arc::new(AtomicBool::new(farm)) }
}
pub fn farm(&self) -> bool {
self.farm.load(Ordering::Relaxed)
}
fn set_farm(&self) {
if !self.farm.swap(true, Ordering::Relaxed) {
log::info!("{}: servers differ in dates only, telling versions by size and bytes", self.source.url);
}
}
}
/// Fills `part` until it is whole, `stop` turns true or something breaks. Whatever arrived is written before it returns, so stop
@ -46,10 +71,10 @@ pub(super) async fn fetch_within(
if *stop.borrow() {
return Err(Error::Stopped);
}
let (mut response, mut known) = if link.ranges {
let (mut response, mut known, mut unsure) = if link.ranges {
range(link, part, file, &mut stop).await?
} else {
(whole(link, part, body, &mut stop).await?, vec![])
(whole(link, part, body, &mut stop).await?, vec![], false)
};
part.begin();
let mut buf = Vec::with_capacity(BUFFER);
@ -73,6 +98,11 @@ pub(super) async fn fetch_within(
return Err(Error::Changed);
}
known.drain(..old.len());
// Another version's reply had the bytes that are here: the servers differ in dates only.
if unsure && known.is_empty() {
link.set_farm();
unsure = false;
}
// Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before
// all is used up.
let mut rest = &chunk[..];
@ -139,38 +169,104 @@ async fn flush(part: &LivePart, file: &PartialFile, buf: Vec<u8>) -> Result<Vec<
Ok(buf)
}
/// Asks for the rest of the part and checks that this is what comes. Also gives the finished bytes it must begin with.
async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec<u8>)> {
/// Asks for the rest of the part and checks that this is what comes. Also gives the finished bytes it must begin with, and
/// whether the reply is of another version of the same size, which these bytes have to confirm.
async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec<u8>, bool)> {
let p = part.get();
let overlap = p.done.min(OVERLAP);
let first = p.start + p.done - overlap;
let known = file.read_at(overlap as usize, first).await?;
let response = send_range(link, first, p.end, stop).await?;
Ok((response, known))
let mut overlap = p.done.min(if link.farm() { SAMPLE } else { OVERLAP });
loop {
let first = p.start + p.done - overlap;
if p.done == 0 {
return Ok((sure_range(link, first, p.end, stop).await?, vec![], false));
}
let (response, unsure) = send_range(link, first, p.end, stop).await?;
// Enough of the bytes here to tell another version from the same file on another server.
if unsure && overlap < p.done.min(SAMPLE) {
overlap = p.done.min(SAMPLE);
continue;
}
let known = file.read_at(overlap as usize, first).await?;
return Ok((response, known, unsure));
}
}
async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<Response> {
let last = end.map(|e| (e - 1).to_string()).unwrap_or_default();
let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), link.version.if_range().as_ref(), stop).await?;
let headers = response.headers();
match response.status() {
StatusCode::PARTIAL_CONTENT => {
let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?;
if !link.version.same_file(&Validators::of(headers, range.total)) {
/// A range from the known version, or from another one shown to have the same bytes.
async fn sure_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<Response> {
let (response, unsure) = send_range(link, first, end, stop).await?;
if !unsure {
return Ok(response);
}
drop(response);
// Only replies of the same size are unsure, so the size is known.
let until = end.or(link.version.size).unwrap_or(first);
prove(link, first, (until - first).min(SAMPLE), stop).await?;
Ok(send_range(link, first, end, stop).await?.0)
}
/// Asks for `len` bytes at `at` until a reply of the known version and one of another can be compared. The same bytes make
/// the link a farm; other bytes, or no reply of the known version, mean the file changed.
async fn prove(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<()> {
let (mut known, mut other) = (None, None);
for _ in 0..PROOF_TRIES {
if link.farm() {
return Ok(());
}
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
let data = all(&link.client, response, len, stop).await?;
if data.len() as u64 != len {
return Err(Error::Cut { got: data.len() as u64, expected: Some(len) });
}
*(if unsure { &mut other } else { &mut known }) = Some(data);
if let (Some(a), Some(b)) = (&known, &other) {
if a != b {
return Err(Error::Changed);
}
if range.first != first || end.is_some_and(|e| range.last >= e) {
return Err(Error::BadReply("another range than asked for".into()));
link.set_farm();
return Ok(());
}
}
Err(Error::Changed)
}
/// A reply to a range, and whether it is of another version of the same size: maybe the same file from another server of
/// a farm, which only its bytes can tell. Never unsure on a farm.
async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<(Response, bool)> {
let last = end.map(|e| (e - 1).to_string()).unwrap_or_default();
// Servers of a farm with other dates answer a date in If-Range with the whole file.
let mut if_range = if link.farm() { None } else { link.version.if_range() };
loop {
let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), if_range.as_ref(), stop).await?;
let headers = response.headers();
match response.status() {
StatusCode::PARTIAL_CONTENT => {
let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?;
let version = Validators::of(headers, range.total);
let unsure = !link.version.same_file(&version);
if unsure && !link.version.maybe_same(&version) {
return Err(Error::Changed);
}
if range.first != first || end.is_some_and(|e| range.last >= e) {
return Err(Error::BadReply("another range than asked for".into()));
}
check_length(headers, range)?;
check_encoding(headers, response.url())?;
return Ok((response, unsure && !link.farm()));
}
check_length(headers, range)?;
check_encoding(headers, response.url())?;
Ok(response)
StatusCode::OK => {
let version = Validators::of(headers, content_length(headers));
if link.version.same_file(&version) || (link.farm() && link.version.maybe_same(&version)) {
return Err(Error::RangeIgnored);
}
if link.version.maybe_same(&version) && if_range.take().is_some() {
continue;
}
return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed });
}
StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => {
return Err(Error::Changed);
}
_ => return Err(status_error(&response)),
}
StatusCode::OK if link.version.same_file(&Validators::of(headers, content_length(headers))) => Err(Error::RangeIgnored),
StatusCode::OK if comes_as_page(link, headers) => Err(Error::Page),
StatusCode::OK => Err(Error::Changed),
StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => Err(Error::Changed),
_ => Err(status_error(&response)),
}
}
@ -208,12 +304,17 @@ pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: &
/// Whether the server has `known` at `at`.
pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result<bool> {
let len = known.len() as u64;
same_body(&link.client, send_range(link, at, Some(at + len), stop).await?, known, stop).await
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
let same = same_body(&link.client, response, known, stop).await?;
if same && unsure && len > 0 {
link.set_farm();
}
Ok(same)
}
/// `len` bytes at `at`.
pub(crate) async fn bytes_at(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<Vec<u8>> {
let response = send_range(link, at, Some(at + len), stop).await?;
let response = sure_range(link, at, Some(at + len), stop).await?;
let data = all(&link.client, response, len, stop).await?;
if data.len() as u64 == len { Ok(data) } else { Err(Error::Cut { got: data.len() as u64, expected: Some(len) }) }
}

View file

@ -446,6 +446,19 @@ impl Validators {
&& agree(self.last_modified.as_ref(), other.last_modified.as_ref())
}
/// Of the same size, so maybe the same file from another server of a farm: only the bytes can tell. Servers like nginx
/// make the tag from size and date (`"5f-1982ea51dc7"`); tags that differ in the size part are another file.
pub fn maybe_same(&self, other: &Validators) -> bool {
fn size_part(tag: &Option<String>) -> Option<&str> {
let tag = tag.as_deref()?;
let (size, date) = tag.strip_prefix("W/").unwrap_or(tag).strip_prefix('"')?.strip_suffix('"')?.split_once('-')?;
let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
(hex(size) && hex(date)).then_some(size)
}
let sizes = size_part(&self.etag).zip(size_part(&other.etag)).is_none_or(|(a, b)| a.eq_ignore_ascii_case(b));
self.size.is_some() && self.size == other.size && sizes
}
/// The value for `If-Range`, which must not be a weak tag.
fn if_range(&self) -> Option<HeaderValue> {
let strong = self.etag.as_ref().filter(|t| !t.starts_with("W/"));
@ -522,4 +535,16 @@ mod tests {
assert_eq!(v(None, Some("W/\"x\""), Some("d1")).if_range().unwrap(), "d1");
assert_eq!(v(None, Some("W/\"x\""), None).if_range(), None);
}
#[test]
fn farm_versions() {
let v = |size, etag: &str, lm: &str| Validators { size, etag: Some(etag.into()), last_modified: Some(lm.into()) };
let a = v(Some(9), "W/\"bd6dcd82-1982ea51dc7\"", "Mon, 21 Jul 2025 20:20:29 GMT");
let b = v(Some(9), "W/\"bd6dcd82-16f743377f5\"", "Sun, 05 Jan 2020 05:35:27 GMT");
assert!(!a.same_file(&b) && a.maybe_same(&b) && b.maybe_same(&a));
assert!(!a.maybe_same(&v(Some(8), "W/\"bd6dcd82-1\"", "x")), "another size");
assert!(!a.maybe_same(&v(Some(9), "W/\"bd6dcd83-1982ea51dc7\"", "x")), "another size in the tag");
assert!(a.maybe_same(&v(Some(9), "\"opaque\"", "x")), "only bytes can tell");
assert!(!v(None, "\"a-1\"", "x").maybe_same(&v(None, "\"a-2\"", "x")), "no size");
}
}

View file

@ -175,6 +175,8 @@ pub struct Task {
pub mime: Option<String>,
pub etag: Option<String>,
pub last_modified: Option<String>,
/// Its link's servers differ in dates and tags but have the same bytes: versions are told by size and bytes.
pub farm: bool,
/// `sha256:…`.
pub checksum: Option<String>,
/// Hashes of its pieces, to repair single ones.
@ -226,6 +228,7 @@ impl Default for Task {
mime: None,
etag: None,
last_modified: None,
farm: false,
checksum: None,
pieces: None,
verified: None,

View file

@ -144,6 +144,7 @@ impl Checked {
task.size = self.size.or(task.size);
(task.etag, task.last_modified) = (self.version.etag.clone(), self.version.last_modified.clone());
task.mime = self.mime.clone();
task.farm = false;
}
}
@ -265,7 +266,7 @@ pub(crate) async fn probed(
checked.reason = Reason::Size { old, new };
return Ok((checked, None));
}
let server = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version };
let server = Link::new(client.clone(), source.at(&probe.url), probe.ranges, probe.version, false);
Ok((checked, Some((server, body))))
}

View file

@ -0,0 +1 @@
ALTER TABLE tasks ADD COLUMN farm INTEGER NOT NULL DEFAULT 0;

View file

@ -16,7 +16,7 @@ use std::thread::JoinHandle;
use std::time::Duration;
/// Never edit one that shipped; add the next number.
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql"), include_str!("006.sql")];
const MIGRATIONS: &[&str] = &[include_str!("001.sql"), include_str!("002.sql"), include_str!("003.sql"), include_str!("004.sql"), include_str!("005.sql"), include_str!("006.sql"), include_str!("007.sql")];
#[derive(Debug)]
pub enum Error {

View file

@ -41,6 +41,7 @@ fn bind_task(c: &Connection, sql: &str, t: &Task) -> Result<usize> {
":proxy": t.proxy, ":secret": t.secret, ":after": t.after, ":start_at": t.start_at, ":added_at": t.added_at,
":finished_at": t.finished_at, ":removed_at": t.removed_at, ":notes": t.notes, ":tries": t.tries,
":replaces": t.replaces, ":pieces": pieces, ":verified": t.verified, ":stream": stream, ":video": video,
":farm": t.farm,
};
Ok(c.execute(sql, columns)?)
}
@ -50,10 +51,10 @@ pub fn insert_task(c: &Connection, t: &Task) -> Result<TaskId> {
c,
"INSERT INTO tasks (url, mirrors, source_page, name, folder, state, queue, position, priority, size, downloaded, mime,
etag, last_modified, checksum, max_parts, speed_limit, headers, proxy, secret, after, start_at, added_at,
finished_at, removed_at, notes, tries, replaces, pieces, verified, stream, video)
finished_at, removed_at, notes, tries, replaces, pieces, verified, stream, video, farm)
VALUES (:url, :mirrors, :source_page, :name, :folder, 'queued', :queue, :position, :priority, :size, :downloaded, :mime,
:etag, :last_modified, :checksum, :max_parts, :speed_limit, :headers, :proxy, :secret, :after, :start_at, :added_at,
:finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream, :video)",
:finished_at, :removed_at, :notes, :tries, :replaces, :pieces, :verified, :stream, :video, :farm)",
t,
)?;
let id = c.last_insert_rowid();
@ -72,7 +73,7 @@ pub fn update_task(c: &Connection, t: &Task) -> Result<usize> {
etag = :etag, last_modified = :last_modified, checksum = :checksum, max_parts = :max_parts,
speed_limit = :speed_limit, headers = :headers, proxy = :proxy, secret = :secret, after = :after,
start_at = :start_at, added_at = :added_at, finished_at = :finished_at, removed_at = :removed_at, notes = :notes,
tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream, video = :video
tries = :tries, replaces = :replaces, pieces = :pieces, verified = :verified, stream = :stream, video = :video, farm = :farm
WHERE id = {}",
t.id
);
@ -123,6 +124,7 @@ fn task(r: &Row) -> Result<Task> {
mime: r.get("mime")?,
etag: r.get("etag")?,
last_modified: r.get("last_modified")?,
farm: r.get("farm")?,
checksum: r.get("checksum")?,
// One that can't be read is one that can't repair anything.
pieces: r.get::<_, Option<String>>("pieces")?.and_then(|p| p.parse().ok()).map(Arc::new),

View file

@ -40,6 +40,11 @@ pub struct Faults {
pub expire_status: Option<u16>,
/// More open connections than this from one client get 429.
pub max_conns: Option<usize>,
/// Served by this many "nodes" in turn (request number modulo N): the same bytes, but each its own Last-Modified and
/// nginx-style weak ETag `W/"<size hex>-<date hex>"`, and If-Range is checked against the node's own.
pub farm: Option<u32>,
/// On a farm, odd nodes serve other bytes of the same size.
pub liar: bool,
}
impl Faults {
@ -83,6 +88,8 @@ impl Faults {
"expire_requests" => num!(expire_requests),
"expire_status" => num!(expire_status),
"max_conns" => num!(max_conns),
"farm" => num!(farm),
"liar" => self.liar = v == "1",
_ => {}
}
Some(())
@ -95,12 +102,13 @@ impl Faults {
$($f: other.$f.clone().or_else(|| self.$f.clone()),)*
ignore_range: self.ignore_range || other.ignore_range,
gzip: self.gzip || other.gzip,
liar: self.liar || other.liar,
} };
}
pick!(
throttle_conn, throttle_total, latency_ms, stall_after, stall_ms, cut_after, reset_after, status,
retry_after, status_count, wrong_length, change_after, version_after_requests, expire_secs,
expire_requests, expire_status, max_conns
expire_requests, expire_status, max_conns, farm
)
}
}

View file

@ -537,13 +537,17 @@ where
reply = reply.with("Retry-After", r.to_string());
}
let src = reply.source.versioned(version);
let node = f.farm.filter(|n| *n > 1).map(|n| req_no % n);
let lies = f.liar && node.is_some_and(|k| k % 2 == 1);
let src = reply.source.versioned(version + u32::from(lies) * 1000);
let total = src.len();
let head_only = req.method == "HEAD";
let mut status = reply.status;
let mut headers = std::mem::take(&mut reply.headers);
let etag = format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id);
let modified = http_date(version);
let (etag, modified) = match node {
Some(k) => (format!("W/\"{total:x}-{:x}\"", 0x1982ea51dc7u64 + u64::from(version * 100 + k)), http_date(version * 7 + k + 1)),
None => (format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id), http_date(version)),
};
let mut range = None;
let ranges_on = reply.file && !f.ignore_range && !reply.chunked && !reply.no_length;
if reply.file && status == 200 {

View file

@ -3,7 +3,8 @@
//! `TestServer::start().await` binds 127.0.0.1 on a free port. Routes (all GET/HEAD):
//! - `/data/<seed>/<len>[/<name>]` deterministic file (`len` accepts k, m, g, t; 100g is fine).
//! Query: `disp=attachment|bare|star|both|inline|evil|dotfile`, `chunked=1`, `nolen=1`, `etag=0`,
//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]).
//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]). `farm=N` serves it from N nodes in turn that differ in
//! Last-Modified and nginx-style ETag only; `liar=1` with it gives the odd nodes other bytes of the same size.
//! - `/redirect/<n>?to=<path>&code=<30x>`, `/redirect/loop`, `/status/<code>`
//! - `/basic/<user>/<pass>/…`, `/digest/<user>/<pass>/…`, `/cookie/<token>/login` then `/cookie/<token>/…`,
//! `/referrer/<needle>/…`: the rest of the path is served after the check.