diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f8e1f2a996..ef61c6ef0a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5934,6 +5934,11 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, // (which follow the time slider) and AlphaEarth's quantised embeddings (which raster styles // don't dequantise) are tile layers. let (file, mut look) = crate::render::rustgis_tiles::cog::split(url); + // A header not read first (a plugin's command in the app, a data cube's file) whose connection + // dropped is read again by what draws the layer now, as a probed one is (#2886). + if !probed { + crate::render::rustgis_tiles::cog::forget_dropped(file); + } // A key given as `null` (a script's unused one) asks for nothing. let given = |k: &str| p.get(k).filter(|v| !v.is_null()); // A data cube's file stays a tile layer, its project opened again too: its address says so. @@ -5961,7 +5966,14 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, let dated = s.map().tiles.get(index).ok_or("added GeoTIFF tile is missing")?.url.clone(); // Its header read now (natively) as an undated address's is before it is added. #[cfg(not(target_arch = "wasm32"))] - let probe = if s.leave_downloads { Ok(false) } else { crate::render::rustgis_tiles::cog::probe_blocking(&dated) }; + // Not probed off the frame: the file shown (not the template) is read again by the map's + // draw if its connection dropped (#2886). + let probe = if s.leave_downloads { + crate::render::rustgis_tiles::cog::forget_dropped(&dated); + Ok(false) + } else { + crate::render::rustgis_tiles::cog::probe_blocking(&dated) + }; #[cfg(target_arch = "wasm32")] let probe: Result = Ok(false); (dated, probe == Ok(true), probe.err()) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1ffa103c7..ae179eeaa3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -31586,6 +31586,74 @@ fn a_stac_data_cube_from_a_plugin_command_in_the_app() { ); } +/// A server that drops every connection once its request is in, and a signal for each request. +#[cfg(not(target_arch = "wasm32"))] +fn serve_dropping_all() -> (String, std::sync::mpsc::Receiver<()>) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let mut buf = [0u8; 4096]; + let _ = std::io::Read::read(&mut stream, &mut buf); + // Sent before the connection drops, so a read that has failed has been counted. + let _ = tx.send(()); + } + }); + (base, rx) +} + +/// Whether a header whose connection dropped (#2886) is asked for again once `add` runs: the +/// requests made before it are let go, and one is waited for after it. +#[cfg(not(target_arch = "wasm32"))] +fn asked_again_after(asked: &std::sync::mpsc::Receiver<()>, add: impl FnOnce()) -> bool { + while asked.try_recv().is_ok() {} + add(); + asked.recv_timeout(std::time::Duration::from_secs(3)).is_ok() +} + +/// A cube's file whose header's connection dropped each time (#2886) is asked for again when the +/// app adds it again (a plugin's command, off the frame), as one the command line adds is. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_cube_file_whose_header_dropped_is_read_again_when_added_off_the_frame() { + let (base, asked) = serve_dropping_all(); + let url = format!("{base}/dropped-cube.tif"); + let e = crate::render::rustgis_tiles::cog::info_blocking(&url).err().unwrap_or_default(); + assert!(e.contains("the connection dropped"), "{e}"); + let mut s = Session::new(Project::default()); + s.leave_downloads = true; + let again = asked_again_after(&asked, || { + s.run("layer.addUrl", &json!({"url": url, "cube": true})).unwrap(); + }); + assert!(again, "the header wasn't asked for again"); +} + +/// A dated address's file whose header's connection dropped (#2886) is asked for again when the +/// app adds the address again off the frame: the file of the date shown, not the template. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_dated_file_whose_header_dropped_is_read_again_when_added_off_the_frame() { + let (base, asked) = serve_dropping_all(); + let files: Vec<_> = (2020..=2021).map(|year| format!("{base}/{year}.tif")).collect(); + let reads: Vec<_> = files + .iter() + .cloned() + .map(|file| std::thread::spawn(move || crate::render::rustgis_tiles::cog::info_blocking(&file).err().unwrap_or_default())) + .collect(); + for read in reads { + let e = read.join().unwrap(); + assert!(e.contains("the connection dropped"), "{e}"); + } + let mut s = Session::new(Project::default()); + s.leave_downloads = true; + let again = asked_again_after(&asked, || { + s.run("layer.addUrl", &json!({"url": format!("{base}/{{date:YYYY}}.tif"), "start": 2020, "end": 2021})).unwrap(); + }); + assert!(again, "the shown date's header wasn't asked for again"); +} + /// An entry that gives no range, as JAXA Earth's don't, is added with one from a sample of its /// files (`"range": "auto"`): the same for every date. Its credit goes on the tile layers it /// added, and its collection's licence comes back with it. diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 0eab06da51..e59970d5b0 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -849,6 +849,14 @@ pub fn retry_after(error: &str) -> Option { Some(Duration::from_secs(secs.clamp(1, crate::failure::MAX_RETRY_AFTER))) } +/// Whether a read failed because its connection dropped before its bytes were in, each time it was +/// tried (see [`crate::failure::with_drops`]): the server is there, unlike one that can't be reached. +pub(crate) fn connection_dropped(error: &str) -> bool { + error + .rsplit_once(" (the connection dropped, tries: ") + .is_some_and(|(_, rest)| rest.strip_suffix(')').is_some_and(|n| n.parse::().is_ok())) +} + /// How long a failed read waits before it is tried again: what its server asked for (see /// [`retry_after`]), else `default`. pub fn retry_wait(error: &str, default: Duration) -> Duration { @@ -2562,8 +2570,10 @@ mod native { //! A tile costs one or two round trips plus the server's own time (Esri's World Imagery //! Wayback answers every tile with a redirect first), and the connections stay open between //! tiles, so fetching is bound by latency: how many requests are under way at once. Each - //! server gets up to [`PER_HOST`] of them (OpenStreetMap's tile servers [`PER_HOST_OSM`]), and - //! the workers share one agent, so a server never sees more open connections than that. + //! server gets up to [`PER_HOST`] of them (OpenStreetMap's tile servers [`PER_HOST_OSM`], + //! each of CDSE's data servers [`crate::copernicus::PER_HOST`], the connections its quota gives + //! a general account), and the workers share one agent, so a server never sees more open + //! connections than that. use std::collections::HashMap; use std::sync::{Condvar, Mutex, OnceLock}; @@ -2672,9 +2682,7 @@ mod native { return String::new(); }; let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); - let authority = rest.get(..end).unwrap_or(rest); - // Credentials in the address aren't part of the server. - authority.rsplit_once('@').map_or(authority, |(_, h)| h).to_ascii_lowercase() + crate::schedule::server(rest.get(..end).unwrap_or(rest)) } /// How many fetches may be under way at once from `host`. @@ -2684,6 +2692,8 @@ mod native { WORKERS } else if name == "tile.openstreetmap.org" || name.ends_with(".tile.openstreetmap.org") { PER_HOST_OSM + } else if crate::copernicus::has_quota(name) { + crate::copernicus::PER_HOST } else { PER_HOST } @@ -3494,6 +3504,42 @@ mod native { /// The User-Agent every request goes with. const USER_AGENT: &str = concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)"); + /// How long a range whose connection dropped before its bytes were in waits before each next + /// try (#2886): some servers drop a share of the connections they are offered, and one drop + /// would fail the whole window, file header or archive the range is for. + const DROP_WAITS: [std::time::Duration; 4] = [ + std::time::Duration::from_millis(200), + std::time::Duration::from_millis(500), + std::time::Duration::from_secs(1), + std::time::Duration::from_secs(2), + ]; + /// No try starts later than this after the range was first asked for, so a server slow to drop + /// its connections adds at most this to the agent's own time limit. + const DROP_WITHIN: std::time::Duration = std::time::Duration::from_secs(10); + + /// Whether `e` says the other side dropped the connection: while it was made secure, after the + /// request went, or before the whole body came. Not one refused, timed out or never found, + /// which asking again at once wouldn't change. + fn dropped(e: &std::io::Error) -> bool { + use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof}; + matches!(e.kind(), BrokenPipe | ConnectionAborted | ConnectionReset | UnexpectedEof) + } + + /// Waits `wait` out, or stops once the request is no longer wanted. A queued fetch keeps its + /// place at its server meanwhile, so a server that drops connections isn't asked for more at + /// once while it does. + fn pause(wait: std::time::Duration) -> Result<(), String> { + let end = std::time::Instant::now() + wait; + loop { + super::check_current()?; + let left = end.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return Ok(()); + } + std::thread::sleep(left.min(std::time::Duration::from_millis(100))); + } + } + /// A request that never got an answer: what kind of failure, for the user (#509). fn unanswered(e: ureq::Error) -> Failure { let reason = match &e { @@ -3614,7 +3660,9 @@ mod native { /// `omit` is an expected answer: its failure isn't recorded, only noted once per server. A /// request carrying a login is recorded by its plain address and scrubbed text only /// ([`RequestDiagnostics::failed`]). `agent` must already enforce `initial` in its resolver; - /// the worker selects that pool before dispatch. Redirects can only narrow it further. + /// the worker selects that pool before dispatch. Redirects can only narrow it further. A range + /// whose connection drops is asked for again from the start ([`DROP_WAITS`]), what came of it + /// thrown away: its login and whether it is still wanted are checked again each time. pub(super) fn fetch_answer( agent: &ureq::Agent, url: &str, @@ -3635,12 +3683,20 @@ mod native { omit: &'static [u16], ) -> Result { use std::io::Read; + // Kept over the tries of a dropped range: once any try carried a login, what comes back is + // scrubbed, as after a single try that did. let mut carried_login = false; // Local file failures are not network traffic. let local = crate::mbtiles::is_tile(url) || url.starts_with(LOCAL); let mut diagnostics = super::RequestDiagnostics::new(url, "GET"); diagnostics.omit_statuses(omit); - let answer = (|| -> Result { + let dropped_now = std::cell::Cell::new(false); + // A body that didn't come whole. + let cut = |e: std::io::Error| { + dropped_now.set(dropped(&e)); + Failure::from(e.to_string()) + }; + let mut attempt = || -> Result { super::check_current()?; if crate::mbtiles::is_tile(url) { return crate::mbtiles::read_local(url).map(|bytes| Fetched { bytes, origin: Origin::named(url) }).map_err(Failure::from); @@ -3707,7 +3763,10 @@ mod native { }; // Recheck the original binding even after redirects dropped its credentials. crate::logins::check(url).map_err(str::to_string)?; - let (mut resp, reached) = connected(|| req.call()).map_err(unanswered)?; + let (mut resp, reached) = connected(|| req.call()).map_err(|e| { + dropped_now.set(matches!(&e, ureq::Error::Io(io) if dropped(io))); + unanswered(e) + })?; ceiling = ceiling.min(reached); let status = resp.status().as_u16(); diagnostics.answered(status); @@ -3837,7 +3896,7 @@ mod native { Wanted::part(resp.body_mut().with_config().limit(limit.saturating_add(1)).reader()) .take(limit) .read_to_end(&mut buf) - .map_err(|e| e.to_string())?; + .map_err(cut)?; if buf.len() as u64 > n { return Err(rustgis_data::diagnostics::message_with_address(url, super::NO_RANGES).into()); } @@ -3851,7 +3910,7 @@ mod native { Wanted::new(resp.body_mut().with_config().limit(max as u64 + 2).reader(), total) .take(max as u64 + 1) .read_to_end(&mut buf) - .map_err(|e| e.to_string())?; + .map_err(cut)?; if buf.len() > max { return Err(format!("larger than {max} bytes").into()); } @@ -3862,7 +3921,27 @@ mod native { buf.truncate(usize::try_from(b - a + 1).unwrap_or(usize::MAX)); } Ok(Fetched { bytes: buf, origin }) - })(); + }; + let (plain, tail) = super::split_tail(super::split_download_limit(url).0); + let ranged = tail.is_some() || super::split_range(plain).1.is_some(); + let asked = std::time::Instant::now(); + let mut drops = 0; + let answer = loop { + dropped_now.set(false); + let mut failure = match attempt() { + Err(failure) if ranged && dropped_now.get() => failure, + answer => break answer, + }; + let wait = DROP_WAITS.get(drops).filter(|w| asked.elapsed() + **w <= DROP_WITHIN); + drops += 1; + let Some(wait) = wait else { + failure.message = crate::failure::with_drops(&failure.message, drops); + break Err(failure); + }; + if let Err(e) = pause(*wait) { + break Err(e.into()); + } + }; let result = if local { answer } else { diagnostics.record(answer) }; let result = crate::logins::check(super::resource_of(url)).map_err(Failure::from).and(result); result.map_err(|mut f| { @@ -7103,6 +7182,17 @@ Connection: close assert!(native::cap("tile.openstreetmap.org") < native::cap("example.org")); assert_eq!(native::cap("a.tile.openstreetmap.org"), native::cap("tile.openstreetmap.org")); assert!(native::cap("") >= native::cap("example.org")); + // Copernicus Data Space's data servers get an account's quota; its catalog has none. + for host in ["download", "zipper", "eodata"] { + assert_eq!(native::cap(&format!("{host}.dataspace.copernicus.eu:443")), 4); + } + assert_eq!(native::cap("stac.dataspace.copernicus.eu"), native::cap("example.org")); + assert_eq!(native::cap("download.dataspace.copernicus.eu.example.org"), native::cap("example.org")); + // An absolute name (a trailing dot) is its server, as the token is sent to it (#2886). + let absolute = "https://Download.Dataspace.Copernicus.eu./a.tif"; + assert!(crate::copernicus::is_data_host(absolute)); + assert_eq!(native::host(absolute), "download.dataspace.copernicus.eu"); + assert_eq!(native::host("http://example.org.:8080/a"), "example.org:8080"); // The newest job whose server has room. let full = native::cap("a.org"); let active: HashMap = [("a.org".to_string(), full)].into(); @@ -7111,6 +7201,86 @@ Connection: close assert_eq!(native::pick(&["a.org"], &HashMap::new()), Some(0)); } + /// A server that drops its first `drops` connections once their request is in and `cut` is + /// sent, then answers with `answer`, and how many requests it has had. + #[cfg(not(target_arch = "wasm32"))] + fn serve_after_drops(drops: usize, cut: &'static str, answer: &'static str) -> (String, Arc) { + use std::io::Write; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let asked = Arc::new(AtomicUsize::new(0)); + let n = asked.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let _ = read_request(&mut stream); + let sent = if n.fetch_add(1, Ordering::SeqCst) < drops { cut } else { answer }; + let _ = stream.write_all(sent.as_bytes()); + } + }); + (base, asked) + } + + /// A range whose connection drops before its answer, or before its whole body, is asked for + /// again (#2886); a refusal, a connection refused and a request for a whole address aren't. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_range_whose_connection_drops_is_asked_for_again() { + const PART: &str = + "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-3/9\r\nContent-Length: 4\r\nConnection: close\r\n\r\nrust"; + let agent = native::agent(); + // The start of `PART`, two of its four bytes in. + const CUT: &str = "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-3/9\r\nContent-Length: 4\r\nConnection: close\r\n\r\nru"; + for cut in ["", CUT] { + let (base, asked) = serve_after_drops(2, cut, PART); + assert_eq!(native::get(&agent, &format!("{base}/a{RANGE}0-3"), &[]).unwrap(), b"rust"); + assert_eq!(asked.load(Ordering::SeqCst), 3); + let (base, asked) = serve_after_drops(1, cut, PART); + assert_eq!(native::get(&agent, &format!("{base}/a{TAIL}4"), &[]).unwrap(), b"rust"); + assert_eq!(asked.load(Ordering::SeqCst), 2); + } + + let (base, asked) = serve_after_drops(1, "", "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); + let e = native::get(&agent, &format!("{base}/a"), &[]).unwrap_err(); + assert!(!connection_dropped(&e), "{e}"); + assert_eq!(asked.load(Ordering::SeqCst), 1); + let (base, asked) = serve_after_drops(0, "", "HTTP/1.1 503 Busy\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + assert_eq!(native::get(&agent, &format!("{base}/a{RANGE}0-3"), &[]).unwrap_err(), "http status: 503"); + assert_eq!(asked.load(Ordering::SeqCst), 1); + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap(); + let e = native::get(&agent, &format!("http://{closed}/a{RANGE}0-3"), &[]).unwrap_err(); + assert!(!connection_dropped(&e), "{e}"); + } + + /// A range dropped every time fails after its tries, saying so; one no longer wanted stops + /// waiting for its next try. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_range_always_dropped_fails_after_its_tries() { + let agent = native::agent(); + let (base, asked) = serve_after_drops(usize::MAX, "", ""); + let url = format!("{base}/a{RANGE}0-3"); + let e = native::get_detailed(&agent, &url).unwrap_err(); + assert!(e.message.ends_with(" (the connection dropped, tries: 5)") && connection_dropped(&e.message), "{}", e.message); + assert_eq!(e.reason, crate::failure::Reason::Unreachable); + assert_eq!(asked.load(Ordering::SeqCst), 5); + + let (base, asked) = serve_after_drops(usize::MAX, "", ""); + let seen = asked.clone(); + let still: Still = Arc::new(move || seen.load(Ordering::SeqCst) < 2); + let e = with_still(still, || native::get(&agent, &format!("{base}/a{RANGE}0-3"), &[])).unwrap_err(); + assert!(!connection_dropped(&e), "{e}"); + assert_eq!(asked.load(Ordering::SeqCst), 2); + } + + #[test] + fn only_a_dropped_connection_is_read_back_as_one() { + assert!(connection_dropped("https://example.org/a.tif: io: Peer disconnected (the connection dropped, tries: 5)")); + for e in ["io: Peer disconnected", "http status: 503 (retry after 30 s)", "x (the connection dropped, tries: many)", ""] { + assert!(!connection_dropped(e), "{e}"); + } + } + /// Many tiles from one server are fetched more than 8 at a time (the old pool), and never /// more than the server's cap. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 98e788d9ca..476fd12ac8 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1623,11 +1623,29 @@ fn read_whole(e: &str) -> bool { e.contains(NOT_COG) || e.contains("not a GeoTIFF") } +/// Forgets a header that failed because its connection dropped +/// ([`crate::cache::connection_dropped`]), so a caller that asks for the file itself (a layer +/// added, an analysis) rather than draws it has the header read again now. The map's draws +/// ([`info`]) keep their wait, as after every other failure. +fn ask_again_if_dropped(url: &str) { + let mut i = infos().lock().unwrap_or_else(|e| e.into_inner()); + if matches!(i.get(url), Some(State::Failed(e, ..)) if crate::cache::connection_dropped(e)) { + i.remove(url); + } +} + +/// [`ask_again_if_dropped`] for a layer added without its header read first (a plugin's command in +/// the app, a data cube's file): the map's draw that follows reads it again. +pub fn forget_dropped(url: &str) { + ask_again_if_dropped(split(url).0); +} + /// Whether the file at `url` is a cloud-optimised GeoTIFF, waiting for the answer (the command /// line): `Ok(false)` for any other file, read whole instead. #[cfg(not(target_arch = "wasm32"))] pub fn probe_blocking(url: &str) -> Result { let url = split(url).0; + ask_again_if_dropped(url); let (tx, rx) = std::sync::mpsc::channel(); with_info(url, Box::new(move |r| tx.send(r.map(|_| ())).unwrap_or_default())); match rx.recv_timeout(std::time::Duration::from_secs(60)) { @@ -1642,6 +1660,7 @@ pub fn probe_blocking(url: &str) -> Result { /// `Ok(false)` for any other file, read whole instead. pub fn probe(url: &str, then: Box) + Send>) { let url = split(url).0; + ask_again_if_dropped(url); with_info( url, Box::new(move |r| { @@ -1673,6 +1692,7 @@ pub fn info_blocking(url: &str) -> Result, String> { #[cfg(not(target_arch = "wasm32"))] pub fn info_until(url: &str, stop: &std::sync::atomic::AtomicBool) -> Result, String> { let url = split(url).0; + ask_again_if_dropped(url); let (tx, rx) = std::sync::mpsc::channel(); with_info(url, Box::new(move |r| tx.send(r).unwrap_or_default())); wait_until(&rx, Duration::from_secs(120), stop).map_err(|stopped| stopped_or(stopped, url, "no answer in two minutes"))? @@ -2475,6 +2495,45 @@ mod tests { assert!(within(), "not armed again: {:?}", crate::cache::next_alarm()); super::infos().lock().unwrap().remove(file); } + + /// A file whose header's connection dropped each time (#2886) is asked for again when it is + /// asked for itself (a layer added again, an analysis), and not by the map's draws, which wait + /// as after any failure. Another failure waits for both. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_header_whose_connection_dropped_is_read_again_when_asked_for() { + let _turn = crate::cache::turn(); + let _alarm = crate::cache::alarm_turn(); + let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let n = asked.clone(); + crate::cache::set_fetcher(move |_, done| { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + done(Ok(b"not a tiff".to_vec())); + }); + let file = "https://dropped-cog.invalid/a.tif"; + let fail = |why: &str| { + let state = super::State::Failed(format!("{file}: {why}"), Instant::now(), crate::cache::ceiling_for(file)); + super::infos().lock().unwrap().insert(file.to_string(), state); + }; + let count = || asked.load(std::sync::atomic::Ordering::SeqCst); + let dropped = crate::failure::with_drops("io: Peer disconnected", 5); + let (tx, rx) = std::sync::mpsc::channel(); + + fail(&dropped); + assert!(super::info(file).is_err_and(|e| e.contains(&dropped)) && count() == 0, "the map's draw asked again"); + assert_eq!((super::probe_blocking(file), count()), (Ok(false), 1)); + fail(&dropped); + assert!(super::info_blocking(file).is_err_and(|e| e.contains("not a GeoTIFF")) && count() == 2); + fail(&dropped); + super::probe(file, Box::new(move |r| tx.send(r).unwrap())); + assert_eq!((rx.recv().unwrap(), count()), (Ok(false), 3)); + + fail("http status: 503"); + assert!(super::probe_blocking(file).is_err_and(|e| e.contains("503")) && count() == 3); + crate::cache::clear_fetcher(); + super::infos().lock().unwrap().remove(file); + } + #[test] fn public_restriction_rejects_an_in_flight_local_header_and_allows_retry() { let _turn = crate::cache::turn(); diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index a59403384a..149250aea2 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -36,6 +36,14 @@ pub const TOKEN_URL: &str = "https://identity.dataspace.copernicus.eu/auth/realm pub const CLIENT_ID: &str = "cdse-public"; /// The hosts whose files need the token: the only ones it is sent to, over HTTPS. pub const DATA_HOSTS: &[&str] = &["download.dataspace.copernicus.eu", "zipper.dataspace.copernicus.eu"]; +/// The hosts where a request counts against the account's quota: [`DATA_HOSTS`] and CDSE's S3 +/// endpoint. +const QUOTA_HOSTS: &[&str] = &["download.dataspace.copernicus.eu", "zipper.dataspace.copernicus.eu", "eodata.dataspace.copernicus.eu"]; +/// Requests under way at once to each of [`QUOTA_HOSTS`], counted per host: the connections a +/// general account may have open (). +/// One more is refused with 429. The quota counts an account's connections over all its hosts, so +/// layers read from two hosts at once may still meet one. +pub(crate) const PER_HOST: usize = 4; /// Where an account is made. pub const SIGN_UP: &str = "https://dataspace.copernicus.eu"; /// An access token is renewed this long before it expires (seconds). @@ -506,6 +514,11 @@ fn https_host(url: &str) -> Option { Some(authority.trim_end_matches('.').to_ascii_lowercase()) } +/// Whether requests to the server `name` (lowercase, no port) count against a CDSE quota. +pub(crate) fn has_quota(name: &str) -> bool { + QUOTA_HOSTS.contains(&name) +} + /// Whether `url` is on a CDSE data host, the only place the token is sent: HTTPS, no user info /// or port, the host exactly one of [`DATA_HOSTS`]. pub fn is_data_host(url: &str) -> bool { diff --git a/crates/tiles/src/failure.rs b/crates/tiles/src/failure.rs index 95d6588bf5..d090ef12b4 100644 --- a/crates/tiles/src/failure.rs +++ b/crates/tiles/src/failure.rs @@ -231,6 +231,14 @@ fn retry_after_secs(value: &str, now: u64) -> Option { Some(secs.clamp(1, MAX_RETRY_AFTER)) } +/// A failure's text (`io: Peer disconnected`) with how many times its range was asked for, the +/// connection dropped before its bytes were in each time (#2886). Read back by +/// [`crate::cache::connection_dropped`]. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn with_drops(text: &str, tries: usize) -> String { + format!("{text} (the connection dropped, tries: {tries})") +} + /// A status's usual name (`403` → `Forbidden`), for the common ones. pub fn status_name(status: u16) -> Option<&'static str> { Some(match status { diff --git a/crates/tiles/src/schedule.rs b/crates/tiles/src/schedule.rs index 231b3b9a1c..255fa84701 100644 --- a/crates/tiles/src/schedule.rs +++ b/crates/tiles/src/schedule.rs @@ -40,9 +40,20 @@ pub(crate) fn host(url: &str) -> String { return String::new(); }; let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); - let authority = rest.get(..end).unwrap_or(rest); - // Credentials in the address aren't part of the server. - authority.rsplit_once('@').map_or(authority, |(_, h)| h).to_ascii_lowercase() + server(rest.get(..end).unwrap_or(rest)) +} + +/// The server an address's authority names (`host[:port]`, lowercase): its credentials left out, +/// and an absolute name (`example.org.`) the same server as `example.org`, as CDSE's token goes to +/// both (#2886). +pub(crate) fn server(authority: &str) -> String { + let server = authority.rsplit_once('@').map_or(authority, |(_, h)| h).to_ascii_lowercase(); + let (name, port) = match server.rsplit_once(':') { + Some((name, port)) if !server.ends_with(']') => (name, Some(port)), + _ => (server.as_str(), None), + }; + let name = name.trim_end_matches('.'); + port.map_or_else(|| name.to_string(), |port| format!("{name}:{port}")) } /// How many fetches may be under way at once from `host`. @@ -52,6 +63,8 @@ pub(crate) fn cap(host: &str) -> usize { LOCAL } else if name == "tile.openstreetmap.org" || name.ends_with(".tile.openstreetmap.org") { PER_HOST_OSM + } else if crate::copernicus::has_quota(name) { + crate::copernicus::PER_HOST } else { PER_HOST } @@ -219,6 +232,15 @@ mod tests { assert_eq!(host("mbtiles:3/1/2@https://example.org/x.mbtiles"), ""); assert_eq!(cap("a.tile.openstreetmap.org"), PER_HOST_OSM); assert_eq!(cap("tiles.example.com"), PER_HOST); + assert_eq!(cap("download.dataspace.copernicus.eu"), crate::copernicus::PER_HOST); + assert_eq!(cap("stac.dataspace.copernicus.eu"), PER_HOST); + // Every host the token goes to counts against the quota; an absolute name is its server. + for name in crate::copernicus::DATA_HOSTS { + assert_eq!(cap(name), crate::copernicus::PER_HOST, "{name}"); + } + assert_eq!(host("https://Download.Dataspace.Copernicus.eu./a.tif"), "download.dataspace.copernicus.eu"); + assert_eq!(host("http://example.org.:8080/a"), "example.org:8080"); + assert_eq!(host("http://[::1]:8080/a"), "[::1]:8080"); assert_eq!(cap(""), LOCAL); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4a360e2ed6..0551158a16 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -153,9 +153,13 @@ app and the browser add the layer, which says why it can't be read. GDAL's COG d makes the overviews. A tile a sparse file leaves out is empty. A tile, the file's header or the overview a layer holds, that fails to arrive is asked for again a minute later, or when its server says to in a `Retry-After` header (with a 429 or 503 answer, within the hour); the map draws again -then. An overview that fails again waits twice as long each time, up to an hour. On the command -line and in Python, which don't draw, the next command run once the wait is over reads a failed -overview again, waiting for it as the project did. +then. On the desktop, the command line and in Python, a part of the file whose connection the server +drops before it is in is first asked for again, up to four times over about four seconds; if a +COG's header still drops, adding the layer again asks for it at once (this is for COGs only: a +PMTiles header, a tile or an overview waits the minute). An overview that fails again waits +twice as long each time, up to an hour. On the command line and in Python, which don't draw, the +next command run once the wait is over reads a failed overview again, waiting for it as the +project did. Exporting the layer (Raster to PMTiles) waits for its tiles on the desktop, up to two minutes, and isn't written without them; the web app can't wait, so an export whose tiles aren't all in says so and asks for the rest: export again once they are in (a large archive may take a few diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index af18d4ec72..3cd78aae2d 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -593,7 +593,9 @@ without it. A collection's items list each band as an asset whose `alternate.https` address is on the data server: add it with `layer.addUrl` (`"cog": true`, since the address ends in `$value`, and `"bbox"` -for a window) and it is read in place, as any COG. A plugin does the same and never sees the token. `copernicus.status` reports the sign-in (as whom, when the token +for a window) and it is read in place, as any COG. Each of CDSE's data servers is asked for at most +four parts at a time, the connections its quota gives a general account. A plugin does the same and +never sees the token. `copernicus.status` reports the sign-in (as whom, when the token expires, until when it is renewed); `copernicus.logout` forgets it and empties the download cache. The command is for the desktop app and the command line (a password typed in a command line stays in the shell's history); the web app signs in from the panel.