diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 18450d6ac7..2bdbc34061 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -458,7 +458,9 @@ pub(crate) fn stored_counting(v: f64, past: &std::sync::atomic::AtomicUsize) -> } } -/// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). +/// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). Discards how +/// many cells were stored as no-data past the f32 range: a caller that reports losses uses +/// [`band_math_reported`]. pub fn band_math(r: &Raster, expr: &str) -> Result, String> { band_math_reported(r, expr).map(|(cells, _)| cells) } diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6a022dce0e..1bccb4b9f2 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2295,13 +2295,26 @@ fn grid_labels(root: &Node, env: [&str; 2], north_first: bool) -> Option<(String /// doesn't say its system is read in it. `None` for longitude/latitude, a system RustGIS doesn't /// read, and any other address. pub fn coverage_request_system(url: &str) -> Option { + let decoded = |v: &str| v.replace("%3A", ":").replace("%3a", ":").replace("%2F", "/").replace("%2f", "/"); + let named = coverage_request_named(url).map(decoded)?; + projected_system(&named).map(|(_, crs)| crs) +} + +/// The system a WCS GetCoverage address names, as written: WCS 2.0's `OUTPUTCRS`, WCS 1.0's +/// `RESPONSE_CRS`, else its `CRS`. `None` for an address naming none, and any other address. +fn coverage_request_named(url: &str) -> Option<&str> { let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); if !(is("service", "wcs") && is("request", "getcoverage")) { return None; } - let decoded = |v: &str| v.replace("%3A", ":").replace("%3a", ":").replace("%2F", "/").replace("%2f", "/"); - let named = ["outputcrs", "response_crs", "crs"].iter().find_map(|k| query_value(url, k)).map(decoded)?; - projected_system(&named).map(|(_, crs)| crs) + // An empty value names nothing. + ["outputcrs", "response_crs", "crs"].iter().find_map(|k| query_value(url, k).filter(|v| !v.trim().is_empty())) +} + +/// Whether a WCS GetCoverage address names the system it asks its coverage in at all (as +/// [`coverage_request_system`] reads it), whichever system that is. +pub fn coverage_request_names_system(url: &str) -> bool { + coverage_request_named(url).is_some() } /// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one @@ -2514,14 +2527,17 @@ pub struct RecordPage { /// Characters of a search's words a catalogue is asked for. pub const MAX_SEARCH_WORDS: usize = 200; -/// A search's words as a catalogue is asked for them, and how many characters were left out: those -/// XML can't hold (control characters), and those past [`MAX_SEARCH_WORDS`]. +/// A search's words as a catalogue is asked for them, and how many characters were left out: +/// other control characters and U+FFFE/U+FFFF, which XML can't hold, and those past +/// [`MAX_SEARCH_WORDS`]. A tab or line break (any control character that is white space) is a +/// space between words, not left out, so the words on either side stay apart. pub fn search_words(words: &str) -> (String, usize, usize) { let words = words.trim(); - let kept: Vec = words.chars().filter(|c| !c.is_control() && !matches!(c, '\u{FFFE}' | '\u{FFFF}')).collect(); - let unwritable = words.chars().count() - kept.len(); + let spaced = words.chars().map(|c| if c.is_control() && c.is_whitespace() { ' ' } else { c }); + let kept: Vec = spaced.filter(|c| !c.is_control() && !matches!(c, '\u{FFFE}' | '\u{FFFF}')).collect(); + let left_out = words.chars().count() - kept.len(); let text: String = kept.iter().take(MAX_SEARCH_WORDS).collect(); - (text.trim().to_string(), unwritable, kept.len().saturating_sub(MAX_SEARCH_WORDS)) + (text.trim().to_string(), left_out, kept.len().saturating_sub(MAX_SEARCH_WORDS)) } /// The GetRecords request (CSW 2.0.2, Dublin Core records) of a search: words anywhere in the @@ -3679,8 +3695,12 @@ pub(crate) fn arcgis_error_text(v: &serde_json::Value) -> Option { Some(format!("service error: {code}: {message}")) } +/// What [`page_error_detail`] says of a cause it can't show: a constant, so no address leaks. +const HIDDEN_CAUSE: &str = " (its cause isn't shown, as it holds the address)"; + /// An optional detail for a page notice. URL paths can hold keys. When an error contains -/// an address, repeat only a parsed status or a fixed reason from the fetcher. +/// an address, repeat only a parsed status or a fixed reason from the fetcher; another cause is +/// said to exist ([`HIDDEN_CAUSE`]) but not shown. fn page_error_detail(error: &str) -> String { use crate::diagnostics::fetch_reason::*; if error.contains("://") { @@ -3698,7 +3718,8 @@ fn page_error_detail(error: &str) -> String { .find_map(|(reason, separator)| tail.strip_prefix(reason)?.starts_with(separator).then_some(reason)) }) }); - return reason.map_or_else(String::new, |reason| format!(" ({reason})")); + // A cause that matches none holds the address, so it isn't shown; that one exists is. + return reason.map_or_else(|| HIDDEN_CAUSE.to_string(), |reason| format!(" ({reason})")); } let mut error = crate::diagnostics::redact(error); crate::diagnostics::cut_with_ellipsis(&mut error, MAX_REASON); @@ -4477,7 +4498,12 @@ impl Pages { // Bound the XML tree while the original feature rows are still held. let Some(schema) = std::str::from_utf8(&bytes) .ok() - .and_then(|text| crate::xml::parse(text, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok()) + // A byte order mark and leading space set aside, as the other XML readers do; + // DTDs still refused. + .and_then(|text| { + let text = text.trim_start_matches('\u{feff}').trim_start(); + crate::xml::parse(text, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok() + }) else { return self.stop("the feature description couldn't be parsed or is too large; the rest aren't read".into()); }; @@ -4811,7 +4837,7 @@ impl Pages { let report = page.report; match &mut self.decoded { None => { - self.placed_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url).is_some()); + self.placed_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url)); self.decoded = Some((page.dataset, report, page.losses)); } Some((ds, joined, losses)) => { @@ -4824,7 +4850,7 @@ impl Pages { // system (`placed_as`), or their positions would be taken for another's. A page // without positions says nothing, and until a page has some, the joined pages take // the system of the next. - let page_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url).is_some()); + let page_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url)); let other_crs = matches!((&self.placed_as, &page_as), (Some(joined), Some(this)) if joined != this); let none = crate::GeometryType::None; let other_type = @@ -4972,10 +4998,11 @@ impl Pages { // In degrees as each page joined was judged (`placed_as`), not by the pages' extent // together: pages in degrees in different axis orders stay in degrees. let degrees = self.placed_as.is_some_and(|p| p.degrees); - // Only when no page named one: a system a page named is kept. + // Only when no page named one, or those that did named the system asked for: a + // system a page named is kept. if (losses.no_crs || losses.unread_code) - && ds.crs.is_none() && let Some(asked) = asked_system(&self.url) + && ds.crs.is_none_or(|c| c == asked) && !degrees { ds.held_in = asked; @@ -5410,8 +5437,9 @@ fn inside(extent: [f64; 4], b: [f64; 4]) -> bool { extent[0] >= b[0] && extent[1] >= b[1] && extent[2] <= b[2] && extent[3] <= b[3] } -/// What a page with positions says of its system: the one it names (`None`: none, or one by a -/// code RustGIS can't use, both read in the system asked for when it is projected), and, naming +/// What a page with positions says of its system: the one it names (`None`: none, one by a code +/// RustGIS can't use, or the projected system asked for itself, all read in the system asked for, +/// which is why such pages join), and, naming /// none, whether its positions are in degrees (when a projected system was asked for). `None` for /// a page without positions. #[derive(Clone, Copy, Debug, PartialEq)] @@ -5422,10 +5450,11 @@ struct PlacedAs { turned: bool, } -fn placed_as(ds: &crate::Dataset, losses: &crate::esripbf::Losses, projected_asked: bool) -> Option { +fn placed_as(ds: &crate::Dataset, losses: &crate::esripbf::Losses, asked: Option) -> Option { if !ds.features.iter().any(|f| f.geometry.is_some()) { return None; } + let projected_asked = asked.is_some(); // Only where a projected system was asked for does it matter whether positions naming none // are in degrees: otherwise they are read as longitude/latitude, as one naming WGS 84 is, so // those pages join, as on main; one naming another system doesn't. @@ -5439,6 +5468,11 @@ fn placed_as(ds: &crate::Dataset, losses: &crate::esripbf::Losses, projected_ask let turned = !e.is_empty() && !as_is && in_degrees([e.min_y, e.min_x, e.max_y, e.max_x]); return Some(PlacedAs { named: None, degrees: as_is || turned, turned }); } + // Naming the system asked for: read in it, as a page naming none and not in degrees is, so + // the two join. + if ds.crs.is_some() && ds.crs == asked { + return Some(PlacedAs { named: None, degrees: false, turned: false }); + } Some(PlacedAs { named: Some(ds.crs.unwrap_or(crate::raster::Crs::LonLat)), degrees: false, turned: false }) } @@ -5560,6 +5594,9 @@ pub enum Assumed { /// It named no system, and its positions are in degrees though a projected system was asked /// for (a server that didn't convert): read in longitude/latitude. DegreesUnnamed, + /// Its positions are north first, but turning them round would take more memory than a read + /// may ([`turn_limit`]): read as they came. + TooLargeToTurn, } impl Assumed { @@ -5569,7 +5606,9 @@ impl Assumed { pub fn loss(self) -> Option { match self { Assumed::Unnamed | Assumed::NotDegrees => None, - Assumed::Unread | Assumed::InDegrees | Assumed::InAsked | Assumed::DegreesUnnamed => Some(crate::loss::LossCode::AssumedCrs), + Assumed::Unread | Assumed::InDegrees | Assumed::InAsked | Assumed::DegreesUnnamed | Assumed::TooLargeToTurn => { + Some(crate::loss::LossCode::AssumedCrs) + } } } @@ -5594,10 +5633,27 @@ impl Assumed { Assumed::DegreesUnnamed => { "{n} service answer(s) named no coordinate system, and their positions are in degrees though another system was asked for: read in longitude/latitude" } + Assumed::TooLargeToTurn => { + "{n} service answer(s) were too large to turn their positions round (north first), so they are read as they came and may draw out of place: filter the layer or ask a smaller area" + } } } } +/// The least memory [`turn_limit`] allows, and its limit in the browser. +const TURN_FLOOR: usize = 512 << 20; +/// The most memory [`turn_limit`] allows, however much the computer has. +const TURN_CEILING: usize = 3 << 30; +/// What turning an answer's positions round takes, a multiple of its bytes ([`rewritten`]). +const TURN_COST: usize = 16; + +/// Most memory, in bytes, turning an answer's positions round may take: on the desktop a quarter +/// of the computer's memory, from [`TURN_FLOOR`] up to [`TURN_CEILING`]; less once RustGIS holds +/// more than half of it ([`crate::memory::planned`], #2431). +fn turn_limit() -> usize { + crate::memory::planned(TURN_FLOOR, TURN_CEILING, 1) +} + /// A service's GeoJSON answer to `url` made ready to read: in the projected system `url` asks it /// in ([`asked_system`]), with a `crs` member naming that system (as a server may leave it out, /// or name it by a code RustGIS doesn't read) and its positions east first; else as @@ -5610,7 +5666,8 @@ impl Assumed { /// naming another system RustGIS reads is read in it; with no bounds, or positions that fit none /// of them, it is read as it names itself, else as asked. /// -/// What it assumed is given back to be said: a system named that RustGIS doesn't read, or none +/// What it assumed is given back to be said (second), and positions it left unturned for their +/// size (third, [`Assumed::TooLargeToTurn`]): a system named that RustGIS doesn't read, or none /// where the positions can't be checked, read as asked; a system named against what the positions /// show. Positions turned round because the layer's bounds show them north first aren't said: /// the bounds decide it, as they do for [`fix_axes`]. @@ -5621,8 +5678,52 @@ impl Assumed { /// The common case, an answer in the system asked for that names it or none, takes no copy: a /// member is added at its end, in place. Turning positions round, or replacing a member, reads /// the whole answer, as [`fix_axes`] does. -pub fn place_answer(bytes: Vec, url: &str, bounds: Option<[f64; 4]>) -> (Vec, Option) { - let Some(crs) = asked_system(url) else { return (fix_axes(&bytes, bounds).unwrap_or(bytes), None) }; +pub fn place_answer(bytes: Vec, url: &str, bounds: Option<[f64; 4]>) -> (Vec, Option, Option) { + place_answer_within(bytes, url, bounds, turn_limit()) +} + +/// [`place_answer`] turning positions round only within `limit` bytes of memory ([`TURN_COST`] +/// times the answer): past it they are read as they came, and [`Assumed::TooLargeToTurn`] comes +/// back third, beside anything else it assumed, both to be said. +fn place_answer_within(bytes: Vec, url: &str, bounds: Option<[f64; 4]>, limit: usize) -> (Vec, Option, Option) { + let too_large = bytes.len().saturating_mul(TURN_COST) > limit; + let Some(crs) = asked_system(url) else { + if too_large && latitude_first(positions_extent(&bytes), bounds) { + return (bytes, None, Some(Assumed::TooLargeToTurn)); + } + return (fix_axes(&bytes, bounds).unwrap_or(bytes), None, None); + }; + place_within(bytes, crs, bounds, too_large) +} + +/// [`place_answer`] for an answer asked in `crs`; `too_large` to turn its positions round. +fn place_within( + bytes: Vec, + crs: crate::raster::Crs, + bounds: Option<[f64; 4]>, + too_large: bool, +) -> (Vec, Option, Option) { + // Set when positions that should be turned round are left as they came. + let unturned = std::cell::Cell::new(false); + let turned = |turn: bool| { + if turn && too_large { + unturned.set(true); + false + } else { + turn + } + }; + let (bytes, assumed) = place_turned(bytes, crs, bounds, &turned); + (bytes, assumed, unturned.get().then_some(Assumed::TooLargeToTurn)) +} + +/// [`place_within`]: `turned` says whether positions that should be turned round are. +fn place_turned( + bytes: Vec, + crs: crate::raster::Crs, + bounds: Option<[f64; 4]>, + turned: &dyn Fn(bool) -> bool, +) -> (Vec, Option) { let Some((extent, top)) = scan_answer(&bytes) else { return (bytes, None) }; let named = named(top.crs.as_ref(), crs); // Named in another system RustGIS reads: read in it, unless its positions are in degrees @@ -5632,13 +5733,14 @@ pub fn place_answer(bytes: Vec, url: &str, bounds: Option<[f64; 4]>) -> (Vec // system asked for is put in one (`rewritten`). // (An object with no `type` isn't GeoJSON: named in place as before, for the reader to refuse.) let collection = top.kind.as_deref().is_none_or(|k| k == "FeatureCollection"); - let as_asked = |bytes: Vec, turn: bool| rewritten(&bytes, Some(crs_member(crs)), turn).unwrap_or(bytes); + let as_asked = |bytes: Vec, turn: bool| rewritten(&bytes, Some(crs_member(crs)), turned(turn)).unwrap_or(bytes); // Turned round when latitude first: as `fix_axes` judges it, from the extent read already, or // when only that order lies within degrees' range. let lonlat = |bytes: Vec, drop_member: bool| { let only_turned = extent.is_some_and(|[x0, y0, x1, y1]| !in_degrees([x0, y0, x1, y1]) && in_degrees([y0, x0, y1, x1])); // Turned by the bounds only into degrees' range. - let turn = only_turned || (latitude_first(extent, bounds) && extent.is_some_and(|[x0, y0, x1, y1]| in_degrees([y0, x0, y1, x1]))); + let turn = + turned(only_turned || (latitude_first(extent, bounds) && extent.is_some_and(|[x0, y0, x1, y1]| in_degrees([y0, x0, y1, x1])))); if turn || drop_member { rewritten(&bytes, None, turn).unwrap_or(bytes) } else { bytes } }; match (at, named) { @@ -6420,6 +6522,39 @@ mod tests { assert!(fix_axes(deep.as_bytes(), hamburg).is_none()); } + /// Positions north first are turned round only within the memory a read may take: past it, + /// the answer is read as it came and that is said; under it, turned and nothing said. + #[test] + fn an_answer_too_large_to_turn_is_read_as_it_came_and_said() { + let wfs = "https://x.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=a&OUTPUTFORMAT=application%2Fjson&SRSNAME=EPSG:2056&COUNT=50000"; + let bern = Some([7.3, 46.9, 7.5, 47.0]); + let north_first = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1200000,2600000]}}]}"#; + let first = |bytes: &[u8]| { + let v: serde_json::Value = serde_json::from_slice(bytes).unwrap(); + v["features"][0]["geometry"]["coordinates"][0].as_f64().unwrap() + }; + let (turned, _, said) = place_answer_within(north_first.as_bytes().to_vec(), wfs, bern, usize::MAX); + assert_eq!((first(&turned), said), (2_600_000.0, None)); + let (kept, _, said) = place_answer_within(north_first.as_bytes().to_vec(), wfs, bern, 1); + assert_eq!((first(&kept), said), (1_200_000.0, Some(Assumed::TooLargeToTurn))); + // Another assumption is kept beside it: a system named that RustGIS doesn't read. + let unread = north_first.replace( + r#""type":"FeatureCollection","#, + r#""type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:999999"}},"#, + ); + let (_, other, said) = place_answer_within(unread.into_bytes(), wfs, bern, 1); + assert_eq!((other, said), (Some(Assumed::Unread), Some(Assumed::TooLargeToTurn))); + assert_eq!(Assumed::TooLargeToTurn.loss(), Some(crate::loss::LossCode::AssumedCrs)); + // Not asked in a projected system: latitude first by the bounds, as `fix_axes` judges it. + let lonlat = wfs.replace("EPSG:2056", "EPSG:4326"); + let hamburg = Some([9.7, 53.4, 10.3, 53.7]); + let lat_first = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[53.55,9.99]}}]}"#; + let (turned, _, said) = place_answer_within(lat_first.as_bytes().to_vec(), &lonlat, hamburg, usize::MAX); + assert_eq!((first(&turned), said), (9.99, None)); + let (kept, _, said) = place_answer_within(lat_first.as_bytes().to_vec(), &lonlat, hamburg, 1); + assert_eq!((kept.as_slice(), said), (lat_first.as_bytes(), Some(Assumed::TooLargeToTurn))); + } + /// A WFS or ArcGIS answer asked in a projected system is read in it (#2032): named when it /// isn't, turned round when written north first, and read as longitude/latitude when the /// server answered in it anyway; an answer naming another system is left to it. Judged @@ -6679,6 +6814,46 @@ mod tests { } }; assert_eq!((ds.features.len(), ds.coord_crs()), (2, lv95)); + // A page naming the system asked for and one naming none, both in it, either way round: + // joined in it, and the one naming none isn't said to be read as longitude/latitude. + let asked_or_none = |id: u64, named: bool, more: bool| { + let mut parts = vec![number(7, 0)]; + if named { + parts.push(message(8, &number(1, 2056))); + } + parts.extend([transform(false, 1.0, 0.0, 0.0), field("OBJECTID", 6)]); + if more { + parts.push(number(9, 1)); + } + parts.push(feature(&[uint(id), geometry(&[], &[2_600_000, 1_200_000])])); + answer(&parts) + }; + for first_named in [false, true] { + let mut step = begin_with_pbf(query, 100); + let (ds, report, note) = loop { + match step { + Step::Fetch(pages) => { + let url = pages.next_url().to_string(); + let a = if !url.contains("/query") { + paged.to_vec() + } else if url.contains("resultOffset=1") { + asked_or_none(2, !first_named, false) + } else { + asked_or_none(1, first_named, true) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, note) => break (*ds, report, note), + other => panic!("{other:?}"), + } + }; + assert_eq!((ds.features.len(), ds.coord_crs(), ds.crs), (2, lv95, Some(lv95)), "first named: {first_named}: {note:?}"); + assert!(note.as_deref().is_none_or(|n| !n.contains("another coordinate system")), "{note:?}"); + assert!(!report.messages.iter().any(|m| m.contains("longitude/latitude")), "{:?}", report.messages); + for f in ds.features.iter() { + assert_eq!(f.geometry, Some(crate::Geometry::Point(crate::Coord::new(2_600_000.0, 1_200_000.0)))); + } + } // Two pages with positions: one naming WGS 84, one LV03; and two naming none, one in // degrees, one not. Each pair stops after its first page, as read alone. let page_at = |id: u64, code: Option, x: i64, y: i64, more: bool| { @@ -6886,6 +7061,33 @@ mod tests { "#; + /// A feature description with space or a byte order mark before its root is read as one + /// without: the retry in sort order still runs. + #[test] + fn a_wfs_schema_with_leading_space_still_sorts_the_retry() { + let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads&COUNT=50000"; + let first = br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":"9"}},{"id":"roads.tmp-2","properties":{"record_number":"2"}}]}"#; + for lead in ["\n ", "\u{feff}", "\u{feff}\n "] { + let spaced = [lead.as_bytes(), WFS_SORT_SCHEMA].concat(); + let sorted_first = br#"{"features":[{"id":"roads.tmp-1","properties":{"record_number":1}},{"id":"roads.tmp-2","properties":{"record_number":2}}]}"#; + let sorted_next = br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":3}}]}"#; + let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { + match (query_value(next, "REQUEST"), query_value(next, "STARTINDEX"), query_value(next, "SORTBY")) { + (Some("DescribeFeatureType"), None, None) => Ok(spaced.clone()), + (_, None, None) => Ok(br#""#.to_vec()), + (_, Some("2"), None) => Err("http status: 400".into()), + (_, Some("0"), Some("record_number")) => Ok(sorted_first.to_vec()), + (_, Some("2"), Some("record_number")) => Ok(sorted_next.to_vec()), + _ => panic!("unexpected request: {next}"), + } + }); + let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let ids: Vec<_> = doc["features"].as_array().unwrap().iter().map(|f| f["id"].as_str().unwrap()).collect(); + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{lead:?}: {note:?}"); + assert_eq!(note, None); + } + } + /// A server without a natural order needs the same explicit sort from offset zero onward. #[test] fn wfs_restarts_rejected_offset_pages_in_schema_order() { @@ -6975,7 +7177,11 @@ mod tests { ), "the first sorted page had a missing or unusable sort value", ), - (None, Err("cannot read https://wfs.example.org/private-path"), "the first sorted page couldn't be read;"), + ( + None, + Err("cannot read https://wfs.example.org/private-path"), + "the first sorted page couldn't be read (its cause isn't shown, as it holds the address);", + ), ] { let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { match (query_value(next, "REQUEST"), query_value(next, "STARTINDEX"), query_value(next, "SORTBY")) { @@ -7146,7 +7352,7 @@ mod tests { ("http status: 500", " (http status: 500)"), ("http status: 500: https://wfs.example.org/private-path", " (HTTP 500)"), ("the request timed out", " (the request timed out)"), - ("cannot read https://wfs.example.org/private-path", ""), + ("cannot read https://wfs.example.org/private-path", HIDDEN_CAUSE), ("https://wfs.example.org/private-path: that address is never fetched", " (that address is never fetched)"), ] { let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { @@ -7185,7 +7391,10 @@ mod tests { assert_eq!(page_error_detail(&error), format!(" ({reason})"), "{text}"); assert_eq!(page_error_detail(&format!("untrusted prefix {error}")), format!(" ({reason})")); } - assert_eq!(page_error_detail("https://example.invalid/private-path: other text"), ""); + // A cause that holds the address: that there is one is said, never the address. + let hidden = page_error_detail("https://example.invalid/private-path: other text"); + assert_eq!(hidden, HIDDEN_CAUSE); + assert!(!hidden.contains("example.invalid") && !hidden.contains("private-path"), "{hidden}"); } /// The caller's sort stays in the feature requests, and hits never add an inferred sort. @@ -9942,7 +10151,10 @@ mod tests { assert_eq!(literal(r"100%_a\b"), r"%100\%\_a\\b%"); assert_eq!(literal("a\u{7}b\u{FFFF}c"), "%abc%"); assert_eq!(literal(&"é".repeat(250)), format!("%{}%", "é".repeat(200))); - assert_eq!(search_words(" a\tb "), ("ab".to_string(), 1, 0)); + // A tab or line break keeps the words apart; another control character is left out. + assert_eq!(search_words(" a\tb\nc "), ("a b c".to_string(), 0, 0)); + assert_eq!(search_words("a\u{0B}b\u{0C}c\u{85}d"), ("a b c d".to_string(), 0, 0)); + assert_eq!(search_words("a\u{7}b"), ("ab".to_string(), 1, 0)); assert_eq!(search_words(&"é".repeat(250)), ("é".repeat(200), 0, 50)); assert_eq!(search_words("solos"), ("solos".to_string(), 0, 0)); diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3e338ca9d3..74fa4077f1 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -589,6 +589,13 @@ pub trait FeatureSource: Send + Sync { let in_own = req.own.is_some_and(|(crs, _)| crs == self.coord_crs()); self.visit_chunks(if in_own { None } else { req.extent }, bytes, visit) } + /// Whether [`FeatureSource::visit_request_chunks`] narrows a box in the source's own system + /// itself (an index read by that box, as a Shapefile's), rather than visiting every feature: + /// a caller sampling a view walks the request only where this costs no more than the extent. + /// Not [`FeatureSource::reads_own_box`], which is about `read` and is true for more sources. + fn walks_own_box(&self) -> bool { + false + } fn info(&self) -> &SourceInfo; /// The coordinate system of the features it gives: a file read in place gives them as the file /// holds them, in its own system (Shapefile, GeoPackage, FlatGeobuf, GeoParquet, GeoJSON); a @@ -629,9 +636,10 @@ pub trait FeatureSource: Send + Sync { fn field_range(&self, _field: &str) -> Option<(f64, f64)> { None } - /// Whether the source holds more features than the `n` read, asked of it when its count - /// ([`SourceInfo::count`]) may be wrong and it can tell without reading them all (a - /// GeoPackage's kept count, #2898); `None` when its count is taken as it is, or it can't tell. + /// Whether the source holds more features than the `n` read, where it can tell without reading + /// them all and its [`SourceInfo::count`] may be wrong (a GeoPackage's kept count, #2898). + /// Asked of every source by `SourceLayer::holds_only`; `None` when its count is taken as it + /// is, or it can't tell. fn holds_more_than(&self, _n: u64) -> Option { None } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 53337cf7d3..f5ab34d6d5 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -623,6 +623,9 @@ impl FeatureSource for ShpSource { fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { self.visit_with(req, None, bytes, visit) } + fn walks_own_box(&self) -> bool { + true + } fn visits_ids(&self) -> bool { true } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 50c24f0217..8fef160745 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1080,7 +1080,7 @@ fn add_field(s: &mut Session, p: &Json) -> CmdResult { if table { rustgis_data::progress::begin(ds.features.len()); } - // A table's runs ahead on a worker, with progress and Cancel ([`table_ahead`]). + // A table's edit runs ahead on a worker, with progress and Cancel ([`table_ahead`]). ds.features.try_add_columns( 1, Value::Null, diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5b908de2d..9facc5e783 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5554,7 +5554,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let left_out = parts_left_out(url, &bytes, p); let cut = url_name_cut("Add Data From URL", url, p, &bytes); // A WCS coverage's own system it was asked for in, for an answer that doesn't say it. - let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(p, url) } else { None }; + let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(s, p, url) } else { None }; let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), None, asked).map_err(named)?; if let Some(n) = left_out { s.notify(n, false); @@ -7240,6 +7240,18 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // paging. let bytes = if service { let label = ps(p, "name").map(str::to_string).unwrap_or_else(|| crate::sources::address_in_message(&url)); + // A WFS type asked in its own system answered with an exception report (which may refuse + // that system): said as `service.add` says it, with how to ask in degrees instead (the app + // downloaded this answer, so it isn't asked again here). + if super::service::is_exception_report(&bytes) + && let Some(lonlat) = rustgis_data::ogc::wfs_lonlat_fallback(&url) + { + let asked = rustgis_data::ogc::asked_system(&url).map(|c| c.label()).unwrap_or_default(); + return Err(format!( + "{label}: asked in its own system ({asked}), the server answered with an exception report, which may refuse that system; to ask for its features in EPSG:4326 instead, add the same address, its other parameters kept, with SRSNAME=EPSG:4326 ({})", + crate::sources::address_in_message(&lonlat) + )); + } super::service::features_answer(s, &label, &url, bytes, bounds) } else { bytes @@ -7260,7 +7272,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let drawn = s.landed_pages.iter().position(|(d, _)| *d == id).map(|i| s.landed_pages.remove(i).1); #[cfg(target_arch = "wasm32")] let drawn = None; - let asked = if coverage { super::raster::coverage_system(p, &url) } else { None }; + let asked = if coverage { super::raster::coverage_system(s, p, &url) } else { None }; let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn, asked)?; if let Some(n) = left_out { s.notify(n, false); @@ -8426,8 +8438,9 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { _ => String::new(), }; let order = if rest.by_number { "by number" } else { "in text order" }; - // A view that holds the whole source says nothing. - let part = l.source.as_ref().is_some_and(|src| !src.holds_only(l.dataset.features.len() as u64)); + // A view that holds the whole source says nothing. Asked only when there is something to say + // (a GeoPackage's kept count steps through rows to tell). + let part = from_view.is_some() && l.source.as_ref().is_some_and(|src| !src.holds_only(l.dataset.features.len() as u64)); let from_view = from_view.filter(|_| part).map(|then| (l.dataset.kept_features(&l.visible_rows()).count(), then)); let mut dropped = None; let out = with(s, p, |l| { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 1809ce207e..90639dce4e 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -843,16 +843,44 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { add_named_bytes(s, p, name, bytes, b(p, "zoom")) } -/// The system a WCS coverage was asked for in, for an answer that doesn't say its own: -/// `"coverageCrs"` (`service.coverage`'s, `EPSG:`), else the one its GetCoverage address -/// `url` names ([`coverage_request_system`](rustgis_data::ogc::coverage_request_system)). -pub(crate) fn coverage_system(p: &Value, url: &str) -> Option { +/// The system a WCS coverage was asked for in, for an answer that doesn't say its own: the one +/// its GetCoverage address `url` names ([`coverage_request_system`](rustgis_data::ogc::coverage_request_system)), +/// which is what the server was asked for; when the address names no system, `"coverageCrs"` +/// (`service.coverage`'s, `EPSG:`). A `coverageCrs` the address overrules is said. +pub(crate) fn coverage_system(s: &mut Session, p: &Value, url: &str) -> Option { // Only `EPSG:`: `Crs::parse` takes WKT and PROJ text too, and keeps a system for them. let given = ps(p, "coverageCrs") .and_then(|c| c.strip_prefix("EPSG:")?.parse::().ok()) .and_then(rustgis_data::raster::Crs::from_epsg) .filter(|c| !c.is_geographic()); - given.or_else(|| rustgis_data::ogc::coverage_request_system(url)) + let Some(asked) = rustgis_data::ogc::coverage_request_system(url) else { + // An address naming another system (longitude/latitude, one RustGIS doesn't read) asked + // the server for that one: its answer isn't read in coverageCrs. + if rustgis_data::ogc::coverage_request_names_system(url) { + if let Some(given) = given { + s.notify( + format!( + "the coverage's address asks for it in another system than coverageCrs {}, so its answer isn't read in that one", + given.label() + ), + false, + ); + } + return None; + } + return given; + }; + if let Some(given) = given.filter(|g| *g != asked) { + s.notify( + format!( + "the coverage's address asks for it in {}, so its answer is read in that system, not in coverageCrs {}", + asked.label(), + given.label() + ), + false, + ); + } + Some(asked) } /// Adds a file's contents (an upload, a download) as its name's extension says. A PDF's page is diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 51f02109c2..fb14a4adae 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -539,9 +539,9 @@ pub fn features_answer(s: &mut Session, name: &str, url: &str, bytes: Vec, b if let Some(note) = rustgis_data::ogc::partial_note(&bytes) { s.notify(format!("{name}: {note}"), false); } - let (bytes, assumed) = rustgis_data::ogc::place_answer(bytes, url, bounds); + let (bytes, assumed, unturned) = rustgis_data::ogc::place_answer(bytes, url, bounds); // Once per kind with a count over the command (a service group reads many answers). - if let Some(assumed) = assumed { + for assumed in [assumed, unturned].into_iter().flatten() { s.notify_counted(assumed.loss(), assumed.template(), 1); } bytes @@ -629,6 +629,55 @@ pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usi } } +/// Whether a fetch's error `e` is the server's refusal, an HTTP status of 400 to 599, the +/// address it may be prefixed with (`
: http status: 400`) set aside. +#[cfg(not(target_arch = "wasm32"))] +fn server_refused(e: &str) -> bool { + refusal_status(e).is_some() +} + +/// The HTTP status of 400 to 599 a fetch's error `e` is, the address it may be prefixed with set +/// aside: what is said of a refusal, never the error's text, which may hold the address. +#[cfg(not(target_arch = "wasm32"))] +fn refusal_status(e: &str) -> Option { + std::iter::once(e) + .chain(e.match_indices(": ").filter_map(|(at, sep)| e.get(at + sep.len()..))) + .find_map(cache::http_status) + .filter(|status| (400..=599).contains(status)) +} + +/// Whether `bytes` are an OWS or WFS 1.0 exception report (not GML, which a server ignoring the +/// JSON output format would send): told by the name of its root element, past a byte order mark, +/// white space, the XML declaration, comments and a DOCTYPE, within its first 64 KB. A scan of the +/// prolog rather than the XML parser: the answer may be a large feature collection, which this +/// looks at without parsing it whole. +pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(bytes.get(..64 << 10).unwrap_or(bytes)); + let mut rest = head.trim_start_matches('\u{feff}').trim_start(); + loop { + let skipped = if rest.starts_with("").map(|at| at + 2) + } else if rest.starts_with("").map(|at| at + 3) + } else if rest.starts_with("')) { + (Some(open), Some(end)) if open < end => rest.get(open..).and_then(|t| t.find(']')).map(|at| open + at), + _ => Some(0), + }; + close.and_then(|from| rest.get(from..)?.find('>').map(|at| from + at + 1)) + } else { + break; + }; + let Some(at) = skipped else { return false }; + rest = rest.get(at..).unwrap_or_default().trim_start(); + } + let Some(tag) = rest.strip_prefix('<') else { return false }; + let name = tag.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next().unwrap_or_default(); + let local = name.rsplit(':').next().unwrap_or_default(); + matches!(local, "ExceptionReport" | "ServiceExceptionReport") +} + /// A service layer's features at `url` read whole while the command waits, as [`download_layer`] /// reads them (in pages, as protocol buffers when an ArcGIS layer lists them), and added with /// `p` (a GeoJSON answer under the file name `file` gives it, its axes checked against @@ -659,28 +708,31 @@ pub(crate) fn add_service_layer( // A WFS type asked in its own system that the server refuses (an error, or an exception // report where features were expected) is asked once more in EPSG:4326, as before RustGIS // asked types in their own system, and that is said. + // Only the server's own refusal: an HTTP error status, or an exception report. A cancel, a + // timeout, an answer past the download cap or an address refused here would fail again (or + // was asked to stop), so it isn't asked a second time. let refused = |r: &Result<(Downloaded, Drawing), String>| match r { - Err(_) => true, - // An OWS or WFS 1.0 exception report (not GML, which a server ignoring the JSON output - // format would send). - Ok((Downloaded::Bytes(b), _)) => { - let head = String::from_utf8_lossy(&b[..b.len().min(1024)]); - head.trim_start().starts_with('<') && head.contains("ExceptionReport") - } + Err(e) => server_refused(e), + Ok((Downloaded::Bytes(b), _)) => is_exception_report(b), Ok(_) => false, }; let fallback = rustgis_data::ogc::wfs_lonlat_fallback(url).filter(|_| refused(&first)); let (url, (downloaded, drawing)) = match fallback { Some(lonlat) => { + // Its status only: the error's text may hold the address. let why = match &first { - Err(e) => e.chars().take(200).collect::(), - Ok(_) => "it answered with an exception report".into(), + // Only a refusal reaches here (`refused`), so it has a status. + Err(e) => format!("HTTP {}", refusal_status(e).unwrap_or_default()), + Ok(_) => "an exception report".into(), }; // Failing too, both are said. - let second = fetch(s, &lonlat).map_err(|e| format!("{e} (asked in its own system first: {why})"))?; + let second = fetch(s, &lonlat).map_err(|e| format!("{e} (asked in its own system first, it answered with {why})"))?; let asked = rustgis_data::ogc::asked_system(url).map(|c| c.label()).unwrap_or_default(); + // The answer may refuse the system or something else: what it was is said, not why. s.notify( - format!("{name}: the server refused its own system ({asked}: {why}); its features were asked for in EPSG:4326 instead"), + format!( + "{name}: asked in its own system ({asked}), the server answered with {why}; its features were asked for in EPSG:4326 instead" + ), false, ); (lonlat, second) @@ -2091,6 +2143,36 @@ fn fetch_records(url: &str, _: &str, _: Reach, _: bool) -> Result<(Vec, Reac mod tests { use super::*; + /// A WFS type is asked again in degrees only on the server's refusal (an error status, its + /// address set aside, or an exception report), never after a timeout, a cancel, an answer + /// past the cap or an address refused here. + #[test] + fn only_a_servers_refusal_asks_a_wfs_type_again() { + for (refusal, status) in [("http status: 400", 400), ("https://x.org/wfs?a=1: http status: 500", 500), ("HTTP 404", 404)] { + assert!(server_refused(refusal), "{refusal}"); + assert_eq!(refusal_status(refusal), Some(status)); + } + for other in [ + "https://x.org/wfs?a=1: the pages took too long", + "cancelled", + "https://x.org/wfs?a=1: larger than RustGIS downloads (512 MB)", + "https://x.org/wfs?a=1: a public address can't lead to a local one", + "http status: 302", + "https://x.org/400: refused", + ] { + assert!(!server_refused(other), "{other}"); + } + assert!(is_exception_report(br#""#)); + assert!(is_exception_report("\u{feff}".as_bytes()), "after a byte order mark"); + assert!(!is_exception_report(br#""#)); + assert!(is_exception_report(br#""#)); + assert!(is_exception_report(br#" ]>"#), "past a DOCTYPE's subset"); + // The words inside another document don't make it one. + assert!(!is_exception_report(br#"ExceptionReport"#)); + assert!(!is_exception_report(br#"{"type":"FeatureCollection","features":[{"properties":{"n":""}}]}"#)); + assert!(!is_exception_report(b"")); + } + /// Every fallback to the standard tile address off the frame is said (AGENTS.md, Never silent): /// a list leading on past two documents, a template refused, a document address refused. A /// template read says nothing (#1319). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7019fb34ed..1538d58681 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -30317,7 +30317,7 @@ fn a_catalogue_refusing_crs84_is_asked_for_the_area_without_it() { assert_eq!(asked.lock().unwrap().clone(), [true]); // Words the catalogue isn't asked for are counted. - let p = json!({"url": "https://cat.example.org/csw", "query": format!("a\tb{}", "c".repeat(250)), "text": PAGE}); + let p = json!({"url": "https://cat.example.org/csw", "query": format!("a\u{7}b{}", "c".repeat(250)), "text": PAGE}); let v = s.run("catalog.search", &p).unwrap(); let said: Vec<&str> = v["notes"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); assert_eq!(said, ["control characters left out of the words searched for: 1", "the words are cut to 200 characters; left out: 52"]); diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 0912bf7c2e..024abc6478 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -98,12 +98,19 @@ fn a_wfs_type_whose_system_is_refused_is_asked_in_degrees() { r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[7.44,46.95]}}]}"#, ); let mut s = Session::new(Project::default()); + // Downloaded by the app (the browser, a plugin): the refusal is said, with the address in + // degrees to add instead, not read as a broken file. + s.downloaded.push((21, refusal.as_bytes().to_vec())); + let e = s.run("layer.addDownload", &json!({"id": 21, "url": url, "name": "Towns", "service": true})).unwrap_err(); + assert!(e.starts_with("Towns: asked in its own system (EPSG:2056), the server answered with an exception report"), "{e}"); + assert!(e.contains("may refuse that system") && e.contains("EPSG:4326 instead"), "{e}"); + assert!(e.contains("SRSNAME=EPSG:4326"), "{e}"); s.run("service.add", &json!({"url": format!("{}/refuses", server.base), "layer": "towns", "text": text, "name": "Towns"})).unwrap(); assert_eq!(first_point(&s, "Towns"), (Crs::LonLat, 7.44, 46.95)); let said = notices(&s); assert!( - said.iter() - .any(|n| n.starts_with("Towns: the server refused its own system (EPSG:2056") && n.ends_with("asked for in EPSG:4326 instead")), + said.iter().any(|n| n.starts_with("Towns: asked in its own system (EPSG:2056), the server answered with an exception report") + && n.ends_with("asked for in EPSG:4326 instead")), "{said:?}" ); } @@ -294,17 +301,40 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { } assert!(s.run("layer.addDownload", &q).is_err(), "{crs:?}"); } - // A coverageCrs that isn't usable leaves it to the address; a usable one comes first. + // A coverageCrs that isn't usable leaves it to the address too. s.downloaded.push((14, tiff.clone())); let added = s .run("layer.addDownload", &json!({"id": 14, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:4326"})) .unwrap(); assert_eq!(crs_of(&s, &added["layer"]), lv95); + // The address's system comes before another given: the answer is in the one asked for. s.downloaded.push((15, tiff.clone())); let added = s .run("layer.addDownload", &json!({"id": 15, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:21781"})) .unwrap(); - assert_eq!(crs_of(&s, &added["layer"]), Crs::from_epsg(21781).unwrap()); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + assert!(notices(&s).iter().any(|n| n.contains("not in coverageCrs")), "{:?}", notices(&s)); + // An address asking for longitude/latitude isn't read in a projected coverageCrs. + let in_degrees = get.replace( + "EPSG/0/2056&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056", + "EPSG/0/2056&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326", + ); + assert_ne!(in_degrees, get); + let mut q = Session::new(Project::default()); + q.downloaded.push((16, tiff.clone())); + let added = + q.run("layer.addDownload", &json!({"id": 16, "url": in_degrees, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:2056"})); + // Its metres can't be placed without a system: refused, never read in LV95. + assert!(added.is_err(), "{added:?}"); + // The coverageCrs set aside is said, whatever the read then does. + let mut q = Session::new(Project::default()); + let p = json!({"coverageCrs": "EPSG:2056"}); + assert_eq!(crate::cmd::raster::coverage_system(&mut q, &p, &in_degrees), None); + assert!(q.notices_since(0).iter().any(|n| n.text.contains("another system than coverageCrs"))); + // An empty OUTPUTCRS names nothing: coverageCrs decides. + let empty = in_degrees.replace("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326", "OUTPUTCRS="); + assert_ne!(empty, in_degrees); + assert_eq!(crate::cmd::raster::coverage_system(&mut q, &p, &empty), Some(lv95)); // Added by address, as the command line adds service.coverage's address: the address says // the system, or coverageCrs does. let added = s.run("layer.addUrl", &json!({"url": get, "name": "By address", "coverage": true})).unwrap(); diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 012d58a81d..80128c0bb5 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -60,8 +60,8 @@ pub struct Report { /// thousands of different notes, and a repeat is found without going through them all. #[serde(skip)] index: HashMap, - /// Different notes past [`MAX_NOTES`], not kept but counted in a closing note of their kind - /// and loss code. + /// Notes past [`MAX_NOTES`], each time one is made (a repeat of one left out counts again), + /// not kept but counted in a closing note of their kind and loss code. #[serde(skip)] more: HashMap<(NoteKind, Option), usize>, /// Where each closing note is in `notes`, kept in step by [`Report::forget`]. diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 5e1171e952..2b622f8c0a 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -177,7 +177,13 @@ fn read_filtered( let (mut kept, mut kept_bytes, mut step, mut seen) = (Vec::new(), 0usize, 1u64, 0u64); let mut areas = super::AmbiguousAreas::default(); let measures_area = rustgis_data::query::uses_area(expr); - let summary = source.visit_chunks(req.extent, FILTER_CHUNK_BYTES, &mut |chunk| { + // By the whole request, its box in the source's own system too, where the source narrows by + // that box itself (a Shapefile, as its first read does): a map in that system keeps features + // its longitude/latitude extent would leave out (#2778). Another source is walked by the + // extent, as before, which keeps its index; walking it by its own box would visit every + // feature. + let walked = if source.walks_own_box() { *req } else { Request { own: None, ..*req } }; + let summary = source.visit_request_chunks(&walked, FILTER_CHUNK_BYTES, &mut |chunk| { scratch.features = chunk.into(); if strict && measures_area @@ -538,6 +544,67 @@ mod tests { assert!(batch.features.len() > copied.features.len(), "{} vs {}", batch.features.len(), copied.features.len()); } + /// A filtered sample of a source on a map in its own system walks the request with its own + /// box, as the first read does, not the longitude/latitude extent, which may leave features out. + #[test] + fn a_filtered_read_in_the_sources_system_walks_its_own_box() { + /// Gives nothing for a longitude/latitude extent: the features it holds have no place there. + struct NoLonLat(Box); + impl FeatureSource for NoLonLat { + fn info(&self) -> &rustgis_data::source::SourceInfo { + self.0.info() + } + fn read(&self, req: &Request) -> Result { + self.0.read(req) + } + fn coord_crs(&self) -> Crs { + Crs::Epsg(32632) + } + // As a Shapefile does: its request walk narrows by its own box. + fn walks_own_box(&self) -> bool { + true + } + fn visit_request_chunks( + &self, + req: &Request, + bytes: usize, + visit: &mut dyn FnMut(Vec) -> Result<()>, + ) -> Result { + match req.own { + Some((_, b)) if !b.intersects(&Extent::new(0.0, 0.0, 10.0, 10.0)) => Ok(Batch { complete: true, ..Batch::default() }), + Some(_) => self.0.visit_chunks(None, bytes, visit), + None => self.visit_chunks(req.extent, bytes, visit), + } + } + fn visit_chunks( + &self, + extent: Option, + bytes: usize, + visit: &mut dyn FnMut(Vec) -> Result<()>, + ) -> Result { + if extent.is_some() { + return Ok(Batch { complete: true, ..Batch::default() }); + } + self.0.visit_chunks(None, bytes, visit) + } + } + let source = NoLonLat(source()); + let scratch = Dataset::new("s", GeometryType::Polygon, vec![]); + let expr = rustgis_data::query::parse("1 = 1", &scratch).unwrap(); + let req = Request { + extent: Some(Extent::new(8.0, 45.0, 10.0, 47.0)), + limit: 10, + own: Some((Crs::Epsg(32632), Extent::new(0.0, 0.0, 1e6, 1e7))), + }; + let (batch, _) = read_filtered(&source, &req, usize::MAX, scratch.clone(), &expr, false, &Default::default()).unwrap(); + assert_eq!(batch.matched, 600); + assert!(!batch.features.is_empty()); + // Walked by that box: none lies in one far from them all. + let far = Request { own: Some((Crs::Epsg(32632), Extent::new(1e9, 1e9, 1e9 + 1.0, 1e9 + 1.0))), ..req }; + let (batch, _) = read_filtered(&source, &far, usize::MAX, scratch, &expr, false, &Default::default()).unwrap(); + assert_eq!(batch.matched, 0); + } + #[test] fn installed_windows_share_the_map_budget_and_reuse_prepared_geometry() { let mut map = crate::Map::new("budget"); diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 8bca33a3ca..f7ff9eee74 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -643,28 +643,21 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { Asked::Children(url) => match r.and_then(|f| Ok((f.origin.reach(), catalog::parse_children_noted(&f.bytes, &f.origin)?))) { Ok((reach, listing)) => { if listing.refused > 0 { - app.session.notify( - i18n::fmt("{n} catalog links were refused by the document's network reach", &[("n", &listing.refused.to_string())]), - false, - ); + app.session.notify(links_refused(listing.refused), false); } if listing.skipped > 0 { - app.session.notify( - i18n::fmt( - "{n} catalog links were left out because their addresses are missing, invalid or not HTTP(S)", - &[("n", &listing.skipped.to_string())], - ), - false, - ); + app.session.notify(links_unusable(listing.skipped), false); } if listing.omitted > 0 { - app.session.notify( + let note = if listing.omitted == 1 { + i18n::fmt("1 catalog link was left out because the listing limit was reached", &[]) + } else { i18n::fmt( "{n} catalog links were left out because the listing limit was reached", &[("n", &listing.omitted.to_string())], - ), - false, - ); + ) + }; + app.session.notify(note, false); } let c = listing.links; st.node_reach = Some(reach); @@ -728,19 +721,10 @@ fn poll_walk(app: &mut RustGisApp, ctx: &egui::Context) { return; } if walk.refused() > 0 { - app.session.notify( - i18n::fmt("{n} catalog links were refused by the document's network reach", &[("n", &walk.refused().to_string())]), - false, - ); + app.session.notify(links_refused(walk.refused()), false); } if walk.skipped() > 0 { - app.session.notify( - i18n::fmt( - "{n} catalog links were left out because their addresses are missing, invalid or not HTTP(S)", - &[("n", &walk.skipped().to_string())], - ), - false, - ); + app.session.notify(links_unusable(walk.skipped()), false); } let st = &mut app.ui.stac; let n = walk.items().len().to_string(); @@ -756,8 +740,12 @@ fn poll_walk(app: &mut RustGisApp, ctx: &egui::Context) { i18n::fmt("Showing {n} items ({f} documents couldn't be read)", &[("n", &n), ("f", &walk.failed.to_string())]) } else if walk.cut && walk.items().len() < 50 { i18n::fmt("Showing {n} items (some catalogs were too deep or too large to read: pick a catalog further down)", &[("n", &n)]) + } else if walk.refused() == 1 { + i18n::fmt("Showing {n} items (1 catalog link was refused)", &[("n", &n)]) } else if walk.refused() > 0 { i18n::fmt("Showing {n} items ({f} catalog links were refused)", &[("n", &n), ("f", &walk.refused().to_string())]) + } else if walk.skipped() == 1 { + i18n::fmt("Showing {n} items (1 catalog link was skipped)", &[("n", &n)]) } else if walk.skipped() > 0 { i18n::fmt("Showing {n} items ({s} catalog links were skipped)", &[("n", &n), ("s", &walk.skipped().to_string())]) } else { @@ -2819,6 +2807,24 @@ fn formatted( add } +/// The notice of `n` catalog links refused by the document's network reach, one or several. +fn links_refused(n: usize) -> String { + if n == 1 { + i18n::fmt("1 catalog link was refused by the document's network reach", &[]) + } else { + i18n::fmt("{n} catalog links were refused by the document's network reach", &[("n", &n.to_string())]) + } +} + +/// The notice of `n` catalog links left out for an address that can't be used, one or several. +fn links_unusable(n: usize) -> String { + if n == 1 { + i18n::fmt("1 catalog link was left out because its address is missing, invalid or not HTTP(S)", &[]) + } else { + i18n::fmt("{n} catalog links were left out because their addresses are missing, invalid or not HTTP(S)", &[("n", &n.to_string())]) + } +} + #[cfg(test)] mod tests { use super::*; @@ -4027,7 +4033,7 @@ mod tests { let notices = app.session.notices_since(mark); assert_eq!(notices.len(), usize::from(refused)); if refused { - assert!(notices[0].text.contains("1 catalog links were refused")); + assert!(notices[0].text.contains("1 catalog link was refused"), "{}", notices[0].text); } } } @@ -4070,8 +4076,8 @@ mod tests { assert_eq!(app.ui.stac.children.len(), 2000); let notices = app.session.notices_since(mark); assert_eq!(notices.len(), 3); - assert!(notices.iter().any(|n| n.text.contains("1 catalog links were refused"))); - assert!(notices.iter().any(|n| n.text.contains("1 catalog links were left out because their addresses"))); + assert!(notices.iter().any(|n| n.text.contains("1 catalog link was refused"))); + assert!(notices.iter().any(|n| n.text.contains("1 catalog link was left out because its address"))); } /// A public item, as a search of `https://stac.example/api` found it: with its own address when `own`.