Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 77 additions & 10 deletions crates/data/src/source/arcgis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ pub struct ArcgisSource {
page: std::sync::atomic::AtomicUsize,
/// Whether the layer's queries take standardized SQL (`MOD`), to sample a view.
sample: bool,
/// The system its features are asked for and held in: the layer's own when RustGIS reads it
/// ([`own_system`]), else longitude/latitude, as before.
held: crate::raster::Crs,
/// What places them in longitude/latitude, to test them against a view (none when held so).
to_lonlat: Option<crate::raster::Transformer>,
/// The code they are asked for by (`outSR`): the one the layer's description gave, or none for
/// longitude/latitude (4326).
out_sr: Option<u32>,
}

impl std::fmt::Debug for ArcgisSource {
Expand Down Expand Up @@ -119,7 +127,7 @@ pub fn open_now(remote: Arc<Remote>) -> Result<ArcgisSource> {
}
let description = crate::ogc::arcgis_layer_url(&query);
let counted = with(&query, &[("returnCountOnly", "true"), ("returnExtentOnly", "true"), ("outSR", "4326"), ("f", "json")]);
let first = with(&features_query(&query), &[("resultRecordCount", "1")]);
let first = with(&features_query(&query, None), &[("resultRecordCount", "1")]);
// Asked for together: one round.
let (d, c, f) = (remote.answer(&description)?, remote.answer(&counted)?, remote.answer(&first)?);
let (Some(d), Some(c), Some(f)) = (d, c, f) else { return Err(remote::need()) };
Expand All @@ -139,6 +147,29 @@ pub fn open_now(remote: Arc<Remote>) -> Result<ArcgisSource> {
// A view is chosen by geometry: a table is downloaded instead.
let geometry_type = geometry_of(&d).ok_or_else(|| refuse("the layer names no geometry (it is a table)"))?;
let sample = d.get("useStandardizedQueries").and_then(serde_json::Value::as_bool) == Some(true);
let (mut held, mut to_lonlat, mut out_sr) = match own_system(&d) {
Some((crs, t, code)) => (crs, Some(t), Some(code)),
None => (crate::raster::Crs::LonLat, None, None),
};
// Asked for in that system once first: a service that answers in another (or one read by its
// definition rather than its code) is asked for in longitude/latitude, as before.
if out_sr.is_some() {
let native = with(&features_query(&query, out_sr), &[("resultRecordCount", "1")]);
// An answer too large to take is read in longitude/latitude, as the first one was.
let answer = match remote.answer(&native) {
Ok(Some(answer)) => Some(answer),
Ok(None) => return Err(remote::need()),
Err(e) if remote::is_too_large(&e) => None,
Err(e) => return Err(e),
};
// In it, empty or not (a page in another system, or saying none, is read in
// longitude/latitude), or no bytes at all, which say nothing of it.
let in_it =
answer.is_some_and(|a| a.is_empty() || crate::esripbf::read_page(&a, "check").is_ok_and(|p| p.dataset.coord_crs() == held));
if !in_it {
(held, to_lonlat, out_sr) = (crate::raster::Crs::LonLat, None, None);
}
}

let c = json(&remote, &counted, &c, MAX_COUNT_ANSWER, "count")?;
let count = count_of(&c).ok_or_else(|| answer_error(&remote, &counted, "the count isn't a number"))?;
Expand All @@ -163,7 +194,7 @@ pub fn open_now(remote: Arc<Remote>) -> Result<ArcgisSource> {
fields: first.as_ref().map(|p| p.dataset.fields.clone()).unwrap_or_default(),
extent,
count: Some(count),
crs: "EPSG:4326".into(),
crs: held.label(),
indexed: true,
notes: Vec::new(),
zm_dropped: false,
Expand All @@ -177,7 +208,20 @@ pub fn open_now(remote: Arc<Remote>) -> Result<ArcgisSource> {
if !sample {
info.notes.push("its queries don't take standardized SQL, so a view holding more features than are drawn shows the first ones by object id rather than a sample of all of them".into());
}
Ok(ArcgisSource { remote, query, info, oid, oid_at, page: std::sync::atomic::AtomicUsize::new(page), sample })
Ok(ArcgisSource { remote, query, info, oid, oid_at, page: std::sync::atomic::AtomicUsize::new(page), sample, held, to_lonlat, out_sr })
}

/// The layer's own coordinate system, from its description's extent (`latestWkid`, else `wkid`),
/// with what places it in longitude/latitude and the code read: `None` when it is
/// longitude/latitude or one RustGIS can't read, which is asked for in longitude/latitude instead.
fn own_system(description: &serde_json::Value) -> Option<(crate::raster::Crs, crate::raster::Transformer, u32)> {
let reference = description.pointer("/extent/spatialReference").or_else(|| description.get("sourceSpatialReference"))?;
let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok());
let (crs, code) = [code("latestWkid"), code("wkid")].into_iter().flatten().find_map(|c| Some((crate::filegdb::crs_of_code(c)?, c)))?;
if crs == crate::raster::Crs::LonLat {
return None;
}
Some((crs, crs.transformer().ok()?, code))
}

/// What a read says of the features a service counted but didn't send (none when it sent them
Expand Down Expand Up @@ -206,11 +250,13 @@ fn with(query: &str, values: &[(&str, &str)]) -> String {
values.iter().fold(query.to_string(), |q, (k, v)| crate::ogc::with_query_value(&q, k, v))
}

/// The layer's query asking for features in protocol buffers, in longitude/latitude, with every
/// field unless it names its own.
fn features_query(query: &str) -> String {
/// The layer's query asking for features in protocol buffers, in the system `out_sr` codes (none
/// for longitude/latitude), with every field unless it names its own.
fn features_query(query: &str, out_sr: Option<u32>) -> String {
// By the code the layer's description gave its own system, or 4326.
let out_sr = out_sr.unwrap_or(4326).to_string();
// With geometry, whatever the query said: a view is chosen by it.
let q = with(query, &[("outSR", "4326"), ("f", "pbf"), ("returnGeometry", "true")]);
let q = with(query, &[("outSR", &out_sr), ("f", "pbf"), ("returnGeometry", "true")]);
if crate::ogc::query_value(&q, "outFields").is_some_and(|f| !f.is_empty()) { q } else { with(&q, &[("outFields", "*")]) }
}

Expand Down Expand Up @@ -289,7 +335,7 @@ fn step_for(matched: u64, limit: usize) -> u64 {
impl ArcgisSource {
/// The query of the features in `cell` (all of them for none), every `step`-th by object id.
fn query_of(&self, cell: Option<&Extent>, step: u64) -> String {
let q = features_query(&self.query);
let q = features_query(&self.query, self.out_sr);
let q = match cell {
Some(c) => with(
&q,
Expand Down Expand Up @@ -350,6 +396,14 @@ impl ArcgisSource {
notes
}

/// Whether a feature, held in the layer's system, meets a view in longitude/latitude.
fn meets(&self, g: &crate::Geometry, view: &Extent) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

meets returns false for any feature whose lon/lat box can't be computed. lonlat_box (io.rs) returns None when any single vertex fails to transform or falls outside ±180.5/±90.5. Such a feature is then left out of view reads without any notice, and the count-based shortfall check won't catch it because the feature was already received. Before this PR, the test was a plain extent intersection and never dropped a feature this way. Impact is probably small, since such features are usually invalid, but it is a silent exclusion. Suggestion: count the features excluded this way and report them in the layer's notes, or test the feature's extent after transforming only its bounding corners. Confidence about 30%. I also haven't checked whether a projected system can produce a lon/lat slightly outside ±180.5 for valid features near the antimeridian.

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature can't reach meets without a lon/lat box: the page decoder (esripbf::read_page) already tests each geometry with the same lonlat_box and keeps only those with a place, counting the others (Losses::unprojected), which every read says as "features have coordinates outside their coordinate system, so are left out of the view". So meets never drops one unsaid; near the antimeridian, the ±180.5 margin is the decoder's as well.

match &self.to_lonlat {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

meets transforms every vertex of each received feature again (io::lonlat_box), but the page decoder has already done the same transform for each geometry (esripbf.rs, the lonlat_box(&g, t) call in the feature loop). On a projected ArcGIS layer, every view read and whole-layer read therefore converts each feature's vertices twice. For large polygons this roughly doubles the reprojection time of the read, with no change in the result. Suggestion: have the decoder keep the lon/lat box it computes (or the view test) so meets reuses it, rather than transforming a second time.

Confidence: about 70% that the cost is real and noticeable on large polygon layers. I haven't measured it.

Category: performance

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

Some(t) => crate::io::lonlat_box(g, t).is_some_and(|b| b.intersects(view)),
None => g.extent().intersects(view),
}
}

/// The features a page asks for now.
fn page(&self) -> usize {
self.page.load(std::sync::atomic::Ordering::Relaxed)
Expand Down Expand Up @@ -488,7 +542,7 @@ impl ArcgisSource {
received = received.saturating_add(sent as u64);
for f in got {
let inside = match (&view, &f.geometry) {
(Some(v), Some(g)) => g.extent().intersects(v),
(Some(v), Some(g)) => self.meets(g, v),
(Some(_), None) => false,
(None, _) => true,
};
Expand Down Expand Up @@ -576,6 +630,14 @@ impl ArcgisSource {
"the layer's fields changed since it was added; add it again",
)));
}
// In the system asked for: a page in another can't be read as if it were.
if !page.dataset.features.is_empty() && page.dataset.coord_crs() != self.held {
self.remote.forget_answer(url);
return Err(DataError::Format(crate::diagnostics::message_with_address(
&self.query,
&format!("the service answered in {}, not the {} asked for", page.dataset.coord_crs().label(), self.held.label()),
)));
}
*skipped = skipped.saturating_add(page.report.skipped);
losses.add(&page.losses);
let sent = page.dataset.features.len();
Expand All @@ -598,6 +660,11 @@ impl FeatureSource for ArcgisSource {
&self.info
}

/// The layer's own system when RustGIS reads it, else longitude/latitude.
fn coord_crs(&self) -> crate::raster::Crs {
self.held
}

fn remote(&self) -> Option<Arc<Remote>> {
Some(self.remote.clone())
}
Expand Down Expand Up @@ -714,7 +781,7 @@ impl FeatureSource for ArcgisSource {
let (got, more, sent) = self.page_of(url, &answer, &mut skipped, &mut losses).inspect_err(|_| forget(&urls))?;
drop(answer);
for f in got {
if view.as_ref().is_none_or(|v| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(v))) {
if view.as_ref().is_none_or(|v| f.geometry.as_ref().is_some_and(|g| self.meets(g, v))) {
visited += 1;
chunks.push(f).inspect_err(|_| forget(&urls))?;
}
Expand Down
86 changes: 84 additions & 2 deletions crates/data/src/source/arcgis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ struct Opts {
over: usize,
/// An answer of no features is no bytes at all.
empty_body: bool,
/// Its layer is in Web Mercator (its description says so), and it answers in the system
/// asked for (`outSR`), Web Mercator or longitude/latitude.
mercator: bool,
/// With `mercator`, its first feature asked for in Web Mercator is an answer too large to
/// take.
probe_too_large: bool,
/// With `mercator`, it answers the first feature asked for in Web Mercator with an empty page
/// in longitude/latitude.
probe_empty_lonlat: bool,
}

impl Default for Opts {
Expand All @@ -75,6 +84,9 @@ impl Default for Opts {
hidden: 0,
over: 0,
empty_body: false,
mercator: false,
probe_too_large: false,
probe_empty_lonlat: false,
}
}
}
Expand Down Expand Up @@ -104,6 +116,9 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc<Asked>) {
hidden,
over,
empty_body,
mercator,
probe_too_large,
probe_empty_lonlat,
} = opts;
let layer = format!("https://{host}/arcgis/rest/services/P/FeatureServer/0");
let asked = Arc::new(Asked::default());
Expand All @@ -117,7 +132,8 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc<Asked>) {
Some(d) => d.as_bytes().to_vec(),
None => format!(
r#"{{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":{page},"supportedQueryFormats":"JSON, geoJSON, PBF","geometryType":"esriGeometryPoint",
"useStandardizedQueries":{sql},"advancedQueryCapabilities":{{"supportsPagination":true}}}}"#
"useStandardizedQueries":{sql},"advancedQueryCapabilities":{{"supportsPagination":true}}{}}}"#,
if mercator { r#","extent":{"xmin":0,"ymin":0,"xmax":1,"ymax":1,"spatialReference":{"wkid":102100,"latestWkid":3857}}"# } else { "" }
)
.into_bytes(),
});
Expand Down Expand Up @@ -153,7 +169,16 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc<Asked>) {
return Some(Vec::new());
}
let geometry_too = value("returnGeometry").as_deref() != Some("false");
let mut parts = vec![number(7, 0), lonlat(), transform(false, 0.01, 0.0, 0.0)];
let in_mercator = mercator && value("outSR").as_deref() == Some("3857");
let probe = in_mercator && value("resultRecordCount").as_deref() == Some("1") && value("resultOffset").is_none();
if probe && probe_too_large {
return Some(vec![0; usize::try_from(remote::MAX_ANSWER).unwrap() + 1]);
}
if probe && probe_empty_lonlat {
return Some(answer(&[number(7, 0), lonlat(), transform(false, 0.01, 0.0, 0.0), field("OBJECTID", 6)]));
}
let reference = if in_mercator { message(8, &number(1, 3857)) } else { lonlat() };
let mut parts = vec![number(7, 0), reference, transform(false, 0.01, 0.0, 0.0)];
if !(sent.is_empty() && empty_without_fields) {
parts.push(field("OBJECTID", 6));
if padded {
Expand All @@ -171,6 +196,12 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc<Asked>) {
}
for id in sent {
let (x, y) = position(id);
let (x, y) = if in_mercator {
let m = rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(x, y));
(m.x, m.y)
} else {
(x, y)
};
let mut at = vec![(x * 100.0).round() as i64, (y * 100.0).round() as i64];
if z {
at.push(100);
Expand Down Expand Up @@ -608,3 +639,54 @@ fn a_layer_matching_nothing_may_answer_with_no_bytes() {
let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap();
assert!(b.complete && b.features.is_empty());
}

/// A layer in a system RustGIS reads is asked for and held in it (`outSR` its code), each feature
/// as the service sends it, and a view still takes the features it holds; one in a system RustGIS
/// can't read is asked for in longitude/latitude, as before.
#[test]
fn a_layer_is_read_in_its_own_system() {
let (query, asked) = service_with("own-system.test", Opts { page: 30, mercator: true, ..Opts::default() });
let src = open_blocking(&query).unwrap();
assert_eq!((src.coord_crs(), src.info.crs.as_str()), (crate::raster::Crs::WebMercator, "EPSG:3857"));
let before = asked.count.load(Ordering::Relaxed);
let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap();
let want: Vec<u64> = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect();
assert_eq!(ids(&b), want);
let pages: Vec<String> = asked.since(before).into_iter().filter(|u| u.contains("resultOffset")).collect();
assert!(!pages.is_empty() && pages.iter().all(|u| u.contains("outSR=3857")), "{pages:?}");
for f in &b.features {
let (x, y) = position(f.id);
let m = rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(x, y));
let Some(crate::Geometry::Point(c)) = &f.geometry else { panic!() };
assert!((c.x - m.x).abs() < 0.01 && (c.y - m.y).abs() < 0.01, "{c:?} vs {m:?}");
}
// A whole-layer read within the view takes the same features, tested in longitude/latitude.
let mut inside = Vec::new();
src.visit_chunks(Some(small_view()), 4 << 10, &mut |c| {
inside.extend(c.iter().map(|f| f.id));
Ok(())
})
.unwrap();
inside.sort_unstable();
assert_eq!(inside, want);
// A first page in Web Mercator too large to take, or empty and in another system: asked for
// in longitude/latitude, as before.
for (host, opts) in [
("probe-large.test", Opts { page: 30, mercator: true, probe_too_large: true, ..Opts::default() }),
("probe-empty.test", Opts { page: 30, mercator: true, probe_empty_lonlat: true, ..Opts::default() }),
] {
let (query, _) = service_with(host, opts);
let src = open_blocking(&query).unwrap();
assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat, "{host}");
assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap()), want, "{host}");
}
// A code RustGIS doesn't read: longitude/latitude, as before.
let description = r#"{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":30,"supportedQueryFormats":"PBF","geometryType":"esriGeometryPoint",
"useStandardizedQueries":true,"advancedQueryCapabilities":{"supportsPagination":true},"extent":{"spatialReference":{"wkid":999999}}}"#;
let (query, asked) = service("unknown-system.test", 30, true, Some(description));
let src = open_blocking(&query).unwrap();
assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat);
let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap();
assert_eq!(ids(&b), want);
assert!(asked.since(0).iter().filter(|u| u.contains("resultOffset")).all(|u| u.contains("outSR=4326")));
}
Loading
Loading