Skip to content
8 changes: 8 additions & 0 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1423,6 +1423,10 @@ pub(crate) trait FeatureSink {
fn restart(&mut self);
/// One element of `"features"`, as its text.
fn feature(&mut self, raw: &str);
/// Whether the read is to stop now (Cancel pressed): it then ends with an error.
fn stopped(&self) -> bool {
false
}
}

/// Reads a GeoJSON document's top level, handing each element of `"features"` to `sink` as it is
Expand Down Expand Up @@ -1491,9 +1495,13 @@ impl<'de> serde::de::Visitor<'de> for Features<'_> {
f.write_str("an array of features")
}

/// Hands each element to the sink as its text, ending with an error once the sink is stopped.
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<(), A::Error> {
while let Some(raw) = seq.next_element::<&'de serde_json::value::RawValue>()? {
self.sink.feature(raw.get());
if self.sink.stopped() {
return Err(serde::de::Error::custom("cancelled"));
}
}
Ok(())
}
Expand Down
68 changes: 57 additions & 11 deletions crates/data/src/source/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,30 @@ struct Scan {
swapped: usize,
/// The places of features whose heights reading drops.
zm: Vec<u32>,
/// Features [`paced`](Scan::pace) so far, and the byte the progress was counted to.
paced: usize,
paced_to: u64,
/// Cancel was pressed: the scan stops.
stopped: bool,
}

/// Features between looks at Cancel (and progress counts) while a file is scanned or converted.
const PACE: usize = 4096;

impl Scan {
/// Says the scan has come `at` bytes into the file, and looks at Cancel: at the first feature
/// and every [`PACE`] after it (#2446).
fn pace(&mut self, at: u64) -> Result<()> {
let n = self.paced;
self.paced += 1;
if !n.is_multiple_of(PACE) {
return Ok(());
}
let done = at.saturating_sub(self.paced_to);
self.paced_to = self.paced_to.max(at);
crate::progress::step(usize::try_from(done).unwrap_or(usize::MAX))
}

/// One element of `"features"`, read from `len` bytes at `offset` (with the comma and
/// whitespace before it).
fn feature(&mut self, f: &Json, offset: u64, len: u64) {
Expand Down Expand Up @@ -180,6 +201,10 @@ impl GeoJsonSource {
let mut file = crate::provenance::open(path)?;
let version = FileVersion::of(&file.metadata()?);
let mut scan = Scan::default();
// How far the scan has come, in bytes of the file; Cancel stops it, said as such rather than
// as the JSON error it ends with.
crate::progress::begin(usize::try_from(version.len).unwrap_or(usize::MAX));
let failed = |e: serde_json::Error| if crate::progress::check().is_err() { DataError::Cancelled } else { bad(e) };
let rest = if version.len <= in_memory {
let mut text = String::new();
file.read_to_string(&mut text)?;
Expand All @@ -188,14 +213,14 @@ impl GeoJsonSource {
if crate::cityjson::looks_like_cityjson(&text) {
return Err(DataError::Unsupported("only GeoJSON FeatureCollections are read in place".into()));
}
crate::io::stream_features(&text, &mut InText { scan: &mut scan, start: text.as_ptr() as usize }).map_err(bad)?
crate::io::stream_features(&text, &mut InText { scan: &mut scan, start: text.as_ptr() as usize }).map_err(failed)?
} else {
let read = std::rc::Rc::new(std::cell::Cell::new(0u64));
let input = Counting { inner: BufReader::with_capacity(BUFFER, &mut file), read: read.clone() };
let mut de = serde_json::Deserializer::from_reader(input);
let rest = Top { scan: &mut scan, read }.deserialize(&mut de).map_err(bad)?;
let rest = Top { scan: &mut scan, read }.deserialize(&mut de).map_err(failed)?;
// Only whitespace may follow, as when read whole.
de.end().map_err(bad)?;
de.end().map_err(failed)?;
rest
};
if rest.get("type").and_then(Json::as_str) != Some("FeatureCollection") {
Expand All @@ -213,7 +238,7 @@ impl GeoJsonSource {
let mut extent = scan.extent;
if let Some(t) = reproject.transformer() {
file.rewind()?;
let pass = convert_pass(&mut file, &scan.places, t);
let pass = convert_pass(&mut file, &scan.places, t)?;
extent = pass.extent;
for (kept, lost) in scan.kinds.iter_mut().zip(pass.dropped) {
*kept = kept.saturating_sub(lost);
Expand Down Expand Up @@ -336,7 +361,9 @@ impl FeatureSource for GeoJsonSource {
}

/// Reads a bounded sample; when native bounds are refused, filters geometry before sampling,
/// counting records and checking Cancel between them.
/// counting records and checking Cancel between them. A whole read (no extent, every match:
/// Add Data loading the file) counts and looks at Cancel likewise; other reads look at Cancel
/// every [`PACE`] features.
fn read(&self, req: &Request) -> Result<Batch> {
let limit = clamp_limit(req.limit);
// Counted first, then sampled, unless the native box is refused: no list of every match.
Expand All @@ -355,12 +382,16 @@ impl FeatureSource for GeoJsonSource {
let mut buf = Vec::new();
let mut features = Vec::with_capacity(matched.div_ceil(step).min(limit));
let mut skipped = 0;
if late {
crate::progress::begin(matched);
// A whole read counts its features as a refused box does; a view's sample only looks.
let counted = late || (req.extent.is_none() && step == 1);
if counted {
crate::progress::begin(if late { matched } else { matched.min(limit) });
}
for i in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }) {
if late {
for (n, i) in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }).enumerate() {
if counted {
crate::progress::step(1)?;
} else if n.is_multiple_of(PACE) {

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.

AGENTS.md (progress): a whole read counts no progress.

On the non-late path only check() runs, and nothing calls progress::begin or progress::step. The late path does both. So when Opened::ahead materializes a file loaded whole (read_at_once → read(Request::all())), the status bar keeps the count left by the open-time scan, which ends near 100% of the file's bytes. The whole load then runs with a full-looking bar. convert_pass (around line 412) has the same gap: it checks Cancel every PACE features and counts nothing, so reprojection of a declared-CRS file sits at 100% too.

The rule says long loops count their progress, and a whole read has a known total (matched, with step 1). Suggest calling crate::progress::begin(matched) before the loop on the non-late path too, with crate::progress::step(1) per feature when step == 1, and a begin/step pair in convert_pass. Confidence about 55%: I did not run the UI, and the count may be visible only in the status bar.

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.

Fixed in 29aed27: a whole read (no extent, every match) counts a step per feature as the late path does, and convert_pass counts its features as a step of its own. A view's sample still only looks at Cancel every PACE features.

crate::progress::check()?;
}
let feature = match self.read_feature((&mut f, &mut pos, &mut buf), i, req, || !late || sample.wants()) {
Ok(Some(feature)) => feature,
Expand Down Expand Up @@ -456,11 +487,16 @@ struct Pass {
}

/// A second pass over the file, made only for a declared coordinate system.
fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Pass {
fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result<Pass> {
let mut f = BufReader::with_capacity(BUFFER, file);
let (mut pos, mut buf) = (0u64, Vec::new());
let mut pass = Pass { failed: Vec::new(), dropped: [0; 3], extent: Extent::EMPTY };
// Counted as a step of its own, a feature at a time every so many.
crate::progress::begin(places.len());
for (i, place) in places.iter().enumerate() {
if i.is_multiple_of(PACE) {
crate::progress::step(if i == 0 { 0 } else { PACE })?;
}
// A feature that can't be read now is left to the reads, which skip it.
if let Some(json) = read_place(&mut f, &mut pos, &mut buf, place)
&& let Ok(Some(g)) = geojson_geometry(&json)
Expand All @@ -476,7 +512,7 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme
}
}
}
pass
Ok(pass)
}

/// A reader counting the bytes read through it, for features' places in the file. The JSON reader
Expand Down Expand Up @@ -557,11 +593,13 @@ impl<'de> serde::de::Visitor<'de> for Elements<'_> {
f.write_str("an array of features")
}

/// Scans each feature with its place in the file, ending with an error once Cancel is pressed.
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<(), A::Error> {
loop {
let start = self.read.get();
let Some(f) = seq.next_element::<Json>()? else { break };
self.scan.feature(&f, start, self.read.get().saturating_sub(start));
self.scan.pace(self.read.get()).map_err(|_| serde::de::Error::custom("cancelled"))?;

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.

Test gap (about 60% confidence): the cancel sweeps never reach the streamed scan path or the reprojection pass.

Elements::visit_seq (this line) is the look at Cancel for files over BYTES_FLOOR, read through the buffer. The new long_commands fixtures (in-place.geojson, many.geojson) are small enough to take the in-memory InText path, so this branch has no cancel coverage. open_with(path, name, 0) already exists in the tests and can drive it with a probe that cancels after a few checks.

The same applies to convert_pass (geojson.rs:498): the sweep fixtures don't seem to declare a coordinate system, so the reprojection pass is only exercised at its first check. I didn't confirm what the GeoJSON export writes for a declared CRS.

Suggested coverage: one streamed-path case (open_with(…, 0) under a probe cancelled at the first few checks, asserting DataError::Cancelled), and one GeoJSON with a declared CRS in the sweep.

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. Both paths look at Cancel (the buffered scan through pace in Elements::visit_seq, the conversion every PACE features), and the sweep covers the same pacing on the in-memory path. Reaching the buffered path needs a fixture past 256 MiB, and the conversion a declared system; extra tests for working code.

}
Ok(())
}
Expand All @@ -579,12 +617,20 @@ impl FeatureSink for InText<'_> {
*self.scan = Scan::default();
}

/// Scans one feature, its place where its text is in the file's; Cancel pressed stops the read.
fn feature(&mut self, raw: &str) {
let offset = (raw.as_ptr() as usize).saturating_sub(self.start) as u64;
match serde_json::from_str::<Json>(raw) {
Ok(f) => self.scan.feature(&f, offset, raw.len() as u64),
// Valid JSON, but with a number that doesn't fit.
Err(_) => self.scan.skipped += 1,
}
if self.scan.pace(offset + raw.len() as u64).is_err() {
self.scan.stopped = true;
}
}

fn stopped(&self) -> bool {
self.scan.stopped
}
}
39 changes: 38 additions & 1 deletion crates/data/src/source/shp/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,17 @@ fn connect(path: &Path, write: bool) -> Result<Connection> {
}

impl DiskIndex {
/// The `.shp`'s index from the cache when one was built for this file as it is now, else built
/// there by scanning its records (looking at Cancel and counting progress as it goes).
/// [`DataError::Cancelled`](crate::DataError::Cancelled) when Cancel was pressed, which
/// [`Index::open`] passes on; any other error when neither can be had, for it to scan the
/// records instead.
pub fn open(path: &Path, len: u64, notes: &mut Vec<String>) -> Result<Self> {
use super::cache;
use crate::source::external::{fnv1a, stamp};
// Cancel is looked at once even when the index is reused, so an opening can always be
// stopped before the layer is added (#2446).
crate::progress::check()?;
let canonical = path.canonicalize()?;
let signature = format!("shp-index-v7:{canonical:?}:{:?}", stamp(path)?);
let mut dir = cache::index_dir();
Expand Down Expand Up @@ -94,7 +102,9 @@ impl DiskIndex {
let (count, note) = {
let mut record = tx.prepare("INSERT INTO records VALUES(?1,?2,?3)").map_err(sql)?;
let mut bounds = tx.prepare("INSERT INTO bounds VALUES(?1,?2,?3,?4,?5)").map_err(sql)?;
let mut paced = Paced::begin(len);
scan_boxed(path, len, |id, place, b| {
paced.at(id, place)?;
record.execute(params![id, place.offset, place.len]).map_err(sql)?;
if union(&mut all_bounds, b) {
let [x0, y0, x1, y1] = b;
Expand Down Expand Up @@ -242,6 +252,31 @@ fn union(all: &mut Option<[f32; 4]>, b: [f32; 4]) -> bool {
true
}

/// The progress of a scan made as a Shapefile is opened (an index built, or the records counted
/// when none can be), in bytes of the `.shp` (#2446).
struct Paced {
to: u32,
}

impl Paced {
/// Starts counting a scan of a `.shp` of `len` bytes.
fn begin(len: u64) -> Self {
crate::progress::begin(usize::try_from(len).unwrap_or(usize::MAX));
Self { to: 0 }
}

/// Counts the bytes up to record `id`, at `place`, every so many records; stops once Cancel
/// was pressed.
fn at(&mut self, id: u32, place: Place) -> Result<()> {
if !id.is_multiple_of(4096) {
return Ok(());
}
let done = place.offset.saturating_sub(self.to);
self.to = self.to.max(place.offset);
crate::progress::step(usize::try_from(done).unwrap_or(usize::MAX))
}
}

/// What scanning the records' headers gathers, as a disk index holds it, for when none can be
/// written.
pub(super) struct Scanned {
Expand All @@ -256,7 +291,9 @@ pub(super) struct Scanned {
/// isn't one.
pub(super) fn scanned(path: &Path, len: u64) -> Result<Scanned> {
let (mut bounds, mut unboxed) = (None, 0u32);
let (count, note) = scan_boxed(path, len, |_, _, b| {
let mut paced = Paced::begin(len);
let (count, note) = scan_boxed(path, len, |id, place, b| {
paced.at(id, place)?;
if !union(&mut bounds, b) && not_a_box(b) {
unboxed += 1;
}
Expand Down
Loading
Loading