From 5b16b511f9e68405227958ee32569e707f36a5e0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 07:59:25 -0600 Subject: [PATCH 1/7] fix(engine): carry streamed field layers and package notices --- crates/data/src/source/geojson.rs | 115 +++-- crates/data/src/source/mod.rs | 6 + crates/engine/src/cmd/exports.rs | 2 + crates/engine/src/cmd/field.rs | 552 ++++++++++++++++++--- crates/engine/src/cmd/field_audit_tests.rs | 2 +- crates/engine/src/cmd/project.rs | 15 +- crates/engine/src/tests/cancellation.rs | 10 +- crates/map/src/lib.rs | 17 +- crates/map/src/source.rs | 5 + crates/ui-egui/src/lib.rs | 21 +- docs/user-guide/field-work.md | 7 +- 11 files changed, 618 insertions(+), 134 deletions(-) diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 6902a3f0b5..3b0f1af6c8 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -226,17 +226,22 @@ impl GeoJsonSource { /// those whose boxes meet it (features without geometry never do). The extent is in the /// file's own coordinates. fn matches(&self, extent: Option) -> impl Iterator + '_ { + self.candidates(extent).filter_map(|(i, matches)| matches.then_some(i)) + } + + /// Walks every index entry, exposing rejected entries too so a full visit can count + /// progress and check Cancel even across a long stretch outside the requested extent. + fn candidates(&self, extent: Option) -> impl Iterator + '_ { // Rounded to the nearest f32: never past a box rounded outward that meets the extent. let e = extent.map(|e| (e.is_empty(), [e.min_x as f32, e.min_y as f32, e.max_x as f32, e.max_y as f32])); - self.boxes - .iter() - .enumerate() - .filter_map(move |(i, b)| match e { - None => Some(i as u32), - Some((true, _)) => None, - Some((false, [x0, y0, x1, y1])) => (b[0] <= x1 && b[2] >= x0 && b[1] <= y1 && b[3] >= y0).then_some(i as u32), - }) - .filter(|i| self.failed.binary_search(i).is_err()) + self.boxes.iter().enumerate().map(move |(i, b)| { + let in_box = match e { + None => true, + Some((true, _)) => false, + Some((false, [x0, y0, x1, y1])) => b[0] <= x1 && b[2] >= x0 && b[1] <= y1 && b[3] >= y0, + }; + (i as u32, in_box && self.failed.binary_search(&(i as u32)).is_err()) + }) } } @@ -256,6 +261,38 @@ impl FeatureSource for GeoJsonSource { self.unreadable + self.failed.len() } + fn visits_extent_chunks(&self) -> bool { + true + } + + /// Visits the matching file records in order and retains only one batch of decoded rows. + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let req = Request { extent, limit: usize::MAX }; + let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(&self.path)?); + let mut pos = 0; + let mut buf = Vec::new(); + let mut batch = Batch { complete: true, ..Batch::default() }; + crate::progress::begin(self.places.len()); + for (i, matches) in self.candidates(native) { + crate::progress::step(1)?; + if !matches { + continue; + } + match self.read_feature((&mut f, &mut pos, &mut buf), i, &req, || true) { + Ok(Some(feature)) => { + batch.matched += 1; + chunks.push(feature)?; + } + Err(()) => batch.skipped += 1, + Ok(None) => {} + } + } + chunks.flush()?; + Ok(batch) + } + /// Reads a bounded sample; when native bounds are refused, filters geometry before sampling, /// counting records and checking Cancel between them. fn read(&self, req: &Request) -> Result { @@ -283,36 +320,14 @@ impl FeatureSource for GeoJsonSource { if late { crate::progress::step(1)?; } - let Some(place) = self.places.get(i as usize) else { continue }; - let Some(json) = read_place(&mut f, &mut pos, &mut buf, place) else { - skipped += 1; - continue; - }; - let Ok(geometry) = geojson_geometry(&json) else { - skipped += 1; - continue; - }; - // To longitude/latitude; a feature that can't be is skipped, as one that can't be read. - let geometry = match (self.reproject.transformer(), geometry) { - (Some(t), Some(g)) => match geometry_to_lonlat(&g, t) { - Some(g) => Some(g), - None => { - skipped += 1; - continue; - } - }, - (_, g) => g, + let feature = match self.read_feature((&mut f, &mut pos, &mut buf), i, req, || !late || sample.wants()) { + Ok(Some(feature)) => feature, + Err(()) => { + skipped += 1; + continue; + } + Ok(None) => continue, }; - // The boxes are rounded outward to f32, so they can match a feature just outside. A - // feature without geometry doesn't match an extent (the boxes leave it out, but there - // are none to filter with when the file's system couldn't bound the extent). - if geometry.as_ref().map_or(req.extent.is_some(), |g| !in_request(g, req)) { - continue; - } - if late && !sample.wants() { - continue; - } - let feature = Feature { id: u64::from(i) + 1, geometry, attrs: geojson_attrs(&json, &self.info.fields) }; if late { sample.keep(feature); } else { @@ -338,6 +353,30 @@ impl FeatureSource for GeoJsonSource { } } +impl GeoJsonSource { + /// Decodes one indexed record. A missing or malformed record is unreadable, while a + /// record past the request's bounds (including rounding in the index) is excluded. + fn read_feature( + &self, + (f, pos, buf): (&mut BufReader, &mut u64, &mut Vec), + i: u32, + req: &Request, + wanted: impl FnOnce() -> bool, + ) -> std::result::Result, ()> { + let place = self.places.get(i as usize).ok_or(())?; + let json = read_place(f, pos, buf, place).ok_or(())?; + let geometry = geojson_geometry(&json).map_err(|_| ())?; + let geometry = match (self.reproject.transformer(), geometry) { + (Some(t), Some(g)) => Some(geometry_to_lonlat(&g, t).ok_or(())?), + (_, g) => g, + }; + if geometry.as_ref().map_or(req.extent.is_some(), |g| !in_request(g, req)) || !wanted() { + return Ok(None); + } + Ok(Some(Feature { id: u64::from(i) + 1, geometry, attrs: geojson_attrs(&json, &self.info.fields) })) + } +} + /// The feature at `place`, read through `f` (at `pos`, which is kept up to date): `None` when the /// file has changed since it was opened. fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec, place: &Place) -> Option { diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 38febdbb5f..d677f2eb72 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -352,6 +352,12 @@ pub trait FeatureSource: Send + Sync { fn visits_chunks(&self) -> bool { self.streams_chunks() } + /// 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. + fn visits_extent_chunks(&self) -> bool { + self.visits_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 diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 25e2af1de5..0b3cc29d83 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -62,6 +62,8 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[ ("layout.export", "Export Layout", super::layout::export_work), ("report.export", "Export Report", super::report::export_work), ("source.publish", "Publish to Source", super::publish::publish_work), + #[cfg(not(target_arch = "wasm32"))] + ("offline.package", "Package for the Field", super::field::export_work), ]; /// `command` and what it is called, when the app writes its file on another thread (see diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 8f8b8f1b26..a41f11084b 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -32,12 +32,31 @@ const PHOTOS: &str = "photos"; pub(crate) const OFFLINE: &str = " (offline)"; /// The most bytes read from one field package's entries when it is opened. const MOST_UNPACKED: usize = rustgis_data::zip::MAX_TOTAL; +/// Optional information for the crew. Older readers extract it like any other companion file. +const LEFT_BEHIND: &str = "left-behind.v1.json"; +const MAX_MANIFEST: usize = 256 << 10; +const MAX_NOTICES: usize = 16; /// Whether a file name or path is a field package's, ignoring case. pub fn is_field_package(name: &str) -> bool { name.to_ascii_lowercase().strip_suffix(EXTENSION).is_some_and(|s| s.ends_with('.')) } +/// Default name for the save picker before the desktop export starts. +#[cfg(not(target_arch = "wasm32"))] +pub fn suggested_name(s: &Session, p: &Value) -> String { + let name = s.map().name.as_str(); + if s.project.field_origin.is_some() || s.opened_package.as_deref().is_some_and(|p| is_field_package(&p.to_string_lossy())) { + return name.strip_suffix(OFFLINE).unwrap_or(name).to_string(); + } + if let Some(area) = name.strip_suffix(OFFLINE) + && s.project.offline_areas.iter().any(|saved| saved.name.eq_ignore_ascii_case(area)) + { + return area.to_string(); + } + super::ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| format!("{name} offline"), str::to_string) +} + /// A field package of the active map, as (name, bytes). /// /// The map of a home offline area or of an opened field package goes as it is, so its edits @@ -46,9 +65,6 @@ pub fn is_field_package(name: &str) -> bool { /// /// Never silent: the raster layers an offline area leaves behind, the tile layers that stay /// online (a web address, not an archive), and an archive that couldn't be read are said. -/// -/// It runs where it is called, on the window's thread from Save (`ui.saveItem`), as Package -/// Project does: each archive is one read and the zip one write, with no Cancel between them. #[cfg(test)] pub(crate) fn package(s: &mut Session, p: &Value) -> Result<(String, Vec), String> { let (name, bytes, notes) = package_output(s, p)?; @@ -82,17 +98,13 @@ fn legacy_user(s: &Session) -> Result<(), String> { /// carries the area's identities and return check, assigned here the first time and recorded as /// one undoable change. Coming back, from a field project, it is that project's own map with the /// photos its features name, keeping the origin it was made with. What it leaves behind is added to -/// `notes`, said once the package has been delivered. +/// `notes`, said once the package has been delivered. Cancel is checked between streamed +/// chunks, tile archives and the encoding steps. A single archive read or ZIP compression +/// runs through before the next check. fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<(String, Vec), String> { - macro_rules! note { - ($text:expr, $error:expr $(,)?) => { - if $error { - s.notify($text, true); - } else { - notes.push(($text).to_string()); - } - }; - } + use rustgis_data::progress; + progress::check().map_err(|e| e.to_string())?; + let mut losses = Vec::new(); let legacy_return = if p.get("legacyReturn").is_some() { legacy_user(s)?; super::b(p, "legacyReturn").ok_or("legacyReturn must be true or false")? @@ -126,14 +138,15 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< if !rasters.is_empty() { m.release_tiles(&rasters); m.layers.retain(|l| !l.is_raster()); - note!(format!("{} raster layer(s) were left out of the field package: it holds feature layers", rasters.len()), false); + losses.push(format!("{} raster layer(s) were left out of the field package: it holds feature layers", rasters.len())); } (area, m) } None => { let rasters = s.map().layers.iter().filter(|l| l.is_raster()).count(); - let features = - |m: &rustgis_map::Map| m.layers.iter().filter(|l| !l.is_raster()).map(|l| l.dataset.features.len()).sum::(); + let features = |m: &rustgis_map::Map| { + m.layers.iter().filter(|l| !l.is_raster() && !l.is_streamed()).map(|l| l.dataset.features.len()).sum::() + }; let had = features(s.map()); // The new area's first package is of the state it starts in: made with it, as one undo step. let made = field_edit(s, "Create field offline area", |s| { @@ -149,21 +162,17 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< let data = s.project.offline_areas.iter().find(|a| a.name == name).map(|a| a.data.clone()).ok_or("the offline area wasn't made")?; if rasters > 0 { - note!(format!("{rasters} raster layer(s) were left out of the field package: an offline area holds feature layers"), false,); + losses.push(format!("{rasters} raster layer(s) were left out of the field package: an offline area holds feature layers")); } - note!( - format!( + notes.push(format!( "Made the offline area '{name}' of this map for the field package: save this project to bring the field's edits back to it later" - ), - false, - ); + )); // The area holds the features its extent (the view, unless one is given) touches. let out = had.saturating_sub(features(&data)); if out > 0 { - note!( - format!("{out} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package"), - false, - ); + losses.push(format!( + "{out} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package" + )); } (name, data) } @@ -173,7 +182,9 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< // Each local archive goes in beside the project, its layer reading it from there. let (mut online, mut unread, mut uploaded) = (Vec::new(), Vec::new(), Vec::new()); let mut taken = std::collections::HashSet::new(); + progress::begin(map.tiles.len()); for t in &mut map.tiles { + progress::step(1).map_err(|e| e.to_string())?; let Some(file) = t.archive_file().map(str::to_string) else { // An archive added to the web app lives in its memory, not in a file to put in. if t.url.starts_with(rustgis_map::tiles::UPLOAD) { @@ -212,46 +223,37 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< } } if !online.is_empty() { - note!( - format!( + losses.push(format!( "{} tile layer(s) in the field package draw from the web and show only online: {}. Add an MBTiles or PMTiles archive for a basemap with no network", online.len(), online.join(", ") - ), - false, - ); + )); } if !uploaded.is_empty() { - note!( - format!( + losses.push(format!( "{} tile archive(s) added to this browser couldn't be put in the field package, as they live only in its memory: {}. Add them to the field from the file", uploaded.len(), uploaded.join(", ") - ), - true, - ); + )); } if !unread.is_empty() { - note!(format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", ")), true); + losses.push(format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } // Coming back, the photos taken in the field go with their features. if coming_back { let photos = take_photos(&mut map, &mut budget); if !photos.unread.is_empty() { let unread = &photos.unread; - note!(format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", ")), true); + losses.push(format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } if !photos.not_pictures.is_empty() { let named = &photos.not_pictures; - note!( - format!( - "{} file(s) a photos field names weren't put in the field package: only pictures go ({}): {}", - named.len(), - PICTURES.join(", "), - named.join(", ") - ), - false, - ); + losses.push(format!( + "{} file(s) a photos field names weren't put in the field package: only pictures go ({}): {}", + named.len(), + PICTURES.join(", "), + named.join(", ") + )); } entries.extend(photos.entries); } @@ -295,9 +297,11 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< })?; } if assigned_identity { - note!("Assigned this legacy offline area an origin identity: save the home project before sending the field package", false); + notes.push( + "Assigned this legacy offline area an origin identity: save the home project before sending the field package".into(), + ); } else if gave_generation { - note!("Gave this offline area a return check: save the home project before sending the field package", false); + notes.push("Gave this offline area a return check: save the home project before sending the field package".into()); } let home_area = s.project.offline_areas.get(ai).ok_or("the offline area was not found")?; Some(crate::project::FieldOrigin { @@ -316,9 +320,19 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< project.field_origin = origin; // The package has no home offline areas and carries its association in field_origin. map.offline_area_id = None; + let mut copied = Vec::new(); if !coming_back { // Older phones also look at the outgoing title to show Send Field Package. map.name = format!("{area}{OFFLINE}"); + let extent = s + .project + .offline_areas + .iter() + .find(|saved| saved.name.eq_ignore_ascii_case(&area)) + .ok_or("the offline area was not found")? + .extent; + let available = project_room(&entries); + copied = copy_streams(&mut map, extent, stream_budget(available), &mut losses)?; } project.maps = vec![map]; let home = &s.project; @@ -345,20 +359,295 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< .map(|(n, what)| format!("{n} {what}")) .collect(); if !stayed.is_empty() { - note!(format!("The field package holds only the map '{area}': {} stayed in this project", stayed.join(", ")), false); + losses.push(format!("The field package holds only the map '{area}': {} stayed in this project", stayed.join(", "))); } project.ramps = s.project.ramps.clone(); project.styles = s.project.styles.clone(); let readme = format!( "{area}: a RustGIS field package.\nOpen it with RustGIS on a phone or a computer (Open Project). Its basemaps are in {BASEMAPS}/.\n" ); - let room = crate::project::max_bytes().min(MOST_UNPACKED as u64).saturating_sub(entries.iter().map(|(_, b)| b.len() as u64).sum()); + entries.push(("README.txt".into(), readme.into_bytes())); + let room = project_room(&entries); let too_large = || "the field package would be too large: leave a tile archive or some data out".to_string(); - let (text, report) = crate::durable::output_owned(project, |p| crate::project::json_within(p, room)?.ok_or_else(too_large))?; + if !copied.is_empty() { + let map = project.maps.first().ok_or("the field package holds no map")?; + let names: Vec<_> = copied.iter().filter_map(|id| map.layer(*id)).map(|l| l.name.as_str()).collect(); + losses.push(format!( + "{} layer(s) read in place at home were copied for reference: {}. Edits to these copies stay in the field project", + names.len(), + names.join(", ") + )); + } + let mut manifest = manifest_bytes(&losses)?; + progress::check().map_err(|e| e.to_string())?; + let (mut text, mut report) = + crate::durable::output(&mut project, None, |p| crate::project::json_within(p, room.saturating_sub(manifest.len() as u64)))?; + if text.is_none() && !copied.is_empty() { + // Row storage and encoded JSON measure different things. The package's hard limit + // also includes loaded layers and basemaps, so retry once without the streamed copies. + losses.pop(); + let map = project.maps.first_mut().ok_or("the field package holds no map")?; + map.release_tiles(&copied); + map.layers.retain(|l| { + if copied.contains(&l.id) { + losses.push(format!( + "{}: {} feature(s) in the offline area were left out because the field package would be too large", + l.name, + l.dataset.features.len() + )); + false + } else { + true + } + }); + manifest = manifest_bytes(&losses)?; + (text, report) = + crate::durable::output(&mut project, None, |p| crate::project::json_within(p, room.saturating_sub(manifest.len() as u64)))?; + } + let text = text.ok_or_else(too_large)?; + progress::check().map_err(|e| e.to_string())?; crate::durable::notify(s, &report); entries.insert(0, (format!("{}.{}", super::items::safe(&area), crate::project::EXTENSION), text.into_bytes())); - entries.push(("README.txt".into(), readme.into_bytes())); - Ok((area, rustgis_data::zip::write(&entries)?)) + if !manifest.is_empty() { + entries.push((LEFT_BEHIND.into(), manifest)); + } + let bytes = rustgis_data::zip::write(&entries)?; + progress::check().map_err(|e| e.to_string())?; + notes.extend(losses); + Ok((area, bytes)) +} + +/// Desktop export worker: build and write against a shared-row project snapshot, then install +/// the home identities and offline area only after a completed write. If the home project changed +/// meanwhile, leave its current state intact and tell the sender that the file must be remade. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn export_work(s: &Session, p: &Value) -> Result { + if p.get("legacyReturn").is_some() { + legacy_user(s)?; + } + let path = super::ps(p, "path").ok_or("path is required")?.to_string(); + not_the_project(s, Path::new(&path))?; + let p = p.clone(); + let construction_notes = s.constructions.output_notes(s.map().layers.iter().map(|l| (s.map().instance_id(), l)))?; + let project = s.project.clone(); + let (view, opened_package) = (s.view_size, s.opened_package.clone()); + let (opened, state) = (s.opened, s.state()); + Ok(Box::new(move || { + let mut copy = Session::new(project); + copy.notices.clear(); + copy.undo_memory.memory = None; + copy.view_size = view; + copy.opened_package = opened_package; + let before = (copy.project.origin_id.clone(), area_ids(©.project)); + let (area, bytes, mut notes) = package_output(&mut copy, &p)?; + let answer = packaged(&path, &area, bytes.len()); + rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; + notes.extend(copy.notices.into_iter().map(|n| n.text)); + notes.extend(construction_notes); + let next = copy.project; + // A newer home state may no longer accept the package (a concurrent sync can advance + // its generation). A return from the field owns its snapshot without any home update. + let outbound = next.offline_areas.iter().any(|saved| saved.name.eq_ignore_ascii_case(&area)); + let change = (before != (next.origin_id.clone(), area_ids(&next))).then_some((next.origin_id, next.offline_areas)); + let then: super::exports::Then = Box::new(move |s, _| { + if outbound && (s.opened != opened || s.state() != state) { + return Err("the home project changed during packaging; make a new package before sending it to the field".into()); + } + if let Some((origin, areas)) = change { + field_edit(s, "Prepare home project for field package", |s| { + s.project.origin_id = origin; + s.project.offline_areas = areas; + Ok(Value::Null) + })?; + } + for note in notes { + s.notify_written(note, false); + } + Ok(()) + }); + Ok(super::exports::Wrote { + answer, + notes: Vec::new(), + then: Some(then), + written_path: Some(path), + diagnostics: Vec::new(), + refused_notes: Vec::new(), + owner: None, + crs_used: Vec::new(), + }) + })) +} + +/// Offline area identity state which packaging can change. Feature rows are shared with home +/// until the worker builds a new area's clipped baseline. +#[cfg(not(target_arch = "wasm32"))] +fn area_ids(project: &Project) -> Vec<(String, String)> { + project.offline_areas.iter().map(|a| (a.id.clone(), a.generation.clone())).collect() +} + +/// Bytes available for project JSON and notices once the companion files have been counted. +fn project_room(entries: &[(String, Vec)]) -> u64 { + crate::project::max_bytes().min(MOST_UNPACKED as u64).saturating_sub(entries.iter().map(|(_, b)| b.len() as u64).sum()) +} + +/// Retain one map's worth of clipped streamed rows within a shared budget. Leave some of the +/// package room for the JSON and plan for both encoders and the other data already in memory. +fn stream_budget(room: u64) -> usize { + let memory = rustgis_data::memory::planned(8 << 20, 128 << 20, 4); + memory.min(usize::try_from(room / 2).unwrap_or(usize::MAX)) +} + +/// Copies only streams backed by portable reads. Failed or oversized layers are removed +/// whole, so a missing source or a truncated sample cannot look like a complete field layer. +fn copy_streams( + map: &mut rustgis_map::Map, + extent: rustgis_data::Extent, + mut budget: usize, + losses: &mut Vec, +) -> Result, String> { + let mut copied = Vec::new(); + let mut omitted = Vec::new(); + for layer in map.layers.iter_mut().filter(|l| l.is_streamed()) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + match copy_stream(layer, extent, budget, losses) { + Ok(Some(used)) => { + budget -= used; + copied.push(layer.id); + } + Ok(None) => omitted.push(layer.id), + Err(error) => { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + losses.push(format!("{}: streamed layer couldn't be put in the field package ({error})", layer.name)); + omitted.push(layer.id); + } + } + } + if !omitted.is_empty() { + map.release_tiles(&omitted); + let omitted: std::collections::HashSet<_> = omitted.into_iter().collect(); + map.layers.retain(|l| !omitted.contains(&l.id)); + } + Ok(copied) +} + +/// Counts every in-area row even when the layer is too large, dropping the retained rows as +/// soon as it cannot fit. Source readers keep one chunk (or one indivisible row) at a time. +fn copy_stream( + layer: &mut rustgis_map::Layer, + extent: rustgis_data::Extent, + budget: usize, + losses: &mut Vec, +) -> Result, String> { + use rustgis_data::{DataError, Feature, progress, source}; + let eligible = layer.source.as_ref().is_some_and(|s| s.linked_file().is_some() || s.embedded.is_some()); + let Some((src, mut dataset)) = (if eligible { layer.chunk_in_extent()? } else { None }) else { + let count = layer + .source + .as_ref() + .and_then(|s| s.info()) + .and_then(|i| i.count) + .map_or_else(|| "source feature count unavailable".into(), |count| format!("{count} feature(s) in the source")); + losses.push(format!("{}: streamed layer left out because its source can't be copied in pieces ({count})", layer.name)); + return Ok(None); + }; + let mut rows = Vec::new(); + let (mut used, mut inside, mut outside) = (0usize, 0usize, 0usize); + let mut fits = true; + let info = src.info(); + let batch = src + .visit_chunks(Some(extent), 1 << 20, &mut |chunk| { + progress::check()?; + for mut row in chunk { + if row.geometry.as_ref().is_none_or(|g| !g.extent().intersects(&extent)) { + outside += 1; + continue; + } + inside += 1; + if fits { + row.attrs.truncate(dataset.fields.len()); + row.attrs + .try_reserve(dataset.fields.len().saturating_sub(row.attrs.len())) + .map_err(|_| DataError::Format("not enough memory for the field package's attributes".into()))?; + row.attrs.resize(dataset.fields.len(), rustgis_data::Value::Null); + // Count twice the row slots for the vector's spare capacity, as it grows. + used = + used.saturating_add(source::chunk_memory::feature_bytes(&row).saturating_add(2 * std::mem::size_of::())); + fits = used <= budget && rows.try_reserve(1).is_ok(); + if fits { + rows.push(row); + } else { + rows = Vec::new(); + } + } + } + Ok(()) + }) + .map_err(|e| e.to_string())?; + let unread = batch.skipped.saturating_add(src.skipped_at_open()); + if unread > 0 { + losses.push(format!("{}: {unread} feature(s) couldn't be read while preparing the field package", layer.name)); + } + if !batch.complete { + return Err("the source did not provide a complete read".into()); + } + if !fits { + losses.push(format!( + "{}: {inside} feature(s) in the offline area were left out because the streamed layer exceeded the field package budget", + layer.name + )); + return Ok(None); + } + // An indexed read can skip the rest of the file outright. Only report a total outside the + // area when the source knows its count and the traversal didn't encounter unreadable rows. + let outside = info.count.filter(|_| unread == 0).map_or(outside as u64, |total| total.saturating_sub(inside as u64)); + if outside > 0 { + losses.push(format!( + "{}: {outside} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package", + layer.name + )); + } + let counted = [ + source::unread_dates_note(&info.fields, &batch.unread_dates), + source::rounded_dates_note(&info.fields, &batch.rounded_dates), + source::null_text_note(&info.fields, &batch.null_text), + ]; + losses.extend(info.notes.iter().chain(&batch.notes).chain(counted.iter().flatten()).map(|note| format!("{}: {note}", layer.name))); + dataset.crs_incomplete = src.lost_to_crs() || (info.format == "Shapefile" && batch.skipped > 0); + if dataset.geometry_type == rustgis_data::GeometryType::None + && let Some(g) = rows.first().and_then(|r| r.geometry.as_ref()) + { + dataset.geometry_type = g.kind(); + } + dataset.features = rows.into(); + dataset.source = None; + layer.source = None; + layer.dataset = dataset; + layer.synced = None; + super::workspace::unbind_table_edits(layer); + layer.selection.clear(); + layer.touch_geometry(); + Ok(Some(used)) +} + +/// Only portable, redacted summaries go into the archive. Keep the list within the receiver's +/// diagnostic limits even when a project has thousands of missing layers. +fn manifest_bytes(losses: &[String]) -> Result, String> { + if losses.is_empty() { + return Ok(Vec::new()); + } + let mut notes: Vec<_> = losses.iter().take(MAX_NOTICES).map(|s| Session::redacted(s).into_string()).collect(); + // JSON can grow when text has escapes. Drop the tail and count it if the byte limit is hit. + loop { + let mut candidate = notes.clone(); + let omitted = losses.len().saturating_sub(notes.len()); + if omitted > 0 { + candidate.push(format!("{omitted} more field package notice(s) were reported when the package was made")); + } + if let Some(text) = crate::project::json_within(&candidate, MAX_MANIFEST as u64)? { + return Ok(text.into_bytes()); + } + notes.pop(); + } } /// A layer's photos field, by its place: its text field named `photos` or `photo`, whatever the @@ -665,17 +954,33 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result { // must be the area's own, of the same kind (a name may have changed in the field), or features // of other layers would be changed. let baseline = s.project.offline_areas.get(ai).map(|a| &a.data).ok_or("no such area")?; - let foreign = edited - .layers - .iter() - .filter(|l| !l.is_raster()) - .any(|l| baseline.layers.iter().find(|b| b.id == l.id).is_some_and(|b| b.geometry_type() != l.geometry_type())) - || !edited.layers.iter().any(|l| baseline.layers.iter().any(|b| b.id == l.id)); + let foreign = + edited.layers.iter().filter(|l| !l.is_raster()).any(|l| { + baseline.layers.iter().find(|b| b.id == l.id).is_some_and(|b| !b.is_streamed() && b.geometry_type() != l.geometry_type()) + }) || !edited.layers.iter().any(|l| baseline.layers.iter().any(|b| b.id == l.id)); if foreign { return Err(format!( "the field package's map isn't one made from this project's offline area '{area}': its layers aren't the area's. Open the project it was made from" )); } + let mut reference = Vec::new(); + edited.layers.retain(|l| { + let keep = !baseline.layers.iter().any(|b| b.id == l.id && b.is_streamed()); + if !keep { + reference.push(l.name.clone()); + } + keep + }); + if !reference.is_empty() { + s.notify( + format!( + "Bring Back skipped {} layer(s) copied from sources read in place at home. Any edits to them stay in the field project: {}", + reference.len(), + reference.join(", ") + ), + false, + ); + } // The photos, beside the project, and the features naming them there. let mut put = 0usize; let mut renamed = 0usize; @@ -862,22 +1167,23 @@ fn fresh_dir(base: &Path, name: &str) -> PathBuf { } /// Unpacks a field package's `bytes` into a folder of its own in the app's folder (`field/`, -/// numbered when that is taken) and returns the folder and the project's text. An entry that +/// numbered when that is taken) and returns the folder, project text and construction notices. An entry that /// would land outside the folder is refused, and the package with it. /// /// The project's own paths are trusted as a project file's are: a package from someone else can /// name files outside the folder, as a `.rgis` can. -pub(crate) fn unpack(bytes: &[u8], stem: &str) -> Result<(PathBuf, String), String> { +pub(crate) fn unpack(bytes: &[u8], stem: &str) -> Result<(PathBuf, String, Vec), String> { let dir = unpack_dir(stem)?; - let text = unpack_into(bytes, &dir)?; - Ok((dir, text)) + let (text, notes) = unpack_into(bytes, &dir)?; + Ok((dir, text, notes)) } /// Unpacks a field package's `bytes` into `dir`, a folder not there yet (see [`unpack`]), and -/// returns the project's text. A write that fails removes what was written. -fn unpack_into(bytes: &[u8], dir: &Path) -> Result { +/// returns the project text and its optional notices. A write that fails removes what was written. +fn unpack_into(bytes: &[u8], dir: &Path) -> Result<(String, Vec), String> { let entries = rustgis_data::zip::read(bytes)?; let mut project = None; + let mut manifest = None; let mut files = Vec::new(); for (name, data) in entries { let parts: Vec<&str> = name.split(['/', '\\']).filter(|p| !p.is_empty()).collect(); @@ -890,6 +1196,12 @@ fn unpack_into(bytes: &[u8], dir: &Path) -> Result { } project = Some(String::from_utf8(data).map_err(|_| "the field package's project is damaged".to_string())?); } else { + if parts.as_slice() == [LEFT_BEHIND] { + if manifest.is_some() { + return Err("the field package holds more than one list of what stayed behind".into()); + } + manifest = Some(read_manifest(&data)); + } files.push((parts.iter().collect::(), data)); } } @@ -914,7 +1226,19 @@ fn unpack_into(bytes: &[u8], dir: &Path) -> Result { return Err(e); } std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - Ok(text) + Ok((text, manifest.unwrap_or_default())) +} + +/// A missing manifest is normal for an old package; a damaged manifest leaves the map usable +/// and gets a notice of its own. +fn read_manifest(bytes: &[u8]) -> Vec { + if bytes.len() <= MAX_MANIFEST + && let Ok(notes) = serde_json::from_slice::>(bytes) + && notes.len() <= MAX_NOTICES + 1 + { + return notes; + } + vec!["The field package's list of what stayed behind could not be read".into()] } /// Reads a field package's project, its relative paths resolved against `dir`. @@ -1016,11 +1340,11 @@ mod tests { // The package: the project, the archive under basemaps/, a README. let entries = rustgis_data::zip::read(&bytes).unwrap(); let names: Vec<&str> = entries.iter().map(|(n, _)| n.as_str()).collect(); - assert_eq!(names, ["Survey.rgis", "basemaps/site.mbtiles", "README.txt"]); + assert_eq!(names, ["Survey.rgis", "basemaps/site.mbtiles", "README.txt", LEFT_BEHIND]); assert_eq!(entries[1].1, b"stand-in archive bytes"); // Unpacked and read: one map, the area's, its features in it, its basemap read from beside it. let into = temp.path().join("unpacked"); - let text = unpack_into(&bytes, &into).unwrap(); + let text = unpack_into(&bytes, &into).unwrap().0; let project = project_in(&text, &into).unwrap(); assert_eq!(project.maps.len(), 1); let map = &project.maps[0]; @@ -1037,6 +1361,65 @@ mod tests { assert!(into.join("basemaps/site.mbtiles").is_file() && again.join("basemaps/site.mbtiles").is_file()); } + #[test] + fn field_package_carries_streamed_features_after_the_source_is_gone() { + let temp = Temp::new("stream"); + let source = temp.path().join("places.gpkg"); + let mut seed = Session::new(Project::default()); + let mut places = rustgis_data::Dataset::new("Places", rustgis_data::GeometryType::Point, vec![]); + places.crs = rustgis_data::raster::Crs::from_epsg(4326); + for x in [1.0, 10.0] { + places.push(Some(rustgis_data::Geometry::Point(rustgis_data::Coord::new(x, 1.0))), vec![]); + } + let id = seed.map_mut().add_dataset(places); + seed.run("share.exportLayer", &json!({"layer": id, "path": source})).unwrap(); + + let mut home = Session::new(Project::default()); + home.run("layer.addData", &json!({"name": "Streamed", "path": source, "layer": "Places", "stream": true})).unwrap(); + assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); + let mark = home.notice_mark(); + let extent = rustgis_data::Extent::new(0.0, 0.0, 2.0, 2.0); + let mut oversized = home.map().clone(); + let mut omissions = Vec::new(); + assert!(copy_streams(&mut oversized, extent, 0, &mut omissions).unwrap().is_empty()); + assert!(oversized.layer_by_name("Streamed").is_none()); + assert!(omissions.iter().any(|n| n.contains("1 feature(s) in the offline area") && n.contains("budget")), "{omissions:?}"); + + let (_, bytes) = package(&mut home, &json!({"name": "Site", "extent": [0, 0, 2, 2]})).unwrap(); + assert!(home.notices_since(mark).iter().any(|n| n.text.contains("copied for reference"))); + let stem = temp.path().file_name().unwrap().to_str().unwrap(); + let path = temp.path().join(format!("{stem}.rgisfield")); + std::fs::write(&path, bytes).unwrap(); + let _unpacked = Temp(unpack_dir(stem).unwrap()); + let mut crew = Session::new(Project::default()); + let held = source.with_extension("held"); + // Hide the original source before opening on the receiving session. SQLite may + // keep the file open on Windows, so drop the live session and use its saved state. + let home_text = serde_json::to_string(&home.project).unwrap(); + drop(oversized); + drop(home); + std::fs::rename(&source, &held).unwrap(); + let mark = crew.notice_mark(); + crew.run("project.open", &json!({"path": path})).unwrap(); + let copy = crew.map().layer_by_name("Streamed").unwrap(); + assert_eq!(copy.dataset.features.len(), 1, "the crew should have the in-area feature"); + assert!(!copy.is_streamed()); + assert!(crew.notices_since(mark).iter().any(|n| n.text.contains("copied for reference"))); + assert!(crew.notices_since(mark).iter().all(|n| !n.text.contains("Made the offline area"))); + + std::fs::rename(&held, &source).unwrap(); + let mut home = Session::new(Project::from_json(&home_text).unwrap()); + crew.run("edit.addFeature", &json!({"layer":"Streamed", "geometry":{"type":"Point", "coordinates":[1.5, 1.5]}})).unwrap(); + let (_, bytes) = package(&mut crew, &Value::Null).unwrap(); + let returned = temp.path().join("returned.rgisfield"); + std::fs::write(&returned, bytes).unwrap(); + let mark = home.notice_mark(); + let done = home.run("offline.bringBack", &json!({"path": returned})).unwrap(); + assert_eq!(done["added"], 0); + assert!(home.notices_since(mark).iter().any(|n| n.text.contains("Bring Back skipped 1 layer"))); + assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); + } + #[test] fn a_field_package_holds_only_its_map_and_a_basemap_of_any_name_is_read() { let temp = Temp::new("only"); @@ -1064,7 +1447,7 @@ mod tests { let names: Vec = rustgis_data::zip::read(&bytes).unwrap().into_iter().map(|(n, _)| n).collect(); assert!(names.contains(&"basemaps/site_a_b__.mbtiles".to_string()), "{names:?}"); let into = temp.path().join("unpacked"); - let project = project_in(&unpack_into(&bytes, &into).unwrap(), &into).unwrap(); + let project = project_in(&unpack_into(&bytes, &into).unwrap().0, &into).unwrap(); assert!(project.tables.is_empty() && project.folders.is_empty() && project.offline_areas.is_empty()); assert_eq!(project.maps.len(), 1); let base = project.maps[0].tiles.iter().find(|t| t.name == "Site").unwrap(); @@ -1122,7 +1505,9 @@ mod tests { s.map_mut().layers.retain(|l| !l.is_raster()); s.map_mut().tiles.push(TileLayer::new("Base", TileKind::PmTiles, archive.display().to_string())); let mark = s.notice_mark(); - package(&mut s, &json!({"name": "Clean"})).unwrap(); + let (_, clean) = package(&mut s, &json!({"name": "Clean", "extent": [-180, -90, 180, 90]})).unwrap(); + let (_, clean_notes) = unpack_into(&clean, &temp.path().join("clean")).unwrap(); + assert!(clean_notes.is_empty(), "{clean_notes:?}"); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().all(|t| !t.contains("left out") && !t.contains("from the web") && !t.contains("couldn't be put")), "{said:?}"); // An archive that can't be read, and a raster layer: each said. @@ -1136,7 +1521,10 @@ mod tests { assert!(s.map().layers.iter().any(|l| l.is_raster())); s.map_mut().tiles.push(TileLayer::new("Gone", TileKind::MbTiles, temp.path().join("gone.mbtiles").display().to_string())); let mark = s.notice_mark(); - package(&mut s, &json!({"name": "Lossy"})).unwrap(); + let (_, lossy) = package(&mut s, &json!({"name": "Lossy"})).unwrap(); + let (_, losses) = unpack_into(&lossy, &temp.path().join("lossy")).unwrap(); + assert!(losses.iter().any(|t| t.contains("couldn't be put") && t.contains("Gone"))); + assert!(losses.iter().any(|t| t.contains("raster layer(s) were left out"))); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("couldn't be put") && t.contains("Gone")), "{said:?}"); assert!(said.iter().any(|t| t.contains("raster layer(s) were left out")), "{said:?}"); @@ -1225,7 +1613,7 @@ mod tests { let (_, out) = package(&mut home, &json!({"name": "Trip", "extent": [-20.0, -40.0, 60.0, 40.0]})).unwrap(); // In the field: the package opened, a city renamed, one added, one deleted, a photo taken. let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); // As `project.open` marks a project opened from a field package. field.opened_package = Some(temp.path().join("sent.rgisfield")); @@ -1303,7 +1691,7 @@ mod tests { assert!(rustgis_data::zip::read(&out).unwrap().iter().all(|(n, _)| !n.starts_with("photos/"))); // Coming back: the picture only, under a plain name; the text file stays named as it was. let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); // As `project.open` marks a project opened from a field package. field.opened_package = Some(temp.path().join("sent.rgisfield")); @@ -1346,7 +1734,7 @@ mod tests { home.run("edit.setValue", &json!({"layer": cities, "row": 1, "field": "photos", "value": gif.display().to_string()})).unwrap(); let (_, out) = package(&mut home, &json!({"name": "Here", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); // Sent back with no edit: the picture goes in, listed with its path; the gif is said. @@ -1374,7 +1762,7 @@ mod tests { home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); let (_, out) = package(&mut home, &json!({"name": "Semi", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let cities = layer(&field, "Cities"); @@ -1422,7 +1810,7 @@ mod tests { home.path = Some(temp.path().join("home.rgis")); let (_, out) = package(&mut home, &json!({"name": "Odd", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let (_, back) = package(&mut field, &Value::Null).unwrap(); @@ -1456,7 +1844,7 @@ mod tests { home.path = Some(temp.path().join("home.rgis")); let (_, bytes) = package(&mut home, &json!({"name": "Site", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&bytes, &unpacked).unwrap(); + let text = unpack_into(&bytes, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let (_, back) = package(&mut field, &Value::Null).unwrap(); @@ -1487,7 +1875,7 @@ mod tests { // The whole world: the area holds every feature, so the field's next id is free at home. let (_, out) = package(&mut home, &json!({"name": "All", "extent": [-180.0, -90.0, 180.0, 90.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let cities = layer(&field, "Cities"); @@ -1515,7 +1903,7 @@ mod tests { let params = json!({"name": "Site", "extent": [-180.0, -85.0, 180.0, 85.0]}); let (_, out) = package(&mut home, ¶ms).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let field_project = project_in(&text, &unpacked).unwrap(); let origin = field_project.field_origin.clone().unwrap(); assert_eq!(origin.project, home.project.origin_id); @@ -1634,7 +2022,7 @@ mod tests { .unwrap(); let (_, out) = package(&mut other, &json!({"name": "Site", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let (_, back) = package(&mut field, &Value::Null).unwrap(); @@ -1656,7 +2044,7 @@ mod tests { home.path = Some(temp.path().join("home.rgis")); let (_, out) = package(&mut home, &json!({"name": "Back", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); - let text = unpack_into(&out, &unpacked).unwrap(); + let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = Session::new(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); let cities = layer(&field, "Cities"); diff --git a/crates/engine/src/cmd/field_audit_tests.rs b/crates/engine/src/cmd/field_audit_tests.rs index 9d84476139..d272196c4f 100644 --- a/crates/engine/src/cmd/field_audit_tests.rs +++ b/crates/engine/src/cmd/field_audit_tests.rs @@ -38,7 +38,7 @@ fn home(temp: &Temp) -> Session { /// Opens the package on a "phone": unpacked into a folder of its own, as `project.open` does. fn phone(temp: &Temp, bytes: &[u8], name: &str) -> Session { let dir = temp.0.join(name); - let text = unpack_into(bytes, &dir).unwrap(); + let (text, _) = unpack_into(bytes, &dir).unwrap(); let mut s = Session::new(project_in(&text, &dir).unwrap()); s.opened_package = Some(temp.0.join(format!("{name}.rgisfield"))); s diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 9deee4afee..2b04c561d5 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -515,20 +515,20 @@ fn open(s: &mut Session, p: &Value) -> CmdResult { let origin = if is_package { path.canonicalize() } else { std::path::absolute(&path) } .map_err(|error| format!("{}: {error}", path.display()))?; super::connections::clear_active(); - let proj = (|| { + let proj = (|| -> Result<_, String> { if is_field { let bytes = crate::project::read_file(&path, MAX_PACKAGE)?; let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - let (dir, text) = super::field::unpack(&bytes, &stem)?; - super::field::project_in(&text, &dir) + let (dir, text, notes) = super::field::unpack(&bytes, &stem)?; + Ok((super::field::project_in(&text, &dir)?, notes)) } else if is_package { let bytes = crate::project::read_file(&path, MAX_PACKAGE)?; - Project::from_import_json(&super::items::package_text(&bytes)?, None) + Ok((Project::from_import_json(&super::items::package_text(&bytes)?, None)?, Vec::new())) } else { - Project::load(&path) + Ok((Project::load(&path)?, Vec::new())) } })(); - let proj = match proj { + let (proj, notes) = match proj { Ok(proj) => proj, Err(error) => { super::connections::restore_active(s); @@ -549,6 +549,9 @@ fn open(s: &mut Session, p: &Value) -> CmdResult { s.path = Some(origin); } s.notify(format!("Opened {}", s.project.name), false); + for note in notes { + s.warn(note); + } super::connections::resolve_project(s); super::connections::note_waiting(s); Ok(Value::Null) diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 136012457b..9f5b361e57 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -135,19 +135,27 @@ pub(super) fn long_commands(boundaries: bool) { ("layout.export", json!({"path": out("layout.pdf"), "dpi": 36})), ("report.export", json!({"path": out("report.pdf"), "dpi": 36})), ("source.publish", json!({"layer": "towns"})), + ("offline.package", json!({"path": out("crew.rgisfield")})), ]; s.run("report.new", &json!({"layer": "Cities"})).unwrap(); // A standalone table to export ranked and limited. s.run("layer.addDataText", &json!({"fileName": "ranks.csv", "text": "name,score\na,1\nb,3\n"})).unwrap(); let registered = crate::cmd::exports::IN_BACKGROUND.iter().map(|(c, ..)| *c).collect::>(); assert_eq!(listed(&exports), registered, "add a new background export here"); + // Reuse the same origin and generation on every retry. The open area includes a real + // streamed layer to exercise cancellation during its source traversal as well as the write. + let mut field = session(&s); + field.run("layer.addData", &json!({"path": out("towns.shp"), "name": "Streamed towns", "stream": true})).unwrap(); + field.run("offline.package", &json!({"path": out("seed.rgisfield"), "name": "Crew", "extent": [9, 44, 11, 46]})).unwrap(); + field.run("offline.open", &json!({"name": "Crew"})).unwrap(); for (command, p) in &exports { // A block's model needs a block on the DEM, which the other exports don't draw. let block = *command == "map.exportBlock"; if block { s.run("map.terrain", &json!({"layer": dem, "block": {}})).unwrap(); } - exercise(&s, command, p, Kind::Export, &dir.0, boundaries); + let input = if *command == "offline.package" { &field } else { &s }; + exercise(input, command, p, Kind::Export, &dir.0, boundaries); if block { s.run("map.terrain", &json!({"off": true})).unwrap(); } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6a2bb6de9f..8263324e0f 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -891,8 +891,23 @@ impl Layer { /// features naming them as [`Layer::load_all`] would. `None` for a layer not /// read in place, or whose source can't be read so (one by its web address). pub fn chunk_export(&self) -> Result, Dataset)>, String> { + self.chunk_copy(source::SourceLayer::visit_source) + } + + /// A streamed layer's complete reader for a geographic extent, and a dataset describing + /// its rows. A reader that can visit an extent may still only sample its interactive views. + pub fn chunk_in_extent(&self) -> Result, Dataset)>, String> { + self.chunk_copy(source::SourceLayer::visit_extent_source) + } + + /// Opens the source and prepares an empty dataset with the layer's fields. The caller + /// selects the traversal contract it needs and decides which rows to retain. + fn chunk_copy( + &self, + visit: impl FnOnce(&source::SourceLayer) -> Option>, + ) -> Result, Dataset)>, String> { let Some(copy) = self.open_source()? else { return Ok(None) }; - let Some(src) = copy.visit_source() else { return Ok(None) }; + let Some(src) = visit(©) else { return Ok(None) }; let info = src.info(); // (A reload that read no rows leaves the reader without a type: the layer's declared one // stands, as in `load_all_counted`.) diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 17d20da157..665dd00902 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -967,6 +967,11 @@ impl SourceLayer { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() } + /// A source that can provide all features in an extent a chunk at a time. + pub(super) fn visit_extent_source(&self) -> Option> { + self.handle.as_ref().filter(|h| h.visits_extent_chunks()).cloned() + } + /// A source capable of a complete, ordered render traversal. pub fn chunk_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.streams_chunks()).cloned() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bc6b3d8ce8..eba86af312 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2938,10 +2938,11 @@ impl RustGisApp { let mark = self.session.notice_mark(); return exportjob::start(self, "map.exportBlock", params).inspect_err(|e| self.command_failed(id, e, mark)); } - // Ordering and writing a standalone table grows with its rows, like Export Features. - if id == "share.exportTable" { + // Table exports and field packages can both read and write large inputs. + if matches!(id, "share.exportTable" | "offline.package") { + let command = if id == "offline.package" { "offline.package" } else { "share.exportTable" }; let mark = self.session.notice_mark(); - return exportjob::start(self, "share.exportTable", params).inspect_err(|e| self.command_failed(id, e, mark)); + return exportjob::start(self, command, params).inspect_err(|e| self.command_failed(id, e, mark)); } // Converting the labels of a layer read in place reads all of its source first, on a // thread of its own, whoever asks (a click, the assistant). @@ -4530,6 +4531,20 @@ impl RustGisApp { } "ui.saveItem" => { let kind = p.get("kind").and_then(Value::as_str).ok_or("kind is required")?; + #[cfg(not(target_arch = "wasm32"))] + if kind == "fieldPackage" && self.reads_off_frame && self.services.download.is_none() { + exportjob::idle(self)?; + let name = rustgis_engine::cmd::field::suggested_name(&self.session, p); + let Some(path) = dialogs::pick_save(&name, &["rgisfield"], tl!("RustGIS field package")) else { + return Ok(Value::Null); + }; + let mut params = p.clone(); + if let Some(fields) = params.as_object_mut() { + fields.remove("kind"); + fields.insert("path".into(), json!(path)); + } + return self.run("offline.package", params); + } // A field package makes an offline area first: one not saved after all goes again. let areas = self.session.project.offline_areas.len(); let session = &mut self.session; diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 0d3b687d25..7f8e829a93 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -146,9 +146,12 @@ A field package (`.rgisfield`) carries a map to the phone and its edits back. 1. **On the computer**, with the map in view, **Data › Offline › Package for the Field** makes the package: a project of that map, the features in view, and the MBTiles and PMTiles archives its tile layers use. The package records the area it was made from in your project, - so save the project after packaging. Raster layers are left out, and the package says so. + so save the project after packaging. A layer read in place from a supported local file is + copied within the area while it fits the package budget. The copy is for reference, and + Bring Back skips edits to it. The sender gets a notice about anything left behind, including + rasters and streamed layers that could not be copied. 2. **On the phone**, open the package with **Open Project** (or **Add Data**). It is unpacked into - a folder of its own and its map opens. + a folder of its own and its map opens. Any notices about what stayed behind appear as it opens. 3. **In the field**, capture and edit as above. 4. **Back from the field**, **Send Field Package**, in the More sheet, saves the map as a field package again, with the photos its features name, wherever you choose (a cloud drive, email, From e67da19c2e5ab65f75ee5e661dc2259345eb67cc Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 08:32:30 -0600 Subject: [PATCH 2/7] refactor(engine): clip streamed rows for a field package in the data crate The engine reads the copied rows through accessors, so the branch adds no direct row uses (cargo xtask rows). --- crates/data/src/source/chunk_memory.rs | 18 +++++++++++++++++- crates/engine/src/cmd/field.rs | 25 ++++++++++++------------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/crates/data/src/source/chunk_memory.rs b/crates/data/src/source/chunk_memory.rs index 4f5d5244c4..ffbb3694d3 100644 --- a/crates/data/src/source/chunk_memory.rs +++ b/crates/data/src/source/chunk_memory.rs @@ -1,5 +1,5 @@ //! Allocation accounting for the chunks of a complete traversal (drawing, exports). -use crate::{Feature, Geometry, Value}; +use crate::{DataError, Extent, Feature, Geometry, Value}; use std::mem::size_of; /// Allocated vector storage owned by a geometry, excluding the enum in its containing array. @@ -80,3 +80,19 @@ impl<'a> Chunker<'a> { (self.visit)(chunk) } } + +/// A streamed row kept for a copy clipped to `extent`: `None` when it has no shape or its shape's +/// extent misses `extent`, else the row with exactly `width` values (cut, or padded with nulls) +/// and the heap bytes it holds. Fails, rather than aborting, when the values can't be allocated. +pub fn clip_row(mut row: Feature, extent: &Extent, width: usize) -> Result, DataError> { + if row.geometry.as_ref().is_none_or(|g| !g.extent().intersects(extent)) { + return Ok(None); + } + row.attrs.truncate(width); + row.attrs + .try_reserve(width.saturating_sub(row.attrs.len())) + .map_err(|_| DataError::Format("not enough memory for the copied attributes".into()))?; + row.attrs.resize(width, Value::Null); + let bytes = feature_bytes(&row); + Ok(Some((row, bytes))) +} diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index a41f11084b..256a3c31a3 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -538,7 +538,7 @@ fn copy_stream( budget: usize, losses: &mut Vec, ) -> Result, String> { - use rustgis_data::{DataError, Feature, progress, source}; + use rustgis_data::{Feature, progress, source}; let eligible = layer.source.as_ref().is_some_and(|s| s.linked_file().is_some() || s.embedded.is_some()); let Some((src, mut dataset)) = (if eligible { layer.chunk_in_extent()? } else { None }) else { let count = layer @@ -557,21 +557,20 @@ fn copy_stream( let batch = src .visit_chunks(Some(extent), 1 << 20, &mut |chunk| { progress::check()?; - for mut row in chunk { - if row.geometry.as_ref().is_none_or(|g| !g.extent().intersects(&extent)) { + for row in chunk { + // Only a row the copy keeps is reshaped; one past the budget is just counted. + let Some((row, bytes)) = (if fits { + source::chunk_memory::clip_row(row, &extent, dataset.fields.len())? + } else { + source::chunk_memory::clip_row(row, &extent, 0)? + }) else { outside += 1; continue; - } + }; inside += 1; if fits { - row.attrs.truncate(dataset.fields.len()); - row.attrs - .try_reserve(dataset.fields.len().saturating_sub(row.attrs.len())) - .map_err(|_| DataError::Format("not enough memory for the field package's attributes".into()))?; - row.attrs.resize(dataset.fields.len(), rustgis_data::Value::Null); // Count twice the row slots for the vector's spare capacity, as it grows. - used = - used.saturating_add(source::chunk_memory::feature_bytes(&row).saturating_add(2 * std::mem::size_of::())); + used = used.saturating_add(bytes.saturating_add(2 * std::mem::size_of::())); fits = used <= budget && rows.try_reserve(1).is_ok(); if fits { rows.push(row); @@ -613,12 +612,12 @@ fn copy_stream( ]; losses.extend(info.notes.iter().chain(&batch.notes).chain(counted.iter().flatten()).map(|note| format!("{}: {note}", layer.name))); dataset.crs_incomplete = src.lost_to_crs() || (info.format == "Shapefile" && batch.skipped > 0); + dataset.features = rows.into(); if dataset.geometry_type == rustgis_data::GeometryType::None - && let Some(g) = rows.first().and_then(|r| r.geometry.as_ref()) + && let Some(g) = dataset.features.geometry(0) { dataset.geometry_type = g.kind(); } - dataset.features = rows.into(); dataset.source = None; layer.source = None; layer.dataset = dataset; From ef933a7faf2e41b0c12268cbbfddf1801fd142be Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 11:36:13 -0600 Subject: [PATCH 3/7] fix(engine): honor field package limits and delivery --- crates/data/src/io.rs | 86 ++++++--- crates/engine/src/cmd/exports.rs | 10 +- crates/engine/src/cmd/field.rs | 293 +++++++++++++++++++++++++------ xtask/row-uses.txt | 2 +- 4 files changed, 307 insertions(+), 84 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c501e20b87..bcf44a7e53 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1066,7 +1066,7 @@ pub fn write_atomic_with>( write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result { let path = link_target(path)?; - atomic_write_at(&path, write) + atomic_write_at(path, write) } /// Atomically replaces an app-managed file, replacing a final symbolic link rather than @@ -1074,25 +1074,42 @@ pub fn write_atomic_with>( /// regular files keep their permissions; a replaced link uses a new file's permissions. pub fn replace_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { use std::io::Write; - atomic_write_at(path, |out| out.write_all(bytes)) + atomic_write_at(path.to_path_buf(), |out| out.write_all(bytes)) } -/// Stages content beside the chosen destination; errors and cancellation retain the old file. +/// Writes and syncs bytes beside the destination, preserving the destination until +/// [`StagedWrite::commit`] installs them. Dropping the result discards the staged file. +pub fn stage_atomic(path: &Path, bytes: &[u8]) -> std::io::Result { + use std::io::Write; + stage_at(link_target(path)?, |w| w.write_all(bytes)).map(|(staged, ())| staged) +} + +/// Stages and installs a write, retaining the old file on error or cancellation. fn atomic_write_at>( - path: &Path, + path: std::path::PathBuf, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result { + let (staged, value) = stage_at(path, write)?; + staged.commit()?; + Ok(value) +} + +/// Syncs the temporary file on the writing thread, so installation only needs a rename +/// and a directory sync. +fn stage_at>( + path: std::path::PathBuf, + write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, +) -> std::result::Result<(StagedWrite, T), E> { use std::io::Write; - let tmp = temp_beside(path)?; + let tmp = temp_beside(&path)?; // Opened before the guard, so a name already taken is never removed. let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?; - // Removes the file on an error and on a panic in `write` alike, unless it was moved into place. - let staged = Staged(&tmp); + let staged = StagedWrite { path, tmp: Some(tmp) }; // The new file takes the old one's mode before any content is written, so a private file // (0600) never becomes readable by others. On Windows a new file inherits its folder's access // rules, and copying a read-only flag would only make the rename fail. #[cfg(unix)] - match std::fs::symlink_metadata(path) { + match std::fs::symlink_metadata(&staged.path) { Ok(old) if !old.file_type().is_symlink() => { use std::os::unix::fs::PermissionsExt; let permissions = old.permissions(); @@ -1112,15 +1129,42 @@ fn atomic_write_at>( out.get_ref().sync_all()?; // Closed before the rename, including on Windows. drop(out); - // A cancel that came while it was written leaves the file there before as it was. This is - // the last look: the rename commits the file, and a Cancel after it finds it written. - if crate::progress::check().is_err() { - return Err(std::io::Error::other(DataError::Cancelled).into()); + Ok((staged, value)) +} + +/// An atomic write awaiting installation. An error or drop removes its temporary file. +pub struct StagedWrite { + path: std::path::PathBuf, + tmp: Option, +} + +impl StagedWrite { + /// The destination resolved at staging time, after following any symbolic links. + pub fn destination(&self) -> &Path { + &self.path + } + + /// Installs the staged file, checking Cancel just before the rename. The previous file + /// remains in place if installation fails. + pub fn commit(mut self) -> std::io::Result<()> { + if crate::progress::check().is_err() { + return Err(std::io::Error::other(DataError::Cancelled)); + } + if let Some(tmp) = &self.tmp { + std::fs::rename(tmp, &self.path)?; + self.tmp = None; + sync_folder(&self.path); + } + Ok(()) + } +} + +impl Drop for StagedWrite { + fn drop(&mut self) { + if let Some(tmp) = &self.tmp { + let _ = std::fs::remove_file(tmp); + } } - std::fs::rename(&tmp, path)?; - std::mem::forget(staged); - sync_folder(path); - Ok(value) } /// The file a write to `path` replaces: `path` itself, or, when it is a symbolic link, the file @@ -1149,16 +1193,6 @@ fn link_target(path: &Path) -> std::io::Result { /// How many symbolic links in a row [`link_target`] follows, as many as Linux does. const MAX_LINKS: usize = 40; -/// A file being written beside its destination: removed when dropped, as an export that -/// failed or panicked leaves it. A finished export forgets it once the file is renamed. -struct Staged<'a>(&'a Path); - -impl Drop for Staged<'_> { - fn drop(&mut self) { - let _ = std::fs::remove_file(self.0); - } -} - // --------------------------------------------------------------------------------------------- // GeoJSON (RFC 7946) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 0b3cc29d83..1f5b3a2697 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -39,8 +39,8 @@ impl Wrote { } } -/// What an export does to the session once its file is written, and adds to its answer; or the -/// failure it says once what came before it was said (a layout's warnings, then its error). +/// Completes an export on the live session and may update its answer. A field package's finalizer +/// checks that its home still accepts the new area or identity before installing the staged file. pub(crate) type Then = Box Result<(), String> + Send>; /// The writing of an export, its inputs read: it needs no session. @@ -300,9 +300,9 @@ impl ExportRun { self.started.clone() } - /// Writes the file, blocking until it's written; `control` stops it and counts its progress - /// (see [`rustgis_analysis::control`]). A cancelled export leaves no file, or the one there - /// before. + /// Writes the file, or stages it if installing it needs the live session. `control` stops the + /// work and counts its progress (see [`rustgis_analysis::control`]). A cancelled export leaves + /// no file, or the one there before. pub fn run(self, control: &std::sync::Arc) -> Result { let inputs = self.started.capture_inputs.then(rustgis_data::provenance::Capture::start); let ExportRun { name, work, started } = self; diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 256a3c31a3..2483b294ae 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -105,6 +105,13 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< use rustgis_data::progress; progress::check().map_err(|e| e.to_string())?; let mut losses = Vec::new(); + let mut archive_errors = Vec::new(); + // These used to be errors as soon as the sender hit them, even if the write later failed. + // Keep a second copy of the text for the recipient's manifest. + let mut archive_error = |s: &mut Session, text: String| { + s.notify(text.clone(), true); + archive_errors.push(text); + }; let legacy_return = if p.get("legacyReturn").is_some() { legacy_user(s)?; super::b(p, "legacyReturn").ok_or("legacyReturn must be true or false")? @@ -230,21 +237,24 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< )); } if !uploaded.is_empty() { - losses.push(format!( + archive_error( + s, + format!( "{} tile archive(s) added to this browser couldn't be put in the field package, as they live only in its memory: {}. Add them to the field from the file", uploaded.len(), uploaded.join(", ") - )); + ), + ); } if !unread.is_empty() { - losses.push(format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + archive_error(s, format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } // Coming back, the photos taken in the field go with their features. if coming_back { let photos = take_photos(&mut map, &mut budget); if !photos.unread.is_empty() { let unread = &photos.unread; - losses.push(format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + archive_error(s, format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } if !photos.not_pictures.is_empty() { let named = &photos.not_pictures; @@ -331,7 +341,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< .find(|saved| saved.name.eq_ignore_ascii_case(&area)) .ok_or("the offline area was not found")? .extent; - let available = project_room(&entries); + let available = project_room(companion_bytes(&entries)); copied = copy_streams(&mut map, extent, stream_budget(available), &mut losses)?; } project.maps = vec![map]; @@ -367,7 +377,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< "{area}: a RustGIS field package.\nOpen it with RustGIS on a phone or a computer (Open Project). Its basemaps are in {BASEMAPS}/.\n" ); entries.push(("README.txt".into(), readme.into_bytes())); - let room = project_room(&entries); + let companions = companion_bytes(&entries); let too_large = || "the field package would be too large: leave a tile archive or some data out".to_string(); if !copied.is_empty() { let map = project.maps.first().ok_or("the field package holds no map")?; @@ -378,10 +388,10 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< names.join(", ") )); } - let mut manifest = manifest_bytes(&losses)?; + let mut manifest = manifest_bytes(&archive_errors, &losses)?; progress::check().map_err(|e| e.to_string())?; let (mut text, mut report) = - crate::durable::output(&mut project, None, |p| crate::project::json_within(p, room.saturating_sub(manifest.len() as u64)))?; + crate::durable::output(&mut project, None, |p| crate::project::json_within(p, project_room(companions + manifest.len() as u64)))?; if text.is_none() && !copied.is_empty() { // Row storage and encoded JSON measure different things. The package's hard limit // also includes loaded layers and basemaps, so retry once without the streamed copies. @@ -400,9 +410,10 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< true } }); - manifest = manifest_bytes(&losses)?; - (text, report) = - crate::durable::output(&mut project, None, |p| crate::project::json_within(p, room.saturating_sub(manifest.len() as u64)))?; + manifest = manifest_bytes(&archive_errors, &losses)?; + (text, report) = crate::durable::output(&mut project, None, |p| { + crate::project::json_within(p, project_room(companions + manifest.len() as u64)) + })?; } let text = text.ok_or_else(too_large)?; progress::check().map_err(|e| e.to_string())?; @@ -417,9 +428,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< Ok((area, bytes)) } -/// Desktop export worker: build and write against a shared-row project snapshot, then install -/// the home identities and offline area only after a completed write. If the home project changed -/// meanwhile, leave its current state intact and tell the sender that the file must be remade. +/// Builds and stages the package against a shared-row project snapshot. Delivery checks +/// the live home state before installing the file and recording the new identities or area. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn export_work(s: &Session, p: &Value) -> Result { if p.get("legacyReturn").is_some() { @@ -439,20 +449,32 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result, Vec<_>) = copy.notices.into_iter().partition(|n| n.error); + let diagnostics = errors.into_iter().map(|n| (n.severity, n.text)).collect(); let next = copy.project; - // A newer home state may no longer accept the package (a concurrent sync can advance - // its generation). A return from the field owns its snapshot without any home update. - let outbound = next.offline_areas.iter().any(|saved| saved.name.eq_ignore_ascii_case(&area)); let change = (before != (next.origin_id.clone(), area_ids(&next))).then_some((next.origin_id, next.offline_areas)); - let then: super::exports::Then = Box::new(move |s, _| { + let control = rustgis_analysis::control::current(); + let then: super::exports::Then = Box::new(move |s, answer| { + let (result, file, notes, outbound) = staged?; if outbound && (s.opened != opened || s.state() != state) { return Err("the home project changed during packaging; make a new package before sending it to the field".into()); } + // Only a rename and directory sync run on the window thread. Cancel still + // applies until the rename, including when the worker has finished staging. + { + let _probe = rustgis_data::progress::install(control.map(|c| c as std::sync::Arc)); + not_the_project(s, file.destination())?; + file.commit().map_err(|e| format!("{path}: {e}"))?; + } if let Some((origin, areas)) = change { field_edit(s, "Prepare home project for field package", |s| { s.project.origin_id = origin; @@ -460,17 +482,21 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Vec<(String, String)> { project.offline_areas.iter().map(|a| (a.id.clone(), a.generation.clone())).collect() } -/// Bytes available for project JSON and notices once the companion files have been counted. -fn project_room(entries: &[(String, Vec)]) -> u64 { - crate::project::max_bytes().min(MOST_UNPACKED as u64).saturating_sub(entries.iter().map(|(_, b)| b.len() as u64).sum()) +fn companion_bytes(entries: &[(String, Vec)]) -> u64 { + entries.iter().map(|(_, bytes)| bytes.len() as u64).sum() +} + +/// The project JSON must fit its own limit and the space left in the unpacked ZIP. +fn project_room(companions: u64) -> u64 { + crate::project::max_bytes().min((MOST_UNPACKED as u64).saturating_sub(companions)) } /// Retain one map's worth of clipped streamed rows within a shared budget. Leave some of the /// package room for the JSON and plan for both encoders and the other data already in memory. fn stream_budget(room: u64) -> usize { - let memory = rustgis_data::memory::planned(8 << 20, 128 << 20, 4); + let memory = rustgis_data::memory::planned(8 << 20, 128 << 20, 1); memory.min(usize::try_from(room / 2).unwrap_or(usize::MAX)) } @@ -630,15 +660,16 @@ fn copy_stream( /// Only portable, redacted summaries go into the archive. Keep the list within the receiver's /// diagnostic limits even when a project has thousands of missing layers. -fn manifest_bytes(losses: &[String]) -> Result, String> { - if losses.is_empty() { +fn manifest_bytes(errors: &[String], losses: &[String]) -> Result, String> { + let total = errors.len() + losses.len(); + if total == 0 { return Ok(Vec::new()); } - let mut notes: Vec<_> = losses.iter().take(MAX_NOTICES).map(|s| Session::redacted(s).into_string()).collect(); + let mut notes: Vec<_> = errors.iter().chain(losses).take(MAX_NOTICES).map(|s| Session::redacted(s).into_string()).collect(); // JSON can grow when text has escapes. Drop the tail and count it if the byte limit is hit. loop { let mut candidate = notes.clone(); - let omitted = losses.len().saturating_sub(notes.len()); + let omitted = total - notes.len(); if omitted > 0 { candidate.push(format!("{omitted} more field package notice(s) were reported when the package was made")); } @@ -661,8 +692,9 @@ fn photos_field(layer: &rustgis_map::Layer) -> Option { fn rewrite_photos(map: &mut rustgis_map::Map, mut rewrite: impl FnMut(&str) -> String) { for l in map.layers.iter_mut().filter(|l| !l.is_raster()) { let Some(fi) = photos_field(l) else { continue }; - for f in &mut l.dataset.features { - let Some(rustgis_data::Value::Text(held)) = f.attrs.get(fi) else { continue }; + let features = &mut l.dataset.features; + for row in 0..features.len() { + let rustgis_data::Value::Text(held) = features.value(row, fi) else { continue }; // Only the paths rewritten change: the rest of the text stays as it was written, so // a feature isn't seen as edited for its spacing. let (mut out, mut last) = (String::new(), 0); @@ -679,9 +711,7 @@ fn rewrite_photos(map: &mut rustgis_map::Map, mut rewrite: impl FnMut(&str) -> S continue; } out.push_str(held.get(last..).unwrap_or_default()); - if let Some(slot) = f.attrs.get_mut(fi) { - *slot = rustgis_data::Value::Text(out); - } + let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); } } } @@ -970,16 +1000,28 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result { } keep }); - if !reference.is_empty() { - s.notify( - format!( - "Bring Back skipped {} layer(s) copied from sources read in place at home. Any edits to them stay in the field project: {}", - reference.len(), - reference.join(", ") - ), - false, - ); - } + let skipped_photos = if !reference.is_empty() && !photos.is_empty() { + let before = photos.len(); + // An entry may be shared by a kept feature and a dropped one. Only discard entries + // left without a reference among the layers passed to Sync. + let mut unused: std::collections::HashSet<_> = photos.iter().map(|(name, _)| name.clone()).collect(); + let prefix = format!("{PHOTOS}/"); + for layer in edited.layers.iter().filter(|l| !l.is_raster()) { + let Some(field) = photos_field(layer) else { continue }; + for value in layer.dataset.features.column(field) { + let rustgis_data::Value::Text(text) = value else { continue }; + for span in photo_paths(text) { + if let Some(name) = text.get(span).and_then(|path| path.strip_prefix(&prefix)) { + unused.remove(name); + } + } + } + } + photos.retain(|(name, _)| !unused.contains(name)); + before - photos.len() + } else { + 0 + }; // The photos, beside the project, and the features naming them there. let mut put = 0usize; let mut renamed = 0usize; @@ -1085,6 +1127,19 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result { summary.push_str(&format!(" ({renamed} under a new name: one of its name was there already)")); } } + if !reference.is_empty() { + s.notify( + format!( + "Bring Back skipped {} layer(s) copied from sources read in place at home. Any edits to them stay in the field project: {}", + reference.len(), + reference.join(", ") + ), + false, + ); + } + if skipped_photos > 0 { + s.notify(format!("Bring Back skipped {skipped_photos} photo(s) without a feature in the layers being brought back"), false); + } if strange > 0 { s.notify(format!("{strange} photo(s) in the field package weren't brought back: their names aren't plain file names"), true); } @@ -1317,6 +1372,121 @@ mod tests { Session::new(crate::sample::world_project()) } + #[test] + fn companions_do_not_reduce_the_project_json_limit() { + crate::project::with_max_bytes(1024, || { + assert_eq!(project_room(128), 1024); + assert_eq!(project_room(MOST_UNPACKED as u64 - 64), 64); + assert_eq!(project_room(MOST_UNPACKED as u64 + 1), 0); + }); + } + + #[cfg(unix)] + #[test] + fn unreadable_photo_is_a_sender_error_and_a_receiver_notice() { + let temp = Temp::new("unreadable-photo"); + let path = temp.path().join("unreadable.jpg"); + std::os::unix::fs::symlink("unreadable.jpg", &path).unwrap(); + let mut home = sample(); + let (_, bytes) = package(&mut home, &json!({"name":"Site", "extent":[-180, -85, 180, 85]})).unwrap(); + let dir = temp.path().join("out"); + let (text, _) = unpack_into(&bytes, &dir).unwrap(); + let mut crew = Session::new(project_in(&text, &dir).unwrap()); + crew.run("edit.addField", &json!({"layer":"Cities", "name":"photos", "type":"text"})).unwrap(); + crew.run("edit.setValue", &json!({"layer":"Cities", "row":0, "field":"photos", "value":path})).unwrap(); + + let mark = crew.notice_mark(); + let (_, bytes) = package(&mut crew, &Value::Null).unwrap(); + let expected = "1 photo(s) couldn't be put in the field package"; + assert_eq!(crew.notices_since(mark).iter().filter(|n| n.error && n.text.contains(expected)).count(), 1); + let (_, losses) = unpack_into(&bytes, &temp.path().join("back")).unwrap(); + assert!(losses.iter().any(|note| note.contains(expected))); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn stream_budget_is_in_bytes_on_a_constrained_host() { + const TEST: &str = "cmd::field::tests::stream_budget_is_in_bytes_on_a_constrained_host"; + const CHILD: &str = "RUSTGIS_TEST_FIELD_BUDGET"; + if std::env::var_os(CHILD).is_some() { + // A 256 MiB host gives the job 64 MiB, and the package has room for it. + assert_eq!(stream_budget(256 << 20), 64 << 20); + assert_eq!(stream_budget(32 << 20), 16 << 20); + return; + } + // The memory override is read once per process. Keep it out of concurrent tests. + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST]) + .env(CHILD, "1") + .env(rustgis_data::memory::OVERRIDE, (256 << 20).to_string()) + .output() + .unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stdout)); + assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed")); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn refused_field_export_leaves_the_destination_as_it_was() { + use crate::cmd::exports::{export_land, export_start}; + let temp = Temp::new("refused"); + let mut home = sample(); + for existing in [false, true] { + let path = temp.path().join(format!("{existing}.rgisfield")); + if existing { + std::fs::write(&path, b"previous package").unwrap(); + } + let params = json!({"path": path, "name": "Site", "extent": [-20, -40, 60, 40]}); + let run = export_start(&mut home, "offline.package", ¶ms).unwrap(); + let started = run.started(); + let wrote = run.run(&rustgis_analysis::control::Control::new()); + assert!(wrote.is_ok()); + home.run("map.rename", &json!({"name": format!("Changed {existing}")})).unwrap(); + let err = export_land(&mut home, started, wrote).unwrap_err(); + assert!(err.contains("the home project changed"), "{err}"); + assert!(home.project.offline_areas.is_empty()); + if existing { + assert_eq!(std::fs::read(&path).unwrap(), b"previous package"); + } else { + assert!(!path.exists()); + } + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), usize::from(existing)); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn archive_losses_are_sender_errors_and_receiver_notices() { + use crate::cmd::exports::{export_land, export_start}; + let temp = Temp::new("archive-loss"); + for (background, write_succeeds) in [(false, true), (false, false), (true, true), (true, false)] { + let mut home = sample(); + let missing = temp.path().join("missing.mbtiles"); + home.map_mut().tiles.push(TileLayer::new("Unread", TileKind::MbTiles, missing.display().to_string())); + home.map_mut().tiles.push(TileLayer::new("Uploaded", TileKind::MbTiles, format!("{}site.mbtiles", rustgis_map::tiles::UPLOAD))); + let path = if write_succeeds { temp.path().join("site.rgisfield") } else { temp.path().join("missing/site.rgisfield") }; + let mark = home.notice_mark(); + let params = json!({"path": path, "name": "Site", "extent": [-20, -40, 60, 40]}); + let result = if background { + let run = export_start(&mut home, "offline.package", ¶ms).unwrap(); + let started = run.started(); + export_land(&mut home, started, run.run(&rustgis_analysis::control::Control::new())) + } else { + home.run("offline.package", ¶ms) + }; + assert_eq!(result.is_ok(), write_succeeds, "{result:?}"); + for name in ["Unread", "Uploaded"] { + assert!(home.notices_since(mark).iter().any(|n| n.error && n.text.contains(name))); + } + if write_succeeds { + let (_, losses) = unpack_into(&std::fs::read(&path).unwrap(), &temp.path().join(format!("field-{background}"))).unwrap(); + for name in ["Unread", "Uploaded"] { + assert!(losses.iter().any(|n| n.contains(name))); + } + } + } + } + #[test] fn a_map_packaged_for_the_field_opens_with_its_basemap_and_comes_from_an_offline_area() { let temp = Temp::new("package"); @@ -1370,12 +1540,13 @@ mod tests { for x in [1.0, 10.0] { places.push(Some(rustgis_data::Geometry::Point(rustgis_data::Coord::new(x, 1.0))), vec![]); } - let id = seed.map_mut().add_dataset(places); + let id = seed.map_mut().add_dataset(places.clone()); seed.run("share.exportLayer", &json!({"layer": id, "path": source})).unwrap(); let mut home = Session::new(Project::default()); home.run("layer.addData", &json!({"name": "Streamed", "path": source, "layer": "Places", "stream": true})).unwrap(); assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); + home.map_mut().add_dataset(places); let mark = home.notice_mark(); let extent = rustgis_data::Extent::new(0.0, 0.0, 2.0, 2.0); let mut oversized = home.map().clone(); @@ -1409,12 +1580,30 @@ mod tests { std::fs::rename(&held, &source).unwrap(); let mut home = Session::new(Project::from_json(&home_text).unwrap()); crew.run("edit.addFeature", &json!({"layer":"Streamed", "geometry":{"type":"Point", "coordinates":[1.5, 1.5]}})).unwrap(); + let photo = temp.path().join("reference.jpg"); + let shared_photo = temp.path().join("shared.jpg"); + std::fs::write(&photo, b"reference photo").unwrap(); + std::fs::write(&shared_photo, b"shared photo").unwrap(); + crew.run("edit.addField", &json!({"layer": "Streamed", "name": "photos", "type": "text"})).unwrap(); + let named = format!("{}; {}", photo.display(), shared_photo.display()); + crew.run("edit.setValue", &json!({"layer": "Streamed", "row": 0, "field": "photos", "value": named})).unwrap(); + crew.run("edit.addField", &json!({"layer": "Places", "name": "photos", "type": "text"})).unwrap(); + crew.run("edit.setValue", &json!({"layer": "Places", "row": 0, "field": "photos", "value": shared_photo})).unwrap(); + home.path = Some(temp.path().join("home.rgis")); let (_, bytes) = package(&mut crew, &Value::Null).unwrap(); + assert!(rustgis_data::zip::read(&bytes).unwrap().iter().any(|(name, _)| name == "photos/reference.jpg")); + std::fs::remove_file(&photo).unwrap(); + std::fs::remove_file(&shared_photo).unwrap(); let returned = temp.path().join("returned.rgisfield"); std::fs::write(&returned, bytes).unwrap(); let mark = home.notice_mark(); let done = home.run("offline.bringBack", &json!({"path": returned})).unwrap(); assert_eq!(done["added"], 0); + assert_eq!(done["photos"], 1); + let photos = temp.path().join("Site photos"); + assert!(!photos.join("reference.jpg").exists()); + assert_eq!(std::fs::read(photos.join("shared.jpg")).unwrap(), b"shared photo"); + assert!(home.notices_since(mark).iter().any(|n| n.text.contains("Bring Back skipped 1 photo"))); assert!(home.notices_since(mark).iter().any(|n| n.text.contains("Bring Back skipped 1 layer"))); assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); } diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 322588ef3a..43118734be 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 833 +count = 831 From d544819d8cc9fe7078b3b0b2e20ff03b573cdf88 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 12:36:30 -0600 Subject: [PATCH 4/7] fix(engine): keep the authority check through a field package's commit The staged package's rename now runs under the progress carrier that checks the live authority as well as Cancel. The budget refusals say how to proceed, and the outside-area notice is given as a lower bound when rows couldn't be read, rather than dropped. --- crates/engine/src/cmd/field.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 2483b294ae..22301f70bc 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -401,7 +401,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< map.layers.retain(|l| { if copied.contains(&l.id) { losses.push(format!( - "{}: {} feature(s) in the offline area were left out because the field package would be too large", + "{}: {} feature(s) in the offline area were left out because the field package would be too large: make the offline area smaller, or filter the layer, then package again", l.name, l.dataset.features.len() )); @@ -471,7 +471,8 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result)); + // Cancel and the live authority check both apply until the rename. + let _probe = rustgis_analysis::control::install_progress(control); not_the_project(s, file.destination())?; file.commit().map_err(|e| format!("{path}: {e}"))?; } @@ -621,17 +622,20 @@ fn copy_stream( } if !fits { losses.push(format!( - "{}: {inside} feature(s) in the offline area were left out because the streamed layer exceeded the field package budget", + "{}: {inside} feature(s) in the offline area were left out because the streamed layer exceeded the field package budget: make the offline area smaller, or filter the layer, then package again", layer.name )); return Ok(None); } - // An indexed read can skip the rest of the file outright. Only report a total outside the - // area when the source knows its count and the traversal didn't encounter unreadable rows. - let outside = info.count.filter(|_| unread == 0).map_or(outside as u64, |total| total.saturating_sub(inside as u64)); + // An indexed read can skip the rest of the file outright, so the total outside the area comes + // from the source's count. With unreadable rows that count may or may not include them, so + // what remains is a lower bound, said as one. + let outside = + info.count.map_or(outside as u64, |total| total.saturating_sub(inside as u64).saturating_sub(unread as u64).max(outside as u64)); if outside > 0 { + let at_least = if unread > 0 { "at least " } else { "" }; losses.push(format!( - "{}: {outside} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package", + "{}: {at_least}{outside} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package", layer.name )); } From 6b000c25546a701154ef2223e23c77ac1275c8cc Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 17:06:37 -0600 Subject: [PATCH 5/7] fix(field): refuse stale streamed GeoJSON in packages --- crates/data/src/source/geojson.rs | 64 +++++++++++++++++++++++++------ crates/engine/src/cmd/field.rs | 43 +++++++++++++++++++-- 2 files changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 3b0f1af6c8..a65388b66d 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -7,7 +7,7 @@ //! way); a larger one is read through a buffer, so it's never held whole. Smaller files are loaded //! whole by `io::read_path`. -use std::fs::File; +use std::fs::{File, Metadata}; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; @@ -34,10 +34,42 @@ struct Place { len: u32, } +/// Metadata of the opened file, cheap to compare without reading the whole source again. +#[derive(PartialEq, Eq)] +struct FileVersion { + len: u64, + modified: Option, + // On Unix, also catch replacements and edits that preserve the modification time. + #[cfg(unix)] + identity_and_change: (u64, u64, i64, i64), +} + +impl FileVersion { + fn of(metadata: &Metadata) -> Self { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + Self { + len: metadata.len(), + modified: metadata.modified().ok(), + #[cfg(unix)] + identity_and_change: (metadata.dev(), metadata.ino(), metadata.ctime(), metadata.ctime_nsec()), + } + } + + /// Checks the same handle used for the scan or visit, including changes during the read. + fn check(&self, file: &File) -> Result<()> { + if *self != Self::of(&file.metadata()?) { + return Err(bad("the file changed on disk since it was opened. Reopen the layer and try again")); + } + Ok(()) + } +} + /// A GeoJSON FeatureCollection read in place. pub struct GeoJsonSource { info: SourceInfo, path: PathBuf, + version: FileVersion, places: Vec, /// Each feature's box in the file's own coordinates, rounded outward (NaN for a feature /// without geometry). @@ -145,9 +177,13 @@ impl GeoJsonSource { /// scan it, and a larger one through a buffer. pub(crate) fn open_with(path: &Path, name: &str, in_memory: u64) -> Result { use serde::de::DeserializeSeed; + let mut file = crate::provenance::open(path)?; + let version = FileVersion::of(&file.metadata()?); let mut scan = Scan::default(); - let rest = if std::fs::metadata(path)?.len() <= in_memory { - let text = crate::provenance::read_to_string(path)?; + let rest = if version.len <= in_memory { + let mut text = String::new(); + file.read_to_string(&mut text)?; + crate::provenance::buffer(path, &file, text.as_bytes()); // Its objects and vertices would all become a JSON tree, only to be refused below. if crate::cityjson::looks_like_cityjson(&text) { return Err(DataError::Unsupported("only GeoJSON FeatureCollections are read in place".into())); @@ -155,8 +191,8 @@ impl GeoJsonSource { crate::io::stream_features(&text, &mut InText { scan: &mut scan, start: text.as_ptr() as usize }).map_err(bad)? } else { let read = std::rc::Rc::new(std::cell::Cell::new(0u64)); - let file = Counting { inner: BufReader::with_capacity(BUFFER, crate::provenance::open(path)?), read: read.clone() }; - let mut de = serde_json::Deserializer::from_reader(file); + 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)?; // Only whitespace may follow, as when read whole. de.end().map_err(bad)?; @@ -176,7 +212,8 @@ impl GeoJsonSource { let mut failed = Vec::new(); let mut extent = scan.extent; if let Some(t) = reproject.transformer() { - let pass = convert_pass(path, &scan.places, t)?; + file.rewind()?; + 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); @@ -219,7 +256,8 @@ impl GeoJsonSource { info.drop_zm(Some(zm)); } let unreadable = scan.skipped; - Ok(GeoJsonSource { info, path: path.to_path_buf(), places: scan.places, boxes: scan.boxes, reproject, failed, unreadable }) + version.check(&file)?; + Ok(GeoJsonSource { info, path: path.to_path_buf(), version, places: scan.places, boxes: scan.boxes, reproject, failed, unreadable }) } /// The features a request matches, in file order: every one without an extent; otherwise @@ -266,11 +304,14 @@ impl FeatureSource for GeoJsonSource { } /// Visits the matching file records in order and retains only one batch of decoded rows. + /// A changed file invalidates the saved bounds and offsets, even for records the bounds + /// would skip. A successful visit uses the same file version as the index. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let req = Request { extent, limit: usize::MAX }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(&self.path)?); + self.version.check(f.get_ref())?; let mut pos = 0; let mut buf = Vec::new(); let mut batch = Batch { complete: true, ..Batch::default() }; @@ -290,6 +331,7 @@ impl FeatureSource for GeoJsonSource { } } chunks.flush()?; + self.version.check(f.get_ref())?; Ok(batch) } @@ -379,7 +421,7 @@ impl GeoJsonSource { /// The feature at `place`, read through `f` (at `pos`, which is kept up to date): `None` when the /// file has changed since it was opened. -fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec, place: &Place) -> Option { +fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec, place: &Place) -> Option { // Ahead and near: through the buffer; otherwise a seek. let read = (|| -> std::io::Result<()> { match i64::try_from(place.offset.wrapping_sub(*pos)) { @@ -414,8 +456,8 @@ struct Pass { } /// A second pass over the file, made only for a declared coordinate system. -fn convert_pass(path: &Path, places: &[Place], t: &crate::raster::Transformer) -> Result { - let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(path)?); +fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> 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 }; for (i, place) in places.iter().enumerate() { @@ -434,7 +476,7 @@ fn convert_pass(path: &Path, places: &[Place], t: &crate::raster::Transformer) - } } } - Ok(pass) + pass } /// A reader counting the bytes read through it, for features' places in the file. The JSON reader diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 22301f70bc..026437bd49 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -401,7 +401,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< map.layers.retain(|l| { if copied.contains(&l.id) { losses.push(format!( - "{}: {} feature(s) in the offline area were left out because the field package would be too large: make the offline area smaller, or filter the layer, then package again", + "{}: {} feature(s) in the offline area were left out because the field package would be too large: package a smaller area, or save the rows you need as a separate layer (for example, export the filtered rows) and package that layer", l.name, l.dataset.features.len() )); @@ -548,7 +548,7 @@ fn copy_streams( Ok(None) => omitted.push(layer.id), Err(error) => { rustgis_data::progress::check().map_err(|e| e.to_string())?; - losses.push(format!("{}: streamed layer couldn't be put in the field package ({error})", layer.name)); + losses.push(format!("1 streamed layer was left out of the field package: {} ({error})", layer.name)); omitted.push(layer.id); } } @@ -622,7 +622,7 @@ fn copy_stream( } if !fits { losses.push(format!( - "{}: {inside} feature(s) in the offline area were left out because the streamed layer exceeded the field package budget: make the offline area smaller, or filter the layer, then package again", + "{}: {inside} feature(s) in the offline area were left out because the streamed layer exceeded the field package budget: package a smaller area, or save the rows you need as a separate layer (for example, export the filtered rows) and package that layer", layer.name )); return Ok(None); @@ -1612,6 +1612,43 @@ mod tests { assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); } + /// A same-length rewrite can move a point into the area without invalidating its byte offset. + #[test] + fn field_package_reports_a_streamed_geojson_changed_since_opening() { + let temp = Temp::new("changed-geojson"); + let source = temp.path().join("places.geojson"); + let write_point = |x| { + let data = json!({ + "type": "FeatureCollection", + "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [x, 1]}}], + }); + std::fs::write(&source, data.to_string()).unwrap(); + }; + write_point(9); + let mut home = Session::new(Project::default()); + home.run("layer.addData", &json!({"name": "Places", "path": source, "stream": true})).unwrap(); + assert!(home.map().layer_by_name("Places").unwrap().is_streamed()); + + let modified = std::fs::metadata(&source).unwrap().modified().unwrap(); + write_point(1); + // Give the rewrite a distinct timestamp even on filesystems with coarse timestamps. + std::fs::File::options().write(true).open(&source).unwrap().set_modified(modified + std::time::Duration::from_secs(4)).unwrap(); + + let mark = home.notice_mark(); + let (_, bytes) = package(&mut home, &json!({"name": "Site", "extent": [0, 0, 2, 2]})).unwrap(); + let into = temp.path().join("unpacked"); + let (text, notices) = unpack_into(&bytes, &into).unwrap(); + let project = project_in(&text, &into).unwrap(); + assert!(project.maps[0].layer_by_name("Places").is_none(), "the stale index included an empty reference layer"); + let notice = |text: &str| { + text.contains("Places") + && text.contains("1 streamed layer") + && text.contains("changed on disk since it was opened. Reopen the layer") + }; + assert!(notices.iter().any(|n| notice(n)), "{notices:?}"); + assert!(home.notices_since(mark).iter().any(|n| notice(&n.text))); + } + #[test] fn a_field_package_holds_only_its_map_and_a_basemap_of_any_name_is_read() { let temp = Temp::new("only"); From dac5c82bf8e6df263206efc34c9cd18d89acaa48 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 18:00:02 -0600 Subject: [PATCH 6/7] fix(engine): say a field package was written when home can't record it If the home change is refused after the package is renamed into place, the error names the written file and says to make a new package. --- crates/engine/src/cmd/field.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 8f81763fc5..c6a495dfeb 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -481,6 +481,9 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Date: Fri, 20 Nov 2026 18:29:04 -0600 Subject: [PATCH 7/7] fix(engine): don't subtract rows refused at open twice from the outside count A source's count already leaves out rows it refused when it opened (GeoJSON's reprojection failures), so only rows skipped while reading come off it, and only those make the count a lower bound. --- crates/engine/src/cmd/field.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index c6a495dfeb..15ae01d84a 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -631,12 +631,14 @@ fn copy_stream( return Ok(None); } // An indexed read can skip the rest of the file outright, so the total outside the area comes - // from the source's count. With unreadable rows that count may or may not include them, so - // what remains is a lower bound, said as one. + // from the source's count. Rows a source refused when it opened are left out of that count + // (GeoJSON's reprojection failures, for one) and said above; rows skipped while reading may + // not be, so with any of those the rest is a lower bound, said as one. + let skipped = batch.skipped as u64; let outside = - info.count.map_or(outside as u64, |total| total.saturating_sub(inside as u64).saturating_sub(unread as u64).max(outside as u64)); + info.count.map_or(outside as u64, |total| total.saturating_sub(inside as u64).saturating_sub(skipped).max(outside as u64)); if outside > 0 { - let at_least = if unread > 0 { "at least " } else { "" }; + let at_least = if skipped > 0 { "at least " } else { "" }; losses.push(format!( "{}: {at_least}{outside} feature(s) outside the offline area's extent, or without a shape, stayed out of the field package", layer.name