From 516c0c0387ac31f93d392dee2086260875e84790 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 11:30:21 -0600 Subject: [PATCH 1/3] fix(data): WFS offset pages ask for a stable order --- crates/data/src/ogc.rs | 296 +++++++++++++++++++++++++++++-- crates/engine/src/cmd/service.rs | 6 +- 2 files changed, 282 insertions(+), 20 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index fee741d618..e359ab6a58 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3747,7 +3747,7 @@ fn is_legacy_wfs_query(url: &str) -> bool { /// Replaces WFS presentation parameters, retaining the query, filters and authentication. /// Hits use the default XML format; feature pages retain the requested GeoJSON format. -fn wfs_page_url(url: &str, offset: Option, size: usize) -> String { +fn wfs_page_url(url: &str, offset: Option, size: usize, order: Option<&str>) -> String { let kept = url .split('#') .next() @@ -3764,11 +3764,113 @@ fn wfs_page_url(url: &str, offset: Option, size: usize) -> String { .join("&"); let url = with_query(base(url), &kept); match offset { - Some(offset) => with_query(&url, &format!("STARTINDEX={offset}&COUNT={size}")), + Some(offset) => { + let url = with_query(&url, &format!("STARTINDEX={offset}&COUNT={size}")); + match order { + Some(key) if query_value(&url, "SORTBY").is_none() => with_query(&url, &format!("SORTBY={}", encode(key))), + _ => url, + } + } None => with_query(&url, "RESULTTYPE=hits"), } } +/// A description for the same feature type and service, without GetFeature selectors. +fn wfs_schema_url(url: &str) -> Option { + wfs_type_name(url)?; + let inner = crate::login_address::inner(url).split('#').next()?; + let (base, query) = inner.split_once('?')?; + let kept = query.split('&').filter(|kv| { + let key = kv.split('=').next().unwrap_or_default(); + ![ + "REQUEST", + "OUTPUTFORMAT", + "SRSNAME", + "COUNT", + "STARTINDEX", + "RESULTTYPE", + "BBOX", + "FILTER", + "CQL_FILTER", + "FEATUREID", + "RESOURCEID", + "PROPERTYNAME", + "SORTBY", + ] + .iter() + .any(|k| key.eq_ignore_ascii_case(k)) + }); + let schema = format!("{base}?REQUEST=DescribeFeatureType&{}", kept.collect::>().join("&")); + Some(crate::login_address::inherit(url, &schema)) +} + +/// The local name of a single requested feature type; joins can have several schemas and keys. +fn wfs_type_name(url: &str) -> Option { + let name = query_value(url, "TYPENAMES").or_else(|| query_value(url, "TYPENAME"))?; + let name = name.replace("%3A", ":").replace("%3a", ":"); + let local = name.rsplit(':').next()?; + (!local.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"_:-.".contains(&b))).then(|| local.to_string()) +} + +/// A DescribeFeatureType can expose a candidate without declaring a unique constraint. +/// Use the sole required scalar property, and check its values at page boundaries. +fn wfs_schema_order(url: &str, bytes: &[u8]) -> Option { + const XSD: &str = "http://www.w3.org/2001/XMLSchema"; + let name = wfs_type_name(url)?; + let doc = + crate::xml::parse(std::str::from_utf8(bytes).ok()?, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok()?; + let root = doc.root_element(); + if !root.has_tag_name((XSD, "schema")) { + return None; + } + let layer = children(&root, "element").find(|n| n.has_tag_name((XSD, "element")) && n.attribute("name") == Some(name.as_str()))?; + let ty = match layer.attribute("type") { + Some(ty) => { + let ty = ty.rsplit(':').next()?; + children(&root, "complexType").find(|n| n.has_tag_name((XSD, "complexType")) && n.attribute("name") == Some(ty))? + } + None => child(&layer, "complexType")?, + }; + let seq = child(&ty, "sequence").or_else(|| child(&child(&child(&ty, "complexContent")?, "extension")?, "sequence"))?; + let mut keys = children(&seq, "element").filter(|n| { + n.has_tag_name((XSD, "element")) + && n.attribute("minOccurs").unwrap_or("1") == "1" + && n.attribute("maxOccurs").unwrap_or("1") == "1" + && matches!(n.attribute("nillable"), None | Some("false" | "0")) + && n.attribute("type").is_some_and(|ty| { + let (prefix, ty) = ty.split_once(':').map_or((None, ty), |(p, t)| (Some(p), t)); + n.lookup_namespace_uri(prefix) == Some(XSD) + && matches!(ty, "ID" | "string" | "integer" | "int" | "long" | "short" | "unsignedInt" | "unsignedLong") + }) + }); + let key = keys.next()?.attribute("name")?; + (keys.next().is_none() && !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))) + .then(|| key.to_string()) +} + +/// A tie cut by a page boundary can repeat or skip rows when the server sorts again. +fn wfs_page_last_key(features: &[Box], key: &str, last: Option<&str>) -> Option { + #[derive(serde::Deserialize)] + struct Properties<'a> { + #[serde(borrow)] + properties: std::collections::BTreeMap, + } + let sort_value = |feature: &RawValue| { + let properties = serde_json::from_str::>(feature.get()).ok()?.properties; + let value = properties.get(key)?.get(); + match value.as_bytes().first()? { + b'"' => serde_json::from_str::(value).ok(), + b'-' | b'0'..=b'9' => Some(value.to_string()), + _ => None, + } + }; + let first = sort_value(features.first()?)?; + if last == Some(first.as_str()) { + return None; + } + sort_value(features.last()?) +} + /// The total from a bounded WFS hits response; unknown counts and exception reports aren't totals. fn wfs_matched(bytes: &[u8]) -> Option { let text = std::str::from_utf8(bytes).ok()?; @@ -3908,6 +4010,7 @@ enum Phase { unidentified: std::collections::HashSet, overlap: bool, duplicates: usize, + order: WfsOrder, }, /// An OGC API or WFS page, retaining the largest reported legacy total across the chain. Linked { total: Option }, @@ -3928,6 +4031,19 @@ enum Phase { }, } +/// WFS offsets normally use the service's default order. On a rejection, try one schema +/// and restart in its order while retaining the original first page until the new one lands. +#[derive(Debug)] +enum WfsOrder { + Original, + Describe, + /// No last value until the first sorted page replaces the original. + Sorted { + key: String, + last: Option, + }, +} + /// A feature collection page's members other than its features (an object), and its features /// as their JSON text; `None` when it is JSON but not a feature collection, an error when it can't /// be read (as when it nests deeper than [`MAX_DEPTH`]). @@ -4013,7 +4129,8 @@ fn first_mark(page: &crate::esripbf::Page) -> Option { /// /// Any other address is fetched as it is. An OGC API or WFS page leads to the next by its `next` /// link. A WFS request without a next link uses a hits count and STARTINDEX pages (WFS 2.0). -/// Legacy WFS without links warns when its requested MAXFEATURES limit is reached. +/// If the first unsorted offset is rejected, it can retry from the start, sorted by a field +/// from the layer's schema. Legacy WFS without links warns when its requested MAXFEATURES limit is reached. /// /// The pages' features end up in one collection, with the first page's other members and /// without its paging ones. A first page that leads nowhere is done at once, unchanged (and @@ -4085,7 +4202,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option, max: usize, paging: Option bool { - matches!(self.phase, Phase::Describe { .. }) + matches!(self.phase, Phase::Describe { .. } | Phase::WfsOffsets { order: WfsOrder::Describe, .. }) } /// Leaves time for smaller-page retries within a blocking reader's total deadline. @@ -4260,7 +4375,7 @@ impl Pages { let mut ids = std::collections::HashSet::new(); self.features.retain(|f| feature_id(f).is_none_or(|id| ids.insert(id))); let duplicates = offset.saturating_sub(self.features.len()); - self.next = wfs_page_url(&self.url, Some(offset), offset.min(self.max)); + self.next = wfs_page_url(&self.url, Some(offset), offset.min(self.max), None); self.phase = Phase::WfsOffsets { matched, offset, @@ -4269,9 +4384,36 @@ impl Pages { unidentified: self.features.iter().filter_map(|f| unidentified_hash(f)).collect(), overlap: false, duplicates, + order: WfsOrder::Original, }; return self.advance(); } + if let Phase::WfsOffsets { size, offset, order, .. } = &mut self.phase { + if matches!(order, WfsOrder::Describe) { + let key = answer.ok().and_then(|bytes| wfs_schema_order(&self.url, &bytes)); + let Some(key) = key else { + return self.stop("the feature description gave no usable sort key; the rest aren't read".into()); + }; + *size = (*size).min(FEATURE_LIMIT); + let next = wfs_page_url(&self.url, Some(0), *size, Some(&key)); + *order = WfsOrder::Sorted { key, last: None }; + self.from = std::mem::replace(&mut self.next, next); + return self.advance(); + } + // The first offset can be refused by a server without a natural order. User-provided + // sorting is never replaced, and later failures don't restart a partially read layer. + if matches!(order, WfsOrder::Original) + && *offset == *size + && query_value(&self.url, "SORTBY").is_none() + && let Err(error) = &answer + && page_error_status(error) == Some(400) + && let Some(next) = wfs_schema_url(&self.url) + { + *order = WfsOrder::Describe; + self.from = std::mem::replace(&mut self.next, next); + return self.advance(); + } + } if let Phase::Describe { pbf } = self.phase { // Read once, whatever its size: the service's error may be as long as a description. let read: Result = answer.and_then(|b| { @@ -4347,12 +4489,16 @@ impl Pages { }; } let read = self.features.len(); - let (page, mut more) = match answer.and_then(|b| split_page(&b)) { + let restart = matches!(self.phase, Phase::WfsOffsets { order: WfsOrder::Sorted { last: None, .. }, .. }); + let (mut page, mut more) = match answer.and_then(|b| split_page(&b)) { Ok(Some(page)) => page, + Ok(None) if restart => return self.stop("the first sorted page isn't a feature collection; the rest aren't read".into()), Ok(None) => return self.stop(format!("the page after feature {read} isn't a feature collection; the rest aren't read")), Err(e) => { let why = if arcgis { self.page_failure(&e) + } else if restart { + format!("the first sorted page couldn't be read ({e}); the rest aren't read") } else { format!("the page after feature {read} couldn't be read ({e}); the rest aren't read") }; @@ -4360,11 +4506,30 @@ impl Pages { } }; let following = match &mut self.phase { - Phase::WfsOffsets { matched, offset, size, ids, unidentified, overlap, duplicates } => { + Phase::WfsOffsets { matched, offset, size, ids, unidentified, overlap, duplicates, order } => { let returned = more.len(); if returned == 0 { return self.stop("the WFS sent an empty page before its reported total; the rest aren't read".into()); } + let key = match order { + WfsOrder::Sorted { key, last } => { + let Some(end) = wfs_page_last_key(&more, key, last.as_deref()) else { + return self.stop("a sorted page boundary had a missing or repeated sort value; the rest aren't read".into()); + }; + if last.replace(end).is_none() { + // Offsets must count one order from the start. Drop the old first + // page only after a usable replacement has landed. + self.features.clear(); + self.doc = std::mem::take(&mut page); + ids.clear(); + unidentified.clear(); + *offset = 0; + *duplicates = 0; + } + Some(key.as_str()) + } + _ => None, + }; let hashes: Vec<_> = more.iter().filter_map(|f| unidentified_hash(f)).collect(); *overlap |= hashes.iter().any(|h| unidentified.contains(h)); unidentified.extend(hashes); @@ -4397,7 +4562,7 @@ impl Pages { } return self.finish(None); } - Some(wfs_page_url(&self.url, Some(*offset), *size)) + Some(wfs_page_url(&self.url, Some(*offset), *size, key)) } Phase::Offsets { size, order, start, first, .. } => { // A server that doesn't honour `resultOffset` sends its first page again. @@ -4433,7 +4598,7 @@ impl Pages { None if matches!(self.phase, Phase::Linked { .. }) && is_wfs_query(&self.url) => { // A next-link chain can end at a server cap too; verify the accumulated total. self.from = self.url.clone(); - self.next = wfs_page_url(&self.url, None, 0); + self.next = wfs_page_url(&self.url, None, 0, None); self.phase = Phase::WfsHits; self.advance() } @@ -4578,7 +4743,14 @@ impl Pages { /// query fetched as it is when none was. fn stop(mut self, note: String) -> Step { let note = match self.phase { - Phase::WfsOffsets { matched, .. } => format!("{} of {matched} WFS features read: {note}", self.features.len()), + Phase::WfsOffsets { matched, offset, ref order, .. } => { + let read = self.features.len(); + if matches!(order, WfsOrder::Describe | WfsOrder::Sorted { last: None, .. }) { + format!("{read} of {matched} WFS features read: the page after feature {offset} couldn't be read (HTTP 400); {note}") + } else { + format!("{read} of {matched} WFS features read: {note}") + } + } Phase::WfsHits => format!("{} WFS features read: {note}", self.features.len()), _ => note, }; @@ -6574,6 +6746,94 @@ mod tests { 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() { + let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads&COUNT=50000"; + let first = br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":"9"}},{"id":"roads.tmp-2","properties":{"record_number":"2"}}]}"#; + for last in ["9", "2"] { + let mut requests = Vec::new(); + let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { + let offset = query_value(next, "STARTINDEX"); + let order = query_value(next, "SORTBY"); + requests.push((query_value(next, "REQUEST").unwrap().to_string(), offset.map(str::to_owned), order.map(str::to_owned))); + match (query_value(next, "REQUEST"), offset, order) { + (Some("DescribeFeatureType"), None, None) => Ok(br#" + + + + + + "#.to_vec()), + (_, 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(serde_json::to_vec(&serde_json::json!({ + "features": [{"id": "roads.tmp-9", "properties": {"record_number": last}}] + })).unwrap()), + _ => 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(); + if last == "9" { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{requests:?}"); + assert_eq!(note, None); + } else { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2"], "{requests:?}"); + let note = note.unwrap(); + assert!(note.contains("2 of 3 WFS features read") && note.contains("repeated sort value"), "{note}"); + } + } + } + + /// The caller's sort stays in the feature requests, and hits never add an inferred sort. + #[test] + fn wfs_page_url_preserves_the_callers_sort_and_selection() { + let url = "https://x.org/wfs?REQUEST=GetFeature&soRtBy=NAME%20D&COUNT=50000&OUTPUTFORMAT=json&BBOX=1,2,3,4&token=t"; + let page = wfs_page_url(url, Some(42), 3, Some("record_number")); + assert_eq!( + page, + "https://x.org/wfs?REQUEST=GetFeature&soRtBy=NAME%20D&OUTPUTFORMAT=json&BBOX=1,2,3,4&token=t&STARTINDEX=42&COUNT=3" + ); + let hit = wfs_page_url(url, None, 0, Some("record_number")); + assert_eq!(hit, "https://x.org/wfs?REQUEST=GetFeature&soRtBy=NAME%20D&BBOX=1,2,3,4&token=t&RESULTTYPE=hits"); + } + + /// A rejected offset with no unambiguous sort field returns the original first page. + #[test] + fn wfs_offset_sort_without_a_key_keeps_the_original_read() { + let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=ns:roads&COUNT=50000&OUTPUTFORMAT=json&BBOX=1,2,3,4&map=roads"; + let first = br#"{"features":[{"id":"roads.1"},{"id":"roads.2"}]}"#; + let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { + if query_value(next, "REQUEST") == Some("DescribeFeatureType") { + assert_eq!(query_value(next, "TYPENAMES"), Some("ns:roads")); + assert_eq!(query_value(next, "map"), Some("roads")); + assert!(query_value(next, "BBOX").is_none()); + assert!(query_value(next, "OUTPUTFORMAT").is_none()); + return Ok(br#" + + + + + "# + .to_vec()); + } + assert_eq!(query_value(next, "BBOX"), Some("1,2,3,4")); + assert!(query_value(next, "SORTBY").is_none()); + if query_value(next, "RESULTTYPE") == Some("hits") { + Ok(br#""#.to_vec()) + } else { + assert_eq!(query_value(next, "STARTINDEX"), Some("2")); + Err("HTTP 400".into()) + } + }); + let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(doc["features"], serde_json::from_slice::(first).unwrap()["features"]); + let note = note.unwrap(); + assert!(note.contains("2 of 3 WFS features read") && note.contains("HTTP 400") && note.contains("no usable sort key"), "{note}"); + } + /// Explicit count windows, below and above the generated request size, do not fetch more. #[test] fn wfs_explicit_count_windows_do_not_page() { diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 33474ca3fc..fbb0fa0415 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -765,6 +765,7 @@ fn download_layer_with( Step::Fetch(pages) => pages, }; let describing = pages.describing(); + let before_features = describing && pages.read() == 0; let allowed = previous.as_ref().map_or_else(|| address::check(pages.next_url(), None), |origin| origin.check(pages.next_url())); let answer = allowed.and_then(|()| { let wait = until.saturating_duration_since(std::time::Instant::now()); @@ -792,8 +793,9 @@ fn download_layer_with( Ok(page) }); step = (*pages).land(answer); - // Nor their time: the features have all of it from when the description is in. - if describing { + // A description before the features leaves their full budget. A WFS description + // fetched after a rejected offset shares the existing deadline. + if before_features { until = std::time::Instant::now() + cache::BLOCKING_TIMEOUT; if let Step::Fetch(pages) = &mut step { drawing = pages.take_drawing_info(); From 2969b840510a2fbd44e350318175ec269c827335 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:02:04 -0600 Subject: [PATCH 2/3] fix(data): harden WFS sorted offset retries --- crates/data/src/ogc.rs | 254 +++++++++++++++++++++++-------- crates/engine/src/cmd/service.rs | 4 +- docs/user-guide/data-formats.md | 2 +- 3 files changed, 194 insertions(+), 66 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index e359ab6a58..c56affa814 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3679,6 +3679,25 @@ pub(crate) fn arcgis_error_text(v: &serde_json::Value) -> Option { Some(format!("service error: {code}: {message}")) } +/// An optional detail for a page notice. URL paths can hold keys, so only known status +/// codes and fixed address-policy reasons are repeated from an error that contains a URL. +fn page_error_detail(error: &str) -> String { + if error.contains("://") { + if let Some(status) = page_error_status(error) { + return format!(" (HTTP {status})"); + } + // These are the fixed reasons from the fetcher's reach check. Use the literal, never + // any part of the surrounding error returned by a fetch. + return ["that address is never fetched", "a document on the web can't point into the local network"] + .into_iter() + .find(|&reason| error.strip_suffix(reason).is_some_and(|prefix| prefix.ends_with(": "))) + .map_or_else(String::new, |reason| format!(" ({reason})")); + } + let mut error = crate::diagnostics::redact(error); + crate::diagnostics::cut_with_ellipsis(&mut error, MAX_REASON); + format!(" ({error})") +} + /// Reads only transport status prefixes or our own service-error prefix, never a number in a URL. fn page_error_status(error: &str) -> Option { let error = error.trim(); @@ -3817,6 +3836,8 @@ fn wfs_type_name(url: &str) -> Option { fn wfs_schema_order(url: &str, bytes: &[u8]) -> Option { const XSD: &str = "http://www.w3.org/2001/XMLSchema"; let name = wfs_type_name(url)?; + // Only one type's schema is needed. A dense 4 MiB document could allocate far more as a + // parsed tree, while the first feature page is still in memory. let doc = crate::xml::parse(std::str::from_utf8(bytes).ok()?, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok()?; let root = doc.root_element(); @@ -3848,8 +3869,37 @@ fn wfs_schema_order(url: &str, bytes: &[u8]) -> Option { .then(|| key.to_string()) } +#[derive(Debug, PartialEq, Eq)] +enum WfsSortValue { + Text(String), + Number { negative: bool, digits: String, exponent: i64 }, +} + +impl WfsSortValue { + /// Normalizes a raw JSON number to significant digits times a power of ten without rounding. + fn number(value: &str) -> Option { + let (mantissa, exponent) = match value.split_once(['e', 'E']) { + Some((mantissa, exponent)) => (mantissa, exponent.parse::().ok()?), + None => (value, 0), + }; + let negative = mantissa.starts_with('-'); + let mantissa = mantissa.trim_start_matches('-'); + let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let digits = format!("{whole}{fraction}"); + let digits = digits.trim_start_matches('0'); + if digits.is_empty() { + return Some(Self::Number { negative: false, digits: "0".into(), exponent: 0 }); + } + let significant = digits.trim_end_matches('0'); + let trailing = i64::try_from(digits.len() - significant.len()).ok()?; + let decimals = i64::try_from(fraction.len()).ok()?; + let exponent = exponent.checked_add(trailing - decimals)?; + Some(Self::Number { negative, digits: significant.into(), exponent }) + } +} + /// A tie cut by a page boundary can repeat or skip rows when the server sorts again. -fn wfs_page_last_key(features: &[Box], key: &str, last: Option<&str>) -> Option { +fn wfs_page_last_key(features: &[Box], key: &str, last: Option<&WfsSortValue>) -> Option { #[derive(serde::Deserialize)] struct Properties<'a> { #[serde(borrow)] @@ -3859,13 +3909,14 @@ fn wfs_page_last_key(features: &[Box], key: &str, last: Option<&str>) let properties = serde_json::from_str::>(feature.get()).ok()?.properties; let value = properties.get(key)?.get(); match value.as_bytes().first()? { - b'"' => serde_json::from_str::(value).ok(), - b'-' | b'0'..=b'9' => Some(value.to_string()), + // Some stores ignore case or trailing whitespace when sorting text. + b'"' => serde_json::from_str::(value).ok().map(|text| WfsSortValue::Text(text.trim_end().to_ascii_lowercase())), + b'-' | b'0'..=b'9' => WfsSortValue::number(value), _ => None, } }; let first = sort_value(features.first()?)?; - if last == Some(first.as_str()) { + if last == Some(&first) { return None; } sort_value(features.last()?) @@ -4036,11 +4087,14 @@ enum Phase { #[derive(Debug)] enum WfsOrder { Original, - Describe, + Describe { + refusal: String, + }, /// No last value until the first sorted page replaces the original. Sorted { key: String, - last: Option, + last: Option, + refusal: String, }, } @@ -4244,7 +4298,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option bool { - matches!(self.phase, Phase::Describe { .. } | Phase::WfsOffsets { order: WfsOrder::Describe, .. }) + matches!(self.phase, Phase::Describe { .. } | Phase::WfsOffsets { order: WfsOrder::Describe { .. }, .. }) } /// Leaves time for smaller-page retries within a blocking reader's total deadline. @@ -4337,27 +4391,13 @@ impl Pages { /// Applies one answer, retrying only failures a smaller query can plausibly fix. fn land_page(mut self, answer: Result, String>) -> Step { if matches!(self.phase, Phase::WfsHits) { - // Why the request failed is kept, so the notice says why completeness is unknown. let matched = match answer { - Ok(b) => wfs_matched(&b).ok_or(None), - // An error holding an address isn't repeated: `redact` keeps its path, which can - // hold a key. - Err(e) => Err(Some(e).filter(|e| !e.contains("://"))), + Ok(b) => wfs_matched(&b).ok_or_else(String::new), + Err(e) => Err(page_error_detail(&e)), }; let matched = match matched { Ok(matched) => matched, - Err(why) => { - // Without the credentials an address in the error may hold, and not all of a - // long one. - let why = why - .map(|e| { - let mut e = crate::diagnostics::redact(&e); - crate::diagnostics::cut_with_ellipsis(&mut e, MAX_REASON); - format!(" ({e})") - }) - .unwrap_or_default(); - return self.stop(format!("the WFS total couldn't be read{why}; the features received may be incomplete")); - } + Err(why) => return self.stop(format!("the WFS total couldn't be read{why}; the features received may be incomplete")), }; let offset = self.features.len(); if offset > self.max { @@ -4389,14 +4429,22 @@ impl Pages { return self.advance(); } if let Phase::WfsOffsets { size, offset, order, .. } = &mut self.phase { - if matches!(order, WfsOrder::Describe) { - let key = answer.ok().and_then(|bytes| wfs_schema_order(&self.url, &bytes)); - let Some(key) = key else { + if let WfsOrder::Describe { refusal } = order { + let bytes = match answer { + Ok(bytes) => bytes, + Err(e) => { + let why = page_error_detail(&e); + return self.stop(format!("the feature description couldn't be read{why}; the rest aren't read")); + } + }; + let Some(key) = wfs_schema_order(&self.url, &bytes) else { return self.stop("the feature description gave no usable sort key; the rest aren't read".into()); }; + // A server can send more than requested. Keep the sorted requests within our + // usual page size even if the original response was larger. *size = (*size).min(FEATURE_LIMIT); let next = wfs_page_url(&self.url, Some(0), *size, Some(&key)); - *order = WfsOrder::Sorted { key, last: None }; + *order = WfsOrder::Sorted { key, last: None, refusal: std::mem::take(refusal) }; self.from = std::mem::replace(&mut self.next, next); return self.advance(); } @@ -4409,7 +4457,7 @@ impl Pages { && page_error_status(error) == Some(400) && let Some(next) = wfs_schema_url(&self.url) { - *order = WfsOrder::Describe; + *order = WfsOrder::Describe { refusal: page_error_detail(error) }; self.from = std::mem::replace(&mut self.next, next); return self.advance(); } @@ -4498,9 +4546,9 @@ impl Pages { let why = if arcgis { self.page_failure(&e) } else if restart { - format!("the first sorted page couldn't be read ({e}); the rest aren't read") + format!("the first sorted page couldn't be read{}; the rest aren't read", page_error_detail(&e)) } else { - format!("the page after feature {read} couldn't be read ({e}); the rest aren't read") + format!("the page after feature {read} couldn't be read{}; the rest aren't read", page_error_detail(&e)) }; return self.stop(why); } @@ -4512,9 +4560,14 @@ impl Pages { return self.stop("the WFS sent an empty page before its reported total; the rest aren't read".into()); } let key = match order { - WfsOrder::Sorted { key, last } => { - let Some(end) = wfs_page_last_key(&more, key, last.as_deref()) else { - return self.stop("a sorted page boundary had a missing or repeated sort value; the rest aren't read".into()); + WfsOrder::Sorted { key, last, .. } => { + let Some(end) = wfs_page_last_key(&more, key, last.as_ref()) else { + let why = if restart { + "the first sorted page had a missing or unusable sort value" + } else { + "a sorted page boundary had a missing, unusable or repeated sort value" + }; + return self.stop(format!("{why}; the rest aren't read")); }; if last.replace(end).is_none() { // Offsets must count one order from the start. Drop the old first @@ -4743,12 +4796,13 @@ impl Pages { /// query fetched as it is when none was. fn stop(mut self, note: String) -> Step { let note = match self.phase { - Phase::WfsOffsets { matched, offset, ref order, .. } => { + Phase::WfsOffsets { matched, ref order, .. } => { let read = self.features.len(); - if matches!(order, WfsOrder::Describe | WfsOrder::Sorted { last: None, .. }) { - format!("{read} of {matched} WFS features read: the page after feature {offset} couldn't be read (HTTP 400); {note}") - } else { - format!("{read} of {matched} WFS features read: {note}") + match order { + WfsOrder::Describe { refusal } | WfsOrder::Sorted { last: None, refusal, .. } => { + format!("{read} of {matched} WFS features read: the page after feature {read} couldn't be read{refusal}; {note}") + } + _ => format!("{read} of {matched} WFS features read: {note}"), } } Phase::WfsHits => format!("{} WFS features read: {note}", self.features.len()), @@ -6746,47 +6800,121 @@ mod tests { assert_eq!(note, None); } + const WFS_SORT_SCHEMA: &[u8] = br#" + + + + + + "#; + /// 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() { let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads&COUNT=50000"; let first = br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":"9"}},{"id":"roads.tmp-2","properties":{"record_number":"2"}}]}"#; - for last in ["9", "2"] { - let mut requests = Vec::new(); + for (end, next_key, tie) in [ + ("2", "3", false), + ("2", "2.0", true), + ("2", r#""2""#, false), + (r#""a""#, r#""A ""#, true), + ("9007199254740992", "9007199254740993.0", false), + ("9007199254740993", "9.007199254740993E15", true), + ] { let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { let offset = query_value(next, "STARTINDEX"); let order = query_value(next, "SORTBY"); - requests.push((query_value(next, "REQUEST").unwrap().to_string(), offset.map(str::to_owned), order.map(str::to_owned))); match (query_value(next, "REQUEST"), offset, order) { - (Some("DescribeFeatureType"), None, None) => Ok(br#" - - - - - - "#.to_vec()), - (_, 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(serde_json::to_vec(&serde_json::json!({ - "features": [{"id": "roads.tmp-9", "properties": {"record_number": last}}] - })).unwrap()), - _ => panic!("unexpected request: {next}"), - } + (Some("DescribeFeatureType"), None, None) => Ok(WFS_SORT_SCHEMA.to_vec()), + (_, None, None) => Ok(br#""#.to_vec()), + (_, Some("2"), None) => Err("http status: 400".into()), + (_, Some("0"), Some("record_number")) => Ok(format!( + r#"{{"features":[{{"id":"roads.tmp-1","properties":{{"record_number":1}}}},{{"id":"roads.tmp-2","properties":{{"record_number":{end}}}}}]}}"# + ).into_bytes()), + (_, Some("2"), Some("record_number")) => Ok(format!( + r#"{{"features":[{{"id":"roads.tmp-9","properties":{{"record_number":{next_key}}}}}]}}"# + ).into_bytes()), + _ => 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(); - if last == "9" { - assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{requests:?}"); - assert_eq!(note, None); - } else { - assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2"], "{requests:?}"); + if tie { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2"], "{end} / {next_key}"); let note = note.unwrap(); assert!(note.contains("2 of 3 WFS features read") && note.contains("repeated sort value"), "{note}"); + } else { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{end} / {next_key}"); + assert_eq!(note, None); } } } + /// A failed description or unusable replacement leaves the original rows and explains the short read. + #[test] + fn wfs_failed_sorted_restart_keeps_original_features() { + 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.9"},{"id":"roads.2"},{"id":"roads.2"}]}"#; + for (description_error, sorted_page, why) in [ + (Some("the request timed out"), Ok(""), "the feature description couldn't be read (the request timed out)"), + (None, Err("http status: 500"), "the first sorted page couldn't be read (http status: 500)"), + (None, Ok("[]"), "the first sorted page isn't a feature collection"), + (None, Ok(r#"{"features":[{"id":"roads.1","properties":{}}]}"#), "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;"), + ] { + 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) => { + description_error.map_or_else(|| Ok(WFS_SORT_SCHEMA.to_vec()), |e| Err(e.into())) + } + (_, None, None) => Ok(br#""#.to_vec()), + (_, Some("3"), None) => Err("http status: 400: no natural order".into()), + (_, Some("0"), Some("record_number")) if description_error.is_none() => { + sorted_page.map(|body| body.as_bytes().to_vec()).map_err(str::to_owned) + } + _ => 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.9", "roads.2"], "{why}"); + let note = note.unwrap(); + assert!(note.contains("2 of 4 WFS features read"), "{note}"); + assert!(note.contains(why), "{note}"); + assert!(note.contains("the page after feature 2 couldn't be read (http status: 400: no natural order)"), "{note}"); + assert!(!note.contains("private-path"), "{note}"); + } + } + + /// Authentication and transport failures on the first offset end the read without asking for the schema. + #[test] + fn wfs_does_not_retry_unrelated_offset_failures() { + 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.1"}]}"#; + for (error, why) in [ + ("http status: 401", " (http status: 401)"), + ("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", ""), + ("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| { + if query_value(next, "RESULTTYPE") == Some("hits") { + return Ok(br#""#.to_vec()); + } + assert_eq!(query_value(next, "REQUEST"), Some("GetFeature")); + assert_eq!(query_value(next, "STARTINDEX"), Some("1")); + assert_eq!(query_value(next, "SORTBY"), None); + Err(error.into()) + }); + let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(doc["features"], serde_json::json!([{"id":"roads.1"}])); + let note = note.unwrap(); + assert!(note.contains(&format!("1 of 2 WFS features read: the page after feature 1 couldn't be read{why};")), "{note}"); + } + } + /// The caller's sort stays in the feature requests, and hits never add an inferred sort. #[test] fn wfs_page_url_preserves_the_callers_sort_and_selection() { diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index fbb0fa0415..7732e0d3ed 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -769,8 +769,8 @@ fn download_layer_with( let allowed = previous.as_ref().map_or_else(|| address::check(pages.next_url(), None), |origin| origin.check(pages.next_url())); let answer = allowed.and_then(|()| { let wait = until.saturating_duration_since(std::time::Instant::now()); - // A layer's description is small: one that hangs is given up on, and its features - // asked for as they are. + // A description gets a short wait. On timeout WFS keeps its first page and stops; + // other services proceed without the schema. let wait = if describing { wait.min(DESCRIPTION_TIMEOUT) } else { pages.page_timeout().map_or(wait, |timeout| wait.min(timeout)) }; // Said as a timeout, so its error says how to add the layer instead. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 04344f7b15..4750a9f4ef 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -340,7 +340,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | --- | --- | --- | | WMS 1.1.1 / 1.3.0 | Named layers offered in Web Mercator or in a coordinate system RustGIS can transform (an EPSG code, CRS:84) | A layer of GetMap images (PNG when the service offers it, else JPEG): one picture of the view, or tiles; see [One picture of the view, or tiles](#one-picture-of-the-view-or-tiles) and [Services in other coordinate systems](#services-in-other-coordinate-systems) | | WMTS | Layers whose tile matrix set is Web Mercator's pyramid, or a tile matrix set in a coordinate system RustGIS can transform | A tile layer from the tile template (or KVP GetTile) | -| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice | +| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice. If the first offset is rejected with HTTP 400 and the schema identifies one candidate sort field, WFS 2.0 retries from the start in that order and gives a notice if the same sort value spans two pages | | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | | WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in the coverage's own projected system when RustGIS reads it, else in EPSG:4326, at most 2048 pixels on a side | From fd66a48cff2032d2d38c32101dce00d5c624adce Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 17:32:38 -0600 Subject: [PATCH 3/3] fix(data): preserve WFS rows during sorted retries --- apps/rustgis-web/src/web.rs | 18 +- crates/data/src/diagnostics.rs | 13 ++ crates/data/src/ogc.rs | 387 +++++++++++++++++++++++++------ crates/engine/src/cmd/service.rs | 69 +++++- crates/tiles/src/address.rs | 13 +- crates/tiles/src/cache.rs | 8 +- docs/user-guide/data-formats.md | 2 +- 7 files changed, 414 insertions(+), 96 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 5185b55eac..da7d37cddb 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -5,7 +5,13 @@ use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::rc::Rc; -use rustgis_ui_egui::rustgis_engine::{data::diagnostics::Capture, sources::message_with_address}; +use rustgis_ui_egui::rustgis_engine::{ + data::diagnostics::{ + Capture, + fetch_reason::{BROWSER_UNREACHABLE, LARGER_THAN, STALLED}, + }, + sources::message_with_address, +}; use rustgis_ui_egui::{FindChords, Inbox, RustGisApp, Services, Slot}; use crate::parts::Notes; @@ -850,7 +856,7 @@ async fn fetch_reached( let err = |e: wasm_bindgen::JsValue| { if authenticated { "the browser couldn't process the authenticated request".to_string() } else { format!("{e:?}") } }; - let stalled = || format!("nothing came in {} seconds", STALL_MS / 1000); + let stalled = || format!("{STALLED} {} seconds", STALL_MS / 1000); let result = async { // A refused fetch is an opaque TypeError ("Failed to fetch") by design. Keep its message // only on requests without a login: even a browser's error may repeat credentials. @@ -867,7 +873,7 @@ async fn fetch_reached( e.dyn_ref::().map(|e| String::from(e.message())).unwrap_or_else(|| err(e)) }; format!( - "the browser couldn't reach it (offline, blocked by a browser extension or the network, or the server doesn't accept requests from web pages): {why}" + "{BROWSER_UNREACHABLE} (offline, blocked by a browser extension or the network, or the server doesn't accept requests from web pages): {why}" ) })? .dyn_into() @@ -930,7 +936,7 @@ async fn fetch_reached( if whole_tail.is_some() { return Err(message_with_address(&url, cache::NO_RANGES)); } - return Err(format!("larger than {max} bytes")); + return Err(format!("{LARGER_THAN} {max} bytes")); } let at = bytes.len(); bytes.resize(at + n, 0); @@ -1020,7 +1026,7 @@ async fn post_json( let result = async { let resp: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise) .await - .map_err(|_| "the browser couldn't reach it (offline, or the server doesn't accept requests from web pages)".to_string())? + .map_err(|_| format!("{BROWSER_UNREACHABLE} (offline, or the server doesn't accept requests from web pages)"))? .dyn_into() .map_err(err)?; diagnostics.answered(resp.status()); @@ -1121,7 +1127,7 @@ async fn head( let result = async { let resp: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise) .await - .map_err(|_| "the browser couldn't reach it (offline, or the server doesn't accept requests from web pages)".to_string())? + .map_err(|_| format!("{BROWSER_UNREACHABLE} (offline, or the server doesn't accept requests from web pages)"))? .dyn_into() .map_err(err)?; diagnostics.answered(resp.status()); diff --git a/crates/data/src/diagnostics.rs b/crates/data/src/diagnostics.rs index 8460a0f636..3896912f6b 100644 --- a/crates/data/src/diagnostics.rs +++ b/crates/data/src/diagnostics.rs @@ -804,6 +804,19 @@ pub fn address_in_message(address: &str) -> String { shown } +/// Fixed fetch failure text that paging notices may retain from an address-bearing error. +pub mod fetch_reason { + pub const BROWSER_UNREACHABLE: &str = "the browser couldn't reach it"; + pub const STALLED: &str = "nothing came in"; + pub const LARGER_THAN: &str = "larger than"; + pub const PAGES_TIMED_OUT: &str = "the pages timed out"; + pub const ADDRESS_HAS_SPACES: &str = "the address has spaces in it"; + pub const HTTP_ONLY: &str = "only http:// and https:// addresses are fetched"; + pub const DOWNGRADE_REDIRECT: &str = "a redirect from https to http"; + pub const FORBIDDEN_ADDRESS: &str = "that address is never fetched"; + pub const PUBLIC_TO_LOCAL: &str = "a document on the web can't point into the local network"; +} + /// Composes a known address and its failure reason without exposing credentials or swallowing /// the reason after a secret query. Exact address occurrences (including unescaped whitespace) /// are sanitized first; unrelated URLs and credential fields still use conservative [`redact`]. diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index c56affa814..3fc590b399 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -3679,19 +3679,26 @@ pub(crate) fn arcgis_error_text(v: &serde_json::Value) -> Option { Some(format!("service error: {code}: {message}")) } -/// An optional detail for a page notice. URL paths can hold keys, so only known status -/// codes and fixed address-policy reasons are repeated from an error that contains a URL. +/// 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. fn page_error_detail(error: &str) -> String { + use crate::diagnostics::fetch_reason::*; if error.contains("://") { if let Some(status) = page_error_status(error) { return format!(" (HTTP {status})"); } - // These are the fixed reasons from the fetcher's reach check. Use the literal, never - // any part of the surrounding error returned by a fetch. - return ["that address is never fetched", "a document on the web can't point into the local network"] - .into_iter() - .find(|&reason| error.strip_suffix(reason).is_some_and(|prefix| prefix.ends_with(": "))) - .map_or_else(String::new, |reason| format!(" ({reason})")); + let reasons = [PAGES_TIMED_OUT, ADDRESS_HAS_SPACES, HTTP_ONLY, DOWNGRADE_REDIRECT, FORBIDDEN_ADDRESS, PUBLIC_TO_LOCAL]; + // The transport can prefix a URL and append details such as a size or browser error. + // Only emit a literal from the allowlist, even if the surrounding text is hostile. + let reason = + std::iter::once(error).chain(error.match_indices(": ").filter_map(|(at, sep)| error.get(at + sep.len()..))).find_map(|tail| { + reasons.into_iter().find(|&reason| tail == reason).or_else(|| { + [(BROWSER_UNREACHABLE, " ("), (STALLED, " "), (LARGER_THAN, " ")] + .into_iter() + .find_map(|(reason, separator)| tail.strip_prefix(reason)?.starts_with(separator).then_some(reason)) + }) + }); + return reason.map_or_else(String::new, |reason| format!(" ({reason})")); } let mut error = crate::diagnostics::redact(error); crate::diagnostics::cut_with_ellipsis(&mut error, MAX_REASON); @@ -3718,7 +3725,7 @@ fn smaller_page_may_help(error: &str) -> bool { return status == 408 || (500..600).contains(&status); } let error = error.to_ascii_lowercase(); - error != "the pages timed out" + error != crate::diagnostics::fetch_reason::PAGES_TIMED_OUT && !error.contains("cancelled") && ["timeout", "timed out", "connection reset", "connection aborted", "unexpected eof"].iter().any(|s| error.contains(s)) } @@ -3833,14 +3840,9 @@ fn wfs_type_name(url: &str) -> Option { /// A DescribeFeatureType can expose a candidate without declaring a unique constraint. /// Use the sole required scalar property, and check its values at page boundaries. -fn wfs_schema_order(url: &str, bytes: &[u8]) -> Option { +fn wfs_schema_order(url: &str, root: Node<'_, '_>) -> Option { const XSD: &str = "http://www.w3.org/2001/XMLSchema"; let name = wfs_type_name(url)?; - // Only one type's schema is needed. A dense 4 MiB document could allocate far more as a - // parsed tree, while the first feature page is still in memory. - let doc = - crate::xml::parse(std::str::from_utf8(bytes).ok()?, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok()?; - let root = doc.root_element(); if !root.has_tag_name((XSD, "schema")) { return None; } @@ -3876,6 +3878,27 @@ enum WfsSortValue { } impl WfsSortValue { + /// Restrict text to ASCII letters and digits. Collations can ignore accents, width, + /// punctuation and spaces, and may equate digit runs that differ only in leading zeroes. + /// Folding case and digit runs covers those ties. A server can still define its own collation. + fn text(value: &str) -> Option { + let value = serde_json::from_str::(value).ok()?; + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + let mut normalized = String::with_capacity(value.len()); + for run in value.as_bytes().chunk_by(|a, b| a.is_ascii_digit() == b.is_ascii_digit()) { + let run = std::str::from_utf8(run).ok()?; + let trimmed = run.trim_start_matches('0'); + if trimmed.is_empty() { + normalized.push('0'); + } else { + normalized.extend(trimmed.chars().map(|c| c.to_ascii_lowercase())); + } + } + Some(Self::Text(normalized)) + } + /// Normalizes a raw JSON number to significant digits times a power of ten without rounding. fn number(value: &str) -> Option { let (mantissa, exponent) = match value.split_once(['e', 'E']) { @@ -3909,14 +3932,15 @@ fn wfs_page_last_key(features: &[Box], key: &str, last: Option<&WfsSor let properties = serde_json::from_str::>(feature.get()).ok()?.properties; let value = properties.get(key)?.get(); match value.as_bytes().first()? { - // Some stores ignore case or trailing whitespace when sorting text. - b'"' => serde_json::from_str::(value).ok().map(|text| WfsSortValue::Text(text.trim_end().to_ascii_lowercase())), + b'"' => WfsSortValue::text(value), b'-' | b'0'..=b'9' => WfsSortValue::number(value), _ => None, } }; let first = sort_value(features.first()?)?; - if last == Some(&first) { + // The schema names one scalar type. A number and a string may sort as the same + // value after server-side coercion, so stop when the types change at a boundary. + if last.is_some_and(|last| last == &first || std::mem::discriminant(last) != std::mem::discriminant(&first)) { return None; } sort_value(features.last()?) @@ -4083,14 +4107,15 @@ enum Phase { } /// WFS offsets normally use the service's default order. On a rejection, try one schema -/// and restart in its order while retaining the original first page until the new one lands. +/// and restart in its order while retaining the original rows until a usable replacement lands. #[derive(Debug)] enum WfsOrder { + FirstOffset, Original, Describe { refusal: String, }, - /// No last value until the first sorted page replaces the original. + /// No last value until the first sorted page replaces the original rows. Sorted { key: String, last: Option, @@ -4298,7 +4323,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option bytes, @@ -4437,7 +4462,14 @@ impl Pages { return self.stop(format!("the feature description couldn't be read{why}; the rest aren't read")); } }; - let Some(key) = wfs_schema_order(&self.url, &bytes) else { + // Bound the XML tree while the original feature rows are still held. + let Some(schema) = std::str::from_utf8(&bytes) + .ok() + .and_then(|text| crate::xml::parse(text, ParsingOptions { nodes_limit: 4096, ..ParsingOptions::default() }).ok()) + else { + return self.stop("the feature description couldn't be parsed or is too large; the rest aren't read".into()); + }; + let Some(key) = wfs_schema_order(&self.url, schema.root_element()) else { return self.stop("the feature description gave no usable sort key; the rest aren't read".into()); }; // A server can send more than requested. Keep the sorted requests within our @@ -4448,18 +4480,19 @@ impl Pages { self.from = std::mem::replace(&mut self.next, next); return self.advance(); } - // The first offset can be refused by a server without a natural order. User-provided - // sorting is never replaced, and later failures don't restart a partially read layer. - if matches!(order, WfsOrder::Original) - && *offset == *size - && query_value(&self.url, "SORTBY").is_none() - && let Err(error) = &answer - && page_error_status(error) == Some(400) - && let Some(next) = wfs_schema_url(&self.url) - { - *order = WfsOrder::Describe { refusal: page_error_detail(error) }; - self.from = std::mem::replace(&mut self.next, next); - return self.advance(); + // A rejected first offset can mean there is no natural order. Explicit sorting + // and every offset after the first are handled without a restart. + if matches!(order, WfsOrder::FirstOffset) { + *order = WfsOrder::Original; + if query_value(&self.url, "SORTBY").is_none() + && let Err(error) = &answer + && page_error_status(error) == Some(400) + && let Some(next) = wfs_schema_url(&self.url) + { + *order = WfsOrder::Describe { refusal: page_error_detail(error) }; + self.from = std::mem::replace(&mut self.next, next); + return self.advance(); + } } } if let Phase::Describe { pbf } = self.phase { @@ -4559,34 +4592,47 @@ impl Pages { if returned == 0 { return self.stop("the WFS sent an empty page before its reported total; the rest aren't read".into()); } - let key = match order { - WfsOrder::Sorted { key, last, .. } => { - let Some(end) = wfs_page_last_key(&more, key, last.as_ref()) else { - let why = if restart { - "the first sorted page had a missing or unusable sort value" - } else { - "a sorted page boundary had a missing, unusable or repeated sort value" - }; - return self.stop(format!("{why}; the rest aren't read")); + let sorted = if let WfsOrder::Sorted { key, last, .. } = order { + let Some(end) = wfs_page_last_key(&more, key, last.as_ref()) else { + let why = if restart { + "the first sorted page had a missing or unusable sort value" + } else { + "a sorted page boundary had a missing, unusable or repeated sort value" }; - if last.replace(end).is_none() { - // Offsets must count one order from the start. Drop the old first - // page only after a usable replacement has landed. - self.features.clear(); - self.doc = std::mem::take(&mut page); - ids.clear(); - unidentified.clear(); - *offset = 0; - *duplicates = 0; - } - Some(key.as_str()) - } - _ => None, + return self.stop(format!("{why}; the rest aren't read")); + }; + Some((key.as_str(), last, end)) + } else { + None }; + if restart { + // Offsets count one order from the start. A replacement must preserve the + // number of rows already kept, even if every later sorted request fails. + // Count ids within the sorted page independently of the unsorted prefix. + let mut replacement_ids = std::collections::HashSet::new(); + more.retain(|f| feature_id(f).is_none_or(|id| replacement_ids.insert(id))); + if more.len() < read { + let distinct = more.len(); + return self.stop(format!( + "the first sorted page returned only {distinct} distinct feature(s); the original rows are kept" + )); + } + self.features.clear(); + self.doc = std::mem::take(&mut page); + *ids = replacement_ids; + unidentified.clear(); + *offset = 0; + *duplicates = 0; + } else { + more.retain(|f| feature_id(f).is_none_or(|id| ids.insert(id))); + } + let key = sorted.map(|(key, last, end)| { + *last = Some(end); + key + }); let hashes: Vec<_> = more.iter().filter_map(|f| unidentified_hash(f)).collect(); *overlap |= hashes.iter().any(|h| unidentified.contains(h)); unidentified.extend(hashes); - more.retain(|f| feature_id(f).is_none_or(|id| ids.insert(id))); *duplicates = duplicates.saturating_add(returned.saturating_sub(more.len())); if more.is_empty() { return self.stop("the WFS repeated an earlier page instead of advancing; the rest aren't read".into()); @@ -6813,13 +6859,31 @@ mod tests { fn wfs_restarts_rejected_offset_pages_in_schema_order() { let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads&COUNT=50000"; let first = br#"{"features":[{"id":"roads.tmp-9","properties":{"record_number":"9"}},{"id":"roads.tmp-2","properties":{"record_number":"2"}}]}"#; - for (end, next_key, tie) in [ - ("2", "3", false), - ("2", "2.0", true), - ("2", r#""2""#, false), - (r#""a""#, r#""A ""#, true), - ("9007199254740992", "9007199254740993.0", false), - ("9007199254740993", "9.007199254740993E15", true), + enum Outcome { + Complete, + StopAtBoundary, + KeepOriginal, + } + use Outcome::*; + for (end, next_key, outcome) in [ + ("2", "3", Complete), + ("2", "2.0", StopAtBoundary), + ("2", r#""2""#, StopAtBoundary), + (r#""2""#, "2.0", StopAtBoundary), + (r#""É""#, r#""é""#, KeepOriginal), + (r#""e""#, r#""é""#, StopAtBoundary), + (r#""é""#, r#""e\u0301""#, KeepOriginal), + (r#""ss""#, r#""ß""#, StopAtBoundary), + (r#""i""#, r#""İ""#, StopAtBoundary), + (r#""a""#, r#""a""#, StopAtBoundary), + (r#""a""#, r#""a\u0000""#, StopAtBoundary), + (r#""a""#, r#"" a""#, StopAtBoundary), + (r#""ab""#, r#""a-b""#, StopAtBoundary), + (r#""a010b""#, r#""A10B""#, StopAtBoundary), + (r#""a00b""#, r#""a0b""#, StopAtBoundary), + (r#""a""#, r#""A ""#, StopAtBoundary), + ("9007199254740992", "9007199254740993.0", Complete), + ("9007199254740993", "9.007199254740993E15", StopAtBoundary), ] { let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { let offset = query_value(next, "STARTINDEX"); @@ -6839,13 +6903,25 @@ mod tests { }); 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(); - if tie { - assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2"], "{end} / {next_key}"); - let note = note.unwrap(); - assert!(note.contains("2 of 3 WFS features read") && note.contains("repeated sort value"), "{note}"); - } else { - assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{end} / {next_key}"); - assert_eq!(note, None); + match outcome { + Complete => { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2", "roads.tmp-9"], "{end} / {next_key}"); + assert_eq!(note, None); + } + StopAtBoundary => { + assert_eq!(ids, ["roads.tmp-1", "roads.tmp-2"], "{end} / {next_key}"); + let note = note.unwrap(); + assert!(note.contains("2 of 3 WFS features read") && note.contains("repeated sort value"), "{note}"); + } + KeepOriginal => { + assert_eq!(ids, ["roads.tmp-9", "roads.tmp-2"], "{end} / {next_key}"); + let note = note.unwrap(); + assert!( + note.contains("2 of 3 WFS features read") + && note.contains("first sorted page had a missing or unusable sort value"), + "{note}" + ); + } } } } @@ -6860,6 +6936,13 @@ mod tests { (None, Err("http status: 500"), "the first sorted page couldn't be read (http status: 500)"), (None, Ok("[]"), "the first sorted page isn't a feature collection"), (None, Ok(r#"{"features":[{"id":"roads.1","properties":{}}]}"#), "the first sorted page had a missing or unusable sort value"), + ( + None, + Ok( + r#"{"features":[{"id":"roads.1","properties":{"record_number":"a"}},{"id":"roads.2","properties":{"record_number":"É"}}]}"#, + ), + "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;"), ] { let (bytes, note) = join_pages(url, first.to_vec(), 100, |next| { @@ -6886,6 +6969,141 @@ mod tests { } } + /// A sorted restart cannot trade an accumulated prefix for a shorter partial read. + #[test] + fn wfs_sorted_restart_preserves_the_original_row_count() { + const URL: &str = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads&COUNT=50000"; + for (pages, count, sorted_count, later_error) in [ + (8, 1_000, 1_000, None), + (8, 1_000, 1_000, Some("HTTP 400")), + (1, 60_000, 50_000, None), + (1, 1_000, 10, Some("HTTP 500")), + (1, 1_000, 1_000, Some("cancelled while it was read")), + ] { + let original = pages * count; + let mut asked = Vec::new(); + let (bytes, note) = super::join_pages(URL, 100_000, |url| { + let param = |key| query_value(url, key); + if param("REQUEST") == Some("DescribeFeatureType") { + return Ok(WFS_SORT_SCHEMA.to_vec()); + } + if param("RESULTTYPE") == Some("hits") { + return Ok(br#""#.to_vec()); + } + let (start, size, source) = if let Some(offset) = param("STARTINDEX") { + if param("SORTBY").is_none() { + assert_eq!(offset.parse::().unwrap(), original); + return Err("HTTP 400".into()); + } + asked.push((offset.parse::().unwrap(), param("COUNT").unwrap().parse::().unwrap())); + if offset != "0" + && let Some(error) = later_error + { + return Err(error.into()); + } + (offset.parse::().unwrap(), sorted_count, "sorted") + } else { + (param("cursor").map_or(0, |v| v.parse().unwrap()), count, "original") + }; + let features: Vec<_> = (start..start + size) + .map(|id| serde_json::json!({"id": format!("{source}.{id}"), "properties":{"record_number":"same"}})) + .collect(); + let mut body = serde_json::json!({"features":features}); + if source == "original" && start + size < original { + body["links"] = serde_json::json!([{"rel":"next","href":format!("{URL}&cursor={}",start + size)}]); + } + Ok(body.to_string().into_bytes()) + }) + .unwrap(); + let replaced = sorted_count == original; + let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let features = doc["features"].as_array().unwrap(); + assert_eq!(features.len(), original, "{pages} x {count}, sorted {sorted_count}, {later_error:?}"); + assert_eq!(features[0]["id"], if replaced { "sorted.0" } else { "original.0" }); + assert_eq!(asked[0], (0, original.min(50_000))); + let note = note.unwrap(); + assert!(note.contains(&format!("{original} of 90000 WFS features read")), "{note}"); + if replaced { + assert_eq!(asked.len(), 2); + assert!(note.contains("cancelled while it was read"), "{note}"); + } else { + assert_eq!(asked.len(), 1); + assert!(note.contains("the first sorted page returned only"), "{note}"); + } + } + } + + /// Compare the rows after deduplication on both sides of the replacement. + #[test] + fn wfs_sorted_restart_counts_distinct_service_ids() { + let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads"; + let first = br#"{"features":[{"id":"old.1"},{"id":"old.1"}]}"#.to_vec(); + for new in [["new.1", "new.1"], ["new.1", "new.2"]] { + let (bytes, note) = super::join_pages(url, 4, |next| { + match (query_value(next, "REQUEST"), query_value(next, "STARTINDEX"), query_value(next, "cursor")) { + (Some("DescribeFeatureType"), None, _) => Ok(WFS_SORT_SCHEMA.to_vec()), + (_, None, Some("2")) => Ok(br#"{"features":[{"id":"old.2"}]}"#.to_vec()), + (_, None, _) if query_value(next, "RESULTTYPE") == Some("hits") => { + Ok(br#""#.to_vec()) + } + (_, None, _) => { + let mut body: serde_json::Value = serde_json::from_slice(&first).unwrap(); + body["links"] = serde_json::json!([{"rel":"next","href":format!("{url}&cursor=2")}]); + Ok(body.to_string().into_bytes()) + } + (_, Some("3"), _) => Err("HTTP 400".into()), + (_, Some("0"), _) => Ok(serde_json::json!({"features":[ + {"id":new[0],"properties":{"record_number":"a"}}, + {"id":new[1],"properties":{"record_number":"b"}} + ]}) + .to_string() + .into_bytes()), + (_, Some("2"), _) if new[0] != new[1] => Ok(br#"{"features":[ + {"id":"new.2","properties":{"record_number":"c"}}, + {"id":"new.3","properties":{"record_number":"d"}} + ]}"# + .to_vec()), + (_, Some("2"), _) => Err("HTTP 400".into()), + _ => panic!("unexpected request: {next}"), + } + }) + .unwrap(); + 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(); + let note = note.unwrap(); + if new[0] == new[1] { + assert_eq!(ids, ["old.1", "old.2"]); + assert!(note.contains("the first sorted page returned only 1 distinct feature"), "{note}"); + } else { + assert_eq!(ids, ["new.1", "new.2", "new.3"]); + assert!(note.contains("paging row limit"), "{note}"); + } + assert!(note.contains("1 repeated service-id rows ignored"), "{note}"); + } + } + + #[test] + fn wfs_unreadable_schema_has_its_own_notice() { + let url = "https://wfs.example.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads"; + let first = br#"{"features":[{"id":"roads.1"}]}"#; + let too_many_nodes = format!("{}", "".repeat(4096)); + for schema in [" Ok(schema.as_bytes().to_vec()), + (_, None) => Ok(br#""#.to_vec()), + (_, Some("1")) => Err("HTTP 400".into()), + _ => panic!("unexpected request: {next}"), + }); + assert_eq!(serde_json::from_slice::(&bytes).unwrap()["features"], serde_json::json!([{"id":"roads.1"}])); + let note = note.unwrap(); + assert!( + note.contains("1 of 2 WFS features read") && note.contains("the feature description couldn't be parsed or is too large"), + "{note}" + ); + } + } + /// Authentication and transport failures on the first offset end the read without asking for the schema. #[test] fn wfs_does_not_retry_unrelated_offset_failures() { @@ -6915,6 +7133,29 @@ mod tests { } } + #[test] + fn wfs_address_bearing_page_errors_keep_only_fixed_reasons() { + for (text, reason) in [ + ( + "the browser couldn't reach it (offline, blocked by a browser extension or the network, or the server doesn't accept requests from web pages): the authenticated request failed", + "the browser couldn't reach it", + ), + ("nothing came in 15 seconds", "nothing came in"), + ("larger than 6000 bytes", "larger than"), + ("the pages timed out", "the pages timed out"), + ("the address has spaces in it", "the address has spaces in it"), + ("only http:// and https:// addresses are fetched", "only http:// and https:// addresses are fetched"), + ("a redirect from https to http", "a redirect from https to http"), + ("that address is never fetched", "that address is never fetched"), + ("a document on the web can't point into the local network", "a document on the web can't point into the local network"), + ] { + let error = crate::diagnostics::message_with_address("https://example.invalid/private-path?token=synthetic", text); + 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"), ""); + } + /// The caller's sort stays in the feature requests, and hits never add an inferred sort. #[test] fn wfs_page_url_preserves_the_callers_sort_and_selection() { diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 7732e0d3ed..0095db6dc1 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -602,10 +602,11 @@ pub(crate) fn bounds_of(v: Option<&Value>) -> Result, String> { /// layer's pages, its description read first, see [`begin`](rustgis_data::ogc::begin)): at most /// `max` bytes of features. The description waits at most /// [`DESCRIPTION_TIMEOUT`](rustgis_data::ogc::DESCRIPTION_TIMEOUT) and takes at most -/// [`DESCRIPTION_MAX`](rustgis_data::ogc::DESCRIPTION_MAX) bytes, apart; the features -/// [`BLOCKING_TIMEOUT`](crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT) in all after it -/// (75 s at most). A page is fetched only where the page before it may point. With `public` (a -/// layer a document read from the internet lists), only internet addresses are fetched. +/// [`DESCRIPTION_MAX`](rustgis_data::ogc::DESCRIPTION_MAX) bytes. Feature requests share +/// [`BLOCKING_TIMEOUT`](crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT). An ArcGIS +/// description before the features has its own deadline (75 s at most in total). A WFS description +/// after a rejected offset shares the running feature deadline. A page is fetched only where +/// the page before it may point. With `public`, only internet addresses are fetched. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usize, public: bool) -> Result, String> { // Its features alone: what they are used for (a task's input, an export) has no layer to draw @@ -769,13 +770,13 @@ fn download_layer_with( let allowed = previous.as_ref().map_or_else(|| address::check(pages.next_url(), None), |origin| origin.check(pages.next_url())); let answer = allowed.and_then(|()| { let wait = until.saturating_duration_since(std::time::Instant::now()); - // A description gets a short wait. On timeout WFS keeps its first page and stops; + // A description gets a short wait. On timeout WFS keeps the rows already read; // other services proceed without the schema. let wait = if describing { wait.min(DESCRIPTION_TIMEOUT) } else { pages.page_timeout().map_or(wait, |timeout| wait.min(timeout)) }; // Said as a timeout, so its error says how to add the layer instead. if wait.is_zero() { - return Err("the pages timed out".to_string()); + return Err(rustgis_data::diagnostics::fetch_reason::PAGES_TIMED_OUT.into()); } // A description has a small budget of its own. let budget = if describing { left.min(DESCRIPTION_MAX) } else { left }; @@ -2360,6 +2361,62 @@ mod tests { } } + /// The native reader charges the sorted retry to the same byte budget. An exhausted + /// budget must still leave at least the rows that survived the original offset refusal. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn wfs_native_byte_budget_preserves_original_row_count() { + use crate::render::rustgis_tiles::{address::Origin, cache::Fetched}; + let root = "https://gis.example.invalid/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads"; + let first = br#"{"features":[{"id":"old.1"},{"id":"old.2"},{"id":"old.3"}]}"#; + let hits = br#""#; + let schema = br#""#; + for count in [1, 3] { + let mut sorted = json!({"features": (1..=count) + .map(|key| json!({"id":format!("sorted.{key}"),"properties":{"k":key}})) + .collect::>() }) + .to_string() + .into_bytes(); + sorted.resize(sorted.len().max(schema.len()), b' '); + let max = first.len() + hits.len() + sorted.len(); + let mut s = Session::new(crate::Project::default()); + let mut exhausted = false; + let result = download_layer_with(&mut s, "roads", root, max, false, |url, budget, _, ceiling| { + let bytes = if url.contains("REQUEST=DescribeFeatureType") { + assert!(budget <= rustgis_data::ogc::DESCRIPTION_MAX); + schema.to_vec() + } else if url.contains("RESULTTYPE=hits") { + hits.to_vec() + } else if url.contains("STARTINDEX=0") { + assert_eq!(budget, sorted.len()); + sorted.clone() + } else if url.contains("SORTBY=k") { + assert_eq!(budget, 0); + exhausted = true; + return Err("the pages are larger than RustGIS downloads".into()); + } else if url.contains("STARTINDEX=3") { + return Err("HTTP 400".into()); + } else { + assert_eq!(url, root); + first.to_vec() + }; + Ok(Fetched { bytes, origin: Origin::named(url).narrow_reach(ceiling) }) + }); + let (Downloaded::Bytes(bytes), _) = result.unwrap() else { panic!("GeoJSON pages") }; + let doc: Value = serde_json::from_slice(&bytes).unwrap(); + let ids: Vec<_> = doc["features"].as_array().unwrap().iter().map(|f| f["id"].as_str().unwrap()).collect(); + if count == 1 { + assert_eq!(ids, ["old.1", "old.2", "old.3"]); + assert!(!exhausted); + } else { + assert_eq!(ids, ["sorted.1", "sorted.2", "sorted.3"]); + assert!(exhausted); + } + let note = &s.notices_since(0)[0].text; + assert!(note.contains("3 of 4 WFS features read"), "{note}"); + } + } + /// A document a service links to is fetched within the reach its linking document's fetch was /// observed at: from a landing page on the internet, only the internet, however the links are /// spelled; from one on this computer or the local network, wherever they point (a self-hosted diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index 8e9dad4ba5..c9fbdd8b07 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -285,18 +285,17 @@ pub fn check_reach(url: &str, ceiling: Reach) -> Result<(), String> { if crate::s3::is_s3(url) { return check_reach(&crate::s3::https_url(url)?, ceiling); } + use rustgis_data::diagnostics::{fetch_reason::*, message_with_address}; let lower = url.to_ascii_lowercase(); if !(lower.starts_with("https://") || lower.starts_with("http://")) { - return Err(rustgis_data::diagnostics::message_with_address(url, "only http:// and https:// addresses are fetched")); + return Err(message_with_address(url, HTTP_ONLY)); } if url.chars().any(|c| c.is_whitespace() || c.is_control()) { - return Err(rustgis_data::diagnostics::message_with_address(url, "the address has spaces in it")); + return Err(message_with_address(url, ADDRESS_HAS_SPACES)); } match reach(url) { - Reach::Forbidden => Err(rustgis_data::diagnostics::message_with_address(url, "that address is never fetched")), - Reach::Local if ceiling == Reach::Public => { - Err(rustgis_data::diagnostics::message_with_address(url, "a document on the web can't point into the local network")) - } + Reach::Forbidden => Err(message_with_address(url, FORBIDDEN_ADDRESS)), + Reach::Local if ceiling == Reach::Public => Err(message_with_address(url, PUBLIC_TO_LOCAL)), _ => Ok(()), } } @@ -306,7 +305,7 @@ pub fn check_reach(url: &str, ceiling: Reach) -> Result<(), String> { pub fn is_refusal(error: &str) -> bool { [ "can't point into the local network", - "that address is never fetched", + rustgis_data::diagnostics::fetch_reason::FORBIDDEN_ADDRESS, "that peer address is never fetched", "resolves to this computer or the local network", ] diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index e59970d5b0..41dae6d261 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -2578,6 +2578,8 @@ mod native { use std::collections::HashMap; use std::sync::{Condvar, Mutex, OnceLock}; + use rustgis_data::diagnostics::fetch_reason::DOWNGRADE_REDIRECT; + #[cfg(test)] use super::DoneDetailed; use super::{Capture, DROPPED, Done, Fetched, FetchedDone, MAX_BYTES}; @@ -3224,7 +3226,7 @@ mod native { let next = crate::template::join(&at, header("location").ok_or("a redirect with no Location")?); Origin { url: at.clone(), reach: ceiling }.check(&next)?; if crate::address::is_https(&at) && !crate::address::is_https(&next) { - return Err(rustgis_data::diagnostics::message_with_address(&next, "a redirect from https to http").into()); + return Err(rustgis_data::diagnostics::message_with_address(&next, DOWNGRADE_REDIRECT).into()); } same_origin &= crate::logins::origin(&next) == first_origin; at = next; @@ -3849,9 +3851,9 @@ mod native { // Never from HTTPS down to plain HTTP, however either scheme is written. if crate::address::is_https(&at) && !crate::address::is_https(&next) { return Err(if carried_login { - "a redirect from https to http".into() + DOWNGRADE_REDIRECT.into() } else { - rustgis_data::diagnostics::message_with_address(&next, "a redirect from https to http").into() + rustgis_data::diagnostics::message_with_address(&next, DOWNGRADE_REDIRECT).into() }); } redirects += 1; diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4750a9f4ef..06ddf17f1e 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -340,7 +340,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | --- | --- | --- | | WMS 1.1.1 / 1.3.0 | Named layers offered in Web Mercator or in a coordinate system RustGIS can transform (an EPSG code, CRS:84) | A layer of GetMap images (PNG when the service offers it, else JPEG): one picture of the view, or tiles; see [One picture of the view, or tiles](#one-picture-of-the-view-or-tiles) and [Services in other coordinate systems](#services-in-other-coordinate-systems) | | WMTS | Layers whose tile matrix set is Web Mercator's pyramid, or a tile matrix set in a coordinate system RustGIS can transform | A tile layer from the tile template (or KVP GetTile) | -| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice. If the first offset is rejected with HTTP 400 and the schema identifies one candidate sort field, WFS 2.0 retries from the start in that order and gives a notice if the same sort value spans two pages | +| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice. If the first offset is rejected with HTTP 400 and the schema identifies one candidate sort field, WFS 2.0 retries from the start in that order. It keeps the original rows unless the first sorted page has usable boundary values and at least as many distinct features. The read stops with a notice if a boundary value is missing or unusable, or if a sort value spans two pages | | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | | WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in the coverage's own projected system when RustGIS reads it, else in EPSG:4326, at most 2048 pixels on a side |