diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index cab56f356f..c9974a153b 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2479,6 +2479,15 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { legends: Vec::new(), }); } else { + if let Some((root, id)) = b.rsplit_once('/') + && id.parse::().is_ok() + && ["/mapserver", "/featureserver"].iter().any(|s| root.to_ascii_lowercase().ends_with(s)) + { + let root = crate::diagnostics::address_in_message(root); + return Err(format!( + "this is layer '{id}': list its service with service.layers using url '{root}', then use service.add with that url and layer '{id}'" + )); + } return Err("an ArcGIS address, but not a FeatureServer, MapServer, ImageServer or VectorTileServer".into()); } let left = v.get("layers").and_then(|l| l.as_array()).map_or(0, Vec::len).saturating_sub(MAX_LISTED_LAYERS); @@ -3188,14 +3197,68 @@ fn supports_pbf(layer: &serde_json::Value) -> bool { /// An ArcGIS query asking for its answer as `format` (`f`, in any case), in place of the format /// it named; its fragment kept, as [`with_query`] keeps it. fn with_format(query: &str, format: &str) -> String { + with_query_value(query, "f", format) +} + +/// Replaces one query value in any case, preserving opaque settings, login bindings and fragments. +fn with_query_value(query: &str, key: &str, value: &str) -> String { + if let Ok(Some(bound)) = crate::login_address::parse(query) { + return crate::login_address::inherit(query, &with_query_value(bound.url, key, value)); + } let (url, fragment) = query.split_once('#').map_or((query, None), |(u, f)| (u, Some(f))); let (base, q) = url.split_once('?').unwrap_or((url, "")); let kept: Vec<&str> = - q.split('&').filter(|kv| !kv.is_empty() && !kv.split('=').next().is_some_and(|k| k.eq_ignore_ascii_case("f"))).collect(); - let asked = with_query(&with_query(base, &kept.join("&")), &format!("f={format}")); + q.split('&').filter(|kv| !kv.is_empty() && !kv.split('=').next().is_some_and(|k| k.eq_ignore_ascii_case(key))).collect(); + let asked = with_query(&with_query(base, &kept.join("&")), &format!("{key}={}", encode(value))); if let Some(f) = fragment { format!("{asked}#{f}") } else { asked } } +/// An ArcGIS feature query with its SQL where clause replaced as one encoded value. Other +/// service protocols return None, so a caller cannot silently ignore an unsupported filter. +pub fn features_where(query: &str, clause: &str) -> Option { + is_arcgis_query(query).then(|| with_query_value(query, "where", clause)) +} + +/// A bounded service error envelope, including those returned with HTTP 200 instead of 5xx. +/// Feature collections and binary pages are left to their own readers. +fn arcgis_page_error(bytes: &[u8]) -> Option { + if bytes.len() > EDGE { + return None; + } + let v: serde_json::Value = serde_json::from_slice(bytes).ok()?; + let error = v.get("error")?.as_object()?; + let code = error.get("code").and_then(serde_json::Value::as_u64).unwrap_or(0); + let message = error.get("message").and_then(serde_json::Value::as_str).unwrap_or("query refused"); + let mut message = crate::diagnostics::redact(message); + crate::diagnostics::cut_with_ellipsis(&mut message, MAX_REASON); + Some(format!("service error: {code}: {message}")) +} + +/// 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(); + let rest = + error.strip_prefix("http status: ").or_else(|| error.strip_prefix("HTTP ")).or_else(|| error.strip_prefix("service error: "))?; + let (code, after) = rest.split_at_checked(3)?; + (after.is_empty() || after.starts_with(':') || after.starts_with(" (retry after ")).then(|| code.parse().ok()).flatten() +} + +/// Size-sensitive failures only. Cancellation, exhausted read budgets, authorization and invalid +/// queries must not cause extra requests; an individual transport timeout leaves room to retry. +fn smaller_page_may_help(error: &str) -> bool { + // A requested wait isn't a size failure. + if error.contains(" (retry after ") { + return false; + } + if let Some(status) = page_error_status(error) { + return status == 408 || (500..600).contains(&status); + } + let error = error.to_ascii_lowercase(); + error != "the pages timed out" + && !error.contains("cancelled") + && ["timeout", "timed out", "connection reset", "connection aborted", "unexpected eof"].iter().any(|s| error.contains(s)) +} + /// The description of the layer an ArcGIS query reads (`…/FeatureServer/0?f=json`), with the /// query's token. fn arcgis_layer_url(query: &str) -> String { @@ -3401,7 +3464,17 @@ enum Phase { /// first feature (a server that ignores the offset sends it again), once it is read; until /// then `first` keeps the first page as it came, to fall back on (none: the address asked /// for is fetched as it is instead). `pbf`: the pages are asked for as protocol buffers. - Offsets { size: usize, order: Option, start: Option, first: Option>, pbf: bool }, + /// `smaller` counts failed page requests retried at a smaller size, for the final notice. + /// `fallback_size` lets a format fallback try the original size before shrinking anew. + Offsets { + size: usize, + order: Option, + start: Option, + first: Option>, + pbf: bool, + smaller: usize, + fallback_size: usize, + }, } /// A feature collection page's members other than its features (an object), and its features @@ -3555,7 +3628,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option Option { + matches!(self.phase, Phase::Offsets { size, .. } if size > 1).then_some(std::time::Duration::from_secs(10)) + } + /// How the ArcGIS layer being read says it is drawn: its description's `drawingInfo` (an /// object), once the description is read, and only the first time it is asked for. A reader /// takes it after landing the description, before the features are read. @@ -3653,6 +3732,16 @@ impl Pages { } } + /// Identifies a failed query without exposing its token or unbounded server text. + fn page_failure(&self, error: &str) -> String { + let layer = crate::diagnostics::address_in_message(&arcgis_layer_url(&self.url)); + let offset = query_value(&self.next, "resultOffset").and_then(|v| v.parse::().ok()).unwrap_or(self.read()); + let mut error = crate::diagnostics::redact(error); + crate::diagnostics::cut_with_ellipsis(&mut error, MAX_REASON); + format!("the page after feature {} couldn't be read ({error}); layer {layer}, offset {offset}; the rest aren't read", self.read()) + } + + /// 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. @@ -3713,12 +3802,43 @@ impl Pages { Some(ArcgisPaging { size: Some(size), order }) => { let page = arcgis_page_url(&self.url, 0, size, order.as_deref()); self.next = if pbf { with_format(&page, "pbf") } else { page }; - self.phase = Phase::Offsets { size, order, start: None, first: None, pbf }; + self.phase = Phase::Offsets { size, order, start: None, first: None, pbf, smaller: 0, fallback_size: size }; self.advance() } paging => self.ask_as_it_is(paging), }; } + let arcgis = is_arcgis_query(&self.url); + let answer = if arcgis { + answer.and_then(|bytes| match arcgis_page_error(&bytes) { + Some(error) => Err(error), + None => Ok(bytes), + }) + } else { + answer + }; + let read = self.read(); + if let Err(error) = &answer { + if smaller_page_may_help(error) + && let Phase::Offsets { size, order, pbf, smaller, .. } = &mut self.phase + && *size > 1 + { + *size = (*size / 2).max(1); + let page = arcgis_page_url(&self.url, read, *size, order.as_deref()); + self.from = self.next.clone(); + self.next = if *pbf { with_format(&page, "pbf") } else { page }; + *smaller += 1; + return self.advance(); + } + // A PBF refusal can be format-specific; try GeoJSON with the same clause first. + if arcgis + && page_error_status(error) == Some(400) + && !matches!(self.phase, Phase::Offsets { pbf: true, .. }) + && query_value(&self.url, "where").is_some_and(|w| !w.eq_ignore_ascii_case("1%3D1") && w != "1=1") + { + return Step::Failed(self.page_failure(&format!("the server rejected the query with its where clause: {error}"))); + } + } if matches!(self.phase, Phase::Offsets { pbf: true, .. }) { return self.land_pbf(answer); } @@ -3726,14 +3846,21 @@ impl Pages { let paging = paging.take(); return match answer { Ok(first) => read_first(&self.url, first, self.max, paging), - Err(e) => Step::Failed(e), + Err(e) => Step::Failed(if arcgis { self.page_failure(&e) } else { e }), }; } let read = self.features.len(); let (page, mut more) = match answer.and_then(|b| split_page(&b)) { Ok(Some(page)) => page, Ok(None) => return self.stop(format!("the page after feature {read} isn't a feature collection; the rest aren't read")), - Err(e) => return self.stop(format!("the page after feature {read} couldn't be read ({e}); the rest aren't read")), + Err(e) => { + let why = if arcgis { + self.page_failure(&e) + } else { + format!("the page after feature {read} couldn't be read ({e}); the rest aren't read") + }; + return self.stop(why); + } }; let following = match &mut self.phase { Phase::WfsOffsets { matched, offset, size, ids, unidentified, overlap, duplicates } => { @@ -3834,12 +3961,14 @@ impl Pages { let read = self.read(); // The features past the limit aren't read, so what they lost isn't counted. let room = self.max.saturating_sub(read); - let Phase::Offsets { size, order, pbf, .. } = &mut self.phase else { return self.finish(None) }; + let Phase::Offsets { size, order, pbf, fallback_size, .. } = &mut self.phase else { return self.finish(None) }; let page = answer.and_then(|bytes| crate::esripbf::read_page_within(&bytes, "query", room).map_err(|e| e.to_string())); let page = match page { Ok(page) => page, Err(e) if self.decoded.is_none() => { *pbf = false; + // A format-specific failure needn't force GeoJSON into single-feature pages. + *size = *fallback_size; // Said in a notice: without the credentials an address or a service's own error // message may hold, and not all of a long one. let mut why = crate::diagnostics::redact(&e); @@ -3852,7 +3981,10 @@ impl Pages { self.next = arcgis_page_url(&self.url, 0, *size, order.as_deref()); return self.advance(); } - Err(e) => return self.stop(format!("the page after feature {read} couldn't be read ({e}); the rest aren't read")), + Err(e) => { + let why = self.page_failure(&e); + return self.stop(why); + } }; self.join_page(page) } @@ -3991,6 +4123,17 @@ impl Pages { /// The pages' features in the first page's collection, without its paging members. fn finish(mut self, note: Option) -> Step { + let note = if let Phase::Offsets { smaller, .. } = &self.phase + && *smaller > 0 + { + let said = format!("{smaller} failed page request(s) retried with smaller pages"); + Some(match note { + Some(note) => format!("{note}; {said}"), + None => said, + }) + } else { + note + }; let note = if let Phase::WfsOffsets { duplicates, .. } = &self.phase && *duplicates > 0 { @@ -5404,10 +5547,11 @@ mod tests { if query_value(u, "f") == Some("pbf") { Err("http status: 500".into()) } else { json_page(u).ok_or_else(|| "404".to_string()) } }); let Step::Done(joined, Some(note)) = step else { panic!("{step:?}") }; - assert!(note.starts_with("its protocol buffer pages couldn't be read (") && note.ends_with("so it is read in GeoJSON"), "{note}"); + assert!(note.starts_with("its protocol buffer pages couldn't be read (") && note.contains("so it is read in GeoJSON"), "{note}"); let v: serde_json::Value = serde_json::from_slice(&joined).unwrap(); assert_eq!(v["features"].as_array().map(Vec::len), Some(5)); - assert!(asked.len() == 5 && asked[2..].iter().all(|u| query_value(u, "f") == Some("geojson")), "{asked:?}"); + assert!(asked.len() == 6 && asked[3..].iter().all(|u| query_value(u, "f") == Some("geojson")), "{asked:?}"); + assert!(asked[3..].iter().all(|u| query_value(u, "resultRecordCount") == Some("2")), "{asked:?}"); assert!(!asked.iter().any(|u| u == query), "{asked:?}"); assert!(note.contains("(http status: 500)"), "{note}"); // A long reason is said cut. @@ -5471,7 +5615,7 @@ mod tests { seen: std::collections::HashSet::new(), next: String::new(), from: String::new(), - phase: Phase::Offsets { size: 2, order: None, start: None, first: None, pbf: true }, + phase: Phase::Offsets { size: 2, order: None, start: None, first: None, pbf: true, smaller: 0, fallback_size: 2 }, decoded: None, decoded_bytes: 0, decoded_budget: max_decoded_bytes(), @@ -5680,7 +5824,8 @@ mod tests { let failed = super::join_pages(query, 100, |u| { if u.contains("resultOffset") || u == query { Err("http status: 500".into()) } else { answer(&mut Vec::new(), u) } }); - assert_eq!(failed, Err("http status: 500".into())); + let error = failed.unwrap_err(); + assert!(error.contains("FeatureServer/0") && error.contains("offset 0") && error.contains("http status: 500"), "{error}"); // The limit cuts it short, with a note. let answer = server(layer(r#", "maxRecordCount": 2"#)); let (joined, note) = join_pages(query, page(0, 2), 3, |u| answer(&mut Vec::new(), u)); @@ -5754,6 +5899,117 @@ mod tests { assert!(note.is_some_and(|n| n.contains("first 0 features"))); } + /// Large polygon pages may fail even below the advertised record limit. Retry the same + /// offset in either format, keep the smaller size, and report the reductions only when used. + #[test] + fn arcgis_pages_retry_at_smaller_sizes() { + use crate::esripbf::tests::page as pbf; + let query = "https://x.org/rest/services/P/MapServer/28/query?where=COUNTY%3D1&f=geojson&token=t"; + let description = br#"{"maxRecordCount":8,"objectIdField":"OBJECTID","supportedQueryFormats":"geoJSON,PBF", + "advancedQueryCapabilities":{"supportsPagination":true}}"#; + for binary in [false, true] { + for fails_at in [None, Some(0), Some(8)] { + let mut step = if binary { begin_with_pbf(query, 100) } else { begin(query, 100) }; + let mut asked = Vec::new(); + let (ids, note) = loop { + let Step::Fetch(pages) = step else { + break match step { + Step::Done(bytes, note) => { + let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + (v["features"].as_array().unwrap().iter().map(|f| f["id"].as_u64().unwrap()).collect::>(), note) + } + Step::Decoded(ds, _, note) => (ds.features.iter().map(|f| f.attrs[0].as_f64().unwrap() as u64).collect(), note), + other => panic!("{other:?}"), + }; + }; + if pages.describing() { + step = pages.land(Ok(description.to_vec())); + continue; + } + let url = pages.next_url(); + assert_eq!(query_value(url, "where"), Some("COUNTY%3D1")); + assert_eq!(query_value(url, "token"), Some("t")); + assert_eq!(query_value(url, "orderByFields"), Some("OBJECTID")); + let offset = query_value(url, "resultOffset").unwrap().parse::().unwrap(); + let size = query_value(url, "resultRecordCount").unwrap().parse::().unwrap(); + asked.push((offset, size)); + let answer = if fails_at.is_some_and(|at| offset >= at) && size > 2 { + Err(if size == 8 { + if fails_at == Some(8) { "timeout: global" } else { "http status: 500" } + } else { + "Connection reset by peer" + } + .into()) + } else { + let end = (offset + size).min(13); + let ids = (offset..end).collect::>(); + Ok(if binary { + pbf(&ids, end < 13, "OBJECTID") + } else { + serde_json::to_vec(&serde_json::json!({"type":"FeatureCollection", "exceededTransferLimit": end < 13, + "features": ids.iter().map(|id| serde_json::json!({"type":"Feature","id":id,"properties":{}})).collect::>() })).unwrap() + }) + }; + step = pages.land(answer); + }; + assert_eq!(ids, (0..13).collect::>(), "{binary}, {fails_at:?}: {asked:?}"); + if let Some(at) = fails_at { + assert!(asked.windows(3).any(|w| w == [(at, 8), (at, 4), (at, 2)]), "{asked:?}"); + let note = note.unwrap(); + assert!(note.contains("2") && note.contains("smaller pages"), "{note}"); + } else { + assert_eq!(note, None); + } + } + } + } + + /// Persistent failures stop at one feature, while authorization, cancellation and exhausted + /// budgets never shrink a page. Kept features still report the failed layer and offset. + #[test] + fn arcgis_retries_are_bounded_and_do_not_retry_read_limits() { + let query = "https://x.org/rest/services/P/MapServer/28/query?where=1%3D1&f=geojson"; + let description = br#"{"maxRecordCount":8,"advancedQueryCapabilities":{"supportsPagination":true}}"#; + let first = br#"{"type":"FeatureCollection","exceededTransferLimit":true,"features":[{"id":0},{"id":1}]}"#; + for (error, sizes) in [ + ("http status: 503", vec![8, 4, 2, 1]), + ("envelope", vec![8, 4, 2, 1]), + ("HTTP 403", vec![8]), + ("http status: 503 (retry after 30 s)", vec![8]), + ("cancelled while it was read", vec![8]), + ("the pages timed out", vec![8]), + ("the pages are larger than RustGIS downloads", vec![8]), + ] { + let mut asked = Vec::new(); + let (bytes, note) = super::join_pages(query, 100, |url| { + if !url.contains("/query") { + return Ok(description.to_vec()); + } + let offset = query_value(url, "resultOffset").unwrap().parse::().unwrap(); + if offset == 0 { + return Ok(first.to_vec()); + } + assert_eq!(offset, 2); + asked.push(query_value(url, "resultRecordCount").unwrap().parse::().unwrap()); + if error == "envelope" { Ok(br#"{"error":{"code":500,"message":"query failed"}}"#.to_vec()) } else { Err(error.into()) } + }) + .unwrap(); + assert_eq!(asked, sizes, "{error}"); + let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(doc["features"].as_array().unwrap().len(), 2); + let note = note.unwrap(); + assert!(note.contains("MapServer/28") && note.contains("offset 2"), "{note}"); + assert_eq!(note.contains("smaller pages"), sizes.len() > 1, "{note}"); + } + } + + #[test] + fn a_layer_address_says_which_service_to_list() { + let root = "https://hazards.fema.gov/arcgis/rest/services/public/NFHL/MapServer"; + let error = parse(&format!("{root}/21?f=json"), br#"{"currentVersion":11,"id":21,"name":"Flood"}"#).unwrap_err(); + assert!(error.contains(root) && error.contains("service.layers") && error.contains("21"), "{error}"); + } + /// An ArcGIS layer's description gives how it is drawn (its `drawingInfo`) once, to be taken /// before its features are read; one without it, or with something other than an object, /// gives none (#2080). diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 7a37cc4390..9359802c44 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -34,7 +34,7 @@ pub fn commands() -> Vec { r#"{"url": "a WMS, WMTS or WFS address (GetCapabilities is added), an OGC API collections address or landing page (its dataset tiles, supported styles and linked collections), or an ArcGIS FeatureServer, MapServer, ImageServer or VectorTileServer, or an ArcGIS services directory or folder (its folders and services, each listed by its own url)", "type"?: "wms"|"wmts"|"wfs"|"ogcapi"|"arcgis" (guessed from the address), "text"?: "the capabilities document, when already fetched", "documents"?: [{"url": "a discovered document address", "text": "its fetched JSON"}], "connection"?: "the saved web-service connection id whose login the requests use", "filter"?: "words a layer's title or name must all contain, in any case: every layer read is searched, not only those a listing shows, and the first 2000 that match are listed; what a listing says in a notice, a search says only in its notes"} → layers with source_url (with filter, total: the layers read, and matched: how many match), and next when supplied documents need another fetch"#, ), C::new("service.add", "Add Service Layer", "Home › Add", add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login"}"#, + r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "where"?: "an ArcGIS feature layer's SQL where clause (1=1 when absent); combined with bbox and kept by every page; rejected clauses give an error", "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login"}"#, ), C::new("service.coverage", "WCS Coverage Request", "Home › Add", coverage).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it)"#, @@ -548,7 +548,8 @@ pub(crate) fn download_layer(s: &mut Session, name: &str, url: &str, max: usize, 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. - let wait = if describing { wait.min(DESCRIPTION_TIMEOUT) } else { wait }; + 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()); @@ -1135,6 +1136,14 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis false, ); } + let where_clause = match p.get("where") { + None | Some(Value::Null) => None, + Some(Value::String(clause)) if !clause.trim().is_empty() => Some(clause.as_str()), + Some(_) => return Err("where must be a non-empty service SQL clause".into()), + }; + if where_clause.is_some() && !matches!(layer.offer, Offer::Features { .. }) { + return Err("where is only supported for ArcGIS feature layers".into()); + } let title = match (&time, asked) { (Some(t), Some(_)) => format!("{} {t}", layer.title), _ => layer.title.clone(), @@ -1322,6 +1331,10 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } } Offer::Features { url: items } => { + let filtered = where_clause + .map(|clause| rustgis_data::ogc::features_where(items, clause).ok_or("where is only supported for ArcGIS feature layers")) + .transpose()?; + let items = filtered.as_deref().unwrap_or(items); let area = features_area(s, p)?; let asked = area.and_then(|a| rustgis_data::ogc::features_in_area(items, a)); #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 62897f1c39..f3dc2af68e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20170,6 +20170,68 @@ fn arcgis_features_read_past_the_record_limit() { ); } +/// A where clause is encoded as one query value, combined with the area and kept by every +/// page. Omitting it retains the whole-layer query; a rejected clause fails without a layer. +#[test] +fn arcgis_service_add_where_filters_every_page_and_reports_rejection() { + use ogc_server::{Route, Server, arcgis_layer, arcgis_page}; + let path = "/arcgis/rest/services/P/MapServer/28"; + let rest = "&outFields=*&returnGeometry=true&outSR=4326&f=geojson"; + let filtered = "DFIRM_ID%3D%2747157C%27%20AND%20NOTE%3D%27A%26B%27"; + let area = "&geometry=-91,34,-89,36&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects"; + let query = |clause: &str, offset| { + let area = if clause == filtered { area } else { "" }; + let query = + if clause == "1%3D1" { format!("where={clause}{rest}") } else { format!("{}&where={clause}", rest.trim_start_matches('&')) }; + format!("{path}/query?{query}{area}&resultOffset={offset}&resultRecordCount=2&orderByFields=OBJECTID") + }; + let mut refused = Route::new(&query("bad_http", 0), "Invalid where clause"); + refused.status = 400; + let server = Server::new(vec![ + Route::new(path, &arcgis_layer(2, true)), + Route::new(&query("1%3D1", 0), &arcgis_page(&[0, 1], true)), + Route::new(&query("1%3D1", 2), &arcgis_page(&[2], false)), + Route::new(&query(filtered, 0), &arcgis_page(&[7, 8], true)), + Route::new(&query(filtered, 2), &arcgis_page(&[9], false)), + Route::new(&query("bad", 0), r#"{"error":{"code":400,"message":"Invalid where clause"}}"#), + refused, + ]); + let service = r#"{"currentVersion":11,"layers":[{"id":28,"name":"Flood"}]}"#; + let url = format!("{}/arcgis/rest/services/P/MapServer", server.base); + for clause in [None, Some("DFIRM_ID='47157C' AND NOTE='A&B'"), Some("bad"), Some("bad_http")] { + let mut session = Session::new(Project::default()); + let mut params = json!({"url":url,"layer":"28","text":service}); + if let Some(clause) = clause { + params["where"] = json!(clause); + if clause.starts_with("DFIRM_ID") { + params["bbox"] = json!([-91, 34, -89, 36]); + } + } + let result = session.run("service.add", ¶ms); + if clause.is_some_and(|clause| clause.starts_with("bad")) { + let error = result.unwrap_err(); + assert!(error.contains("where clause") && error.contains("rejected"), "{error}"); + assert!(session.map().layers.is_empty()); + } else { + assert_eq!(result.unwrap()["features"], 3); + let ids = session.map().layers[0].dataset.features.iter().map(|f| f.attrs[0].as_f64()).collect::>(); + let first = if clause.is_some() { 7.0 } else { 0.0 }; + assert_eq!(ids, [Some(first), Some(first + 1.0), Some(first + 2.0)]); + if clause.is_some() { + let source = session.map().layers[0].dataset.source.as_deref().unwrap(); + assert!(source.contains(&format!("where={filtered}")) && source.contains("geometry=-91,34,-89,36"), "{source}"); + } + } + } + let clauses = server + .requests() + .into_iter() + .filter(|r| r.path.ends_with("/query")) + .map(|r| r.query.iter().filter(|(k, _)| k == "where").map(|(_, v)| v.clone()).collect::>()) + .collect::>(); + assert_eq!(clauses, [vec!["1%3D1"], vec!["1%3D1"], vec![filtered], vec![filtered], vec!["bad"], vec!["bad_http"]]); +} + /// An ArcGIS layer whose description lists protocol buffers is read through service.add in `f=pbf` /// pages into one layer, known by its address; one whose first such page can't be read is read in /// GeoJSON pages instead (#1326). diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index baa5eb4713..6c65320283 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -515,15 +515,15 @@ pub(crate) fn read_pages(app: &mut RustGisApp, landed: Landed) { go_on(app, landed, rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD, step); } -/// An ArcGIS layer's description fetched in the background: at most `max` bytes, its download -/// given up on natively after [`ogc::DESCRIPTION_TIMEOUT`]. -fn fetch_description(url: &str, max: usize) -> Slot, String>> { +/// A bounded description or retryable feature page fetched off the frame. Native downloads +/// end at the timeout; the browser's late answer is discarded by the polling read. +fn fetch_within(url: &str, max: usize, timeout: std::time::Duration) -> Slot, String>> { let slot: Slot, String>> = Slot::default(); let land = slot.clone(); rustgis_engine::render::rustgis_tiles::cache::download_within( url, max, - ogc::DESCRIPTION_TIMEOUT, + timeout, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)), ); slot @@ -545,13 +545,12 @@ pub fn poll_pages(app: &mut RustGisApp, ctx: &egui::Context) { continue; } let answer = read.slot.lock().unwrap_or_else(|e| e.into_inner()).take(); - // A layer's description that doesn't come in time is given up on, and the layer's query - // fetched as it is (natively its download ends then too; the browser's fetch keeps its - // own time, and what it brings is dropped). + // A description that takes too long is given up on; a feature page can be retried at a + // smaller size. Native downloads end then too; a browser's late answer is dropped. let describing = read.pages.describing(); let answer = answer.or_else(|| { - (describing && read.asked.elapsed() >= ogc::DESCRIPTION_TIMEOUT) - .then(|| Err("the layer's description took too long".to_string())) + let timeout = if describing { Some(ogc::DESCRIPTION_TIMEOUT) } else { read.pages.page_timeout() }; + timeout.filter(|timeout| read.asked.elapsed() >= *timeout).map(|_| Err("timeout: service page".to_string())) }); match answer { Some(answer) => { @@ -617,8 +616,11 @@ pub(crate) fn go_on(app: &mut RustGisApp, landed: Landed, left: usize, step: Ste let next = next_request(app, &landed.params, &pages); let slot = match next { // A layer's description: small, and soon given up on. - Ok(url) if pages.describing() => fetch_description(&url, left.min(ogc::DESCRIPTION_MAX)), - Ok(url) => fetch_into_limited(&url, left), + Ok(url) if pages.describing() => fetch_within(&url, left.min(ogc::DESCRIPTION_MAX), ogc::DESCRIPTION_TIMEOUT), + Ok(url) => match pages.page_timeout() { + Some(timeout) => fetch_within(&url, left, timeout), + None => fetch_into_limited(&url, left), + }, Err(e) => Slot::new(std::sync::Mutex::new(Some(Err(e)))), }; app.ui.service_pages.push(PageRead { landed, pages, left, slot, asked: web_time::Instant::now() }); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index ac8e04af49..7f6a28d264 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -351,6 +351,16 @@ its type). A WebMercatorQuad tileset is found by its tile matrix set, whatever the server calls it. A service that asks for a token says so. In the web app the server must allow requests from web pages (CORS). +For an address ending in a layer id, such as `…/NFHL/MapServer/21`, list the service root +(`…/NFHL/MapServer`) with `service.layers`, then pass `"layer":"21"` to `service.add` +with that same root. Both MapServer and FeatureServer services can offer feature layers. + +When an ArcGIS feature page fails with a server error, a timeout or a reset connection, RustGIS +retries that offset with half as many features, down to one feature per page. Subsequent pages +keep the smaller size. A notice counts the requests retried with smaller pages. Persistent +failures identify the layer and offset; features already received are kept with an incomplete-read +notice. The feature, byte, memory and overall wait limits still apply, and Cancel stops the read. + A coverage is read once, for the view when it was added (its DescribeCoverage first, for its axes, format and bounds; `service.coverage` gives the GetCoverage address alone). Moving the map doesn't ask for it again: add it again for another area. The server reprojects it to EPSG:4326 (WCS 2.0 @@ -380,6 +390,16 @@ each service's own terms: - **ArcGIS:** an envelope in EPSG:4326 the features intersect; the pages past the record limit keep it. +For an ArcGIS feature layer, `service.add` also accepts a SQL `"where"` clause in the service's +field names. It is sent as one query value, combined with `"bbox"` when given, and kept by every +page, including retries. Without it the query stays `1=1` (the whole layer). A clause rejected +by the server gives an error; it is never retried without the filter. Other service types do not +accept this parameter. + +```sh +rustgis-cli run --cmd 'service.add={"url":"https://hazards.fema.gov/arcgis/rest/services/public/NFHL/MapServer","layer":"28","where":"DFIRM_ID=\u002747157C\u0027"}' +``` + A WFS 1.0 service reads its box in the feature type's own coordinate system, so it is asked for the whole layer, as is an area across the antimeridian; a note says so. When a whole layer takes longer than `service.add` waits (a minute for its features), the error suggests `"bbox"`: