LRC-MAP-VIEW: a slow or throttling tile server can't hold a download slot or hide its status

From review on the Map view:
- An error answer (429, 5xx) is returned with its status and headers as soon as
  they arrive, its body never read: an error page too large or too slow no longer
  hides that the host is throttling (Retry-After reaches the backoff).
- lightcraft-fetch's Limits gains an overall deadline (`deadline`, HttpError::TooSlow),
  checked before every socket read and write, including chunk-size and trailer
  lines and each TLS handshake step (complete_io looped inside and is no longer
  used), and in connection setup when it comes before the connect timeout. A
  server trickling one byte under the stall timeout can no longer hold a request
  indefinitely. The tile transport sets it to its connect + body time; the model
  downloader passes none.
This commit is contained in:
Bruno D.
2026-12-02 17:23:41 -05:00
parent bfdaf65212
commit 1f2cbe4607
5 changed files with 87 additions and 10 deletions
+9 -1
View File
@@ -150,9 +150,17 @@ impl Transport for HttpTransport {
fn get(&self, url: &str, headers: &[(&'static str, String)], max_body: usize, cancel: &AtomicBool) -> Result<HttpResponse, TransportError> {
use lightcraft_fetch::http;
let url = http::Url::parse(url).map_err(|e| e.to_string())?;
let limits = http::Limits { connect: self.connect_timeout, stall: self.stall_timeout, cancel };
// the whole request (headers, chunk framing, trailers, body) within connect + body time: a
// server trickling bytes can't hold one of the two network slots past it
let deadline = Some(Instant::now() + self.connect_timeout + self.body_timeout);
let limits = http::Limits { connect: self.connect_timeout, stall: self.stall_timeout, cancel, deadline };
let hs: Vec<(&str, String)> = headers.iter().map(|(k, v)| (*k, v.clone())).collect();
let mut r = http::get(&url, &hs, &limits).map_err(|e| e.to_string())?;
// an error's status and headers (a 429's Retry-After) are what matters: its body is never
// read, so an error page too large or too slow can't hide that the host is throttling
if !(200..300).contains(&r.status) {
return Ok(HttpResponse { status: r.status, headers: kept_headers(|h| r.header_all(h)), body: Vec::new() });
}
if r.content_length().is_some_and(|n| n > max_body as u64) {
return Err(TransportError::TooLarge(format!("tile larger than {max_body} bytes")));
}
+6 -1
View File
@@ -426,7 +426,7 @@ fn the_http_transport_sends_the_right_headers_and_caps_bodies() {
let body = tile.clone();
let server = std::thread::spawn(move || {
let mut requests = Vec::new();
for i in 0..4 {
for i in 0..5 {
let (mut s, _) = listener.accept().unwrap();
let mut r = BufReader::new(s.try_clone().unwrap());
let mut head = Vec::new();
@@ -448,6 +448,8 @@ fn the_http_transport_sends_the_right_headers_and_caps_bodies() {
}
1 => s.write_all(b"HTTP/1.1 304 Not Modified\r\nCache-Control: max-age=60\r\n\r\n").unwrap(),
2 => s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3000000\r\n\r\n").unwrap(),
// throttled, with an error page far past the tile cap
3 => s.write_all(b"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 120\r\nContent-Length: 30000000\r\n\r\n").unwrap(),
_ => {
// chunked, past the cap without announcing it
s.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n").unwrap();
@@ -478,6 +480,9 @@ fn the_http_transport_sends_the_right_headers_and_caps_bodies() {
assert!(
matches!(t.get(&format!("{base}/1/0/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err(), TransportError::TooLarge(m) if m.contains("larger"))
);
// the throttling reaches the service, though the error page is over the cap
let r = t.get(&format!("{base}/1/1/0.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap();
assert_eq!((r.status, r.header("retry-after"), r.body.len()), (429, Some("120"), 0));
assert!(
matches!(t.get(&format!("{base}/1/1/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err(), TransportError::TooLarge(m) if m.contains("larger"))
);
+69 -5
View File
@@ -24,6 +24,8 @@ pub enum HttpError {
Connect(String),
/// No data arrived for the stall timeout.
Stalled,
/// The request went past its overall deadline ([`Limits::deadline`]), data arriving or not.
TooSlow,
/// The cancel flag was raised.
Cancelled,
/// TLS failed (certificate, handshake).
@@ -40,6 +42,7 @@ impl std::fmt::Display for HttpError {
HttpError::BadUrl(e) => write!(f, "unusable URL: {e}"),
HttpError::Connect(e) => write!(f, "could not connect: {e}"),
HttpError::Stalled => write!(f, "the server stopped sending data"),
HttpError::TooSlow => write!(f, "the server took too long to answer"),
HttpError::Cancelled => write!(f, "cancelled"),
HttpError::Tls(e) => write!(f, "secure connection failed: {e}"),
HttpError::Protocol(e) => write!(f, "unexpected response: {e}"),
@@ -91,6 +94,16 @@ pub struct Limits<'a> {
pub connect: Duration,
pub stall: Duration,
pub cancel: &'a AtomicBool,
/// When the whole request must be done by (`None`: no limit). The stall timeout restarts with
/// every byte, so without this a server sending a byte now and then (in headers, chunk sizes,
/// trailers or the body) could hold one request for as long as it likes.
pub deadline: Option<Instant>,
}
impl Limits<'_> {
fn past_deadline(&self) -> bool {
self.deadline.is_some_and(|d| Instant::now() >= d)
}
}
/// How often a blocked read wakes up to check the cancel flag.
@@ -175,10 +188,12 @@ fn connect_any(host: &str, addrs: &[SocketAddr], deadline: Instant, limits: &Lim
impl Stream {
fn connect(url: &Url, limits: &Limits) -> Result<Stream, HttpError> {
// the lookup and the connection attempts share one connect timeout
let deadline = Instant::now() + limits.connect;
// the connect timeout, or the request's overall deadline when that comes first
let deadline = limits.deadline.map_or(Instant::now() + limits.connect, |d| d.min(Instant::now() + limits.connect));
let too_slow = |e: HttpError| if limits.past_deadline() { HttpError::TooSlow } else { e };
let (host, port) = (url.host.clone(), url.port);
let addrs = lookup(&url.host, move || (host.as_str(), port).to_socket_addrs().map(Iterator::collect), deadline, limits)?;
let sock = connect_any(&url.host, &addrs, deadline, limits)?;
let addrs = lookup(&url.host, move || (host.as_str(), port).to_socket_addrs().map(Iterator::collect), deadline, limits).map_err(too_slow)?;
let sock = connect_any(&url.host, &addrs, deadline, limits).map_err(too_slow)?;
sock.set_read_timeout(Some(TICK)).map_err(|e| HttpError::Io(e.to_string()))?;
sock.set_write_timeout(Some(TICK)).map_err(|e| HttpError::Io(e.to_string()))?;
let _ = sock.set_nodelay(true);
@@ -199,6 +214,9 @@ impl Stream {
if limits.cancel.load(Ordering::Relaxed) {
return Err(HttpError::Cancelled);
}
if limits.past_deadline() {
return Err(HttpError::TooSlow);
}
match f() {
Ok(v) => return Ok(v),
Err(e) if is_timeout(&e) => {
@@ -214,8 +232,21 @@ impl Stream {
fn handshake(&mut self, limits: &Limits) -> Result<(), HttpError> {
let Stream::Tls(conn, sock) = self else { return Ok(()) };
// one socket read or write at a time (not complete_io, which loops inside), so the
// deadline and cancel flag are checked between every step
while conn.is_handshaking() {
Self::retry(limits, || conn.complete_io(sock))?;
while conn.wants_write() {
Self::retry(limits, || conn.write_tls(sock))?;
}
if conn.is_handshaking() && conn.wants_read() {
if Self::retry(limits, || conn.read_tls(sock))? == 0 {
return Err(HttpError::Tls("connection closed during the handshake".into()));
}
conn.process_new_packets().map_err(|e| HttpError::Tls(e.to_string()))?;
}
}
while conn.wants_write() {
Self::retry(limits, || conn.write_tls(sock))?;
}
Ok(())
}
@@ -254,6 +285,9 @@ impl Stream {
if limits.cancel.load(Ordering::Relaxed) {
return Err(HttpError::Cancelled);
}
if limits.past_deadline() {
return Err(HttpError::TooSlow);
}
match conn.reader().read(buf) {
Ok(n) => return Ok(n),
// closed without close_notify: the caller checks the length it got
@@ -504,7 +538,37 @@ mod tests_connect {
use super::*;
fn limits(cancel: &AtomicBool) -> Limits<'_> {
Limits { connect: Duration::from_millis(300), stall: Duration::from_secs(1), cancel }
Limits { connect: Duration::from_millis(300), stall: Duration::from_secs(1), cancel, deadline: None }
}
/// A server that trickles bytes (one per 100 ms, never stalling a full second) is stopped at the
/// request's deadline instead of holding it for as long as it likes.
#[test]
fn a_trickling_server_is_stopped_at_the_deadline() {
use std::io::Write;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let _ = s.write_all(
b"HTTP/1.1 200 OK
",
);
for _ in 0..100 {
if s.write_all(b"X").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
});
let cancel = AtomicBool::new(false);
let limits = Limits { deadline: Some(Instant::now() + Duration::from_millis(500)), ..limits(&cancel) };
let url = Url::parse(&format!("http://127.0.0.1:{port}/t")).unwrap();
let t = Instant::now();
let r = get(&url, &[], &limits);
assert!(matches!(r, Err(HttpError::TooSlow)), "{:?}", r.err());
assert!(t.elapsed() < Duration::from_secs(3), "stopped near the deadline: {:?}", t.elapsed());
drop(server);
}
/// A name lookup that hangs is given up on at the connect timeout, and Cancel stops it at once (issue #1532).
+2 -2
View File
@@ -359,7 +359,7 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
if let Some(src) = local {
copy_local(&src, &part, limit, f.size, cancel, report)?;
} else if fetched {
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel };
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel, deadline: None };
let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?;
let origin = url.host.clone();
let mut redirects = 0;
@@ -567,7 +567,7 @@ fn copy_local(src: &Path, part: &Path, limit: u64, size: Option<u64>, cancel: &A
fn http_fail(e: HttpError) -> Fail {
match e {
HttpError::Cancelled => Fail::Cancelled,
HttpError::Stalled | HttpError::Io(_) | HttpError::Protocol(_) => Fail::Retry(e.to_string()),
HttpError::Stalled | HttpError::TooSlow | HttpError::Io(_) | HttpError::Protocol(_) => Fail::Retry(e.to_string()),
HttpError::BadUrl(_) | HttpError::Connect(_) | HttpError::Tls(_) => Fail::NextMirror(e.to_string()),
}
}
+1 -1
View File
@@ -583,7 +583,7 @@ fn a_callers_user_agent_replaces_the_default() {
agents
});
let cancel = AtomicBool::new(false);
let limits = crate::http::Limits { connect: Duration::from_secs(5), stall: Duration::from_secs(5), cancel: &cancel };
let limits = crate::http::Limits { connect: Duration::from_secs(5), stall: Duration::from_secs(5), cancel: &cancel, deadline: None };
assert_eq!(crate::http::get(&url, headers, &limits).unwrap().status, 204);
worker.join().unwrap()
}