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
49 changes: 48 additions & 1 deletion crates/data/src/source/chunk_memory.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -33,3 +33,50 @@ pub fn feature_bytes(f: &Feature) -> usize {
pub fn features_bytes(features: &Vec<Feature>) -> usize {
features.iter().fold(features.capacity().saturating_mul(size_of::<Feature>()), |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<Feature>,
visit: &'a mut dyn FnMut(Vec<Feature>) -> 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<Feature>) -> crate::Result<()>) -> crate::Result<Self> {
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::<Feature>());
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)
}
}
69 changes: 69 additions & 0 deletions crates/data/src/source/fgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<R: Read + Seek>(
&self,
open: &impl Fn() -> Result<R>,
extent: Option<Extent>,
chunks: &mut super::chunk_memory::Chunker<'_>,
) -> Result<Batch> {
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<Vec<u64>> = match indexed {

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.

Performance (medium confidence). For an extent over an indexed FlatGeobuf, numbers holds 8 bytes per matched feature for the whole traversal, regardless of the chunk budget. On a large indexed file with a broad extent, that is an allocation proportional to the layer size, which cuts against the "exports no longer hold the whole layer" goal. The doc comment already says it holds the numbers, so this is a conscious trade-off. If it's acceptable, consider noting in the visit_chunks contract that the id list is unbounded. If not, the ids could be recomputed by walking the index per chunk.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Kept, and now stated in the trait contract too (3186740): "a provider may hold … an index's list of matches (FlatGeobuf, for an extent) besides". The export the next pull request adds reads with no extent, which builds no list; an extent visit holds 8 bytes per match, against about 355 bytes per decoded feature, as a read already does.

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 {
Expand Down Expand Up @@ -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<Extent>, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
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.
Expand Down
74 changes: 70 additions & 4 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PathBuf>,
/// 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 {
Expand Down Expand Up @@ -69,7 +72,10 @@ fn feature_tables(conn: &Connection) -> Result<Vec<String>> {

impl GpkgSource {
pub fn open(path: &Path, layer: Option<&str>) -> Result<Self> {
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
Expand Down Expand Up @@ -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);
Expand All @@ -109,7 +116,8 @@ impl GpkgSource {
}
}

fn open_conn(conn: Connection, layer: Option<&str>, temp: Option<PathBuf>) -> Result<Self> {
/// 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<PathBuf>, id: Option<(u64, u64)>) -> Result<Self> {
let tables = feature_tables(&conn)?;
let table = match layer {
Some(l) => tables
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -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

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.

Doc is wrong about locking (Bugs, ~80% confidence). The scan's SELECT stays open for the whole traversal, so SQLite holds a read transaction across every visitor call. In the default rollback-journal mode that keeps a SHARED lock, so a writer (another app editing the same .gpkg) fails to commit with SQLITE_BUSY until the export finishes. Readers are not blocked, so "the map's reads go on" holds, but "nothing is locked while the visitor runs" does not. Suggest rewording to say that a writer of the file waits for the scan to end.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right: one open SELECT is one read transaction, so outside WAL mode another program's write to the file waits for the scan to end; only the source's own connection is free. The doc will say so in the next pull request of this stack (the streamed export), which reworks this traversal anyway; this one is approved as it stands.

/// put in place of the one opened is refused (where the system says files' identities).
fn visit_chunks(&self, extent: Option<Extent>, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
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())));

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.

Misleading error for a deleted file (Bugs, low, ~55% confidence). file_identity returns None when the path can't be stat'ed, so a GeoPackage that was removed (not replaced) fails this check with "the file was replaced since it was added; add it again". Consider returning the I/O error from std::fs::metadata when the file is missing, and keeping the "replaced" message only for a real identity mismatch.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed: a removed file should fail as missing (the I/O error), keeping "replaced" for a real identity mismatch. That goes into the next pull request of this stack with a test, along with the locking wording above.

}
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.
Expand Down
75 changes: 67 additions & 8 deletions crates/data/src/source/gpkg_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Extent>, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
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<Value> {
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()
}
}
25 changes: 20 additions & 5 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Extent>, _bytes: usize, _visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
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
Expand Down
Loading
Loading