diff --git a/crates/data/src/diagnostics.rs b/crates/data/src/diagnostics.rs index f75553520b..b7577f90df 100644 --- a/crates/data/src/diagnostics.rs +++ b/crates/data/src/diagnostics.rs @@ -450,7 +450,7 @@ fn bounded(text: &str, limit: usize) -> String { } /// `text` cut to `limit` bytes at a character, an ellipsis marking the cut. -fn cut_with_ellipsis(text: &mut String, limit: usize) { +pub(crate) fn cut_with_ellipsis(text: &mut String, limit: usize) { if text.len() > limit { let mut end = limit.saturating_sub(3); while !text.is_char_boundary(end) { diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 0f1e85ef01..ff32ef5546 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -63,7 +63,7 @@ const MAX_TEXT_BYTES: usize = 512 << 20; fn row_bytes(features: usize, fields: usize) -> usize { use std::mem::size_of; // Declared, kept or not, as a column, a field and a name to tell repeats by. - let field = size_of::<(String, u64, bool)>() + size_of::>() + size_of::() + size_of::(); + let field = size_of::() + size_of::>() + size_of::() + size_of::(); let row = size_of::().saturating_add(fields.saturating_mul(size_of::())); features.saturating_mul(row).saturating_add(fields.saturating_mul(field)) } @@ -92,7 +92,8 @@ const LAST_FIELD_TYPE: u64 = 16; pub struct Page { /// Its features, in longitude/latitude. pub dataset: Dataset, - /// What was left out or assumed while reading it. + /// What was left out or assumed while reading it, but for what its features lost + /// ([`losses`](Self::losses)). pub report: ReadReport, /// The service holds more features than it sent (`exceededTransferLimit`): the next page /// starts after these. @@ -100,9 +101,20 @@ pub struct Page { /// The field holding the features' object ids (`esriFieldTypeOID`), by its place in /// `dataset.fields`. pub object_id_field: Option, - /// What its features lost, counted (also said in `report`): a reader joining pages sums them - /// and says each once ([`Losses::messages`]). + /// What its features lost, counted: a reader joining pages sums them and says each once + /// ([`Losses::messages`]), as [`read`] says a single page's. pub losses: Losses, + /// About the memory its fields, rows, text values and geometries take, in bytes, as counted + /// against [`MAX_ROW_BYTES`], [`MAX_TEXT_BYTES`] and [`MAX_GEOMETRY_BYTES`]: a reader joining + /// pages sums them against a budget of its own. + pub memory: usize, + /// Features it holds past the limit it was read within ([`read_page_within`]), not read: what + /// they lost isn't counted. + pub left_out: usize, + /// A hash of how many features it holds and of its first and last features as they were sent, + /// taken before any limit: a reader of pages tells a page sent again by it when the features + /// have no object id. + pub fingerprint: u64, } /// What a page's features lost or had assumed, counted. @@ -133,7 +145,7 @@ impl Losses { self.with_zm = self.with_zm.saturating_add(other.with_zm); } - /// What they say, one message per kind (as [`read_page`] says them). + /// What they say, one message per kind (as [`read`] says them). pub fn messages(&self) -> Vec { let mut out = Vec::new(); if self.no_crs { @@ -167,6 +179,7 @@ impl Losses { /// Reads an answer as a layer named `name`, saying when the service held more features than it sent. pub fn read(bytes: &[u8], name: &str) -> Result<(Dataset, ReadReport)> { let mut page = read_page(bytes, name)?; + page.report.messages.extend(page.losses.messages()); if page.exceeded_transfer_limit { page.report.messages.push(format!( "the service sent {} features only (its record limit); the rest aren't in this answer", @@ -186,6 +199,13 @@ pub fn is_esripbf(bytes: &[u8]) -> bool { /// Reads one page of an answer as a layer named `name`. pub fn read_page(bytes: &[u8], name: &str) -> Result { + read_page_within(bytes, name, usize::MAX) +} + +/// Reads one page of an answer as a layer named `name`, its first `limit` features only (the +/// rest are counted in [`Page::left_out`]): a reader joining pages up to a number of features +/// counts what those it keeps lost, and no others. +pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result { if bytes.is_empty() { return Err(invalid("the answer is empty: the service refused the query (ask for it with f=json to see why)")); } @@ -227,6 +247,18 @@ pub fn read_page(bytes: &[u8], name: &str) -> Result { return Err(too_many_rows(features.len(), declared.len())); } } + let fingerprint = { + use std::hash::Hasher as _; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + hash.write_usize(features.len()); + for f in [features.first(), features.last()].into_iter().flatten() { + hash.write(f); + } + hash.finish() + }; + let left_out = features.len().saturating_sub(limit); + features.truncate(limit); + let rows = row_bytes(features.len(), declared.len()); // A point layer's type is the format's default, which an answer leaves out. let shape_kind = geometry_type.unwrap_or(POINT); // Refused whether or not a feature has coordinates, so such a layer isn't read as empty. @@ -243,7 +275,7 @@ pub fn read_page(bytes: &[u8], name: &str) -> Result { let mut names = std::collections::HashSet::new(); let (mut repeated, mut not_read, mut unknown) = (0usize, 0usize, 0usize); let mut object_id_field = None; - for (name, number, utf8) in declared { + for Declared { name, number, utf8, alias } in declared { tally.not_utf8 += usize::from(!utf8); let Some(read_as) = kind(number) else { not_read += 1; @@ -261,7 +293,7 @@ pub fn read_page(bytes: &[u8], name: &str) -> Result { object_id_field = Some(fields.len()); } columns.push(Some((fields.len(), read_as))); - fields.push(Field::new(name, read_as.field_type())); + fields.push(Field { name, ty: read_as.field_type(), alias }); } if repeated > 0 { report.messages.push(format!("{repeated} fields repeat an earlier field's name and are left out")); @@ -331,9 +363,11 @@ pub fn read_page(bytes: &[u8], name: &str) -> Result { unprojected, with_zm, }; - report.messages.extend(losses.messages()); ds.zm_dropped = with_zm > 0; - Ok(Page { dataset: ds, report, exceeded_transfer_limit: more, object_id_field, losses }) + let memory = rows + .saturating_add(MAX_GEOMETRY_BYTES.saturating_sub(tally.geometry_room)) + .saturating_add(MAX_TEXT_BYTES.saturating_sub(tally.text_room)); + Ok(Page { dataset: ds, report, exceeded_transfer_limit: more, object_id_field, losses, memory, left_out, fingerprint }) } /// A reader of protocol buffer fields, which refuses what runs past its bytes. @@ -575,10 +609,22 @@ fn read_transform(bytes: &[u8]) -> Result { Ok(t) } -/// A field's name, its type's number (`FieldType`) and whether the name was valid UTF-8. -/// The name is taken from `tally`'s text room before it's made, twice: it's kept lowercase too. -fn field(bytes: &[u8], tally: &mut Tally) -> Result<(String, u64, bool)> { +/// A field as an answer declares it. +struct Declared { + name: String, + /// Its type's number (`FieldType`). + number: u64, + /// Whether its name and alias were valid UTF-8. + utf8: bool, + /// None when empty or the name itself. + alias: Option, +} + +/// A field as declared. The name is taken from `tally`'s text room before it's made, twice: it's +/// kept lowercase too; the alias once. +fn field(bytes: &[u8], tally: &mut Tally) -> Result { let (mut name, mut number, mut utf8) = (String::new(), 0, true); + let (mut alias, mut alias_utf8) = (String::new(), true); let mut r = Reader::new(bytes); while !r.done() { match r.key()? { @@ -589,10 +635,17 @@ fn field(bytes: &[u8], tally: &mut Tally) -> Result<(String, u64, bool)> { name = String::from_utf8_lossy(raw).into_owned(); } (2, 0) => number = r.varint()?, + (3, 2) => { + let raw = r.message()?; + tally.spend_text(lossy_len(raw))?; + alias_utf8 = std::str::from_utf8(raw).is_ok(); + alias = String::from_utf8_lossy(raw).into_owned(); + } (_, wire) => r.skip(wire)?, } } - Ok((name, number, utf8)) + let alias = Some(alias).filter(|a| !a.is_empty() && *a != name); + Ok(Declared { name, number, utf8: utf8 && alias_utf8, alias }) } /// The code of an answer's coordinate system (its `latestWkid` when RustGIS knows it, else its diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index b0683bf355..3958d49d68 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -4,7 +4,7 @@ use crate::raster::Crs; // Encoding, as `FeatureCollection.proto` lays answers out: shared with the engine's tests. #[path = "../../../../tests/support/esripbf.rs"] mod encode; -pub(crate) use encode::page; +pub(crate) use encode::{page, page_with_z}; // Named, so they come before the reader's own functions of the same names (`field`, `feature`). use encode::{ answer, double, feature, field, geometry, lonlat, message, null, number, packed, real, single, sint64, text, transform, uint, uint64, @@ -166,6 +166,53 @@ fn z_and_m_are_dropped_and_said_even_when_they_are_all_alike() { assert_eq!(report.messages, [crate::zm_note(Some(2))]); } +#[test] +fn field_aliases_are_kept_unless_empty_or_the_name() { + let declared = + |name: &str, alias: &str| message(13, &[message(1, name.as_bytes()), number(2, 4), message(3, alias.as_bytes())].concat()); + let bytes = answer(&[ + lonlat(), + transform(false, 1.0, 0.0, 0.0), + declared("POP_2020", "Population 2020"), + declared("NAME", "NAME"), + declared("CODE", ""), + field("PLAIN", 4), + feature(&[geometry(&[], &[1, 2])]), + ]); + let (ds, report) = read(&bytes, "t").unwrap(); + let aliases: Vec<_> = ds.fields.iter().map(|f| f.alias.as_deref()).collect(); + assert_eq!(aliases, [Some("Population 2020"), None, None, None]); + assert_eq!(ds.fields[0].display(), "Population 2020"); + assert!(report.messages.is_empty(), "{:?}", report.messages); + // An alias that isn't UTF-8 is read as it can be, and said. + let bytes = answer(&[lonlat(), message(13, &[message(1, b"A"), number(2, 4), message(3, b"Pop\xff")].concat())]); + let (ds, report) = read(&bytes, "t").unwrap(); + assert_eq!(ds.fields[0].alias.as_deref(), Some("Pop\u{fffd}")); + assert!(report.messages.iter().any(|m| m.contains("aren't valid UTF-8")), "{:?}", report.messages); +} + +#[test] +fn a_page_read_within_a_limit_counts_what_the_features_kept_lost() { + let bytes = answer(&[ + number(10, 1), + lonlat(), + transform(false, 1.0, 0.0, 0.0), + feature(&[geometry(&[], &[4, 6, 100])]), + feature(&[geometry(&[], &[1, 1, 100])]), + feature(&[geometry(&[], &[2, 2, 100])]), + ]); + let page = read_page_within(&bytes, "t", 1).unwrap(); + assert_eq!((page.dataset.features.len(), page.left_out, page.losses.with_zm), (1, 2, 1)); + assert_eq!(page.losses.messages(), [crate::zm_note(Some(1))]); + assert!(page.report.messages.is_empty(), "the losses are said apart: {:?}", page.report.messages); + // Within a limit it doesn't reach, the whole page. + let page = read_page_within(&bytes, "t", 3).unwrap(); + assert_eq!((page.dataset.features.len(), page.left_out, page.losses.with_zm), (3, 0, 3)); + let all = read_page(&bytes, "t").unwrap(); + assert_eq!((all.left_out, all.memory), (0, page.memory)); + assert!(read_page_within(&bytes, "t", 1).unwrap().memory < all.memory); +} + #[test] fn web_mercator_answers_are_turned_to_longitude_latitude() { let bytes = answer(&[ diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index a89916a71b..f0825ddf5f 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2694,6 +2694,31 @@ pub fn max_paged_features() -> usize { crate::memory::scaled(crate::memory::physical(), PAGED_FEATURES_FLOOR, PAGED_FEATURES_CEILING, 20 << 10) } +/// The most bytes of why a layer's protocol buffer pages couldn't be read that its note says. +const MAX_REASON: usize = 200; + +/// The note of a layer read in GeoJSON because its protocol buffer pages couldn't be read (`why`), +/// before the reading's own `note`. +fn read_in_geojson(why: &str, note: Option) -> String { + let said = format!("its protocol buffer pages couldn't be read ({why}), so it is read in GeoJSON"); + match note { + Some(note) => format!("{said}; {note}"), + None => said, + } +} + +/// The least memory [`max_decoded_bytes`] allows, and its limit in the browser. +pub const DECODED_FLOOR: usize = 512 << 20; +/// The most memory [`max_decoded_bytes`] allows, however much the computer has. +pub const DECODED_CEILING: usize = 3 << 30; + +/// Most memory, in bytes, an ArcGIS layer's protocol buffer pages may take once read: on the +/// desktop a quarter of the computer's memory, from [`DECODED_FLOOR`] up to [`DECODED_CEILING`]. +/// The download budget doesn't bound it: a vertex takes 1 to 3 bytes in a page and 16 read. +pub fn max_decoded_bytes() -> usize { + crate::memory::scaled(crate::memory::physical(), DECODED_FLOOR, DECODED_CEILING, 1) +} + /// A feature collection page's JSON `next` link, resolved against the page's address. fn next_page(url: &str, page: &serde_json::Value) -> Option { let link = page.get("links")?.as_array()?.iter().find(|l| { @@ -2761,13 +2786,15 @@ fn supports_pbf(layer: &serde_json::Value) -> bool { layer.get("supportedQueryFormats").and_then(|f| f.as_str()).is_some_and(|f| f.split(',').any(|f| f.trim().eq_ignore_ascii_case("pbf"))) } -/// An ArcGIS query asking for its answer as `format` (`f`), in place of the format it named. +/// 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 { - let url = query.split('#').next().unwrap_or(query); + 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(); - with_query(&with_query(base, &kept.join("&")), &format!("f={format}")) + let asked = with_query(&with_query(base, &kept.join("&")), &format!("f={format}")); + if let Some(f) = fragment { format!("{asked}#{f}") } else { asked } } /// The description of the layer an ArcGIS query reads (`…/FeatureServer/0?f=json`), with the @@ -2902,7 +2929,8 @@ pub enum Step { /// The next answer to fetch ([`Pages::next_url`]), to hand to [`Pages::land`]. Fetch(Box), /// The collection as read (the pages joined, or the first page as it came) and a note when - /// some features were left unread. + /// some features were left unread, or it was read in GeoJSON because its protocol buffer + /// pages couldn't be read. Done(Vec, Option), /// An ArcGIS layer read in protocol buffer pages (`f=pbf`, see [`begin_with_pbf`]): its /// features, what reading them said, and a note when some were left unread. @@ -2931,6 +2959,12 @@ pub struct Pages { phase: Phase, /// The protocol buffer pages read, as one layer, and what reading them said. decoded: Option<(crate::Dataset, crate::ReadReport, crate::esripbf::Losses)>, + /// The memory those pages take, in bytes, and the most they may ([`max_decoded_bytes`]). + decoded_bytes: usize, + decoded_budget: usize, + /// Why the layer's first protocol buffer page couldn't be read, when it is read in GeoJSON + /// pages instead: said in the note it ends with. + pbf_failed: Option, } /// What the answer being fetched is. @@ -3024,20 +3058,17 @@ fn first_value(features: &[Box]) -> Option { } /// What tells a protocol buffer page from another, to find a page sent again: its first feature's -/// object id, or else (no id, or an empty one) its length and its first and last features' -/// geometries and values (ids are numbered within each page, and two pages may start with the same -/// row). +/// object id, or else (no id, or an empty one) its fingerprint, taken from the page as it was sent +/// (ids are numbered within each page, two pages may start with the same row, and a page sent +/// again may be cut shorter by the limit). fn first_mark(page: &crate::esripbf::Page) -> Option { - let features = &page.dataset.features; - let (f, l) = (features.first()?, features.last()?); + let f = page.dataset.features.first()?; let id = page .object_id_field .and_then(|i| f.attrs.get(i)) .filter(|id| **id != crate::Value::Null) .and_then(|id| serde_json::to_value(id).ok()); - id.or_else(|| { - Some(serde_json::Value::String(format!("{} {:?} {:?} {:?} {:?}", features.len(), f.geometry, f.attrs, l.geometry, l.attrs))) - }) + id.or_else(|| Some(serde_json::Value::String(format!("{:016x}", page.fingerprint)))) } /// Starts reading a service's features at `url`, up to `max`, before anything is fetched. @@ -3087,6 +3118,9 @@ fn start(url: &str, max: usize, pbf: bool) -> Step { from: url.to_string(), phase, decoded: None, + decoded_bytes: 0, + decoded_budget: max_decoded_bytes(), + pbf_failed: None, })) } @@ -3149,6 +3183,9 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option, String>) -> Step { + let Some(why) = self.pbf_failed.take() else { return self.land_page(answer) }; + match self.land_page(answer) { + // Carried to the next page, whichever reading goes on with it. + Step::Fetch(mut pages) => { + pages.pbf_failed = Some(why); + Step::Fetch(pages) + } + Step::Done(bytes, note) => Step::Done(bytes, Some(read_in_geojson(&why, note))), + Step::Decoded(ds, report, note) => Step::Decoded(ds, report, Some(read_in_geojson(&why, note))), + step => step, + } + } + + fn land_page(mut self, answer: Result, String>) -> Step { if matches!(self.phase, Phase::WfsHits) { let matched = answer.ok().and_then(|b| wfs_matched(&b)); let Some(matched) = matched else { @@ -3347,12 +3399,19 @@ impl Pages { /// with the pages read. fn land_pbf(mut self, answer: Result, String>) -> Step { 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 page = answer.and_then(|bytes| crate::esripbf::read_page(&bytes, "query").map_err(|e| e.to_string())); + 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(_) if self.decoded.is_none() => { + Err(e) if self.decoded.is_none() => { *pbf = false; + // 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); + crate::diagnostics::cut_with_ellipsis(&mut why, MAX_REASON); + self.pbf_failed = Some(why); // A query that asked for protocol buffers itself is read in GeoJSON too. if query_value(&self.url, "f").is_some_and(|f| f.eq_ignore_ascii_case("pbf")) { self.url = with_format(&self.url, "geojson"); @@ -3377,18 +3436,27 @@ impl Pages { if start.is_none() { *start = mark; } + // The first page is kept whatever it takes (the reader bounds a page); a later one that + // would take the layer past its memory budget isn't joined. + let bytes = self.decoded_bytes.saturating_add(page.memory); + if self.decoded.is_some() && bytes > self.decoded_budget { + let mb = self.decoded_budget >> 20; + return self.stop(format!("the page after feature {read} would take the layer past {mb} MB of memory; the rest aren't read")); + } + self.decoded_bytes = bytes; + let cut = page.left_out > 0; let returned = page.dataset.features.len(); let following = page.exceeded_transfer_limit.then(|| with_format(&arcgis_page_url(&self.url, read + returned, *size, order.as_deref()), "pbf")); // What the features lost is summed over the pages, and said once (in `finish`); the // page's other messages, about its fields and system, once each. - let counted = page.losses.messages(); - let mut report = page.report; - report.messages.retain(|m| !counted.contains(m)); + let report = page.report; match &mut self.decoded { None => self.decoded = Some((page.dataset, report, page.losses)), Some((ds, joined, losses)) => { - if ds.fields != page.dataset.fields { + // By name and type: the first page's aliases are kept. + let same = |a: &crate::Field, b: &crate::Field| a.name == b.name && a.ty == b.ty; + if ds.fields.len() != page.dataset.fields.len() || !ds.fields.iter().zip(&page.dataset.fields).all(|(a, b)| same(a, b)) { return self.stop(format!("the page after feature {read} has other fields than the first; the rest aren't read")); } // Each page's positions are in its own system, and its geometries of its own type; @@ -3419,7 +3487,7 @@ impl Pages { losses.add(&page.losses); } } - if self.read() > self.max { + if cut || self.read() > self.max { return self.finish_at_max(); } match following { @@ -4694,7 +4762,7 @@ mod tests { /// the limit end the read with the pages read so far, and a note. What the pages' features lost is said once, summed. #[test] fn arcgis_pbf_pages_joined_when_the_layer_lists_them() { - use crate::esripbf::tests::page as pbf; + use crate::esripbf::tests::{page as pbf, page_with_z as pbf_z}; let query = "https://x.org/arcgis/rest/services/P/FeatureServer/0/query?where=1%3D1&outFields=*&f=geojson&token=t"; let description = "https://x.org/arcgis/rest/services/P/FeatureServer/0?f=json&token=t"; let layer = br#"{"objectIdField": "OBJECTID", "maxRecordCount": 2, "supportedQueryFormats": "JSON, geoJSON, PBF", @@ -4745,7 +4813,7 @@ mod tests { // `begin` reads the same layer in GeoJSON. let (step, asked) = run(false, 100, &|u: &str| json_page(u).ok_or_else(|| "404".to_string())); - assert!(matches!(step, Step::Done(..)), "{step:?}"); + assert!(matches!(step, Step::Done(_, None)), "{step:?}"); assert!(asked[1..].iter().all(|u| query_value(u, "f") == Some("geojson")), "{asked:?}"); // A first page refused as a protocol buffer: GeoJSON pages from the start. @@ -4756,7 +4824,8 @@ mod tests { json_page(u).ok_or_else(|| "404".to_string()) } }); - let Step::Done(joined, None) = step else { panic!("{step:?}") }; + 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}"); let v: serde_json::Value = serde_json::from_slice(&joined).unwrap(); assert_eq!(v["features"].as_array().map(Vec::len), Some(5)); assert_eq!(asked.len(), 5, "the description, the refused page, then three in GeoJSON: {asked:?}"); @@ -4779,7 +4848,8 @@ mod tests { asked.push(u); step = (*pages).land(a); } - let Step::Done(joined, None) = step else { panic!("{step:?}") }; + 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}"); 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:?}"); @@ -4789,11 +4859,29 @@ mod tests { let (step, asked) = run(true, 100, &|u: &str| { 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, None) = step else { panic!("{step:?}") }; + 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}"); 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.iter().any(|u| u == query), "{asked:?}"); + assert!(note.contains("(http status: 500)"), "{note}"); + // A long reason is said cut. + let (step, _) = run(true, 100, &|u: &str| { + if query_value(u, "f") == Some("pbf") { Err("x".repeat(1000)) } else { json_page(u).ok_or_else(|| "404".to_string()) } + }); + let Step::Done(_, Some(note)) = step else { panic!("{step:?}") }; + assert!(note.len() < 300 && note.contains("x…)"), "{note}"); + // A credential in the reason isn't said (an address's query isn't, nor what follows it). + let (step, _) = run(true, 100, &|u: &str| { + if query_value(u, "f") == Some("pbf") { + Err("timed out: https://x.org/q?token=hidden".into()) + } else { + json_page(u).ok_or_else(|| "404".to_string()) + } + }); + let Step::Done(_, Some(note)) = step else { panic!("{step:?}") }; + assert!(!note.contains("hidden") && note.contains("(timed out: https://x.org/q"), "{note}"); // A later page that fails: the pages read, said. let (step, _) = run(true, 100, &|u: &str| if offset(u) == Some(2) { Err("http status: 500".into()) } else { pbf_server(u) }); @@ -4820,6 +4908,16 @@ mod tests { let Step::Decoded(ds, _, Some(note)) = step else { panic!("{step:?}") }; assert_eq!(ids(&ds), [0.0, 1.0, 2.0]); assert!(note.contains("first 3 features"), "{note}"); + // A page cut at the limit: what the features left out lost isn't counted. + let z_server = |u: &str| -> Result, String> { + let o = offset(u).ok_or_else(|| "404".to_string())?; + Ok(pbf_z(&(o..(o + 2).min(5)).collect::>(), o + 2 < 5, "OBJECTID")) + }; + let (step, _) = run(true, 3, &z_server); + let Step::Decoded(ds, report, Some(note)) = step else { panic!("{step:?}") }; + assert_eq!(ids(&ds), [0.0, 1.0, 2.0]); + assert!(note.contains("first 3 features"), "{note}"); + assert_eq!(report.messages, [crate::zm_note(Some(3))]); let fresh = || Pages { url: query.into(), @@ -4831,6 +4929,9 @@ mod tests { from: String::new(), phase: Phase::Offsets { size: 2, order: None, start: None, first: None, pbf: true }, decoded: None, + decoded_bytes: 0, + decoded_budget: max_decoded_bytes(), + pbf_failed: None, }; // A page in another coordinate system, or of another geometry type, isn't joined; one // that doesn't say its system is. @@ -4867,12 +4968,44 @@ mod tests { let Step::Fetch(first) = fresh().join_page(blank(&[0, 1])) else { panic!("the first page") }; let Step::Fetch(p) = (*first).join_page(blank(&[2, 3])) else { panic!("an empty object id taken for a page sent again") }; assert_eq!(p.read(), 4); + // A page without object ids sent again is told so, even cut shorter by the limit. + let idless = |limit: usize| { + let mut p = crate::esripbf::read_page_within(&pbf(&[0, 1], true, "OBJECTID"), "query", limit).unwrap(); + p.object_id_field = None; + p + }; + let Step::Fetch(first) = fresh().join_page(idless(usize::MAX)) else { panic!("the first page") }; + let Step::Decoded(ds, _, Some(note)) = (*first).join_page(idless(1)) else { panic!("a page sent again, cut, joined") }; + assert_eq!(ds.features.len(), 2); + assert!(note.contains("first features again"), "{note}"); + // Pages are joined by their fields' names and types: another alias doesn't stop the read. + let Step::Fetch(first) = fresh().join_page(page(&[0, 1], lonlat, point)) else { panic!("the first page") }; + let mut aliased = page(&[2, 3], lonlat, point); + aliased.dataset.fields[0].alias = Some("Object id".into()); + let Step::Fetch(p) = (*first).join_page(aliased) else { panic!("another alias taken for other fields") }; + assert_eq!(p.read(), 4); + // A page that would take the layer past its memory budget isn't joined, and says so; the + // first page is kept whatever it takes, and one within the budget is joined. + let first = page(&[0, 1], lonlat, point); + assert!(first.memory > 0); + let budget = first.memory * 3 / 2; + let Step::Fetch(mut p) = fresh().join_page(first) else { panic!("the first page") }; + p.decoded_budget = budget; + let Step::Decoded(ds, _, Some(note)) = (*p).join_page(page(&[2, 3], lonlat, point)) else { panic!("past the budget") }; + assert_eq!(ids(&ds), [0.0, 1.0]); + assert!(note.contains("after feature 2 would take the layer past 0 MB of memory"), "{note}"); + let mut p = fresh(); + p.decoded_budget = 0; + let Step::Fetch(mut p) = p.join_page(page(&[0, 1], lonlat, point)) else { panic!("the first page, over the budget") }; + p.decoded_budget = usize::MAX; + let Step::Fetch(p) = (*p).join_page(page(&[2, 3], lonlat, point)) else { panic!("within the budget") }; + assert_eq!(p.read(), 4); + assert!(p.decoded_bytes > 0); // What the features lost, summed over the pages and said once. let mut pages = fresh(); for (ids, more, rings) in [(&[0, 1][..], true, 2), (&[2, 3][..], false, 3)] { let mut page = crate::esripbf::read_page(&pbf(ids, more, "OBJECTID"), "query").unwrap(); page.losses.flat_rings = rings; - page.report.messages.extend(page.losses.messages()); pages = match pages.join_page(page) { Step::Fetch(p) => *p, Step::Decoded(_, report, None) => { @@ -4884,6 +5017,48 @@ mod tests { } } + /// Protocol buffer pages only when the layer's description lists them and names its page + /// size: a layer that names none, or doesn't list them, is read in GeoJSON as before. + #[test] + fn arcgis_pbf_pages_only_when_listed_with_a_page_size() { + let query = "https://x.org/arcgis/rest/services/P/FeatureServer/0/query?where=1%3D1&outFields=*&f=geojson"; + let description = "https://x.org/arcgis/rest/services/P/FeatureServer/0?f=json"; + // One page that holds the whole layer. + let page = br#"{"type": "FeatureCollection", "features": [{"type": "Feature", "id": 0, "properties": {}}]}"#; + for (layer, first) in [ + // No page size: the query as it is first, in GeoJSON. + (r#"{"supportedQueryFormats": "JSON, geoJSON, PBF", "advancedQueryCapabilities": {"supportsPagination": true}}"#, Some(query)), + // Protocol buffers not listed: GeoJSON pages from the start. + ( + r#"{"maxRecordCount": 1, "supportedQueryFormats": "JSON, geoJSON", "advancedQueryCapabilities": {"supportsPagination": true}}"#, + None, + ), + ] { + let mut asked = Vec::new(); + let mut step = begin_with_pbf(query, 100); + while let Step::Fetch(pages) = step { + let u = pages.next_url().to_string(); + let a = if u == description { Ok(layer.as_bytes().to_vec()) } else { Ok(page.to_vec()) }; + asked.push(u); + step = (*pages).land(a); + } + assert!(matches!(step, Step::Done(_, None)), "{layer}: {step:?}"); + assert!(asked.len() == 2 && asked[0] == description, "{layer}: {asked:?}"); + assert!(query_value(&asked[1], "f") == Some("geojson"), "{layer}: {asked:?}"); + if let Some(first) = first { + assert_eq!(asked[1], first); + } + } + } + + #[test] + fn with_format_replaces_the_format_in_any_case_and_keeps_the_fragment() { + let q = "https://x.org/FeatureServer/0/query?F=geojson&where=1%3D1&f=json#part"; + assert_eq!(with_format(q, "pbf"), "https://x.org/FeatureServer/0/query?where=1%3D1&f=pbf#part"); + assert_eq!(with_format("https://x.org/FeatureServer/0/query", "pbf"), "https://x.org/FeatureServer/0/query?f=pbf"); + assert_eq!(with_format("https://x.org/q?f=pbf", "geojson"), "https://x.org/q?f=geojson"); + } + /// An ArcGIS layer's description first: a layer that pages is read from the start in pages of /// its `maxRecordCount` ordered by its object ids (a page asked for in no order may hold other /// features than the ordered first: Hawaii's zoning did), each from where the last stopped, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e5e18421fe..2c66b1c10a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12955,8 +12955,15 @@ fn arcgis_layer_read_in_protocol_buffer_pages() { let r = s.run("service.add", &json!({"url": url, "layer": "Zoning", "text": service})).unwrap(); assert_eq!(r["features"], 3); assert!(s.map().layer_by_name("Zoning").is_some()); + // The layer read in protocol buffers says nothing; the one read in GeoJSON says why. let texts: Vec<_> = s.notices.iter().map(|n| n.text.as_str()).collect(); - assert!(!texts.iter().any(|t| t.contains("aren't read") || t.contains("protocol buffers")), "{texts:?}"); + assert!(!texts.iter().any(|t| t.contains("aren't read") || t.starts_with("Parcels")), "{texts:?}"); + assert!( + texts + .iter() + .any(|t| t.starts_with("Zoning: its protocol buffer pages couldn't be read (") && t.ends_with("so it is read in GeoJSON")), + "{texts:?}" + ); // Each layer's description, then its pages: in protocol buffers, or in GeoJSON after the one // refused. let asked: Vec<_> = server diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 5cdb7f0b67..b985ec7362 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -27,7 +27,7 @@ not every EPSG code; azimuthal equidistant systems such as Equi7 need the deskto | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed. Vector-tile `.pbf` files use Add Tile Layer instead. | -| ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | +| ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | | TopoJSON | `.topojson`, or `.json` | Add Data, drop the file, or upload | Shared arcs (quantized or not) are rebuilt into geometries. A `.topojson` adds a layer per object, up to 64; a topology named `.json` adds its first object and names the others in a notice. Use `.topojson` to add them all. | | CityJSON | `.city.json`, or `.json` | Add Data, drop the file, upload, or From URL… | CityJSON 1.1 and 2.0, read in 2D: a layer per City Object type and geometry family (a name two layers would share, such as two long types cut to their first 64 characters, or two that differ only in ASCII case, gets ` (2)`, ` (3)`… on the later ones: the first number no other layer's name uses). Surfaces and solids become footprints (LoD 0, else the `GroundSurface` surfaces, else the union of the faces of the highest LoD, else the outline of the points; a geometry of more than 200,000 faces is the outline of its points (of its ground's, for a footprint from the ground), with a notice, unless its footprint is its ground and all of its ground faces are within the cap), with `z_min`, `z_max` and `height` fields, from every level of detail and the children's heights included, so Style › Extrusion stands them up. Also `id`, `type`, `parent`, `lod` and the object's attributes. A `.city.json`, or a model from an address, adds every layer, up to 64; a file named `.json` adds its first layer with something to draw and names the others in a notice. A file that names no coordinate system and isn't longitude/latitude is refused: for now the way to add it is the `"crs"` parameter of `layer.addData`, from the command line, Python or the AI Assistant. Geometry instances are drawn as a point at their reference point, with no height, and `TINRelief` objects aren't drawn; a notice says so, as it does for addresses. Appearance (materials and textures) isn't read, and a notice says how much is left out. Heights are kept in the file's unit: in a coordinate system that doesn't measure in metres, a notice says so, as Style › Extrusion reads metres. In a zip, a `"crs"` applies only to a model that names no coordinate system RustGIS knows. In the browser a footprint that needs a union is the outline of the object's points; a notice says so. Extrusions have no base height yet, so a part above the ground stands on the ground. | | AutoCAD DXF | `.dxf` (ASCII) | Add Data, drop the file, or upload | Points, lines and polygons layers from the drawing's entities: POINT, LINE, LWPOLYLINE and POLYLINE (bulges drawn as arcs; closed ones stay lines; polyface meshes become polygons), CIRCLE, ARC, ELLIPSE, SPLINE, HELIX, LEADER, MLINE (its centre line), TEXT, MTEXT, ATTRIB and constant ATTDEF (points with their text, at the alignment point of justified text), HATCH boundaries (holes found by nesting), SOLID, TRACE and 3DFACE (polygons). Blocks (named in any case) are drawn where INSERTs place them (scaled, rotated, in arrays, nested up to 8 deep), and so are DIMENSIONs' blocks (a linear dimension without one draws its lines and measured text). Entities in an object's own coordinate system are turned into the drawing's. Fields: `layer`, `entity`, `color` (ACI, BYLAYER and BYBLOCK resolved), `linetype`, `text`, `height`, `rotation`, `block`, `elevation` and `paperspace`. The drawing's layouts (paper space: title blocks, viewport frames) are left out, with a notice, unless `"paperSpace": true`. A drawing never says its coordinate system: give `"crs"` (such as `EPSG:2263`), or its coordinates are kept as they are, with a notice. `"layer"` picks one of the drawing's own layers, and `info.fileLayers` lists them. Up to 2 million features (500,000 in the web app). Not read: binary DXF, MULTILEADER, WIPEOUT, IMAGE and ACIS solids (3DSOLID, REGION), named in a notice. | @@ -257,7 +257,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | 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 EPSG:4326, at most 2048 pixels on a side | -| ArcGIS REST | FeatureServer and MapServer layers; a MapServer's map; an ImageServer; a VectorTileServer | Layers queried as GeoJSON, or in protocol buffers (`f=pbf`, smaller and quicker to read) when the layer's description lists them and names its record limit (the description read first, or given up on after 15 seconds; a first protocol buffer page that can't be fetched or read has the layer read in GeoJSON), page by page past the server's record limit (`resultOffset`) up to 100,000 features or more on a computer with more memory (a command such as `service.add` waits a minute at most for the features), where the layer supports paging (ArcGIS Server 10.3 and later; otherwise up to the record limit); a map as its tile cache when it is Web Mercator's pyramid, else exported images; an ImageServer as exported images; a VectorTileServer as its MapLibre style | +| ArcGIS REST | FeatureServer and MapServer layers; a MapServer's map; an ImageServer; a VectorTileServer | Layers queried as GeoJSON, or in protocol buffers (`f=pbf`, smaller and quicker to read) when the layer's description lists them and names its record limit (the description read first, or given up on after 15 seconds; a first protocol buffer page that can't be fetched or read has the layer read in GeoJSON, with a notice saying why), page by page past the server's record limit (`resultOffset`) up to 100,000 features or more on a computer with more memory (in protocol buffers, also no more than a quarter of the computer's memory once read, from 512 MB, the web app's limit, up to 3 GB; a later page past it ends the read with a notice, and the first page is always kept, within the reader's own limits for a page) (a command such as `service.add` waits a minute at most for the features), where the layer supports paging (ArcGIS Server 10.3 and later; otherwise up to the record limit); a map as its tile cache when it is Web Mercator's pyramid, else exported images; an ImageServer as exported images; a VectorTileServer as its MapLibre style | A WMS or WMTS layer's tiles are asked for down to the detail its service gives, and stretched only past it: a WMTS layer's over the zooms of its tile matrix set (or those its diff --git a/tests/support/esripbf.rs b/tests/support/esripbf.rs index cd9e4e6a6e..b538a42a4f 100644 --- a/tests/support/esripbf.rs +++ b/tests/support/esripbf.rs @@ -131,3 +131,13 @@ pub fn page(ids: &[u64], more: bool, oid: &str) -> Vec { parts.extend(ids.iter().map(|&id| feature(&[uint(id), geometry(&[], &[i64::try_from(id).unwrap_or(0), 1])]))); answer(&parts) } + +/// A [`page`] whose points have Z values (100), which the reader drops and says. +pub fn page_with_z(ids: &[u64], more: bool, oid: &str) -> Vec { + let mut parts = vec![number(7, POINT), number(10, 1), lonlat(), transform(false, 1.0, 0.0, 0.0), field(oid, OID)]; + if more { + parts.push(number(9, 1)); + } + parts.extend(ids.iter().map(|&id| feature(&[uint(id), geometry(&[], &[i64::try_from(id).unwrap_or(0), 1, 100])]))); + answer(&parts) +}