diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 724e595ddf..e6936b1794 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2484,28 +2484,77 @@ pub struct RecordPage { pub records: Vec, } +/// Characters of a search's words a catalogue is asked for. +pub const MAX_SEARCH_WORDS: usize = 200; + +/// A search's words as a catalogue is asked for them, and how many characters were left out: those +/// XML can't hold (control characters), and those past [`MAX_SEARCH_WORDS`]. +pub fn search_words(words: &str) -> (String, usize, usize) { + let words = words.trim(); + let kept: Vec = words.chars().filter(|c| !c.is_control() && !matches!(c, '\u{FFFE}' | '\u{FFFF}')).collect(); + let unwritable = words.chars().count() - kept.len(); + let text: String = kept.iter().take(MAX_SEARCH_WORDS).collect(); + (text.trim().to_string(), unwritable, kept.len().saturating_sub(MAX_SEARCH_WORDS)) +} + /// The GetRecords request (CSW 2.0.2, Dublin Core records) of a search: words anywhere in the -/// records, within a longitude/latitude box, from position `start` (1-based). -pub fn records_url(endpoint_url: &str, words: &str, bbox: Option<[f64; 4]>, start: u64) -> String { - let words: String = words.chars().filter(|c| !c.is_control()).take(200).collect::().trim().replace('\'', "''"); - let mut cql = Vec::new(); +/// records, within a longitude/latitude box, from position `start` (1-based). The search is a +/// filter in XML (OGC Filter 1.1.0), which GeoNetwork, pycsw and Esri Geoportal all read; they +/// don't share a form of CQL (#2889). +/// +/// `named` says the box is in CRS84, which tells its longitudes from its latitudes. Not every +/// catalogue reads that name: one that answers with an exception ([`records_refused`]) is asked +/// again without it. It isn't left out at first: pycsw then takes the corners latitude first. +pub fn records_url(endpoint_url: &str, words: &str, bbox: Option<[f64; 4]>, named: bool, start: u64) -> String { + let (mut names, mut terms) = (String::from(r#"xmlns:ogc="http://www.opengis.net/ogc""#), Vec::new()); + let (words, ..) = search_words(words); if !words.is_empty() { - cql.push(format!("AnyText LIKE '%{words}%'")); + names.push_str(r#" xmlns:csw="http://www.opengis.net/cat/csw/2.0.2""#); + // Found as written: a wildcard or an escape among them stands for itself. + let mut literal = String::new(); + for c in words.chars() { + if matches!(c, '%' | '_' | '\\') { + literal.push('\\'); + } + literal.push(c); + } + let literal = literal.replace('&', "&").replace('<', "<").replace('>', ">"); + terms.push(format!( + r#"csw:AnyText%{literal}%"# + )); } if let Some([w, s, e, n]) = bbox { - cql.push(format!("BBOX(ows:BoundingBox,{w},{s},{e},{n})")); + names.push_str(r#" xmlns:ows="http://www.opengis.net/ows" xmlns:gml="http://www.opengis.net/gml""#); + let crs = if named { r#" srsName="urn:ogc:def:crs:OGC:1.3:CRS84""# } else { "" }; + terms.push(format!( + "ows:BoundingBox{w} {s}{e} {n}" + )); } let mut q = format!( "SERVICE=CSW&VERSION=2.0.2&REQUEST=GetRecords&typeNames=csw:Record&resultType=results&elementSetName=full&outputSchema={}&maxRecords={RECORDS_PAGE}&startPosition={}", encode("http://www.opengis.net/cat/csw/2.0.2"), start.max(1) ); - if !cql.is_empty() { - q.push_str(&format!("&constraintLanguage=CQL_TEXT&constraint_language_version=1.1.0&constraint={}", encode(&cql.join(" AND ")))); + if !terms.is_empty() { + let all = if terms.len() > 1 { format!("{}", terms.concat()) } else { terms.concat() }; + let filter = format!("{all}"); + q.push_str(&format!("&constraintLanguage=FILTER&constraint_language_version=1.1.0&constraint={}", encode(&filter))); } with_query(&endpoint(endpoint_url), &q) } +/// Whether a GetRecords answer is an exception: the catalogue refusing the request, rather than +/// its records or something else's answer. +pub fn records_refused(body: &[u8]) -> bool { + let text = std::str::from_utf8(body).unwrap_or_default(); + xml(text, 2_000_000).is_ok_and(|doc| is_exception(local(&doc.root_element()))) +} + +/// Whether a document's root says it is a service's exception. +fn is_exception(root: &str) -> bool { + matches!(root, "ServiceExceptionReport" | "ExceptionReport") +} + /// What a link's protocol (or, when it says nothing useful, its address) makes it. fn link_kind(protocol: &str, url: &str) -> &'static str { let p = protocol.to_ascii_lowercase(); @@ -2552,7 +2601,7 @@ pub fn parse_records(url: &str, body: &[u8]) -> Result { let root = doc.root_element(); match local(&root) { "GetRecordsResponse" => {} - "ServiceExceptionReport" | "ExceptionReport" => { + name if is_exception(name) => { return Err(format!("the catalogue answered with an error: {}", text_of(&root).chars().take(300).collect::())); } other => return Err(format!("not a catalogue's (CSW) answer (<{other}>)")), @@ -9076,11 +9125,12 @@ mod tests { "https://cat.example.org/csw?SERVICE=CSW&REQUEST=GetCapabilities", "O'Brien\u{7}", Some([7.0, 46.0, 8.0, 47.0]), + true, 21, ); assert!(u.starts_with("https://cat.example.org/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetRecords&"), "{u}"); - assert!(u.contains("&startPosition=21&") && u.contains("O%27%27Brien") && u.contains("BBOX%28ows:BoundingBox,7,46,8,47%29"), "{u}"); - assert!(!records_url("https://cat.example.org/csw", " ", None, 0).contains("constraint=")); + assert!(u.contains("&startPosition=21&") && u.contains("O%27Brien%25"), "{u}"); + assert!(!records_url("https://cat.example.org/csw", " ", None, true, 0).contains("constraint")); let xml = r#" @@ -9126,6 +9176,67 @@ mod tests { assert_eq!(parse_records("https://c.org/csw", many.as_bytes()).unwrap().records.len(), RECORDS_PAGE as usize * 5); } + /// A search is a filter in XML which parses, with what was typed found as written (#2889): its + /// markup, and the wildcards and escape of the search, stand for themselves. + #[test] + fn a_catalogue_is_searched_by_a_filter_in_xml() { + // The constraint of a request, read back. + let filter = |words: &str, bbox: Option<[f64; 4]>, named: bool| { + let u = records_url("https://cat.example.org/csw?map=a", words, bbox, named, 1); + assert!(u.starts_with("https://cat.example.org/csw?map=a&SERVICE=CSW&"), "{u}"); + let (head, constraint) = u.split_once("&constraint=").unwrap(); + assert!(head.ends_with("&constraintLanguage=FILTER&constraint_language_version=1.1.0"), "{u}"); + let mut bytes = Vec::new(); + let mut rest = constraint.bytes(); + while let Some(b) = rest.next() { + bytes.push(match b { + b'%' => u8::from_str_radix(std::str::from_utf8(&[rest.next().unwrap(), rest.next().unwrap()]).unwrap(), 16).unwrap(), + b => b, + }); + } + String::from_utf8(bytes).unwrap() + }; + let literal = |words: &str| { + let f = filter(words, None, true); + let doc = xml(&f, 1000).unwrap(); + let name = doc.descendants().find(|n| local(n) == "PropertyName").unwrap(); + assert_eq!((local(&name.parent().unwrap()), text_of(&name).as_str()), ("PropertyIsLike", "csw:AnyText")); + doc.descendants().find(|n| local(n) == "Literal").and_then(|n| n.text().map(String::from)).unwrap() + }; + assert_eq!(literal(" solos "), "%solos%"); + assert_eq!(literal("uso & ]]> \"d'água\""), "%uso & ]]> \"d'água\"%"); + assert_eq!(literal(r"100%_a\b"), r"%100\%\_a\\b%"); + assert_eq!(literal("a\u{7}b\u{FFFF}c"), "%abc%"); + assert_eq!(literal(&"é".repeat(250)), format!("%{}%", "é".repeat(200))); + assert_eq!(search_words(" a\tb "), ("ab".to_string(), 1, 0)); + assert_eq!(search_words(&"é".repeat(250)), ("é".repeat(200), 0, 50)); + assert_eq!(search_words("solos"), ("solos".to_string(), 0, 0)); + + let area = Some([-43.5, -21.0, -42.0, -20.25]); + for named in [true, false] { + let f = filter("", area, named); + let doc = xml(&f, 1000).unwrap(); + assert_eq!(local(&doc.root_element().first_child().unwrap()), "BBOX", "{f}"); + let envelope = doc.descendants().find(|n| local(n) == "Envelope").unwrap(); + assert_eq!(envelope.attribute("srsName"), named.then_some("urn:ogc:def:crs:OGC:1.3:CRS84")); + assert_eq!(child_text(&envelope, "lowerCorner").as_deref(), Some("-43.5 -21")); + assert_eq!(child_text(&envelope, "upperCorner").as_deref(), Some("-42 -20.25")); + } + // Both together. + let f = filter("solos", area, true); + let doc = xml(&f, 1000).unwrap(); + let and = doc.root_element().first_child().unwrap(); + assert_eq!(local(&and), "And", "{f}"); + assert_eq!(and.children().map(|n| local(&n).to_string()).collect::>(), ["PropertyIsLike", "BBOX"]); + + // A refusal, told from records, a page that isn't a catalogue's and one that isn't XML. + assert!(records_refused(b"bad filter")); + assert!(records_refused(b"\n")); + for other in [&b""[..], b"", b"", b"\xff", b""] { + assert!(!records_refused(other), "{other:?}"); + } + } + /// Every kind of document is read up to the limit, and what's past it is counted in a note. #[test] fn a_document_past_the_read_limit_says_how_much_it_left_out() { diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index a4038366c0..868ed22ce4 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -29,7 +29,7 @@ cache.cancel cache.empty cache.emptyIndexes cache.fill -catalog.search url query? bbox? start? text? connection? +catalog.search url query? bbox? start? bboxCrs? text? connection? connection.browse id node? probe? answer? documents? connection.cancelToken id connection.duplicate id name? diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index d16cf33337..1ba148758b 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -41,7 +41,7 @@ pub fn commands() -> Vec { 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), its area in longitude/latitude, and "coverageCrs": the coverage's own system when it is asked in it (as layer.addUrl takes it, for an answer that doesn't say its system)"#, ), C::new("catalog.search", "Search Catalogue", "Home › Add", catalog_search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default), "start"?: "the first record's position (a page's next)", "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them; a link with "fromDocument": true came from a catalogue read from the internet: give layer.addUrl that too)"#, + r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default; one across the antimeridian isn't asked for, which a note says), "start"?: "the first record's position (a page's next)", "bboxCrs"?: "CRS84" | "none" (how the area's coordinate system is named to the catalogue; by default CRS84, and none when the catalogue answers that with an exception to a request RustGIS makes (a supplied text isn't asked again); the answer's bboxCrs says which was read, to give with its next page), "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them; a link with "fromDocument": true came from a catalogue read from the internet: give layer.addUrl that too)"#, ), ]; commands.extend(group::commands()); @@ -1857,17 +1857,80 @@ fn coverage(s: &mut Session, p: &Value) -> CmdResult { Ok(out) } +/// Said when the records read are those of an area asked for without its coordinate system. +pub const AREA_UNNAMED: &str = "the catalogue answered with an exception when the area's coordinate system was named (CRS84), so it was asked again without it, longitude first"; + +/// Said when an area across the antimeridian was given: it isn't asked for ([`search_area`]). +pub const AREA_ACROSS_ANTIMERIDIAN: &str = + "the area crosses the antimeridian, which the catalogue isn't asked for: the whole catalogue is searched"; + +/// The notes `catalog.search` gives about its words alone, the same on every page of a search: +/// control characters left out and words cut. +pub fn words_notes(query: &str) -> Vec { + let (_, unwritable, cut) = rustgis_data::ogc::search_words(query); + let mut notes = Vec::new(); + if unwritable > 0 { + notes.push(format!("control characters left out of the words searched for: {unwritable}")); + } + if cut > 0 { + notes.push(format!("the words are cut to {} characters; left out: {cut}", rustgis_data::ogc::MAX_SEARCH_WORDS)); + } + notes +} + +/// The area `catalog.search` asks for, if any. A box across the antimeridian isn't asked for: the +/// whole catalogue is searched. +fn search_area(s: &Session, p: &Value) -> Result, String> { + match p.get("bbox") { + None | Some(Value::Null) => Ok(None), + Some(_) => Ok(Some(super::catalogs::area(s, p)?).filter(|a| a[0] <= a[2])), + } +} + +/// Whether `catalog.search` names its area's coordinate system; `None` when it isn't told, so one +/// refused with it named is asked for again without ([`records_again`]). +fn area_named(p: &Value) -> Result, String> { + match p.get("bboxCrs") { + None | Some(Value::Null) => Ok(None), + Some(v) if v == "CRS84" => Ok(Some(true)), + Some(v) if v == "none" => Ok(Some(false)), + Some(_) => Err("bboxCrs is \"CRS84\" or \"none\"".into()), + } +} + /// The GetRecords request `catalog.search` makes of its parameters (the app fetches it first). pub fn records_request(s: &Session, p: &Value) -> Result { let url = url_of(p)?; let words = ps(p, "query").unwrap_or(""); - let bbox = match p.get("bbox") { - None | Some(Value::Null) => None, - // A box across the antimeridian isn't asked for: the whole catalogue is searched. - Some(_) => Some(super::catalogs::area(s, p)?).filter(|a| a[0] <= a[2]), - }; + let bbox = search_area(s, p)?; + let named = area_named(p)?.unwrap_or(true); let start = p.get("start").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1_000_000); - Ok(crate::render::rustgis_tiles::logins::inherit(url, &rustgis_data::ogc::records_url(url, words, bbox, start))) + Ok(crate::render::rustgis_tiles::logins::inherit(url, &rustgis_data::ogc::records_url(url, words, bbox, named, start))) +} + +/// `catalog.search`'s parameters for asking again after the answer `body`: the catalogue answered +/// an area whose coordinate system was named with an exception, so it is asked for without +/// ([`AREA_UNNAMED`]). With them, the error the answer is. `None` when there is nothing to ask again. +pub fn records_again(s: &Session, p: &Value, body: &[u8]) -> Option<(Value, String)> { + if area_named(p).ok()?.is_some() || search_area(s, p).ok()?.is_none() || !rustgis_data::ogc::records_refused(body) { + return None; + } + let url = url_of(p).ok()?; + let refused = crate::sources::message_with_address(url, &rustgis_data::ogc::parse_records(url, body).err()?); + let mut again = p.clone(); + again.as_object_mut()?.remove("text"); + again["bboxCrs"] = json!("none"); + Some((again, refused)) +} + +/// The error of a search refused with its area's coordinate system named (`first`) and failed +/// again without (`second`): the first, with what the second says besides. +pub fn refused_again(first: &str, second: &str) -> String { + let shared = first.match_indices(": ").filter_map(|(i, _)| first.get(..i + 2)).filter(|label| second.starts_with(label)).last(); + match second.strip_prefix(shared.unwrap_or("")) { + Some(rest) if first != second => format!("{first} (asked again without the area's coordinate system: {rest})"), + _ => first.to_string(), + } } /// A WCS coverage's answer is a GeoTIFF; anything else (an XML exception, an HTML page, plain @@ -1905,13 +1968,40 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option within.min(Reach::Public), None => within, }; - let (page, reach) = match ps(p, "text") { - Some(text) => ( - rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))?, - within, - ), - None => fetch_records(url, &request, within)?, + let mut named = area_named(p)?.unwrap_or(true); + let mut notes = Vec::new(); + let parse = |request: &str, bytes: &[u8]| { + rustgis_data::ogc::parse_records(request, bytes).map_err(|e| crate::sources::message_with_address(url, &e)) }; + let (request, page, reach) = match ps(p, "text") { + Some(text) => { + let page = parse(&request, text.as_bytes())?; + (request, page, within) + } + None => { + let (bytes, reach) = fetch_records(url, &request, within)?; + match records_again(s, p, &bytes) { + None => { + let page = parse(&request, &bytes)?; + (request, page, reach) + } + Some((again, refused)) => { + let request = records_request(s, &again)?; + let within = within.min(cache::ceiling_for(&request)); + let (page, reach) = fetch_records(url, &request, within) + .and_then(|(bytes, reach)| Ok((parse(&request, &bytes)?, reach))) + .map_err(|second| refused_again(&refused, &second))?; + named = false; + notes.push(AREA_UNNAMED.to_string()); + (request, page, reach) + } + } + } + }; + notes.extend(words_notes(ps(p, "query").unwrap_or(""))); + if p.get("bbox").is_some_and(|b| !b.is_null()) && search_area(s, p)?.is_none() { + notes.push(AREA_ACROSS_ANTIMERIDIAN.to_string()); + } let mut dropped = 0usize; let records: Vec = page .records @@ -1941,8 +2031,14 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option 0 { - out["notes"] = - json!([format!("{dropped} links point to addresses RustGIS won't fetch for a catalogue on the web and are left out")]); + notes.push(format!("{dropped} links point to addresses RustGIS won't fetch for a catalogue on the web and are left out")); + } + if !notes.is_empty() { + out["notes"] = json!(notes); + } + // Given with the next page, it is read as this one was. + if search_area(s, p)?.is_some() { + out["bboxCrs"] = json!(if named { "CRS84" } else { "none" }); } if !s.policy_user() { crate::sources::redact_url_fields(&mut out); @@ -1950,18 +2046,18 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option Result<(rustgis_data::ogc::RecordPage, Reach), String> { +fn fetch_records(url: &str, request: &str, ceiling: Reach) -> Result<(Vec, Reach), String> { let fetched = cache::download_blocking_with_origin_within(request, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) .map_err(cache::large_file_hint) .map_err(|e| crate::sources::message_with_address(url, &e))?; - let page = rustgis_data::ogc::parse_records(request, &fetched.bytes).map_err(|e| crate::sources::message_with_address(url, &e))?; - Ok((page, fetched.origin.reach())) + let reach = fetched.origin.reach(); + Ok((fetched.bytes, reach)) } #[cfg(target_arch = "wasm32")] -fn fetch_records(url: &str, _: &str, _: Reach) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { +fn fetch_records(url: &str, _: &str, _: Reach) -> Result<(Vec, Reach), String> { Err(crate::sources::message_with_address(url, "in the web app, use Home › Add › Add Data › From Service › Search Catalogue")) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1ffa103c7..63e2d96f3c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -27494,10 +27494,102 @@ fn wcs_coverages_and_catalogue_records() { json!([{"url": "https://geo.example.org/wms", "kind": "wms", "name": null, "protocol": "OGC:WMS", "fromDocument": true}]) ); assert!(v["notes"][0].as_str().is_some_and(|n| n.contains("1 links")), "{v}"); - assert!(v["request"].as_str().is_some_and(|r| r.contains("AnyText%20LIKE%20%27%25forest%25%27")), "{v}"); + assert!(v["request"].as_str().is_some_and(|r| r.contains("csw:AnyText") && r.contains("%25forest%25")), "{v}"); assert!(s.run("catalog.search", &json!({"url": "https://cat.example.org/csw", "text": ""})).is_err()); } +/// `catalog.search` names its area's coordinate system (CRS84), and asks again without only a +/// catalogue that answers that with an exception, said and given with the next page (#2889). +#[test] +fn a_catalogue_refusing_crs84_is_asked_for_the_area_without_it() { + use std::io::Write; + const REFUSED: &str = "WORDS"; + const PAGE: &str = r#""#; + // A catalogue answering an area with CRS84 named, and without, as given: its address, and + // whether each request named it. + let serve = |named: String, unnamed: String| { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/csw", listener.local_addr().unwrap()); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut s) = stream else { continue }; + let is_named = read_request(&mut s).contains("CRS84"); + log.lock().unwrap().push(is_named); + let body = if is_named { &named } else { &unnamed }; + let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + } + }); + (url, asked) + }; + let refused = |words: &str| REFUSED.replace("WORDS", words); + let mut s = Session::new(Project::default()); + let area = json!([-43, -21, -42, -20]); + + // Read with CRS84: nothing said, asked once. + let (url, asked) = serve(PAGE.into(), refused("never asked")); + let v = s.run("catalog.search", &json!({"url": url, "query": "solos", "bbox": area})).unwrap(); + assert_eq!((v["matched"].as_u64(), v["bboxCrs"].as_str(), v.get("notes")), (Some(443), Some("CRS84"), None), "{v}"); + assert_eq!(asked.lock().unwrap().clone(), [true]); + + // Refused, then read without it: said, and its next page is asked for without it at once. + let (url, asked) = serve(refused("CRS84?"), PAGE.into()); + let v = s.run("catalog.search", &json!({"url": url, "query": "solos", "bbox": area})).unwrap(); + assert_eq!((v["matched"].as_u64(), v["bboxCrs"].as_str()), (Some(443), Some("none")), "{v}"); + assert_eq!(v["notes"], json!([crate::cmd::service::AREA_UNNAMED])); + assert!(v["request"].as_str().is_some_and(|r| r.contains("ows:BoundingBox") && !r.contains("CRS84")), "{v}"); + let next = s.run("catalog.search", &json!({"url": url, "query": "solos", "bbox": area, "start": 21, "bboxCrs": "none"})).unwrap(); + assert_eq!((next["bboxCrs"].as_str(), next.get("notes")), (Some("none"), None), "{next}"); + // Named as told, it isn't asked again; nor are words alone. + let e = s.run("catalog.search", &json!({"url": url, "bbox": area, "bboxCrs": "CRS84"})).unwrap_err(); + assert!(e.ends_with("the catalogue answered with an error: CRS84?"), "{e}"); + let v = s.run("catalog.search", &json!({"url": url, "query": "solos"})).unwrap(); + assert!(v.get("bboxCrs").is_none() && v.get("notes").is_none(), "{v}"); + assert_eq!(asked.lock().unwrap().clone(), [true, false, false, true, false]); + assert!(s.run("catalog.search", &json!({"url": url, "bbox": area, "bboxCrs": "EPSG:4326"})).unwrap_err().contains("bboxCrs")); + + // Refused both ways: the catalogue's words, the second's when they differ. + let (url, asked) = serve(refused("no areas"), refused("no areas")); + let e = s.run("catalog.search", &json!({"url": url, "bbox": area})).unwrap_err(); + assert!(e.ends_with("the catalogue answered with an error: no areas"), "{e}"); + assert_eq!(asked.lock().unwrap().clone(), [true, false]); + let (url, _) = serve(refused("no such system"), refused("no areas")); + let e = s.run("catalog.search", &json!({"url": url, "bbox": area})).unwrap_err(); + assert!(e.ends_with("error: no such system (asked again without the area's coordinate system: no areas)"), "{e}"); + // The note says what happened, not why: an exception may be about something else. + let (url, _) = serve(refused("the server is busy"), PAGE.into()); + let v = s.run("catalog.search", &json!({"url": url, "bbox": area})).unwrap(); + let note = v["notes"][0].as_str().unwrap_or_default(); + assert!(note.contains("answered with an exception when") && !note.contains("refused"), "{note}"); + // What isn't a catalogue's answer is no refusal. + let (url, asked) = serve("".into(), PAGE.into()); + assert!(s.run("catalog.search", &json!({"url": url, "bbox": area})).is_err()); + assert_eq!(asked.lock().unwrap().clone(), [true]); + + // Words the catalogue isn't asked for are counted. + let p = json!({"url": "https://cat.example.org/csw", "query": format!("a\tb{}", "c".repeat(250)), "text": PAGE}); + let v = s.run("catalog.search", &p).unwrap(); + let said: Vec<&str> = v["notes"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + assert_eq!(said, ["control characters left out of the words searched for: 1", "the words are cut to 200 characters; left out: 52"]); +} + +/// An area across the antimeridian isn't asked for, so the whole catalogue is searched, and the +/// answer says so; an area on one side says nothing of it. +#[test] +fn a_catalogue_area_across_the_antimeridian_is_said_to_be_left_out() { + const PAGE: &str = r#""#; + let mut s = Session::new(Project::default()); + let search = |s: &mut Session, area: Value| { + s.run("catalog.search", &json!({"url": "https://cat.example.org/csw", "query": "solos", "bbox": area, "text": PAGE})).unwrap() + }; + let v = search(&mut s, json!([170, -20, -170, -10])); + assert!(!v["request"].as_str().unwrap_or_default().contains("BoundingBox"), "{v}"); + assert_eq!((v.get("bboxCrs"), &v["notes"]), (None, &json!([crate::cmd::service::AREA_ACROSS_ANTIMERIDIAN])), "{v}"); + let v = search(&mut s, json!([-43, -21, -42, -20])); + assert!(v["request"].as_str().unwrap_or_default().contains("BoundingBox") && v.get("notes").is_none(), "{v}"); +} + /// A KMZ's ground overlays become raster layers kept in the project; a KML whose picture is a web /// address or outside its folder says so. #[test] diff --git a/crates/ui-egui/src/cswui.rs b/crates/ui-egui/src/cswui.rs index 6eb42f9421..cf8a3a2b56 100644 --- a/crates/ui-egui/src/cswui.rs +++ b/crates/ui-egui/src/cswui.rs @@ -4,7 +4,10 @@ //! off the frame; `catalog.search` reads the answers. use egui::vec2; -use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; +use rustgis_engine::{ + cmd::service, + render::rustgis_tiles::{address::Reach, cache}, +}; use serde_json::{Value, json}; use crate::{RustGisApp, Slot}; @@ -16,8 +19,8 @@ pub struct State { pub query: String, /// Only records within the map's area. pub use_view: bool, - /// `catalog.search`'s parameters and its answer on the way. - waiting: Option<(Value, Slot, String>>)>, + /// The request on its way. + waiting: Option, records: Vec, matched: u64, next: Option, @@ -27,6 +30,14 @@ pub struct State { pub error: Option, } +/// A page asked for: `catalog.search`'s parameters, its answer on the way, and the error of the +/// request it is the second try of (`service::records_again`). +struct Asked { + p: Value, + answer: Slot, String>>, + refused: Option, +} + /// Links shown for a record. const SHOWN_LINKS: usize = 6; @@ -70,8 +81,8 @@ pub fn search(app: &mut RustGisApp, start: u64) { } let asked = p.clone(); p["start"] = json!(start); - match rustgis_engine::cmd::service::records_request(&app.session, &p) { - Ok(request) => { + match ask(app, p, None) { + Ok(()) => { let st = &mut app.ui.csw; st.error = None; if start <= 1 { @@ -81,36 +92,70 @@ pub fn search(app: &mut RustGisApp, start: u64) { st.next = None; st.asked = asked; } - // A catalogue held to the internet is searched only there; an answer read from the - // internet is recorded, so `catalog.search` holds the links it lists there. - if p.get("url").and_then(Value::as_str).is_some_and(|url| cache::ceiling_for(url) == Reach::Public) { - cache::restrict_to_public(&request); - } - st.waiting = Some((p, crate::fetch_document_into(&request))); } Err(e) => app.ui.csw.error = Some(e), } } +/// Sends a page's request, its answer read by [`poll`]. +fn ask(app: &mut RustGisApp, p: Value, refused: Option) -> Result<(), String> { + let request = service::records_request(&app.session, &p)?; + // A catalogue held to the internet is searched only there; an answer read from the + // internet is recorded, so `catalog.search` holds the links it lists there. + if p.get("url").and_then(Value::as_str).is_some_and(|url| cache::ceiling_for(url) == Reach::Public) { + cache::restrict_to_public(&request); + } + app.ui.csw.waiting = Some(Asked { p, answer: crate::fetch_document_into(&request), refused }); + Ok(()) +} + /// Reads a page of records once it has arrived. pub fn poll(app: &mut RustGisApp) { - let Some((_, slot)) = &app.ui.csw.waiting else { return }; - let Some(r) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; - let Some((mut p, _)) = app.ui.csw.waiting.take() else { return }; - let r = r.and_then(|bytes| { - p["text"] = json!(String::from_utf8_lossy(&bytes)); - // Not `app.run`: an error belongs in the dialog, not the notices. - app.session.run("catalog.search", &p) - }); - let st = &mut app.ui.csw; + let Some(Asked { answer, .. }) = &app.ui.csw.waiting else { return }; + let Some(r) = answer.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; + let Some(Asked { mut p, refused, .. }) = app.ui.csw.waiting.take() else { return }; + let r = match r { + Ok(bytes) => { + // Before the command reads it: a refusal asked again for is no error yet. + if let Some((again, refused)) = service::records_again(&app.session, &p, &bytes) { + if let Err(e) = ask(app, again, Some(refused)) { + app.ui.csw.error = Some(e); + } + return; + } + p["text"] = json!(String::from_utf8_lossy(&bytes)); + // Not `app.run`: an error belongs in the dialog, not the notices. + app.session.run("catalog.search", &p) + } + Err(e) => Err(e), + }; match r { Ok(v) => { + let st = &mut app.ui.csw; st.matched = v.get("matched").and_then(Value::as_u64).unwrap_or(0); st.next = v.get("next").and_then(Value::as_u64); st.records.extend(v.get("records").and_then(Value::as_array).into_iter().flatten().cloned()); - st.notes.extend(v.get("notes").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(String::from)); + // A note about the words or the area is the same on every page: it is listed once. Any + // other counts what its own page left out, so each is kept. + let same = service::words_notes(p.get("query").and_then(Value::as_str).unwrap_or("")); + let page = v.get("notes").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); + for note in refused.map(|_| service::AREA_UNNAMED).into_iter().chain(page) { + let repeats = [service::AREA_UNNAMED, service::AREA_ACROSS_ANTIMERIDIAN].contains(¬e) || same.iter().any(|s| s == note); + if !(repeats && st.notes.iter().any(|n| n == note)) { + st.notes.push(note.to_string()); + } + } + // More asks for the area as this page's was read. + if let Some(crs) = v.get("bboxCrs") { + st.asked["bboxCrs"] = crs.clone(); + } + } + Err(e) => { + app.ui.csw.error = Some(match refused { + Some(first) => service::refused_again(&first, &e), + None => e, + }); } - Err(e) => st.error = Some(e), } } @@ -162,6 +207,13 @@ fn records(app: &mut RustGisApp, ui: &mut egui::Ui) { let list = crate::sourcespane::connections_snapshot(app); let st = &app.ui.csw; if st.records.is_empty() && st.matched == 0 { + // Nothing matched, but how the search was asked is still said. + if !st.notes.is_empty() { + ui.separator(); + } + for n in &st.notes { + ui.label(egui::RichText::new(n).small().weak()); + } return; } ui.separator(); @@ -341,4 +393,152 @@ mod tests { assert_eq!(asked.lock().unwrap().clone(), [want]); } } + + /// Only where the map is: a catalogue that answers the area's CRS84 with an exception is asked + /// once more without it, which is said, and More asks as that page was read; one that answers + /// it is asked once. One that refuses both shows the server's words (#2889). + #[test] + fn an_area_refused_with_its_system_named_is_asked_for_again_without() { + const REFUSED: &str = "no such system"; + const PAGE: &str = r#"Roads"#; + for (n, named, unnamed) in [(1, true, true), (2, false, true), (3, false, false)] { + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let is_named = url.contains("CRS84"); + log.lock().unwrap().push((is_named, url.contains("&startPosition=21&"), ceiling)); + let body = if if is_named { named } else { unnamed } { PAGE } else { REFUSED }; + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: body.into(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.session.run("map.zoomToExtent", &json!({"extent": [-43, -21, -42, -20]})).unwrap(); + let csw = format!("https://csw-area-{n}.example/csw"); + // Held to the internet, which the second request follows too. + app.run("ui.addService", json!({"url": csw, "type": "csw", "query": "roads", "bbox": "view", "fromDocument": true})).unwrap(); + poll(&mut app); + poll(&mut app); + let public = Reach::Public; + let st = &app.ui.csw; + assert!(st.waiting.is_none()); + if !named && !unnamed { + assert_eq!(asked.lock().unwrap().clone(), [(true, false, public), (false, false, public)]); + let error = st.error.as_deref().unwrap_or_default(); + assert!(error.ends_with("the catalogue answered with an error: no such system"), "{error}"); + assert!(st.records.is_empty() && st.notes.is_empty()); + continue; + } + assert_eq!((st.error.as_deref(), st.records.len(), st.next), (None, 1, Some(21))); + // The refusal asked again for isn't an error in the status bar either. + assert!(!app.session.notices.iter().any(|n| n.error)); + let said = if named { vec![] } else { vec![service::AREA_UNNAMED.to_string()] }; + assert_eq!(st.notes, said); + search(&mut app, 21); + poll(&mut app); + let first: &[_] = if named { &[(true, false, public)] } else { &[(true, false, public), (false, false, public)] }; + assert_eq!(asked.lock().unwrap().clone(), [first, &[(named, true, public)]].concat()); + let st = &app.ui.csw; + assert_eq!((st.error.as_deref(), st.records.len(), &st.notes), (None, 2, &said)); + } + } + + /// A note about the words (a control character left out) is the same on every page: More + /// doesn't list it again. + #[test] + fn a_note_about_the_words_is_listed_once_over_pages() { + const PAGE: &str = r#"Roads"#; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: PAGE.into(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.run("ui.addService", json!({"url": "https://csw-words.example/csw", "type": "csw", "query": "ro\u{7}ads"})).unwrap(); + poll(&mut app); + let said = vec!["control characters left out of the words searched for: 1".to_string()]; + assert_eq!((app.ui.csw.records.len(), &app.ui.csw.notes), (1, &said)); + search(&mut app, 21); + poll(&mut app); + assert_eq!((app.ui.csw.records.len(), &app.ui.csw.notes), (2, &said)); + } + + /// An area across the antimeridian, left out of every page's request, is said once over pages. + #[test] + fn an_area_across_the_antimeridian_is_said_once_over_pages() { + const PAGE: &str = r#"Roads"#; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: PAGE.into(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + // The search More pages through, its area across the antimeridian. + app.ui.csw.asked = json!({"url": "https://csw-pacific.example/csw", "query": "roads", "bbox": [170, -20, -170, -10]}); + for page in [1, 2] { + search(&mut app, 1 + 20 * page); + poll(&mut app); + assert_eq!(app.ui.csw.records.len(), page as usize); + } + assert_eq!(app.ui.csw.notes, [service::AREA_ACROSS_ANTIMERIDIAN.to_string()]); + } + + /// A note that counts what one page left out is said for every page, even when two pages + /// leave out as many: More keeps both, so nothing is under-counted. + #[test] + fn a_note_counting_a_pages_links_is_kept_for_every_page() { + const PAGE: &str = r#"Roadshttp://10.0.0.4/wmshttp://10.0.0.5/wfs"#; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: PAGE.into(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + // Held to the internet: links to the local network are left out. + app.run( + "ui.addService", + json!({"url": "https://csw-links.example/csw", "type": "csw", "query": "ro\u{7}ads", "fromDocument": true}), + ) + .unwrap(); + poll(&mut app); + let words = "control characters left out of the words searched for: 1".to_string(); + let links = "2 links point to addresses RustGIS won't fetch for a catalogue on the web and are left out".to_string(); + assert_eq!((app.ui.csw.records.len(), &app.ui.csw.notes), (1, &vec![words.clone(), links.clone()])); + search(&mut app, 21); + poll(&mut app); + assert_eq!((app.ui.csw.records.len(), &app.ui.csw.notes), (2, &vec![words, links.clone(), links])); + } + + /// A search that matched nothing still says how it was asked: the area asked for again without + /// its system is shown with no records (#2889). + #[test] + fn a_search_that_matched_nothing_shows_its_notes() { + use egui_kittest::kittest::Queryable; + const REFUSED: &str = "no such system"; + const NONE: &str = r#""#; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let body = if url.contains("CRS84") { REFUSED } else { NONE }; + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: body.into(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.session.run("map.zoomToExtent", &json!({"extent": [-43, -21, -42, -20]})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(16).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.state_mut() + .run("ui.addService", json!({"url": "https://csw-nothing.example/csw", "type": "csw", "query": "roads", "bbox": "view"})) + .unwrap(); + h.run_steps(4); + let st = &h.state().ui.csw; + assert_eq!((st.error.as_deref(), st.records.len(), st.matched), (None, 0, 0)); + assert_eq!(st.notes, [service::AREA_UNNAMED.to_string()]); + assert!(h.query_by_label(service::AREA_UNNAMED).is_some(), "the note isn't shown"); + } }