diff --git a/crates/data/src/source/chunk_memory.rs b/crates/data/src/source/chunk_memory.rs index e9cd4a258f..4f5d5244c4 100644 --- a/crates/data/src/source/chunk_memory.rs +++ b/crates/data/src/source/chunk_memory.rs @@ -1,4 +1,4 @@ -//! Allocation accounting for complete render chunks. +//! Allocation accounting for the chunks of a complete traversal (drawing, exports). use crate::{Feature, Geometry, Value}; use std::mem::size_of; @@ -33,3 +33,50 @@ pub fn feature_bytes(f: &Feature) -> usize { pub fn features_bytes(features: &Vec) -> usize { features.iter().fold(features.capacity().saturating_mul(size_of::()), |n, f| n.saturating_add(feature_bytes(f))) } + +/// Gathers features into chunks of at most `bytes` of owned storage for +/// [`FeatureSource::visit_chunks`](super::FeatureSource::visit_chunks), handing each to the +/// visitor as it fills. A feature larger than the target on its own is handed over alone. +pub(crate) struct Chunker<'a> { + bytes: usize, + used: usize, + features: Vec, + visit: &'a mut dyn FnMut(Vec) -> crate::Result<()>, +} + +impl<'a> Chunker<'a> { + /// Refuses a zero target, which no feature fits. + pub(crate) fn new(bytes: usize, visit: &'a mut dyn FnMut(Vec) -> crate::Result<()>) -> crate::Result { + if bytes == 0 { + return Err(crate::DataError::Format("the chunk memory budget is zero".into())); + } + Ok(Chunker { bytes, used: 0, features: Vec::new(), visit }) + } + + /// Adds a feature, first handing over the chunk it would overflow. + pub(crate) fn push(&mut self, feature: Feature) -> crate::Result<()> { + let size = feature_bytes(&feature).saturating_add(size_of::()); + if !self.features.is_empty() && self.used.saturating_add(size) > self.bytes { + self.flush()?; + } + // A geometry is indivisible: a row bigger than the target is kept whole rather than + // dropped or failing the whole traversal. + if size > self.bytes { + return (self.visit)(vec![feature]); + } + self.used = self.used.saturating_add(size); + self.features.push(feature); + Ok(()) + } + + /// Hands over the features gathered so far, if any. + pub(crate) fn flush(&mut self) -> crate::Result<()> { + if self.features.is_empty() { + return Ok(()); + } + let mut chunk = std::mem::take(&mut self.features); + chunk.shrink_to_fit(); + self.used = 0; + (self.visit)(chunk) + } +} diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 5ef57d08b0..88d1acec42 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -175,6 +175,59 @@ impl FgbSource { Ok(out) } + /// Visits the features a complete [`FgbSource::read_with`] of `extent` gives, in the same + /// order and with the same ids, a chunk at a time. An extent read through the index holds + /// the feature numbers it finds (8 bytes each) for the ids, as a read does. + fn visit_with( + &self, + open: &impl Fn() -> Result, + extent: Option, + chunks: &mut super::chunk_memory::Chunker<'_>, + ) -> Result { + let req = Request { extent, limit: usize::MAX }; + let reader = open_reader(open()?)?; + let native = extent.map(|e| self.reproject.extent_from_lonlat(&e)); + let indexed = native.filter(|_| self.info.indexed); + let mut numbers: Option> = match indexed { + Some(e) => Some(self.search(open()?, &e)?), + None => None, + }; + let mut iter = match indexed { + Some(e) => reader.select_bbox(e.min_x, e.min_y, e.max_x, e.max_y).map_err(err)?, + None => reader.select_all().map_err(err)?, + }; + // As in a read: an index walk that disagrees with the selection is not trusted for ids. + if let Some(nums) = &numbers + && iter.features_count() != Some(nums.len()) + { + numbers = None; + iter = open_reader(open()?)?.select_all().map_err(err)?; + } + let mut out = Batch { complete: true, ..Batch::default() }; + let mut n = 0u64; + while let Some(f) = iter.next().map_err(err)? { + n += 1; + let id = numbers.as_ref().and_then(|v| v.get(usize::try_from(n - 1).unwrap_or(usize::MAX)).copied()).unwrap_or(n); + let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.geometry(g)); + let Some(geometry) = geometry else { + out.skipped += 1; + continue; + }; + if !in_request(&geometry, &req) { + continue; + } + let mut props = Props { fields: &self.info.fields, values: vec![Value::Null; self.info.fields.len()] }; + if f.process_properties(&mut props).is_err() { + out.skipped += 1; + continue; + } + out.matched += 1; + chunks.push(Feature { id, geometry: Some(geometry), attrs: props.values })?; + } + chunks.flush()?; + Ok(out) + } + /// The geometry type of a file that declares none (mixed output), from its first features: a /// read that stops there, not a pass over the file. fn peek_kind(&self) -> GeometryType { @@ -480,6 +533,22 @@ impl FeatureSource for FgbSource { _ => None, } } + + /// A file or an upload; a file by its web address is read a view at a time, not in full. + fn visits_chunks(&self) -> bool { + !matches!(self.input, Input::Remote(_)) + } + + /// In file order, or the index's order for an extent, as a read; one feature decoded at a + /// time from the file or upload. + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + match &self.input { + Input::Path(p) => self.visit_with(&|| Ok(BufReader::new(std::fs::File::open(p)?)), extent, &mut chunks), + Input::Bytes(b) => self.visit_with(&|| Ok(Cursor::new(b.clone())), extent, &mut chunks), + Input::Remote(_) => Err(DataError::Unsupported("a whole FlatGeobuf by its web address read a chunk at a time".into())), + } + } } /// FlatBuffers verifies the header's layout, not the index arithmetic it advertises. diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index b21a986501..a05f7796e3 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -30,6 +30,9 @@ pub struct GpkgSource { reproject: Reproject, /// A copy written for a file opened from memory, removed when the source is dropped. temp: Option, + /// The database file and its identity when opened ([`file_identity`]), for a traversal on a + /// connection of its own to check it reads the same file. + file: Option<(PathBuf, Option<(u64, u64)>)>, } impl Drop for GpkgSource { @@ -69,7 +72,10 @@ fn feature_tables(conn: &Connection) -> Result> { impl GpkgSource { pub fn open(path: &Path, layer: Option<&str>) -> Result { - Self::open_conn(open_db(path)?, layer, None) + // The identity is taken before the database is opened: a file put in its place after + // this leaves it describing the file opened, which a traversal then refuses to swap. + let id = file_identity(path); + Self::open_conn(open_db(path)?, layer, None, id) } /// Opens a GeoPackage held in memory, through a temporary copy (SQLite reads files). The copy @@ -100,7 +106,8 @@ impl GpkgSource { return Err(e.into()); } drop(f); - match open_db(&p).and_then(|c| Self::open_conn(c, layer, Some(p.clone()))) { + let id = file_identity(&p); + match open_db(&p).and_then(|c| Self::open_conn(c, layer, Some(p.clone()), id)) { Ok(s) => Ok(s), Err(e) => { let _ = std::fs::remove_file(&p); @@ -109,7 +116,8 @@ impl GpkgSource { } } - fn open_conn(conn: Connection, layer: Option<&str>, temp: Option) -> Result { + /// A source on an open database; `id` is the file's identity taken before it was opened. + fn open_conn(conn: Connection, layer: Option<&str>, temp: Option, id: Option<(u64, u64)>) -> Result { let tables = feature_tables(&conn)?; let table = match layer { Some(l) => tables @@ -212,7 +220,8 @@ impl GpkgSource { indexed: rtree.is_some(), notes, }; - let mut src = GpkgSource { info, conn: Mutex::new(Some(conn)), table, geom, pk, rtree, reproject, temp }; + let file = conn.path().filter(|p| !p.is_empty()).map(|p| (PathBuf::from(p), id)); + let mut src = GpkgSource { info, conn: Mutex::new(Some(conn)), table, geom, pk, rtree, reproject, temp, file }; if src.info.geometry_type == GeometryType::None { src.info.geometry_type = src.peek_kind(); } @@ -368,6 +377,63 @@ impl FeatureSource for GpkgSource { } Ok(out) } + + /// Every table in a file is scanned in full, whatever its index. + fn visits_chunks(&self) -> bool { + self.file.is_some() + } + + /// A scan in table order: the envelope in each geometry's header tests the extent before + /// decoding, as a read without the spatial index does, with the same statement. It runs on a + /// read-only connection of its own, one statement and so one snapshot of the database, so + /// the map's reads of the layer go on and nothing is locked while the visitor runs. A file + /// put in place of the one opened is refused (where the system says files' identities). + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + let Some((path, id)) = &self.file else { return Err(DataError::Format("GeoPackage: no file to read".into())) }; + let same_file = || { + if id.is_some() && file_identity(path) != *id { + return Err(DataError::Format(format!("{}: the file was replaced since it was added; add it again", path.display()))); + } + Ok(()) + }; + same_file()?; + let conn = open_db(path)?; + same_file()?; + let req = Request { extent, limit: usize::MAX }; + let native = extent.map(|e| self.reproject.extent_from_lonlat(&e)); + let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table)); + let mut st = conn.prepare(&sql).map_err(err)?; + let mut rows = st.query([]).map_err(err)?; + let mut out = Batch { complete: true, ..Batch::default() }; + while let Some(r) = rows.next().map_err(err)? { + match self.feature(r, native.as_ref(), &req).map_err(err)? { + Row::Feature(f) => { + out.matched += 1; + chunks.push(f)?; + } + Row::Skip => {} + Row::Bad => out.skipped += 1, + } + } + chunks.flush()?; + Ok(out) + } +} + +/// A file's device and inode, which tell it from another file put at its path since; `None` +/// where the system doesn't say them. +fn file_identity(path: &Path) -> Option<(u64, u64)> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(path).ok().map(|m| (m.dev(), m.ino())) + } + #[cfg(not(unix))] + { + let _ = path; + None + } } /// WGS 84 as OGC WKT, the coordinate system GeoPackages are written in. diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 24ae53cf48..241b4ca283 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -284,18 +284,77 @@ impl FeatureSource for GpkgMemSource { if !in_request(&geometry, req) || (!known && !sample.wants()) { return ControlFlow::Continue(()); } - let attrs = self - .info - .fields - .iter() - .zip(&self.field_cols) - .map(|(f, &c)| r.get(c).map(|v| value(v, f.ty)).unwrap_or(Value::Null)) - .collect(); // Integer keys, negative ones too, map to distinct ids. - sample.keep(Feature { id: rowid as u64, geometry: Some(geometry), attrs }); + sample.keep(Feature { id: rowid as u64, geometry: Some(geometry), attrs: self.attrs(r) }); ControlFlow::Continue(()) }) .map_err(err)?; Ok(Batch { matched: sample.seen(), complete: sample.complete(), features: sample.items, skipped }) } + + /// The upload is held in memory already, so every table can be visited. + fn visits_chunks(&self) -> bool { + true + } + + /// A scan in table order, keeping and skipping the rows a whole read does. + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + let req = Request { extent, limit: usize::MAX }; + let native = extent.map(|e| self.reproject.extent_from_lonlat(&e)); + let mut out = Batch { complete: true, ..Batch::default() }; + // The visitor's error, which stops the scan. + let mut failed = None; + self.db + .rows(&self.table, |rowid, r| { + let blob = match r.get(self.geom_col) { + Some(Val::Blob(b)) => b, + Some(Val::Null) | None => return ControlFlow::Continue(()), + Some(_) => { + out.skipped += 1; + return ControlFlow::Continue(()); + } + }; + if super::gpkg_blob::is_empty_blob(blob) { + return ControlFlow::Continue(()); + } + let Some((envelope, body)) = super::gpkg_blob::split_blob(blob) else { + out.skipped += 1; + return ControlFlow::Continue(()); + }; + if let (Some(q), Some(e)) = (&native, envelope) + && !e.intersects(q) + { + return ControlFlow::Continue(()); + } + let Some(geometry) = wkb::decode(body).and_then(|g| self.reproject.geometry(g)) else { + out.skipped += 1; + return ControlFlow::Continue(()); + }; + if !in_request(&geometry, &req) { + return ControlFlow::Continue(()); + } + out.matched += 1; + match chunks.push(Feature { id: rowid as u64, geometry: Some(geometry), attrs: self.attrs(r) }) { + Ok(()) => ControlFlow::Continue(()), + Err(e) => { + failed = Some(e); + ControlFlow::Break(()) + } + } + }) + .map_err(err)?; + if let Some(e) = failed { + return Err(e); + } + chunks.flush()?; + Ok(out) + } +} + +impl GpkgMemSource { + /// A row's field values, in `info.fields` order. + fn attrs(&self, r: &[Val]) -> Vec { + self.info.fields.iter().zip(&self.field_cols).map(|(f, &c)| r.get(c).map(|v| value(v, f.ty)).unwrap_or(Value::Null)).collect() + } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index a4862b605c..ae19f38702 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -202,15 +202,30 @@ pub struct Batch { /// A vector data source read in place. pub trait FeatureSource: Send + Sync { - /// Whether complete, ordered traversal is available without an interaction row limit. + /// Whether the map draws the source by complete traversal ([`FeatureSource::visit_chunks`]) + /// on every render rather than from a sampled view window. Implies + /// [`FeatureSource::visits_chunks`]. fn streams_chunks(&self) -> bool { false } - /// Visits every matching feature in source painter order. Release each chunk before the - /// next callback. `bytes` targets owned feature storage; an indivisible larger row is emitted alone. - /// Callback errors stop traversal. Success returns an empty, complete summary batch. + /// Whether [`FeatureSource::visit_chunks`] is available, for a pass over the whole source + /// (an export) that holds one chunk at a time. Unlike [`FeatureSource::streams_chunks`], it + /// leaves drawing alone. + fn visits_chunks(&self) -> bool { + self.streams_chunks() + } + /// Visits every matching feature in source painter order: the features and ids a complete + /// [`FeatureSource::read`] of the same extent gives, in the same order and with the same + /// skipped count when there is no extent (an extent read through an index may order and skip + /// differently). Release each chunk before the next callback. `bytes` targets owned feature + /// storage; an indivisible larger row is emitted alone, and a provider may hold its own unit + /// of the file (a GeoParquet row group) or an index's list of matches (FlatGeobuf, for an + /// extent) besides. Callback errors stop traversal. Success returns an empty, complete + /// summary batch. Its `matched` is the provider's count of matches: the features visited for + /// GeoPackage, FlatGeobuf and GeoParquet, the records the index matched for Shapefile (which + /// may include rows skipped or deleted). fn visit_chunks(&self, _extent: Option, _bytes: usize, _visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { - Err(DataError::Format("this provider does not support chunk traversal".into())) + Err(DataError::Unsupported("a source that can't be read a chunk at a time".into())) } fn info(&self) -> &SourceInfo; /// Whether features were left out of every read because the coordinate system the source diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 7fe3e02737..c845a7d977 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -47,6 +47,8 @@ pub struct ParquetSource { remote: Option>, /// Every row group meeting a read's extent is read (a catalog's index), never a sample of them. exact: bool, + /// The most rows read from one row group: `MAX_GROUP_ROWS`, lowered by tests. + group_rows: usize, } impl ParquetSource { @@ -212,7 +214,8 @@ impl ParquetSource { indexed: covering.is_some(), notes, }; - let mut src = ParquetSource { info, reader, geom_col, field_cols, covering, reproject, remote, exact: false }; + let mut src = + ParquetSource { info, reader, geom_col, field_cols, covering, reproject, remote, exact: false, group_rows: MAX_GROUP_ROWS }; if src.info.geometry_type == GeometryType::None { src.info.geometry_type = super::peek_kind(&src); } @@ -220,6 +223,39 @@ impl ParquetSource { } } +impl ParquetSource { + /// A source that reads at most `rows` of a row group, for tests of the cap. + #[cfg(test)] + pub(crate) fn with_group_rows(mut self, rows: usize) -> Self { + self.group_rows = rows; + self + } + + /// The rows of row group `g` read. Row counts come from the file: bounded by what the + /// geometry column chunk holds, and by a cap, so a crafted count can't size a huge allocation. + fn rows_in(&self, md: &ParquetMetaData, g: usize) -> usize { + let rg = md.row_group(g); + let rows = usize::try_from(rg.num_rows()).unwrap_or(0); + let values = rg.columns().get(self.geom_col).and_then(|c| usize::try_from(c.num_values()).ok()).unwrap_or(0); + rows.min(values).min(self.group_rows) + } + + /// Which rows of row group `g` have a bounding box meeting the native extent `e`, read from + /// the covering columns `c` alone. A row without a box is kept, for its geometry to decide. + fn covered_rows(&self, md: &ParquetMetaData, g: usize, e: &Extent, c: [usize; 4]) -> Result> { + let rg = self.reader.get_row_group(g).map_err(err)?; + let n = self.rows_in(md, g); + let cols: Vec>> = c.iter().map(|&i| read_f64(rg.as_ref(), i, n)).collect::>()?; + let v = |k: usize, r: usize| cols.get(k).and_then(|c| c.get(r).copied().flatten()).unwrap_or(f64::NAN); + Ok((0..n) + .map(|r| { + let be = Extent::new(v(0, r), v(1, r), v(2, r), v(3, r)); + be.is_empty() || be.intersects(e) + }) + .collect()) + } +} + impl FeatureSource for ParquetSource { fn info(&self) -> &SourceInfo { &self.info @@ -229,14 +265,7 @@ impl FeatureSource for ParquetSource { let limit = clamp_limit(req.limit); let md = self.reader.metadata(); let native = req.extent.map(|e| self.reproject.extent_from_lonlat(&e)); - // Row counts come from the file: bounded by what the geometry column chunk holds, and by a - // cap, so a crafted count can't size a huge allocation. - let rows_in = |g: usize| { - let rg = md.row_group(g); - let rows = usize::try_from(rg.num_rows()).unwrap_or(0); - let values = rg.columns().get(self.geom_col).and_then(|c| usize::try_from(c.num_values()).ok()).unwrap_or(0); - rows.min(values).min(MAX_GROUP_ROWS) - }; + let rows_in = |g: usize| self.rows_in(md, g); // Row groups whose bounding box meets the extent. let mut groups: Vec = (0..md.num_row_groups()) .filter(|&g| match (native, self.covering) { @@ -287,20 +316,7 @@ impl FeatureSource for ParquetSource { for &g in &groups { keep.push(match (native, self.covering) { (Some(_), Some(_)) if inside(g) => None, - (Some(e), Some(c)) => { - let rg = self.reader.get_row_group(g).map_err(err)?; - let n = rows_in(g); - let cols: Vec>> = c.iter().map(|&i| read_f64(rg.as_ref(), i, n)).collect::>()?; - let v = |k: usize, r: usize| cols.get(k).and_then(|c| c.get(r).copied().flatten()).unwrap_or(f64::NAN); - Some( - (0..n) - .map(|r| { - let be = Extent::new(v(0, r), v(1, r), v(2, r), v(3, r)); - be.is_empty() || be.intersects(&e) - }) - .collect(), - ) - } + (Some(e), Some(c)) => Some(self.covered_rows(md, g, &e, c)?), _ => None, }); } @@ -359,7 +375,7 @@ impl FeatureSource for ParquetSource { continue; } let values = attrs.iter().map(|col| col.get(k).cloned().unwrap_or(Value::Null)).collect(); - sample.keep(Feature { id: base + r as u64 + 1, geometry: Some(geometry), attrs: values }); + sample.keep(Feature { id: base.saturating_add(r as u64 + 1), geometry: Some(geometry), attrs: values }); } } let matched = if late { sample.seen() } else { matched.saturating_mul(thinned as u64) }; @@ -369,6 +385,83 @@ impl FeatureSource for ParquetSource { fn remote(&self) -> Option> { self.remote.clone() } + + /// A file or an upload; a file by its web address is read a view at a time, not in full. + fn visits_chunks(&self) -> bool { + self.remote.is_none() + } + + /// A row group at a time, in file order: the features, ids and skipped rows of a complete + /// read of the same extent. The taken rows of one row group are decoded together before + /// they are chunked, so the peak is a row group's columns plus a chunk. + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + if self.remote.is_some() { + return Err(DataError::Unsupported("a whole GeoParquet by its web address read a chunk at a time".into())); + } + let req = Request { extent, limit: usize::MAX }; + let md = self.reader.metadata(); + let native = extent.map(|e| self.reproject.extent_from_lonlat(&e)); + let mut out = Batch { complete: true, ..Batch::default() }; + let mut base = 0u64; + for g in 0..md.num_row_groups() { + // From the declared row counts, as a read numbers them. + let start = base; + let declared = u64::try_from(md.row_group(g).num_rows()).unwrap_or(0); + base = base.saturating_add(declared); + let area = match (native, self.covering) { + (Some(e), Some(c)) => Some((e, c, group_extent(md, g, c))), + _ => None, + }; + if let Some((e, _, Some(ge))) = area + && !ge.intersects(&e) + { + continue; + } + // A read takes at most `MAX_GROUP_ROWS` of a row group, and no more than its geometry + // column holds. A traversal promises every row, so a group it can't read whole is an + // error, not a quietly shorter export; it is refused before anything is read. + let readable = self.rows_in(md, g); + if declared > self.group_rows as u64 { + return Err(DataError::Format(format!( + "GeoParquet: row group {g} has {declared} rows, more than the {} read from one", + self.group_rows + ))); + } + if declared > readable as u64 { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + let take = match area { + Some((e, c, ge)) if !ge.is_some_and(|ge| contains(&e, &ge)) => self.covered_rows(md, g, &e, c)?, + _ => vec![true; readable], + }; + if !take.iter().any(|&t| t) { + continue; + } + let rg = self.reader.get_row_group(g).map_err(err)?; + let geoms = read_bytes(rg.as_ref(), self.geom_col, &take)?; + let attrs: Vec> = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take)).collect::>()?; + let wanted = take.iter().filter(|&&t| t).count(); + if geoms.len() != wanted || attrs.iter().any(|a| a.len() != wanted) { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + for (k, (r, _)) in take.iter().enumerate().filter(|(_, t)| **t).enumerate() { + let geometry = geoms.get(k).and_then(|b| b.as_deref()).and_then(wkb::decode).and_then(|geom| self.reproject.geometry(geom)); + let Some(geometry) = geometry else { + out.skipped += 1; + continue; + }; + if !in_request(&geometry, &req) { + continue; + } + let values = attrs.iter().map(|col| col.get(k).cloned().unwrap_or(Value::Null)).collect(); + out.matched += 1; + chunks.push(Feature { id: start.saturating_add(r as u64 + 1), geometry: Some(geometry), attrs: values })?; + } + } + chunks.flush()?; + Ok(out) + } } /// The footer read first from a file by its address: enough for most files' metadata. diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 569d40b365..ac418ffd72 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -220,20 +220,16 @@ impl FeatureSource for ShpSource { } fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let encoding = self.encoding.decoder(); - if bytes == 0 { - return Err(bad("the render memory budget is zero")); - } + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let extent = extent.map(|e| self.reproject.extent_from_lonlat(&e)); if extent.is_some_and(|e| e.is_empty()) { return Ok(Batch { complete: true, ..Batch::default() }); } let bounds = extent.map(|e| [e.min_x as f32, e.min_y as f32, e.max_x as f32, e.max_y as f32]); - let mut used = 0usize; let mut shp = Cursor::open(&self.shp)?; let mut dbf = Cursor::open(&self.dbf)?; let mut buf = Vec::new(); let mut row = vec![0u8; self.table.row_len]; - let mut features = Vec::new(); let mut skipped = 0; // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing @@ -278,27 +274,9 @@ impl FeatureSource for ShpSource { } else { vec![Value::Null; self.table.columns.len()] }; - let feature = Feature { id: u64::from(i) + 1, geometry, attrs }; - let size = super::chunk_memory::feature_bytes(&feature).saturating_add(std::mem::size_of::()); - if !features.is_empty() && used.saturating_add(size) > bytes { - features.shrink_to_fit(); - visit(std::mem::take(&mut features))?; - used = 0; - } - // A geometry is indivisible. Preserve a valid detailed row instead of dropping it - // or failing the entire layer when it alone exceeds the chunk target. - if size > bytes { - visit(vec![feature])?; - return Ok(()); - } - used = used.saturating_add(size); - features.push(feature); - Ok(()) + chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs }) })?; - if !features.is_empty() { - features.shrink_to_fit(); - visit(features)?; - } + chunks.flush()?; Ok(Batch { features: Vec::new(), matched, complete, skipped }) } } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 71ec5783fd..4257257faf 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1769,3 +1769,126 @@ fn shapefile_complete_chunks_keep_all_rows_order_attributes_and_budget() { .unwrap(); assert_eq!(rows, expected.features); } + +/// Every feature of a complete traversal, in order, checking each chunk against the budget. +fn visit_all(src: &dyn FeatureSource, extent: Option, budget: usize) -> (Vec, Batch, usize) { + let (mut rows, mut calls) = (Vec::new(), 0); + let summary = src + .visit_chunks(extent, budget, &mut |chunk| { + calls += 1; + // Only a row that alone exceeds the budget comes over it, by itself. + let alone_too_big = |c: &Vec| { + c.len() == 1 && c.iter().all(|f| chunk_memory::feature_bytes(f) + std::mem::size_of::() > budget) + }; + assert!(chunk_memory::features_bytes(&chunk) <= budget || alone_too_big(&chunk), "{}", src.info().format); + rows.extend(chunk); + Ok(()) + }) + .unwrap(); + (rows, summary, calls) +} + +/// GeoPackage, FlatGeobuf and GeoParquet visit, a chunk at a time, exactly the features a whole +/// read gives (ids, attributes, order and skipped rows), for exports. They still draw from a +/// view window: a complete traversal on every render would be far slower. +#[test] +fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { + let d = dir().join("visit"); + std::fs::create_dir_all(&d).unwrap(); + let (gpkg, gpkg_scan, fgb, pq, pq_plain) = + (d.join("grid.gpkg"), d.join("scan.gpkg"), d.join("grid.fgb"), d.join("grid.parquet"), d.join("plain.parquet")); + write_gpkg(&gpkg, true); + write_gpkg(&gpkg_scan, false); + write_fgb(&fgb); + write_parquet(&pq, true); + write_parquet(&pq_plain, false); + let mut sources: Vec> = Vec::new(); + for p in [&gpkg, &gpkg_scan, &fgb, &pq, &pq_plain] { + sources.push(open_path(p, None).unwrap()); + } + for p in [&gpkg, &fgb, &pq] { + sources.push(open_bytes(&p.file_name().unwrap().to_string_lossy(), std::fs::read(p).unwrap(), None).unwrap()); + } + // The browser's GeoPackage reader. + sources.push(Box::new(gpkg_mem::GpkgMemSource::open_shared(Shared(Arc::new(std::fs::read(&gpkg_scan).unwrap())), None).unwrap())); + let extent = Extent::new(-100.0, -30.0, 20.0, 45.0); + let by_id = |mut v: Vec| { + v.sort_by_key(|f| f.id); + v + }; + for src in &sources { + let format = src.info().format; + assert!(src.visits_chunks() && !src.streams_chunks(), "{format}"); + let whole = src.read(&Request::all()).unwrap(); + assert!(whole.complete && whole.features.len() == 600, "{format}"); + for budget in [256, 4096, 1 << 20] { + let (rows, summary, calls) = visit_all(src.as_ref(), None, budget); + assert_eq!(rows, whole.features, "{format} at {budget} bytes"); + assert!(summary.complete && summary.features.is_empty(), "{format}"); + assert_eq!((summary.matched, summary.skipped), (600, whole.skipped), "{format}"); + assert!(budget > 4096 || calls > 1, "{format} at {budget} bytes came in one chunk"); + } + // Each row alone when none fits the budget. + assert_eq!(visit_all(src.as_ref(), None, 1).0, whole.features, "{format}"); + // An extent: the features a complete read of it gives (the R-tree's order may differ). + let part = src.read(&Request { extent: Some(extent), limit: 10_000 }).unwrap(); + assert!(part.complete && part.features.len() == in_box(&extent), "{format}"); + let (rows, summary, _) = visit_all(src.as_ref(), Some(extent), 1024); + assert!(summary.complete && summary.features.is_empty() && summary.matched == rows.len() as u64, "{format}"); + if src.info().indexed { + assert_eq!(by_id(rows), by_id(part.features), "{format}"); + } else { + assert_eq!(rows, part.features, "{format}"); + } + assert!(visit_all(src.as_ref(), Some(Extent::new(1.0, 1.0, 2.0, 2.0)), 1024).0.is_empty(), "{format}"); + // A visitor's error stops the traversal; a zero budget is refused before any row. + let mut calls = 0; + let stopped = src.visit_chunks(None, 256, &mut |_| { + calls += 1; + Err(DataError::Format("cancelled".into())) + }); + assert!(stopped.is_err() && calls == 1, "{format}"); + assert!(src.visit_chunks(None, 0, &mut |_| panic!("a zero budget must not emit")).is_err(), "{format}"); + // The map's reads of the layer go on while a traversal waits on its visitor. + src.visit_chunks(None, 256, &mut |_| { + assert_eq!(src.read(&Request { extent: None, limit: 1 }).unwrap().features.len(), 1, "{format}"); + Ok(()) + }) + .unwrap(); + } + // A row group longer than a read takes from one: a traversal refuses it rather than leave + // its last rows out. + let capped = parquet::ParquetSource::open_path(&pq_plain, "plain").unwrap().with_group_rows(40); + let error = capped.visit_chunks(None, 4096, &mut |_| Ok(())).unwrap_err().to_string(); + assert!(error.contains("row group 0 has 50 rows, more than the 40"), "{error}"); + // A capped row group outside the extent is passed over, not refused. + let capped = parquet::ParquetSource::open_path(&pq, "grid").unwrap().with_group_rows(40); + assert!(visit_all(&capped, Some(Extent::new(178.0, 0.0, 179.0, 1.0)), 4096).0.is_empty()); + // A GeoPackage put in place of the one added is refused, not read as the layer. + #[cfg(unix)] + { + let src = open_path(&gpkg, None).unwrap(); + let other = d.join("other.gpkg"); + write_gpkg(&other, false); + std::fs::rename(&other, &gpkg).unwrap(); + let error = src.visit_chunks(None, 4096, &mut |_| Ok(())).unwrap_err().to_string(); + assert!(error.contains("replaced"), "{error}"); + assert_eq!(src.read(&Request::all()).unwrap().features.len(), 600); + } + // An unreadable geometry is skipped and counted, and a row without one left out, as a read does. + drop(sources); + let c = rusqlite::Connection::open(&gpkg_scan).unwrap(); + c.execute_batch("INSERT INTO \"grid \"\"q\"\"\" (geom, name) VALUES (X'4750000300000000DEAD', 'bad'), (NULL, 'none');").unwrap(); + drop(c); + let src = open_path(&gpkg_scan, None).unwrap(); + let whole = src.read(&Request::all()).unwrap(); + assert_eq!((whole.features.len(), whole.skipped), (600, 1)); + let (rows, summary, _) = visit_all(src.as_ref(), None, 4096); + assert_eq!((rows, summary.skipped), (whole.features, 1)); + // The browser's reader of the same file skips and leaves out the same rows. + let mem = gpkg_mem::GpkgMemSource::open_shared(Shared(Arc::new(std::fs::read(&gpkg_scan).unwrap())), None).unwrap(); + let whole = mem.read(&Request::all()).unwrap(); + assert_eq!((whole.features.len(), whole.skipped), (600, 1)); + let (rows, summary, _) = visit_all(&mem, None, 4096); + assert_eq!((rows, summary.skipped), (whole.features, 1)); +}