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
6 changes: 6 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,12 @@ pub trait FeatureSource: Send + Sync {
fn finds_all_by_area(&self) -> bool {
false
}
/// Whether the source is as it was when opened, judged cheaply (its files' sizes and
/// modification times), for what was read from it and kept beside it: `Ok(false)` when it
/// changed or the source can't say, and the error a read would give when it can't be read.
fn same_as_opened(&self) -> Result<bool> {
Ok(false)
}
/// Whether a complete bounded traversal for a geographic extent is available. This also
/// covers readers whose view and whole-export paths still use their existing sample or
/// whole-read contracts.
Expand Down
41 changes: 40 additions & 1 deletion crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,35 @@ pub struct ShpSource {
/// trust: [`BOXES_UNKNOWN`] until a whole read has looked, then [`BOXES_HOLD`] or
/// [`BOXES_DONT`].
boxes: AtomicU8,
/// The `.shp`'s and the `.dbf`'s versions as opened
/// ([`FeatureSource::same_as_opened`]).
stamps: [Option<Stamp>; 2],
}

/// What a file's metadata says of its version ([`FeatureSource::same_as_opened`]): its size and
/// modification time and, on Unix, its identity and change time, which a write of the same size
/// within the clock's step still moves. `None` without a modification time: then no copy of what
/// was read is trusted.
#[derive(PartialEq, Eq)]
struct Stamp {
len: u64,
modified: std::time::SystemTime,
#[cfg(unix)]
identity_and_change: (u64, u64, i64, i64),
}

impl Stamp {
fn of(path: &Path) -> Option<Stamp> {
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
let m = std::fs::metadata(path).ok()?;
Some(Stamp {
len: m.len(),
modified: m.modified().ok()?,
#[cfg(unix)]
identity_and_change: (m.dev(), m.ino(), m.ctime(), m.ctime_nsec()),
})
}
}

/// Not yet looked at ([`ShpSource::boxes`]).
Expand Down Expand Up @@ -113,6 +142,8 @@ impl ShpSource {
if !dbf.is_file() {
return Err(bad(format!("{} is missing", dbf.display())));
}
// Taken before anything is read, so a file written while it opens is seen as changed.
let stamps = [Stamp::of(path), Stamp::of(&dbf)];
let mut notes = Vec::new();
let table = read_table(&dbf)?;
let cpg = crate::dbf::read_cpg(path, &mut notes);
Expand Down Expand Up @@ -227,7 +258,7 @@ impl ShpSource {
}
// Points too: each record's own type is read, whatever the header says.
let boxes = AtomicU8::new(BOXES_UNKNOWN);
Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes })
Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes, stamps })
}
}

Expand Down Expand Up @@ -379,6 +410,14 @@ impl FeatureSource for ShpSource {
fn finds_all_by_area(&self) -> bool {
self.index.unboxed == 0 && self.boxes.load(Relaxed) == BOXES_HOLD
}
/// Both files opened as a read opens them, so one gone gives a read's error, then their
/// versions ([`Stamp`]) compared with those at opening.
fn same_as_opened(&self) -> Result<bool> {
drop(crate::provenance::open(&self.shp)?);
drop(crate::provenance::open(&self.dbf)?);
let now = [Stamp::of(&self.shp), Stamp::of(&self.dbf)];
Ok(self.stamps.iter().all(Option::is_some) && now == self.stamps)
}
/// Visits located shapes in a spatial request; geometry-less rows belong only to whole reads.
/// Counts scanned records and checks Cancel before filtering them.
fn visit_chunks(&self, extent: Option<Extent>, bytes: usize, visit: &mut dyn FnMut(Vec<Feature>) -> Result<()>) -> Result<Batch> {
Expand Down
29 changes: 29 additions & 0 deletions crates/data/src/source/shp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -888,3 +888,32 @@ fn reads_by_area_find_every_shape_once_a_whole_read_has_seen_the_boxes_hold() {
assert!(s.finds_all_by_area(), "each point is its own box");
});
}

