diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 061311ccfc..b165cc8af6 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -628,7 +628,10 @@ fn use_picker( answer_ended(&answers, ended); })); let saver = phone.clone(); - app.services.download = Some(Box::new(move |name: &str, bytes: Vec| saver.save_file(name, bytes, false))); + // The buttons' downloads are the only holder of their bytes, so nothing is copied here. + app.services.download = Some(Box::new(move |name: &str, bytes: std::sync::Arc>| { + saver.save_file(name, std::sync::Arc::unwrap_or_clone(bytes), false) + })); let saver = phone.clone(); app.services.save_project = Some(Box::new(move |name: &str, bytes: Vec, document: Option<&str>| match document { Some(document) => saver.write_back(document, name, bytes), diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index d28db0de7b..5185b55eac 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1440,7 +1440,7 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e }); })), open_options: None, - download: Some(Box::new(|name: &str, bytes: Vec| download(name, &bytes))), + download: Some(Box::new(|name: &str, bytes: std::sync::Arc>| download(name, &bytes))), inbox: Some(inbox), geolibre_manifests: Some(Box::new(move |slot| crate::geolibre::manifests(slot, gl_list_ctx.clone()))), geolibre_run: Some(Box::new(move |job, slot| crate::geolibre::run(job, slot, gl_run_ctx.clone()))), diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs new file mode 100644 index 0000000000..98435d5368 --- /dev/null +++ b/crates/data/src/capped.rs @@ -0,0 +1,393 @@ +//! A file made in memory under a size limit, such as a download in the browser: its writer fails +//! as soon as the file would pass the limit, so it is never held larger. + +use std::io::{Error, ErrorKind, Seek, SeekFrom, Write}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use crate::{DataError, Result}; + +/// The most bytes the buffers a file is made in may hold in all (a Shapefile's parts share one). +#[derive(Debug)] +pub struct Limit { + max: usize, + held: AtomicUsize, + passed: AtomicBool, +} + +impl Limit { + /// A limit of `max` bytes. + pub const fn new(max: usize) -> Self { + Limit { max, held: AtomicUsize::new(0), passed: AtomicBool::new(false) } + } + + /// No limit but memory: for a file that is to be written. + pub const fn none() -> Self { + Limit::new(usize::MAX) + } + + /// Whether a write was refused for passing the limit. + pub fn passed(&self) -> bool { + self.passed.load(Ordering::Relaxed) + } + + /// An empty buffer counted against this limit. + pub(crate) fn buffer(&self) -> Buffer<'_> { + Buffer { file: Vec::new(), at: 0, limit: self, charged: 0 } + } + + /// Counts `bytes` held apart from the buffers (files made in them and taken out, while an + /// archive of them is made) against the limit until the guard is dropped; refused past it. + pub(crate) fn hold(&self, bytes: usize) -> Result> { + self.take(bytes).map_err(|_| DataError::Format(format!("the file passes the {} bytes it may come to", self.max)))?; + Ok(Held { limit: self, bytes }) + } + + /// `made`, or an error once a write was refused: a writer may drop that write's error (some + /// finish their file as they are dropped), so this, not its result, says whether the file is + /// whole. + pub(crate) fn whole(&self, made: Result) -> Result { + if self.passed() { + return Err(DataError::Format(format!("the file passes the {} bytes it may come to", self.max))); + } + made + } + + /// Counts `n` more bytes held, refusing them past the limit, and gives how many are held. + fn take(&self, n: usize) -> std::io::Result { + // In one update, so the count never holds a total past the limit, even for a moment + // another buffer on the same limit could see. + let grown = |held: usize| held.checked_add(n).filter(|total| *total <= self.max); + match self.held.try_update(Ordering::Relaxed, Ordering::Relaxed, grown) { + Ok(before) => Ok(before + n), + Err(_) => { + self.passed.store(true, Ordering::Relaxed); + Err(Error::other("the file passes the size it may come to")) + } + } + } +} + +/// Bytes counted against a [`Limit`] while they are held ([`Limit::hold`]). +pub(crate) struct Held<'a> { + limit: &'a Limit, + bytes: usize, +} + +impl Drop for Held<'_> { + fn drop(&mut self) { + self.limit.held.fetch_sub(self.bytes, Ordering::Relaxed); + } +} + +/// A file made in memory within a [`Limit`], written and sought as a file is. +#[derive(Debug)] +pub(crate) struct Buffer<'a> { + file: Vec, + /// Where the next write goes. + at: u64, + limit: &'a Limit, + /// The allocation counted against the limit: what the system holds, not the file's length. + charged: usize, +} + +impl Buffer<'_> { + /// The file made, its spare room given back, no longer counted against the limit. + pub(crate) fn into_inner(mut self) -> Vec { + let mut file = std::mem::take(&mut self.file); + file.shrink_to_fit(); + self.release(); + file + } + + /// Stops counting the buffer's allocation against the limit, once. + fn release(&mut self) { + self.limit.held.fetch_sub(std::mem::take(&mut self.charged), Ordering::Relaxed); + } + + /// Makes room for the file to reach `end` bytes, within the limit, which counts the + /// allocation (its capacity, not the file's length): it doubles, but never past what the + /// limit leaves, and a refusal by the system is an error. + fn reserve(&mut self, end: usize) -> std::io::Result<()> { + let old = self.file.capacity(); + if end <= old { + return Ok(()); + } + let left = self.limit.max.saturating_sub(self.limit.held.load(Ordering::Relaxed)); + // At least `end`; past what is left only when `end` is, which the limit then refuses. + let room = old.saturating_mul(2).max(end).min(old.saturating_add(left)).max(end); + self.limit.take(room - old)?; + self.charged += room - old; + // For bytes, `try_reserve_exact` allocates what is asked. + self.file.try_reserve_exact(room - self.file.len()).map_err(|_| Error::from(ErrorKind::OutOfMemory))?; + Ok(()) + } +} + +impl Drop for Buffer<'_> { + /// A buffer dropped with its file, as after a refused write or a writer's error, gives back + /// what it held. + fn drop(&mut self) { + self.release(); + } +} + +impl Write for Buffer<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let too_far = || Error::from(ErrorKind::InvalidInput); + let at = usize::try_from(self.at).map_err(|_| too_far())?; + let end = at.checked_add(bytes.len()).ok_or_else(too_far)?; + if bytes.is_empty() { + return Ok(0); + } + self.reserve(end)?; + if at == self.file.len() { + self.file.extend_from_slice(bytes); + } else { + // Over what is there, or past the end, the gap left zero as in a file. + if end > self.file.len() { + self.file.resize(end, 0); + } + self.file.get_mut(at..end).ok_or_else(too_far)?.copy_from_slice(bytes); + } + self.at = end as u64; + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Seek for Buffer<'_> { + fn seek(&mut self, to: SeekFrom) -> std::io::Result { + let at = match to { + SeekFrom::Start(at) => Some(at), + SeekFrom::End(by) => (self.file.len() as u64).checked_add_signed(by), + SeekFrom::Current(by) => self.at.checked_add_signed(by), + }; + self.at = at.ok_or_else(|| Error::from(ErrorKind::InvalidInput))?; + Ok(self.at) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::AtomicU64; + + use super::*; + use crate::raster::{ColorHint, Crs, GeoTransform, Raster, cogwrite, geotiff}; + use crate::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + + /// A request past the limit, however large, is refused without changing what is counted. + #[test] + fn a_request_past_the_limit_leaves_the_count_as_it_was() { + let limit = Limit::new(10); + limit.take(8).unwrap(); + assert!(limit.take(usize::MAX - 7).is_err()); + assert_eq!(limit.held.load(Ordering::Relaxed), 8); + assert_eq!(limit.take(2).unwrap(), 10); + assert!(limit.take(1).is_err()); + } + + /// A buffer holds what a file would after seeks and gaps, never allocates past its limit, and + /// once a write is refused the limit says so, whatever the writer made of the refusal. + #[test] + fn a_buffer_is_a_file_that_stops_at_its_limit() { + let limit = Limit::new(10); + let mut b = limit.buffer(); + b.write_all(b"abcd").unwrap(); + b.seek(SeekFrom::Start(1)).unwrap(); + b.write_all(b"XY").unwrap(); + b.seek(SeekFrom::End(2)).unwrap(); + b.write_all(b"z").unwrap(); + assert_eq!(b.file, b"aXYd\0\0z"); + // Another buffer shares what is left of the limit, which counts allocations: the first + // holds 8 bytes of room for its 7. + assert_eq!(b.file.capacity(), 8); + let mut other = limit.buffer(); + other.write_all(b"12").unwrap(); + assert!(!limit.passed()); + assert!(other.write_all(b"3").is_err()); + assert!(limit.passed() && b.file.capacity() <= 10, "{}", b.file.capacity()); + let e = limit.whole(Ok(())).unwrap_err().to_string(); + assert!(e.contains("passes the 10 bytes"), "{e}"); + assert!(b.seek(SeekFrom::Current(-100)).is_err()); + let limit = Limit::new(1000); + let mut b = limit.buffer(); + for _ in 0..100 { + b.write_all(b"ten bytes.").unwrap(); + assert!(b.file.capacity() <= 1000, "{}", b.file.capacity()); + } + assert_eq!(b.into_inner().len(), 1000); + limit.buffer().write_all(&[0; 1000]).unwrap(); + assert!(!limit.passed(), "a file handed over is no longer counted"); + // Buffers sharing a limit are held to it by what they allocate, not by their lengths, + // and a file handed on keeps no spare room. + let limit = Limit::new(1000); + let mut parts = [limit.buffer(), limit.buffer(), limit.buffer()]; + let mut refused = false; + for round in 0..200 { + for i in 0..3 { + if let Some(part) = parts.get_mut(i) { + refused |= part.write_all(&[round as u8; 7]).is_err(); + } + let allocated: usize = parts.iter().map(|p| p.file.capacity()).sum(); + assert!(allocated <= 1000, "{allocated} bytes allocated"); + } + } + assert!(refused && limit.passed()); + let [first, ..] = parts; + let file = first.into_inner(); + assert_eq!(file.capacity(), file.len()); + } + + /// Counts the items a writer says it has done. + #[derive(Default)] + struct Done(AtomicU64); + + impl crate::progress::Probe for Done { + fn cancelled(&self) -> bool { + false + } + fn begin(&self, _: u64) {} + fn advance(&self, n: u64) { + self.0.fetch_add(n, Ordering::Relaxed); + } + } + + /// Each vector format a download is made in stops within the first features that pass the + /// limit, and under it gives the bytes the writer without one gives. + #[test] + fn every_download_format_stops_at_the_limit() { + const ROWS: u64 = 5_000; + let fields = vec![Field::new("name", FieldType::Text)]; + let mut ds = Dataset::new("Places", GeometryType::Point, fields); + for i in 0..ROWS { + let at = crate::Coord::new((i % 360) as f64 - 180.0, (i % 170) as f64 - 85.0); + ds.push(Some(Geometry::Point(at)), vec![Value::Text(format!("place {i}"))]); + } + let formats = ["geojson", "csv", "kml", "kmz", "gpx", "shp", "parquet"]; + let whole = |ext: &str, limit: &Limit| crate::io::write_bytes_noted_within(&ds, ext, Crs::LonLat, "out", limit).map(|w| w.0); + let text = |format: &str, limit: &Limit| crate::io::text_bytes_within(&ds, format, Some(0), limit); + let check = |name: &str, early: bool, make: &dyn Fn(&Limit) -> Result>| { + let unlimited = make(&Limit::none()).unwrap(); + assert_eq!(make(&Limit::new(1 << 24)).unwrap(), unlimited, "{name}"); + let done = Arc::new(Done::default()); + let _probe = crate::progress::install(Some(done.clone())); + let limit = Limit::new(200); + assert!(make(&limit).is_err() && limit.passed(), "{name}"); + let done = done.0.load(Ordering::Relaxed); + // A GeoParquet writes a group of rows at a time. + assert!(!early || done < ROWS / 2, "{name}: {done} of {ROWS} features before it stopped"); + }; + for ext in formats { + check(ext, ext != "parquet", &|limit| whole(ext, limit)); + } + for format in ["geojson", "csv", "kml", "gpx", "wkt"] { + check(format, true, &|limit| text(format, limit)); + } + // A KMZ and a zipped Shapefile are held to the limit before they are zipped, though their + // zips would fit. + for (ext, parts) in [("kmz", &["kml"][..]), ("shp", &["shp", "shx", "dbf"])] { + let zip = whole(ext, &Limit::none()).unwrap(); + let counted = |name: &str| parts.iter().any(|p| name.ends_with(p)); + let unzipped: usize = crate::zip::read(&zip).unwrap().iter().filter(|e| counted(&e.0)).map(|e| e.1.len()).sum(); + assert!(zip.len() < unzipped - 1, "{ext}"); + assert!(whole(ext, &Limit::new(unzipped - 1)).is_err(), "{ext}"); + // The parts stay counted while the archive is made, so both must fit: with room for + // half the archive past them it is refused, with room to spare it is the same zip. + let all: usize = crate::zip::read(&zip).unwrap().iter().map(|e| e.1.len()).sum(); + assert!(whole(ext, &Limit::new(all + zip.len() / 2)).is_err(), "{ext}: parts and archive past the limit"); + assert_eq!(whole(ext, &Limit::new(2 * (all + zip.len()))).unwrap(), zip, "{ext}"); + } + } + + /// A [`Buffer`] that notes the largest piece offered to it. + struct Pieces<'a> { + to: Buffer<'a>, + largest: usize, + } + + impl Write for Pieces<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.largest = self.largest.max(bytes.len()); + self.to.write(bytes) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// A buffer dropped without being handed over, as a refused write or a writer's error leaves + /// one, no longer counts against the limit, and a file handed over is released only once. + #[test] + fn a_dropped_buffer_gives_back_what_it_held() { + let limit = Limit::new(10); + let mut refused = limit.buffer(); + refused.write_all(b"12345678").unwrap(); + assert!(refused.write_all(b"abc").is_err() && limit.passed()); + drop(refused); + let mut next = limit.buffer(); + next.write_all(&[7; 10]).unwrap(); + assert!(limit.buffer().write_all(b"1").is_err(), "the buffer held is still counted"); + assert_eq!(next.into_inner(), [7; 10]); + assert_eq!(limit.held.load(Ordering::Relaxed), 0); + } + + /// One feature whose geometry text alone passes the limit: GeoJSON, KML, GPX and WKT hand it + /// over a piece at a time, so it is refused at the limit without ever being made whole. + #[test] + fn one_large_geometry_stops_at_the_limit_without_its_text_made_whole() { + const MAX: usize = 10_000; + let points: Vec = (0..20_000).map(|i| crate::Coord::new(f64::from(i % 360) - 180.0, 1.5)).collect(); + for g in [Geometry::MultiPoint(points.clone()), Geometry::Line(vec![points.clone()]), Geometry::Polygon(vec![vec![points]])] { + let mut ds = Dataset::new("Coast", GeometryType::Polyline, vec![]); + ds.push(Some(g), vec![]); + for format in ["geojson", "kml", "gpx", "wkt"] { + let limit = Limit::new(MAX); + let mut out = Pieces { to: limit.buffer(), largest: 0 }; + let made = match format { + // Without the buffering `write_geojson` adds, to see each piece. + "geojson" => crate::io::GeoJsonWriter::new(&mut out, &ds.name, &ds.fields) + .and_then(|mut w| w.write(&ds.features).and_then(|()| w.finish().map(drop))), + "kml" => crate::interop::write_kml(&ds, None, &mut out), + "gpx" => crate::interop::write_gpx(&ds, None, &mut out), + _ => crate::interop::write_wkt_csv(&ds, &mut out), + }; + // No fixed text of these documents is as long as this. + assert!(out.largest < 200, "{format}: a piece of {} bytes", out.largest); + assert!(out.to.file.capacity() <= MAX, "{format}: {} bytes held", out.to.file.capacity()); + let e = limit.whole(made).unwrap_err().to_string(); + assert!(limit.passed() && e.contains("passes the 10000 bytes"), "{format}: {e}"); + } + } + } + + /// A GeoTIFF and a cloud-optimised one stop at the limit, and under it are unchanged. + #[test] + fn a_geotiff_download_stops_at_the_limit() { + let transform = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 0.001, pixel_height: -0.001 }; + let cells: Vec = (0..1_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 8) as f32).collect(); + let r = Raster::new("r", 1000, 1000, vec![cells], transform, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + for cog in [false, true] { + let make = |limit: &Limit| { + if cog { + cogwrite::write_with_info_within(&r, 0, limit).map(|(bytes, _)| bytes) + } else { + geotiff::write_within(&r, 0, limit) + } + }; + let unlimited = make(&Limit::none()).unwrap(); + assert_eq!(make(&Limit::new(unlimited.len())).unwrap(), unlimited, "cog {cog}"); + let done = Arc::new(Done::default()); + let _probe = crate::progress::install(Some(done.clone())); + let limit = Limit::new(1000); + assert!(make(&limit).is_err() && limit.passed(), "cog {cog}"); + // At the first piece of the image, of the four or more. + let done = done.0.load(Ordering::Relaxed); + assert!(done <= 1, "cog {cog}: {done} pieces"); + } + } +} diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 646dac96ca..76802e85c7 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -1,6 +1,7 @@ -//! Writers for exchange formats: KML, GPX and CSV with WKT geometry. +//! Writers for exchange formats: KML, GPX and CSV with WKT geometry. Geometry text goes to the +//! output a coordinate at a time, so a large feature's is never held whole. -use std::fmt::Write as _; +use std::io::Write; use rustgis_geom::Coord; @@ -36,51 +37,86 @@ fn feature_place(layer: &str, feature: u64, what: &str) -> String { format!("{layer}, feature id {feature}, {what}") } -fn coords(pts: &[Coord]) -> String { - pts.iter().map(|c| format!("{},{}", c.x, c.y)).collect::>().join(" ") +/// KML coordinate tuples, space-separated. +fn write_kml_coords(out: &mut impl Write, pts: &[Coord]) -> std::io::Result<()> { + for (i, c) in pts.iter().enumerate() { + if i > 0 { + out.write_all(b" ")?; + } + write!(out, "{},{}", c.x, c.y)?; + } + Ok(()) +} + +/// A KML point. +fn write_kml_point(out: &mut impl Write, c: &Coord) -> std::io::Result<()> { + write!(out, "{},{}", c.x, c.y) } -fn kml_geometry(g: &Geometry) -> String { +/// A geometry as KML; one of other than a single part is a `MultiGeometry`. +fn write_kml_geometry(out: &mut impl Write, g: &Geometry) -> std::io::Result<()> { + let multi = match g { + Geometry::Point(_) => false, + Geometry::MultiPoint(_) => true, + Geometry::Line(parts) => parts.len() != 1, + Geometry::Polygon(polys) => polys.len() != 1, + }; + if multi { + out.write_all(b"")?; + } match g { - Geometry::Point(c) => format!("{},{}", c.x, c.y), + Geometry::Point(c) => write_kml_point(out, c)?, Geometry::MultiPoint(v) => { - format!("{}", v.iter().map(|c| kml_geometry(&Geometry::Point(*c))).collect::()) + for c in v { + write_kml_point(out, c)?; + } } Geometry::Line(parts) => { - let ls: String = parts.iter().map(|p| format!("{}", coords(p))).collect(); - if parts.len() == 1 { ls } else { format!("{ls}") } + for p in parts { + out.write_all(b"")?; + write_kml_coords(out, p)?; + out.write_all(b"")?; + } } Geometry::Polygon(polys) => { - let ps: String = polys - .iter() - .map(|rings| { - let mut it = rings.iter(); - let outer = it - .next() - .map(|r| { - format!("{}", coords(r)) - }) - .unwrap_or_default(); - let inner: String = it - .map(|r| { - format!("{}", coords(r)) - }) - .collect(); - format!("{outer}{inner}") - }) - .collect(); - if polys.len() == 1 { ps } else { format!("{ps}") } + for rings in polys { + out.write_all(b"")?; + for (i, ring) in rings.iter().enumerate() { + let side = if i == 0 { "outerBoundaryIs" } else { "innerBoundaryIs" }; + write!(out, "<{side}>")?; + write_kml_coords(out, ring)?; + write!(out, "")?; + } + out.write_all(b"")?; + } } } + if multi { + out.write_all(b"")?; + } + Ok(()) } /// A KML document, one placemark per feature, named by `name_field` and with every attribute. /// A cancelled run ([`crate::progress`]) stops it with [`crate::DataError::Cancelled`]. pub fn to_kml(ds: &Dataset, name_field: Option) -> crate::Result { - let mut out = format!( + let mut out = Vec::new(); + write_kml(ds, name_field, &mut out)?; + text(out) +} + +/// What a writer of text made, as a string. +fn text(out: Vec) -> crate::Result { + String::from_utf8(out).map_err(|e| crate::DataError::Format(e.to_string())) +} + +/// [`to_kml`]'s document, written to `out` as it is made. +pub(crate) fn write_kml(ds: &Dataset, name_field: Option, out: &mut impl Write) -> crate::Result<()> { + write!( + out, "\n{}\n", xml(&ds.name, "KML", || "layer name".to_string())? - ); + )?; // KML's description is text. Other types and differently-cased columns stay in // ExtendedData, where the reader preserves their values and reports name collisions. let description = ds.fields.iter().position(|f| f.name == "description" && f.ty == crate::FieldType::Text); @@ -114,137 +150,187 @@ pub fn to_kml(ds: &Dataset, name_field: Option) -> crate::Result Ok(format!("{value}")) }) .collect::>()?; - out.push_str(&format!( - "{}{description}{data}{}\n", - xml(&name, "KML", || feature_place(&ds.name, f.id, "name"))?, - kml_geometry(g) - )); + write!( + out, + "{}{description}{data}", + xml(&name, "KML", || feature_place(&ds.name, f.id, "name"))? + )?; + write_kml_geometry(out, g)?; + out.write_all(b"\n")?; } - out.push_str("\n"); - Ok(out) + out.write_all(b"\n")?; + Ok(()) +} + +/// A GPX track segment of `pts`. +fn write_gpx_segment(out: &mut impl Write, pts: &[Coord]) -> std::io::Result<()> { + out.write_all(b"")?; + for c in pts { + write!(out, "", c.y, c.x)?; + } + out.write_all(b"") } /// A GPX file: points become waypoints, lines tracks (polygon outlines too). /// A cancelled run ([`crate::progress`]) stops it with [`crate::DataError::Cancelled`]. pub fn to_gpx(ds: &Dataset, name_field: Option) -> crate::Result { - let mut out = String::from( - "\n\n", - ); + let mut out = Vec::new(); + write_gpx(ds, name_field, &mut out)?; + text(out) +} + +/// [`to_gpx`]'s document, written to `out` as it is made: GPX holds its waypoints before its +/// tracks, so the features are gone through for each, and no track waits in memory. +pub(crate) fn write_gpx(ds: &Dataset, name_field: Option, out: &mut impl Write) -> crate::Result<()> { + out.write_all( + b"\n\n", + )?; let pt = |c: &Coord| format!("lat=\"{}\" lon=\"{}\"", c.y, c.x); - let mut tracks = String::new(); - for (r, f) in ds.features.iter().enumerate() { - crate::progress::step(1)?; - let Some(g) = &f.geometry else { continue }; - let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string()); - let name = xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?; - match g { - Geometry::Point(c) => out.push_str(&format!("{name}\n", pt(c))), - Geometry::MultiPoint(v) => v.iter().for_each(|c| out.push_str(&format!("{name}\n", pt(c)))), - Geometry::Line(parts) => { - let segs: String = parts - .iter() - .map(|p| format!("{}", p.iter().map(|c| format!("", pt(c))).collect::())) - .collect(); - tracks.push_str(&format!("{name}{segs}\n")); + for tracks in [false, true] { + for (r, f) in ds.features.iter().enumerate() { + // Each feature counts once, in the first pass. + if tracks { + crate::progress::check()?; + } else { + crate::progress::step(1)?; } - Geometry::Polygon(polys) => { - let segs: String = polys - .iter() - .filter_map(|r| r.first()) - .map(|p| format!("{}", p.iter().map(|c| format!("", pt(c))).collect::())) - .collect(); - tracks.push_str(&format!("{name}{segs}\n")); + let Some(g) = &f.geometry else { continue }; + // Waypoints in the first pass, tracks in the second: a feature the pass doesn't write + // costs it no name. + let written = match g { + Geometry::Point(_) | Geometry::MultiPoint(_) => !tracks, + Geometry::Line(_) | Geometry::Polygon(_) => tracks, + }; + if !written { + continue; + } + let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string()); + let name = xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?; + match g { + Geometry::Point(c) if !tracks => writeln!(out, "{name}", pt(c))?, + Geometry::MultiPoint(v) if !tracks => { + for c in v { + writeln!(out, "{name}", pt(c))?; + } + } + Geometry::Line(parts) if tracks => { + write!(out, "{name}")?; + for p in parts { + write_gpx_segment(out, p)?; + } + out.write_all(b"\n")?; + } + Geometry::Polygon(polys) if tracks => { + write!(out, "{name}")?; + for ring in polys.iter().filter_map(|r| r.first()) { + write_gpx_segment(out, ring)?; + } + out.write_all(b"\n")?; + } + _ => {} } } } - out.push_str(&tracks); - out.push_str("\n"); - Ok(out) + out.write_all(b"\n")?; + Ok(()) } /// Well-known text for a geometry. pub fn wkt(g: &Geometry) -> String { - fn coord(out: &mut String, p: &Coord) { - let _ = write!(out, "{} {}", p.x, p.y); + let mut out = Vec::new(); + // A `Vec` takes every write, and the text is ASCII. + let _ = write_wkt(&mut out, g); + text(out).unwrap_or_default() +} + +/// [`wkt`]'s text, written to `out`. +fn write_wkt(out: &mut impl Write, g: &Geometry) -> std::io::Result<()> { + fn coord(out: &mut impl Write, p: &Coord) -> std::io::Result<()> { + write!(out, "{} {}", p.x, p.y) } - fn list(out: &mut String, v: &[Coord]) { + /// Coordinates, comma-separated. + fn list(out: &mut impl Write, v: &[Coord]) -> std::io::Result<()> { for (i, p) in v.iter().enumerate() { if i > 0 { - out.push_str(", "); + out.write_all(b", ")?; } - coord(out, p); + coord(out, p)?; } + Ok(()) } - fn rings(out: &mut String, rs: &[Vec]) { + /// Each ring's coordinates in parentheses, comma-separated. + fn rings(out: &mut impl Write, rs: &[Vec]) -> std::io::Result<()> { for (i, r) in rs.iter().enumerate() { if i > 0 { - out.push_str(", "); + out.write_all(b", ")?; } - out.push('('); - list(out, r); - out.push(')'); + out.write_all(b"(")?; + list(out, r)?; + out.write_all(b")")?; } + Ok(()) } - let mut out = String::new(); match g { Geometry::Point(p) => { - out.push_str("POINT ("); - coord(&mut out, p); - out.push(')'); + out.write_all(b"POINT (")?; + coord(out, p)?; } Geometry::MultiPoint(v) => { - out.push_str("MULTIPOINT ("); + out.write_all(b"MULTIPOINT (")?; for (i, p) in v.iter().enumerate() { if i > 0 { - out.push_str(", "); + out.write_all(b", ")?; } - out.push('('); - coord(&mut out, p); - out.push(')'); + out.write_all(b"(")?; + coord(out, p)?; + out.write_all(b")")?; } - out.push(')'); } Geometry::Line(parts) if parts.len() == 1 => { - out.push_str("LINESTRING ("); + out.write_all(b"LINESTRING (")?; if let Some(p) = parts.first() { - list(&mut out, p); + list(out, p)?; } - out.push(')'); } Geometry::Line(parts) => { - out.push_str("MULTILINESTRING ("); - for (i, p) in parts.iter().enumerate() { - if i > 0 { - out.push_str(", "); - } - out.push('('); - list(&mut out, p); - out.push(')'); - } - out.push(')'); + out.write_all(b"MULTILINESTRING (")?; + rings(out, parts)?; } Geometry::Polygon(polys) => { if polys.len() == 1 { - out.push_str("POLYGON ("); + out.write_all(b"POLYGON (")?; if let Some(rs) = polys.first() { - rings(&mut out, rs); + rings(out, rs)?; } - out.push(')'); } else { - out.push_str("MULTIPOLYGON ("); + out.write_all(b"MULTIPOLYGON (")?; for (i, rs) in polys.iter().enumerate() { if i > 0 { - out.push_str(", "); + out.write_all(b", ")?; } - out.push('('); - rings(&mut out, rs); - out.push(')'); + out.write_all(b"(")?; + rings(out, rs)?; + out.write_all(b")")?; } - out.push(')'); } } } - out + out.write_all(b")") +} + +/// A sink that refuses a comma: whether [`write_wkt`] fails on it says whether a geometry's text +/// is quoted in a CSV cell, without making the text. Text without a comma is a coordinate at most. +struct NoComma; + +impl Write for NoComma { + /// Takes the bytes, or fails on a comma among them. + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if bytes.contains(&b',') { Err(std::io::ErrorKind::InvalidData.into()) } else { Ok(bytes.len()) } + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } } /// Decodes an encoded polyline (Google's algorithm; `precision` 5, or 6 as OSRM and Valhalla @@ -528,26 +614,38 @@ pub(crate) fn wkt_csv_text(s: &str) -> String { /// CSV with a `wkt` geometry column and every attribute; cancellable between features. pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { + let mut out = Vec::new(); + write_wkt_csv(ds, &mut out)?; + text(out) +} + +/// [`to_wkt_csv`]'s text, written to `out` as it is made. +pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result<()> { let q = |s: &str| { let s = wkt_csv_text(s); if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } }; - let mut out = String::from("wkt"); + out.write_all(b"wkt")?; for f in &ds.fields { - out.push(','); - out.push_str(&q(&f.name)); + write!(out, ",{}", q(&f.name))?; } - out.push('\n'); + out.write_all(b"\n")?; for f in &ds.features { crate::progress::step(1)?; - out.push_str(&q(&f.geometry.as_ref().map(wkt).unwrap_or_default())); + if let Some(g) = &f.geometry { + // As `q` would: WKT holds no quote or line break and starts like no formula, so its + // cell is quoted for a comma alone, with nothing in it to escape. + let quote: &[u8] = if write_wkt(&mut NoComma, g).is_err() { b"\"" } else { b"" }; + out.write_all(quote)?; + write_wkt(out, g)?; + out.write_all(quote)?; + } for v in &f.attrs { - out.push(','); - out.push_str(&q(&v.to_file_text())); + write!(out, ",{}", q(&v.to_file_text()))?; } - out.push('\n'); + out.write_all(b"\n")?; } - Ok(out) + Ok(()) } #[cfg(test)] @@ -609,4 +707,71 @@ mod tests { let c = to_wkt_csv(&ds).unwrap(); assert!(c.contains("POINT (1 2),,0.1234567891\n") && c.contains(",B,0.000000001\n"), "{c}"); } + + /// Each geometry shape's text in KML, GPX and a WKT cell, the empty and one-coordinate ones + /// too: a cell is quoted only when its text holds a comma. + #[test] + fn kml_gpx_and_wkt_csv_text_of_each_geometry_shape() { + let (a, b) = (Coord::new(1.5, -2.0), Coord::new(3.0, 4.0)); + let kml_point = |c: &str| format!("{c}"); + let kml_line = |c: &str| format!("{c}"); + let ring = |side: &str, c: &str| format!("<{side}>{c}"); + let outer = ring("outerBoundaryIs", "1.5,-2 3,4"); + let inner = ring("innerBoundaryIs", "3,4"); + let many = |parts: &str| format!("{parts}"); + let (pa, pb) = (r#"lat="-2" lon="1.5""#, r#"lat="4" lon="3""#); + let wpt = |at: &str| format!("1\n"); + let trk = |segments: &str| format!("1{segments}\n"); + let ab = format!(""); + let only_b = format!(""); + let cases = [ + (Geometry::Point(a), kml_point("1.5,-2"), wpt(pa), "POINT (1.5 -2)"), + (Geometry::MultiPoint(vec![]), many(""), String::new(), "MULTIPOINT ()"), + (Geometry::MultiPoint(vec![a]), many(&kml_point("1.5,-2")), wpt(pa), "MULTIPOINT ((1.5 -2))"), + ( + Geometry::MultiPoint(vec![a, b]), + many(&(kml_point("1.5,-2") + &kml_point("3,4"))), + wpt(pa) + &wpt(pb), + "\"MULTIPOINT ((1.5 -2), (3 4))\"", + ), + (Geometry::Line(vec![]), many(""), trk(""), "MULTILINESTRING ()"), + (Geometry::Line(vec![vec![b]]), kml_line("3,4"), trk(&only_b), "LINESTRING (3 4)"), + (Geometry::Line(vec![vec![a, b]]), kml_line("1.5,-2 3,4"), trk(&ab), "\"LINESTRING (1.5 -2, 3 4)\""), + ( + Geometry::Line(vec![vec![a, b], vec![b]]), + many(&(kml_line("1.5,-2 3,4") + &kml_line("3,4"))), + trk(&(ab.clone() + &only_b)), + "\"MULTILINESTRING ((1.5 -2, 3 4), (3 4))\"", + ), + (Geometry::Polygon(vec![]), many(""), trk(""), "MULTIPOLYGON ()"), + ( + Geometry::Polygon(vec![vec![vec![b]]]), + format!("{}", ring("outerBoundaryIs", "3,4")), + trk(&only_b), + "POLYGON ((3 4))", + ), + ( + Geometry::Polygon(vec![vec![vec![a, b], vec![b]]]), + format!("{outer}{inner}"), + trk(&ab), + "\"POLYGON ((1.5 -2, 3 4), (3 4))\"", + ), + ( + Geometry::Polygon(vec![vec![vec![a, b], vec![b]], vec![]]), + many(&format!("{outer}{inner}")), + trk(&ab), + "\"MULTIPOLYGON (((1.5 -2, 3 4), (3 4)), ())\"", + ), + ]; + for (g, kml, gpx, cell) in cases { + let mut ds = Dataset::new("t", GeometryType::Point, vec![]); + ds.push(Some(g), vec![]); + let k = to_kml(&ds, None).unwrap(); + let placemark = format!("1{kml}\n"); + assert!(k.contains(&placemark), "{k}"); + let x = to_gpx(&ds, None).unwrap(); + assert!(x.ends_with(&format!("GPX/1/1\">\n{gpx}\n")), "{x}"); + assert_eq!(to_wkt_csv(&ds).unwrap(), format!("wkt\n{cell}\n")); + } + } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d84245a2e6..0af0169c63 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1,9 +1,12 @@ //! Vector readers and writers: GeoJSON, CSV (with longitude/latitude columns) and Shapefile. +use std::collections::BTreeMap; use std::path::Path; +use serde::ser::{Serialize, SerializeMap, Serializer}; use serde_json::{Map, Value as Json, json}; +use crate::capped::Limit; use crate::raster::{Crs, planetary}; use crate::{Coord, DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadReport, Result, Value}; @@ -1037,6 +1040,18 @@ pub fn write_bytes_noted( ext: &str, crs: Crs, name: &str, +) -> Result<(Vec, usize, Vec, rustgis_geom::Extent)> { + write_bytes_noted_within(ds, ext, crs, name, &Limit::none()) +} + +/// [`write_bytes_noted`] within `limit`: the file, and a zipped format's files before they are +/// zipped, are refused as soon as they would pass it. +pub fn write_bytes_noted_within( + ds: &Dataset, + ext: &str, + crs: Crs, + name: &str, + limit: &Limit, ) -> Result<(Vec, usize, Vec, rustgis_geom::Extent)> { let ext = ext.to_ascii_lowercase(); if crs != Crs::LonLat { @@ -1046,11 +1061,11 @@ pub fn write_bytes_noted( check_projected(&ext, crs)?; } if crs == ds.coord_crs() { - let (bytes, left_out) = projected_bytes(ds, &ext, crs)?; + let (bytes, left_out) = projected_bytes_within(ds, &ext, crs, limit)?; return Ok((bytes, left_out, Vec::new(), ds.lonlat_extent())); } let (projected, unplaced, placed) = project_leaving_out_placed(ds, crs)?; - let (bytes, left_out) = projected_bytes(&projected, &ext, crs)?; + let (bytes, left_out) = projected_bytes_within(&projected, &ext, crs, limit)?; let notes = unplaced_export_note(name, &ds.name, unplaced, crs).into_iter().collect(); Ok((bytes, left_out, notes, lonlat_extent_placed(ds, crs, placed))) } @@ -1066,31 +1081,83 @@ fn lonlat_extent_placed(ds: &Dataset, crs: Crs, placed: Option Result<(Vec, usize)> { + projected_bytes_within(ds, ext, crs, &Limit::none()) +} + +/// [`projected_bytes`] within `limit` ([`write_bytes_noted_within`]). +fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> Result<(Vec, usize)> { crate::progress::begin(ds.features.len()); - Ok(match ext { - "geojson" | "json" => { - let mut w = GeoJsonWriter::new(Vec::new(), &ds.name, &ds.fields)?; - w.write(&ds.features)?; - (w.finish()?, 0) - } - "csv" => (to_csv_in(ds, crs)?.into_bytes(), 0), - "fgb" => (crate::source::fgb::write_in(ds, crs)?, without_geometry(ds)), - "parquet" | "geoparquet" => (crate::source::parquet::write_in(ds, crs)?, 0), - "kml" => (crate::interop::to_kml(ds, name_field(ds))?.into_bytes(), without_geometry(ds)), - "kmz" => { - let kml = crate::interop::to_kml(ds, name_field(ds))?.into_bytes(); - (crate::zip::write(&[("doc.kml".to_string(), kml)]).map_err(DataError::Format)?, without_geometry(ds)) - } - "gpx" => (crate::interop::to_gpx(ds, name_field(ds))?.into_bytes(), gpx_left_out(ds)), - "shp" | "zip" => { - let (parts, left_out) = shapefile_parts_in(ds, crs)?; - let base: String = ds.name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '_' }).collect(); - let base = if base.trim().is_empty() { "layer".to_string() } else { base }; - let entries: Vec<(String, Vec)> = parts.into_iter().map(|(e, b)| (format!("{base}.{e}"), b)).collect(); - (crate::zip::write(&entries).map_err(DataError::Format)?, left_out) - } - other => return Err(DataError::Unsupported(other.to_string())), - }) + let mut out = limit.buffer(); + let made = (|| { + Ok(match ext { + "geojson" | "json" => { + write_geojson(ds, &mut out)?; + (out.into_inner(), 0) + } + "csv" => { + write_csv(ds, crs, &mut out)?; + (out.into_inner(), 0) + } + "fgb" => { + let left_out = without_geometry(ds); + crate::source::fgb::write_features(&ds.name, ds.geometry_type, &ds.fields, crs, &mut out, &mut |add| add(&ds.features))?; + (out.into_inner(), left_out) + } + "parquet" | "geoparquet" => { + crate::source::parquet::write_features(ds.geometry_type, &ds.fields, crs, &mut out, &mut |add| add(&ds.features))?; + (out.into_inner(), 0) + } + "kml" => { + crate::interop::write_kml(ds, name_field(ds), &mut out)?; + (out.into_inner(), without_geometry(ds)) + } + "kmz" => { + crate::interop::write_kml(ds, name_field(ds), &mut out)?; + let kml = out.into_inner(); + (zipped(&[("doc.kml".to_string(), kml)], limit)?, without_geometry(ds)) + } + "gpx" => { + crate::interop::write_gpx(ds, name_field(ds), &mut out)?; + (out.into_inner(), gpx_left_out(ds)) + } + "shp" | "zip" => { + let (parts, left_out, _) = shapefile_parts_within(ds, crs, None, limit)?; + let base: String = + ds.name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '_' }).collect(); + let base = if base.trim().is_empty() { "layer".to_string() } else { base }; + let entries: Vec<(String, Vec)> = parts.into_iter().map(|(e, b)| (format!("{base}.{e}"), b)).collect(); + (zipped(&entries, limit)?, left_out) + } + other => return Err(DataError::Unsupported(other.to_string())), + }) + })(); + limit.whole(made) +} + +/// A zip of `entries`, which were held to `limit` as they were made: they stay counted against it +/// while the archive is made, and the archive is written within what they leave, so the two +/// together never pass it (besides one entry's compressed bytes at a time). +fn zipped(entries: &[(String, Vec)], limit: &Limit) -> Result> { + let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum(); + let _parts = limit.hold(parts)?; + let mut out = limit.buffer(); + let made = crate::zip::write_to(entries, &mut out).map_err(DataError::Format); + limit.whole(made.map(|()| out.into_inner())) +} + +/// The text `data.convert` makes of a dataset in longitude/latitude, in `format` (`geojson`, +/// `csv`, `kml`, `gpx`, else WKT in a CSV), within `limit`. KML and GPX name placemarks by the +/// field `name_field`. +pub fn text_bytes_within(ds: &Dataset, format: &str, name_field: Option, limit: &Limit) -> Result> { + let mut out = limit.buffer(); + let made = match format { + "geojson" => write_geojson(ds, &mut out), + "csv" => write_csv(ds, Crs::LonLat, &mut out), + "kml" => crate::interop::write_kml(ds, name_field, &mut out), + "gpx" => crate::interop::write_gpx(ds, name_field, &mut out), + _ => crate::interop::write_wkt_csv(ds, &mut out), + }; + limit.whole(made.map(|()| out.into_inner())) } /// Writes a dataset by extension (`.geojson`/`.json`, `.csv`, `.fgb`, `.gpkg` on the desktop, @@ -1726,25 +1793,75 @@ pub fn geometry_from_geojson(mut g: &Json) -> Option { } } +/// A geometry as a GeoJSON geometry object. pub fn geometry_to_geojson(g: &Geometry) -> Json { - fn c(c: &Coord) -> Json { - json!([c.x, c.y]) + // Making a value can't fail: every key is text. + serde_json::to_value(GeoJsonGeometry(g)).unwrap_or_default() +} + +/// A geometry as its GeoJSON object serializes, a coordinate at a time: written to a file, no +/// copy of it is made. Its members are in sorted order, as a [`Json`] object holds them. +struct GeoJsonGeometry<'a>(&'a Geometry); + +impl Serialize for GeoJsonGeometry<'_> { + /// A line or polygon of one part is the single kind, any other number the `Multi` one. + fn serialize(&self, s: S) -> std::result::Result { + let mut object = s.serialize_map(Some(2))?; + let kind = match self.0 { + Geometry::Point(p) => { + object.serialize_entry("coordinates", &[p.x, p.y])?; + "Point" + } + Geometry::MultiPoint(v) => { + object.serialize_entry("coordinates", &Positions(v))?; + "MultiPoint" + } + Geometry::Line(parts) if let [only] = parts.as_slice() => { + object.serialize_entry("coordinates", &Positions(only))?; + "LineString" + } + Geometry::Line(parts) => { + object.serialize_entry("coordinates", &Rings(parts))?; + "MultiLineString" + } + Geometry::Polygon(polys) if let [only] = polys.as_slice() => { + object.serialize_entry("coordinates", &Rings(only))?; + "Polygon" + } + Geometry::Polygon(polys) => { + object.serialize_entry("coordinates", &Polygons(polys))?; + "MultiPolygon" + } + }; + object.serialize_entry("type", kind)?; + object.end() } - fn l(v: &[Coord]) -> Json { - Json::Array(v.iter().map(c).collect()) +} + +/// A line's or ring's positions, `[x, y]` each. +struct Positions<'a>(&'a [Coord]); + +impl Serialize for Positions<'_> { + fn serialize(&self, s: S) -> std::result::Result { + s.collect_seq(self.0.iter().map(|c| [c.x, c.y])) } - match g { - Geometry::Point(p) => json!({"type": "Point", "coordinates": c(p)}), - Geometry::MultiPoint(v) => json!({"type": "MultiPoint", "coordinates": l(v)}), - Geometry::Line(parts) if let [only] = parts.as_slice() => json!({"type": "LineString", "coordinates": l(only)}), - Geometry::Line(parts) => json!({"type": "MultiLineString", "coordinates": parts.iter().map(|p| l(p)).collect::>()}), - Geometry::Polygon(polys) if let [only] = polys.as_slice() => { - json!({"type": "Polygon", "coordinates": only.iter().map(|r| l(r)).collect::>()}) - } - Geometry::Polygon(polys) => json!({"type": "MultiPolygon", "coordinates": polys - .iter() - .map(|rings| rings.iter().map(|r| l(r)).collect::>()) - .collect::>()}), +} + +/// The lines of a MultiLineString, or the rings of a polygon. +struct Rings<'a>(&'a [Vec]); + +impl Serialize for Rings<'_> { + fn serialize(&self, s: S) -> std::result::Result { + s.collect_seq(self.0.iter().map(|r| Positions(r))) + } +} + +/// The polygons of a MultiPolygon. +struct Polygons<'a>(&'a [Vec>]); + +impl Serialize for Polygons<'_> { + fn serialize(&self, s: S) -> std::result::Result { + s.collect_seq(self.0.iter().map(|p| Rings(p))) } } @@ -2320,18 +2437,67 @@ pub fn to_geojson(ds: &Dataset) -> Json { /// A GeoJSON text conversion with per-feature progress and cancellation, of `ds`'s coordinates as /// they are: the caller converts a dataset held in another system first ([`Dataset::in_lonlat`]). pub fn to_geojson_text(ds: &Dataset) -> Result { - let mut writer = GeoJsonWriter::new(Vec::new(), &ds.name, &ds.fields)?; + let mut out = Vec::new(); + write_geojson(ds, &mut out)?; + String::from_utf8(out).map_err(|e| DataError::Format(e.to_string())) +} + +/// [`to_geojson_text`]'s collection, written to `out`, buffered: its serializer writes a few +/// bytes at a time. +fn write_geojson(ds: &Dataset, out: &mut impl std::io::Write) -> Result<()> { + let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?; writer.write(&ds.features)?; - String::from_utf8(writer.finish()?).map_err(|e| DataError::Format(e.to_string())) + std::io::Write::flush(&mut writer.finish()?)?; + Ok(()) } /// A feature as a GeoJSON Feature, its attributes named by `fields`. -fn feature_to_geojson(fields: &[Field], f: &crate::Feature) -> Json { - let mut props = Map::new(); - for (field, v) in fields.iter().zip(&f.attrs) { - props.insert(field.name.clone(), v.to_json()); +fn feature_to_geojson(fields: &[Field], feature: &crate::Feature) -> Json { + // Making a value can't fail: every key is text. + serde_json::to_value(GeoJsonFeature { fields, feature }).unwrap_or_default() +} + +/// [`feature_to_geojson`]'s object as it serializes, from the row itself: its geometry and text +/// are written as they are walked, so a large feature is never held a second time, and a sink +/// that refuses a write stops it there. Its members are in sorted order, as a [`Json`] object +/// holds them. +struct GeoJsonFeature<'a> { + fields: &'a [Field], + feature: &'a crate::Feature, +} + +impl Serialize for GeoJsonFeature<'_> { + /// The properties borrow their names and values from the fields and the row. + fn serialize(&self, s: S) -> std::result::Result { + let f = self.feature; + // By name, in order; of two fields with one name, the last one's value. + let properties: BTreeMap<&str, Property> = + self.fields.iter().zip(&f.attrs).map(|(field, v)| (field.name.as_str(), Property(v))).collect(); + let mut object = s.serialize_map(Some(4))?; + object.serialize_entry("geometry", &f.geometry.as_ref().map(GeoJsonGeometry))?; + object.serialize_entry("id", &f.id)?; + object.serialize_entry("properties", &properties)?; + object.serialize_entry("type", "Feature")?; + object.end() + } +} + +/// An attribute value as a GeoJSON property: what [`Value::to_json`] gives, its text not copied. +struct Property<'a>(&'a Value); + +impl Serialize for Property<'_> { + /// A date or date-time is written as its text. + fn serialize(&self, s: S) -> std::result::Result { + match self.0 { + Value::Null => s.serialize_unit(), + Value::Int(i) => s.serialize_i64(*i), + // JSON writes a number that isn't finite as null. + Value::Float(f) => s.serialize_f64(*f), + Value::Text(t) => s.serialize_str(t), + Value::Bool(b) => s.serialize_bool(*b), + v @ (Value::Date(_) | Value::DateTime(_)) => s.collect_str(v), + } } - json!({"type": "Feature", "id": f.id, "properties": props, "geometry": f.geometry.as_ref().map(geometry_to_geojson)}) } /// Writes a GeoJSON FeatureCollection a run of features at a time, for exports that never hold @@ -2359,7 +2525,8 @@ impl GeoJsonWriter { if !std::mem::take(&mut self.first) { self.out.write_all(b",")?; } - serde_json::to_writer(&mut self.out, &feature_to_geojson(&self.fields, f)).map_err(|e| DataError::Format(e.to_string()))?; + let feature = GeoJsonFeature { fields: &self.fields, feature: f }; + serde_json::to_writer(&mut self.out, &feature).map_err(|e| DataError::Format(e.to_string()))?; } Ok(()) } @@ -3531,9 +3698,17 @@ pub fn to_csv(ds: &Dataset) -> Result { /// As [`to_csv`], for a dataset whose coordinates are in `crs`: a projected system's go in x and y /// columns ([`csv_projected_names`]). pub fn to_csv_in(ds: &Dataset, crs: Crs) -> Result { - let mut w = CsvWriter::new(Vec::new(), &ds.fields, ds.geometry_type, crs)?; + let mut out = Vec::new(); + write_csv(ds, crs, &mut out)?; + String::from_utf8(out).map_err(|e| DataError::Format(e.to_string())) +} + +/// [`to_csv_in`]'s text, written to `out`. +fn write_csv(ds: &Dataset, crs: Crs, out: &mut impl std::io::Write) -> Result<()> { + let mut w = CsvWriter::new(out, &ds.fields, ds.geometry_type, crs)?; w.write(&ds.features)?; - String::from_utf8(w.finish()?).map_err(|e| DataError::Format(e.to_string())) + w.finish()?; + Ok(()) } /// Writes CSV a run of features at a time: a header of the fields, and for a point layer @@ -6127,9 +6302,18 @@ pub(crate) fn shapefile_parts_styled( ds: &Dataset, crs: Crs, style: Option<&DbfStyle>, +) -> Result<(Vec<(&'static str, Vec)>, usize, Vec)> { + shapefile_parts_within(ds, crs, style, &Limit::none()) +} + +/// [`shapefile_parts_styled`], the `.shp`, `.shx` and `.dbf` together within `limit`. +fn shapefile_parts_within( + ds: &Dataset, + crs: Crs, + style: Option<&DbfStyle>, + limit: &Limit, ) -> Result<(Vec<(&'static str, Vec)>, usize, Vec)> { use shapefile::dbase::{FieldName, FieldValue, Record, TableWriterBuilder}; - use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); let names = dbf_names(&ds.fields); let dbf_name = |n: &str| FieldName::try_from(n).map_err(|e| DataError::Format(format!("Shapefile: field {n}: {e}"))); @@ -6185,7 +6369,7 @@ pub(crate) fn shapefile_parts_styled( let pt = |c: &Coord| shapefile::Point::new(c.x, c.y); let finite = |c: &&Coord| c.x.is_finite() && c.y.is_finite(); - let (mut shp, mut shx, mut dbf) = (Cursor::new(Vec::new()), Cursor::new(Vec::new()), Cursor::new(Vec::new())); + let (mut shp, mut shx, mut dbf) = (limit.buffer(), limit.buffer(), limit.buffer()); let mut left_out = 0; let mut written = 0; { @@ -7104,6 +7288,86 @@ mod tests { assert_eq!(back.value(1, 0), &Value::Text("B".into())); } + /// The text of every geometry shape and value type: keys sorted, the last of two fields of one + /// name kept, and a number that isn't finite written as null. + #[test] + fn geojson_text_of_every_geometry_and_value_is_pinned() { + let fields = ["z", "int", "float \"q\"", "text", "bool", "day", "when", "z"].map(|n| Field::new(n, FieldType::Text)); + let mut ds = Dataset::new("Shapes \"1\"\n", GeometryType::None, fields.to_vec()); + let c = Coord::new; + let (a, b) = (c(1.5, -2.0), c(0.1 + 0.2, 1e-7)); + let ring = vec![c(0.0, 0.0), c(4.0, 0.0), c(4.0, 4.0), c(0.0, 0.0)]; + let hole = vec![c(1.0, 1.0), c(2.0, 1.0), c(1.0, 1.0)]; + let geometries = [ + None, + Some(Geometry::Point(a)), + Some(Geometry::Point(c(f64::NAN, f64::NEG_INFINITY))), + Some(Geometry::MultiPoint(vec![])), + Some(Geometry::MultiPoint(vec![a, b])), + Some(Geometry::Line(vec![])), + Some(Geometry::Line(vec![vec![]])), + Some(Geometry::Line(vec![vec![c(-0.0, 1e300)]])), + Some(Geometry::Line(vec![vec![a, b], vec![]])), + Some(Geometry::Polygon(vec![])), + Some(Geometry::Polygon(vec![vec![]])), + Some(Geometry::Polygon(vec![vec![ring.clone(), hole.clone()]])), + Some(Geometry::Polygon(vec![vec![ring, hole], vec![]])), + ]; + let values = vec![ + Value::Text("first z".into()), + Value::Int(i64::MIN), + Value::Float(2.0), + Value::Text("a\"b\\c\n\t\u{1}é€/".into()), + Value::Bool(true), + Value::Date(crate::date::Date::parse("2026-03-05").unwrap()), + Value::DateTime(crate::date::DateTime::parse("2026-03-05T12:30:00.5+02:00").unwrap()), + Value::Null, + ]; + let others = [f64::NAN, f64::INFINITY, -0.0, 1e300, 5e-324].map(Value::Float); + for (i, g) in geometries.into_iter().enumerate() { + let mut row = values.clone(); + if let Some(v) = i.checked_sub(1).and_then(|i| others.get(i)) { + row[2] = v.clone(); + row[7] = Value::Int(7); + } + ds.push(g, row); + } + let ring = "[[0.0,0.0],[4.0,0.0],[4.0,4.0],[0.0,0.0]],[[1.0,1.0],[2.0,1.0],[1.0,1.0]]"; + let geometries = [ + "null".to_string(), + r#"{"coordinates":[1.5,-2.0],"type":"Point"}"#.into(), + r#"{"coordinates":[null,null],"type":"Point"}"#.into(), + r#"{"coordinates":[],"type":"MultiPoint"}"#.into(), + r#"{"coordinates":[[1.5,-2.0],[0.30000000000000004,1e-7]],"type":"MultiPoint"}"#.into(), + r#"{"coordinates":[],"type":"MultiLineString"}"#.into(), + r#"{"coordinates":[],"type":"LineString"}"#.into(), + r#"{"coordinates":[[-0.0,1e+300]],"type":"LineString"}"#.into(), + r#"{"coordinates":[[[1.5,-2.0],[0.30000000000000004,1e-7]],[]],"type":"MultiLineString"}"#.into(), + r#"{"coordinates":[],"type":"MultiPolygon"}"#.into(), + r#"{"coordinates":[],"type":"Polygon"}"#.into(), + format!(r#"{{"coordinates":[{ring}],"type":"Polygon"}}"#), + format!(r#"{{"coordinates":[[{ring}],[]],"type":"MultiPolygon"}}"#), + ]; + let numbers = ["2.0", "null", "null", "-0.0", "1e+300", "5e-324"]; + let features: Vec = geometries + .iter() + .enumerate() + .map(|(i, g)| { + let float = numbers.get(i).unwrap_or(&"2.0"); + let z = if (1..=5).contains(&i) { "7" } else { "null" }; + let id = ds.features[i].id; + let properties = format!( + r#"{{"bool":true,"day":"2026-03-05","float \"q\"":{float},"int":-9223372036854775808,"text":"a\"b\\c\n\t\u0001é€/","when":"2026-03-05T12:30:00.500+02:00","z":{z}}}"# + ); + format!(r#"{{"geometry":{g},"id":{id},"properties":{properties},"type":"Feature"}}"#) + }) + .collect(); + let features = format!("[{}]", features.join(",")); + let expected = format!(r#"{{"type":"FeatureCollection","name":"Shapes \"1\"\n","features":{features}}}"#); + assert_eq!(to_geojson_text(&ds).unwrap(), expected); + assert_eq!(to_geojson(&ds)["features"].to_string(), features); + } + #[test] fn geojson_collection_never_exports_only_a_member() { let point = json!({"type":"Point", "coordinates":[1,2]}); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 8865fee38f..e22dc24cc1 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -5,6 +5,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod address; +pub mod capped; pub mod citygml; pub mod cityjson; mod citymodel; diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index bf8414a9d1..75434d3487 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -44,6 +44,7 @@ use std::path::Path; use super::geotiff::{GeoKeys, fits_bytes, geo_keys}; use super::{ColorHint, Raster}; +use crate::capped::Limit; use crate::{DataError, Result}; /// Pixels along a tile's sides, in the full image and in every overview. @@ -1050,9 +1051,19 @@ pub fn written_bands(r: &Raster, band: usize) -> Result> { /// A raster as the bytes of a cloud-optimised GeoTIFF (for the browser, which downloads them). pub fn write(r: &Raster, band: usize) -> Result> { - let mut out = std::io::Cursor::new(Vec::new()); - write_to(r, band, Flavour::Auto, &mut out)?; - Ok(out.into_inner()) + write_with_info(r, band).map(|(bytes, _)| bytes) +} + +/// [`write`], also saying how the file is laid out, as [`write_file`] does. +pub fn write_with_info(r: &Raster, band: usize) -> Result<(Vec, CogInfo)> { + write_with_info_within(r, band, &Limit::none()) +} + +/// [`write_with_info`] within `limit`: refused as soon as the file would pass it. +pub fn write_with_info_within(r: &Raster, band: usize, limit: &Limit) -> Result<(Vec, CogInfo)> { + let mut out = limit.buffer(); + let info = write_to(r, band, Flavour::Auto, &mut out); + limit.whole(info.map(|info| (out.into_inner(), info))) } /// Writes a cloud-optimised GeoTIFF to `path` through a temporary file beside it, synced and diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index c63f1b7fb8..9d7d18b1c4 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -15,6 +15,7 @@ use tiff::tags::Tag; use super::cog::Sparse; use super::crs::CustomCrs; use super::{ColorHint, Crs, Exact, GeoTransform, ImageGrid, Raster, Uncounted, max_samples}; +use crate::capped::Limit; use crate::{DataError, Result}; fn err(e: impl std::fmt::Display) -> DataError { @@ -2278,7 +2279,14 @@ fn alpha_hits_no_data(r: &Raster, opaque: f32, alpha: &[f32]) -> bool { /// COG writer ([`super::cogwrite::write_strips`]). A cancelled run stops it (with /// [`DataError::Cancelled`]) within a strip. pub fn write(r: &Raster, band: usize) -> Result> { - encode(r, band, false) + write_within(r, band, &Limit::none()) +} + +/// [`write`] within `limit`: refused as soon as the file would pass it. +pub fn write_within(r: &Raster, band: usize, limit: &Limit) -> Result> { + let mut out = limit.buffer(); + let made = encode(r, band, false, &mut out); + limit.whole(made.map(|()| out.into_inner())) } /// Writes every band of a raster, for a layer whose pixels the project keeps: as [`write`] does @@ -2288,7 +2296,9 @@ pub fn write(r: &Raster, band: usize) -> Result> { /// reads them back as the same bands. An integer raster's alpha, when written as floats, is divided /// by its opaque value, as [`write`] does. pub fn write_all(r: &Raster) -> Result> { - encode(r, 0, true) + let mut out = std::io::Cursor::new(Vec::new()); + encode(r, 0, true, &mut out)?; + Ok(out.into_inner()) } /// Writes `data` (samples interleaved as `img` lays them out, a row after another) as `img`'s @@ -2297,7 +2307,7 @@ fn put( img: super::cogwrite::Strips, data: &[T], le: fn(T) -> [u8; N], - out: &mut std::io::Cursor>, + out: &mut (impl std::io::Write + std::io::Seek), ) -> Result<()> { put_cells(img, data, |v| le(*v), out) } @@ -2308,7 +2318,7 @@ fn put_cells( img: super::cogwrite::Strips, data: &[T], cell: impl Fn(&T) -> [u8; N] + Sync, - out: &mut std::io::Cursor>, + out: &mut (impl std::io::Write + std::io::Seek), ) -> Result<()> { let per_row = img.w as usize * usize::from(img.spp); super::cogwrite::write_strips(img, out, |rows, buf| { @@ -2321,11 +2331,10 @@ fn put_cells( /// [`write`] (or with `every`, [`write_all`]). Whether a single 8-bit band's cells are all bytes /// is one look over the band, on several threads, with no look at Cancel inside it: Cancel is /// looked at after it, and between strips as they are written. -fn encode(r: &Raster, band: usize, every: bool) -> Result> { +fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write + std::io::Seek)) -> Result<()> { use super::cogwrite::{Sample, Strips, few_classes, geo_entries}; // A scan's place is only where it was laid on the view: not coordinates to write into a file. r.require_coordinates().map_err(err)?; - let mut out = std::io::Cursor::new(Vec::new()); let gt = r.transform; if gt.pixel_height > 0.0 || gt.pixel_width < 0.0 { return Err(err("only north-up rasters can be exported for now")); @@ -2421,7 +2430,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { // Every band holds `n` values (checked above), so none is filled in. data.extend(r.bands.iter().enumerate().map(|(bi, b)| $sample(bi, b.data.get(i).copied().unwrap_or(f32::NAN)))); } - put(image(&all[..], $kind, extras)?, &data, $le, &mut out)?; + put(image(&all[..], $kind, extras)?, &data, $le, out)?; }}; } if as_bytes { @@ -2446,13 +2455,13 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { for i in 0..n { data.extend([red.get(i), green.get(i), blue.get(i), a.get(i)].map(|v| v.copied().unwrap_or(0))); } - put(image(&[0, 1, 2, 3], Sample::Byte, fourth())?, &data, u8::to_le_bytes, &mut out)?; + put(image(&[0, 1, 2, 3], Sample::Byte, fourth())?, &data, u8::to_le_bytes, out)?; } else { let mut data = Vec::with_capacity(n * 3); for i in 0..n { data.extend([red.get(i), green.get(i), blue.get(i)].map(|v| v.copied().unwrap_or(0))); } - put(image(&[0, 1, 2], Sample::Byte, Vec::new())?, &data, u8::to_le_bytes, &mut out)?; + put(image(&[0, 1, 2], Sample::Byte, Vec::new())?, &data, u8::to_le_bytes, out)?; } } else if rgb && let (Some(red), Some(green), Some(blue)) = (r.bands.first(), r.bands.get(1), r.bands.get(2)) { // Colour bands that aren't bytes (three embedding dimensions): kept as 32-bit floats, with @@ -2470,14 +2479,14 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { for i in 0..n { data.extend([cell(false, at(red, i)), cell(false, at(green, i)), cell(false, at(blue, i)), cell(true, at(alpha, i))]); } - put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, &mut out)?; + put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, out)?; } None => { let mut data = Vec::with_capacity(n * 3); for i in 0..n { data.extend([at(red, i), at(green, i), at(blue, i)]); } - put(image(&[0, 1, 2], Sample::Float, Vec::new())?, &data, f32::to_le_bytes, &mut out)?; + put(image(&[0, 1, 2], Sample::Float, Vec::new())?, &data, f32::to_le_bytes, out)?; } } } else { @@ -2492,12 +2501,12 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { crate::progress::check()?; let nodata = r.nodata.map_or(0, |d| d as u8); let cell = |v: &f32| [if r.is_valid(*v) { *v as u8 } else { nodata }]; - put_cells(image(&[band], Sample::Byte, Vec::new())?, &b.data, cell, &mut out)?; + put_cells(image(&[band], Sample::Byte, Vec::new())?, &b.data, cell, out)?; } else { - put(image(&[band], Sample::Float, Vec::new())?, &b.data, f32::to_le_bytes, &mut out)?; + put(image(&[band], Sample::Float, Vec::new())?, &b.data, f32::to_le_bytes, out)?; } } - Ok(out.into_inner()) + Ok(()) } #[cfg(test)] diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3af146d1ac..a16a47d387 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -814,13 +814,48 @@ pub fn layers(path: &Path) -> Result> { /// source can, otherwise in one read up to [`MAX_LIMIT`]. A larger source, or an incomplete read, /// is refused. pub fn materialize(src: &dyn FeatureSource) -> Result<(Dataset, ReadReport)> { - materialize_within(src, MAX_READ_BYTES) + materialize_within(src, MAX_READ_BYTES, None) +} + +/// [`materialize`] for a caller that can hold only `budget` bytes of features: a larger source is +/// refused with the error `refusal`. It is refused before it is read when the count it gives says +/// its rows and their values alone are larger. A source that can be walked whole a chunk at a time +/// ([`FeatureSource::visits_extent_chunks`], a GeoJSON read in place too) is refused as soon as +/// what is read passes the budget, having held no more than a chunk, or one larger feature, past +/// it. A file by its web address that can't be walked is refused before it is read, as neither its +/// count nor its size says what its geometry and text decode to. Any other source read at once +/// can't be stopped partway: it is measured once read. +pub fn materialize_up_to(src: &dyn FeatureSource, budget: u64, refusal: &str) -> Result<(Dataset, ReadReport)> { + let info = src.info(); + let row = std::mem::size_of::().saturating_add(info.fields.len().saturating_mul(std::mem::size_of::())); + if info.count.is_some_and(|n| n.saturating_mul(row as u64) > budget) { + return Err(DataError::Format(refusal.to_string())); + } + if src.remote().is_some() && !src.visits_extent_chunks() { + return Err(DataError::Format(format!( + "{}: a file read by its web address can't be read whole within a memory limit: download it and add the file, or use the desktop app", + info.name + ))); + } + materialize_within(src, budget, Some(refusal)) } -/// [`materialize`], with `budget` bytes for a source read a chunk at a time. -fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, ReadReport)> { +/// [`materialize`], with `budget` bytes for a source read a chunk at a time. `refusal`, given by a +/// caller held to the budget, is the error for a source over it: then a source that can only be +/// walked by extent is walked too, and one read at once is measured against the budget. +fn materialize_within(src: &dyn FeatureSource, budget: u64, refusal: Option<&str>) -> Result<(Dataset, ReadReport)> { let info = src.info(); - let batch = if src.visits_chunks() { read_chunks(src, budget)? } else { read_at_once(src)? }; + let batch = if src.visits_chunks() || (refusal.is_some() && src.visits_extent_chunks()) { + read_chunks(src, budget, refusal)? + } else { + let batch = read_at_once(src)?; + if let Some(refusal) = refusal + && chunk_memory::features_bytes(&batch.features) as u64 > budget + { + return Err(DataError::Format(refusal.to_string())); + } + batch + }; let Batch { features, skipped, unread_dates, rounded_dates, null_text, notes, not_utf8, .. } = batch; let mut ds = Dataset::new(info.name.clone(), info.geometry_type, info.fields.clone()); ds.crs = info.coordinate_system(); @@ -890,16 +925,18 @@ fn read_at_once(src: &dyn FeatureSource) -> Result { } /// Every feature of a source that can be read a chunk at a time, with the rows it skipped and the -/// values it counted, refusing the source once its features would hold more than `budget` bytes. -fn read_chunks(src: &dyn FeatureSource, budget: u64) -> Result { +/// values it counted, refusing the source once its features would hold more than `budget` bytes, +/// with the error `refusal` when given. +fn read_chunks(src: &dyn FeatureSource, budget: u64, refusal: Option<&str>) -> Result { let info = src.info(); let row_bytes = std::mem::size_of::() as u64; let too_large = || { - DataError::Format(format!( - "{}: the layer needs more than the {} MiB a whole read may hold: clip or filter it first", - info.name, - budget >> 20 - )) + DataError::Format(match refusal { + Some(refusal) => refusal.to_string(), + None => { + format!("{}: the layer needs more than the {} MiB a whole read may hold: clip or filter it first", info.name, budget >> 20) + } + }) }; let no_memory = || DataError::Format(format!("{}: not enough memory to read the whole layer", info.name)); // A count that alone is too many rows is refused before reading. It isn't trusted to size the diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 35daae1eeb..1aa60906b2 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -787,15 +787,102 @@ fn whole_reads_by_chunk_stay_within_the_memory_budget() { let src = open_path(&p, None).unwrap(); assert!(src.visits_chunks(), "{ext}"); let once = src.read(&Request::all()).unwrap().features; - let (whole, report) = materialize_within(src.as_ref(), MAX_READ_BYTES).unwrap(); + let (whole, report) = materialize_within(src.as_ref(), MAX_READ_BYTES, None).unwrap(); assert_eq!(whole.features.to_vec(), once, "{ext}"); assert_eq!(report.skipped, 0, "{ext}"); let half = chunk_memory::features_bytes(&once) as u64 / 2; - let error = materialize_within(src.as_ref(), half).unwrap_err().to_string(); + let error = materialize_within(src.as_ref(), half, None).unwrap_err().to_string(); assert!(error.contains("clip or filter it first"), "{ext}: {error}"); } } +/// A source as its provider answers, counting its whole reads and the features it walks. +struct Counted { + inner: Box, + reads: std::sync::atomic::AtomicUsize, + walked: std::sync::atomic::AtomicUsize, +} + +impl Counted { + /// `inner`, nothing read yet. + fn new(inner: Box) -> Counted { + Counted { inner, reads: Default::default(), walked: Default::default() } + } +} + +impl FeatureSource for Counted { + fn info(&self) -> &SourceInfo { + self.inner.info() + } + + fn read(&self, req: &Request) -> Result { + self.reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.inner.read(req) + } + + fn visits_chunks(&self) -> bool { + self.inner.visits_chunks() + } + + fn visits_extent_chunks(&self) -> bool { + self.inner.visits_extent_chunks() + } + + fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + self.inner.visit_chunks(extent, bytes, &mut |chunk| { + self.walked.fetch_add(chunk.len(), std::sync::atomic::Ordering::Relaxed); + visit(chunk) + }) + } + + fn remote(&self) -> Option> { + self.inner.remote() + } +} + +/// A budgeted read of a GeoJSON read in place, whose few features hold large geometries its count +/// says nothing of, is refused as it is walked: it is never read at once, nor walked to its end. +/// Within the budget it gives what one read gives. +#[test] +fn a_budgeted_read_of_a_geojson_stops_before_all_its_geometry_is_held() { + use std::sync::atomic::Ordering::Relaxed; + const FEATURES: usize = 12; + // 960 kB of coordinates a feature: more than a chunk in all. + let line = vec!["[1,2]"; 60_000].join(","); + let feature = format!(r#"{{"type":"Feature","properties":{{}},"geometry":{{"type":"LineString","coordinates":[{line}]}}}}"#); + let p = dir().join("budget-lines.geojson"); + std::fs::write(&p, format!(r#"{{"type":"FeatureCollection","features":[{}]}}"#, vec![feature; FEATURES].join(","))).unwrap(); + let src = Counted::new(open_path(&p, None).unwrap()); + assert_eq!(src.info().count, Some(FEATURES as u64)); + let error = materialize_up_to(&src, 1 << 20, "over the budget").unwrap_err().to_string(); + assert!(error.contains("over the budget"), "{error}"); + assert_eq!(src.reads.load(Relaxed), 0, "refused without a read of the whole source"); + let walked = src.walked.load(Relaxed); + assert!(walked > 0 && walked < FEATURES, "{walked} features walked"); + + let (ds, report) = materialize_up_to(&src, MAX_READ_BYTES, "over the budget").unwrap(); + assert_eq!(ds.features.to_vec(), src.inner.read(&Request::all()).unwrap().features); + assert_eq!(report.skipped, 0); + assert!(report.messages.is_empty(), "{:?}", report.messages); +} + +/// A file read by its web address can only be read at once, and its count doesn't say what its +/// geometry and text decode to: a budgeted read refuses it, even with its bytes already fetched. +#[test] +fn a_budgeted_read_refuses_a_file_by_its_web_address_before_reading_it() { + for (url, parquet) in [("https://test.example/budget.fgb", false), ("https://test.example/budget.geoparquet", true)] { + remote::testing::serve(url, big(4, parquet)); + // Fetched whole, as a view of its whole extent leaves it: a read now needs nothing more. + let view: Arc = Arc::from(open_url_blocking(url).unwrap()); + assert!(read_blocking(&view, &Request::all()).unwrap().complete, "{url}"); + let src = Counted::new(open_url_blocking(url).unwrap()); + assert!(src.inner.read(&Request::all()).unwrap().complete, "{url}"); + let error = materialize_up_to(&src, MAX_READ_BYTES, "over the budget").unwrap_err().to_string(); + assert!(error.contains("by its web address") && error.contains("download"), "{url}: {error}"); + assert_eq!(src.reads.load(std::sync::atomic::Ordering::Relaxed), 0, "{url}"); + } +} + /// A GeoParquet column in another body's system (PROJJSON, as PROJ writes IAU_2015) is read as /// its longitude/latitude with a notice, refused when its coordinates are projected or count west, /// and an EPSG one says nothing of bodies. diff --git a/crates/data/src/zip.rs b/crates/data/src/zip.rs index 865f554ab7..d2ccff7880 100644 --- a/crates/data/src/zip.rs +++ b/crates/data/src/zip.rs @@ -36,9 +36,19 @@ fn crc32(data: &[u8]) -> u32 { /// holds at most 65,535 entries and 4 GiB, and names of up to 65,535 bytes; beyond that it's an /// error rather than a damaged archive. pub fn write(entries: &[(String, Vec)]) -> Result, String> { + let mut out = Vec::new(); + write_to(entries, &mut out)?; + Ok(out) +} + +/// [`write`]'s archive, written to `out` as it is made (a buffer held to a limit stops it there). +/// Besides `out`, it holds the central directory and one entry's compressed bytes at a time. +pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Write) -> Result<(), String> { let too_big = || "the archive is too large for a zip file".to_string(); + let failed = |e: std::io::Error| e.to_string(); let count = u16::try_from(entries.len()).map_err(|_| too_big())?; - let mut out = Vec::new(); + // How much of the archive is written: where the next entry starts. + let mut written: usize = 0; let mut central = Vec::new(); for (name, data) in entries { let n = name.as_bytes(); @@ -47,7 +57,7 @@ pub fn write(entries: &[(String, Vec)]) -> Result, String> { let crc = crc32(data); let z = miniz_oxide::deflate::compress_to_vec(data, 6); let (method, body): (u16, &[u8]) = if z.len() < data.len() { (8, &z) } else { (0, data) }; - let offset = u32::try_from(out.len()).map_err(|_| too_big())?; + let offset = u32::try_from(written).map_err(|_| too_big())?; let body_len = u32::try_from(body.len()).map_err(|_| too_big())?; let header = |sig: u32, central: bool| { let mut h = Vec::new(); @@ -75,21 +85,23 @@ pub fn write(entries: &[(String, Vec)]) -> Result, String> { h.extend_from_slice(n); h }; - out.extend_from_slice(&header(0x0403_4B50, false)); - out.extend_from_slice(body); + let local = header(0x0403_4B50, false); + out.write_all(&local).map_err(failed)?; + out.write_all(body).map_err(failed)?; + written = written.saturating_add(local.len()).saturating_add(body.len()); central.extend_from_slice(&header(0x0201_4B50, true)); } - let cd_offset = u32::try_from(out.len()).map_err(|_| too_big())?; + let cd_offset = u32::try_from(written).map_err(|_| too_big())?; let cd_len = u32::try_from(central.len()).map_err(|_| too_big())?; - out.extend_from_slice(¢ral); - out.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); - out.extend_from_slice(&[0, 0, 0, 0]); - out.extend_from_slice(&count.to_le_bytes()); - out.extend_from_slice(&count.to_le_bytes()); - out.extend_from_slice(&cd_len.to_le_bytes()); - out.extend_from_slice(&cd_offset.to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - Ok(out) + let mut end = central; + end.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); + end.extend_from_slice(&[0, 0, 0, 0]); + end.extend_from_slice(&count.to_le_bytes()); + end.extend_from_slice(&count.to_le_bytes()); + end.extend_from_slice(&cd_len.to_le_bytes()); + end.extend_from_slice(&cd_offset.to_le_bytes()); + end.extend_from_slice(&0u16.to_le_bytes()); + out.write_all(&end).map_err(failed) } fn u16_at(b: &[u8], i: usize) -> Option { diff --git a/crates/engine/src/cmd/block_model.rs b/crates/engine/src/cmd/block_model.rs index f0ba7c7a68..f39b570e92 100644 --- a/crates/engine/src/cmd/block_model.rs +++ b/crates/engine/src/cmd/block_model.rs @@ -72,8 +72,9 @@ fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { /// progress and Cancel, as an export is (`exports::IN_BACKGROUND`), since it waits for elevation /// tiles and draws a texture of up to 8192 pixels a side. pub(crate) fn export_work(s: &Session, p: &Value) -> Result { - if cfg!(target_arch = "wasm32") { - return Err("exporting a block needs the desktop app".into()); + // Refused where files are downloaded: the web app doesn't wait for elevation tiles ([`read_ground`]). + if s.downloads_files() { + return Err("the web app can't export a block; open the project in the desktop app and export it there".into()); } let path = ps(p, "path").ok_or("path is required (a .glb, or a .gltf with everything embedded)")?.to_string(); let lower = path.to_ascii_lowercase(); diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index ef8f198358..28ed400fd9 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -5,7 +5,17 @@ //! [`export_land`] says what was written, as the command would have. The admitted operation owns //! preparation, file commit and delivery; a completed write remains written even if delivery //! is subsequently refused. +//! +//! The browser has no filesystem to write a path in ([`Session::downloads_files`]): there +//! [`write_here`] names the export after the path's file, its work gives the bytes back instead +//! of writing them ([`place`]), and the front end offers them as a download, as it does a tool's +//! file output (`gp.fileDelivered`). +use std::borrow::Cow; +use std::sync::Arc; + +use rustgis_data::Dataset; +use rustgis_data::capped::Limit; use serde_json::Value; use crate::{CmdResult, Session}; @@ -21,7 +31,11 @@ pub struct Wrote { /// Source failures to report if delivery cannot update their live layers. pub(crate) refused_notes: Vec, /// A physical write completed, even if authority to deliver its result is later refused. + /// With `download` it is the download's name, and nothing is written yet. pub(crate) written_path: Option, + /// The file's bytes when it is downloaded rather than written ([`place`]): what it says + /// (`notes`, `then`) is said once the front end has taken the download. + pub(crate) download: Option>>, /// What it does to the session once written, after its notes, and adds to its answer (a /// GeoPackage table replaced: the layers reading it read it again). pub(crate) then: Option, @@ -35,7 +49,8 @@ pub struct Wrote { } impl Wrote { - fn completion_notes(&self) -> Vec { + /// What it will say or has said of the file, as plain text. + pub(crate) fn completion_notes(&self) -> Vec { self.notes .texts() .chain(self.diagnostics.iter().map(|(_, text)| text.as_str())) @@ -78,6 +93,116 @@ pub fn runs_in_background(command: &str) -> Option<(&'static str, &'static str)> IN_BACKGROUND.iter().find(|(c, ..)| *c == command).map(|(c, name, _)| (*c, *name)) } +/// Puts an export's finished file where it goes: written at `path`, or, when it is downloaded +/// (`download`, [`Session::downloads_files`]), given back for [`Wrote::download`]. The bytes are +/// never copied: a file a layer holds is shared with the download. +pub(crate) fn place(download: bool, path: &str, bytes: impl Into>>) -> Result>>, String> { + let bytes = bytes.into(); + if download { + return Ok(Some(bytes)); + } + rustgis_data::io::write_atomic(std::path::Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; + Ok(None) +} + +/// The most files that wait for download at once. +pub(crate) const MAX_DOWNLOADS: usize = 8; + +/// The room for one more download: what the files waiting leave of the most bytes they may hold +/// in all ([`Session::download_room`]). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Room { + pub(crate) bytes: usize, + /// What the files already waiting hold. + pub(crate) waiting: usize, +} + +impl Room { + /// Why `path`'s file, stopped as it passed the room, can't be downloaded, and what to do. + pub(crate) fn refusal(self, path: &str) -> String { + let cap = mib(self.bytes.saturating_add(self.waiting)); + let ways = "export less (a selection of features, a smaller size or fewer pages), use the Export buttons, or use the desktop app"; + if self.waiting == 0 { + format!("{path}: stopped once the file passed the {cap} MiB a command can download in the browser; {ways}") + } else { + format!( + "{path}: stopped once the file passed what is left of the {cap} MiB that downloads can hold in the browser, {} MiB of it taken by those already waiting; split the task, model, or script into smaller runs, {ways}", + mib(self.waiting) + ) + } + } + + /// `path`'s file as `make` encodes it, stopped as soon as it passes the room, so no more of + /// it is ever held. + pub(crate) fn encode(self, path: &str, make: impl FnOnce(&Limit) -> rustgis_data::Result) -> Result { + let limit = Limit::new(self.bytes); + make(&limit).map_err(|e| if limit.passed() { self.refusal(path) } else { format!("{path}: {e}") }) + } +} + +/// `bytes` in MiB, rounded up. +pub(crate) fn mib(bytes: usize) -> usize { + bytes.div_ceil(1 << 20) +} + +/// The most feature storage a layer read in place may take while its download is made, and the +/// most the files waiting for download may hold. The features and the file are held at once, in +/// the browser's memory. A fixed figure: the browser can't say what memory it has free, so +/// `rustgis_data::memory::planned` would give its floor there. +pub(crate) const MAX_DOWNLOAD_BYTES: usize = 256 << 20; + +/// Every feature of layer `l`, read in place, for a file made in memory to be downloaded: refused +/// past [`MAX_DOWNLOAD_BYTES`] of features, before any is read when the source's count alone says +/// so. A definition query is applied after the read, so it doesn't make the read smaller. +pub(super) fn read_for_download(l: &rustgis_map::Layer) -> Result<(Dataset, rustgis_map::Unreadable), String> { + let refusal = format!( + "{}: the layer needs more than the {} MiB of features the web app reads for a download; zoom in, select the features you need, use Make Layer From Selected Features and export that layer, or use the desktop app", + l.name, + MAX_DOWNLOAD_BYTES >> 20 + ); + l.load_all_counted_up_to(MAX_DOWNLOAD_BYTES as u64, &refusal) +} + +/// Export `command`'s parameters when its file is downloaded: `path` cut to the download's name, +/// with what to say of that once it is downloaded. A Shapefile, several files, is downloaded as +/// a `.zip`. Refused here, before anything is read, for a path with no file name and for the +/// formats the browser can't write. +fn for_download<'a>(command: &str, p: &'a Value) -> Result<(Cow<'a, Value>, Vec), String> { + // No path, or parameters that aren't an object: the export says what it needs. + let Some(path) = super::ps(p, "path") else { return Ok((Cow::Borrowed(p), Vec::new())) }; + let mut name = path.rsplit(['/', '\\']).next().unwrap_or_default().to_string(); + if matches!(name.as_str(), "" | "." | "..") { + return Err(format!( + "{path}: the browser downloads an export under the file name its path ends in, and this one has none; end it in a name such as map.png" + )); + } + let folder = name != path; + let mut notes = Vec::new(); + if matches!(command, "share.exportLayer" | "share.exportTable") { + let named = std::path::Path::new(&name); + match named.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase().as_str() { + "gpkg" | "fgb" => { + return Err(format!( + "{path}: the web app can't write GeoPackage or FlatGeobuf files; export to .geojson, .csv, .parquet, .zip (a Shapefile), .kml, .kmz or .gpx, which it downloads, or use the desktop app" + )); + } + "shp" => { + name = named.with_extension("zip").to_string_lossy().into_owned(); + notes.push(format!("{name}: a Shapefile is several files, so the browser downloads them in one .zip")); + } + _ => {} + } + } + if folder { + notes.push(format!("{name}: the browser chooses where downloads go, so the folder in '{path}' wasn't used")); + } + let mut p = p.clone(); + if let Some(params) = p.as_object_mut() { + params.insert("path".into(), Value::String(name)); + } + Ok((Cow::Owned(p), notes)) +} + /// Background exports that render map, layout, report, or scene text with installed fonts. fn uses_fonts(command: &str) -> bool { matches!(command, "share.exportMap" | "layout.export" | "report.export" | "map.exportOrbit" | "map.exportBlock") @@ -96,12 +221,18 @@ fn cjk_scan_pending() -> bool { rustgis_render::fonts::cjk_roots_pending() } -/// `command`'s export written here: it says what it wrote. +/// `command`'s export written here: it says what it wrote. Where files are downloaded +/// ([`Session::downloads_files`]) it answers that the download is pending instead, and says what +/// it wrote when the front end acknowledges it. pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult { let &(_, name, start) = IN_BACKGROUND.iter().find(|(c, ..)| *c == command).ok_or_else(|| format!("{command} isn't an export"))?; if uses_fonts(command) && cjk_scan_pending() { return Err("CJK font folder scan is still running; try exporting again in a moment".into()); } + // Only an export that takes a path is named after it (Publish to Source writes the layer's + // own source, and says itself what the browser can't do). + let takes_path = s.registry.get(command).and_then(|c| c.param_keys()).is_some_and(|keys| keys.contains(&"path")); + let (p, renamed) = if s.downloads_files() && takes_path { for_download(command, p)? } else { (Cow::Borrowed(p), Vec::new()) }; let owner = s.continuation()?; owner.check()?; let current = owner.clone(); @@ -109,7 +240,7 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult // The probe keeps authority checks at file commit even when the user cannot cancel this run. let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() }; let (mut wrote, pending_cjk) = crate::render::rustgis_tiles::cache::with_still(still, || { - let work = start(s, p)?; + let work = start(s, &p)?; if uses_fonts(command) { let (res, hit) = rustgis_render::fonts::track_pending_cjk(|| written_under(name, &control, work)); Ok::<_, String>((res?, hit)) @@ -123,8 +254,17 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing.".into(), )); } - s.check_continuation(&owner) - .map_err(|why| completion_with_notes(command, wrote.written_path.as_deref(), &wrote.completion_notes(), why))?; + s.check_continuation(&owner).map_err(|why| { + // A download not yet offered wrote nothing. + let written = wrote.written_path.as_deref().filter(|_| wrote.download.is_none()); + completion_with_notes(command, written, &wrote.completion_notes(), why) + })?; + if wrote.download.is_some() { + for (i, note) in renamed.into_iter().enumerate() { + wrote.notes.insert(i, note); + } + return super::gp::queue_export(s, wrote); + } said(s, wrote) } @@ -164,7 +304,7 @@ fn written_under(name: &str, control: &std::sync::Arc CmdResult { +pub(super) fn said(s: &mut Session, wrote: Wrote) -> CmdResult { let Wrote { mut answer, notes, diagnostics, then, written_path, .. } = wrote; let mark = s.notice_mark(); say(s, diagnostics); @@ -303,6 +443,8 @@ pub(crate) fn drawn( diagnostics: notices, refused_notes, written_path, + // Its caller's, which placed the file ([`place`]). + download: None, then: Some(then), #[cfg(not(target_arch = "wasm32"))] owner: None, @@ -546,6 +688,7 @@ mod tests { refused_notes: Vec::new(), notes: ["Exported x"].into_iter().collect(), written_path: Some("x".into()), + download: None, then: None, #[cfg(not(target_arch = "wasm32"))] owner: None, diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 52ac809cd6..5dceb6d7b2 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -669,6 +669,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result bool { spec.params.iter().any(|p| matches!(p.kind, rustgis_analysis::ParamKind::SaveFile { .. })) } -/// A browser file export waiting for delivery, without a success record until acknowledged. +/// A browser file waiting for delivery: a tool's output, without a success record until +/// acknowledged, or an export's file, which says what it wrote only then. pub(crate) struct PendingFile { pub(crate) continuation: crate::policy::Continuation, pub(crate) id: u64, pub(crate) file_name: String, - pub(crate) bytes: Option>, - record: GpRecord, - losses: Vec, + /// Shared with whatever else holds the file (a raster layer its own), until handed over. + pub(crate) bytes: Option>>, + from: Delivery, +} + +impl PendingFile { + /// Whether an export command made it ([`queue_export`]). + pub(crate) fn is_export(&self) -> bool { + matches!(self.from, Delivery::Export(_)) + } } +/// What a pending file's acknowledgment completes. +enum Delivery { + #[cfg_attr(not(any(target_arch = "wasm32", test)), expect(dead_code, reason = "the desktop writes a tool's file output itself"))] + Tool { record: Box, losses: Vec }, + /// What the export says and does once its file is out, its bytes moved to the queue. + Export(Box), +} + +/// Queues a tool's file output for download under the name its `output` parameter gives (a name, +/// not a path), else the tool's own. #[cfg(any(target_arch = "wasm32", test))] fn queue_file(s: &mut Session, file_name: String, bytes: Vec, record: GpRecord, losses: Vec) -> CmdResult { let file_name = @@ -3824,26 +3844,79 @@ fn queue_file(s: &mut Session, file_name: String, bytes: Vec, record: GpReco if file_name.is_empty() || file_name.contains(['/', '\\']) { return Err("output must be a file name, not a path, in the browser".into()); } - const MAX_PENDING_BYTES: usize = 256 * 1024 * 1024; - let held = s.file_outputs.iter().filter_map(|f| f.bytes.as_ref()).map(Vec::len).sum::(); - if s.file_outputs.len() >= 8 || bytes.len() > MAX_PENDING_BYTES.saturating_sub(held) { - return Err("file export queue limit reached (8 files or 256 MiB); split the task, model, or script into smaller runs".into()); + queue(s, file_name, Arc::new(bytes), Delivery::Tool { record: Box::new(record), losses }) +} + +/// Queues an export's file for download under its name (`written_path`). The answer says it is +/// pending, with what the file will say, for a caller that reads no notices later. +pub(super) fn queue_export(s: &mut Session, mut wrote: super::exports::Wrote) -> CmdResult { + let (Some(bytes), Some(file_name)) = (wrote.download.take(), wrote.written_path.clone()) else { + return Err("this export made no file to download".into()); + }; + // Not exported until the download is taken: the claim goes from the pending answer, and what + // follows it (what the file leaves out) stays, under the file's name. + let exported = format!("Exported {file_name}"); + let messages: Vec = wrote + .completion_notes() + .into_iter() + .filter_map(|message| match message.strip_prefix(&exported) { + Some("") => None, + Some(note) if note.starts_with([' ', ';']) => Some(format!("{file_name}{note}")), + _ => Some(message), + }) + .collect(); + let mut out = queue(s, file_name, bytes, Delivery::Export(Box::new(wrote)))?; + out["messages"] = json!(messages); + Ok(out) +} + +/// Why no more can wait for download, of the `cap` bytes that waiting files may hold in all. +pub(crate) fn queue_full(cap: usize) -> String { + format!( + "file export queue limit reached ({} files or {} MiB); split the task, model, or script into smaller runs", + super::exports::MAX_DOWNLOADS, + super::exports::mib(cap) + ) +} + +/// Holds `bytes` for the front end to offer as the download `file_name` and acknowledge with +/// `gp.fileDelivered`, within what the queue holds. +fn queue(s: &mut Session, file_name: String, bytes: Arc>, from: Delivery) -> CmdResult { + use super::exports::{MAX_DOWNLOADS, mib}; + // A file held only here gives back its spare room first: an encoder's buffer can be twice + // its length. One shared (a raster layer's own file) counts whole. + let bytes = match Arc::try_unwrap(bytes) { + Ok(mut file) => { + file.shrink_to_fit(); + Arc::new(file) + } + Err(shared) => shared, + }; + let cap = s.download_cap(); + let held = s.waiting_download_bytes(); + // An export whose writer takes a limit was stopped at it; this is what holds the others (a + // picture, an SVG, a PDF past its pages, the file a raster layer holds) to it. + // Measured as the queue counts what waits: by what the file holds, its spare room included. + let size = bytes.capacity(); + if matches!(from, Delivery::Export(_)) && size > cap { + return Err(format!( + "{file_name}: {} MiB, more than the {} MiB a command can download in the browser; export less (a selection of features, a smaller size or fewer pages), use the Export buttons, or use the desktop app", + mib(size), + mib(cap) + )); + } + if s.waiting_download_count() >= MAX_DOWNLOADS || size > cap.saturating_sub(held) { + return Err(queue_full(cap)); } s.next_pending = s.next_pending.wrapping_add(1); let id = s.next_pending; - s.file_outputs.push(PendingFile { - id, - file_name: file_name.clone(), - bytes: Some(bytes), - record, - losses, - continuation: s.continuation()?, - }); + s.file_outputs.push(PendingFile { id, file_name: file_name.clone(), bytes: Some(bytes), from, continuation: s.continuation()? }); s.request_only = true; Ok(json!({"pending": true, "download": id, "file": file_name})) } -/// Records a completed file delivery through the generated-message history seam. +/// Records a completed file delivery: a tool's through the generated-message history seam, an +/// export's by saying what it wrote. fn file_delivered(s: &mut Session, p: &Value) -> CmdResult { let id = p.get("id").and_then(Value::as_u64).ok_or("id is required")?; let i = s.file_outputs.iter().position(|f| f.id == id).ok_or("no pending file with that id")?; @@ -3851,32 +3924,49 @@ fn file_delivered(s: &mut Session, p: &Value) -> CmdResult { if s.file_outputs[i].bytes.is_some() { return Err("the file has not been handed to the download service".into()); } - let mut file = s.file_outputs.remove(i); + let file = s.file_outputs.remove(i); let error = p.get("error").and_then(Value::as_str); - file.record.ok = error.is_none(); - if let Some(error) = error { - file.record.messages.push(error.to_string()); - } if let Some(report) = &mut s.model_run { report.file_delivered(id, error); } - for message in &file.record.messages { - if file.record.ok { + let (mut record, losses) = match file.from { + Delivery::Tool { record, losses } => (*record, losses), + Delivery::Export(wrote) => { + // An export leaves the project as it is: no Undo step for finishing one. + s.request_only = true; + let mut out = match error { + None => super::exports::said(s, *wrote)?, + Some(error) => { + s.notify(error.to_string(), true); + json!({"messages": [error]}) + } + }; + out["file"] = json!(file.file_name); + out["delivered"] = json!(error.is_none()); + return Ok(out); + } + }; + record.ok = error.is_none(); + if let Some(error) = error { + record.messages.push(error.to_string()); + } + for message in &record.messages { + if record.ok { s.notify_written(message.clone()); } else { s.notify(message.clone(), true); } } - for loss in file.losses { - if file.record.ok { + for loss in losses { + if record.ok { publish_tool_loss(s, loss.code, &loss.text, true); } else { s.notify(loss.text.clone(), true); } - file.record.messages.push(loss.text); + record.messages.push(loss.text); } - let out = json!({"file": file.file_name, "delivered": file.record.ok, "messages": file.record.messages}); - s.push_gp_record(file.record); + let out = json!({"file": file.file_name, "delivered": record.ok, "messages": record.messages}); + s.push_gp_record(record); if s.project.gp_history.len() > 500 { s.project.gp_history.remove(0); } @@ -4253,7 +4343,7 @@ mod file_tests { assert_eq!(files.len(), 1); assert_eq!(files[0].1, "Elevation.pmtiles"); assert!(files[0].2.starts_with(b"PMTiles\x03")); - assert_eq!(files[0].2, expected, "layer and group transparency are both applied"); + assert_eq!(*files[0].2, expected, "layer and group transparency are both applied"); assert_eq!(s.map().layers.len(), 1); assert!( s.run("gp.run", &json!({"tool": "rasterToPmtiles", "params": {"input": "Elevation", "minZoom": 2, "maxZoom": 1}})).is_err() @@ -4279,6 +4369,21 @@ mod file_tests { s.run("test.queueFile", &json!({"name":name,"bytes":bytes,"record":record})) } + /// A file queued with spare room (an encoder's buffer) gives it back before it is admitted, + /// so what waits never passes the limit the queue counts it against. + #[test] + fn a_queued_file_is_held_to_the_limit_by_what_it_holds() { + let mut s = Session::new(crate::Project::default()); + s.download_cap = Some(50); + s.registry.commands.push(C::new("test.queueRoomy", "File export", "Test", |s, _| { + let mut file = Vec::with_capacity(100); + file.extend_from_slice(&[7; 10]); + super::queue_file(s, "roomy.bin".into(), file, record(), Vec::new()) + })); + assert_eq!(s.run("test.queueRoomy", &Value::Null).unwrap()["pending"], true); + assert_eq!(s.waiting_download_bytes(), 10); + } + fn record() -> GpRecord { GpRecord { tool: "File export".into(), @@ -4472,7 +4577,7 @@ mod file_tests { assert!(s.project.gp_history.is_empty()); assert!(s.run("gp.fileDelivered", &json!({"id": id})).is_err()); assert!(s.project.gp_history.is_empty()); - assert_eq!(s.take_gp_files(), vec![(id, "cities.pmtiles".into(), vec![1, 2, 3])]); + assert_eq!(s.take_gp_files(), vec![(id, "cities.pmtiles".into(), std::sync::Arc::new(vec![1, 2, 3]))]); assert!(s.take_gp_files().is_empty(), "bytes are handed over once"); let out = s.run("gp.fileDelivered", &json!({"id": id, "error": "browser rejected download"})).unwrap(); assert_eq!(out["delivered"], false); diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index d48463674a..9850bc1c87 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -29,10 +29,26 @@ pub fn layout_bytes_with( all: bool, georeference: bool, options: rustgis_render::pdf::Options, +) -> Result, String> { + layout_bytes_for(s, li, pdf, dpi, all, georeference, options, None) +} + +/// [`layout_bytes_with`] for a file that may be downloaded to the path given: a PDF's pages are +/// then held to that room too, and stopped as they pass it. +#[expect(clippy::too_many_arguments, reason = "the export's own settings")] +fn layout_bytes_for( + s: &mut Session, + li: usize, + pdf: bool, + dpi: f64, + all: bool, + georeference: bool, + options: rustgis_render::pdf::Options, + download: Option<(crate::cmd::exports::Room, &str)>, ) -> Result, String> { let layout = s.project.layouts.get(li).ok_or("no layout")?; let revisions = rustgis_render::layout::archive_revisions(layout, &s.project.maps); - let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference, options); + let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference, options, download); let layout = s.project.layouts.get(li).ok_or("no layout")?; revisions.finish_revision( rustgis_render::layout::archive_revisions(layout, &s.project.maps), @@ -108,6 +124,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( all: bool, georeference: bool, options: rustgis_render::pdf::Options, + download: Option<(crate::cmd::exports::Room, &str)>, ) -> Result, String> { let saved = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&saved) { @@ -194,6 +211,11 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( out.push(rustgis_render::pdf::Page::drawing(drawing, w, h).with_viewports(geo.viewports)); } held += out.last().map_or(0, rustgis_render::pdf::Page::len); + if let Some((room, path)) = download + && held > room.bytes + { + return Err(room.refusal(path)); + } if held > PDF_BUDGET { return Err(format!( "the PDF passed {} MB at page {}; export at a lower dpi, or fewer pages", @@ -421,21 +443,26 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result<(&rustgis_data::sync::Synced, &str), /// and its record is of the files written and those rows, so it reads `inSync`; the project then /// has a change to save. pub(crate) fn publish_work(s: &Session, p: &Value) -> Result { + const WEB: &str = "the web app can't write files on this computer; publish from the desktop app"; let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("the layer no longer exists")?; + // The layer's own source is written, not a path a download could be named after. + if s.downloads_files() { + return Err(WEB.into()); + } let (synced, path) = record(l)?; #[cfg(target_arch = "wasm32")] { let _ = (synced, path); - Err("the web app can't write files on this computer".into()) + Err(WEB.into()) } #[cfg(not(target_arch = "wasm32"))] { @@ -92,6 +97,7 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result Result Result Result<(Doc, Vec Result<(Vec, usize), String> { let name = s.project.reports.get(i).map(|r| r.name.clone()).unwrap_or_default(); - let (bytes, mut copy) = whole_bytes(detached(&s.project), s.path.clone(), i, dpi, pdf); + let (bytes, mut copy) = whole_bytes(detached(&s.project), s.path.clone(), i, dpi, pdf, None); super::exports::say_coded(s, super::exports::copy_notices_coded(&mut copy, &name)); bytes } @@ -1038,17 +1038,21 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result, ) -> (Result<(Vec, usize), String>, Session) { let mut copy = Session::new(project); copy.path = path; - let bytes = whole_copy(&mut copy, i).and_then(|()| drawn_bytes(&mut copy, i, dpi, pdf)); + let bytes = whole_copy(&mut copy, i).and_then(|()| drawn_bytes(&mut copy, i, dpi, pdf, download)); (bytes, copy) } @@ -1138,7 +1143,13 @@ pub(crate) fn reported_layers(input: &impl super::InputSource, i: usize) -> Vec< /// The report as a PDF (every page) or a PNG (the first page), and its page count, drawn from /// the features `s`'s layers hold. -fn drawn_bytes(s: &mut Session, i: usize, dpi: f64, pdf: bool) -> Result<(Vec, usize), String> { +fn drawn_bytes( + s: &mut Session, + i: usize, + dpi: f64, + pdf: bool, + download: Option<(super::exports::Room, &str)>, +) -> Result<(Vec, usize), String> { let (doc, pages) = pages(s, i)?; let revision = |s: &Session| { pages @@ -1152,7 +1163,7 @@ fn drawn_bytes(s: &mut Session, i: usize, dpi: f64, pdf: bool) -> Result<(Vec, ) -> Result<(Vec, usize), String> { let n = if pdf { pages.len() } else { 1 }; let mut out = Vec::new(); @@ -1206,6 +1218,12 @@ fn report_pages_bytes( out.push(page); } held += out.last().map_or(0, rustgis_render::pdf::Page::len); + // Where the file is downloaded, its pages are held to the room it has too. + if let Some((room, path)) = download + && held > room.bytes + { + return Err(room.refusal(path)); + } if held > PDF_BUDGET { return Err(format!("the PDF passed {} MB at page {}; export at a lower dpi", PDF_BUDGET >> 20, k + 1)); } diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 68ff574617..d0c0bedf2f 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -12,7 +12,7 @@ use rustgis_data::raster::Crs; use rustgis_render::View; use serde_json::{Value, json}; -use super::exports::{Work, Wrote}; +use super::exports::{Room, Work, Wrote}; use super::{f, need_layer, ps}; use crate::{CommandSpec as C, Session}; @@ -421,15 +421,18 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { return Err("cog is for a GeoTIFF (.tif or .tiff) export".into()); } let (mut map, view_size) = (s.map().detached(), s.view_size); + let download = s.download_room()?.is_some(); Ok(Box::new(move || { let mut shadows = Vec::new(); + let mut held = None; let written = (|| { let (png, said) = rustgis_render::shadows_said(|| png_of(&mut map, view_size, width, height, dpi)); let png = png?; shadows = shadow_warnings(&path, &said); rustgis_data::progress::check().map_err(|e| e.to_string())?; - rustgis_data::io::write_atomic(Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path, "bytes": png.len()})) + let bytes = png.len(); + held = super::exports::place(download, &path, png)?; + Ok(json!({"path": path, "bytes": bytes})) })(); // What the size limit did, and layers drawn without their cast shadows, are said of a // file written. @@ -439,7 +442,7 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { } else { Vec::new() }; - super::exports::drawn(std::slice::from_ref(&map), sized, written, path) + super::exports::drawn(std::slice::from_ref(&map), sized, written, path).map(|wrote| Wrote { download: held, ..wrote }) })) } @@ -487,8 +490,10 @@ fn geotiff_work( fits_pixels(&view, turned)?; let name = m.name.clone(); let mut map = m.detached(); + let download = s.download_room()?; Ok(Box::new(move || { let mut notices = notices; + let mut held = None; let written = (|| { let placed = rustgis_render::render_placed(&mut map, &view)?; rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -502,14 +507,24 @@ fn geotiff_work( r.copyright = (!credits.is_empty()).then(|| credits.join(" | ")); rustgis_data::progress::check().map_err(|e| e.to_string())?; let (bytes, tiled) = if cog { - // Tiles go to the file as they are made; its tiling is in the answer, as Export - // Raster gives it. - let c = rustgis_data::raster::cogwrite::write_file(&r, 0, Path::new(&path)).map_err(|e| format!("{path}: {e}"))?; + // Tiles go to the file as they are made (a download holds them all); its tiling + // is in the answer, as Export Raster gives it. + let c = if let Some(room) = download { + let (bytes, c) = room.encode(&path, |limit| rustgis_data::raster::cogwrite::write_with_info_within(&r, 0, limit))?; + held = Some(std::sync::Arc::new(bytes)); + c + } else { + rustgis_data::raster::cogwrite::write_file(&r, 0, Path::new(&path)).map_err(|e| format!("{path}: {e}"))? + }; (c.bytes, Some(json!({"overviews": c.levels.len().saturating_sub(1), "bigTiff": c.big}))) } else { - let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| format!("{path}: {e}"))?; - rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - (bytes.len() as u64, None) + let bytes = match download { + Some(room) => room.encode(&path, |limit| rustgis_data::raster::geotiff::write_within(&r, 0, limit))?, + None => rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| format!("{path}: {e}"))?, + }; + let len = bytes.len() as u64; + held = super::exports::place(download.is_some(), &path, bytes)?; + (len, None) }; let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); if let Some(t) = tiled { @@ -531,7 +546,7 @@ fn geotiff_work( if written.is_ok() { notices.splice(0..0, sized); } - super::exports::drawn(std::slice::from_ref(&map), notices, written, path) + super::exports::drawn(std::slice::from_ref(&map), notices, written, path).map(|wrote| Wrote { download: held, ..wrote }) })) } @@ -626,9 +641,10 @@ pub(crate) fn layer_work(s: &Session, p: &Value) -> Result { let compatibility = ps(p, "crs").and_then(|text| asked.and_then(|crs| rustgis_data::raster::wkt::typed_crs_note(text, crs))); let (boxes, map) = (s.constructions.clone(), s.map().instance_id()); let project = s.project.coordinate_system; + let download = s.download_room()?; Ok(Box::new(move || { let note = boxes.export_notes(map, &l)?; - let mut wrote = write_layer(&l, &path, asked, project, gpkg)?; + let mut wrote = write_layer(&l, &path, asked, project, gpkg, download)?; wrote.notes.extend(note); if let Some(note) = compatibility { wrote.notes.insert(0, format!("crs: {note}")); @@ -693,7 +709,16 @@ pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec /// Writes layer `l` to `path`, in `asked` or the system the format defaults to (the project's, /// `project`, for a layer with none of its own); a GeoPackage's table goes where `gpkg` says. -fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: Option, gpkg: GpkgTable) -> Result { +/// With `download`, the file is made in memory, within that room, and given back instead +/// ([`Wrote::download`]). +fn write_layer( + l: &rustgis_map::Layer, + path: &str, + asked: Option, + project: Option, + gpkg: GpkgTable, + download: Option, +) -> Result { let ext = Path::new(&path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); // A layer read in place from the GeoPackage it goes into is read whole first: SQLite can't // write a file while the same export is reading it. @@ -701,10 +726,13 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: && l.source.as_ref().and_then(|src| src.path.as_deref()).is_some_and(|src| same_file(Path::new(src), Path::new(&path))); // A streamed layer exports its whole source, not the features read for the view: a chunk at // a time where the source and format allow, so its size isn't limited by memory. - let chunks = if l.is_streamed() && rustgis_data::export::streams(&ext) && !from_target { l.chunk_export()? } else { None }; + // A download is made whole, in memory. + let chunks = + if download.is_none() && l.is_streamed() && rustgis_data::export::streams(&ext) && !from_target { l.chunk_export()? } else { None }; + let mut held = None; use std::borrow::Cow; let (mut whole, unreadable) = if l.is_streamed() && chunks.is_none() { - let (dataset, unreadable) = l.load_all_counted()?; + let (dataset, unreadable) = if download.is_some() { super::exports::read_for_download(l)? } else { l.load_all_counted()? }; (Cow::Owned(dataset), unreadable) } else { (Cow::Borrowed(&l.dataset), rustgis_map::Unreadable::default()) @@ -779,8 +807,14 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: .map_err(|e| e.to_string())?; // The layer's box in longitude/latitude comes back with the write, taken from the places // converted for the file when it is written there, so each is converted once. - let (left_out, table, placed, lonlat) = - rustgis_data::io::write_path_placed(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; + let (left_out, table, placed, lonlat) = if let Some(room) = download { + let (bytes, left_out, notes, lonlat) = + room.encode(path, |limit| rustgis_data::io::write_bytes_noted_within(ds, &ext, crs, path, limit))?; + held = Some(std::sync::Arc::new(bytes)); + (left_out, None, notes, lonlat) + } else { + rustgis_data::io::write_path_placed(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())? + }; lonlat_extent = Some(lonlat); // Old parts of a Shapefile written over that couldn't be removed. format_notes.extend(placed); @@ -865,6 +899,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: refused_notes, notes: said, written_path, + download: held, then, #[cfg(not(target_arch = "wasm32"))] owner: None, diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index bffdef6461..2b9c7ae300 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -153,6 +153,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result let gpkg = super::gpkg_table(p, &ext)?; let mut ds = s.project.tables.get(s.table_index(p)?).ok_or("no such table")?.dataset.clone(); let (sort, limit) = options(&ds, p)?; + let download = s.download_room()?; Ok(Box::new(move || { let omitted = ordered(&mut ds, &sort, limit)?; let default = ds.name.clone(); @@ -173,8 +174,16 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result notes.extend(super::gpkg_dates_note(&ds, &ext, &path)); let name_field = rustgis_data::io::name_field(&ds); notes.extend(rustgis_data::io::export_losses_notes(&ds, &ext, name_field, &path).map_err(|e| e.to_string())?); - let (left_out, table, placed) = - rustgis_data::io::write_path_to(&ds, Path::new(&path), rustgis_data::raster::Crs::LonLat, &gpkg).map_err(|e| e.to_string())?; + let crs = rustgis_data::raster::Crs::LonLat; + let mut held = None; + let (left_out, table, placed) = if let Some(room) = download { + let (bytes, left_out, notes, _) = + room.encode(&path, |limit| rustgis_data::io::write_bytes_noted_within(&ds, &ext, crs, &path, limit))?; + held = Some(std::sync::Arc::new(bytes)); + (left_out, None, notes) + } else { + rustgis_data::io::write_path_to(&ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())? + }; // Old parts of a Shapefile written over that couldn't be removed. notes.extend(placed); if let Some(note) = rustgis_data::io::left_out_note(&path, &ext, left_out) { @@ -201,6 +210,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result diagnostics: Vec::new(), refused_notes, written_path, + download: held, then: Some(Box::new(move |s, out| { if let Some(note) = omitted_note { let mark = s.notice_mark(); diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index fa5894b649..e43a5b0a53 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -246,9 +246,9 @@ fn orbit_params(p: &Value) -> Result { /// the copy left out is said by the session's own landing check (`notice_landed_rasters`, after /// each command and on each frame of the app), not frame by frame here. pub(crate) fn orbit_work(s: &Session, p: &Value) -> Result { - // Files are written by the desktop app; the browser's go through its services. - if cfg!(target_arch = "wasm32") { - return Err("exporting an orbit needs the desktop app".into()); + // Refused where files are downloaded: the web app draws no animations ([`super::time::animate`]). + if s.downloads_files() { + return Err("the web app can't export an orbit; open the project in the desktop app and export it there".into()); } let path = ps(p, "path").ok_or("path is required (a .gif, or a .zip of PNG frames)")?.to_string(); let lower = path.to_ascii_lowercase(); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b4fac8af81..3bedf52e8c 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2625,7 +2625,8 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { let construction_notes = s.constructions.export_notes(s.map().instance_id(), layer)?; let mut ds = Cow::Borrowed(feature_ds(s, p)?); let report = rustgis_data::export::filter_dataset(&mut ds, layer.definition_query.as_deref()).map_err(|e| e.to_string())?; - let (text, notes) = converted(&ds, p)?; + let (text, notes) = converted(&ds, p, None)?; + let text = String::from_utf8(text).map_err(|e| e.to_string())?; let null_numbers = rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, conversion_format(p)?); let target = ds.name.clone(); let query_note = super::share::query_export_note(&target, &layer.name, &report); @@ -2653,10 +2654,14 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Result 0 { notes.push(super::whole::unread_note(&path, unreadable.rows)); } notes.extend(super::share::read_notes(&path, &ds.name, &unreadable)); (notes, rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, format), report) }; - let bytes = std::fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?.len(); + let bytes = match &held { + Some(bytes) => bytes.len() as u64, + None => std::fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?.len(), + }; notes.extend(construction_notes); notes.push(format!("Exported {path}")); let target = path.clone(); @@ -2737,6 +2746,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Result<&str, String> { } } -/// Serializes a complete dataset and collects its loss notices for delivery after success. -fn converted(ds: &Dataset, p: &Value) -> Result<(String, rustgis_data::loss::Notes), String> { +/// Serializes a complete dataset and collects its loss notices for delivery after success. For a +/// `download`, the text is stopped as soon as it passes that room. +fn converted(ds: &Dataset, p: &Value, download: Option) -> Result<(Vec, rustgis_data::loss::Notes), String> { let name_field = ps(p, "nameField").and_then(|n| ds.field_index(n)).or_else(|| ds.fields.iter().position(|f| f.name.eq_ignore_ascii_case("name"))); let format = conversion_format(p)?; @@ -2763,12 +2774,10 @@ fn converted(ds: &Dataset, p: &Value) -> Result<(String, rustgis_data::loss::Not // in: the text and what it loses are read from the copy there. A feature with a place that // can't be given there is written without its geometry, and said. let (lonlat, unplaced) = ds.in_lonlat_leaving_out()?; - let text = match format { - "geojson" => rustgis_data::io::to_geojson_text(&lonlat).map_err(|e| e.to_string())?, - "csv" => rustgis_data::io::to_csv(&lonlat).map_err(|e| e.to_string())?, - "kml" => rustgis_data::interop::to_kml(&lonlat, name_field).map_err(|e| e.to_string())?, - "gpx" => rustgis_data::interop::to_gpx(&lonlat, name_field).map_err(|e| e.to_string())?, - _ => rustgis_data::interop::to_wkt_csv(&lonlat).map_err(|e| e.to_string())?, + let encode = |limit: &rustgis_data::capped::Limit| rustgis_data::io::text_bytes_within(&lonlat, format, name_field, limit); + let text = match download { + Some(room) => room.encode(ps(p, "path").unwrap_or(&ds.name), encode)?, + None => encode(&rustgis_data::capped::Limit::none()).map_err(|e| e.to_string())?, }; let target = ps(p, "path").unwrap_or(&ds.name); let mut notes = rustgis_data::export_notes([(ds, ds.lonlat_extent())], target, rustgis_data::raster::Crs::LonLat); diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 6dfbdcf6c9..e9345ee6b3 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -255,6 +255,12 @@ pub fn commands() -> Vec { C::new("offline.package", "Package for the Field", "Data › Offline", |s, p| { let written = s.notice_mark(); let path = super::ps(p, "path").ok_or("path is required")?.to_string(); + // Refused before the package, and its offline area, are made. + if s.downloads_files() { + return Err(format!( + "{path}: the web app can't write a field package to a path, from a script or the Assistant either; use Package for the Field on the ribbon, which downloads it" + )); + } super::field::not_the_project(s, std::path::Path::new(&path))?; let had = s.project.offline_areas.len(); let (area, bytes, notes) = super::field::package_output(s, p)?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5e481d8132..918148431f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1064,6 +1064,9 @@ pub struct Session { /// Exercises the browser delivery path with real tools in native engine tests. #[cfg(test)] queue_gp_files: bool, + /// A smaller limit than [`cmd::exports::MAX_DOWNLOAD_BYTES`] for a test to reach. + #[cfg(test)] + pub(crate) download_cap: Option, /// Asynchronous runs started and not yet complete: (id, job, resolved params, start time). #[cfg(feature = "geolibre")] pub(crate) started: Vec<(u64, rustgis_geolibre::Job, serde_json::Value, u64, policy::Continuation)>, @@ -1581,6 +1584,8 @@ impl Session { file_outputs: Vec::new(), #[cfg(test)] queue_gp_files: false, + #[cfg(test)] + download_cap: None, request_only: false, shared_steps: StepTally::default(), leave_downloads: false, @@ -1798,10 +1803,87 @@ impl Session { r } - /// Takes tool files awaiting download. Metadata stays until `gp.fileDelivered` acknowledges - /// delivery, so producing bytes alone never records a successful run. Another caller's - /// queued files stay untouched until their owner or the native host takes them. - pub fn take_gp_files(&mut self) -> Vec<(u64, String, Vec)> { + /// Whether the files commands make reach the user as downloads: the browser has no filesystem + /// to write a path in, so a tool's file output and an export queue their bytes for the front + /// end ([`Session::take_gp_files`]). + pub(crate) fn downloads_files(&self) -> bool { + #[cfg(test)] + if self.queue_gp_files { + return true; + } + cfg!(target_arch = "wasm32") + } + + /// The most bytes the files waiting for download may hold in all. + pub(crate) fn download_cap(&self) -> usize { + #[cfg(test)] + if let Some(cap) = self.download_cap { + return cap; + } + cmd::exports::MAX_DOWNLOAD_BYTES + } + + /// Where files are downloaded, the room for one more; `None` where they are written. Refused + /// when no more can wait, before any of it is made. + pub(crate) fn download_room(&self) -> Result, String> { + if !self.downloads_files() { + return Ok(None); + } + let waiting = self.waiting_download_bytes(); + let bytes = self.download_cap().saturating_sub(waiting); + if self.waiting_download_count() >= cmd::exports::MAX_DOWNLOADS || bytes == 0 { + return Err(cmd::gp::queue_full(self.download_cap())); + } + Ok(Some(cmd::exports::Room { bytes, waiting })) + } + + /// The files waiting for download: this project's, and those of a project a command replaced, + /// kept until the command ends in case it gives that project back. + fn waiting_downloads(&self) -> impl Iterator { + self.file_outputs.iter().chain(self.put_aside.iter().flat_map(|aside| aside.file_outputs.iter())) + } + + /// How many files wait for download, those put aside with a replaced project included. + pub(crate) fn waiting_download_count(&self) -> usize { + self.waiting_downloads().count() + } + + /// The bytes the files waiting for download hold, those put aside included. + pub(crate) fn waiting_download_bytes(&self) -> usize { + self.waiting_downloads().filter_map(|f| f.bytes.as_ref()).map(|bytes| bytes.capacity()).sum() + } + + /// Whether pending download `id` is an export's: no geoprocessing run records it. + pub fn is_export_file(&self, id: u64) -> bool { + self.file_outputs.iter().any(|file| file.id == id && file.is_export()) + } + + /// Says which queued downloads among `files` are dropped, and `why`: the exports in one + /// notice (the desktop would have written their files by now), the tools' file outputs in + /// another (a run is recorded only once its file is delivered, so these go unrecorded). + fn say_dropped_downloads<'a>(&mut self, files: impl IntoIterator, why: &str) { + let (exports, tools): (Vec<_>, Vec<_>) = files.into_iter().partition(|file| file.is_export()); + let names = |files: Vec<&cmd::gp::PendingFile>| files.iter().map(|file| file.file_name.clone()).collect::>(); + let (exports, tools) = (names(exports), names(tools)); + if !exports.is_empty() { + self.notify(format!("{} export(s) not downloaded, {why}: {}", exports.len(), listed(&exports)), true); + } + if !tools.is_empty() { + self.notify( + format!( + "{} tool output file(s) not downloaded, {why}, so their runs aren't in the geoprocessing history: {}", + tools.len(), + listed(&tools) + ), + true, + ); + } + } + + /// Takes tool and export files awaiting download. Metadata stays until `gp.fileDelivered` + /// acknowledges delivery, so producing bytes alone never records a successful run. Another + /// caller's queued files stay untouched until their owner or the native host takes them. + pub fn take_gp_files(&mut self) -> Vec<(u64, String, std::sync::Arc>)> { let mut live = Vec::new(); let mut refused: Vec<(String, Vec)> = Vec::new(); for mut file in std::mem::take(&mut self.file_outputs) { @@ -2457,6 +2539,8 @@ impl Session { }, _ => res, }; + // Queued for download in a project the command opened, then gave up for the one before. + let mut opened_files = Vec::new(); match (&res, snapshot) { // A command that only left a request for the front end (a download in the browser, // [`Session::request_url`]) changed nothing: no undo step, nothing to save yet. The @@ -2538,7 +2622,7 @@ impl Session { // Replaced during the command: what it held beside itself (its undo history, its // trust, its unsaved state) comes back with it. if self.opened != opened { - self.give_back(opened); + opened_files = self.give_back(opened); } if let Some(files) = files { self.file_identity = files.identity; @@ -2595,7 +2679,11 @@ impl Session { self.restore_url_request_checkpoint(requests); (self.plugin_retries, self.url_waits) = retry_state; // Keep only still-present old identities: drained bytes and terminal refusals stay consumed. - self.file_outputs.retain(|file| file_outputs.contains(&file.id)); + let (kept, mut dropped): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.file_outputs).into_iter().partition(|file| file_outputs.contains(&file.id)); + self.file_outputs = kept; + dropped.append(&mut opened_files); + self.say_dropped_downloads(&dropped, "as the command that made them failed"); } let quiet = std::mem::take(&mut self.quiet_failure); if let Err(e) = &res @@ -2605,7 +2693,9 @@ impl Session { } // The command, and those it ran, are done: a replaced project stays replaced. if self.depth == 0 { - self.put_aside = None; + if let Some(replaced) = self.put_aside.take() { + self.say_dropped_downloads(&replaced.file_outputs, "as another project replaced theirs first"); + } self.published_syncs.clear(); // Frame maintenance and some policy adapters run a guard without command dispatch. // Otherwise the command epilogue trims once, after any maintenance steps. @@ -2697,9 +2787,10 @@ impl Session { } /// Gives back what project `opened` held beside itself, when it is restored. Every field is - /// named (no `..`): one added to [`PutAside`] and not given back doesn't compile. - fn give_back(&mut self, opened: u64) { - let Some(a) = self.put_aside.take_if(|a| a.opened == opened) else { return }; + /// named (no `..`): one added to [`PutAside`] and not given back doesn't compile. Returns the + /// files waiting for download that those given back take the place of. + fn give_back(&mut self, opened: u64) -> Vec { + let Some(a) = self.put_aside.take_if(|a| a.opened == opened) else { return Vec::new() }; let PutAside { constructions, opened: _, @@ -2766,7 +2857,7 @@ impl Session { self.opened_package = opened_package; self.file_identity = file_identity; (self.pending, self.plugin_runs, self.plugin_retries, self.url_waits) = (pending, plugin_runs, plugin_retries, url_waits); - self.file_outputs = file_outputs; + let replaced = std::mem::replace(&mut self.file_outputs, file_outputs); (self.downloading, self.downloaded, self.url_requests) = (downloading, downloaded, url_requests); self.downloaded_reach = downloaded_reach; self.restore_policy_work(policy_work); @@ -2785,6 +2876,7 @@ impl Session { { self.sql_results = sql_results; } + replaced } /// Says what reading raster layers' pixels lost when it wasn't said as each was added (pixels @@ -3719,7 +3811,8 @@ impl Session { /// Forgets undo/redo and extent history and marks the project clean (after new/open, or a /// front end setting up how the project starts): what [`PutAside`] holds, dropped. pub fn clear_history(&mut self) { - drop(self.take_project_state()); + let replaced = self.take_project_state(); + self.say_dropped_downloads(&replaced.file_outputs, "as another project replaced theirs first"); self.undo_memory.clear(); self.project_starts = self.project_starts.wrapping_add(1); // A state of its own: undo back past a replacement made within a command (a task's step) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 106c90811f..f07d5d6841 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -62,6 +62,10 @@ mod block_model; #[path = "tests/write_notices.rs"] mod write_notices; +#[cfg(not(target_arch = "wasm32"))] +#[path = "tests/browser_exports.rs"] +mod browser_exports; + #[path = "tests/held_layers.rs"] mod held_layers; #[path = "tests/map_system_places.rs"] @@ -39976,6 +39980,9 @@ fn params_name_every_key_a_command_reads() { ("gp.zonalStats", "input"), ("gp.zonalStats", "target"), ("profile.alongSelected", "row"), + // The scan sees `exports::write_here`'s shared read of `path`, which `source.publish` + // never reaches: `takes_path` there guards it. + ("source.publish", "path"), ("sources.remove", "name"), ("sources.remove", "extra"), ]; diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs new file mode 100644 index 0000000000..223a4949cd --- /dev/null +++ b/crates/engine/src/tests/browser_exports.rs @@ -0,0 +1,558 @@ +//! Exports by command where files are downloaded: the browser has no filesystem to write a path +//! in, so a script's, the Assistant's or a plugin's export is offered as a download instead. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; +use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value as Cell}; +use serde_json::{Value, json}; + +use super::write_notices::Files; +use crate::{CmdResult, Project, Session}; + +/// A point layer, a standalone table and a raster, a layout and a report. A field name longer +/// than a Shapefile holds and a NaN, which GeoJSON can't, give exports something to say. +/// `browser` is whether files are downloaded. +fn session(files: &Files, browser: bool) -> Session { + let mut s = Session::new(Project::default()); + let fields = vec![Field::new("long_attribute_name", FieldType::Text), Field::new("score", FieldType::Double)]; + let mut ds = Dataset::new("Places", GeometryType::Point, fields.clone()); + ds.crs = rustgis_data::raster::Crs::from_epsg(4326); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 2.0))), vec![Cell::Text("kept".into()), Cell::Float(f64::NAN)]); + s.map_mut().add_dataset(ds); + let mut totals = Dataset::new("Totals", GeometryType::None, fields); + totals.push(None, vec![Cell::Text("a".into()), Cell::Float(1.5)]); + s.project.add_table(totals); + let grid = files.path().join("dem.asc"); + std::fs::write(&grid, "ncols 2\nnrows 2\nxllcorner 0\nyllcorner 0\ncellsize 1\n1 2\n3 4\n").unwrap(); + s.run("layer.addData", &json!({"path": grid, "name": "Dem"})).unwrap(); + s.run("layout.new", &json!({"name": "Page", "template": "blank"})).unwrap(); + s.run("report.new", &json!({"layer": "Places", "name": "List"})).unwrap(); + s.queue_gp_files = browser; + s +} + +/// `params` writing to `path`. +fn to(params: &Value, path: &str) -> Value { + let mut p = params.clone(); + p["path"] = json!(path); + p +} + +/// The notices said since `mark`. +fn said(s: &Session, mark: u64) -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +/// Takes the one queued download and acknowledges it as the app does: its name, its bytes and +/// the acknowledgment's answer. +fn deliver(s: &mut Session, pending: &Value, error: Option<&str>) -> (String, Vec, CmdResult) { + assert_eq!(pending["pending"], true, "{pending}"); + let mut files = s.take_gp_files(); + assert_eq!(files.len(), 1, "{pending}"); + let (id, name, bytes) = files.remove(0); + assert_eq!(pending["download"].as_u64(), Some(id)); + let answer = s.acknowledge_gp_file(id, error); + (name, bytes.to_vec(), answer) +} + +/// Each export command the browser can run downloads the file the desktop writes, under the +/// path's name, and says of it what the desktop says, once the download is taken. +#[test] +fn a_browser_export_by_path_downloads_the_desktops_file_and_says_the_same() { + // Command, other parameters, file name, and whether two writes of it give the same bytes. + let cases = [ + ("share.exportTable", json!({"table": "Totals"}), "totals.csv", true), + ("share.exportTable", json!({"table": "Totals", "limit": 0}), "totals.geojson", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.geojson", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.csv", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.zip", true), + ("share.exportLayer", json!({"layer": "Places", "crs": "EPSG:3857"}), "z.parquet", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.kml", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.kmz", true), + ("share.exportLayer", json!({"layer": "Places"}), "z.gpx", true), + ("data.convert", json!({"layer": "Places", "format": "wkt"}), "z.txt", true), + ("data.convert", json!({"layer": "Places", "format": "csv"}), "z.csv", true), + ("share.exportRaster", json!({"layer": "Dem"}), "dem.tif", true), + ("share.exportRaster", json!({"layer": "Dem", "cog": true}), "cog.tif", true), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", true), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.tif", true), + ("share.exportMap", json!({"width": 64, "height": 64, "cog": true}), "mapcog.tif", true), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.pdf", false), + ("report.export", json!({"report": "List", "dpi": 72}), "list.pdf", false), + ]; + // A new export is listed here, or among those refused. + for (command, ..) in crate::cmd::exports::IN_BACKGROUND { + assert!(cases.iter().any(|c| c.0 == *command) || REFUSED.iter().any(|r| r.0 == *command), "{command}"); + } + for (command, params, file, same_bytes) in cases { + let files = Files::new(); + let mut desktop = session(&files, false); + let path = files.path().join(file); + let path = path.to_str().unwrap(); + let mark = desktop.notice_mark(); + let wrote = desktop.run(command, &to(¶ms, path)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + let written = std::fs::read(path).unwrap(); + let folder = format!("{}{}", files.path().display(), std::path::MAIN_SEPARATOR); + let desktop_said: Vec = said(&desktop, mark).into_iter().map(|n| n.replace(&folder, "")).collect(); + // A layer's export says it was exported, and what its format couldn't hold. + if command == "share.exportLayer" { + assert!(desktop_said.contains(&format!("Exported {file}")), "{file}: {desktop_said:?}"); + } + if file == "z.geojson" { + assert!(desktop_said.iter().any(|n| n.contains("written as null")), "{desktop_said:?}"); + } + if file == "z.zip" { + assert!(desktop_said.iter().any(|n| n.contains("long_attribute_name")), "{desktop_said:?}"); + } + + let mut browser = session(&files, true); + std::fs::remove_file(path).unwrap(); + let (mark, steps) = (browser.notice_mark(), browser.undo_depth()); + let pending = browser.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + assert_eq!(said(&browser, mark), Vec::::new(), "{command} {file}: nothing is said before the download"); + let (name, bytes, answer) = deliver(&mut browser, &pending, None); + assert_eq!(name, file); + if same_bytes { + assert!(bytes == written, "{command} {file}: {} bytes downloaded, {} written", bytes.len(), written.len()); + } else { + assert_eq!(bytes.get(..4), written.get(..4), "{command} {file}"); + } + assert_eq!(said(&browser, mark), desktop_said, "{command} {file}"); + let answer = answer.unwrap(); + assert_eq!((&answer["delivered"], &answer["file"]), (&json!(true), &json!(file)), "{answer}"); + for (key, value) in wrote.as_object().unwrap() { + if key != "path" && (same_bytes || key != "bytes") { + assert_eq!(&answer[key], value, "{command} {file}: {key}"); + } + } + assert_eq!(answer["path"], file); + assert!(!std::path::Path::new(file).exists(), "{command} {file}: no file is written"); + assert!(browser.project.gp_history.is_empty(), "an export isn't a tool run"); + assert_eq!(browser.undo_depth(), steps, "{command} {file}"); + } +} + +/// The reported script: each line's export is downloaded, its losses told to a caller that reads +/// only the answer. +#[test] +fn a_scripts_browser_exports_are_pending_downloads() { + let files = Files::new(); + let mut s = session(&files, true); + let script = "share.exportTable {\"table\": \"Totals\", \"path\": \"totals.csv\"}\n\ + share.exportLayer {\"layer\": \"Places\", \"path\": \"z.geojson\"}"; + let mark = s.notice_mark(); + let ran = s.run("script.run", &json!({"script": script})).unwrap(); + let results: Vec<&Value> = ran["ran"].as_array().unwrap().iter().map(|r| &r["result"]).collect(); + assert_eq!(results.iter().map(|r| &r["file"]).collect::>(), ["totals.csv", "z.geojson"]); + let messages = results[1]["messages"].to_string(); + assert!(messages.contains("written as null") && !messages.contains("Exported"), "{messages}"); + assert_eq!(s.take_gp_files().len(), 2); + assert_eq!(said(&s, mark), Vec::::new()); +} + +/// What the download's name can't keep of the path is said, once the download is taken; a plain +/// file name says neither. +#[test] +fn a_browser_export_says_when_its_download_is_named_otherwise() { + let files = Files::new(); + let mut s = session(&files, true); + for (command, path, file, zipped, folder) in [ + ("share.exportLayer", "z.geojson", "z.geojson", false, false), + ("share.exportLayer", "z.zip", "z.zip", false, false), + ("share.exportLayer", "Roads.SHP", "Roads.zip", true, false), + ("share.exportLayer", "/home/me/out/rows.shp", "rows.zip", true, true), + ("share.exportTable", "out\\rows.csv", "rows.csv", false, true), + ] { + let params = json!({"layer": "Places", "table": "Totals", "path": path}); + let mark = s.notice_mark(); + let pending = s.run(command, ¶ms).unwrap(); + let (name, bytes, _) = deliver(&mut s, &pending, None); + assert_eq!(name, file, "{path}"); + assert_eq!(bytes.starts_with(b"PK"), file.ends_with(".zip"), "{path}"); + let notices = said(&s, mark); + let zip_note = format!("{file}: a Shapefile is several files, so the browser downloads them in one .zip"); + let folder_note = format!("{file}: the browser chooses where downloads go, so the folder in '{path}' wasn't used"); + assert_eq!(notices.contains(&zip_note), zipped, "{path}: {notices:?}"); + assert_eq!(notices.contains(&folder_note), folder, "{path}: {notices:?}"); + } +} + +/// What the browser can't write: the command, its path, and what its refusal says to do. +const REFUSED: &[(&str, &str, &str)] = &[ + ("share.exportLayer", "z.gpkg", "can't write GeoPackage or FlatGeobuf files; export to .geojson"), + ("share.exportLayer", "z.FGB", "can't write GeoPackage or FlatGeobuf files; export to .geojson"), + ("share.exportTable", "rows.gpkg", "can't write GeoPackage or FlatGeobuf files; export to .geojson"), + ("share.exportLayer", "out/", "this one has none"), + ("share.exportMap", "..", "this one has none"), + ("offline.package", "site.rgisfield", "use Package for the Field on the ribbon"), + ("map.exportOrbit", "spin.gif", "the web app can't export an orbit; open the project in the desktop app"), + ("map.exportBlock", "block.glb", "the web app can't export a block; open the project in the desktop app"), + ("source.publish", "unused", "publish from the desktop app"), +]; + +/// What the browser can't write is refused before anything is made, saying how to export instead. +#[test] +fn what_the_browser_cant_write_is_refused_up_front() { + let files = Files::new(); + let mut s = session(&files, true); + // A layer read from a file, which Publish to Source writes back to. + let filed = files.path().join("filed.geojson"); + std::fs::write(&filed, r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"a":1},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#).unwrap(); + s.run("layer.addData", &json!({"path": filed, "name": "Filed"})).unwrap(); + for &(command, path, why) in REFUSED { + let areas = s.project.offline_areas.len(); + let layer = if command == "source.publish" { "Filed" } else { "Places" }; + let params = json!({"layer": layer, "table": "Totals", "name": "Site", "path": path, "frames": 1, "width": 64, "height": 64}); + let params = if command == "source.publish" { json!({"layer": layer}) } else { params }; + let e = s.run(command, ¶ms).unwrap_err(); + assert!(e.contains(why), "{command} {path}: {e}"); + assert_eq!(s.project.offline_areas.len(), areas); + assert!(s.take_gp_files().is_empty()); + assert!(!std::path::Path::new(path).is_file(), "{command}: no file is written"); + } +} + +/// A raster layer `name` of `bands` bands, and the GeoTIFF of its first one. +fn raster(name: &str, bands: usize) -> (rustgis_data::raster::Raster, Vec) { + let transform = rustgis_data::raster::GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = rustgis_data::raster::Raster::new( + name, + 2, + 2, + vec![vec![1.0, 2.0, 3.0, 4.0]; bands], + transform, + rustgis_data::raster::Crs::LonLat, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + let tif = rustgis_data::raster::geotiff::write(&r, 0).unwrap(); + (r, tif) +} + +/// A pending export doesn't claim its file is exported, whatever follows that claim in what the +/// file says; what it leaves out is still in the answer, and the claim is made on delivery. +#[test] +fn a_pending_raster_export_says_what_it_leaves_out_but_not_that_it_is_exported() { + let files = Files::new(); + let mut s = session(&files, true); + let (r, tif) = raster("Bands", 2); + s.map_mut().add_raster("Bands", rustgis_map::RasterLayer::from_bytes(r, "bands.tif", tif)); + for (layer, file, lossy) in [("Bands", "bands.tif", true), ("Dem", "dem.tif", false)] { + let mark = s.notice_mark(); + let pending = s.run("share.exportRaster", &json!({"layer": layer, "path": file})).unwrap(); + let messages: Vec<&str> = pending["messages"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(!messages.iter().any(|m| m.contains("Exported")), "{messages:?}"); + if lossy { + assert_eq!(messages.len(), 1, "{messages:?}"); + assert!(messages[0].starts_with("bands.tif; 1 of its 2 bands written"), "{messages:?}"); + } else { + assert_eq!(messages, Vec::<&str>::new()); + } + deliver(&mut s, &pending, None).2.unwrap(); + let notices = said(&s, mark); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with(&format!("Exported {file}")), "{notices:?}"); + assert_eq!(notices[0].contains("1 of its 2 bands written"), lossy, "{notices:?}"); + } +} + +/// A raster a command made is downloaded from the file its layer holds, with no second copy. +#[test] +fn a_raster_download_shares_the_layers_file() { + let files = Files::new(); + let mut s = session(&files, true); + let (r, tif) = raster("Made", 1); + let id = s.map_mut().add_raster("Made", rustgis_map::RasterLayer::from_written(r, "made.tif", tif)); + let held = s.map().layer(id).unwrap().raster.as_ref().unwrap().written_file().unwrap().clone(); + s.run("share.exportRaster", &json!({"layer": "Made", "path": "made.tif"})).unwrap(); + let downloads = s.take_gp_files(); + assert_eq!(downloads.len(), 1); + assert_eq!(downloads[0].2.as_ptr(), held.as_ptr(), "the layer's own bytes are handed over"); +} + +/// A source read in place which says it holds `count` features, or gives a row of `text` bytes, +/// as a large layer does, and notes whether it was read. +struct Large { + info: SourceInfo, + inner: Box, + text: usize, + chunks: bool, + read: Arc, +} + +impl Large { + /// The row of `text` bytes: its room is reserved, not filled. + fn row(&self) -> Feature { + let mut text = String::with_capacity(self.text); + text.push('x'); + Feature { id: 1, geometry: Some(Geometry::Point(rustgis_data::Coord::new(1.0, 2.0))), attrs: vec![Cell::Text(text)] } + } +} + +impl FeatureSource for Large { + fn info(&self) -> &SourceInfo { + &self.info + } + + /// The whole source in one read, as one that can't be read a chunk at a time answers. + fn read(&self, req: &Request) -> rustgis_data::Result { + self.read.store(true, Ordering::Relaxed); + if self.text == 0 { + return self.inner.read(req); + } + Ok(Batch { features: vec![self.row()], matched: 1, complete: true, ..Batch::default() }) + } + + fn visits_chunks(&self) -> bool { + self.chunks + } + + /// The large row as one chunk, else the small file's rows. + fn visit_chunks( + &self, + extent: Option, + bytes: usize, + visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, + ) -> rustgis_data::Result { + self.read.store(true, Ordering::Relaxed); + if self.text == 0 { + return self.inner.visit_chunks(extent, bytes, visit); + } + visit(vec![self.row()])?; + Ok(Batch { matched: 1, complete: true, ..Batch::default() }) + } +} + +/// Adds layer `name`, read in place from a [`Large`] source; gives whether it has been read. +fn streamed(s: &mut Session, name: &str, count: Option, text: usize, chunks: bool) -> Arc { + let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("a", FieldType::Text)]); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1.0, 2.0))), vec![Cell::Text("kept".into())]); + let bytes = Arc::new(rustgis_data::source::fgb::write(&ds).unwrap()); + let inner = rustgis_data::source::open_shared("large.fgb", bytes.clone(), None).unwrap(); + let mut info = inner.info().clone(); + info.count = count; + let read = Arc::new(AtomicBool::new(false)); + let source = Large { info, inner, text, chunks, read: read.clone() }; + let source = rustgis_map::source::SourceLayer::from_bytes("large.fgb", bytes, None, Box::new(source)); + let mut layer = rustgis_map::Layer::new_streamed(s.map().layers.len() as u32 + 10, source); + layer.name = name.into(); + s.map_mut().layers.push(layer); + read +} + +/// A layer read in place too large to hold while its download is made is refused: before any of +/// it is read when its source says how many features it holds, else as soon as what is read +/// passes the limit. A small one downloads. +#[test] +fn a_browser_export_of_a_large_streamed_layer_is_refused() { + let files = Files::new(); + let mut s = session(&files, true); + // Name, count the source says, bytes of its row, read a chunk at a time, read before refusal. + let cases = [ + ("Many", Some(10_000_000), 0, true, false), + ("ManyAtOnce", Some(10_000_000), 0, false, false), + ("Heavy", None, 300 << 20, true, true), + ("HeavyAtOnce", Some(1), 300 << 20, false, true), + ]; + for (layer, count, text, chunks, reads) in cases { + for (command, params, file) in [ + ("share.exportLayer", json!({"layer": layer}), "z.geojson"), + ("data.convert", json!({"layer": layer, "format": "csv"}), "z.csv"), + ] { + let read = streamed(&mut s, layer, count, text, chunks); + let e = s.run(command, &to(¶ms, file)).unwrap_err(); + assert!(e.contains(layer) && e.contains("more than the 256 MiB"), "{command} {layer}: {e}"); + assert!(e.contains("Make Layer From Selected Features") && e.contains("desktop app"), "{e}"); + assert_eq!(read.load(Ordering::Relaxed), reads, "{command} {layer}"); + assert!(s.take_gp_files().is_empty()); + s.map_mut().layers.retain(|l| l.name != layer); + } + } + for chunks in [true, false] { + let layer = format!("Small{chunks}"); + streamed(&mut s, &layer, Some(1), 0, chunks); + let mark = s.notice_mark(); + let pending = s.run("share.exportLayer", &json!({"layer": layer, "path": "small.geojson"})).unwrap(); + let (_, bytes, _) = deliver(&mut s, &pending, None); + assert!(String::from_utf8_lossy(&bytes).contains("kept")); + assert_eq!(said(&s, mark), ["Exported small.geojson"]); + } +} + +/// Every export command that downloads, over the limit (a stand-in of ten bytes): its +/// writer stops once the file passes it, nothing waits to be downloaded, and the refusal says +/// how to export. A picture's size is bounded by its pixels, so a PNG, an SVG, and the file a +/// raster layer already holds are refused once made. Under the limit, each downloads. +#[test] +fn a_browser_export_over_the_limit_is_stopped_as_it_is_made() { + const STOPPED: &str = "stopped once the file passed"; + const MADE: &str = "more than the 1 MiB a command can download"; + let cases = [ + ("share.exportTable", json!({"table": "Totals"}), "t.csv", STOPPED), + ("share.exportTable", json!({"table": "Totals"}), "t.geojson", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.geojson", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.csv", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.parquet", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.kml", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.kmz", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.gpx", STOPPED), + ("share.exportLayer", json!({"layer": "Places"}), "z.zip", STOPPED), + ("data.convert", json!({"layer": "Places", "format": "geojson"}), "z.geojson", STOPPED), + ("data.convert", json!({"layer": "Places", "format": "csv"}), "z.csv", STOPPED), + ("data.convert", json!({"layer": "Places", "format": "kml"}), "z.kml", STOPPED), + ("data.convert", json!({"layer": "Places", "format": "gpx"}), "z.gpx", STOPPED), + ("data.convert", json!({"layer": "Places", "format": "wkt"}), "z.txt", STOPPED), + ("share.exportRaster", json!({"layer": "Dem"}), "dem.tif", STOPPED), + ("share.exportRaster", json!({"layer": "Dem", "cog": true}), "cog.tif", STOPPED), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.tif", STOPPED), + ("share.exportMap", json!({"width": 64, "height": 64, "cog": true}), "mapcog.tif", STOPPED), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.pdf", STOPPED), + ("report.export", json!({"report": "List", "dpi": 72}), "list.pdf", STOPPED), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", MADE), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.png", MADE), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.svg", MADE), + ("report.export", json!({"report": "List", "dpi": 72}), "list.png", MADE), + ("share.exportRaster", json!({"layer": "Made"}), "made.tif", MADE), + ]; + for (command, ..) in crate::cmd::exports::IN_BACKGROUND { + assert!(cases.iter().any(|c| c.0 == *command) || REFUSED.iter().any(|r| r.0 == *command), "{command}"); + } + let files = Files::new(); + let mut s = session(&files, true); + let (r, tif) = raster("Made", 1); + s.map_mut().add_raster("Made", rustgis_map::RasterLayer::from_written(r, "made.tif", tif)); + for (command, params, file, refusal) in cases { + s.download_cap = Some(10); + let e = s.run(command, &to(¶ms, file)).unwrap_err(); + assert!(e.contains(file) && e.contains(refusal) && e.contains("export less"), "{command} {file}: {e}"); + assert!(e.contains("desktop app"), "{e}"); + assert!(s.take_gp_files().is_empty(), "{command} {file}"); + s.download_cap = Some(1 << 20); + let pending = s.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + let (_, bytes, answer) = deliver(&mut s, &pending, None); + assert!(!bytes.is_empty() && bytes.len() <= 1 << 20, "{command} {file}: {}", bytes.len()); + answer.unwrap(); + } +} + +/// The limit is what the downloads waiting leave of it: an export that would fit by itself is +/// refused, saying what is waiting, and a full queue is refused before anything is made. +#[test] +fn a_browser_export_is_held_to_what_the_waiting_downloads_leave() { + let files = Files::new(); + let mut s = session(&files, true); + let table = |path: &str| json!({"table": "Totals", "path": path}); + s.run("share.exportTable", &table("first.csv")).unwrap(); + let first = s.file_outputs.iter().filter_map(|f| f.bytes.as_ref()).map(|b| b.len()).sum::(); + s.download_cap = Some(first * 2 - 1); + let e = s.run("share.exportTable", &table("second.csv")).unwrap_err(); + assert!(e.contains("second.csv: stopped once the file passed") && e.contains("already waiting"), "{e}"); + assert!(e.contains("split the task"), "{e}"); + s.download_cap = Some(first * 2); + s.run("share.exportTable", &table("second.csv")).unwrap(); + let e = s.run("share.exportTable", &table("third.csv")).unwrap_err(); + assert!(e.contains("file export queue limit reached"), "{e}"); + assert_eq!(s.take_gp_files().len(), 2); +} + +/// A project a command replaces keeps its downloads waiting until the command ends, in case it +/// is given back, and they count against the limit: an export in the new project can't pass it. +#[test] +fn downloads_put_aside_with_a_replaced_project_count_against_the_limit() { + let files = Files::new(); + let mut s = session(&files, true); + let script = "project.new\nshare.exportMap {\"width\": 64, \"height\": 64, \"path\": \"later.png\"}"; + // What the new project's map comes to by itself. + let mut alone = session(&files, true); + alone.run("script.run", &json!({"script": script})).unwrap(); + let map = alone.take_gp_files().iter().map(|f| f.2.len()).sum::(); + s.run("share.exportTable", &json!({"table": "Totals", "path": "totals.csv"})).unwrap(); + // Room for either file, not both. + s.download_cap = Some(s.waiting_download_bytes() + map - 1); + let e = s.run("script.run", &json!({"script": script})).unwrap_err(); + assert!(e.contains("share.exportMap"), "{e}"); + let waiting: Vec = s.take_gp_files().into_iter().map(|f| f.1).collect(); + assert_eq!(waiting, ["totals.csv"]); +} + +/// An export queued in a project a command opened, before that command fails, is said to be +/// dropped; one that waited in the project given back still waits. +#[test] +fn a_failed_commands_export_from_a_project_it_opened_is_said_dropped() { + let files = Files::new(); + let mut s = session(&files, true); + s.run("share.exportTable", &json!({"table": "Totals", "path": "totals.csv"})).unwrap(); + let mark = s.notice_mark(); + let script = "project.new\nshare.exportMap {\"width\": 64, \"height\": 64, \"path\": \"later.png\"}\nno.suchCommand"; + s.run("script.run", &json!({"script": script})).unwrap_err(); + let dropped: Vec = said(&s, mark).into_iter().filter(|n| n.contains("not downloaded")).collect(); + assert_eq!(dropped, ["1 export(s) not downloaded, as the command that made them failed: later.png"]); + let waiting: Vec = s.take_gp_files().into_iter().map(|f| f.1).collect(); + assert_eq!(waiting, ["totals.csv"]); +} + +/// A download the browser refuses is an error, and nothing says the file was exported. +#[test] +fn a_browser_export_not_taken_is_not_said_to_be_exported() { + let files = Files::new(); + let mut s = session(&files, true); + let pending = s.run("share.exportLayer", &json!({"layer": "Places", "path": "z.geojson"})).unwrap(); + let mark = s.notice_mark(); + let (_, _, answer) = deliver(&mut s, &pending, Some("download blocked")); + assert_eq!(answer.unwrap()["delivered"], false); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].error && notices[0].text == "download blocked", "{notices:?}"); + assert!(s.project.gp_history.is_empty()); +} + +/// A queued download dropped by a later failure, or by another project replacing its own, is +/// said, an export's and a tool output's each in a notice of its own: the desktop would have +/// written the file by then, and a tool's run is recorded only once its file is delivered. A run +/// that keeps them says nothing. +#[test] +fn a_browser_download_dropped_before_it_is_offered_is_said() { + let export = "share.exportTable {\"table\": \"Totals\", \"path\": \"totals.csv\"}"; + let tool = "gp.run {\"tool\": \"rasterToPmtiles\", \"params\": {\"input\": \"Dem\", \"minZoom\": 0, \"maxZoom\": 0}}"; + let expected = |queued: &[&str], why: &str| { + let mut notices = Vec::new(); + if queued.contains(&export) { + notices.push(format!("1 export(s) not downloaded, {why}: totals.csv")); + } + if queued.contains(&tool) { + notices.push(format!( + "1 tool output file(s) not downloaded, {why}, so their runs aren't in the geoprocessing history: Dem.pmtiles" + )); + } + notices + }; + let dropped = |s: &Session, mark: u64| -> Vec { said(s, mark).into_iter().filter(|n| n.contains("not downloaded")).collect() }; + for queued in [&[export][..], &[tool], &[export, tool]] { + for (then, why) in [ + ("map.zoomFull", None), + ("no.suchCommand", Some("as the command that made them failed")), + ("project.new", Some("as another project replaced theirs first")), + ] { + let files = Files::new(); + let mut s = session(&files, true); + let mark = s.notice_mark(); + let ran = s.run("script.run", &json!({"script": format!("{}\n{then}", queued.join("\n"))})); + assert_eq!(ran.is_ok(), then != "no.suchCommand", "{ran:?}"); + let notices = why.map(|why| expected(queued, why)).unwrap_or_default(); + assert_eq!(dropped(&s, mark), notices, "{queued:?}, {then}"); + assert_eq!(s.take_gp_files().len(), if why.is_none() { queued.len() } else { 0 }, "{queued:?}, {then}"); + assert!(s.project.gp_history.is_empty(), "no run is recorded before delivery"); + } + // Replaced by itself, between the command and the frame that would offer the file. + let files = Files::new(); + let mut s = session(&files, true); + s.run("script.run", &json!({"script": queued.join("\n")})).unwrap(); + let mark = s.notice_mark(); + s.run("project.new", &json!({})).unwrap(); + assert_eq!(dropped(&s, mark), expected(queued, "as another project replaced theirs first"), "{queued:?}"); + } +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6c33c8a340..fc1d56aabe 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -954,7 +954,18 @@ impl Layer { /// [`Layer::load_all`], with what of the source couldn't be read. pub fn load_all_counted(&self) -> Result<(Dataset, Unreadable), String> { - let (ds, report) = self.load_all_with_notices()?; + self.counted(None) + } + + /// [`Layer::load_all_counted`] for a caller that can hold only `budget` bytes of features: a + /// larger source is refused with `refusal` ([`rustgis_data::source::materialize_up_to`]). + pub fn load_all_counted_up_to(&self, budget: u64, refusal: &str) -> Result<(Dataset, Unreadable), String> { + self.counted(Some((budget, refusal))) + } + + /// The whole read behind [`Layer::load_all_counted`], within `limit` when given. + fn counted(&self, limit: Option<(u64, &str)>) -> Result<(Dataset, Unreadable), String> { + let (ds, report) = self.load_all_with_notices(limit)?; // materialize also puts the typed date diagnostics in messages. Existing consumers // give them their own export wording, so preserve only the other messages here. let date_notes: Vec<_> = report.unread_dates.iter().chain(&report.rounded_dates).map(|n| format!(": {}", n.as_str())).collect(); @@ -973,12 +984,14 @@ impl Layer { /// A whole read with its complete reader report, including messages beyond rows and dates. /// Callers decide which opening notices were already shown and which the new read discovered. pub fn load_all_reported(&self) -> Result<(Dataset, rustgis_data::ReadReport), String> { - self.load_all_with_notices() + self.load_all_with_notices(None) } - fn load_all_with_notices(&self) -> Result<(Dataset, rustgis_data::ReadReport), String> { + /// Reads the source whole, within `limit` (bytes of features, and the error past them) when + /// given, and names and types what is read as the layer does. + fn load_all_with_notices(&self, limit: Option<(u64, &str)>) -> Result<(Dataset, rustgis_data::ReadReport), String> { let Some(copy) = self.open_source()? else { return Ok((self.dataset.clone(), rustgis_data::ReadReport::default())) }; - let (mut ds, mut report) = copy.read_all()?; + let (mut ds, mut report) = copy.read_all_within(limit)?; if let Some(info) = copy.info() { ds.zm_dropped |= info.zm_dropped; for note in &info.notes { diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index ddbe8f8ceb..ea5722101b 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1896,12 +1896,22 @@ impl SourceLayer { /// Every feature of the source, up to the read limit (a source by its web address fetching /// what that needs, on the desktop). pub fn read_all(&self) -> Result<(rustgis_data::Dataset, rustgis_data::ReadReport), String> { + self.read_all_within(None) + } + + /// [`SourceLayer::read_all`], within `limit` when given: the most bytes of features, and the + /// error past them ([`rustgis_data::source::materialize_up_to`]). + pub(crate) fn read_all_within(&self, limit: Option<(u64, &str)>) -> Result<(rustgis_data::Dataset, rustgis_data::ReadReport), String> { let h = self.handle.clone().ok_or("the layer's source isn't open")?; + let read = |source: &dyn FeatureSource| match limit { + Some((budget, refusal)) => rustgis_data::source::materialize_up_to(source, budget, refusal), + None => rustgis_data::source::materialize(source), + }; #[cfg(not(target_arch = "wasm32"))] if h.remote().is_some() { - return rustgis_data::source::materialize(&rustgis_data::source::Fetching(h)).map_err(|e| e.to_string()); + return read(&rustgis_data::source::Fetching(h)).map_err(|e| e.to_string()); } - let r = rustgis_data::source::materialize(h.as_ref()).map_err(|e| e.to_string()); + let r = read(h.as_ref()).map_err(|e| e.to_string()); match r { Err(e) if e.contains(rustgis_data::source::remote::NEED) => { Err("the web app reads a file by its address a view at a time: download it to load it whole".into()) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index af5ccc7619..e2c45e3ec8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -148,6 +148,8 @@ mod workspacepanes; mod worldviewui; mod zarrui; +use std::sync::Arc; + use rustgis_engine::cmd::service_added::Removal; use rustgis_engine::render::rustgis_tiles::failure::Failure; use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; @@ -495,8 +497,10 @@ pub struct Services { /// [`RustGisApp::photos`]. `None` where there is no camera to ask. pub take_photo: Option Result<(), String>>>, /// Offers bytes as a download named `file_name`; success means submission to the host's - /// download mechanism. Browsers do not expose confirmation that the file was saved. - pub download: Option) -> Result<(), String>>>, + /// download mechanism. Browsers do not expose confirmation that the file was saved. The bytes + /// may be shared with what the session holds (a raster layer's file), so they aren't copied + /// to be offered. + pub download: Option>) -> Result<(), String>>>, /// Starts saving a project on a phone: written back to the document given (one the project /// was opened from or last saved as, with leave to write it), or through the native picker /// when there is none. The shell reports the eventual result through @@ -2927,7 +2931,7 @@ impl RustGisApp { } }; let file = format!("{stem}.rgis"); - if let Err(e) = self.services.download.as_ref().ok_or(tl!("no download service"))?(&file, text.into_bytes()) { + if let Err(e) = self.services.download.as_ref().ok_or(tl!("no download service"))?(&file, Arc::new(text.into_bytes())) { self.session.project.name = old; return Err(e); } @@ -2957,7 +2961,7 @@ impl RustGisApp { fn download(&mut self, name: &str, bytes: Vec) -> bool { match &self.services.download { Some(d) => { - if let Err(e) = d(name, bytes) { + if let Err(e) = d(name, Arc::new(bytes)) { self.session.notify(e, true); return false; } @@ -2991,14 +2995,19 @@ impl RustGisApp { Some(download) => download(&name, bytes), None => Err(tl!("this build has no download service").into()), }; - // gp.fileDelivered reports delivery failures from its history record. The app also - // reports acknowledgment failures before dispatch, without repeating engine notices. + // gp.fileDelivered reports delivery failures itself. The app also reports + // acknowledgment failures before dispatch, without repeating engine notices. + // Asked before the acknowledgment forgets the file. + let export = self.session.is_export_file(id); let completed = self.acknowledge_gp_file(id, delivered.as_ref().err().map(String::as_str)); let result = delivered.and(completed); - self.gp.last = Some(match &result { - Ok(_) => (true, self.session.project.gp_history.last().map(|h| h.messages.clone()).unwrap_or_default()), - Err(error) => (false, vec![error.clone()]), - }); + // An export isn't a tool run: the Geoprocessing pane keeps showing the last one. + if !export { + self.gp.last = Some(match &result { + Ok(_) => (true, self.session.project.gp_history.last().map(|h| h.messages.clone()).unwrap_or_default()), + Err(error) => (false, vec![error.clone()]), + }); + } requested = complete_gp_file(requested, id, &result); } requested @@ -10186,7 +10195,7 @@ mod download_service_tests { let downloaded = file.clone(); let mut app = RustGisApp::with_sample().with_services(Services { download: Some(Box::new(move |_, bytes| { - *downloaded.lock().unwrap() = bytes; + *downloaded.lock().unwrap() = std::sync::Arc::unwrap_or_clone(bytes); Ok(()) })), ..Default::default() @@ -10211,7 +10220,7 @@ mod download_service_tests { let downloaded = file.clone(); let mut app = RustGisApp::with_sample().with_services(Services { download: Some(Box::new(move |_, bytes| { - *downloaded.lock().unwrap() = bytes; + *downloaded.lock().unwrap() = std::sync::Arc::unwrap_or_clone(bytes); Ok(()) })), ..Default::default() @@ -10249,7 +10258,7 @@ mod download_service_tests { if !accept { return Err("browser rejected download".into()); } - taken.lock().unwrap().push((name.to_string(), bytes)); + taken.lock().unwrap().push((name.to_string(), bytes.to_vec())); Ok(()) })), ..Default::default() @@ -10320,7 +10329,7 @@ mod download_service_tests { use rustgis_engine::geom::Coord; // A NaN accepted, a NaN refused, and finite numbers only (nothing to say). for (accept, first) in [(true, f64::NAN), (false, f64::NAN), (true, 2.5)] { - let download: Box) -> Result<(), String>> = + let download: Box>) -> Result<(), String>> = if accept { Box::new(|_, _| Ok(())) } else { Box::new(|_, _| Err("browser rejected download".into())) }; let mut app = RustGisApp::with_sample().with_services(Services { download: Some(download), ..Default::default() }); let mut ds = Dataset::new("Gauges", GeometryType::Point, vec![Field::new("level", FieldType::Double)]); @@ -10347,7 +10356,7 @@ mod download_service_tests { use rustgis_engine::geom::Coord; let changed = |app: &RustGisApp| app.session.notices.iter().filter(|n| n.text.contains("changed to fit a Shapefile")).count(); let with = |accept: bool| { - let download: Box) -> Result<(), String>> = + let download: Box>) -> Result<(), String>> = if accept { Box::new(|_, _| Ok(())) } else { Box::new(|_, _| Err("browser rejected download".into())) }; let mut app = RustGisApp::with_sample().with_services(Services { download: Some(download), ..Default::default() }); let mut ds = Dataset::new( diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index cd5b2f7856..5e9d242176 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -579,7 +579,7 @@ mod tests { let got = std::rc::Rc::new(std::cell::RefCell::new(None)); let sink = got.clone(); app.services.download = Some(Box::new(move |name, bytes| { - *sink.borrow_mut() = Some((name.to_string(), String::from_utf8(bytes).unwrap())); + *sink.borrow_mut() = Some((name.to_string(), String::from_utf8(bytes.to_vec()).unwrap())); Ok(()) })); save(&mut app); diff --git a/crates/ui-egui/src/shortcutfile.rs b/crates/ui-egui/src/shortcutfile.rs index a940cb39ed..f14d422e57 100644 --- a/crates/ui-egui/src/shortcutfile.rs +++ b/crates/ui-egui/src/shortcutfile.rs @@ -208,7 +208,7 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result { } } else if !p.get("text").and_then(Value::as_bool).unwrap_or(false) { if let Some(download) = &app.services.download { - download("rustgis-shortcuts.json", text.as_bytes().to_vec())?; + download("rustgis-shortcuts.json", std::sync::Arc::new(text.as_bytes().to_vec()))?; } else if let Some(path) = dialogs::pick_save("rustgis-shortcuts.json", &["json"], tl!("Keyboard shortcuts")) { rustgis_engine::data::io::write_atomic(std::path::Path::new(&path), text.as_bytes()).map_err(|e| e.to_string())?; } diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 0eebea6fd9..acfa3044cf 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -4539,8 +4539,8 @@ fn web_save_asks_for_the_file_name() { let got = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Vec)>::new())); let log = got.clone(); let services = rustgis_ui_egui::Services { - download: Some(Box::new(move |name: &str, bytes: Vec| { - log.lock().unwrap().push((name.to_string(), bytes)); + download: Some(Box::new(move |name: &str, bytes: std::sync::Arc>| { + log.lock().unwrap().push((name.to_string(), bytes.to_vec())); Ok(()) })), ..Default::default() diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a6606d06b1..9d13f07ca7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -522,7 +522,9 @@ vertex per ring allows for implicit ring closure. The work-limit error is distin the memory-limit error: simplify polygon rings, reduce the input extent, or narrow the zoom range. These limits reject the whole export rather than sampling or truncating it. Browser task, model and script runs can queue at most eight files or 256 MiB of archive bytes -before downloads are submitted; split larger batches into separate runs. Browser success +before downloads are submitted; split larger batches into separate runs, and start each run only after the previous run's downloads are submitted. A file still waiting when +its script, model or task fails, or when another project replaces its own, is dropped with a +notice, and its run is left out of the geoprocessing history. Browser success means the download was submitted, not confirmation that the browser saved it. Example: ```text diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index ca43d1a7de..8fa08cf50f 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -84,6 +84,25 @@ the formats above that can hold it: for a table without geometry, CSV, GeoJSON, (no GeoPackage in the web app, which downloads the file). Scripts and the command line use `share.exportTable`. +The browser can't write to a folder, so in the web app an export command with a `path` (from the +Script pane, the Assistant or a plugin) downloads the file under the name the path ends in, once +the commands finish: `share.exportLayer`, `share.exportTable`, `share.exportMap`, +`share.exportRaster` (a raster layer), `layout.export`, `report.export` and `data.convert`. A +folder in the path isn't used, and a `.shp` path downloads a `.zip` of the Shapefile's files; a +notice says each. At most 8 files, 256 MiB in all, can wait to be downloaded (a geoprocessing +tool's file output waits the same way), and those of a script that then fails, or of a project +replaced before they are offered, are dropped with a notice. A tool output dropped this way leaves +its run out of the geoprocessing history. An export is refused once its file passes what is left of +the 256 MiB, as it is made where the format allows, and for a Shapefile's `.zip` or a KMZ counting +its files before they are zipped: export a selection of features, a smaller size or fewer pages, +or use the desktop app. +`share.exportLayer` and `data.convert` read a layer read in place whole for such a download, up to +256 MiB of features; past that, select the features you need and export a layer made from them with +**Make Layer From Selected Features**, or use the desktop app. They don't read a layer added by its +web address this way: download the file and add it, or use the desktop app. +GeoPackage and FlatGeobuf, a tile layer as a raster, an orbit, a block and publishing to a source +need the desktop app; for a field package, use **Package for the Field** on the ribbon. + To export the largest rows of a Summary Statistics result, give `share.exportTable` an optional `sort` list and `limit`. Each sort key names a stored field; `descending` defaults to `false`. Keys are applied in list order. Numbers sort numerically, text sorts case-sensitively, and nulls