From b22b2cd9bfae55a6976ac384c9540416fc0e941c Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 00:39:58 -0500 Subject: [PATCH 01/22] fix(data): release sweep follow-ups (data services) Deferred review points in service reads: turning answers' axes within a memory limit, protocol buffer pages naming the asked system joining those naming none, losses counted past the page limit said, a WFS schema with leading space, a hidden cause said to exist, WFS fallback only on the server's refusal and said on the download route, the coverage address's system first, a filtered window walking its own box, singular STAC link notices, and doc fixes. --- crates/analysis/src/rasterops.rs | 4 +- crates/data/src/ogc.rs | 274 ++++++++++++++++++++++-- crates/data/src/source/mod.rs | 7 +- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/layer.rs | 17 +- crates/engine/src/cmd/raster.rs | 19 +- crates/engine/src/cmd/service.rs | 51 ++++- crates/engine/src/tests/services_own.rs | 11 +- crates/map/src/qgis/mod.rs | 4 +- crates/map/src/source/window.rs | 45 +++- crates/ui-egui/src/stacui.rs | 64 +++--- 11 files changed, 424 insertions(+), 74 deletions(-) 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..cfe771a9f8 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2514,14 +2514,15 @@ 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: +/// control characters (tab and line breaks too, which would join words) and U+FFFE/U+FFFF, which +/// XML can't hold, and those past [`MAX_SEARCH_WORDS`]. 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 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 +3680,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 +3703,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); @@ -4052,6 +4058,9 @@ pub struct Pages { /// The memory those pages take, in bytes, and the most they may ([`max_decoded_bytes`]). decoded_bytes: usize, decoded_budget: usize, + /// The decoded features read past the limit and cut away ([`Pages::finish_at_max`]), which + /// the joined losses still count. + cut_past_max: usize, /// Why the layer's first protocol buffer page couldn't be read, when it is read in GeoJSON /// pages instead: said in the note it ends with. pbf_failed: Option, @@ -4250,6 +4259,7 @@ fn start(url: &str, max: usize, pbf: bool) -> Step { decoded: None, placed_as: None, decoded_bytes: 0, + cut_past_max: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, paging_failed: None, @@ -4326,6 +4336,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option { - 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 +4838,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 = @@ -4931,6 +4945,7 @@ impl Pages { let max = self.max; self.features.truncate(max); if let Some((ds, ..)) = &mut self.decoded { + self.cut_past_max = ds.features.len().saturating_sub(max); ds.features.truncate(max); } // Not through `stop`, whose "N WFS features read:" would say the count twice. @@ -4972,10 +4987,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; @@ -5005,7 +5021,17 @@ impl Pages { report.messages.push(note); } } - report.messages.extend(losses.messages()); + let lost = losses.messages(); + // The counts are summed over the pages as read, before the features past the limit + // were cut away: said, as they can't be split by feature. + if self.cut_past_max > 0 && !lost.is_empty() { + report.messages.extend(lost); + report + .messages + .push(format!("the counts above cover {} more feature(s) read past the limit, which aren't kept", self.cut_past_max)); + } else { + report.messages.extend(lost); + } return Step::Decoded(Box::new(ds), report, note); } // Done before a page was read (a limit of none). @@ -5422,10 +5448,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 +5466,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 +5592,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 +5604,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 +5631,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 @@ -5622,7 +5676,46 @@ impl Assumed { /// 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) }; + 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 that is what it gives back to say, +/// before anything else it assumed. +fn place_answer_within(bytes: Vec, url: &str, bounds: Option<[f64; 4]>, limit: usize) -> (Vec, 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, Some(Assumed::TooLargeToTurn)); + } + return (fix_axes(&bytes, bounds).unwrap_or(bytes), 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) { + // 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, if unturned.get() { Some(Assumed::TooLargeToTurn) } else { assumed }) +} + +/// [`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 +5725,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 +6514,32 @@ 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))); + 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 @@ -6579,6 +6699,57 @@ mod tests { ); } + /// Losses counted over the pages are said with how many features read past the limit, and + /// cut away, they cover; a read the limit doesn't cut says no such thing. + #[test] + fn pbf_losses_past_the_limit_say_what_they_cover() { + use crate::esripbf::tests::encode::{answer, feature, field, geometry, lonlat, number, transform, uint}; + let query = + "https://x.org/arcgis/rest/services/P/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=4326&f=geojson"; + let paged = br#"{"objectIdField": "OBJECTID", "maxRecordCount": 2, "supportedQueryFormats": "JSON, geoJSON, PBF", + "advancedQueryCapabilities": {"supportsPagination": true}}"#; + // A clockwise square; and one with a ring of three points on a line, which is left out. + let square = || geometry(&[5], &[0, 0, 0, 10, 10, 0, 0, -10, -10, 0]); + let flat = || geometry(&[5, 3], &[0, 0, 0, 10, 10, 0, 0, -10, -10, 0, 0, 0, 5, 0, 5, 0]); + let page = |ids: [u64; 2], last_flat: bool, more: bool| { + let mut parts = vec![number(7, 3), lonlat(), transform(false, 1.0, 0.0, 0.0), field("OBJECTID", 6)]; + if more { + parts.push(number(9, 1)); + } + parts.push(feature(&[uint(ids[0]), square()])); + parts.push(feature(&[uint(ids[1]), if last_flat { flat() } else { square() }])); + answer(&parts) + }; + let read = |max: usize| { + let mut step = begin_with_pbf(query, max); + 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=2") { + page([3, 4], true, false) + } else { + page([1, 2], false, true) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, _) => break (*ds, report), + other => panic!("{other:?}"), + } + } + }; + let (ds, report) = read(3); + assert_eq!(ds.features.len(), 3); + let said: Vec<&str> = report.messages.texts().collect(); + assert!(said.contains(&"1 polygon rings have no area and are left out"), "{said:?}"); + assert!(said.iter().any(|m| m.contains("cover 1 more feature(s) read past the limit")), "{said:?}"); + let (ds, report) = read(4); + assert_eq!(ds.features.len(), 4); + assert!(!report.messages.iter().any(|m| m.contains("past the limit")), "{:?}", report.messages); + } + /// Protocol-buffer pages naming no system, asked for in a projected one (`outSR`), are held in /// it as they came, and that is said, not read as longitude/latitude. #[test] @@ -6679,6 +6850,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 +7097,29 @@ mod tests { "#; + /// A feature description with space 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"}}]}"#; + let spaced = [b"\n ".as_slice(), WFS_SORT_SCHEMA].concat(); + 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(br#"{"features":[{"id":"roads.tmp-1","properties":{"record_number":1}},{"id":"roads.tmp-2","properties":{"record_number":2}}]}"#.to_vec()), + (_, Some("2"), Some("record_number")) => Ok(br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":3}}]}"#.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"], "{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() { @@ -7185,7 +7419,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. @@ -7815,6 +8052,7 @@ mod tests { decoded: None, placed_as: None, decoded_bytes: 0, + cut_past_max: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, paging_failed: None, diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3e338ca9d3..4c3d0658b4 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -629,9 +629,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/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..bd2b03b7c0 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -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 that the server refuses: said as `service.add` says + // it, with the address in degrees to add 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}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead: {}", + crate::sources::address_in_message(&lonlat) + )); + } super::service::features_answer(s, &label, &url, bytes, bounds) } else { bytes @@ -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..50e5082a6d 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -843,16 +843,19 @@ 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)). +/// 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, else `"coverageCrs"` (`service.coverage`'s, +/// `EPSG:`). pub(crate) fn coverage_system(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 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()) + }; + rustgis_data::ogc::coverage_request_system(url).or_else(given) } /// 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..ecca267b99 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -637,6 +637,22 @@ pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usi /// `service.add`, and `layer.addUrl` with `"service": true` with no app to leave it to (#1144). #[cfg(not(target_arch = "wasm32"))] #[expect(clippy::too_many_arguments, reason = "the two adds differ in each of them")] +/// 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. +fn server_refused(e: &str) -> bool { + std::iter::once(e) + .chain(e.match_indices(": ").filter_map(|(at, sep)| e.get(at + sep.len()..))) + .find_map(cache::http_status) + .is_some_and(|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 their first kilobyte. +pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)); + head.trim_start().starts_with('<') && head.contains("ExceptionReport") +} + pub(crate) fn add_service_layer( s: &mut Session, p: &Value, @@ -659,14 +675,12 @@ 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)); @@ -2091,6 +2105,29 @@ 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 in ["http status: 400", "https://x.org/wfs?a=1: http status: 500", "HTTP 404"] { + assert!(server_refused(refusal), "{refusal}"); + } + 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(br#""#)); + 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/services_own.rs b/crates/engine/src/tests/services_own.rs index 0912bf7c2e..7f4cfb12ce 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -98,6 +98,12 @@ 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: the server refused its own system (EPSG:2056") && e.contains("asked for in 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); @@ -294,17 +300,18 @@ 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); // 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..386aad86e9 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -177,7 +177,9 @@ 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: a map in that system keeps + // features its longitude/latitude extent would leave out (#2778). + let summary = source.visit_request_chunks(req, FILTER_CHUNK_BYTES, &mut |chunk| { scratch.features = chunk.into(); if strict && measures_area @@ -538,6 +540,47 @@ 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) + } + 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, &expr, false, &Default::default()).unwrap(); + assert_eq!(batch.matched, 600); + assert!(!batch.features.is_empty()); + } + #[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`. From 4784b62cdd6fbf20cef3ed9ce8b0eb621eaf683f Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:05:38 -0500 Subject: [PATCH 02/22] fix(engine): keep add_service_layer's attributes on it --- crates/engine/src/cmd/service.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index ecca267b99..00ad67b2fe 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -629,16 +629,9 @@ pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usi } } -/// 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 -/// `bounds`); then known by `url`, and drawn as its ArcGIS service draws it or said why not -/// (#2152), each by `name`. With `public`, only internet addresses are fetched. For -/// `service.add`, and `layer.addUrl` with `"service": true` with no app to leave it to (#1144). -#[cfg(not(target_arch = "wasm32"))] -#[expect(clippy::too_many_arguments, reason = "the two adds differ in each of them")] /// 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 { std::iter::once(e) .chain(e.match_indices(": ").filter_map(|(at, sep)| e.get(at + sep.len()..))) @@ -653,6 +646,14 @@ pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { head.trim_start().starts_with('<') && head.contains("ExceptionReport") } +/// 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 +/// `bounds`); then known by `url`, and drawn as its ArcGIS service draws it or said why not +/// (#2152), each by `name`. With `public`, only internet addresses are fetched. For +/// `service.add`, and `layer.addUrl` with `"service": true` with no app to leave it to (#1144). +#[cfg(not(target_arch = "wasm32"))] +#[expect(clippy::too_many_arguments, reason = "the two adds differ in each of them")] pub(crate) fn add_service_layer( s: &mut Session, p: &Value, From 7dae0d41557b6adfc72caeb3cd5d98b1aefbd837 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:24:49 -0500 Subject: [PATCH 03/22] fix(data): review follow-ups on the service sweep The too-large-to-turn assumption is said beside any other; a tab or line break in search words is a space; a filtered window tests each feature against its own box; page tests take the hidden-cause marker. The losses-past-limit note is dropped: a page is decoded only up to the room left, so the joined losses never count a cut feature. --- crates/data/src/ogc.rs | 129 ++++++++++--------------------- crates/engine/src/cmd/service.rs | 4 +- crates/engine/src/tests.rs | 2 +- crates/map/src/source/window.rs | 15 +++- 4 files changed, 56 insertions(+), 94 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index cfe771a9f8..9ad88717f2 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2515,11 +2515,13 @@ pub struct RecordPage { 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: -/// control characters (tab and line breaks too, which would join words) and U+FFFE/U+FFFF, which -/// XML can't hold, and those past [`MAX_SEARCH_WORDS`]. +/// other control characters and U+FFFE/U+FFFF, which XML can't hold, and those past +/// [`MAX_SEARCH_WORDS`]. A tab or line break 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 spaced = words.chars().map(|c| if matches!(c, '\t' | '\n' | '\r') { ' ' } 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(), left_out, kept.len().saturating_sub(MAX_SEARCH_WORDS)) @@ -4058,9 +4060,6 @@ pub struct Pages { /// The memory those pages take, in bytes, and the most they may ([`max_decoded_bytes`]). decoded_bytes: usize, decoded_budget: usize, - /// The decoded features read past the limit and cut away ([`Pages::finish_at_max`]), which - /// the joined losses still count. - cut_past_max: usize, /// Why the layer's first protocol buffer page couldn't be read, when it is read in GeoJSON /// pages instead: said in the note it ends with. pbf_failed: Option, @@ -4259,7 +4258,6 @@ fn start(url: &str, max: usize, pbf: bool) -> Step { decoded: None, placed_as: None, decoded_bytes: 0, - cut_past_max: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, paging_failed: None, @@ -4336,7 +4334,6 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option 0 && !lost.is_empty() { - report.messages.extend(lost); - report - .messages - .push(format!("the counts above cover {} more feature(s) read past the limit, which aren't kept", self.cut_past_max)); - } else { - report.messages.extend(lost); - } + report.messages.extend(losses.messages()); return Step::Decoded(Box::new(ds), report, note); } // Done before a page was read (a limit of none). @@ -5664,7 +5650,8 @@ fn turn_limit() -> usize { /// 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`]. @@ -5675,26 +5662,31 @@ fn turn_limit() -> usize { /// 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) { +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 that is what it gives back to say, -/// before anything else it assumed. -fn place_answer_within(bytes: Vec, url: &str, bounds: Option<[f64; 4]>, limit: usize) -> (Vec, Option) { +/// 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, Some(Assumed::TooLargeToTurn)); + return (bytes, None, Some(Assumed::TooLargeToTurn)); } - return (fix_axes(&bytes, bounds).unwrap_or(bytes), None); + 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) { +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| { @@ -5706,7 +5698,7 @@ fn place_within(bytes: Vec, crs: crate::raster::Crs, bounds: Option<[f64; 4] } }; let (bytes, assumed) = place_turned(bytes, crs, bounds, &turned); - (bytes, if unturned.get() { Some(Assumed::TooLargeToTurn) } else { assumed }) + (bytes, assumed, unturned.get().then_some(Assumed::TooLargeToTurn)) } /// [`place_within`]: `turned` says whether positions that should be turned round are. @@ -6525,18 +6517,25 @@ mod tests { 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); + 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); + 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); + 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); + 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))); } @@ -6699,57 +6698,6 @@ mod tests { ); } - /// Losses counted over the pages are said with how many features read past the limit, and - /// cut away, they cover; a read the limit doesn't cut says no such thing. - #[test] - fn pbf_losses_past_the_limit_say_what_they_cover() { - use crate::esripbf::tests::encode::{answer, feature, field, geometry, lonlat, number, transform, uint}; - let query = - "https://x.org/arcgis/rest/services/P/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=4326&f=geojson"; - let paged = br#"{"objectIdField": "OBJECTID", "maxRecordCount": 2, "supportedQueryFormats": "JSON, geoJSON, PBF", - "advancedQueryCapabilities": {"supportsPagination": true}}"#; - // A clockwise square; and one with a ring of three points on a line, which is left out. - let square = || geometry(&[5], &[0, 0, 0, 10, 10, 0, 0, -10, -10, 0]); - let flat = || geometry(&[5, 3], &[0, 0, 0, 10, 10, 0, 0, -10, -10, 0, 0, 0, 5, 0, 5, 0]); - let page = |ids: [u64; 2], last_flat: bool, more: bool| { - let mut parts = vec![number(7, 3), lonlat(), transform(false, 1.0, 0.0, 0.0), field("OBJECTID", 6)]; - if more { - parts.push(number(9, 1)); - } - parts.push(feature(&[uint(ids[0]), square()])); - parts.push(feature(&[uint(ids[1]), if last_flat { flat() } else { square() }])); - answer(&parts) - }; - let read = |max: usize| { - let mut step = begin_with_pbf(query, max); - 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=2") { - page([3, 4], true, false) - } else { - page([1, 2], false, true) - }; - step = (*pages).land(Ok(a)); - } - Step::Decoded(ds, report, _) => break (*ds, report), - other => panic!("{other:?}"), - } - } - }; - let (ds, report) = read(3); - assert_eq!(ds.features.len(), 3); - let said: Vec<&str> = report.messages.texts().collect(); - assert!(said.contains(&"1 polygon rings have no area and are left out"), "{said:?}"); - assert!(said.iter().any(|m| m.contains("cover 1 more feature(s) read past the limit")), "{said:?}"); - let (ds, report) = read(4); - assert_eq!(ds.features.len(), 4); - assert!(!report.messages.iter().any(|m| m.contains("past the limit")), "{:?}", report.messages); - } - /// Protocol-buffer pages naming no system, asked for in a projected one (`outSR`), are held in /// it as they came, and that is said, not read as longitude/latitude. #[test] @@ -7209,7 +7157,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")) { @@ -7380,7 +7332,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| { @@ -8052,7 +8004,6 @@ mod tests { decoded: None, placed_as: None, decoded_bytes: 0, - cut_past_max: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, paging_failed: None, @@ -10180,7 +10131,9 @@ 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{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/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 00ad67b2fe..22e64f3473 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 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/map/src/source/window.rs b/crates/map/src/source/window.rs index 386aad86e9..94d354765b 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -178,8 +178,13 @@ fn read_filtered( let mut areas = super::AmbiguousAreas::default(); let measures_area = rustgis_data::query::uses_area(expr); // By the whole request, its box in the source's own system too: a map in that system keeps - // features its longitude/latitude extent would leave out (#2778). - let summary = source.visit_request_chunks(req, FILTER_CHUNK_BYTES, &mut |chunk| { + // features its longitude/latitude extent would leave out (#2778). A source that doesn't test + // that box itself visits every feature, so each is tested here, as the first read does. + let own = req.own.filter(|(crs, _)| *crs == source.coord_crs()).map(|(_, b)| b); + let summary = source.visit_request_chunks(req, FILTER_CHUNK_BYTES, &mut |mut chunk| { + if let Some(b) = own { + chunk.retain(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&b))); + } scratch.features = chunk.into(); if strict && measures_area @@ -576,9 +581,13 @@ mod tests { limit: 10, own: Some((Crs::Epsg(32632), Extent::new(0.0, 0.0, 1e6, 1e7))), }; - let (batch, _) = read_filtered(&source, &req, usize::MAX, scratch, &expr, false, &Default::default()).unwrap(); + 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()); + // Its features are tested against 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] From ce02c7701359729c3fffebdfef4e47d4505ebc6d Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:40:05 -0500 Subject: [PATCH 04/22] fix(engine): name the SRSNAME the refused WFS add needs, as the address shown omits its query --- crates/engine/src/cmd/layer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index bd2b03b7c0..68277ac95f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7248,7 +7248,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { { let asked = rustgis_data::ogc::asked_system(&url).map(|c| c.label()).unwrap_or_default(); return Err(format!( - "{label}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead: {}", + "{label}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead (its address with SRSNAME=EPSG:4326: {})", crate::sources::address_in_message(&lonlat) )); } From 1812d62cfcf88457fdf44cd79da8afbc3459c1b6 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:52:39 -0500 Subject: [PATCH 05/22] fix(engine): an exception report after a byte order mark is one --- crates/engine/src/cmd/service.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 22e64f3473..ead5b5109f 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -643,7 +643,7 @@ fn server_refused(e: &str) -> bool { /// JSON output format would send), told by their first kilobyte. pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { let head = String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)); - head.trim_start().starts_with('<') && head.contains("ExceptionReport") + head.trim_start_matches('\u{feff}').trim_start().starts_with('<') && head.contains("ExceptionReport") } /// A service layer's features at `url` read whole while the command waits, as [`download_layer`] @@ -2125,6 +2125,7 @@ mod tests { 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(b"")); } From 834ddf6bf57c52a163679e29ea84c2c6097cce94 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 02:17:05 -0500 Subject: [PATCH 06/22] fix(data): a WFS schema after a byte order mark sorts the retry too And the refused-WFS hint says to keep the address's other parameters. --- crates/data/src/ogc.rs | 28 ++++++++++++++++------------ crates/engine/src/cmd/layer.rs | 2 +- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 9ad88717f2..a914b4443a 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4485,9 +4485,11 @@ impl Pages { // Bound the XML tree while the original feature rows are still held. let Some(schema) = std::str::from_utf8(&bytes) .ok() - // Leading space trimmed, as [`xml`] does; DTDs still refused. + // A byte order mark and leading space set aside, as the other XML readers do; + // DTDs still refused. .and_then(|text| { - crate::xml::parse(text.trim_start(), ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok() + 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()); @@ -7045,15 +7047,16 @@ mod tests { "#; - /// A feature description with space before its root is read as one without: the retry in - /// sort order still runs. + /// 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"}}]}"#; - let spaced = [b"\n ".as_slice(), WFS_SORT_SCHEMA].concat(); - let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { - match (query_value(next, "REQUEST"), query_value(next, "STARTINDEX"), query_value(next, "SORTBY")) { + for lead in ["\n ", "\u{feff}", "\u{feff}\n "] { + let spaced = [lead.as_bytes(), WFS_SORT_SCHEMA].concat(); + 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()), @@ -7061,11 +7064,12 @@ mod tests { (_, Some("2"), Some("record_number")) => Ok(br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":3}}]}"#.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"], "{note:?}"); - assert_eq!(note, None); + }); + 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. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 68277ac95f..fe0fdad365 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7248,7 +7248,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { { let asked = rustgis_data::ogc::asked_system(&url).map(|c| c.label()).unwrap_or_default(); return Err(format!( - "{label}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead (its address with SRSNAME=EPSG:4326: {})", + "{label}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead: the same address, its other parameters kept, with SRSNAME=EPSG:4326 ({})", crate::sources::address_in_message(&lonlat) )); } From 194e0a7ac81e8687650967115948a37e555022a2 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 02:41:08 -0500 Subject: [PATCH 07/22] refactor(map): test the own box in rustgis-data, not with a row field read --- crates/data/src/source/mod.rs | 7 +++++++ crates/map/src/source/window.rs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 4c3d0658b4..08f0f70e88 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -241,6 +241,13 @@ impl Request { } } +/// Keeps the features of `chunk` whose box in the source's own system meets `own`, as a source +/// that reads [`Request::own`] itself would have visited them: for a caller walking a source that +/// visits every feature for that box ([`FeatureSource::visit_request_chunks`]'s default). +pub fn retain_in_own_box(chunk: &mut Vec, own: &Extent) { + chunk.retain(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(own))); +} + /// A box over the whole plane: as [`Request::own`], every feature in the source's own system, /// those longitude/latitude can't place included (a map in that system draws them as they are). pub fn whole_plane() -> Extent { diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 94d354765b..8d62f354cd 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -183,7 +183,7 @@ fn read_filtered( let own = req.own.filter(|(crs, _)| *crs == source.coord_crs()).map(|(_, b)| b); let summary = source.visit_request_chunks(req, FILTER_CHUNK_BYTES, &mut |mut chunk| { if let Some(b) = own { - chunk.retain(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&b))); + rustgis_data::source::retain_in_own_box(&mut chunk, &b); } scratch.features = chunk.into(); if strict From 048b665a05e091db4227e37ec232451de85ef097 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 04:00:54 -0500 Subject: [PATCH 08/22] fix(engine): say what a refused WFS answer was, not a cause, and only its status An exception report may refuse the system or something else, so the notice and the download-route error say what the server answered; a first error is said by its HTTP status alone, as its text may hold the address. --- crates/engine/src/cmd/layer.rs | 8 ++++---- crates/engine/src/cmd/service.rs | 24 ++++++++++++++++++------ crates/engine/src/tests/services_own.rs | 7 ++++--- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index fe0fdad365..add6e19889 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7240,15 +7240,15 @@ 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 that the server refuses: said as `service.add` says - // it, with the address in degrees to add instead (the app downloaded this answer, so it - // isn't asked again here). + // 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}: the server refused its own system ({asked}: it answered with an exception report); add its features asked for in EPSG:4326 instead: the same address, its other parameters kept, with SRSNAME=EPSG:4326 ({})", + "{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) )); } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index ead5b5109f..64ca5b1ff2 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -633,10 +633,17 @@ pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usi /// 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) - .is_some_and(|status| (400..=599).contains(&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 @@ -687,15 +694,19 @@ pub(crate) fn add_service_layer( 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(), + Err(e) => refusal_status(e).map_or_else(|| "an error".to_string(), |status| format!("HTTP {status}")), + 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 {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 {why}; its features were asked for in EPSG:4326 instead" + ), false, ); (lonlat, second) @@ -2111,8 +2122,9 @@ mod tests { /// past the cap or an address refused here. #[test] fn only_a_servers_refusal_asks_a_wfs_type_again() { - for refusal in ["http status: 400", "https://x.org/wfs?a=1: http status: 500", "HTTP 404"] { + 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", diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 7f4cfb12ce..6cf9c78373 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -102,14 +102,15 @@ fn a_wfs_type_whose_system_is_refused_is_asked_in_degrees() { // 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: the server refused its own system (EPSG:2056") && e.contains("asked for in EPSG:4326 instead"), "{e}"); + 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 an exception report") + && n.ends_with("asked for in EPSG:4326 instead")), "{said:?}" ); } From 821ded84f533517fcf2c8794e685b7e9303880ee Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 04:08:22 -0500 Subject: [PATCH 09/22] fix(data): every white-space control character keeps search words apart --- crates/data/src/ogc.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index a914b4443a..d39e463f5b 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2516,11 +2516,11 @@ 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: /// other control characters and U+FFFE/U+FFFF, which XML can't hold, and those past -/// [`MAX_SEARCH_WORDS`]. A tab or line break is a space between words, not left out, so the words -/// on either side stay apart. +/// [`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 spaced = words.chars().map(|c| if matches!(c, '\t' | '\n' | '\r') { ' ' } else { c }); + 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(); @@ -10137,6 +10137,7 @@ mod tests { assert_eq!(literal(&"é".repeat(250)), format!("%{}%", "é".repeat(200))); // 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)); From bcc4c7280e44b0b99a28fac994246ba9c599a87c Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 04:37:35 -0500 Subject: [PATCH 10/22] fix(map): walk a filtered window by its own box only where the source narrows by it A source without its own own-box walk (GeoPackage, FlatGeobuf, GeoParquet) is walked by the extent again, keeping its index and row-group pruning; a Shapefile, which narrows by its own box, keeps the fix. FeatureSource::visits_own_box says which. --- crates/data/src/source/mod.rs | 10 ++++++++++ crates/data/src/source/shp.rs | 3 +++ crates/map/src/source/window.rs | 18 +++++++++++++----- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 08f0f70e88..d2208f7200 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -591,6 +591,12 @@ pub trait FeatureSource: Send + Sync { /// against it, converting nothing. One that doesn't visits every feature when given a box in /// its own system, never fewer than it holds (its extent, in longitude/latitude, may hold /// less), and reads the extent otherwise (no box, or one in another system). + /// 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. + fn visits_own_box(&self) -> bool { + false + } fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { // A box in another system is read as if absent, as `Request::own` has it. let in_own = req.own.is_some_and(|(crs, _)| crs == self.coord_crs()); @@ -900,6 +906,10 @@ impl FeatureSource for Fetching { self.0.reads_own_box() } + fn visits_own_box(&self) -> bool { + self.0.visits_own_box() + } + fn lost_to_crs(&self) -> bool { self.0.lost_to_crs() } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 53337cf7d3..32a615bb40 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 visits_own_box(&self) -> bool { + true + } fn visits_ids(&self) -> bool { true } diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 8d62f354cd..49c8a9fa43 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -177,11 +177,15 @@ 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); - // By the whole request, its box in the source's own system too: a map in that system keeps - // features its longitude/latitude extent would leave out (#2778). A source that doesn't test - // that box itself visits every feature, so each is tested here, as the first read does. - let own = req.own.filter(|(crs, _)| *crs == source.coord_crs()).map(|(_, b)| b); - let summary = source.visit_request_chunks(req, FILTER_CHUNK_BYTES, &mut |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): 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. Each feature is + // tested against the own box here too, as the first read does. + let by_own = source.visits_own_box(); + let own = req.own.filter(|(crs, _)| by_own && *crs == source.coord_crs()).map(|(_, b)| b); + let walked = if by_own { *req } else { Request { own: None, ..*req } }; + let summary = source.visit_request_chunks(&walked, FILTER_CHUNK_BYTES, &mut |mut chunk| { if let Some(b) = own { rustgis_data::source::retain_in_own_box(&mut chunk, &b); } @@ -561,6 +565,10 @@ mod tests { fn coord_crs(&self) -> Crs { Crs::Epsg(32632) } + // As a Shapefile says: its request walk narrows by its own box. + fn visits_own_box(&self) -> bool { + true + } fn visit_chunks( &self, extent: Option, From b9bcff1b5c08c695781f97ff8f794d3d3bd4dad8 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 04:44:11 -0500 Subject: [PATCH 11/22] fix(map): leave the own-box narrowing to the source that does it A source that narrows by its own box keeps what its own read keeps (a Shapefile record without a usable geometry included), so the filtered walk drops nothing more; visits_own_box's doc moves below the method whose doc it had taken. --- crates/data/src/source/mod.rs | 17 +++++------------ crates/map/src/source/window.rs | 33 ++++++++++++++++++++------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index d2208f7200..b317865c2c 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -241,13 +241,6 @@ impl Request { } } -/// Keeps the features of `chunk` whose box in the source's own system meets `own`, as a source -/// that reads [`Request::own`] itself would have visited them: for a caller walking a source that -/// visits every feature for that box ([`FeatureSource::visit_request_chunks`]'s default). -pub fn retain_in_own_box(chunk: &mut Vec, own: &Extent) { - chunk.retain(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(own))); -} - /// A box over the whole plane: as [`Request::own`], every feature in the source's own system, /// those longitude/latitude can't place included (a map in that system draws them as they are). pub fn whole_plane() -> Extent { @@ -591,17 +584,17 @@ pub trait FeatureSource: Send + Sync { /// against it, converting nothing. One that doesn't visits every feature when given a box in /// its own system, never fewer than it holds (its extent, in longitude/latitude, may hold /// less), and reads the extent otherwise (no box, or one in another system). + fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + // A box in another system is read as if absent, as `Request::own` has it. + 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. fn visits_own_box(&self) -> bool { false } - fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { - // A box in another system is read as if absent, as `Request::own` has it. - 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) - } 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 diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 49c8a9fa43..0d98eae475 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -178,17 +178,12 @@ fn read_filtered( let mut areas = super::AmbiguousAreas::default(); let measures_area = rustgis_data::query::uses_area(expr); // By the whole request, its box in the source's own system too, where the source narrows by - // that box itself (a Shapefile): 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. Each feature is - // tested against the own box here too, as the first read does. - let by_own = source.visits_own_box(); - let own = req.own.filter(|(crs, _)| by_own && *crs == source.coord_crs()).map(|(_, b)| b); - let walked = if by_own { *req } else { Request { own: None, ..*req } }; - let summary = source.visit_request_chunks(&walked, FILTER_CHUNK_BYTES, &mut |mut chunk| { - if let Some(b) = own { - rustgis_data::source::retain_in_own_box(&mut chunk, &b); - } + // 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.visits_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 @@ -565,10 +560,22 @@ mod tests { fn coord_crs(&self) -> Crs { Crs::Epsg(32632) } - // As a Shapefile says: its request walk narrows by its own box. + // As a Shapefile does: its request walk narrows by its own box. fn visits_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, @@ -592,7 +599,7 @@ mod tests { 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()); - // Its features are tested against that box: none lies in one far from them all. + // 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); From 7b413873bd7ff400c25eaa4cddfe86a144929b60 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 04:50:02 -0500 Subject: [PATCH 12/22] refactor: Fetching keeps the default visits_own_box; a refusal's status said directly --- crates/data/src/source/mod.rs | 4 ---- crates/engine/src/cmd/service.rs | 3 ++- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b317865c2c..62a1c4f6d9 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -899,10 +899,6 @@ impl FeatureSource for Fetching { self.0.reads_own_box() } - fn visits_own_box(&self) -> bool { - self.0.visits_own_box() - } - fn lost_to_crs(&self) -> bool { self.0.lost_to_crs() } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 64ca5b1ff2..11834ff902 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -696,7 +696,8 @@ pub(crate) fn add_service_layer( Some(lonlat) => { // Its status only: the error's text may hold the address. let why = match &first { - Err(e) => refusal_status(e).map_or_else(|| "an error".to_string(), |status| format!("HTTP {status}")), + // 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. From 16b3533d29497f9101b0904197f5e0d3436cbb22 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 05:21:51 -0500 Subject: [PATCH 13/22] fix(engine): tell an exception report by its root element --- crates/engine/src/cmd/service.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 11834ff902..eecd503f0c 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -647,10 +647,28 @@ fn refusal_status(e: &str) -> Option { } /// 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 their first kilobyte. +/// 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. pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { - let head = String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)); - head.trim_start_matches('\u{feff}').trim_start().starts_with('<') && head.contains("ExceptionReport") + 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("').map(|at| 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`] @@ -2140,6 +2158,10 @@ mod tests { 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#""#)); + // 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"")); } From 4a6235f674494351efb448de97e578df6cbc1937 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 05:30:45 -0500 Subject: [PATCH 14/22] fix(engine): skip a DOCTYPE's internal subset before an exception report's root --- crates/engine/src/cmd/service.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index eecd503f0c..08555154fa 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -658,7 +658,12 @@ pub(crate) fn is_exception_report(bytes: &[u8]) -> bool { } else if rest.starts_with("").map(|at| at + 3) } else if rest.starts_with("').map(|at| at + 1) + // A DOCTYPE, past its internal subset (`[ … ]`) when it has one. + let close = match (rest.find('['), rest.find('>')) { + (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; }; @@ -2159,6 +2164,7 @@ mod tests { 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":""}}]}"#)); From 99b756fe919a9a2bfead1d48c384a793d7c2787d Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 05:38:30 -0500 Subject: [PATCH 15/22] fix(engine): say a coverageCrs the coverage's address overrules --- crates/engine/src/cmd/layer.rs | 4 ++-- crates/engine/src/cmd/raster.rs | 27 ++++++++++++++++--------- crates/engine/src/tests/services_own.rs | 1 + 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index add6e19889..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); @@ -7272,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); diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 50e5082a6d..20b46eda60 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -846,16 +846,25 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { /// 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, else `"coverageCrs"` (`service.coverage`'s, -/// `EPSG:`). -pub(crate) fn coverage_system(p: &Value, url: &str) -> Option { +/// `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()) - }; - rustgis_data::ogc::coverage_request_system(url).or_else(given) + 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()); + let Some(asked) = rustgis_data::ogc::coverage_request_system(url) else { 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/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 6cf9c78373..e09d55e594 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -313,6 +313,7 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { .run("layer.addDownload", &json!({"id": 15, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:21781"})) .unwrap(); assert_eq!(crs_of(&s, &added["layer"]), lv95); + assert!(notices(&s).iter().any(|n| n.contains("not in coverageCrs")), "{:?}", notices(&s)); // 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(); From a9d27a37d5cf886cc3aa550ac8573eff4e2ed308 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:09:48 -0500 Subject: [PATCH 16/22] fix(engine): a coverage address naming another system isn't read in coverageCrs An address asking for longitude/latitude (or a system RustGIS doesn't read) asked the server for that one, so its untagged answer is no longer read in a projected coverageCrs; a coverageCrs set aside is said. --- crates/data/src/ogc.rs | 9 +++++++++ crates/engine/src/cmd/raster.rs | 22 +++++++++++++++++++--- crates/engine/src/tests/services_own.rs | 15 +++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index d39e463f5b..62815d9b12 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2304,6 +2304,15 @@ pub fn coverage_request_system(url: &str) -> Option { projected_system(&named).map(|(_, crs)| crs) } +/// 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 { + let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); + is("service", "wcs") + && is("request", "getcoverage") + && ["outputcrs", "response_crs", "crs"].iter().any(|k| query_value(url, k).is_some()) +} + /// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one /// first, or neither; with `xy`, `x` and `y` count as east and north too. fn north_first_labels(a: &str, b: &str, xy: bool) -> Option { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 20b46eda60..90639dce4e 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -845,15 +845,31 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { /// 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, else `"coverageCrs"` (`service.coverage`'s, -/// `EPSG:`). A `coverageCrs` the address overrules is said. +/// 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()); - let Some(asked) = rustgis_data::ogc::coverage_request_system(url) else { return given }; + 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!( diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index e09d55e594..6ff89f723b 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -314,6 +314,21 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { .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 in degrees: refused, never read in LV95. + if let Ok(added) = added { + assert_ne!(crs_of(&q, &added["layer"]), lv95); + assert!(notices(&q).iter().any(|n| n.contains("another system than coverageCrs")), "{:?}", notices(&q)); + } // 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(); From 557a5cd749ba09f3a2f8501f744f20d88de7c5b7 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:18:37 -0500 Subject: [PATCH 17/22] test: indent the schema retry test; pin the coverageCrs notice whatever the read does --- crates/data/src/ogc.rs | 16 +++++++++------- crates/engine/src/tests/services_own.rs | 6 +++++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 62815d9b12..cd3a9b9d9f 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -7064,15 +7064,17 @@ mod tests { 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(br#"{"features":[{"id":"roads.tmp-1","properties":{"record_number":1}},{"id":"roads.tmp-2","properties":{"record_number":2}}]}"#.to_vec()), - (_, Some("2"), Some("record_number")) => Ok(br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":3}}]}"#.to_vec()), - _ => panic!("unexpected request: {next}"), - } + (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(); diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 6ff89f723b..8eb2e45f27 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -327,8 +327,12 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { // Its metres can't be placed in degrees: refused, never read in LV95. if let Ok(added) = added { assert_ne!(crs_of(&q, &added["layer"]), lv95); - assert!(notices(&q).iter().any(|n| n.contains("another system than coverageCrs")), "{:?}", notices(&q)); } + // 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"))); // 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(); From 47070ad9f82d2adc14c0da028b3df95464c4950e Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:23:51 -0500 Subject: [PATCH 18/22] docs(engine): say why the exception-report check scans rather than parses --- crates/engine/src/cmd/service.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 08555154fa..f62a94319b 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -648,7 +648,9 @@ fn refusal_status(e: &str) -> Option { /// 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. +/// 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(); From c11c449b5c001678742f26864dd8a1bf75718cc2 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:31:20 -0500 Subject: [PATCH 19/22] refactor(data): one reader of the system a GetCoverage address names --- crates/data/src/ogc.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index cd3a9b9d9f..71f17b1cd3 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2295,22 +2295,25 @@ 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) + ["outputcrs", "response_crs", "crs"].iter().find_map(|k| query_value(url, k)) } /// 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 { - let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); - is("service", "wcs") - && is("request", "getcoverage") - && ["outputcrs", "response_crs", "crs"].iter().any(|k| query_value(url, k).is_some()) + coverage_request_named(url).is_some() } /// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one From 751d7c055f5f2bc8429e192c30e109ba1e004b88 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:38:57 -0500 Subject: [PATCH 20/22] test(engine): pin the refusal of a coverage asked in degrees --- crates/engine/src/tests/services_own.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 8eb2e45f27..0fa17bf53a 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -324,10 +324,8 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { 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 in degrees: refused, never read in LV95. - if let Ok(added) = added { - assert_ne!(crs_of(&q, &added["layer"]), lv95); - } + // 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"}); From 6da410c61ebb2043eb9598a72054bc5796888152 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:44:54 -0500 Subject: [PATCH 21/22] fix(data): an empty OUTPUTCRS names no system --- crates/data/src/ogc.rs | 3 ++- crates/engine/src/tests/services_own.rs | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 71f17b1cd3..dec9d5e1f8 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2307,7 +2307,8 @@ fn coverage_request_named(url: &str) -> Option<&str> { if !(is("service", "wcs") && is("request", "getcoverage")) { return None; } - ["outputcrs", "response_crs", "crs"].iter().find_map(|k| query_value(url, k)) + // 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 diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 0fa17bf53a..24f715cba5 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -331,6 +331,10 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { 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(); From 66bbdd80ee57aab97803b50448f04eb941bb0d4d Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 06:56:12 -0500 Subject: [PATCH 22/22] refactor: walks_own_box, one wording for a refused answer, placed_as doc --- crates/data/src/ogc.rs | 5 +++-- crates/data/src/source/mod.rs | 3 ++- crates/data/src/source/shp.rs | 2 +- crates/engine/src/cmd/service.rs | 4 ++-- crates/engine/src/tests/services_own.rs | 2 +- crates/map/src/source/window.rs | 4 ++-- 6 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index dec9d5e1f8..1bccb4b9f2 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -5437,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)] diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 62a1c4f6d9..74fa4077f1 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -592,7 +592,8 @@ pub trait FeatureSource: Send + Sync { /// 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. - fn visits_own_box(&self) -> bool { + /// 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; diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 32a615bb40..f5ab34d6d5 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -623,7 +623,7 @@ 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 visits_own_box(&self) -> bool { + fn walks_own_box(&self) -> bool { true } fn visits_ids(&self) -> bool { diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index f62a94319b..fb14a4adae 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -726,12 +726,12 @@ pub(crate) fn add_service_layer( 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, it answered {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}: asked in its own system ({asked}), the server answered {why}; its features were asked for in EPSG:4326 instead" + "{name}: asked in its own system ({asked}), the server answered with {why}; its features were asked for in EPSG:4326 instead" ), false, ); diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 24f715cba5..024abc6478 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -109,7 +109,7 @@ fn a_wfs_type_whose_system_is_refused_is_asked_in_degrees() { 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: asked in its own system (EPSG:2056), the server answered an exception report") + 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:?}" ); diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 0d98eae475..2b622f8c0a 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -182,7 +182,7 @@ fn read_filtered( // 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.visits_own_box() { *req } else { Request { own: None, ..*req } }; + 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 @@ -561,7 +561,7 @@ mod tests { Crs::Epsg(32632) } // As a Shapefile does: its request walk narrows by its own box. - fn visits_own_box(&self) -> bool { + fn walks_own_box(&self) -> bool { true } fn visit_request_chunks(