/// A Shapefile says whether it is as it was opened (#1065): yes until it is written again (on Unix
/// at the same size and time too), and a read's error once it is gone.
#[test]
fn a_shapefile_says_whether_it_is_as_it_was_opened() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("pts.shp");
let mut ds = Dataset::new("pts", GeometryType::Point, vec![]);
ds.push(Some(Geometry::Point(Coord::new(1.0, 1.0))), vec![]);
write_shapefile(&ds, &path);
cache::with_index_dir(tmp.path().join("cache"), || {
let s = ShpSource::open_path(&path, "pts").unwrap();
assert!(s.same_as_opened().unwrap(), "as opened");
// The same size, its time set back: the change time still moves.
let dbf = path.with_extension("dbf");
let modified = std::fs::metadata(&dbf).unwrap().modified().unwrap();
let bytes = std::fs::read(&dbf).unwrap();
std::fs::write(&dbf, &bytes).unwrap();
std::fs::File::options().write(true).open(&dbf).unwrap().set_modified(modified).unwrap();
#[cfg(unix)]
assert!(!s.same_as_opened().unwrap(), "written again at the same size and time");

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.

This same-size case assumes the .dbf's change time moves between opening and this rewrite. set_modified restores only the modification time, so if both writes land in one kernel clock tick, same_as_opened stays true and this assertion fails. I haven't seen it fail: Stamp::of reads the change time at opening, and kernels with multigrain timestamps stamp the next write finely after that, so I rate the flake risk low. If it ever shows up, wait for the clock to step before the rewrite (with a // test-wait: reason, as test-hygiene requires) rather than relaxing the assertion.

Category: quality

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.

Left for the release quality pass: the change time is taken at opening, and the rewrite comes after reading both files, so on current kernels it moves. If it ever flakes, the fix is a wait for the clock to step, as you say.

let s = ShpSource::open_path(&path, "pts").unwrap();
ds.push(Some(Geometry::Point(Coord::new(2.0, 2.0))), vec![]);
write_shapefile(&ds, &path);
assert!(!s.same_as_opened().unwrap(), "written again");
std::fs::remove_file(&path).unwrap();
assert!(s.same_as_opened().is_err(), "gone");
});
}
20 changes: 20 additions & 0 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1529,6 +1529,18 @@ impl Layer {
fits
}

/// Takes the rows of `kept`, a chunk of a streamed layer drawn before (a copy of this layer
/// with other rows), and the geometry drawing made of them: projected, and thinned for
/// display. Sharing them costs a pointer; this layer keeps its own look. What drawing makes
/// that `kept` lacks is made from the rows as usual.
pub fn draw_rows_of(&mut self, kept: &Layer) {
self.clear_cache();
self.dataset.features = kept.dataset.features.clone();
self.dataset.held_in = kept.dataset.held_in;
self.geometry_rev = kept.geometry_rev;
self.adopt_cache(kept);
}

/// Whether the projected geometry cache is filled for a projection, from the layer's current
/// rows and its coordinate system ([`Dataset::coord_crs`]).
pub fn is_cached(&self, key: &str) -> bool {
Expand Down Expand Up @@ -3092,6 +3104,14 @@ impl Map {
for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) {
pending |= l.sync_source_with(view, block, env);
}
// A view kept for its frames fits in what its share leaves beside the rows it holds now,
// hidden or not: a share shrunk by another streamed layer, or a larger view installed,
// lets it go.
for l in &self.layers {
if let Some(src) = &l.source {
src.trim_kept_view(bytes.saturating_sub(l.view_cache_bytes()));
}
}
pending
}

Expand Down
46 changes: 46 additions & 0 deletions crates/map/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use rustgis_geom::Extent;
use serde::{Deserialize, Serialize};

mod render_lod;
mod render_view;
pub use render_view::KEPT_VIEW_BYTES;
mod window;
pub(crate) use window::Query;

Expand Down Expand Up @@ -178,6 +180,9 @@ pub struct SourceLayer {
/// Whole-source thinning decisions shared by render snapshots, independent of view rows.
#[serde(skip)]
render_lod: Arc<Mutex<render_lod::Decisions>>,
/// The last view's rows and drawn geometry, shared by render snapshots ([`render_view`]).
#[serde(skip)]
render_view: Arc<Mutex<render_view::KeptView>>,
#[serde(skip)]
pending: Option<Arc<Pending>>,
/// Projection used for this disposable window's geometry cache.
Expand Down Expand Up @@ -1203,6 +1208,44 @@ impl SourceLayer {
cache.get_or_try_insert(handle, projection, level, calculate)
}

/// The chunks a frame drew from the source's last view, with their projected and display
/// geometry, when that view was read for a longitude/latitude box holding `near`, drawn for
/// `key` (the projection and datum grids, as the renderer names them) and holding at most
/// `room` bytes (#1065). They hold rows only: the drawing takes the layer's look from the
/// layer, its rows and geometry from them ([`crate::Layer::draw_rows_of`]).
pub fn kept_view(&self, key: &str, near: &Extent, room: usize) -> Option<Arc<Vec<crate::Layer>>> {
let handle = self.handle.as_ref()?;
self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(handle, key, near, room)
}

/// Whether a frame at resolution `res` (map units a pixel) should read a view wider than it
/// draws, to keep it for the frames after: not after a view as coarse or coarser was too large
/// to keep.
pub fn view_worth_keeping(&self, key: &str, res: f64) -> bool {
let Some(handle) = &self.handle else { return false };
self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).worth_keeping(handle, key, res)
}

