Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,19 +244,22 @@ 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,
_rows: &[usize],
_min_zoom: u8,
_max_zoom: u8,
_source_layer: &str,
_file_name: &str,
) -> Result<(Vec<u8>, Vec<String>), 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<Vec<u8>, 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<Vec<u8>, String> {
Err("raster-to-PMTiles export is unavailable in this input provider".into())
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1521,7 +1521,7 @@ fn vector_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
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 })
}

Expand All @@ -1531,7 +1531,7 @@ fn raster_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
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![] })
}

Expand Down
88 changes: 84 additions & 4 deletions crates/data/src/capped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(());
}
Expand All @@ -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 }
}

Expand Down Expand Up @@ -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<u8>,
/// Where the next write goes.
at: u64,
Expand All @@ -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<u8> {
pub fn into_inner(mut self) -> Vec<u8> {
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.
Expand Down Expand Up @@ -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(&copy, 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(&copy), "{format}");
let notes = crate::io::export_losses_notes_in_lonlat(&ds, format, Some(0), "out").unwrap();
assert_eq!(notes, crate::io::export_losses_notes(&copy, 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(&copy, &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() {
Expand Down
49 changes: 38 additions & 11 deletions crates/data/src/interop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<usize>, 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<Item = Row<'a>>,
name_field: Option<usize>,
out: &mut impl Write,
) -> crate::Result<()> {
check_xml(&ds.name, "KML", || "layer name".to_string())?;
out.write_all(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"")?;
out.write_all(
Expand All @@ -162,15 +173,15 @@ pub(crate) fn write_kml(ds: &Dataset, name_field: Option<usize>, 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"))?;
Expand Down Expand Up @@ -249,18 +260,29 @@ pub fn to_gpx(ds: &Dataset, name_field: Option<usize>) -> crate::Result<String>
/// [`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<usize>, 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<Item = Row<'a>>>(
ds: &Dataset,
mut rows: impl FnMut() -> I,
name_field: Option<usize>,
out: &mut impl Write,
) -> crate::Result<()> {
out.write_all(
b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<gpx version=\"1.1\" creator=\"RustGIS\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n",
)?;
for tracks in [false, true] {
for (r, f) in ds.features.iter().enumerate() {
for f in rows() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write_gpx_of calls rows() once per pass, so a GPX download now converts every geometry twice (waypoints, then tracks). Before the change the download wrote from a copy that was converted once. The notes pass adds more: written_with_geometry and text_losses_written each convert the layer again. Counting the converted walks, a KML download converts the layer about 3 times and a GPX one about 4 times, where the copy took 1. The bytes don't change, so this is CPU, not memory, but on a national layer it is several times the reprojection work.

Options: accept the cost and state it in the PR (the pull request's memory figures don't cover it), or have the notes pass take its counts from the walk that writes the file rather than converting again.

Confidence: medium on the size of the cost; it depends on how heavy the reprojection is against the I/O.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right about the cost, which the description now states. It is CPU on a download, whose file is at most 256 MiB; the desktop keeps the copy converted on several threads for exports. Taking the notices from the walk that writes would tie the counting to each writer, which is more than this change.

// 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 {
Expand All @@ -270,7 +292,7 @@ pub(crate) fn write_gpx(ds: &Dataset, name_field: Option<usize>, 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)?,
Expand Down Expand Up @@ -707,6 +729,11 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result<String> {
/// [`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<Item = Row<'a>>, 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",")?;
Expand All @@ -717,17 +744,17 @@ 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"" };
out.write_all(quote)?;
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)?;
}
Expand Down
Loading
Loading