diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index ff15444680..43e5cda998 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1842,6 +1842,11 @@ pub fn read_bands_counted_blocking( if x1 <= x0 || y1 <= y0 { return Ok(outs); } + let window = Window { x: (x0, x1), y: (y0, y1), from: (cols.0, rows.0), w, nodata: info.layout.nodata.map(|v| v as f32) }; + if info.layout.strips { + read_strips(info, &url, level, bands, &window, &mut outs, wait, stop)?; + return Ok(outs); + } let (tw, th, across) = (l.tile_width.max(1), l.tile_height.max(1), l.across().max(1)); // The tiles the window takes, counted before they are listed, in checked arithmetic: a // hostile header can't make a long list or a wrapped index. @@ -1863,50 +1868,231 @@ pub fn read_bands_counted_blocking( format!("tiles not read in {} s", wait.as_secs()) }; let picked = wait_until(&rx, wait, stop).map_err(|stopped| stopped_or(stopped, &url, &late))??; - let nodata = info.layout.nodata.map(|v| v as f32); for (&t, p) in tiles.iter().zip(&picked) { - let (tx0, ty0) = ((t % across).saturating_mul(tw), (t / across).saturating_mul(th)); - for ((chunk, b), (out, rounded, overflowed)) in p.iter().zip(outs.iter_mut()) { - let Some(values) = chunk.get(*b) else { continue }; - for py in ty0.max(y0)..ty0.saturating_add(th).min(y1) { - for px in tx0.max(x0)..tx0.saturating_add(tw).min(x1) { - let i = (py - ty0) as usize * tw as usize + (px - tx0) as usize; - let Some(&v) = values.get(i) else { continue }; - // A marked value past `f32`'s range is infinite: left out as no value, and - // counted apart from those rounded. No-data isn't marked. - if chunk.rounded_at(*b, i) { - if v.is_infinite() { *overflowed += 1 } else { *rounded += 1 } - } - if v.is_finite() - && Some(v) != nodata - && let Some(slot) = out.get_mut((py - rows.0) as usize * w + (px - cols.0) as usize) - { - *slot = v; - } + let at = ((t % across).saturating_mul(tw), (t / across).saturating_mul(th), tw, th); + for ((chunk, b), out) in p.iter().zip(outs.iter_mut()) { + window.copy(chunk, *b, at, out); + } + } + Ok(outs) +} + +/// Where a read's values go: the window's part inside the file (columns `x`, rows `y` of the +/// level's grid), its first column and row (`from`), its width, and the value that means none. +#[cfg(not(target_arch = "wasm32"))] +struct Window { + x: (u32, u32), + y: (u32, u32), + from: (u32, u32), + w: usize, + nodata: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Window { + /// Copies band `b` of a decoded chunk into `out` (values, rounded, overflowed): the chunk is a + /// tile `tw × th` whose first cell is (`tx0`, `ty0`), and only its cells in the window go. + fn copy(&self, chunk: &cog::Tile, b: usize, (tx0, ty0, tw, th): (u32, u32, u32, u32), out: &mut (Vec, u64, u64)) { + let Some(values) = chunk.get(b) else { return }; + let (out, rounded, overflowed) = out; + for py in ty0.max(self.y.0)..ty0.saturating_add(th).min(self.y.1) { + for px in tx0.max(self.x.0)..tx0.saturating_add(tw).min(self.x.1) { + let i = (py - ty0) as usize * tw as usize + (px - tx0) as usize; + let Some(&v) = values.get(i) else { continue }; + // A marked value past `f32`'s range is infinite: left out as no value, and + // counted apart from those rounded. No-data isn't marked. + if chunk.rounded_at(b, i) { + if v.is_infinite() { *overflowed += 1 } else { *rounded += 1 } + } + if v.is_finite() + && Some(v) != self.nodata + && let Some(slot) = out.get_mut((py - self.from.1) as usize * self.w + (px - self.from.0) as usize) + { + *slot = v; + } + } + } + } +} + +/// The most bytes one request of a window of a file in strips asks for (#2592): strips that +/// follow one another in the file are read together up to this (a strip larger is read alone). +#[cfg(not(target_arch = "wasm32"))] +const STRIP_RUN_BYTES: u64 = 4 << 20; + +/// The requests of a window of a file in strips under way at once. +#[cfg(not(target_arch = "wasm32"))] +const STRIP_RUNS_AT_ONCE: usize = 8; + +/// The chunks of `chunks` (in the order of the file's index) split into runs whose bytes follow +/// one another in the file, of at most `max` bytes each unless a chunk alone is larger: each run +/// (a range of places in `chunks`) is one request. A chunk without bytes is in no run (no data). +#[cfg(not(target_arch = "wasm32"))] +fn strip_runs(l: &Level, chunks: &[u32], max: u64) -> Vec> { + let place = |c: u32| Some((*l.offsets.get(c as usize)?, *l.counts.get(c as usize)?)); + let mut runs: Vec> = Vec::new(); + let mut end = None::<(u64, u64)>; + for (k, &c) in chunks.iter().enumerate() { + let Some((at, len)) = place(c).filter(|p| p.1 > 0) else { continue }; + match (runs.last_mut(), end) { + (Some(run), Some((first, next))) if run.end == k && next == at && at.saturating_add(len) - first <= max => { + run.end = k + 1; + end = Some((first, at.saturating_add(len))); + } + _ => { + runs.push(k..k + 1); + end = Some((at, at.saturating_add(len))); + } + } + } + runs +} + +/// [`read_bands_counted_blocking`] for a file in strips (#2592): the window's strips that follow +/// one another in the file are read in requests of up to [`STRIP_RUN_BYTES`], +/// [`STRIP_RUNS_AT_ONCE`] under way at once, and each strip, decoded, is copied out to the +/// window's columns. The strips aren't kept in the tile cache: no map tile draws them. The +/// [`MAX_VALUE_TILES`] bound counts the requests, not the strips. +#[cfg(not(target_arch = "wasm32"))] +fn read_strips( + info: &Arc, + url: &str, + level: usize, + bands: &[usize], + window: &Window, + outs: &mut [(Vec, u64, u64)], + wait: Duration, + stop: &std::sync::atomic::AtomicBool, +) -> Result<(), String> { + let l = info.layout.levels.get(level).ok_or("no such overview")?; + let th = l.tile_height.max(1); + // Each chunk the window takes, with the bands it holds: (place in `outs`, place in the chunk). + let mut wanted: BTreeMap> = BTreeMap::new(); + for strip in window.y.0 / th..=(window.y.1 - 1) / th { + for (i, &b) in bands.iter().enumerate() { + let (c, at) = info.layout.chunk(l, strip, b).ok_or_else(|| format!("no band {} in strip {strip}", b + 1))?; + wanted.entry(c).or_default().push((i, at)); + } + } + let chunks: Vec = wanted.keys().copied().collect(); + let runs = strip_runs(l, &chunks, STRIP_RUN_BYTES); + if runs.len() > MAX_VALUE_TILES { + return Err(format!("{} reads of the file's strips for one read; at most {MAX_VALUE_TILES}: take a smaller area", runs.len())); + } + let ceiling = info.reach.min(crate::cache::ceiling_for(url)); + let end = Instant::now() + wait; + let late = format!("strips not read in {} s", wait.as_secs()); + let (tx, rx) = std::sync::mpsc::channel::<(usize, Result, String>)>(); + // A run's chunks, and where its bytes start and end in the file (`strip_runs` saw them all). + let place = |c: u32| (l.offsets.get(c as usize).copied().unwrap_or(0), l.counts.get(c as usize).copied().unwrap_or(0)); + let span = |k: usize| { + let run = runs.get(k).and_then(|r| chunks.get(r.clone())).unwrap_or_default(); + let (first, last) = (place(run.first().copied().unwrap_or(0)).0, run.last().map_or(0, |&c| place(c).0.saturating_add(place(c).1))); + (run, first, last) + }; + let (mut next, mut again, mut in_flight, mut dropped) = (0, Vec::new(), 0, 0); + loop { + while in_flight < STRIP_RUNS_AT_ONCE { + let k = match again.pop() { + Some(k) => k, + None if next < runs.len() => { + next += 1; + next - 1 + } + None => break, + }; + if stop.load(std::sync::atomic::Ordering::Relaxed) { + return Err(message_with_address(url, STOPPED)); + } + crate::cache::check_still(&crate::cache::current_still())?; + crate::logins::check(url).map_err(str::to_string)?; + if ceiling > crate::cache::ceiling_for(url) { + return Err(REACH_CHANGED.into()); + } + let (run, at, until) = span(k); + // Bytes at offset 0 would be the file's header: a broken index, said. + if at == 0 { + return Err(format!("strip {} of level {level} has bytes but no offset", run.first().copied().unwrap_or(0))); + } + let tx = tx.clone(); + read(url, at, until - at, ceiling, Box::new(move |r| tx.send((k, r)).unwrap_or_default())); + in_flight += 1; + } + if in_flight == 0 { + return Ok(()); + } + let left = end.saturating_duration_since(Instant::now()); + let (k, r) = wait_until(&rx, left, stop).map_err(|stopped| stopped_or(stopped, url, &late))?; + in_flight -= 1; + // The address may reach less than when its strips were asked for: not used (#2592). + if ceiling > crate::cache::ceiling_for(url) { + return Err(REACH_CHANGED.into()); + } + let bytes = match r { + // Dropped by the fetch queue (other reads filled it): asked for again, a delay, until + // the drops pass `drops_allowed`. + Err(e) if e == crate::cache::DROPPED => { + dropped += 1; + if dropped > drops_allowed(runs.len()) { + return Err(format!("the fetch queue dropped its strips {dropped} times (other reads filled it): busy")); + } + again.push(k); + continue; + } + Err(e) => return Err(e), + Ok(b) => b, + }; + let (run, start, _) = span(k); + for &c in run { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + return Err(message_with_address(url, STOPPED)); + } + let (at, len) = place(c); + let at = (at - start) as usize; + let own = bytes.get(at..at.saturating_add(len as usize)).ok_or_else(|| format!("strip {c} of level {level} cut short"))?; + let tile = cog::decode_tile_counted(&info.header, &info.layout, level, c, own.to_vec()).map_err(|e| e.to_string())?; + let strip = c % l.tiles().max(1); + for &(i, b) in wanted.get(&c).into_iter().flatten() { + if let Some(out) = outs.get_mut(i) { + window.copy(&tile, b, (0, strip.saturating_mul(th), l.tile_width.max(1), th), out); } } } } - Ok(outs) } #[cfg(test)] mod tests { - /// A window of a GeoTIFF in strips (#2592) is read by range, a strip a tile, only its rows' - /// strips; the map doesn't draw the file in place (it is read whole for that, as before). + /// Serves `file` by range to the reads of this test, counting the bytes and requests served; + /// the first `drops` requests from `from` on are dropped by the fetch queue. #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_window_of_a_geotiff_in_strips_reads_its_rows_by_range() { - let _turn = crate::cache::turn(); - let file = Arc::new(cog::example_strips(300, 200, 2)); - let (bytes, served) = (Arc::new(std::sync::atomic::AtomicU64::new(0)), file.clone()); - let counted = bytes.clone(); + fn serve_strips(file: Arc>, from: Arc, drops: u64) -> (Arc, Arc) { + let (bytes, asked) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0))); + let (counted, requests, dropped) = (bytes.clone(), asked.clone(), AtomicU64::new(0)); crate::cache::set_fetcher(move |url, done| { let (a, b) = crate::cache::split_range(&url).1.unwrap(); - let range = served.get(a as usize..((b + 1) as usize).min(served.len())).unwrap_or_default().to_vec(); - counted.fetch_add(range.len() as u64, std::sync::atomic::Ordering::SeqCst); + requests.fetch_add(1, Ordering::SeqCst); + if a >= from.load(Ordering::SeqCst) && dropped.fetch_add(1, Ordering::SeqCst) < drops { + done(Err(crate::cache::DROPPED.into())); + return; + } + let range = file.get(a as usize..((b + 1) as usize).min(file.len())).unwrap_or_default().to_vec(); + counted.fetch_add(range.len() as u64, Ordering::SeqCst); done(Ok(range)); }); + (bytes, asked) + } + + /// A window of a GeoTIFF in strips (#2592) is read by range, only its rows' strips, those that + /// follow one another in one request; the map doesn't draw the file in place (it is read whole + /// for that, as before). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_window_of_a_geotiff_in_strips_reads_its_rows_by_range() { + let _turn = crate::cache::turn(); + let file = Arc::new(cog::example_strips(300, 200, 2)); + let from = Arc::new(AtomicU64::new(u64::MAX)); + let (bytes, asked) = serve_strips(file.clone(), from, 0); let url = "https://strips-cog.invalid/scene.tif"; let never = std::sync::atomic::AtomicBool::new(false); let e = super::info_until(url, &never).err().unwrap_or_default(); @@ -1915,7 +2101,7 @@ mod tests { let info = super::window_info_until(url, &never).unwrap(); assert!(info.layout.strips && info.layout.levels[0].tiles() == 100, "a strip a tile"); assert!(super::info(url).is_err_and(|e| e.contains(NOT_COG)) && super::info_landed(url).is_none(), "not drawn in place"); - let header = bytes.load(std::sync::atomic::Ordering::SeqCst); + let (header, headers) = (bytes.load(Ordering::SeqCst), asked.load(Ordering::SeqCst)); // Columns 40–89 and rows 51–100: the 26 strips of rows 50–101. let values = super::read_values_blocking(&info, url, 0, 0, (40, 90), (51, 101)).unwrap(); assert_eq!(values.len(), 50 * 50); @@ -1925,12 +2111,93 @@ mod tests { } let full = &info.layout.levels[0]; let strips: u64 = full.counts[25..51].iter().sum(); - assert_eq!(bytes.load(std::sync::atomic::Ordering::SeqCst) - header, strips, "only the window's strips are read"); + assert_eq!(bytes.load(Ordering::SeqCst) - header, strips, "only the window's strips are read"); + assert_eq!(asked.load(Ordering::SeqCst) - headers, 1, "in one request"); assert!(strips < file.len() as u64 / 3); crate::cache::clear_fetcher(); super::forget_file(url); } + /// A window of more strips than the tiles one read takes ([`super::MAX_VALUE_TILES`]) is read + /// in a few requests, one the fetch queue dropped asked for again; strips that don't follow + /// one another, or past [`super::STRIP_RUN_BYTES`], are runs of their own, and empty ones + /// none. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_strips_of_a_window_are_read_in_a_few_requests() { + let _turn = crate::cache::turn(); + let file = Arc::new(cog::example_strips(4, 5000, 1)); + let from = Arc::new(AtomicU64::new(u64::MAX)); + let (_, asked) = serve_strips(file, from.clone(), 1); + let url = "https://strips-cog.invalid/rows.tif"; + let info = super::window_info_until(url, &std::sync::atomic::AtomicBool::new(false)).unwrap(); + let l = &info.layout.levels[0]; + assert_eq!(l.tiles(), 5000); + from.store(l.offsets[0], Ordering::SeqCst); + let headers = asked.load(Ordering::SeqCst); + let values = super::read_values_blocking(&info, url, 0, 0, (1, 3), (0, 5000)).unwrap(); + for (i, v) in values.iter().enumerate() { + let (x, y) = (1 + i as i32 % 2, i as i32 / 2); + assert_eq!(*v, (7 * x - 3 * y) as f32, "cell ({x}, {y})"); + } + assert_eq!(asked.load(Ordering::SeqCst) - headers, 2, "one request, dropped once and asked again"); + crate::cache::clear_fetcher(); + super::forget_file(url); + // Strips 0–1 follow one another, 2 is empty, 3 lies apart, 4–6 pass 12 bytes together. + let mut l = l.clone(); + (l.offsets, l.counts) = (vec![100, 104, 0, 200, 300, 306, 312], vec![4, 4, 0, 6, 6, 6, 6]); + assert_eq!(super::strip_runs(&l, &[0, 1, 2, 3, 4, 5, 6], 12), vec![0..2, 3..4, 4..6, 6..7]); + assert_eq!(super::strip_runs(&l, &[3], 2), vec![0..1], "a strip larger than a run is read alone"); + } + + /// A read of strips stopped before it starts asks for none, and one whose address may reach + /// less once its strips are under way fails with [`super::REACH_CHANGED`], as a tile does. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_read_of_strips_stops_and_keeps_to_its_reach() { + let _turn = crate::cache::turn(); + let file = Arc::new(cog::example_strips(300, 200, 2)); + let held = Arc::new(Mutex::new(Vec::<(String, Done)>::new())); + let (hold, (asked, came)) = (held.clone(), std::sync::mpsc::channel()); + crate::cache::set_fetcher(move |url, done| { + hold.lock().unwrap().push((url, done)); + asked.send(()).unwrap_or_default(); + }); + let drain = || { + let pending = std::mem::take(&mut *held.lock().unwrap()); + for (url, done) in pending { + let (a, b) = crate::cache::split_range(&url).1.unwrap(); + done(Ok(file[a as usize..((b + 1) as usize).min(file.len())].to_vec())); + } + }; + let url = "https://strips-reach.example/scene.tif"; + let (tx, rx) = std::sync::mpsc::channel(); + with_any_info(url, Box::new(move |r| tx.send(r).unwrap())); + let info = loop { + drain(); + if let Ok(r) = rx.try_recv() { + break r.unwrap(); + } + }; + let stop = std::sync::atomic::AtomicBool::new(true); + let e = super::read_values_counted_blocking(&info, url, 0, 0, (0, 300), (0, 200), &stop).unwrap_err(); + assert!(e.contains(STOPPED), "{e}"); + assert!(held.lock().unwrap().is_empty(), "no strip asked for"); + while came.try_recv().is_ok() {} + let reader = std::thread::Builder::new().spawn({ + let info = info.clone(); + move || super::read_values_blocking(&info, url, 0, 0, (0, 300), (0, 200)) + }); + let reader = reader.unwrap(); + // The strips asked for, the address is restricted before they land. + came.recv().unwrap(); + crate::cache::restrict_to_public(url); + drain(); + assert_eq!(reader.join().unwrap().err().as_deref(), Some(super::REACH_CHANGED)); + crate::cache::clear_fetcher(); + forget_file(url); + } + /// Two callers share cached bytes, but a joining callback never borrows the loader's /// lifetime. Both metadata-to-overview and tile-to-next-tile run the real range reader; /// a retired loader also leaves no successful header or raw tile for later callers.