/// Keeps the chunks a frame at resolution `res` drew from a view read for `read`, with the
/// bytes they hold, in place of the last view kept; `None` says they came to more than may be
/// kept.
pub fn keep_view(&self, key: &str, read: Extent, res: f64, chunks: Option<(Vec<crate::Layer>, usize)>) {
let Some(handle) = &self.handle else { return };
self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).put(handle, key, read, res, chunks);
}

/// Lets the kept view go when it holds more than `room` bytes.
pub fn trim_kept_view(&self, room: usize) {
self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).trim(room);
}

/// Puts the kept chunks drawn again, with the geometry drawing made of them, in place of
/// `drawn`, the ones [`SourceLayer::kept_view`] gave, while those are still what is kept.
pub fn refresh_kept_view(&self, key: &str, drawn: &Arc<Vec<crate::Layer>>, chunks: Vec<crate::Layer>, bytes: usize) {
let Some(handle) = &self.handle else { return };
self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).refresh(handle, key, drawn, chunks, bytes);
}

/// Retained interaction bytes assigned by the map, or the standalone default.
pub fn budget(&self) -> usize {
if self.byte_budget == 0 { VIEW_BYTES } else { self.byte_budget }
Expand Down Expand Up @@ -1734,6 +1777,7 @@ impl SourceLayer {
pub fn detach_read(&mut self) {
self.pending = None;
self.render_lod = Default::default();
self.render_view = Default::default();
}

/// Whether `other` (a copy of this one) reads the same source the same way: the same file and
Expand All @@ -1757,6 +1801,7 @@ impl SourceLayer {
/// Forgets the window, so the next view reads again (after the source changes).
pub fn reset(&mut self) {
self.render_lod = Default::default();
self.render_view = Default::default();
self.reset_window();
}

Expand Down Expand Up @@ -2021,6 +2066,7 @@ impl SourceLayer {
handle: _,
window: _,
render_lod: _,
render_view: _,
pending: _,
projection: _,
ready_cache: _,
Expand Down
157 changes: 157 additions & 0 deletions crates/map/src/source/render_view.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
//! The features a streamed layer's last view read and the geometry its drawing made of them
//! (projected, and thinned for display), kept so that a frame of a view inside that one draws
//! without reading, parsing or projecting them again (#1065). Shared by render snapshots, like
//! the thinning decisions ([`super::render_lod`]), and bounded by [`KEPT_VIEW_BYTES`] and the
//! room the source's share of the map's view memory leaves.
use rustgis_data::source::FeatureSource;
use rustgis_geom::Extent;
use std::sync::{Arc, Weak};

use crate::Layer;

/// The most a kept view holds: its rows and the geometry drawn from them
/// ([`Layer::view_cache_bytes`]). A view with more, or with more than the source's share of the
/// map's view memory leaves beside its interaction rows, is drawn without being kept.
pub const KEPT_VIEW_BYTES: usize = crate::lod::CACHE_BYTES;

#[derive(Default)]
pub(super) struct KeptView {
source: Option<Weak<dyn FeatureSource>>,
/// What its geometry was drawn for: the projection ([`crate::Projection::code`]) and the
/// datum grids there were then, as the renderer names them.
key: String,
/// The longitude/latitude box it was read for: every feature whose box meets it.
read: Extent,
/// The chunks drawn from it in turn, in the source's order.
chunks: Arc<Vec<Layer>>,
/// What the chunks hold ([`Layer::view_cache_bytes`]).
bytes: usize,
/// The coarsest resolution (map units a pixel) a view's read was found too large to keep at,
/// for this key: views as coarse or coarser read only what they draw, and keep nothing.
too_large_at: Option<f64>,
}

impl KeptView {
/// Forgets everything kept for another source or key.
fn follow(&mut self, source: &Arc<dyn FeatureSource>, key: &str) {
let same = self.source.as_ref().and_then(Weak::upgrade).is_some_and(|old| Arc::ptr_eq(&old, source));
if !same || self.key != key {
*self = KeptView { source: Some(Arc::downgrade(source)), key: key.into(), ..KeptView::default() };
}
}

/// Forgets the chunks, keeping what was learnt of sizes.
fn drop_chunks(&mut self) {
self.read = Extent::EMPTY;
self.chunks = Arc::default();
self.bytes = 0;
}

/// The kept chunks, when they were read for a box holding `near` and hold at most `room`
/// bytes; ones holding more (the source's share shrank) are let go.
pub(super) fn get(&mut self, source: &Arc<dyn FeatureSource>, key: &str, near: &Extent, room: usize) -> Option<Arc<Vec<Layer>>> {
self.follow(source, key);
if self.bytes > room {
self.drop_chunks();
}
let r = &self.read;
// A view read with nothing in it is kept too (no chunks): its frames draw nothing. With
// nothing kept, `read` is empty and holds no box.
let holds = r.min_x <= near.min_x && r.min_y <= near.min_y && r.max_x >= near.max_x && r.max_y >= near.max_y;
holds.then(|| Arc::clone(&self.chunks))
}

/// Lets the chunks go when they hold more than `room` bytes.
pub(super) fn trim(&mut self, room: usize) {
if self.bytes > room {
self.drop_chunks();
}
}

/// Whether a view at resolution `res` is worth reading wider than it draws to keep: not
/// when one as coarse or coarser was already too large to keep.
pub(super) fn worth_keeping(&mut self, source: &Arc<dyn FeatureSource>, key: &str, res: f64) -> bool {
self.follow(source, key);
self.too_large_at.is_none_or(|at| res < at)
}

/// Keeps `chunks` of `bytes`, read for `read`, in place of what was kept; `None` when they
/// came to more than may be kept at resolution `res`, which is remembered.
pub(super) fn put(&mut self, source: &Arc<dyn FeatureSource>, key: &str, read: Extent, res: f64, chunks: Option<(Vec<Layer>, usize)>) {
self.follow(source, key);
match chunks {
Some((chunks, bytes)) => {
self.read = read;
self.chunks = Arc::new(chunks);
self.bytes = bytes;
}
None => {
self.drop_chunks();
self.too_large_at = Some(self.too_large_at.map_or(res, |at| at.min(res)));
}
}
}

/// Puts `chunks` of `bytes` (the kept ones drawn again, with the geometry that drawing made,
/// a finer level of detail say) in place of `drawn`, when those are still what is kept;
/// another source or key kept since is left as it is.
pub(super) fn refresh(
&mut self,
source: &Arc<dyn FeatureSource>,
key: &str,
drawn: &Arc<Vec<Layer>>,
chunks: Vec<Layer>,
bytes: usize,
) {
let same = self.source.as_ref().and_then(Weak::upgrade).is_some_and(|old| Arc::ptr_eq(&old, source));
if same && self.key == key && Arc::ptr_eq(&self.chunks, drawn) {
self.chunks = Arc::new(chunks);
self.bytes = bytes;
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use rustgis_data::source::{Batch, Request, SourceInfo};

struct Empty(SourceInfo);
impl FeatureSource for Empty {
fn info(&self) -> &SourceInfo {
&self.0
}
fn read(&self, _: &Request) -> rustgis_data::Result<Batch> {
Ok(Batch::default())
}
}

/// A view too large to keep stops wider reads at its resolution and coarser ones, not at
/// finer ones; another projection or source starts afresh.
#[test]
fn a_view_too_large_to_keep_stops_wide_reads_as_coarse_or_coarser() {
let info = SourceInfo {
name: "s".into(),
format: "test",
geometry_type: rustgis_data::GeometryType::Point,
fields: Vec::new(),
extent: Extent::EMPTY,
count: Some(0),
crs: "EPSG:4326".into(),
indexed: true,
notes: Default::default(),
zm_dropped: false,
};
let source: Arc<dyn FeatureSource> = Arc::new(Empty(info.clone()));
let mut kept = KeptView::default();
assert!(kept.worth_keeping(&source, "3857", 100.0));
kept.put(&source, "3857", Extent::new(0.0, 0.0, 1.0, 1.0), 100.0, None);
assert!(!kept.worth_keeping(&source, "3857", 100.0));
assert!(!kept.worth_keeping(&source, "3857", 200.0));
assert!(kept.worth_keeping(&source, "3857", 50.0));
assert!(kept.get(&source, "3857", &Extent::new(0.2, 0.2, 0.4, 0.4), usize::MAX).is_none(), "nothing kept");
assert!(kept.worth_keeping(&source, "robinson", 100.0), "another projection");
let other: Arc<dyn FeatureSource> = Arc::new(Empty(info));
assert!(kept.worth_keeping(&other, "3857", 100.0), "another source");
}
}
Loading
Loading