diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 3d112a3576..4ff3c56e31 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -244,6 +244,7 @@ pub trait Inputs { } /// Builds a vector-tile archive without coupling the analysis crate to the tile crate. + /// `file_name` is the file it is for, which a refusal names. fn vector_to_pmtiles( &self, _dataset: &Dataset, @@ -251,12 +252,14 @@ pub trait Inputs { _min_zoom: u8, _max_zoom: u8, _source_layer: &str, + _file_name: &str, ) -> Result<(Vec, Vec), String> { Err("vector-to-PMTiles export is unavailable in this input provider".into()) } - /// Builds a raster tile archive with the layer's existing display style. - fn raster_to_pmtiles(&self, _layer: &str, _min_zoom: u8, _max_zoom: u8) -> Result, String> { + /// Builds a raster tile archive with the layer's existing display style, for the file + /// `file_name`, which a refusal names. + fn raster_to_pmtiles(&self, _layer: &str, _min_zoom: u8, _max_zoom: u8, _file_name: &str) -> Result, String> { Err("raster-to-PMTiles export is unavailable in this input provider".into()) } } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 457003c733..bf5efe06c5 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1521,7 +1521,7 @@ fn vector_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result { let default_name = ds.name.rsplit(['/', '\\']).find(|name| !name.is_empty()).unwrap_or("output"); let file_name = if output.is_empty() { format!("{default_name}.pmtiles") } else { output.to_string() }; let selected = inp.selection(s(p, "input")); - let (bytes, messages) = inp.vector_to_pmtiles(ds, selected, min_zoom, max_zoom, source_layer)?; + let (bytes, messages) = inp.vector_to_pmtiles(ds, selected, min_zoom, max_zoom, source_layer, &file_name)?; Ok(ToolResult { losses: Vec::new(), output: Output::File { file_name, bytes }, messages }) } @@ -1531,7 +1531,7 @@ fn raster_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result { let output = s(p, "output").trim(); let default_name = name.rsplit(['/', '\\']).find(|part| !part.is_empty()).unwrap_or("output"); let file_name = if output.is_empty() { format!("{default_name}.pmtiles") } else { output.to_string() }; - let bytes = inp.raster_to_pmtiles(name, min_zoom, max_zoom)?; + let bytes = inp.raster_to_pmtiles(name, min_zoom, max_zoom, &file_name)?; Ok(ToolResult { losses: Vec::new(), output: Output::File { file_name, bytes }, messages: vec![] }) } diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 2bb3dd920e..091ad4797d 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -54,7 +54,7 @@ impl Limit { /// Refuses, and notes the limit passed, when files that come to `bytes` can't be held: for a /// writer to ask before it builds a large piece of them that would then be refused. - pub(crate) fn fits(&self, bytes: usize) -> Result<()> { + pub fn fits(&self, bytes: usize) -> Result<()> { if bytes <= self.max { return Ok(()); } @@ -67,8 +67,13 @@ impl Limit { self.fits(self.held.load(Ordering::Relaxed).saturating_add(more)) } + /// The most bytes it holds. + pub(crate) fn max(&self) -> usize { + self.max + } + /// An empty buffer counted against this limit. - pub(crate) fn buffer(&self) -> Buffer<'_> { + pub fn buffer(&self) -> Buffer<'_> { Buffer { file: Vec::new(), at: 0, limit: self, charged: 0, room: None } } @@ -126,7 +131,7 @@ impl Drop for Held<'_> { /// A file made in memory within a [`Limit`], written and sought as a file is. #[derive(Debug)] -pub(crate) struct Buffer<'a> { +pub struct Buffer<'a> { file: Vec, /// Where the next write goes. at: u64, @@ -138,8 +143,24 @@ pub(crate) struct Buffer<'a> { } impl Buffer<'_> { + /// What has been written so far. + pub fn written(&self) -> &[u8] { + &self.file + } + + /// Puts `head` before everything written, within the limit and without a second copy of the + /// file: for a format whose index is known last and read first. The next write goes to the + /// end; one refused leaves the file and the place to write as they were. + pub fn prepend(&mut self, head: &[u8]) -> std::io::Result<()> { + let at = std::mem::replace(&mut self.at, self.file.len() as u64); + self.write_all(head).inspect_err(|_| self.at = at)?; + let by = head.len().min(self.file.len()); + self.file.rotate_right(by); + Ok(()) + } + /// The file made, its spare room given back, no longer counted against the limit. - pub(crate) fn into_inner(mut self) -> Vec { + pub fn into_inner(mut self) -> Vec { let mut file = std::mem::take(&mut self.file); // Only a file held to a limit (a download, which waits counted by what it holds) gives // back its spare room: a file to be written isn't reallocated for it. @@ -519,6 +540,65 @@ mod tests { } } + /// A layer held in another system, each feature converted as a limited write reaches it, gives + /// what its converted copy gives: the bytes, what is left out, the notes and the extent. + #[test] + fn a_download_converted_as_it_is_written_matches_the_converted_copy() { + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut ds = Dataset::new("Mixed", GeometryType::Point, fields); + let at = |i: u32| crate::Coord::new(2.0 + f64::from(i) * 0.001, 48.0); + let shapes = [ + Some(Geometry::Point(at(1))), + Some(Geometry::MultiPoint(vec![at(2), at(3)])), + Some(Geometry::MultiPoint(Vec::new())), + Some(Geometry::Line(vec![vec![at(4), at(5)]])), + Some(Geometry::Polygon(vec![vec![vec![at(6), at(7), crate::Coord::new(2.0, 48.1), at(6)]]])), + Some(Geometry::Point(crate::Coord::new(f64::NAN, 48.0))), + None, + ]; + for (i, g) in shapes.into_iter().enumerate() { + ds.push(g, vec![Value::Text(format!(" ={i} ")), Value::Int(i as i64)]); + } + ds.hold_in(Crs::from_epsg(32631).unwrap()).unwrap(); + // Places that can't be given in longitude/latitude. + let far = crate::Coord::new(1e9, 5_411_500.0); + for g in [Geometry::Point(far), Geometry::MultiPoint(vec![far, far]), Geometry::Line(vec![vec![far, far]])] { + ds.push(Some(g), vec![Value::Text("far".into()), Value::Null]); + } + let (copy, unplaced) = ds.in_lonlat_leaving_out().unwrap(); + assert_eq!(unplaced, 3); + let roomy = Limit::new(1 << 24); + for (ext, crs) in ["geojson", "csv", "kml", "kmz", "gpx"] + .map(|ext| (ext, Crs::LonLat)) + .into_iter() + .chain([("csv", Crs::from_epsg(32632).unwrap())]) + { + let copied = crate::io::write_bytes_noted_within(&ds, ext, crs, "out", &Limit::none()).unwrap(); + let walked = crate::io::write_bytes_noted_within(&ds, ext, crs, "out", &roomy).unwrap(); + assert_eq!(walked.0, copied.0, "{ext}"); + assert_eq!((walked.1, walked.2, walked.3), (copied.1, copied.2, copied.3), "{ext}"); + } + for format in ["geojson", "csv", "kml", "gpx", "wkt"] { + let walked = crate::io::text_bytes_in_lonlat_within(&ds, format, Some(0), &roomy).unwrap(); + assert_eq!(walked.bytes, crate::io::text_bytes_within(©, format, Some(0), &roomy).unwrap(), "{format}"); + let without = copy.features.iter().filter(|f| f.geometry.is_none()).count(); + assert_eq!((walked.unplaced, walked.without_geometry), (unplaced, without), "{format}"); + assert_eq!(walked.gpx_left_out, crate::io::gpx_left_out(©), "{format}"); + let notes = crate::io::export_losses_notes_in_lonlat(&ds, format, Some(0), "out").unwrap(); + assert_eq!(notes, crate::io::export_losses_notes(©, format, Some(0), "out").unwrap(), "{format}"); + } + let (mut walked, mut copied) = (Vec::new(), Vec::new()); + assert_eq!(crate::io::write_geojson_in_lonlat(&ds, &mut walked).unwrap(), unplaced); + crate::io::write_geojson(©, &mut copied).unwrap(); + assert_eq!(walked, copied); + // An `items` document is the same collection, saying how many it returns. + let mut items = Vec::new(); + assert_eq!(crate::io::write_geojson_items_in_lonlat(&ds, &mut items).unwrap(), unplaced); + copied.truncate(copied.len() - 2); + copied.extend_from_slice(format!("],\"numberReturned\":{}}}", ds.features.len()).as_bytes()); + assert_eq!(items, copied); + } + /// 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() { diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index b0a8d31068..d1176d6d30 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -7,6 +7,7 @@ use std::io::Write; use rustgis_geom::Coord; use crate::capped::write_pieces; +use crate::io::{Row, Walk}; use crate::{Dataset, Geometry}; /// Refuses text XML can't hold: it is kept exactly or refused, never cleaned without reporting its @@ -140,6 +141,16 @@ pub(crate) fn kml_typed_string(field: &crate::Field) -> bool { /// [`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_kml_of(ds, Walk::held(ds).rows(None), name_field, out) +} + +/// [`write_kml`] of `ds`'s name and fields with `rows`, in longitude/latitude. +pub(crate) fn write_kml_of<'a>( + ds: &Dataset, + rows: impl Iterator>, + name_field: Option, + out: &mut impl Write, +) -> crate::Result<()> { check_xml(&ds.name, "KML", || "layer name".to_string())?; out.write_all(b"\n, out: &mut impl // 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); - for (r, f) in ds.features.iter().enumerate() { + for f in rows { crate::progress::step(1)?; - let Some(g) = &f.geometry else { continue }; - let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| ds.value(r, fi).file_text()); - let description = match description.map(|fi| ds.value(r, fi)) { + let Some(g) = f.geometry.as_deref() else { continue }; + let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| f.value(fi).file_text()); + let description = match description.map(|fi| f.value(fi)) { Some(crate::Value::Text(text)) => Some(text), _ => None, }; - let data = || ds.fields.iter().zip(&f.attrs).filter(|(_, v)| !v.is_null()); + let data = || ds.fields.iter().zip(f.attrs).filter(|(_, v)| !v.is_null()); // All the placemark's text is checked before any of it is written. if let Some(text) = description { check_xml(text, "KML", || feature_place(&ds.name, f.id, "description"))?; @@ -249,18 +260,29 @@ pub fn to_gpx(ds: &Dataset, name_field: Option) -> crate::Result /// [`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<()> { + write_gpx_of(ds, || Walk::held(ds).rows(None), name_field, out) +} + +/// [`write_gpx`] of `ds`'s name with the features each call of `rows` walks, in +/// longitude/latitude. +pub(crate) fn write_gpx_of<'a, I: Iterator>>( + ds: &Dataset, + mut rows: impl FnMut() -> I, + name_field: Option, + out: &mut impl Write, +) -> crate::Result<()> { out.write_all( b"\n\n", )?; for tracks in [false, true] { - for (r, f) in ds.features.iter().enumerate() { + for f in rows() { // Each feature counts once, in the first pass. if tracks { crate::progress::check()?; } else { crate::progress::step(1)?; } - let Some(g) = &f.geometry else { continue }; + let Some(g) = f.geometry.as_deref() 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 { @@ -270,7 +292,7 @@ pub(crate) fn write_gpx(ds: &Dataset, name_field: Option, out: &mut impl if !written { continue; } - let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| ds.value(r, fi).file_text()); + let name = name_field.map_or_else(|| f.id.to_string().into(), |fi| f.value(fi).file_text()); check_xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?; match g { Geometry::Point(c) if !tracks => write_gpx_waypoint(out, c, &name)?, @@ -707,6 +729,11 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { /// [`to_wkt_csv`]'s text, written to `out` as it is made. Field names and text cells that start /// like a spreadsheet formula take an apostrophe, as in plain CSV. pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result<()> { + write_wkt_csv_of(ds, Walk::held(ds).rows(None), out) +} + +/// [`write_wkt_csv`] of `ds`'s fields with `rows`. +pub(crate) fn write_wkt_csv_of<'a>(ds: &Dataset, rows: impl Iterator>, out: &mut impl Write) -> crate::Result<()> { /// A comma, then `text` as a CSV cell with `guard` before it. fn cell(out: &mut impl Write, guard: &str, text: &str) -> std::io::Result<()> { out.write_all(b",")?; @@ -717,9 +744,9 @@ pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result cell(out, wkt_csv_guard(&f.name), &f.name)?; } out.write_all(b"\n")?; - for f in &ds.features { + for f in rows { crate::progress::step(1)?; - if let Some(g) = &f.geometry { + if let Some(g) = f.geometry.as_deref() { // As `write_csv_cell` 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"" }; @@ -727,7 +754,7 @@ pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result write_wkt(out, g)?; out.write_all(quote)?; } - for v in &f.attrs { + for v in f.attrs { let (guard, text) = crate::io::csv_cell(v); cell(out, guard, &text)?; } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index cf4cbf6f99..61d8605674 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1,6 +1,7 @@ //! Vector readers and writers: GeoJSON, CSV (with longitude/latitude columns) and Shapefile. use std::borrow::Cow; +use std::cell::Cell; use std::collections::BTreeMap; use std::path::Path; use std::sync::atomic::AtomicUsize; @@ -904,6 +905,16 @@ fn project_pieces_leaving_out( /// place converted, as [`project_each_leaving_out`] says. fn leave_out_unplaced(f: &mut crate::Feature, to: &crate::raster::Reprojection, placed: &mut rustgis_geom::Extent) -> bool { let Some(g) = f.geometry.as_mut() else { return false }; + let lost = project_geometry(g, to, placed); + if lost { + f.geometry = None; + } + lost +} + +/// Converts `g` with `to` as [`leave_out_unplaced`] does, returning whether a place of it has none +/// in the target, when `g` is to be left out. +fn project_geometry(g: &mut Geometry, to: &crate::raster::Reprojection, placed: &mut rustgis_geom::Extent) -> bool { if to.is_identity() { return false; } @@ -921,9 +932,6 @@ fn leave_out_unplaced(f: &mut crate::Feature, to: &crate::raster::Reprojection, lost |= !c.is_finite(); } }); - if lost { - f.geometry = None; - } lost } @@ -1047,7 +1055,10 @@ pub fn write_bytes_noted( } /// [`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. +/// zipped, are refused as soon as they would pass it. Written in another system under a limit, a +/// format that goes a feature at a time converts each as it is written; one that needs the layer +/// whole (a Shapefile, GeoParquet, FlatGeobuf) is refused before its converted copy is made when +/// the features, which the copy takes again, are more than the limit. pub fn write_bytes_noted_within( ds: &Dataset, ext: &str, @@ -1066,6 +1077,19 @@ pub fn write_bytes_noted_within( let (bytes, left_out) = projected_bytes_within(ds, &ext, crs, limit)?; return Ok((bytes, left_out, Vec::new(), ds.lonlat_extent())); } + if limit.bounded() { + if goes_a_feature_at_a_time(&ext) { + let to = ds.coord_crs().to(crs).map_err(DataError::Format)?; + // A layer of no features never looks at Cancel as it is written. + crate::progress::check()?; + let tally = Cell::default(); + let (bytes, left_out) = walked_bytes_within(ds, &ext, crs, Walk::for_export(ds, &to), &tally, limit)?; + let Tally { unplaced, placed, .. } = tally.get(); + let notes = unplaced_export_note(name, &ds.name, unplaced, crs).into_iter().collect(); + return Ok((bytes, left_out, notes, lonlat_extent_placed(ds, crs, (!to.is_identity()).then_some(placed)))); + } + copy_fits(ds, crs, limit)?; + } let (projected, unplaced, placed) = project_leaving_out_placed(ds, 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(); @@ -1088,18 +1112,13 @@ fn projected_bytes(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usize) /// [`projected_bytes`] within `limit` ([`write_bytes_noted_within`]). fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> Result<(Vec, usize)> { + if goes_a_feature_at_a_time(ext) { + return walked_bytes_within(ds, ext, crs, Walk::held(ds), &Cell::default(), limit); + } crate::progress::begin(ds.features.len()); 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))?; @@ -1109,19 +1128,6 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R 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(); - (crate::zip::write_within(&[("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 = @@ -1136,21 +1142,220 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R limit.whole(made) } +/// Refuses, before it is made, the copy of `ds`'s features in `crs` that a writer needing the +/// layer whole would take, when the features are more than `limit` holds: the copy is held beside +/// the layer and the file. +fn copy_fits(ds: &Dataset, crs: Crs, limit: &Limit) -> Result<()> { + let (needs, room) = (ds.features.held_bytes(), limit.max()); + if needs <= room { + return Ok(()); + } + let (needs, room) = sizes_apart(needs, room); + Err(DataError::Format(format!( + "{}: writing it in {} takes a converted copy of its features, {needs}, more than the {room} this download has room for; select the features you need, use Make Layer From Selected Features and export that layer, export a clipped layer, or use the desktop app", + ds.name, + crs.label(), + ))) +} + +/// How two sizes, `more` larger than `less`, are said: in MiB, or in bytes where the MiB don't tell +/// them apart. +pub fn sizes_apart(more: usize, less: usize) -> (String, String) { + let (more_mib, less_mib) = (more.div_ceil(1 << 20), less.div_ceil(1 << 20)); + if more_mib > less_mib { + return (format!("{more_mib} MiB"), format!("{less_mib} MiB")); + } + (format!("{more} bytes"), format!("{less} bytes")) +} + +/// Whether a file of extension `ext` is written from one feature after another, so each can be +/// converted as it is reached. +fn goes_a_feature_at_a_time(ext: &str) -> bool { + matches!(ext, "geojson" | "json" | "csv" | "kml" | "kmz" | "gpx") +} + +/// [`projected_bytes_within`] for those formats, its features as `walk` gives them, in `crs`'s +/// coordinates; `tally` counts what the walk met. +fn walked_bytes_within(ds: &Dataset, ext: &str, crs: Crs, walk: Walk<'_>, tally: &Cell, limit: &Limit) -> Result<(Vec, usize)> { + crate::progress::begin(ds.features.len()); + let mut out = limit.buffer(); + let made = write_text(ds, ext, walk, tally, name_field(ds), crs, &mut out).and_then(|()| { + let file = out.into_inner(); + Ok(match ext { + "kmz" => crate::zip::write_within(&[("doc.kml".to_string(), file)], limit)?, + _ => file, + }) + }); + let left_out = match ext { + "kml" | "kmz" => tally.get().without_geometry, + "gpx" => tally.get().gpx_left_out, + _ => 0, + }; + limit.whole(made.map(|file| (file, left_out))) +} + +/// The text of a file of extension (or `data.convert` format) `format`: GeoJSON, CSV, KML (a +/// KMZ's document), GPX, else WKT in a CSV. `ds` gives its name, fields and kind, `walk` its +/// features, in `crs`'s coordinates. +fn write_text( + ds: &Dataset, + format: &str, + walk: Walk<'_>, + tally: &Cell, + name_field: Option, + crs: Crs, + out: &mut impl std::io::Write, +) -> Result<()> { + match format { + "geojson" | "json" => write_geojson_of(ds, walk.rows(Some(tally)), false, out), + "csv" => write_csv_of(ds, walk.rows(Some(tally)), crs, out), + "kml" | "kmz" => crate::interop::write_kml_of(ds, walk.rows(Some(tally)), name_field, out), + "gpx" => { + // GPX goes through the features twice: they are counted the first time. + let mut counted = Some(tally); + crate::interop::write_gpx_of(ds, || walk.rows(counted.take()), name_field, out) + } + _ => crate::interop::write_wkt_csv_of(ds, walk.rows(Some(tally)), out), + } +} + +/// A feature as a writer takes it: its attributes borrowed, and its geometry too unless it was +/// converted, so a large value is never copied before a limit can refuse it. +pub(crate) struct Row<'a> { + pub(crate) id: u64, + pub(crate) geometry: Option>, + pub(crate) attrs: &'a [Value], +} + +impl<'a> Row<'a> { + fn held(f: &'a crate::Feature) -> Self { + Row { id: f.id, geometry: f.geometry.as_ref().map(Cow::Borrowed), attrs: &f.attrs } + } + + /// Its value in field `field`, or Null where it has none. + pub(crate) fn value(&self, field: usize) -> &'a Value { + self.attrs.get(field).unwrap_or(&Value::Null) + } +} + +/// A layer's features as a writer walks them: as they are held, or each converted as it is +/// reached, so that a file made to be downloaded needs no converted copy of the layer. +#[derive(Clone, Copy)] +pub(crate) struct Walk<'a> { + features: &'a [crate::Feature], + convert: Option<(&'a crate::raster::Reprojection, Convert)>, +} + +/// Which conversion a walk makes: that of the copy it stands in for, so both leave out the same. +#[derive(Clone, Copy)] +enum Convert { + /// [`project_leaving_out`]'s. + Export, + /// [`Dataset::in_lonlat_leaving_out`]'s. + LonLat, +} + +/// What a walk met, counted in the features as it gave them. +#[derive(Clone, Copy)] +pub(crate) struct Tally { + /// Features whose geometry the conversion left out. + unplaced: usize, + /// Features with no geometry, those among them. + without_geometry: usize, + /// Features a GPX file leaves out ([`gpx_left_out`]). + gpx_left_out: usize, + /// The box of the places an export's conversion placed. + placed: rustgis_geom::Extent, +} + +impl Default for Tally { + fn default() -> Self { + Tally { unplaced: 0, without_geometry: 0, gpx_left_out: 0, placed: rustgis_geom::Extent::EMPTY } + } +} + +impl<'a> Walk<'a> { + pub(crate) fn held(ds: &'a Dataset) -> Self { + Walk { features: &ds.features, convert: None } + } + + /// Converted by `to` as an export in another system is. + fn for_export(ds: &'a Dataset, to: &'a crate::raster::Reprojection) -> Self { + Walk { features: &ds.features, convert: (!to.is_identity()).then_some((to, Convert::Export)) } + } + + /// Converted by `to`, its [`Dataset::lonlat_conversion`], as its copy in longitude/latitude is. + fn in_lonlat(ds: &'a Dataset, to: &'a crate::raster::Reprojection) -> Self { + Walk { features: &ds.features, convert: (!to.is_identity()).then_some((to, Convert::LonLat)) } + } + + /// Each feature's row in turn, counted in `tally` when there is one. Only a converted one's + /// geometry is made, and dropped before the next is. + pub(crate) fn rows(self, tally: Option<&'a Cell>) -> impl Iterator> { + self.features.iter().map(move |f| { + let mut placed = rustgis_geom::Extent::EMPTY; + let geometry = match (&f.geometry, self.convert) { + (None, _) => None, + (Some(g), None) => Some(Cow::Borrowed(g)), + (Some(g), Some((to, Convert::Export))) => { + let mut g = g.clone(); + (!project_geometry(&mut g, to, &mut placed)).then_some(Cow::Owned(g)) + } + (Some(g), Some((to, Convert::LonLat))) => crate::lonlat_or_left_out(g, to).map(Cow::Owned), + }; + if let Some(tally) = tally { + let mut t = tally.get(); + t.unplaced += usize::from(f.geometry.is_some() && geometry.is_none()); + t.without_geometry += usize::from(geometry.is_none()); + t.gpx_left_out += usize::from(gpx_leaves_out(geometry.as_deref())); + t.placed = t.placed.union(&placed); + tally.set(t); + } + Row { id: f.id, geometry, attrs: &f.attrs } + }) + } +} + +/// A `data.convert` format as [`write_text`] takes it: what isn't one of the four is WKT in a CSV, +/// a file's other extensions for them included. +fn text_format(format: &str) -> &str { + if matches!(format, "geojson" | "csv" | "kml" | "gpx") { format } else { "wkt" } +} + /// 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), - }; + let made = write_text(ds, text_format(format), Walk::held(ds), &Cell::default(), name_field, Crs::LonLat, &mut out); limit.whole(made.map(|()| out.into_inner())) } +/// What [`text_bytes_in_lonlat_within`] made, and what it counted as it went. +pub struct LonLatText { + pub bytes: Vec, + /// Features written without their geometry, as a place of each can't be given in + /// longitude/latitude. + pub unplaced: usize, + /// Features with no geometry in longitude/latitude, those among them. + pub without_geometry: usize, + /// Features a GPX file leaves out ([`gpx_left_out`]). + pub gpx_left_out: usize, +} + +/// [`text_bytes_within`] for a dataset held in any system: the file its copy in longitude/latitude +/// ([`Dataset::in_lonlat_leaving_out`]) gives, each feature converted as it is written, so that +/// copy is never held. +pub fn text_bytes_in_lonlat_within(ds: &Dataset, format: &str, name_field: Option, limit: &Limit) -> Result { + let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; + crate::progress::check()?; + let tally = Cell::default(); + let mut out = limit.buffer(); + let made = write_text(ds, text_format(format), Walk::in_lonlat(ds, &to), &tally, name_field, Crs::LonLat, &mut out); + let Tally { unplaced, without_geometry, gpx_left_out, .. } = tally.get(); + limit.whole(made.map(|()| LonLatText { bytes: out.into_inner(), unplaced, without_geometry, gpx_left_out })) +} + /// Writes a dataset by extension (`.geojson`/`.json`, `.csv`, `.fgb`, `.gpkg` on the desktop, /// `.parquet`/`.geoparquet`, `.shp`, `.zip`, `.kml`, `.kmz` or `.gpx`); returns the number of features the /// format couldn't hold (FlatGeobuf, KML, GPX and Shapefile hold only features with geometry). A @@ -2437,25 +2642,50 @@ pub fn to_geojson_text(ds: &Dataset) -> Result { /// bytes at a time. The features are written as they are walked, so a sink that refuses a write /// ([`crate::capped::Limit::file`]) stops it there. pub fn write_geojson(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> { - let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?; - writer.write(&ds.features)?; - std::io::Write::flush(&mut writer.finish()?)?; - Ok(()) + write_geojson_of(ds, Walk::held(ds).rows(None), false, out) +} + +/// [`write_geojson`] for the copy of `ds` in longitude/latitude +/// ([`Dataset::in_lonlat_leaving_out`]), each feature converted as it is written, so that copy is +/// never held. Returns how many were written without their geometry. +pub fn write_geojson_in_lonlat(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result { + geojson_in_lonlat(ds, false, out) +} + +/// [`write_geojson_in_lonlat`] for an OGC API Features `items` document, which also says how many +/// features it returns (`numberReturned`). +pub fn write_geojson_items_in_lonlat(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result { + geojson_in_lonlat(ds, true, out) +} + +fn geojson_in_lonlat(ds: &Dataset, items: bool, out: &mut (impl std::io::Write + ?Sized)) -> Result { + let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; + crate::progress::check()?; + let tally = Cell::default(); + write_geojson_of(ds, Walk::in_lonlat(ds, &to).rows(Some(&tally)), items, out)?; + Ok(tally.get().unplaced) } -/// [`write_geojson`] for an OGC API Features `items` document, which also says how many features -/// it returns (`numberReturned`). -pub fn write_geojson_items(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> { +/// `ds`'s collection of `rows`; with `items`, saying how many it returns. +fn write_geojson_of<'a>( + ds: &Dataset, + rows: impl Iterator>, + items: bool, + out: &mut (impl std::io::Write + ?Sized), +) -> Result<()> { let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?; - writer.write(&ds.features)?; - std::io::Write::flush(&mut writer.finish_returning(ds.features.len())?)?; + for row in rows { + writer.write_row(&row)?; + } + let mut out = if items { writer.finish_returning(ds.features.len())? } else { writer.finish()? }; + std::io::Write::flush(&mut out)?; Ok(()) } /// A feature as a GeoJSON Feature, its attributes named by `fields`. 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() + serde_json::to_value(GeoJsonFeature { fields, row: &Row::held(feature) }).unwrap_or_default() } /// [`feature_to_geojson`]'s object as it serializes, from the row itself: its geometry and text @@ -2464,18 +2694,18 @@ fn feature_to_geojson(fields: &[Field], feature: &crate::Feature) -> Json { /// holds them. struct GeoJsonFeature<'a> { fields: &'a [Field], - feature: &'a crate::Feature, + row: &'a Row<'a>, } 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; + let f = self.row; // 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(); + 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("geometry", &f.geometry.as_deref().map(GeoJsonGeometry))?; object.serialize_entry("id", &f.id)?; object.serialize_entry("properties", &properties)?; object.serialize_entry("type", "Feature")?; @@ -2521,15 +2751,17 @@ impl GeoJsonWriter { /// Writes the next features. pub(crate) fn write(&mut self, features: &[crate::Feature]) -> Result<()> { - for f in features { - crate::progress::step(1)?; - if !std::mem::take(&mut self.first) { - self.out.write_all(b",")?; - } - let feature = GeoJsonFeature { fields: &self.fields, feature: f }; - serde_json::to_writer(&mut self.out, &feature).map_err(|e| DataError::Format(e.to_string()))?; + features.iter().try_for_each(|f| self.write_row(&Row::held(f))) + } + + /// Writes the next feature. + fn write_row(&mut self, row: &Row<'_>) -> Result<()> { + crate::progress::step(1)?; + if !std::mem::take(&mut self.first) { + self.out.write_all(b",")?; } - Ok(()) + let feature = GeoJsonFeature { fields: &self.fields, row }; + serde_json::to_writer(&mut self.out, &feature).map_err(|e| DataError::Format(e.to_string())) } /// Closes the collection and gives the writer back. @@ -3782,8 +4014,15 @@ pub fn to_csv_in(ds: &Dataset, crs: Crs) -> Result { /// [`to_csv_in`]'s text, written to `out`. fn write_csv(ds: &Dataset, crs: Crs, out: &mut impl std::io::Write) -> Result<()> { + write_csv_of(ds, Walk::held(ds).rows(None), crs, out) +} + +/// `ds`'s CSV of `rows`, in `crs`'s coordinates. +fn write_csv_of<'a>(ds: &Dataset, rows: impl Iterator>, 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)?; + for row in rows { + w.write_row(&row)?; + } w.finish()?; Ok(()) } @@ -3817,32 +4056,34 @@ impl CsvWriter { /// Writes the next features, a row each. pub(crate) fn write(&mut self, features: &[crate::Feature]) -> Result<()> { - for f in features { - crate::progress::step(1)?; - let mut row: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(f.attrs.len() + 2); - if self.point { - let c = f.geometry.as_ref().and_then(|g| g.label_point()); - row.push(("", c.map(|c| c.x.to_string()).unwrap_or_default().into())); - row.push(("", c.map(|c| c.y.to_string()).unwrap_or_default().into())); - } - row.extend(f.attrs.iter().map(csv_cell)); - if row.len() != self.columns { - return Err(DataError::Format(format!("CSV: a row of {} cells under {} columns", row.len(), self.columns))); - } - // The `csv` crate takes a cell whole, so a guarded one is first joined to its - // apostrophe: a row with a long one is written without it. - if row.iter().any(|(guard, text)| !guard.is_empty() && text.len() > crate::capped::PIECE) { - self.write_past(&row)?; - continue; - } - let w = self.w.as_mut().ok_or_else(csv_stopped)?; - for (guard, text) in &row { - let written = if guard.is_empty() { w.write_field(text.as_bytes()) } else { w.write_field(format!("{guard}{text}")) }; - written.map_err(|e| DataError::Format(e.to_string()))?; - } - // Ends the row. - w.write_record(None::<&[u8]>).map_err(|e| DataError::Format(e.to_string()))?; - } + features.iter().try_for_each(|f| self.write_row(&Row::held(f))) + } + + /// Writes the next feature's row. + fn write_row(&mut self, f: &Row<'_>) -> Result<()> { + crate::progress::step(1)?; + let mut row: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(f.attrs.len() + 2); + if self.point { + let c = f.geometry.as_deref().and_then(Geometry::label_point); + row.push(("", c.map(|c| c.x.to_string()).unwrap_or_default().into())); + row.push(("", c.map(|c| c.y.to_string()).unwrap_or_default().into())); + } + row.extend(f.attrs.iter().map(csv_cell)); + if row.len() != self.columns { + return Err(DataError::Format(format!("CSV: a row of {} cells under {} columns", row.len(), self.columns))); + } + // The `csv` crate takes a cell whole, so a guarded one is first joined to its + // apostrophe: a row with a long one is written without it. + if row.iter().any(|(guard, text)| !guard.is_empty() && text.len() > crate::capped::PIECE) { + return self.write_past(&row); + } + let w = self.w.as_mut().ok_or_else(csv_stopped)?; + for (guard, text) in &row { + let written = if guard.is_empty() { w.write_field(text.as_bytes()) } else { w.write_field(format!("{guard}{text}")) }; + written.map_err(|e| DataError::Format(e.to_string()))?; + } + // Ends the row. + w.write_record(None::<&[u8]>).map_err(|e| DataError::Format(e.to_string()))?; Ok(()) } @@ -5540,31 +5781,41 @@ impl CsvLosses { /// As [`CsvLosses::of`], for features whose points are written where `place` puts them (in /// another system): only the points are converted, not the features. fn of_placed(features: &[crate::Feature], gt: GeometryType, fields: &[Field], place: &dyn Fn(Coord) -> Option) -> Result { - let mut out = Self { points: gt == GeometryType::Point, guarded: vec![0; fields.len()], ..Self::default() }; + let mut out = Self::none_yet(gt, fields); for feature in features { crate::progress::check()?; - for (count, value) in out.guarded.iter_mut().zip(&feature.attrs) { - *count += usize::from(matches!(value, Value::Text(text) if csv_needs_guard(text))); - } - let geometry = feature.geometry.as_ref(); - let point = if out.points { geometry.and_then(Geometry::label_point) } else { None }; - if out.points && !point.and_then(place).is_some_and(usable_degree_point) { - out.unusable_points += 1; - } - let Some(g) = geometry else { continue }; - match (gt, g) { - (GeometryType::Point, Geometry::Point(_)) => {} - // No point to write: its coordinate cells are left empty. - (GeometryType::Point, _) if point.is_none() => out.unwritten += 1, - (GeometryType::Point, Geometry::MultiPoint(v)) if v.len() <= 1 => {} - (GeometryType::Point, _) => out.as_one_point += 1, - // A layer of lines or polygons, or one that declares no type: no coordinates. - _ => out.unwritten += 1, - } + out.count(&Row::held(feature), gt, place); } Ok(out) } + /// The losses of such a layer before any feature is counted. + fn none_yet(gt: GeometryType, fields: &[Field]) -> Self { + Self { points: gt == GeometryType::Point, guarded: vec![0; fields.len()], ..Self::default() } + } + + /// Adds `feature`'s losses, its point written where `place` puts it. + fn count(&mut self, feature: &Row<'_>, gt: GeometryType, place: &dyn Fn(Coord) -> Option) { + for (count, value) in self.guarded.iter_mut().zip(feature.attrs) { + *count += usize::from(matches!(value, Value::Text(text) if csv_needs_guard(text))); + } + let geometry = feature.geometry.as_deref(); + let point = if self.points { geometry.and_then(Geometry::label_point) } else { None }; + if self.points && !point.and_then(place).is_some_and(usable_degree_point) { + self.unusable_points += 1; + } + let Some(g) = geometry else { return }; + match (gt, g) { + (GeometryType::Point, Geometry::Point(_)) => {} + // No point to write: its coordinate cells are left empty. + (GeometryType::Point, _) if point.is_none() => self.unwritten += 1, + (GeometryType::Point, Geometry::MultiPoint(v)) if v.len() <= 1 => {} + (GeometryType::Point, _) => self.as_one_point += 1, + // A layer of lines or polygons, or one that declares no type: no coordinates. + _ => self.unwritten += 1, + } + } + /// One notice for each loss of a layer written to `target`; none without loss. Geometry /// not written is counted by feature, whatever its kind: a layer of one type can hold others. pub fn notes(&self, fields: &[Field], target: &str) -> Vec { @@ -5763,6 +6014,11 @@ impl TextLosses { /// in memory, which is less than the write it follows (the same formatting, plus the write), /// and a streamed export counts a chunk at a time, looking at Cancel between chunks. pub fn of(features: &[crate::Feature], fields: &[Field], gt: GeometryType, ext: &str, name_field: Option) -> Self { + Self::of_rows(features.iter().map(Row::held), fields, gt, ext, name_field) + } + + /// [`TextLosses::of`] for features given a row at a time. + fn of_rows<'a>(rows: impl Iterator>, fields: &[Field], gt: GeometryType, ext: &str, name_field: Option) -> Self { let (csv, shp, kml, gpx) = (matches!(ext, "csv" | "wkt"), matches!(ext, "shp" | "zip"), matches!(ext, "kml" | "kmz"), ext == "gpx"); if !(csv || shp || kml || gpx) { return Self::default(); @@ -5805,10 +6061,10 @@ impl TextLosses { GeometryType::Polyline => 1, _ => 2, }; - for feature in features { - let layer = match &feature.geometry { + for feature in rows { + let layer = match feature.geometry.as_deref() { _ if csv => 0, - g if shp && shapefile_keeps(g.as_ref(), gt) => 0, + g if shp && shapefile_keeps(g, gt) => 0, Some(g) if kml && crate::kml::keeps(g) => { vertices = vertices.saturating_add(crate::kml::lost_vertices(g)); layer_of(g) @@ -6056,15 +6312,13 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option // geographic system's, whose points alone are converted to be checked (no copy of the // layer); a projected system's aren't degrees, so aren't checked as such. let losses = if crs == Crs::LonLat { - match ds.in_lonlat() { - Ok(ds) => CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?, + let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; + match csv_losses_in_lonlat(ds, &to)? { + (losses, 0) => losses, // A place that can't be given there (written without its geometry, and said // by [`unplaced_export_note`]): its points converted one by one, those that // can't be counted as unusable. - Err(_) => { - let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; - CsvLosses::of_placed(&ds.features, ds.geometry_type, &ds.fields, &|c| to.point(c))? - } + _ => CsvLosses::of_placed(&ds.features, ds.geometry_type, &ds.fields, &|c| to.point(c))?, } } else if crs.is_geographic() && crs != ds.coord_crs() { let to = ds.coord_crs().to(crs).map_err(DataError::Format)?; @@ -6072,9 +6326,7 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option } else { CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)? }; - let mut notes = losses.notes(&ds.fields, target); - notes.extend(losses.coordinates_note_in(&ds.fields, target, crs).map(crate::loss::Note::plain)); - notes + csv_notes(&losses, &ds.fields, target, crs) } "wkt" => { let mut notes = Vec::new(); @@ -6094,23 +6346,80 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option Ok(notes.into()) } +/// What a CSV written in `crs` says of `losses`. +fn csv_notes(losses: &CsvLosses, fields: &[Field], target: &str, crs: Crs) -> Vec { + let mut notes = losses.notes(fields, target); + notes.extend(losses.coordinates_note_in(fields, target, crs).map(crate::loss::Note::plain)); + notes +} + +/// [`CsvLosses`] of `ds`'s copy in longitude/latitude (by `to`), each feature converted on its own +/// so that copy is never held, and how many of them lose their geometry there. +fn csv_losses_in_lonlat(ds: &Dataset, to: &crate::raster::Reprojection) -> Result<(CsvLosses, usize)> { + let mut losses = CsvLosses::none_yet(ds.geometry_type, &ds.fields); + let tally = Cell::default(); + for feature in Walk::in_lonlat(ds, to).rows(Some(&tally)) { + crate::progress::check()?; + losses.count(&feature, ds.geometry_type, &Some); + } + Ok((losses, tally.get().unplaced)) +} + +/// What [`export_losses_notes`] says of `ds`'s copy in longitude/latitude +/// ([`Dataset::in_lonlat_leaving_out`]), without that copy being held. (KML's and GPX's are +/// worked out from `ds` as it is, which converts as they go.) +pub fn export_losses_notes_in_lonlat(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result { + if ext != "csv" { + return export_losses_notes(ds, ext, name_field, target); + } + let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; + let (losses, _) = csv_losses_in_lonlat(ds, &to)?; + let mut notes = csv_notes(&losses, &ds.fields, target, Crs::LonLat); + notes.extend(text_losses_written(ds, ext, name_field)?.notes(&ds.fields, target)); + Ok(notes.into()) +} + /// [`TextLosses`] of `ds` as written to a file with extension `ext`. KML and GPX hold /// longitude/latitude, so a layer held in another system has its places checked where the writer -/// puts them: a chunk of features converted at a time (no copy of the layer), one with a place +/// puts them: a run of features' geometry converted at a time (no copy of the layer), one with a place /// that can't be given there without its geometry, as it is written. fn text_losses_written(ds: &Dataset, ext: &str, name_field: Option) -> Result { - let of = |features: &[crate::Feature]| TextLosses::of(features, &ds.fields, ds.geometry_type, ext, name_field); let to = if matches!(ext, "kml" | "kmz" | "gpx") { Some(ds.lonlat_conversion().map_err(DataError::of_conversion)?) } else { None }; - let Some(to) = to.filter(|to| !to.is_identity()) else { return Ok(of(&ds.features)) }; + let Some(to) = to.filter(|to| !to.is_identity()) else { + return Ok(TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field)); + }; let mut losses = TextLosses::default(); - for chunk in ds.features.chunks(8192) { - let mut chunk = chunk.to_vec(); - project_each_leaving_out(&mut chunk, &to, false)?; - losses += of(&chunk); + // Converted a run at a time, on several threads where that pays; only their geometry is. + let mut rest: &[crate::Feature] = &ds.features; + while !rest.is_empty() { + let (run, after) = rest.split_at(run_of(rest, 8192, 1 << 16)?); + rest = after; + let mut placed: Vec = + run.iter().map(|f| crate::Feature { id: f.id, geometry: f.geometry.clone(), attrs: Vec::new() }).collect(); + project_each_leaving_out(&mut placed, &to, false)?; + let rows = run.iter().zip(placed).map(|(f, p)| Row { id: f.id, geometry: p.geometry.map(Cow::Owned), attrs: &f.attrs }); + losses += TextLosses::of_rows(rows, &ds.fields, ds.geometry_type, ext, name_field); } Ok(losses) } +/// How many of `features` to take next: at most `most` and at least one, ended once they hold +/// `vertices` vertices or more. +fn run_of(features: &[crate::Feature], most: usize, vertices: usize) -> Result { + let (mut n, mut held) = (0usize, 0usize); + for f in features.iter().take(most) { + crate::progress::check()?; + if n > 0 && held >= vertices { + break; + } + if let Some(g) = &f.geometry { + g.for_each_coord(|_| held += 1); + } + n += 1; + } + Ok(n) +} + /// KML fields whose name is blank once trimmed, with values in the placemarks written: each is /// written as ``, which reading drops, so the column and its values are gone /// (#2415). A field with no value written is said by [`kml_empty_fields_note`]. @@ -6199,12 +6508,16 @@ fn kml_empty_fields_note(ds: &Dataset, placed: &[bool], target: &str) -> Result< /// Features a GPX file of `ds` leaves out: those without geometry, and multipoints without a /// point, which give no waypoint. pub fn gpx_left_out(ds: &Dataset) -> usize { - let empty = |g: &Option| match g { + ds.features.iter().filter(|f| gpx_leaves_out(f.geometry.as_ref())).count() +} + +/// Whether a GPX file leaves out a feature with geometry `g` ([`gpx_left_out`]). +fn gpx_leaves_out(g: Option<&Geometry>) -> bool { + match g { None => true, Some(Geometry::MultiPoint(v)) => v.is_empty(), Some(_) => false, - }; - ds.features.iter().filter(|f| empty(&f.geometry)).count() + } } /// What a GPX file of `ds` can't hold, each feature named from field `name_field`: other diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 8f2258725f..4c843c95bb 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1264,7 +1264,7 @@ impl Dataset { for (i, f) in out.features.iter_mut().enumerate() { stop_when_asked(i)?; if let Some(g) = f.geometry.take() { - f.geometry = convert_keeping_missing(&to, &g, &HeldPlaces::default()); + f.geometry = lonlat_or_left_out(&g, &to); unplaced += usize::from(f.geometry.is_none()); } } @@ -1605,6 +1605,12 @@ fn edit_into_own(to: &raster::Reprojection, g: &Geometry, held: &HeldPlaces) -> if clamped { None } else { convert_keeping_missing(to, g, held) } } +/// `g` in longitude/latitude by `to`, or `None` when a place of it can't be given there: what +/// [`Dataset::in_lonlat_leaving_out`] makes of each feature's geometry. +fn lonlat_or_left_out(g: &Geometry, to: &raster::Reprojection) -> Option { + convert_keeping_missing(to, g, &HeldPlaces::default()) +} + /// `g` converted, its missing coordinates (NaN, infinite) kept as they are and a held place /// written as held; `None` when a place that is one can't be converted. fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldPlaces) -> Option { diff --git a/crates/data/tests/projected_download_memory.rs b/crates/data/tests/projected_download_memory.rs new file mode 100644 index 0000000000..f5013c69df --- /dev/null +++ b/crates/data/tests/projected_download_memory.rs @@ -0,0 +1,94 @@ +//! The memory a limited write takes of a layer held in another system than the file's: it makes +//! no converted copy of the layer before the limit refuses it. A test binary of its own, as the +//! peak it reads is the whole process's. +#![cfg(target_os = "linux")] + +use rustgis_data::capped::Limit; +use rustgis_data::raster::Crs; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; + +/// The features of the layer, and the bytes of text each holds. +const ROWS: usize = 120_000; +const TEXT: usize = 400; +/// The room each file is held to. +const ROOM: usize = 1 << 20; + +/// The most memory this process has held since the peak was last reset, in bytes. +fn peak_bytes() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let line = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).unwrap(); + line.trim().trim_end_matches("kB").trim().parse::().unwrap() * 1024 +} + +/// How far `run` takes the peak past what is held as it starts. +fn growth(run: impl FnOnce()) -> usize { + // Linux sets the peak back to what is held now. + std::fs::write("/proc/self/clear_refs", "5").unwrap(); + let before = peak_bytes(); + run(); + peak_bytes().saturating_sub(before) +} + +/// The CSV notices, counted before a file is written, then each format, of which `shp`, `parquet` +/// and `fgb` need the layer whole in the other system. The last write a layer of one feature, whose text alone is +/// as large, and count what KML loses of it. +const CASES: [&str; 13] = + ["notices", "geojson", "csv", "kml", "kmz", "gpx", "shp", "parquet", "fgb", "value geojson", "value csv", "value kml", "value notices"]; + +/// The environment variable naming the one case a process of this test measures. +const CASE: &str = "PROJECTED_DOWNLOAD_CASE"; + +#[test] +fn a_limited_write_in_another_system_makes_no_copy_of_the_layer() { + if let Ok(case) = std::env::var(CASE) { + return measure(&case); + } + // A process for each: memory one case frees would hide what the next takes. + let failed: Vec<&str> = CASES + .into_iter() + .filter(|case| { + let run = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "a_limited_write_in_another_system_makes_no_copy_of_the_layer", "--nocapture"]) + .env(CASE, case) + .status() + .unwrap(); + !run.success() + }) + .collect(); + assert!(failed.is_empty(), "{failed:?}"); +} + +fn measure(case: &str) { + let mut ds = Dataset::new("held", GeometryType::Point, vec![Field::new("note", FieldType::Text)]); + let one = case.strip_prefix("value "); + let (rows, text) = if one.is_some() { (1, ROWS * TEXT) } else { (ROWS, TEXT) }; + for i in 0..rows { + ds.push(Some(Geometry::Point(Coord::new(2.0 + (i % 100) as f64 * 0.01, 48.0))), vec![Value::Text("x".repeat(text))]); + } + ds.hold_in(Crs::from_epsg(32631).unwrap()).unwrap(); + let held = ds.features.held_bytes(); + assert!(held > 40 << 20, "{held}"); + let format = one.unwrap_or(case); + let notices = format == "notices"; + let whole = matches!(case, "shp" | "parquet" | "fgb"); + let (mut said, mut passed) = (None, false); + let grew = growth(|| { + if notices { + let ext = if one.is_some() { "kml" } else { "csv" }; + rustgis_data::io::export_losses_notes_in(&ds, ext, None, "t", Crs::LonLat).unwrap(); + return; + } + let crs = if case == "shp" { Crs::from_epsg(32632).unwrap() } else { Crs::LonLat }; + let limit = Limit::new(ROOM); + said = rustgis_data::io::write_bytes_noted_within(&ds, format, crs, "t", &limit).err().map(|e| e.to_string()); + passed = limit.passed(); + }); + eprintln!("{case}: the peak grew {:.3} of the layer ({} KiB of {} KiB)", grew as f64 / held as f64, grew >> 10, held >> 10); + assert!(grew < held / 4, "{case}: the peak grew {} MiB, the layer holding {} MiB", grew >> 20, held >> 20); + assert_eq!(said.is_some(), !notices, "{case}: an over-limit write is refused"); + assert_eq!(passed, !whole && !notices, "{case}: {said:?}"); + if whole { + let e = said.unwrap_or_else(|| panic!("{case}: not refused")); + assert!(e.contains("held: writing it in") && e.contains("Make Layer From Selected Features"), "{case}: {e}"); + } +} diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 96d2f73680..593042c04f 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1357,6 +1357,9 @@ struct MapInputs<'a> { /// The view's longitude/latitude extent, worked out the first time a tool asks for it (it /// inverse-projects the view, which most tools never need). view: std::cell::OnceCell>, + /// The room a file the tool makes has, where it is downloaded ([`Session::download_room`]); + /// `None` for a file that is written. + room: Option, } impl MapInputs<'_> { @@ -1434,6 +1437,16 @@ impl MapInputs<'_> { Ok(()) } + /// The file `file_name` as `make` builds it, within the room a download has: stopped as it + /// passes the room, and refused in the words a command's download is. + fn file_within(&self, file_name: &str, make: impl FnOnce(&rustgis_data::capped::Limit) -> Result) -> Result { + let limit = rustgis_data::capped::Limit::new(self.room.map_or(usize::MAX, |room| room.bytes)); + make(&limit).map_err(|e| match self.room { + Some(room) if limit.passed() => room.refusal(file_name), + _ => e, + }) + } + /// The flat map's projection, built on first use. fn flat(&self) -> Option<&(String, rustgis_map::projection::Flat, f64)> { let map = &self.snap.map; @@ -1549,6 +1562,7 @@ fn inputs_of<'a>( _held: held, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new(), + room: None, }) } @@ -2445,16 +2459,18 @@ impl Inputs for MapInputs<'_> { min_zoom: u8, max_zoom: u8, source_layer: &str, + file_name: &str, ) -> Result<(Vec, Vec), String> { - let out = crate::render::rustgis_tiles::vector_export::export(dataset, rows, min_zoom, max_zoom, source_layer)?; + use crate::render::rustgis_tiles::vector_export::export_within; + let out = self.file_within(file_name, |limit| export_within(dataset, rows, min_zoom, max_zoom, source_layer, limit))?; Ok((out.bytes, out.messages)) } - fn raster_to_pmtiles(&self, layer: &str, min_zoom: u8, max_zoom: u8) -> Result, String> { + fn raster_to_pmtiles(&self, layer: &str, min_zoom: u8, max_zoom: u8, file_name: &str) -> Result, String> { let map = &self.snap.map; let layer = map.layer_by_name(layer).ok_or_else(|| format!("no raster layer named '{layer}'"))?; let raster = layer.raster.as_ref().ok_or_else(|| format!("no raster layer named '{}'", layer.name))?; let opacity = map.layer_opacity(layer); - crate::render::raster_export::export(raster, min_zoom, max_zoom, opacity) + self.file_within(file_name, |limit| crate::render::raster_export::export_within(raster, min_zoom, max_zoom, opacity, limit)) } fn dataset(&self, layer: &str) -> Option<&Dataset> { // (A standalone table converted for the run is had by its number, [`table_key`].) @@ -3641,6 +3657,13 @@ pub(crate) fn execute( } #[cfg(not(target_arch = "wasm32"))] let read = recording.then(|| Snapshot::owned(s)); + // A tool's file is a download in the browser: refused now when no more can wait, before + // any of it is made. + let room = if writes_files(spec) { s.download_room() } else { Ok(None) }; + let room = match room { + Ok(room) => room, + Err(e) => return apply_with(s, run_of(t0), kept(), Err(e), 0, opts), + }; // Reading the inputs stops on Cancel too, as a run the app starts on a thread does. #[cfg(not(target_arch = "wasm32"))] let _probe = rustgis_analysis::control::install_progress(Some(control.clone())); @@ -3648,7 +3671,7 @@ pub(crate) fn execute( // raster file read in place, as one the app starts on a thread does. let tiled = tiled_for(pin); let inputs = match map_inputs(s, Some(spec), params, tiled) { - Ok(inputs) => inputs, + Ok(inputs) => MapInputs { room, ..inputs }, // A batch item that can't read its input is kept in the history as a failed run. Err(e) if opts.record.is_some() => return apply_with(s, run_of(t0), kept(), Err(e), now_ms().saturating_sub(t0), opts), Err(e) => return Err(e), diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 93092c533d..3fd423afba 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -937,6 +937,9 @@ fn package_map( // geometry: one notice for all the layers. let mut unplaced = (0usize, Vec::new()); if mobile { + if tol > 0.0 && out.downloads() { + simplified_copies_fit(&m, out.most())?; + } for l in &mut m.layers { if l.is_raster() || tol <= 0.0 { continue; @@ -983,6 +986,26 @@ fn package_map( Ok(archive) } +/// Refuses a mobile package, before any layer is copied, when the copies simplifying takes (one of +/// each feature layer's features, all held until the package is made) are more than the `most` +/// bytes its download has room for. +fn simplified_copies_fit(m: &Map, most: usize) -> Result<(), String> { + let mut needs = 0usize; + for l in m.layers.iter().filter(|l| !l.is_raster()) { + let before = needs; + needs = needs.saturating_add(l.dataset.features.held_bytes()); + if needs > most { + let with = if before == 0 { "simplifying it takes" } else { "with the layers before it, simplifying it takes" }; + let (needs, room) = rustgis_data::io::sizes_apart(needs, most); + return Err(format!( + "{}: {with} a copy of {needs} of features, more than the {room} this download has room for; hide the layers you don't need, select the features you need and use Make Layer From Selected Features, give \"tolerance\": 0 to package without simplifying, or use the desktop app", + l.name + )); + } + } + Ok(()) +} + /// The geoprocessing history with the layers its runs made, as GeoJSON. fn package_gp(s: &mut Session, out: Output<'_>) -> Result, String> { if s.project.gp_history.is_empty() { @@ -1004,13 +1027,17 @@ fn package_gp(s: &mut Session, out: Output<'_>) -> Result, String> { file = format!("results/{base}_{k}.geojson"); } // GeoJSON is longitude/latitude, whatever system the result holds its coordinates in; a - // feature with a place that can't be given there is written without its geometry. - let (ds, lost) = l.dataset.in_lonlat_leaving_out()?; + // feature with a place that can't be given there is written without its geometry. Each + // is converted as it is written, with no converted copy of the layer. + let mut lost = 0; + parts.make(file, |w| { + lost = rustgis_data::io::write_geojson_in_lonlat(&l.dataset, w).map_err(|e| e.to_string())?; + Ok(()) + })?; if lost > 0 { unplaced.0 += lost; unplaced.1.push(l.name.clone()); } - parts.make(file, |w| rustgis_data::io::write_geojson(&ds, w).map_err(|e| e.to_string()))?; } let archive = parts.zip()?; if let Some(said) = rustgis_data::unplaced_note("Geoprocessing package", &unplaced.1.join(", "), unplaced.0) { diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index c0651320f7..7629a3f0d0 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -1017,12 +1017,14 @@ fn ogc_entries(parts: &mut Parts<'_>, title: &str, layers: &[&Dataset], unplaced } parts.push(format!("collections/{id}.json"), serde_json::to_vec_pretty(&col).map_err(|e| e.to_string())?)?; // GeoJSON is longitude/latitude, whatever system the layer holds its coordinates in; a - // feature with a place that can't be given there is written without its geometry. - let (lonlat, lost) = ds.in_lonlat_leaving_out()?; - unplaced.add(&ds.name, lost); + // feature with a place that can't be given there is written without its geometry. Each + // is converted as it is written, with no converted copy of the layer. + let mut lost = 0; parts.make(format!("collections/{id}/items.json"), |w| { - rustgis_data::io::write_geojson_items(&lonlat, w).map_err(|e| e.to_string()) + lost = rustgis_data::io::write_geojson_items_in_lonlat(ds, w).map_err(|e| e.to_string())?; + Ok(()) })?; + unplaced.add(&ds.name, lost); cols.push(col); } let landing = json!({"title": title, "links": [ @@ -1041,7 +1043,7 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, out: Output<'_ let src = safe(&l.name); // The same features as the collection's items, counted there. parts.make(format!("{src}.geojson"), |w| { - rustgis_data::io::write_geojson(&l.dataset.in_lonlat_leaving_out()?.0, w).map_err(|e| e.to_string()) + rustgis_data::io::write_geojson_in_lonlat(&l.dataset, w).map(drop).map_err(|e| e.to_string()) })?; let mut m = s.map().clone(); m.layers = vec![l.clone()]; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 95a62b5a95..dafa296fef 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2820,30 +2820,27 @@ fn converted(ds: &Dataset, p: &Value, download: Option) -> 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)?; // Every format here is longitude/latitude, whatever system the layer holds its coordinates - // 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 encode = |limit: &rustgis_data::capped::Limit| rustgis_data::io::text_bytes_within(&lonlat, format, name_field, limit); - let text = match download { + // in: each feature is converted as it is written, with no converted copy of the layer. One + // with a place that can't be given there is written without its geometry, and said. + // (A system that can't be converted at all is refused in its own words, not as the file's.) + ds.lonlat_conversion()?; + let encode = |limit: &rustgis_data::capped::Limit| rustgis_data::io::text_bytes_in_lonlat_within(ds, format, name_field, limit); + let made = 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); - notes.extend(rustgis_data::unplaced_note(target, &ds.name, unplaced)); + notes.extend(rustgis_data::unplaced_note(target, &ds.name, made.unplaced)); // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. - notes.extend(rustgis_data::io::export_losses_notes(&lonlat, format, name_field, target).map_err(|e| e.to_string())?); + notes.extend(rustgis_data::io::export_losses_notes_in_lonlat(ds, format, name_field, target).map_err(|e| e.to_string())?); // KML and GPX hold features with geometry only: counted in what is written, so a feature // whose geometry is left out above is counted as left out too. if let ext @ ("kml" | "gpx") = format { - let without = if ext == "gpx" { - rustgis_data::io::gpx_left_out(&lonlat) - } else { - lonlat.features.iter().filter(|f| f.geometry.is_none()).count() - }; + let without = if ext == "gpx" { made.gpx_left_out } else { made.without_geometry }; notes.extend(rustgis_data::io::left_out_note(target, ext, without)); } - Ok((text, notes)) + Ok((made.bytes, notes)) } /// Binds the extent layer, or all full-extent layers, without computing a view or loading pixels. diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs index 7972d8ce58..1e1006c6c8 100644 --- a/crates/engine/src/tests/browser_exports.rs +++ b/crates/engine/src/tests/browser_exports.rs @@ -749,8 +749,8 @@ fn a_browser_file_command_downloads_the_desktops_file_and_says_the_same() { /// Every command that saves, packages or shares a file, over the limit (a stand-in of ten /// bytes), is stopped as the file is made: nothing waits to be downloaded, and the refusal says -/// what to do. A bookmarks file, of a bounded size, is refused once made. -/// Under the limit, each downloads. +/// what to do. A bookmarks file, of a bounded size, is refused once made, and a mobile package +/// before the copies it simplifies are. Under the limit, each downloads. #[test] fn a_browser_file_command_over_the_limit_is_stopped_as_it_is_made() { const STOPPED: &str = "stopped once the file passed"; @@ -767,7 +767,11 @@ fn a_browser_file_command_over_the_limit_is_stopped_as_it_is_made() { let refusal = if command == "bookmark.save" { MADE } else { STOPPED }; s.download_cap = Some(10); let e = s.run(command, &to(¶ms, file)).unwrap_err(); - assert!(e.contains(file) && e.contains(refusal) && e.contains("make a smaller file"), "{command} {file}: {e}"); + if file == "mobile.rgismpk" { + assert!(e.contains("simplifying it takes a copy") && e.contains("desktop app"), "{command} {file}: {e}"); + } else { + assert!(e.contains(file) && e.contains(refusal) && e.contains("make a smaller file"), "{command} {file}: {e}"); + } assert!(s.take_gp_files().is_empty(), "{command} {file}"); s.download_cap = Some(8 << 20); let pending = s.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); @@ -992,3 +996,189 @@ fn what_a_download_cant_stand_in_for_is_refused() { s.run("raster.mosaic", &json!({"inputs": ["Dem", "Dem"]})).unwrap(); s.run("share.dataStore", &json!({})).unwrap(); } + +/// [`session`] with a few points a vector tile archive can hold. +fn spots(files: &Files, browser: bool) -> Session { + let mut s = session(files, browser); + let mut ds = Dataset::new("Spots", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for i in 0..40 { + let at = rustgis_data::Coord::new(f64::from(i) * 4.0 - 80.0, f64::from(i) - 20.0); + ds.push(Some(Geometry::Point(at)), vec![Cell::Text(format!("spot {i}"))]); + } + s.map_mut().add_dataset(ds); + s +} + +/// A tool's file where files are downloaded has the room the downloads waiting leave: one that +/// fits it to the byte is the desktop's file, with what the desktop says of it; with a byte less +/// it is refused as it is made, nothing waits, and the history keeps the failed run. +#[test] +fn a_browser_tool_file_is_held_to_its_room_as_it_is_made() { + for (tool, input, file) in [("vectorToPmtiles", "Spots", "spots.pmtiles"), ("rasterToPmtiles", "Dem", "dem.pmtiles")] { + let files = Files::new(); + let params = |output: &str| json!({"tool": tool, "params": {"input": input, "minZoom": 0, "maxZoom": 3, "output": output}}); + let mut desktop = spots(&files, false); + let path = files.path().join(file); + desktop.run("gp.run", ¶ms(path.to_str().unwrap())).unwrap(); + let written = std::fs::read(&path).unwrap(); + let desktop_said = desktop.project.gp_history.last().unwrap().messages.clone(); + + let mut s = spots(&files, true); + s.download_cap = Some(written.len()); + let pending = s.run("gp.run", ¶ms(file)).unwrap_or_else(|e| panic!("{tool}: {e}")); + let (_, bytes, answer) = deliver(&mut s, &pending, None); + assert!(bytes == written, "{tool}: {} bytes downloaded, {} written", bytes.len(), written.len()); + assert_eq!(answer.unwrap()["messages"], json!(desktop_said), "{tool}"); + + s.download_cap = Some(written.len() - 1); + let e = s.run("gp.run", ¶ms(file)).unwrap_err(); + assert!(e.contains(&format!("{file}: stopped once the file passed")) && e.contains("make a smaller file"), "{tool}: {e}"); + assert!(s.take_gp_files().is_empty(), "{tool}"); + let record = s.project.gp_history.last().unwrap(); + assert!(!record.ok && record.messages == [e.clone()], "{tool}: {:?}", record.messages); + } +} + +/// A script, a model and a task step run a tool's file under the same room. +#[test] +fn a_browser_tool_file_from_a_script_model_or_task_is_held_to_its_room() { + let tool = json!({"tool": "vectorToPmtiles", "params": {"input": "Spots", "minZoom": 0, "maxZoom": 0}}); + let files = Files::new(); + let mut s = spots(&files, true); + s.run("model.new", &json!({"name": "File", "steps": [tool]})).unwrap(); + s.run("task.new", &json!({"name": "File", "steps": [{"title": "Export", "command": "gp.run", "params": tool}]})).unwrap(); + s.download_cap = Some(100); + for (command, params) in [ + ("script.run", json!({"script": format!("gp.run {tool}")})), + ("model.run", json!({"name": "File"})), + ("task.run", json!({"task": "File"})), + ] { + let e = s.run(command, ¶ms).unwrap_err(); + assert!(e.contains(".pmtiles: stopped once the file passed"), "{command}: {e}"); + assert!(s.take_gp_files().is_empty(), "{command}"); + } +} + +/// Runs the raster tile tool over Dem, counting how often the run looks at Cancel, once or more +/// a tile, and takes what it queued. +fn tiles_counted(s: &mut Session) -> (CmdResult, u64) { + let control = rustgis_analysis::control::Control::cancelled_at_look(u64::MAX); + let params = json!({"input": "Dem", "minZoom": 0, "maxZoom": 11}); + let made = crate::cmd::gp::run_tool_with(s, "rasterToPmtiles", ¶ms, &control); + s.take_gp_files(); + (made, control.looked()) +} + +/// A tool that makes a file draws no tile after the one that takes the file past its room. +#[test] +fn a_browser_tool_file_past_its_room_draws_no_more_tiles() { + let files = Files::new(); + let mut s = session(&files, true); + let (made, whole) = tiles_counted(&mut s); + made.unwrap(); + assert!(whole > 100, "{whole} looks for the whole archive"); + // Room for the header, not for a tile. + s.download_cap = Some(200); + let (made, looked) = tiles_counted(&mut s); + assert!(looked * 10 < whole, "{looked} looks past the room, {whole} for the whole archive: {made:?}"); + let e = made.unwrap_err(); + assert!(e.contains("stopped once the file passed"), "{e}"); +} + +/// A tool that makes a file is refused before it draws a tile when no more downloads can wait. +#[test] +fn a_browser_tool_file_is_refused_before_it_is_made_when_no_more_can_wait() { + let files = Files::new(); + let mut s = session(&files, true); + for i in 0..crate::cmd::exports::MAX_DOWNLOADS { + s.run("share.exportTable", &json!({"table": "Totals", "path": format!("{i}.csv")})).unwrap(); + } + let (made, looked) = tiles_counted(&mut s); + // The one look before a run starts. + assert!(looked <= 1, "{looked} looks with the queue full: {made:?}"); + let e = made.unwrap_err(); + assert!(e.contains("file export queue limit reached"), "{e}"); + assert!(!s.project.gp_history.last().unwrap().ok); +} + +/// [`session`] with the layer "Held" in UTM 31N: points, one of them a place that can't be given +/// in longitude/latitude, with text that exports have something to say of. +fn held_in_utm(files: &Files, browser: bool, rows: u32) -> Session { + let mut s = session(files, browser); + let mut ds = Dataset::new("Held", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for i in 0..rows { + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(2.0 + f64::from(i % 100) * 0.01, 48.0))), vec![Cell::Text(format!(" ={i}"))]); + } + ds.hold_in(rustgis_data::raster::Crs::from_epsg(32631).unwrap()).unwrap(); + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(1e9, 5_411_500.0))), vec![Cell::Text("far east".into())]); + s.map_mut().add_dataset(ds); + s +} + +/// A layer held in another system downloads the file the desktop writes, with what the desktop +/// says of it, however it is converted on the way. +#[test] +fn a_browser_download_of_a_projected_layer_is_the_desktops_file() { + let cases = [ + ("share.exportLayer", json!({"layer": "Held"}), "h.geojson", true), + ("share.exportLayer", json!({"layer": "Held"}), "h.csv", true), + ("share.exportLayer", json!({"layer": "Held"}), "h.kml", true), + ("share.exportLayer", json!({"layer": "Held"}), "h.kmz", true), + ("share.exportLayer", json!({"layer": "Held"}), "h.gpx", true), + ("share.exportLayer", json!({"layer": "Held", "crs": "EPSG:32632"}), "h.csv", true), + ("data.convert", json!({"layer": "Held", "format": "geojson"}), "c.geojson", true), + ("data.convert", json!({"layer": "Held", "format": "csv"}), "c.csv", true), + ("data.convert", json!({"layer": "Held", "format": "kml"}), "c.kml", true), + ("data.convert", json!({"layer": "Held", "format": "gpx"}), "c.gpx", true), + ("data.convert", json!({"layer": "Held", "format": "wkt"}), "c.txt", true), + ("share.webLayer", json!({"layer": "Held"}), "web.zip", false), + ("share.geodataService", json!({}), "service.zip", false), + ]; + for (command, params, file, same_bytes) in cases { + let files = Files::new(); + let mut desktop = held_in_utm(&files, false, 20); + let path = files.path().join(file); + let path = path.to_str().unwrap(); + let mark = desktop.notice_mark(); + 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 mut desktop_said: Vec = + said(&desktop, mark).into_iter().map(|n| n.replace(&folder, "")).filter(|n| !says_it_is_out(n)).collect(); + desktop_said.sort(); + assert!(desktop_said.iter().any(|n| n.contains("can't be given in")), "{command} {file}: {desktop_said:?}"); + let mut browser = held_in_utm(&files, true, 20); + let mark = browser.notice_mark(); + let pending = browser.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + let (_, bytes, answer) = deliver(&mut browser, &pending, None); + answer.unwrap(); + if same_bytes { + assert!(bytes == written, "{command} {file}: {} bytes downloaded, {} written", bytes.len(), written.len()); + } else { + assert_same_shape(&bytes, &written, &format!("{command} {file}")); + } + let mut rest: Vec<_> = said(&browser, mark).into_iter().filter(|n| !says_it_is_out(n)).collect(); + rest.sort(); + assert_eq!(rest, desktop_said, "{command} {file}"); + } +} + +/// A download that needs a converted copy of a layer whole (a Shapefile in another system, a +/// mobile package's simplified layers) is refused before the copy is made when the layer's +/// features are more than the download has room for, saying what to do. +#[test] +fn a_browser_download_needing_a_converted_copy_past_its_room_is_refused() { + let files = Files::new(); + let mut s = held_in_utm(&files, true, 20_000); + s.download_cap = Some(1 << 20); + for (command, params, file) in [ + ("share.exportLayer", json!({"layer": "Held", "crs": "EPSG:32632"}), "h.zip"), + ("share.exportLayer", json!({"layer": "Held", "crs": "EPSG:4326"}), "h.parquet"), + ("map.package", json!({"mobile": true}), "m.rgismpk"), + ] { + let e = s.run(command, &to(¶ms, file)).unwrap_err(); + assert!(e.contains("Held") && e.contains("copy of") && e.contains("more than the 1 MiB"), "{command} {file}: {e}"); + assert!(e.contains("Make Layer From Selected Features") && e.contains("desktop app"), "{command} {file}: {e}"); + assert!(s.take_gp_files().is_empty(), "{command} {file}"); + } +} diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 3148f8dda2..a8fddf2c0f 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -1,5 +1,6 @@ //! Export a styled raster as Web Mercator PNG tiles in a PMTiles archive. +use rustgis_data::capped::Limit; use rustgis_geom::{Coord, MERCATOR_R, extent_to_merc}; use rustgis_map::{camera::Camera, projection::Flat, raster::RasterLayer}; use serde_json::json; @@ -25,6 +26,12 @@ fn tile_range(start: f64, end: f64, n: u32) -> (u32, u32) { /// Raster pixels are rendered with the same style and resampling as the map. pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> Result, String> { + export_within(layer, min_zoom, max_zoom, opacity, &Limit::none()) +} + +/// [`export`] with the archive held to `limit`: no tile is drawn after the one that passes it +/// ([`Limit::passed`] then says so). +pub fn export_within(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32, limit: &Limit) -> Result, String> { if min_zoom > max_zoom || max_zoom > 16 { return Err("zoom range must satisfy 0 <= minZoom <= maxZoom <= 16".into()); } @@ -75,93 +82,89 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> let light = raster::Lights { shadow: shadow.as_deref().map(Vec::as_slice), sky: sky.as_deref().map(Vec::as_slice), water: None }; // A raster read in place waits for its tiles natively, two minutes at most in all. let deadline = web_time::Instant::now() + rustgis_data::raster::IN_PLACE_WAIT; - let mut tiles = Vec::new(); + // In the order the archive holds them, so each goes straight into it. + let mut places: Vec<(u64, u8, u32, u32)> = ranges + .into_iter() + .flat_map(|(z, x0, x1, y0, y1)| (y0..=y1).flat_map(move |y| (x0..=x1).map(move |x| (pmtiles::tile_id(z, x, y), z, x, y)))) + .collect(); + places.sort_unstable(); + let mut archive = pmtiles::Builder::new(limit); let mut bytes = 0usize; - for (z, x0, x1, y0, y1) in ranges { + for (_, z, x, y) in places { let size = 2.0 * half / f64::from(1u32 << z); - for y in y0..=y1 { - for x in x0..=x1 { - rustgis_data::progress::check().map_err(|e| e.to_string())?; - if crate::cancel::requested() { - return Err(rustgis_data::DataError::Cancelled.to_string()); - } - let center = Coord::new(-half + (f64::from(x) + 0.5) * size, half - (f64::from(y) + 0.5) * size); - let view = - View { width: 256.0, height: 256.0, pixels_per_point: 1.0, camera: Camera::new(center, size / 256.0), sky: false }; - let place = raster::Place::Flat(&Flat::Mercator, "EPSG:3857"); - let stats = stats.as_deref().map(Vec::as_slice); - let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; - match layer.path.as_deref().filter(|_| layer.reads_in_place()) { - // Read in place: at the tile's level, once its parts have arrived (natively; - // the browser draws what has). - Some(address) => { - let mut idle = 0; - loop { - rustgis_data::progress::check().map_err(|e| e.to_string())?; - if crate::cancel::requested() { - return Err(rustgis_data::DataError::Cancelled.to_string()); - } - let drawn_at = crate::rustgis_tiles::cache::generation(); - match raster::draw_in_place(&mut image, address, r, &layer.style, stats, &view, opacity, true, place, light) { - Ok(false) => break, - Ok(true) => {} - // Drawn from less than the tile needs: not written in its place. - Err(e) => return Err(format!("{}: {e}, so the archive isn't written", r.name)), - } - // An archive of the overview where the image is wanted isn't written. - let left = deadline.saturating_duration_since(web_time::Instant::now()); - if cfg!(target_arch = "wasm32") { - return Err(format!( - "{}: its tiles are still being read (this export asked for the rest): export again once they are in", - r.name - )); - } - if left.is_zero() || idle >= IDLE_WAITS { - return Err(format!("{}: its tiles didn't all arrive, so the archive isn't written", r.name)); - } - crate::rustgis_tiles::cache::wait_for_news_unless( - drawn_at, - left.min(web_time::Duration::from_secs(30)), - || crate::cancel::requested() || rustgis_data::progress::check().is_err(), - ); - if crate::rustgis_tiles::cache::generation() == drawn_at { - idle += 1; - } else { - idle = 0; - } - image.fill(tiny_skia::Color::TRANSPARENT); - } + rustgis_data::progress::check().map_err(|e| e.to_string())?; + if crate::cancel::requested() { + return Err(rustgis_data::DataError::Cancelled.to_string()); + } + let center = Coord::new(-half + (f64::from(x) + 0.5) * size, half - (f64::from(y) + 0.5) * size); + let view = View { width: 256.0, height: 256.0, pixels_per_point: 1.0, camera: Camera::new(center, size / 256.0), sky: false }; + let place = raster::Place::Flat(&Flat::Mercator, "EPSG:3857"); + let stats = stats.as_deref().map(Vec::as_slice); + let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; + match layer.path.as_deref().filter(|_| layer.reads_in_place()) { + // Read in place: at the tile's level, once its parts have arrived (natively; + // the browser draws what has). + Some(address) => { + let mut idle = 0; + loop { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + if crate::cancel::requested() { + return Err(rustgis_data::DataError::Cancelled.to_string()); } - None => raster::draw(&mut image, r, &layer.style, stats, &view, opacity, true, place, light), - } - if image.data().as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0) { - continue; - } - let png = image.encode_png().map_err(|e| format!("couldn't encode a raster tile: {e}"))?; - bytes = bytes.checked_add(png.len()).ok_or("raster tile data is too large")?; - if bytes > MAX_BYTES { - return Err("raster export exceeds 64 MiB of tile data; reduce the zoom range or raster extent".into()); + let drawn_at = crate::rustgis_tiles::cache::generation(); + match raster::draw_in_place(&mut image, address, r, &layer.style, stats, &view, opacity, true, place, light) { + Ok(false) => break, + Ok(true) => {} + // Drawn from less than the tile needs: not written in its place. + Err(e) => return Err(format!("{}: {e}, so the archive isn't written", r.name)), + } + // An archive of the overview where the image is wanted isn't written. + let left = deadline.saturating_duration_since(web_time::Instant::now()); + if cfg!(target_arch = "wasm32") { + return Err(format!( + "{}: its tiles are still being read (this export asked for the rest): export again once they are in", + r.name + )); + } + if left.is_zero() || idle >= IDLE_WAITS { + return Err(format!("{}: its tiles didn't all arrive, so the archive isn't written", r.name)); + } + crate::rustgis_tiles::cache::wait_for_news_unless(drawn_at, left.min(web_time::Duration::from_secs(30)), || { + crate::cancel::requested() || rustgis_data::progress::check().is_err() + }); + if crate::rustgis_tiles::cache::generation() == drawn_at { + idle += 1; + } else { + idle = 0; + } + image.fill(tiny_skia::Color::TRANSPARENT); } - tiles.push((z, x, y, png)); } + None => raster::draw(&mut image, r, &layer.style, stats, &view, opacity, true, place, light), + } + if image.data().as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0) { + continue; + } + let png = image.encode_png().map_err(|e| format!("couldn't encode a raster tile: {e}"))?; + bytes = bytes.checked_add(png.len()).ok_or("raster tile data is too large")?; + if bytes > MAX_BYTES { + return Err("raster export exceeds 64 MiB of tile data; reduce the zoom range or raster extent".into()); } + archive.push(z, x, y, &png)?; } rustgis_data::progress::check().map_err(|e| e.to_string())?; if crate::cancel::requested() { return Err(rustgis_data::DataError::Cancelled.to_string()); } - if tiles.is_empty() { + if archive.is_empty() { return Err("the raster has no visible pixels in the requested tiles".into()); } - pmtiles::write( - tiles, - &NewArchive { - tile_type: TileType::Png, - gzipped_tiles: false, - bounds: [e.min_x, e.min_y, e.max_x, e.max_y], - metadata: json!({"name": r.name}), - }, - ) + archive.finish(&NewArchive { + tile_type: TileType::Png, + gzipped_tiles: false, + bounds: [e.min_x, e.min_y, e.max_x, e.max_y], + metadata: json!({"name": r.name}), + }) } #[expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index 8ddb2a3832..79e6f6bef3 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -13,8 +13,11 @@ //! archive information or directories, and reload epochs reject pre-reload completions. use std::collections::HashMap; +use std::hash::{BuildHasher, RandomState}; +use std::io::Write as _; use std::sync::{Arc, Mutex, OnceLock}; +use rustgis_data::capped::{Buffer, Limit}; use serde_json::Value; use web_time::{Duration, Instant}; @@ -295,113 +298,227 @@ pub struct NewArchive { /// stored once, its directories uncompressed, in leaf directories when the root would pass the /// first 16 KB. Tiles given twice keep the last. pub fn write(tiles: Vec<(u8, u32, u32, Vec)>, a: &NewArchive) -> Result, String> { - if !a.metadata.is_object() { - return Err("PMTiles metadata must be a JSON object".into()); - } - let meta = serde_json::to_vec(&a.metadata).map_err(|e| e.to_string())?; - if meta.len() > MAX_BYTES { - return Err("PMTiles metadata exceeds the 16 MiB limit".into()); + // Metadata that can't be written is said before anything about the tiles. + let limit = Limit::none(); + let meta = metadata_bytes(a, &limit, 0)?; + if let Some((z, x, y, _)) = tiles.iter().find(|(z, x, y, _)| !is_address(*z, *x, *y)) { + return Err(not_a_tile(*z, *x, *y)); } - // A tile outside its zoom would take the id of another zoom's; readers stop at zoom 30. - if let Some((z, x, y, _)) = tiles.iter().find(|(z, x, y, _)| *z > 30 || u64::from(*x) >= 1u64 << z || u64::from(*y) >= 1u64 << z) { - return Err(format!("{z}/{x}/{y} isn't a tile (zoom 0–30, x and y below 2^zoom)")); - } - let mut tiles: Vec<(u64, u8, Vec)> = tiles.into_iter().map(|(z, x, y, b)| (tile_id(z, x, y), z, b)).collect(); + let mut tiles: Vec<(u64, (u8, u32, u32, Vec))> = tiles.into_iter().map(|t| (tile_id(t.0, t.1, t.2), t)).collect(); tiles.sort_by_key(|t| t.0); // The last of each id (a stable sort keeps them in the order given). - let mut unique: Vec<(u64, u8, Vec)> = Vec::with_capacity(tiles.len()); + let mut unique: Vec<(u64, (u8, u32, u32, Vec))> = Vec::with_capacity(tiles.len()); for t in tiles { match unique.last_mut() { Some(last) if last.0 == t.0 => *last = t, _ => unique.push(t), } } - let (Some(first), Some(last)) = (unique.first(), unique.last()) else { return Err("an archive needs at least one tile".into()) }; - let (min_zoom, max_zoom) = (first.1, last.1); - let mut data: Vec = Vec::new(); - let mut stored: HashMap<&[u8], (u64, u64)> = HashMap::new(); - let mut entries: Vec = Vec::new(); - for (id, _, b) in &unique { - let (offset, length) = *stored.entry(b.as_slice()).or_insert_with(|| { - let at = data.len() as u64; - data.extend_from_slice(b); - (at, b.len() as u64) + let mut archive = Builder::new(&limit); + // Each tile's bytes are given back as soon as the archive holds them. + for (_, (z, x, y, bytes)) in unique { + archive.push(z, x, y, &bytes)?; + } + archive.finish_with(meta, a) +} + +/// Whether there is a tile at this address: one outside its zoom would take the id of another +/// zoom's, and readers stop at zoom 30. +fn is_address(z: u8, x: u32, y: u32) -> bool { + z <= 30 && u64::from(x) < 1u64 << z && u64::from(y) < 1u64 << z +} + +fn not_a_tile(z: u8, x: u32, y: u32) -> String { + format!("{z}/{x}/{y} isn't a tile (zoom 0–30, x and y below 2^zoom)") +} + +/// How many bytes were written to it. +struct Length(usize); + +impl std::io::Write for Length { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(bytes.len()); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// `a`'s metadata as the archive holds it: measured before it is made, and refused when it and the +/// `data` bytes of tiles come to more than `limit`, or it alone to more than a reader takes. +fn metadata_bytes(a: &NewArchive, limit: &Limit, data: usize) -> Result, String> { + if !a.metadata.is_object() { + return Err("PMTiles metadata must be a JSON object".into()); + } + let mut length = Length(0); + serde_json::to_writer(&mut length, &a.metadata).map_err(|e| e.to_string())?; + if length.0 > MAX_BYTES { + return Err("PMTiles metadata exceeds the 16 MiB limit".into()); + } + limit.fits(data.saturating_add(length.0)).map_err(|e| e.to_string())?; + serde_json::to_vec(&a.metadata).map_err(|e| e.to_string()) +} + +/// An archive made a tile at a time, in the order of their ids ([`tile_id`]), as [`write`] makes +/// one: each tile goes straight into the file, so none is held beside it, and the file is held to +/// a limit as it grows. +pub struct Builder<'a> { + /// The tile data so far; the header and directories go before it at the end. + data: Buffer<'a>, + limit: &'a Limit, + entries: Vec, + /// Where each tile stored lies in the data (offset, length), by the hash of its bytes. + stored: HashMap>, + hasher: RandomState, + contents: u64, + /// The first tile's zoom and the last's: the least and the most, as ids run by zoom. + zooms: Option<(u8, u8)>, + last: Option, +} + +impl<'a> Builder<'a> { + /// An archive with no tiles yet, held to `limit`. + pub fn new(limit: &'a Limit) -> Self { + Builder { + data: limit.buffer(), + limit, + entries: Vec::new(), + stored: HashMap::new(), + hasher: RandomState::new(), + contents: 0, + zooms: None, + last: None, + } + } + + /// Whether no tile has been added. + pub fn is_empty(&self) -> bool { + self.last.is_none() + } + + /// Adds a tile, which comes after those added in the order of their ids. Refused once the + /// data passes the limit ([`Limit::passed`] then says so). + pub fn push(&mut self, z: u8, x: u32, y: u32, bytes: &[u8]) -> Result<(), String> { + if !is_address(z, x, y) { + return Err(not_a_tile(z, x, y)); + } + let id = tile_id(z, x, y); + if self.last.is_some_and(|last| id <= last) { + return Err(format!("{z}/{x}/{y}: an archive's tiles are added once each, in the order of their ids")); + } + let same = self.stored.entry(self.hasher.hash_one(bytes)).or_default(); + let found = same.iter().copied().find(|&(at, length)| { + let range = usize::try_from(at).ok().zip(usize::try_from(at + length).ok()); + range.and_then(|(from, to)| self.data.written().get(from..to)) == Some(bytes) }); + let (offset, length) = match found { + Some(place) => place, + None => { + let place = (self.data.written().len() as u64, bytes.len() as u64); + self.data.write_all(bytes).map_err(|e| e.to_string())?; + same.push(place); + self.contents += 1; + place + } + }; + self.last = Some(id); + self.zooms = Some((self.zooms.map_or(z, |zooms| zooms.0), z)); // The same tile right after the previous one: a longer run. - if let Some(e) = entries.last_mut() + if let Some(e) = self.entries.last_mut() && e.offset == offset && e.length == length - && e.tile_id + e.run_length == *id + && e.tile_id + e.run_length == id { e.run_length += 1; - continue; + return Ok(()); } - entries.push(Entry { tile_id: *id, offset, length, run_length: 1 }); - } - let contents = stored.len() as u64; - let addressed: u64 = entries.iter().map(|e| e.run_length).sum(); - // The root directory, or leaves of more entries each until the root fits. - let mut root = write_dir(&entries); - let mut leaves = Vec::new(); - let mut per_leaf = 4096usize; - while 127 + root.len() > HEAD as usize { - leaves.clear(); - let mut index = Vec::new(); - for chunk in entries.chunks(per_leaf) { - let Some(first) = chunk.first() else { continue }; - let leaf = write_dir(chunk); - index.push(Entry { tile_id: first.tile_id, offset: leaves.len() as u64, length: leaf.len() as u64, run_length: 0 }); - leaves.extend(leaf); - } - root = write_dir(&index); - per_leaf = per_leaf.checked_mul(2).ok_or("too many tiles")?; - } - let root_at = 127u64; - let meta_at = root_at + root.len() as u64; - let leaf_at = meta_at + meta.len() as u64; - let data_at = leaf_at + leaves.len() as u64; - let mut h = b"PMTiles".to_vec(); - h.push(3); - for v in [ - root_at, - root.len() as u64, - meta_at, - meta.len() as u64, - leaf_at, - leaves.len() as u64, - data_at, - data.len() as u64, - addressed, - entries.len() as u64, - contents, - ] { - h.extend_from_slice(&v.to_le_bytes()); - } - let tile_type = match a.tile_type { - TileType::Unknown => 0, - TileType::Mvt => 1, - TileType::Png => 2, - TileType::Jpeg => 3, - TileType::Webp => 4, - TileType::Avif => 5, - }; - // Clustered; directories uncompressed; tiles as given. - h.extend_from_slice(&[1, 1, if a.gzipped_tiles { 2 } else { 1 }, tile_type, min_zoom, max_zoom]); - let e7 = |v: f64, max: f64| ((v.clamp(-max, max) * 1e7).round() as i32).to_le_bytes(); - let [w, so, e, n] = a.bounds; - for (v, max) in [(w, 180.0), (so, 90.0), (e, 180.0), (n, 90.0)] { - h.extend_from_slice(&e7(v, max)); - } - h.push(min_zoom); - h.extend_from_slice(&e7((w + e) / 2.0, 180.0)); - h.extend_from_slice(&e7((so + n) / 2.0, 90.0)); - let mut out = h; - out.reserve_exact(root.len() + meta.len() + leaves.len() + data.len()); - for part in [root, meta, leaves] { - out.extend_from_slice(&part); - } - out.extend_from_slice(&data); - Ok(out) + // Each entry takes four bytes of a directory at least, so many of one tile's bytes can't pass + // the limit in what is held before the directories are made. + let least = (self.entries.len() + 1).saturating_mul(4).saturating_add(127); + self.limit.fits(self.data.written().len().saturating_add(least)).map_err(|e| e.to_string())?; + self.entries.push(Entry { tile_id: id, offset, length, run_length: 1 }); + Ok(()) + } + + /// The archive of the tiles added, said of as `a` says. Refused when its header and + /// directories, with the data, pass the limit. + pub fn finish(self, a: &NewArchive) -> Result, String> { + let meta = metadata_bytes(a, self.limit, self.data.written().len())?; + self.finish_with(meta, a) + } + + /// [`Builder::finish`] with `a`'s metadata as [`metadata_bytes`] gave it. + fn finish_with(mut self, meta: Vec, a: &NewArchive) -> Result, String> { + let Some((min_zoom, max_zoom)) = self.zooms else { return Err("an archive needs at least one tile".into()) }; + let entries = std::mem::take(&mut self.entries); + let addressed: u64 = entries.iter().map(|e| e.run_length).sum(); + // The root directory, or leaves of more entries each until the root fits. + let mut root = write_dir(&entries); + let mut leaves = Vec::new(); + let mut per_leaf = 4096usize; + while 127 + root.len() > HEAD as usize { + leaves.clear(); + let mut index = Vec::new(); + for chunk in entries.chunks(per_leaf) { + let Some(first) = chunk.first() else { continue }; + let leaf = write_dir(chunk); + index.push(Entry { tile_id: first.tile_id, offset: leaves.len() as u64, length: leaf.len() as u64, run_length: 0 }); + leaves.extend(leaf); + } + root = write_dir(&index); + per_leaf = per_leaf.checked_mul(2).ok_or("too many tiles")?; + } + let root_at = 127u64; + let meta_at = root_at + root.len() as u64; + let leaf_at = meta_at + meta.len() as u64; + let data_at = leaf_at + leaves.len() as u64; + let mut h = b"PMTiles".to_vec(); + h.push(3); + for v in [ + root_at, + root.len() as u64, + meta_at, + meta.len() as u64, + leaf_at, + leaves.len() as u64, + data_at, + self.data.written().len() as u64, + addressed, + entries.len() as u64, + self.contents, + ] { + h.extend_from_slice(&v.to_le_bytes()); + } + let tile_type = match a.tile_type { + TileType::Unknown => 0, + TileType::Mvt => 1, + TileType::Png => 2, + TileType::Jpeg => 3, + TileType::Webp => 4, + TileType::Avif => 5, + }; + // Clustered; directories uncompressed; tiles as given. + h.extend_from_slice(&[1, 1, if a.gzipped_tiles { 2 } else { 1 }, tile_type, min_zoom, max_zoom]); + let e7 = |v: f64, max: f64| ((v.clamp(-max, max) * 1e7).round() as i32).to_le_bytes(); + let [w, so, e, n] = a.bounds; + for (v, max) in [(w, 180.0), (so, 90.0), (e, 180.0), (n, 90.0)] { + h.extend_from_slice(&e7(v, max)); + } + h.push(min_zoom); + h.extend_from_slice(&e7((w + e) / 2.0, 180.0)); + h.extend_from_slice(&e7((so + n) / 2.0, 90.0)); + // Refused before the parts are put together, not once they are. + let parts = [self.data.written().len(), root.len(), meta.len(), leaves.len()]; + self.limit.fits(parts.into_iter().fold(h.len(), usize::saturating_add)).map_err(|e| e.to_string())?; + let mut head = h; + for part in [root, meta, leaves] { + head.extend_from_slice(&part); + } + self.data.prepend(&head).map_err(|e| e.to_string())?; + Ok(self.data.into_inner()) + } } /// A directory: delta-coded tile ids, then run lengths, lengths and offsets (0 for "right after diff --git a/crates/tiles/src/vector_export.rs b/crates/tiles/src/vector_export.rs index 7a77f2fe45..b2327cf43c 100644 --- a/crates/tiles/src/vector_export.rs +++ b/crates/tiles/src/vector_export.rs @@ -16,6 +16,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::mem::size_of; use geo::{BooleanOps, Coord as GC, LineString, Polygon, Rect, Validation}; +use rustgis_data::capped::Limit; use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value}; use crate::{mvt, pmtiles}; @@ -57,6 +58,19 @@ struct Notices { /// Geometry must already be normalized to WGS 84 degrees, as required by [`Dataset`]. /// Its `crs` is source provenance and must not be used to transform those degrees again. pub fn export(dataset: &Dataset, rows: &[usize], min_zoom: u8, max_zoom: u8, source_layer: &str) -> Result { + export_within(dataset, rows, min_zoom, max_zoom, source_layer, &Limit::none()) +} + +/// [`export`] with the archive held to `limit`: no tile is encoded after the one that passes it +/// ([`Limit::passed`] then says so). +pub fn export_within( + dataset: &Dataset, + rows: &[usize], + min_zoom: u8, + max_zoom: u8, + source_layer: &str, + limit: &Limit, +) -> Result { if min_zoom > max_zoom || max_zoom > 16 { return Err("zoom range must satisfy 0 <= minZoom <= maxZoom <= 16".into()); } @@ -183,25 +197,38 @@ pub fn export(dataset: &Dataset, rows: &[usize], min_zoom: u8, max_zoom: u8, sou "bounds": bounds, "vector_layers": [{"id": source_layer, "fields": fields, "minzoom": min_zoom, "maxzoom": max_zoom}] }); - let mut encoded = Vec::with_capacity(tiles.len()); - let mut encoded_size = 0usize; - for ((z, x, y), features) in tiles { + // Encoded in the order the archive holds them, so each goes straight into it and none is + // held beside it. + let mut order: Vec<(u64, TileKey)> = tiles.keys().map(|&(z, x, y)| (pmtiles::tile_id(z, x, y), (z, x, y))).collect(); + order.sort_unstable(); + let mut archive = pmtiles::Builder::new(limit); + let mut sizes = Vec::with_capacity(order.len()); + let (mut encoded_size, mut reserved) = (0usize, 0usize); + for (_, key @ (z, x, y)) in order { + let Some(features) = tiles.remove(&key) else { continue }; let tile = mvt::Tile { layers: vec![mvt::Layer { name: source_layer.into(), extent: EXTENT, features }] }; let estimate = tile_size(&tile)?; // mvt::encode holds feature messages, values, dedup keys, layer and final bytes. budget.ensure(product(estimate, 16)?)?; let bytes = mvt::encode(&tile); + // What the archive's end asks for, of the tiles so far: more with each tile, so a job it + // would refuse is refused as it gets there, before the rest is built. encoded_size = encoded_size.checked_add(bytes.len()).ok_or(MEMORY_ERROR)?; - budget.add(product(bytes.len().checked_add(128).ok_or(MEMORY_ERROR)?, 2)?)?; - encoded.push((z, x, y, bytes)); - } - // pmtiles::write retains input payloads while building deduplicated data and output. - // Eight payload lengths cover growth and final copies; directories/hash/sort overhead - // is reserved separately (far above the writer's per-entry representation). - budget.ensure(product(encoded_size, 8)?.checked_add(product(encoded.len(), 2048)?).ok_or(MEMORY_ERROR)?)?; - let tile_count = encoded.len(); - let bytes = - pmtiles::write(encoded, &pmtiles::NewArchive { tile_type: pmtiles::TileType::Mvt, gzipped_tiles: false, bounds, metadata })?; + reserved = reserved.checked_add(tile_memory(bytes.len())?).ok_or(MEMORY_ERROR)?; + budget.ensure(reserved.checked_add(archive_memory(encoded_size, sizes.len() + 1)?).ok_or(MEMORY_ERROR)?)?; + sizes.push((key, estimate, bytes.len())); + archive.push(z, x, y, &bytes)?; + } + // Which jobs the budget refuses doesn't hang on the order the tiles were encoded in: each is + // counted in the order of zoom, column and row, with those before it. + sizes.sort_unstable_by_key(|tile| tile.0); + for &(_, estimate, length) in &sizes { + budget.ensure(product(estimate, 16)?)?; + budget.add(tile_memory(length)?)?; + } + budget.ensure(archive_memory(encoded_size, sizes.len())?)?; + let tile_count = sizes.len(); + let bytes = archive.finish(&pmtiles::NewArchive { tile_type: pmtiles::TileType::Mvt, gzipped_tiles: false, bounds, metadata })?; let mut messages = vec![format!("Exported {tile_count} tiles at zooms {min_zoom}–{max_zoom}; clipping buffer is 8/4096 tile units.")]; if notices.poles > 0 { messages.push(format!("Clamped {} coordinates to Web Mercator's ±{MAX_LAT}° latitude limit.", notices.poles)); @@ -251,6 +278,15 @@ impl Budget { fn product(a: usize, b: usize) -> Result { a.checked_mul(b).ok_or_else(|| MEMORY_ERROR.into()) } +/// What a tile of `length` bytes is counted as once it is encoded. +fn tile_memory(length: usize) -> Result { + product(length.checked_add(128).ok_or(MEMORY_ERROR)?, 2) +} +/// What the archive of `tiles` tiles, `bytes` in all, is counted as: its data, directories and +/// hashes, and their growth. +fn archive_memory(bytes: usize, tiles: usize) -> Result { + product(bytes, 8)?.checked_add(product(tiles, 2048)?).ok_or_else(|| MEMORY_ERROR.into()) +} fn geometry_memory(vertices: usize, rings: usize, polygon: bool) -> Result { let slots = vertices.checked_add(rings).and_then(|n| n.checked_add(8)).ok_or(MEMORY_ERROR)?; // Per vertex/ring, 256 bytes cover projected f64 coordinates, up to two clipped @@ -700,6 +736,22 @@ mod tests { Ok((tiles, notices)) } + /// A job past the memory budget is refused as its archive passes it, not once the whole + /// archive has been built: here after a few of its 48 MiB, well before the limit. + #[test] + fn a_job_past_the_memory_budget_is_refused_before_its_archive_is_built() { + let mut ds = Dataset::new("Notes", rustgis_data::GeometryType::Point, vec![rustgis_data::Field::new("note", FieldType::Text)]); + for i in 0..48u8 { + let at = Coord::new(-170.0 + f64::from(i % 30) * 11.25, if i < 30 { 20.0 } else { 50.0 }); + ds.push(Some(Geometry::Point(at)), vec![Value::Text(char::from(b'A' + i).to_string().repeat(1 << 20))]); + } + let rows: Vec = (0..48).collect(); + let limit = Limit::new(40 << 20); + let refused = export_within(&ds, &rows, 5, 5, "notes", &limit).map(|e| e.bytes.len()); + assert_eq!(refused, Err(MEMORY_ERROR.to_string())); + assert!(!limit.passed()); + } + #[test] fn archive_preserves_ids_types_nulls_and_metadata() -> Result<(), String> { let mut ds = dataset(Geometry::Point(Coord::new(20.0, 30.0)));