diff --git a/crates/analysis/src/texture.rs b/crates/analysis/src/texture.rs index 8a2db044d0..3a8f539b1c 100644 --- a/crates/analysis/src/texture.rs +++ b/crates/analysis/src/texture.rs @@ -26,6 +26,28 @@ pub const PAD: usize = 64; /// items that a small model is shaded in a few looks at Cancel. const BLOCK_CELLS: usize = 1 << 16; +/// The most padded cells a model may take: the column pass holds two padded grids of complex +/// 32-bit numbers at once, 8 bytes a padded cell each and 16 for both, the whole of the 16 bytes a +/// cell that [`max_pixels`] plans: half as many leaves room for the model, the output and the +/// percentiles' copy beside them. +fn max_padded_cells() -> usize { + padded_cells_within(max_pixels()) +} + +/// The padded cells a plan of `pixels` cells (16 bytes each) holds: half of them. +fn padded_cells_within(pixels: usize) -> usize { + pixels / 2 +} + +/// The padded sides of a `w` × `h` model, each mirrored [`PAD`] cells out and grown to small +/// factors: `None` when a side or their product is past `limit`. A side past the limit on its own +/// is refused before it is padded, so the sum can't overflow. +fn padded_size(w: usize, h: usize, limit: usize) -> Option<(usize, usize)> { + let side = |n: usize| (n <= limit).then(|| smooth(n + 2 * PAD)); + let (pw, ph) = (side(w)?, side(h)?); + (pw <= limit && ph <= limit && pw.saturating_mul(ph) <= limit).then_some((pw, ph)) +} + /// The fractional Laplacian of band `b` of `r` with exponent `alpha`: positive on ridges, negative /// in valleys, in the band's unit per metre^α, [`NODATA`] where the band has none. Cells are /// measured in metres ([`Raster::cell_size_m`]: a geographic model at its middle's latitude, a @@ -43,7 +65,8 @@ pub fn texture(r: &Raster, b: usize, alpha: f64) -> Result, String> { /// Three passes, each by blocks of rows on the threads: the padded model is read and its rows transformed; /// each column is transformed, filtered and transformed back; then each row of the model is /// transformed back. Beyond the model and the output, it holds two padded grids of complex -/// 32-bit numbers (16 bytes a padded cell), the first only until the columns are taken from it. +/// 32-bit numbers (8 bytes a padded cell each, 16 for both), the first only until the columns +/// are taken from it; [`max_padded_cells`] plans for both. pub(crate) fn texture_on(threads: Option, r: &Raster, b: usize, alpha: f64) -> Result, String> { if !(alpha.is_finite() && alpha > 0.0) { return Err("alpha must be a number more than 0".into()); @@ -66,19 +89,13 @@ pub(crate) fn texture_on(threads: Option, r: &Raster, b: usize, alpha: f6 if !(cx.is_finite() && cy.is_finite() && cx > 0.0 && cy > 0.0) { return Err(format!("{}'s cells have no size", r.name)); } - let too_large = || { - format!( - "{} is too large for texture shading: with its margins, more than the {} cells this computer can hold", - r.name, - max_pixels() - ) + let limit = max_padded_cells(); + let Some((pw, ph)) = padded_size(w, h, limit) else { + return Err(format!( + "{} is too large for texture shading: with its margins, more than the {limit} cells this computer can hold; clip it to a smaller area first", + r.name + )); }; - // A side past the limit on its own is refused before it is padded, so the sum can't overflow. - let side = |n: usize| (n <= max_pixels()).then(|| smooth(n + 2 * PAD)); - let (Some(pw), Some(ph)) = (side(w), side(h)) else { return Err(too_large()) }; - if pw.saturating_mul(ph) > max_pixels() { - return Err(too_large()); - } let mut planner = FftPlanner::::new(); let (row_fwd, row_inv) = (planner.plan_fft_forward(pw), planner.plan_fft_inverse(pw)); let (col_fwd, col_inv) = (planner.plan_fft_forward(ph), planner.plan_fft_inverse(ph)); @@ -199,6 +216,18 @@ mod tests { use super::*; use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; + /// The padded size is refused one cell past the limit and kept at it, a side past it on its + /// own included; the limit plans for both complex grids, not one. + #[test] + fn the_padded_size_keeps_to_its_limit() { + let (pw, ph) = (smooth(100 + 2 * PAD), smooth(40 + 2 * PAD)); + let at = pw * ph; + assert_eq!(padded_size(100, 40, at), Some((pw, ph))); + assert_eq!(padded_size(100, 40, at - 1), None); + assert_eq!(padded_size(usize::MAX, 1, at), None, "a side past the limit isn't padded"); + assert_eq!(padded_cells_within(64 << 20), 32 << 20, "two grids of 8 bytes a cell, and room beside them, against a plan of 16"); + } + /// A `width × height` grid of 30 m × 20 m cells in UTM 23S, each `z(col, row)`, -9999 its no-data. fn dem(width: u32, height: u32, z: impl Fn(f64, f64) -> f64) -> Raster { dem_in(Crs::Epsg(32723), (30., 20.), width, height, z) diff --git a/crates/assistant/src/acp.rs b/crates/assistant/src/acp.rs index 4a137c388f..500f78a697 100644 --- a/crates/assistant/src/acp.rs +++ b/crates/assistant/src/acp.rs @@ -569,10 +569,7 @@ impl Session { if let Some(t) = u.pointer("/content/text").and_then(Value::as_str) { // A message past MAX_TEXT is cut there: the agent's output is untrusted. let room = MAX_TEXT.saturating_sub(self.text.len()); - let mut end = t.len().min(room); - while !t.is_char_boundary(end) { - end -= 1; - } + let end = t.floor_char_boundary(room); self.text.push_str(t.get(..end).unwrap_or("")); } Vec::new() diff --git a/crates/assistant/src/compact.rs b/crates/assistant/src/compact.rs index 8ac4934919..4a38da4829 100644 --- a/crates/assistant/src/compact.rs +++ b/crates/assistant/src/compact.rs @@ -190,10 +190,7 @@ fn cut_results(rs: &mut [ToolResult]) -> bool { let mut changed = false; for r in rs.iter_mut() { if r.content.len() > TRIMMED_RESULT { - let mut end = TRIMMED_RESULT - TRIMMED_SUFFIX.len(); - while !r.content.is_char_boundary(end) { - end -= 1; - } + let end = r.content.floor_char_boundary(TRIMMED_RESULT - TRIMMED_SUFFIX.len()); r.content = format!("{}{TRIMMED_SUFFIX}", r.content.get(..end).unwrap_or_default()); changed = true; } @@ -222,10 +219,7 @@ pub fn as_text_with_limit(turns: &[Turn], upto: usize, limit: usize) -> String { remaining -= text.len(); chunks.push(text); } else { - let mut start = text.len().saturating_sub(remaining); - while !text.is_char_boundary(start) { - start += 1; - } + let start = text.ceil_char_boundary(text.len().saturating_sub(remaining)); chunks.push(text.get(start..).unwrap_or_default().to_string()); omitted = true; break; diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 3b7df60eaa..dd494e3ae2 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -1118,7 +1118,7 @@ impl StreamPreview { self.text.push_str(&self.delta(&v)); // Previews stay small: the whole reply is read separately. if self.text.len() > MAX_RESPONSE { - let cut = (0..=MAX_RESPONSE).rev().find(|i| self.text.is_char_boundary(*i)).unwrap_or(0); + let cut = self.text.floor_char_boundary(MAX_RESPONSE); self.text.truncate(cut); } } diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 06da31c122..45e5772216 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -1065,11 +1065,7 @@ fn loss_forms(losses: &[Value]) -> Vec<(Value, bool)> { /// The first `max` bytes of `text`, cut at a character boundary. fn clip_bytes(text: &str, max: usize) -> String { - let mut end = max.min(text.len()); - while !text.is_char_boundary(end) { - end -= 1; - } - text[..end].to_string() + text.get(..text.floor_char_boundary(max)).unwrap_or_default().to_string() } /// A failed command's error, cleaned of login values, with what the command said before failing @@ -1536,6 +1532,14 @@ mod tests { use super::*; use rustgis_engine::render::rustgis_tiles::logins; + /// A clip keeps whole characters: one straddling the limit is dropped, not cut. + #[test] + fn clip_bytes_drops_a_character_straddling_the_limit() { + assert_eq!(clip_bytes("aé", 2), "a"); + assert_eq!(clip_bytes("aé", 3), "aé"); + assert_eq!(clip_bytes("abc", 10), "abc"); + } + #[test] fn results_carry_plain_addresses_not_login_wrappers() { let mut s = Session::new(rustgis_engine::Project::default()); diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 38d5841277..bad0117dbf 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -304,6 +304,18 @@ pub(crate) fn crs_of_code(code: u32) -> Option { Crs::from_epsg(code).or_else(|| crate::raster::crs::esri_crs(code)) } +/// An ArcGIS `spatialReference`'s system and code: the first of its `latestWkid` and `wkid` that +/// [`crs_of_code`] knows, so a newer code RustGIS can't read falls back to the older one. +pub(crate) fn arcgis_code(reference: &serde_json::Value) -> Option<(Crs, u32)> { + arcgis_codes(reference).find_map(|c| Some((crs_of_code(c)?, c))) +} + +/// An ArcGIS `spatialReference`'s codes, `latestWkid` then `wkid`, each a nonzero `u32`. +pub(crate) fn arcgis_codes(reference: &serde_json::Value) -> impl Iterator { + let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok()).filter(|c| *c != 0); + [code("latestWkid"), code("wkid")].into_iter().flatten() +} + /// One table as a dataset: `None` for a table with no rows and no fields worth showing. `wkid` is /// its coordinate system's code, when the item definitions give one. /// Reads a table and its row index, keeping typed attributes and reporting invalid or rounded dates. diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 7c37513a9f..83d8460daf 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -42,6 +42,8 @@ pub mod ogc; pub mod osm; pub mod photo; pub mod png; +#[cfg(not(target_arch = "wasm32"))] +pub mod process; pub mod progress; pub mod provenance; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6a022dce0e..660bf6652c 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2694,7 +2694,11 @@ fn merc_to_lonlat(x: f64, y: f64) -> (f64, f64) { fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> { let f = |k: &str| e.get(k).and_then(|v| v.as_f64()); let (x0, y0, x1, y1) = (f("xmin")?, f("ymin")?, f("xmax")?, f("ymax")?); - let wkid = e.pointer("/spatialReference/latestWkid").or_else(|| e.pointer("/spatialReference/wkid")).and_then(|w| w.as_i64())?; + // The first of latestWkid and wkid that RustGIS reads, as a layer's own system is chosen: an + // extent it can't convert in that system has no box, not one read in the other. + let mercator = |c: u32| matches!(c, 3857 | 102100 | 102113 | 900913); + let wkid = crate::filegdb::arcgis_codes(e.get("spatialReference")?) + .find(|c| *c == 4326 || mercator(*c) || crate::filegdb::crs_of_code(*c).is_some())?; match wkid { 4326 => lonlat_box(x0, y0, x1, y1), 3857 | 102100 | 102113 | 900913 => { @@ -2704,7 +2708,7 @@ fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> { } // Another system RustGIS reads: its box converted, its edges followed. _ => { - let crs = crate::filegdb::crs_of_code(u32::try_from(wkid).ok()?)?; + let crs = crate::filegdb::crs_of_code(wkid)?; let b = crs.to(crate::raster::Crs::LonLat).ok()?.extent(&rustgis_geom::Extent { min_x: x0, min_y: y0, max_x: x1, max_y: y1 }); if b.is_empty() { return None; @@ -2717,7 +2721,11 @@ fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> { /// Whether a cached map service's tiles are Web Mercator's own pyramid (zoom 0 at 156543 m/px). fn arcgis_mercator_cache(v: &serde_json::Value) -> bool { let Some(ti) = v.get("tileInfo") else { return false }; - let wkid = ti.pointer("/spatialReference/latestWkid").or_else(|| ti.pointer("/spatialReference/wkid")).and_then(|w| w.as_i64()); + // The first of latestWkid and wkid that RustGIS reads, as an extent's code is chosen. + let mercator = |c: u32| matches!(c, 3857 | 102100 | 102113); + let wkid = ti + .get("spatialReference") + .and_then(|r| crate::filegdb::arcgis_codes(r).find(|c| mercator(*c) || crate::filegdb::crs_of_code(*c).is_some())); let first = ti.pointer("/lods/0/resolution").and_then(|r| r.as_f64()); let level0 = ti.pointer("/lods/0/level").and_then(|l| l.as_i64()); let rows = ti.get("rows").and_then(|r| r.as_i64()).unwrap_or(256); @@ -5782,6 +5790,20 @@ mod document_tests; mod tests { use super::*; + /// A tile cache's code is the first of latestWkid and wkid that RustGIS reads: one it can't + /// read falls back to Web Mercator's wkid, and one it reads that isn't Web Mercator stays not. + #[test] + fn a_mercator_cache_falls_back_to_its_wkid() { + let cache = |sr: serde_json::Value| serde_json::json!({"tileInfo": {"rows": 256, "spatialReference": sr, "lods": [{"level": 0, "resolution": 156_543.033_928_041}]}}); + assert!(arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 3857})))); + assert!(arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 999_999})))); + assert!(!arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 4326})))); + // An extent its first readable code can't hold has no box, rather than one read in the other. + let extent = + serde_json::json!({"xmin": 200, "ymin": 40, "xmax": 201, "ymax": 41, "spatialReference": {"latestWkid": 4326, "wkid": 3857}}); + assert_eq!(arcgis_extent(&extent), None); + } + #[test] fn capabilities_and_collections_preserve_only_the_explicit_login() { let binding = "0123456789abcdef"; @@ -5975,6 +5997,14 @@ mod tests { let bern = parse("https://x.org/arcgis/rest/services/A/FeatureServer", lv95.as_bytes()).unwrap(); let [w, so, e, n] = bern.layers[0].bbox.unwrap(); assert!(w < 7.44 && e > 7.44 && so < 46.95 && n > 46.95 && e - w < 2.0 && n - so < 1.5, "{:?}", bern.layers[0].bbox); + // A latestWkid RustGIS doesn't read falls back to the wkid, as a layer's own system does. + let newer = lv95.replace(r#"{"wkid": 2056}"#, r#"{"wkid": 2056, "latestWkid": 999999}"#); + assert_ne!(newer, lv95); + let newer = parse("https://x.org/arcgis/rest/services/A/FeatureServer", newer.as_bytes()).unwrap(); + assert_eq!(newer.layers[0].bbox, bern.layers[0].bbox); + // Web Mercator's old and new codes stay Web Mercator. + let [w, so, e, n] = s.layers[0].bbox.unwrap(); + assert!((w + 8.98).abs() < 0.01 && so.abs() < 1e-9 && (e - 8.98).abs() < 0.01 && (n - 8.94).abs() < 0.01, "{:?}", s.layers[0].bbox); // In longitude/latitude, or a system RustGIS doesn't read (said): asked in EPSG:4326. // A system given only as WKT has no code to ask for it by: said too. for (sr, note) in [ diff --git a/crates/data/src/process.rs b/crates/data/src/process.rs new file mode 100644 index 0000000000..b6048eb990 --- /dev/null +++ b/crates/data/src/process.rs @@ -0,0 +1,52 @@ +//! Reading what a program started on the desktop prints, within a limit. + +/// The most of a program's standard output, and of its standard error, that is kept. +pub const PIPE_LIMIT: u64 = 64 << 20; + +/// What ends a program's messages cut at their limit ([`marked_cut`]). +pub const CUT: &[u8] = b"\n(cut)"; + +/// `text` kept to `limit` bytes and ended with [`CUT`] when `cut`: for messages that are only +/// shown, so a cut is said rather than refused. +pub fn marked_cut(mut text: Vec, cut: bool, limit: u64) -> Vec { + if cut { + text.truncate(usize::try_from(limit).unwrap_or(usize::MAX).saturating_sub(CUT.len())); + text.extend_from_slice(CUT); + } + text +} + +/// Reads `pipe` to its end on a thread of its own, keeping its first `limit` bytes and reading +/// the rest into the void, so a program that prints without end can't fill the memory, and +/// can't block on a full pipe either. The thread answers the bytes kept and whether any were +/// left out (or a read failed partway); a thread the system refuses is the error. +pub fn drain_bounded( + mut pipe: impl std::io::Read + Send + 'static, + limit: u64, +) -> std::io::Result, bool)>> { + use std::io::Read as _; + std::thread::Builder::new().spawn(move || { + let mut buf = Vec::new(); + let read = pipe.by_ref().take(limit).read_to_end(&mut buf); + let rest = std::io::copy(&mut pipe, &mut std::io::sink()); + // A pipe that fails partway counts as cut: what was kept may not be all it held. + (buf, read.is_err() || !matches!(rest, Ok(0))) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Exactly the limit is kept whole and said uncut; one byte more is cut to the limit and said. + #[test] + fn a_pipe_is_kept_to_its_limit_and_says_when_cut() { + let (kept, cut) = drain_bounded(std::io::Cursor::new(vec![7u8; 10]), 10).unwrap().join().unwrap(); + assert_eq!((kept.len(), cut), (10, false)); + let (kept, cut) = drain_bounded(std::io::Cursor::new(vec![7u8; 11]), 10).unwrap().join().unwrap(); + assert_eq!((kept.len(), cut), (10, true)); + assert_eq!(marked_cut(kept.clone(), false, 10), kept); + let marked = marked_cut(kept, true, 10); + assert!(marked.len() == 10 && marked.ends_with(CUT), "{marked:?}"); + } +} diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index f5d027cd72..91d226ebaf 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -216,8 +216,7 @@ pub fn open_now(remote: Arc) -> Result { /// longitude/latitude or one RustGIS can't read, which is asked for in longitude/latitude instead. fn own_system(description: &serde_json::Value) -> Option<(crate::raster::Crs, crate::raster::Transformer, u32)> { let reference = description.pointer("/extent/spatialReference").or_else(|| description.get("sourceSpatialReference"))?; - let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok()); - let (crs, code) = [code("latestWkid"), code("wkid")].into_iter().flatten().find_map(|c| Some((crate::filegdb::crs_of_code(c)?, c)))?; + let (crs, code) = crate::filegdb::arcgis_code(reference)?; if crs == crate::raster::Crs::LonLat { return None; } diff --git a/crates/data/src/source/external.rs b/crates/data/src/source/external.rs index b64b8bef89..c4c83105ec 100644 --- a/crates/data/src/source/external.rs +++ b/crates/data/src/source/external.rs @@ -163,8 +163,7 @@ pub(crate) fn output_with_budget( run(c, timeout, what, workspace, None) } -/// The most of a program's standard output, and of its standard error, that is kept. -const PIPE_LIMIT: u64 = 64 << 20; +use crate::process::PIPE_LIMIT; fn run( mut c: Command, @@ -197,18 +196,10 @@ fn run( return Err(e); } } - // Keeps the first `PIPE_LIMIT` bytes and reads the rest into the void, so a program that prints - // without end can't fill the memory, and can't block on a full pipe either. - let drain = |p: Option>| { - std::thread::Builder::new().spawn(move || { - let mut buf = Vec::new(); - if let Some(mut p) = p { - let _ = p.by_ref().take(PIPE_LIMIT).read_to_end(&mut buf); - let _ = std::io::copy(&mut p, &mut std::io::sink()); - } - buf - }) - }; + // Keeps the first `PIPE_LIMIT` bytes of each, so a program that prints without end can't + // fill the memory, and can't block on a full pipe either. + let drain = + |p: Option>| crate::process::drain_bounded(p.unwrap_or_else(|| Box::new(std::io::empty())), PIPE_LIMIT); let out = drain(child.stdout.take().map(|p| Box::new(p) as Box)); let err = drain(child.stderr.take().map(|p| Box::new(p) as Box)); // No thread to read its output with: the program is stopped, as without one to write with. @@ -257,8 +248,17 @@ fn run( return Err(e); } }; - let stdout = out.join().unwrap_or_default(); - let stderr = err.join().unwrap_or_default(); + // A reader that stopped without an answer leaves nothing to trust: an error, not an empty one. + let unread = |pipe: &str| std::io::Error::other(format!("{what}'s {pipe} couldn't be read")); + let (stdout, out_cut) = out.join().map_err(|_| unread("output"))?; + let (stderr, err_cut) = err.join().map_err(|_| unread("messages"))?; + // Its output is parsed: a part of it is no answer. Its messages are only shown: cut, and said. + if out_cut { + return Err(std::io::Error::other(format!( + "{what}'s output couldn't be read to the end, or it printed more than {PIPE_LIMIT} bytes: narrow the request first (a smaller extent, a row limit or a filter)" + ))); + } + let stderr = crate::process::marked_cut(stderr, err_cut, PIPE_LIMIT); Ok(std::process::Output { status, stdout, stderr }) } @@ -593,17 +593,26 @@ mod tests { assert!(out.status.success(), "without a probe a program only runs"); } - /// A program that prints more than the limit keeps the start of it and still finishes: its - /// pipes are read to the end. + /// A program that prints more than the limit still finishes (its pipes are read to the end): + /// output past it is an error, not a shorter answer; messages past it keep their start and + /// say they were cut. #[cfg(unix)] #[test] - fn output_past_the_limit_is_dropped_and_the_program_finishes() { + fn output_past_the_limit_is_refused_and_the_program_finishes() { let mut c = Command::new("/bin/sh"); c.args(["-c", "head -c 100000000 /dev/zero; head -c 70000000 /dev/zero >&2; echo done >&2"]); + let e = output(c, std::time::Duration::from_secs(120), "printer").unwrap_err(); + assert!( + e.to_string().contains(&format!("printer's output couldn't be read to the end, or it printed more than {PIPE_LIMIT} bytes")), + "{e}" + ); + let mut c = Command::new("/bin/sh"); + c.args(["-c", "echo small; head -c 70000000 /dev/zero >&2"]); let out = output(c, std::time::Duration::from_secs(120), "printer").unwrap(); assert!(out.status.success()); - assert_eq!(out.stdout.len() as u64, PIPE_LIMIT); + assert_eq!(out.stdout, b"small\n"); assert_eq!(out.stderr.len() as u64, PIPE_LIMIT, "the limit is per pipe"); + assert!(out.stderr.ends_with(crate::process::CUT)); let mut c = Command::new("/bin/sh"); c.args(["-c", "echo small; echo oops >&2"]); let out = output(c, std::time::Duration::from_secs(60), "printer").unwrap(); diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index a2ad50e138..15242f757e 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -711,7 +711,7 @@ impl FeatureSource for ParquetSource { let declared = u64::try_from(md.row_group(g).num_rows()).unwrap_or(0); if declared > self.group_rows as u64 { return Err(DataError::Format(format!( - "GeoParquet: row group {g} has {declared} rows, more than the {} read from one", + "GeoParquet: row group {g} has {declared} rows, more than the {} read from one: write it again with smaller row groups", self.group_rows ))); } @@ -990,7 +990,7 @@ impl FeatureSource for ParquetSource { let readable = self.rows_in(md, g); if declared > self.group_rows as u64 { return Err(DataError::Format(format!( - "GeoParquet: row group {g} has {declared} rows, more than the {} read from one", + "GeoParquet: row group {g} has {declared} rows, more than the {} read from one: write it again with smaller row groups", self.group_rows ))); } @@ -2276,10 +2276,11 @@ const MAX_VECTOR_VALUES: usize = if cfg!(target_arch = "wasm32") { 8 << 20 } els /// The rows of row group `g`, refused when they are more than the `cap` read from one, for a read /// that can't say it left some out. fn whole_group(g: usize, rows: i64, cap: usize) -> Result { - usize::try_from(rows) - .ok() - .filter(|rows| *rows <= cap) - .ok_or_else(|| DataError::Format(format!("GeoParquet: row group {g} has {rows} rows, more than the {cap} read from one"))) + usize::try_from(rows).ok().filter(|rows| *rows <= cap).ok_or_else(|| { + DataError::Format(format!( + "GeoParquet: row group {g} has {rows} rows, more than the {cap} read from one: write it again with smaller row groups" + )) + }) } /// Reads the points of a GeoParquet in `extent` (longitude/latitude) with the vectors of a list @@ -2292,6 +2293,13 @@ fn whole_group(g: usize, rows: i64, cap: usize) -> Result { /// extent needs. Fails with [`remote::NEED`] until the bytes it needs are fetched (run it with /// [`remote::drive`]). pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_groups: usize, max_points: usize) -> Result { + read_vectors_with(file, extent, column, (max_groups, max_points), MAX_GROUP_ROWS) +} + +/// [`read_vectors`], reading at most `group_rows` rows of a row group: a group with more is an +/// error, not one whose last rows' points are quietly left out. +fn read_vectors_with(file: &Arc, extent: &Extent, column: &str, limits: (usize, usize), group_rows: usize) -> Result { + let (max_groups, max_points) = limits; let reader = remote_reader(file)?; let md = reader.metadata(); let schema = md.file_metadata().schema_descr(); @@ -2327,7 +2335,7 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group let (mut zm, mut unplaced, mut others) = (0usize, 0usize, 0usize); for &g in &groups { let rg = reader.get_row_group(g).map_err(err)?; - let rows = whole_group(g, rg.metadata().num_rows(), MAX_GROUP_ROWS)?; + let rows = whole_group(g, rg.metadata().num_rows(), group_rows)?; let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(*decoded, g))?; if geoms.len() != rows { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); @@ -2387,7 +2395,8 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group let mut out = Vectors::default(); for (g, inside) in &found { let rg = reader.get_row_group(*g).map_err(err)?; - let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0).min(MAX_GROUP_ROWS); + // Every group in `found` passed `whole_group` above. + let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0); let mut take = vec![false; rows]; for (r, _) in inside { if let Some(t) = take.get_mut(*r) { @@ -3390,6 +3399,46 @@ mod tests { assert!(error.contains("the 2399 bytes the decoded-column budget has left"), "{error}"); } + /// A row group with more rows than a vector read takes is refused, naming the group and both + /// counts, not read short; one within it gives every point in the extent. + #[test] + fn read_vectors_refuses_a_group_it_cant_read_whole() { + use arrow_array::types::Float32Type; + use arrow_array::{ArrayRef, BinaryArray, ListArray, RecordBatch}; + use arrow_schema::{DataType, Field as AField, Schema}; + let points: Vec> = [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)] + .iter() + .map(|&(x, y)| crate::wkb::encode(&crate::Geometry::Point(rustgis_geom::Coord::new(x, y)))) + .collect(); + let geometry: ArrayRef = Arc::new(BinaryArray::from_iter_values(points.iter())); + let embedding: ArrayRef = + Arc::new(ListArray::from_iter_primitive::((0..3).map(|i| Some(vec![Some(i as f32), Some(1.0)])))); + let item = Arc::new(AField::new("item", DataType::Float32, true)); + let schema = Arc::new(Schema::new(vec![ + AField::new("geometry", DataType::Binary, false), + AField::new("embedding", DataType::List(item), true), + ])); + let batch = RecordBatch::try_new(schema.clone(), vec![geometry, embedding]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = ::parquet::arrow::ArrowWriter::try_new(&mut bytes, schema, None).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let url = "https://test.example/vectors-group-cap.parquet"; + remote::testing::serve(url, bytes); + let everywhere = Extent::new(-180.0, -90.0, 180.0, 90.0); + let read = |group_rows: usize| { + remote::drive_blocking( + remote::file(url), + Arc::new(move || read_vectors_with(&remote::file(url), &everywhere, "embedding", (10, 10), group_rows)), + ) + }; + let error = read(2).unwrap_err().to_string(); + assert!(error.contains("row group 0 has 3 rows, more than the 2 read from one"), "{error}"); + let v = read(3).unwrap(); + assert_eq!(v.points, [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]); + assert_eq!((v.dims, v.values.len()), (2, 6)); + } + /// The layout `delta_stream` reads agrees with a real writer's: the count and the end of the /// stream (the page holds nothing else) for many shapes of values, in pages of one stream. #[test] diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 15459ccde4..afa7a7aaff 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2243,14 +2243,25 @@ fn domain(s: &mut Session, p: &Json) -> CmdResult { } let kind = if let Some(codes) = p.get("coded").and_then(Json::as_array) { // A code its field can't hold as given is refused, not cut to another or left out. + // Nor is a list too long, an entry that isn't a pair, or a code that asks for null. + super::at_most("coded", "a coded domain", codes, 10_000)?; let mut pairs: Vec<(Value, String)> = Vec::new(); - for c in codes.iter().take(10_000) { - let Some(given) = c.get(0) else { continue }; + for c in codes { + let given = c + .as_array() + .filter(|a| (1..=2).contains(&a.len())) + .and_then(|a| a.first()) + .ok_or("coded is a list of [code, description] pairs")?; let code = super::edit::held_default(&fname, &Value::from_json(given), ty)?; - let desc = c.get(1).and_then(Json::as_str).map(String::from).unwrap_or_else(|| code.to_string()); - if !code.is_null() { - pairs.push((code, desc)); + if code.is_null() { + return Err(format!("coded: a code for '{fname}' can't be empty or null")); } + // No description (or null) is the code's own text; one of another kind is refused. + let desc = match c.get(1) { + None | Some(Json::Null) => code.to_string(), + Some(d) => d.as_str().map(String::from).ok_or("coded: a description is text")?, + }; + pairs.push((code, desc)); } if pairs.is_empty() { return Err("coded is a list of [code, description] pairs".into()); diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index d90b386715..3b31088bb2 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -850,7 +850,7 @@ pub(crate) fn similarity_work(s: &Session, p: &Value) -> Result Result Result, extra: Value) -> Result { - let bytes = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; - let name = r.name.clone(); - let layer = RasterLayer::from_written(r, format!("{name}.tif"), bytes); - let said = name.clone(); - let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { - let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); - let added = id.and_then(|id| s.map().layer(id)).map_or(said, |l| l.name.clone()); - for note in notes { - s.say(note.prefixed(&added)); - } - }); - Ok(super::workflows::made_layer(name, layer, Some(extra), Some(then))) -} - /// AlphaEarth's files of `years` (in their order) for the tile nearest the centre of `area` that /// has them all, from one read of the index (a wait that doesn't look at Cancel); the tile's /// place, and what to say of the search. @@ -1558,7 +1540,7 @@ mod tests { let r = quantised([[1.0; 3]; 4]); let made = |name: &str, notes: Vec| { let raster = rustgis_analysis::rasterops::derive(&r, name, vec![vec![0.5; 4]]).unwrap(); - made_saying(raster, notes, json!({"year": 2024})).unwrap() + super::super::workflows::made_noted(raster, notes, json!({"year": 2024}), |_| {}).unwrap() }; let mark = s.notice_mark(); let mut with_loss: Vec = notes.iter().map(Note::from).collect(); @@ -1717,7 +1699,8 @@ mod tests { s.map_mut().add_dataset(lines); let grid = quantised([[1.0; 3]; 4]); let raster = rustgis_analysis::rasterops::derive(&grid, "Grid", vec![vec![0.5; 4]]).unwrap(); - super::super::workflows::add_made(&mut s, made_saying(raster, Vec::new(), json!({})).unwrap()).unwrap(); + super::super::workflows::add_made(&mut s, super::super::workflows::made_noted(raster, Vec::new(), json!({}), |_| {}).unwrap()) + .unwrap(); let mut refused = |points: Value| { let before = s.map().layers.len(); let e = s.run("embeddings.similarity", &json!({"dataset": "alphaearth", "points": points, "bbox": area})).unwrap_err(); diff --git a/crates/engine/src/cmd/layout/chart.rs b/crates/engine/src/cmd/layout/chart.rs index 2fd1e386c1..ae7cb7533d 100644 --- a/crates/engine/src/cmd/layout/chart.rs +++ b/crates/engine/src/cmd/layout/chart.rs @@ -52,9 +52,15 @@ pub(in crate::cmd::layout) fn gives_scale_bar_details(p: &Value) -> bool { /// A whole number from 0 to `hi` given as `k`, when it's given (and not null): an error when it's /// not a number, not whole or out of range. pub(in crate::cmd::layout) fn given_count(p: &Value, k: &str, hi: usize) -> Result, String> { - let what = format!("a whole number from 0 to {hi}"); + given_count_from(p, k, 0, hi) +} + +/// [`given_count`] with a lowest count other than 0: one outside `lo..=hi` is refused, not held +/// to the nearest end. +pub(in crate::cmd::layout) fn given_count_from(p: &Value, k: &str, lo: usize, hi: usize) -> Result, String> { + let what = format!("a whole number from {lo} to {hi}"); match given_num(p, k, &what)? { - Some(n) if n >= 0.0 && n.fract() == 0.0 && n <= hi as f64 => Ok(Some(n as usize)), + Some(n) if n >= lo as f64 && n.fract() == 0.0 && n <= hi as f64 => Ok(Some(n as usize)), Some(_) => Err(format!("{k} is {what}")), None => Ok(None), } diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 36890e16a1..9c37692bd5 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -820,8 +820,10 @@ pub(in crate::cmd::layout) fn tick_side(p: &Value) -> Result, S } } +/// A colorbar's tick count: one outside 2 to [`MAX_COLORBAR_TICKS`] is refused, not held to the +/// nearest end. pub(in crate::cmd::layout) fn ticks(p: &Value) -> Result, String> { - Ok(given_num(p, "ticks", "a number")?.map(|v| v.round().clamp(2.0, MAX_COLORBAR_TICKS as f64) as usize)) + given_count_from(p, "ticks", 2, MAX_COLORBAR_TICKS) } /// An extent indicator's outline colour and width (points) from `color` and `width` in `p`, each diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index ce492a8740..f1740304f5 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -213,10 +213,14 @@ pub(in crate::cmd::layout) fn add_profile(s: &mut Session, p: &Value) -> CmdResu let first = sections.first().ok_or("the frame has no section line: add one first (layout.addElement with kind section)")?; let layer = if gives(p, "layer") { String::new() } else { first_profile_layer(map)? }; let base = Profile::new(frame, first.name.clone(), layer, ProfileSide::default_for(first.line)); - let (mut new, held) = profile_params(s, l, p, base)?; - // Titled with its layer's name unless given one ("" for none), as a colorbar is. + let (mut new, mut held) = profile_params(s, l, p, base)?; + // Titled with its layer's name unless given one ("" for none), as a colorbar is; a name + // longer than a title holds is cut, and said. if p.get("title").is_none_or(Value::is_null) { new.title = new.layer.chars().take(MAX_PROFILE_TEXT).collect(); + if new.layer.chars().count() > MAX_PROFILE_TEXT { + held.push(format!("title cut to the first {MAX_PROFILE_TEXT} characters of the layer's name")); + } } let rect = new.rect(frame_box); let l = s.project.layouts.get_mut(li).ok_or("no layout")?; diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 51a06a6ef4..8b09fd9273 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -56,8 +56,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result *units, }; - let divisions = - given_num(p, "divisions", "a number")?.map_or(*divisions, |n| n.round().clamp(1.0, MAX_SCALE_DIVISIONS as f64) as usize); + let divisions = given_count_from(p, "divisions", 1, MAX_SCALE_DIVISIONS)?.unwrap_or(*divisions); let (color, fill) = (color(p, "color", *c)?, color(p, "fill", *fill)?); let text_size = text_size_param(p, "textSize", SCALE_BAR_TEXT_PT)?.unwrap_or(*text_size); // Its details, each read before any is set: one part is the division whole. diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 057654b661..f5a8a758fc 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -67,11 +67,11 @@ mod desktop { use rustgis_data::loss::{LossCode, Note}; use rustgis_data::raster::Raster; - use rustgis_map::{Ramp, RasterLayer, RasterRenderer, Stretch}; + use rustgis_map::{Ramp, RasterRenderer, Stretch}; use serde_json::{Value, json}; use super::super::layer::{WindowAsked, WindowRaster}; - use super::super::workflows::{Made, Then, Work}; + use super::super::workflows::{Work, made_noted}; use crate::Session; use crate::render::rustgis_tiles::stac::{self, bands as sb}; @@ -172,7 +172,9 @@ mod desktop { Ok(Box::new(move || { rustgis_data::progress::check().map_err(|e| e.to_string())?; let (made, notes) = read_and_stack(&name, &channels, &picked, &hrefs, bbox, cell, anonymous)?; - made_saying(made, notes, json!({"bands": channels, "bbox": bbox})) + made_noted(made, notes, json!({"bands": channels, "bbox": bbox}), |layer| { + layer.style.renderer = RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }; + }) })) } @@ -224,22 +226,12 @@ mod desktop { } rustgis_data::progress::check().map_err(|e| e.to_string())?; let raster = rustgis_analysis::rasterops::derive(&stacked, &name, vec![band])?; - let then = noted(raster.name.clone(), notes); - // The encode below is one step with no look inside it: Cancel is looked at before it. - rustgis_data::progress::check().map_err(|e| e.to_string())?; - let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; - let layer_name = raster.name.clone(); - let mut layer = RasterLayer::from_written(raster, format!("{layer_name}.tif"), bytes); // Drawn in colour over the range the index means something in, not grey over this window's own. let (ramp, min, max) = index_look(id); - layer.style.renderer = RasterRenderer::Stretch { band: 0, ramp, invert: false }; - layer.style.stretch = Stretch::Custom { min, max, bands: None }; - Ok(super::super::workflows::made_layer( - layer_name, - layer, - Some(json!({"index": id, "bands": wanted, "bbox": bbox})), - Some(then), - )) + made_noted(raster, notes, json!({"index": id, "bands": wanted, "bbox": bbox}), |layer| { + layer.style.renderer = RasterRenderer::Stretch { band: 0, ramp, invert: false }; + layer.style.stretch = Stretch::Custom { min, max, bands: None }; + }) })) } @@ -692,30 +684,6 @@ mod desktop { } Ok((raster, notes)) } - - /// The made raster, kept as a GeoTIFF and drawn as red, green and blue, with what to say of it - /// once it is added (by its name on the map) and what the command answers besides. - fn made_saying(raster: Raster, notes: Vec, extra: Value) -> Result { - // The encode is one step with no look inside it: Cancel is looked at before it. - rustgis_data::progress::check().map_err(|e| e.to_string())?; - let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; - let name = raster.name.clone(); - let mut layer = RasterLayer::from_written(raster, format!("{name}.tif"), bytes); - layer.style.renderer = RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }; - let then = noted(name.clone(), notes); - Ok(super::super::workflows::made_layer(name, layer, Some(extra), Some(then))) - } - - /// What to say of a made layer once it is added: each note, by the layer's name on the map. - fn noted(name: String, notes: Vec) -> Then { - Box::new(move |s: &mut Session, v: &mut Value| { - let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); - let added = id.and_then(|id| s.map().layer(id)).map_or(name, |l| l.name.clone()); - for note in notes { - s.say(note.prefixed(&added)); - } - }) - } } #[expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index e417065ffb..46c60ee8bd 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -423,6 +423,38 @@ pub(crate) fn made_then(raster: Raster, extra: Option, then: Option Ok(m) } +/// What to say of a made layer once it is added: each note, by the layer's name on the map +/// (`name` when the answer names no layer). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn noted(name: String, notes: Vec) -> Then { + Box::new(move |s: &mut Session, v: &mut Value| { + let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); + let added = id.and_then(|id| s.map().layer(id)).map_or(name, |l| l.name.clone()); + for note in notes { + s.say(note.prefixed(&added)); + } + }) +} + +/// The made raster, kept as a GeoTIFF and styled by `style`, with what to say of it once it is +/// added ([`noted`]) and what the command answers besides (`extra`). The encode is one step with +/// no look inside it: Cancel is looked at before it. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn made_noted( + raster: Raster, + notes: Vec, + extra: Value, + style: impl FnOnce(&mut rustgis_map::RasterLayer), +) -> Result { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; + let name = raster.name.clone(); + let mut layer = rustgis_map::RasterLayer::from_written(raster, format!("{name}.tif"), bytes); + style(&mut layer); + let then = noted(name.clone(), notes); + Ok(made_layer(name, layer, Some(extra), Some(then))) +} + /// A layer made (styled, say), to be added as `name`. pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: Option, then: Option) -> Made { Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new(), staged: None } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c187eec3e3..b5966464cf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13569,9 +13569,15 @@ fn layout_surrounds_take_cartographic_options() { assert!(matches!(find(&s, "northArrow").kind, ElementKind::NorthArrow { style: ArrowStyle::Compass, .. })); let star = s.run("layout.addElement", &json!({"kind": "northArrow", "style": "STAR"})).unwrap()["element"].as_u64().unwrap() as u32; assert!(matches!(s.project.layouts[0].element(star).unwrap().kind, ElementKind::NorthArrow { style: ArrowStyle::Star, .. })); - // Scale bars: units, divisions and a style; divisions are clamped. + // Scale bars: units, divisions and a style; divisions out of range are refused, not held. let bar = find(&s, "scaleBar").id; - s.run("layout.update", &json!({"element": bar, "units": "mi", "divisions": 99, "style": "stepped"})).unwrap(); + let before = find(&s, "scaleBar").kind.clone(); + for divisions in [json!(99), json!(50), json!(0), json!(-3), json!(2.5)] { + let err = s.run("layout.update", &json!({"element": bar, "units": "mi", "divisions": divisions})).unwrap_err(); + assert_eq!(err, "divisions is a whole number from 1 to 10", "{divisions}"); + assert_eq!(find(&s, "scaleBar").kind, before, "{divisions}: a refused update changes nothing"); + } + s.run("layout.update", &json!({"element": bar, "units": "mi", "divisions": 10, "style": "stepped"})).unwrap(); assert!(matches!( find(&s, "scaleBar").kind, ElementKind::ScaleBar { units: ScaleUnits::Miles, divisions: 10, style: ScaleBarStyle::Stepped, .. } @@ -14803,10 +14809,24 @@ fn layout_colorbars_follow_a_raster() { let id = s.run("layout.addElement", &json!({"kind": "colorbar"})).unwrap()["element"].as_u64().unwrap() as u32; assert!(matches!(kind(&s, id), ElementKind::Colorbar { layer: None, ticks: 5, reverse: false, .. }), "{:?}", kind(&s, id)); assert!(s.run("layout.addElement", &json!({"kind": "colorbar", "layer": "Countries"})).is_err(), "a feature layer has no colour scale"); + // A tick count out of range is refused, not held to 2 or 21; one in range says nothing. + let count = s.project.layouts[0].elements.len(); + for ticks in [json!(100), json!(1e9), json!(0), json!(1), json!(3.6)] { + let err = s.run("layout.addElement", &json!({"kind": "colorbar", "ticks": ticks})).unwrap_err(); + assert_eq!(err, "ticks is a whole number from 2 to 21", "{ticks}"); + assert!(s.run("layout.update", &json!({"element": id, "ticks": ticks})).is_err(), "{ticks}"); + } + assert_eq!(s.project.layouts[0].elements.len(), count, "a refused colorbar isn't added"); + assert!(matches!(kind(&s, id), ElementKind::Colorbar { ticks: 5, .. }), "a refused update changes nothing"); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "ticks": 7})).unwrap(); + assert!(s.notices_since(mark).is_empty(), "{:?}", s.notices_since(mark)); + assert!(matches!(kind(&s, id), ElementKind::Colorbar { ticks: 7, .. })); + s.run("layout.update", &json!({"element": id, "ticks": 5})).unwrap(); s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap(); let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); let named = s - .run("layout.addElement", &json!({"kind": "colorbar", "layer": dem.to_uppercase(), "orientation": "vertical", "ticks": 1e9, "tickSide": "left", "reverse": true})) + .run("layout.addElement", &json!({"kind": "colorbar", "layer": dem.to_uppercase(), "orientation": "vertical", "ticks": 21, "tickSide": "left", "reverse": true})) .unwrap()["element"] .as_u64() .unwrap() as u32; @@ -18414,6 +18434,34 @@ fn project_items_files_styles_packages_tasks_and_3d() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_coded_domain_refuses_codes_it_would_leave_out() { + let mut s = world(); + s.run("layer.template", &json!({"template": "routes", "name": "Roads"})).unwrap(); + let domains = |s: &Session| s.map().layer_by_name("Roads").unwrap().design.domains.clone(); + let many: Vec = (0..10_001).map(|i| json!([format!("c{i}"), "C"])).collect(); + let err = s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": many})).unwrap_err(); + assert!(err.contains("at most 10000"), "{err}"); + let err = s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [["paved", "Paved"], "gravel"]})).unwrap_err(); + assert_eq!(err, "coded is a list of [code, description] pairs"); + let err = s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [["paved", "Paved", "extra"]]})).unwrap_err(); + assert_eq!(err, "coded is a list of [code, description] pairs"); + let err = s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [["paved", 5]]})).unwrap_err(); + assert_eq!(err, "coded: a description is text"); + let err = + s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [[null, "None"], ["paved", "Paved"]]})).unwrap_err(); + assert_eq!(err, "coded: a code for 'surface' can't be empty or null"); + let err = + s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [["", "None"], ["paved", "Paved"]]})).unwrap_err(); + assert_eq!(err, "coded: a code for 'surface' can't be empty or null"); + assert!(domains(&s).is_empty(), "a refused domain isn't set"); + s.run("data.domain", &json!({"layer": "Roads", "field": "surface", "coded": [["paved", "Paved"], ["gravel", "Gravel"]]})).unwrap(); + match domains(&s).first().map(|d| &d.kind) { + Some(rustgis_map::design::DomainKind::Coded(pairs)) => assert_eq!(pairs.len(), 2), + other => panic!("{other:?}"), + } +} + #[test] fn data_design_rules_hold_on_every_edit() { let mut s = world(); diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index c4e6c1664e..de63a27082 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -90,6 +90,26 @@ fn frame_box(s: &Session, frame: u32) -> [f64; 4] { [e.x, e.y, e.w, e.h] } +/// A profile titled after a layer whose name is longer than a title holds keeps the first +/// characters and says it cut the rest; a short name says nothing. +#[test] +fn a_profiles_title_cut_from_a_long_layer_name_is_said() { + let (mut s, frame) = with_dem(); + s.run("layout.update", &json!({"element": frame, "scale": 5e6})).unwrap(); + s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50]})).unwrap(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap()["element"].as_u64().unwrap(); + assert!(said(&s, mark).iter().all(|t| !t.contains("title cut")), "{:?}", said(&s, mark)); + assert_eq!(profile(&s, id).0.title, "DEM"); + let long = "D".repeat(150); + s.run("layer.rename", &json!({"layer": "DEM", "name": long})).unwrap(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap()["element"].as_u64().unwrap(); + let cut: Vec = said(&s, mark).into_iter().filter(|t| t.contains("title cut")).collect(); + assert_eq!(cut.len(), 1, "{:?}", said(&s, mark)); + assert_eq!(profile(&s, id).0.title.chars().count(), rustgis_map::layout::MAX_PROFILE_TEXT); +} + /// A profile is added along a section line of its frame (its first unless named), of the top /// raster shown unless named, beside the frame on the side the line runs along; it follows the /// frame when moved or resized, and goes with it; and all of it is undone. diff --git a/crates/geolibre/src/runner.rs b/crates/geolibre/src/runner.rs index c44978caff..98a21a8d11 100644 --- a/crates/geolibre/src/runner.rs +++ b/crates/geolibre/src/runner.rs @@ -135,9 +135,9 @@ fn command(exe: &Path) -> Command { /// Runs `c` to completion, or kills it after `limit`. For the quick queries (version, /// manifests): a program that only happens to be called `geolibre` mustn't hang the app. Tool /// runs have no limit, since a large raster can legitimately take a long time. -fn output_within(c: Command, limit: Duration) -> Option { +fn output_within(c: Command, limit: Duration) -> Result { let start = Instant::now(); - output_until(c, &|| (start.elapsed() >= limit).then(|| "timed out".to_string())).ok() + output_until(c, &|| (start.elapsed() >= limit).then(|| "timed out".to_string())) } /// Starts `c`, waiting out a program file that is still held open for writing ("text file @@ -162,27 +162,25 @@ fn spawn_when_free(c: &mut Command, stop: &dyn Fn() -> Option) -> Result } } +/// The most of the runner's standard output, and of its standard error, that is kept: past it, +/// output is an error and messages are cut. +const PIPE_LIMIT: u64 = if cfg!(test) { 1 << 16 } else { rustgis_data::process::PIPE_LIMIT }; + /// Runs `c` to completion, unless `stop` gives a reason first (looked at every 20 ms): then the /// process is killed and the reason is the error. Both pipes are drained while it runs. fn output_until(mut c: Command, stop: &dyn Fn() -> Option) -> Result { c.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); let mut child = spawn_when_free(&mut c, stop)?; // Drain both pipes on threads while the process runs: a full pipe (large manifests, or - // many warnings) would otherwise block it until the time limit. - fn drain(mut pipe: impl std::io::Read + Send + 'static) -> std::io::Result>> { - std::thread::Builder::new().spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - buf - }) - } + // many warnings) would otherwise block it until the time limit. Each keeps PIPE_LIMIT bytes. + let drain = |pipe| rustgis_data::process::drain_bounded(pipe, PIPE_LIMIT); let (Some(out), Some(err)) = (child.stdout.take(), child.stderr.take()) else { // Not expected with piped output, but never leave the process running. let _ = child.kill(); let _ = child.wait(); return Err("the program's output couldn't be read".into()); }; - let (out_reader, err_reader) = match (drain(out), drain(err)) { + let (out_reader, err_reader) = match (drain(Box::new(out) as Box), drain(Box::new(err))) { (Ok(out), Ok(err)) => (out, err), // No thread to read its output with: never leave the process running. (Err(e), _) | (_, Err(e)) => { @@ -204,8 +202,16 @@ fn output_until(mut c: Command, stop: &dyn Fn() -> Option) -> Result Option { } let mut c = command(exe); c.arg("version"); - let out = output_within(c, Duration::from_secs(10))?; + let out = output_within(c, Duration::from_secs(10)).ok()?; let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); (out.status.success() && text.starts_with("geolibre-cli")).then_some(text) } @@ -317,7 +323,7 @@ pub fn manifests() -> Result, String> { let (exe, _) = find().ok_or("the GeoLibre runner isn't installed")?; let mut c = command(&exe); c.arg("manifests"); - let out = output_within(c, Duration::from_secs(60)).ok_or_else(|| format!("{}: no answer to `manifests`", exe.display()))?; + let out = output_within(c, Duration::from_secs(60)).map_err(|e| format!("{}: no answer to `manifests` ({e})", exe.display()))?; if !out.status.success() { return Err(format!("{}: {}", exe.display(), String::from_utf8_lossy(&out.stderr).trim())); } @@ -376,7 +382,12 @@ pub(crate) fn run_pinned( let err = String::from_utf8_lossy(&out.stderr); let err = err.trim(); let err = if err.is_empty() { "the tool stopped unexpectedly" } else { err }; - return Err(err.lines().take(20).collect::>().join("\n")); + // The first lines, and a word that there were more (or that the program's were cut). + let mut shown: Vec<&str> = err.lines().take(20).collect(); + if err.lines().count() > shown.len() { + shown.push("(cut)"); + } + return Err(shown.join("\n")); } Ok(String::from_utf8_lossy(&out.stdout).lines().map(str::to_string).collect()) } @@ -437,6 +448,30 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Output past the limit is an error, not a shorter answer; messages past it are kept to the + /// limit and said to be cut; output within it comes back whole. + #[cfg(unix)] + #[test] + fn output_past_the_pipe_limit_is_refused() { + use rustgis_data::process::CUT; + let past = PIPE_LIMIT + 1024; + let mut c = Command::new("sh"); + c.args(["-c", &format!("head -c {past} /dev/zero")]); + let e = output_until(c, &|| None).unwrap_err(); + assert!(e.contains(&PIPE_LIMIT.to_string()), "{e}"); + let mut c = Command::new("sh"); + c.args(["-c", &format!("head -c {past} /dev/zero >&2; echo done")]); + let out = output_until(c, &|| None).unwrap(); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "done"); + assert_eq!(out.stderr.len() as u64, PIPE_LIMIT); + assert!(out.stderr.ends_with(CUT)); + let mut c = Command::new("sh"); + c.args(["-c", &format!("head -c {PIPE_LIMIT} /dev/zero >&2")]); + let out = output_until(c, &|| None).unwrap(); + assert_eq!(out.stderr.len() as u64, PIPE_LIMIT, "exactly the limit is kept whole"); + assert!(!out.stderr.ends_with(CUT)); + } + /// A program asked to stop is killed at once, not waited for (#1562): a GeoLibre step of a /// model run in the background stops with its Cancel. #[test] diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index eed912d573..4df46361e3 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -36,8 +36,9 @@ pub const CACHE_BYTES: usize = 64 * 1024 * 1024; /// each thread takes several turns, in a layer of few rows. const CHUNK_ROWS: usize = 256; -/// A level of fewer vertices than this is built on the calling thread alone. -const THREADS_FROM_VERTICES: usize = 50_000; +/// Work of fewer vertices than this is done on the calling thread alone: starting threads would +/// cost more than they save ([`threads_for`]; the map view's meshes follow it too). +pub const THREADS_FROM_VERTICES: usize = 50_000; /// What building a row takes beside its result, per vertex: each run projected (16 bytes a vertex), /// which vertices to keep, and the kept ones, before the row is counted in the budget. @@ -226,10 +227,11 @@ fn map_budgeted_at<'g>( map_budgeted_rows(len, budget, threads, |row| geometry(row).map(&build)) } -/// The threads to build a level of `total` vertices on, the biggest row taking `biggest` bytes to -/// build ([`row_scratch`]): at most `most`, one below [`THREADS_FROM_VERTICES`], and as many as -/// `scratch` bytes hold beyond one thread's, each building a row as big as the biggest. -fn threads_for(total: usize, biggest: usize, most: usize, scratch: usize) -> usize { +/// The threads to do work of `total` vertices on (a level, or the map view's meshes), the biggest +/// item taking `biggest` bytes to do (a level's [`row_scratch`]): at most `most`, one below +/// [`THREADS_FROM_VERTICES`], and as many as `scratch` bytes hold beyond one thread's, each doing +/// an item as big as the biggest. +pub fn threads_for(total: usize, biggest: usize, most: usize, scratch: usize) -> usize { if total < THREADS_FROM_VERTICES { return 1; } diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs index ce028d8868..3a557fb613 100644 --- a/crates/render/src/mesh_tiles.rs +++ b/crates/render/src/mesh_tiles.rs @@ -58,28 +58,20 @@ const MAX_TILES: usize = 4096; /// tiles), the layer is made one mesh, so the lists stay within 8 MB of indices. const MAX_MEMBERS: usize = 1 << 20; -/// A layer estimated at fewer vertices than this is meshed on one thread: starting threads would -/// cost more than they save. -const THREADS_FROM_VERTICES: usize = 50_000; - /// The bytes a mesh vertex takes while a tile is tessellated: the vertex (40 bytes), its share of /// the indices and lyon's scratch. const SCRATCH_PER_VERTEX: usize = 96; -/// The threads to mesh `tiles` on: one for little work, else as many as the tiles and the user's -/// thread count allow, and no more than [`rustgis_data::memory::thread_scratch`] holds beyond one -/// thread's, each meshing a tile as big as the biggest (by the features' estimates, each counted -/// whole in every tile it reaches). +/// The threads to mesh `tiles` on, by [`rustgis_map::lod::threads_for`]: one for little work, else +/// as many as the tiles and the user's thread count allow, and no more than +/// [`rustgis_data::memory::thread_scratch`] holds beyond one thread's, each meshing a tile as big +/// as the biggest (by the features' estimates, each counted whole in every tile it reaches). fn threads_for(features: &[Feature<'_>], tiles: &[&(Tile, Vec)]) -> usize { let estimate = |members: &[usize]| members.iter().filter_map(|k| features.get(*k)).map(|f| f.estimate).fold(0usize, usize::saturating_add); let total = tiles.iter().map(|(_, m)| estimate(m)).fold(0usize, usize::saturating_add); - if total < THREADS_FROM_VERTICES { - return 1; - } - let biggest = tiles.iter().map(|(_, m)| estimate(m)).max().unwrap_or(0).saturating_mul(SCRATCH_PER_VERTEX).max(1); - let affordable = (rustgis_data::memory::thread_scratch() / biggest).saturating_add(1); - rustgis_data::threads::for_items(tiles.len()).min(affordable).max(1) + let biggest = tiles.iter().map(|(_, m)| estimate(m)).max().unwrap_or(0).saturating_mul(SCRATCH_PER_VERTEX); + rustgis_map::lod::threads_for(total, biggest, rustgis_data::threads::for_items(tiles.len()), rustgis_data::memory::thread_scratch()) } /// The side of the tiles, map units: the power of two nearest [`TILE_PX`] physical pixels at diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 46e4189d55..529b3eadbc 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -2754,21 +2754,21 @@ mod tests { let mark = app.session.notice_mark(); assert!(!add_point(&mut app, cities.id, &state)); assert!(app.session.notices_since(mark).iter().any(|n| n.error)); - // A code of no text is not offered: it would show as chosen whenever nothing is. - run( - &mut app, - "data.domain", - json!({"layer": cities.id, "field": text.name, "coded": [["", "None"], ["cap", "Capital"]], "force": true}), - ); - let layer = app.session.map().layer(cities.id).unwrap(); - assert_eq!(choices(layer, &text), Some(vec![("cap".into(), "Capital".into())])); - // With no code left to offer, the field is typed into, as one without a list is. - // (The command itself drops a code of no text; a design read from a project may hold one.) + // A code of no text is not offered: it would show as chosen whenever nothing is. The + // command refuses one; a design read from a project may still hold one. + let coded = json!({"layer": cities.id, "field": text.name, "coded": [["", "None"], ["cap", "Capital"]], "force": true}); + assert!(app.session.run("data.domain", &coded).is_err()); use rustgis_ui_egui::rustgis_engine::data::Value as Stored; use rustgis_ui_egui::rustgis_engine::map::design::{Domain, DomainKind}; + let none = (Stored::Text(String::new()), "None".to_string()); let mut copy = app.session.map().layer(cities.id).unwrap().clone(); - copy.design.domains = - vec![Domain { field: text.name.clone(), kind: DomainKind::Coded(vec![(Stored::Text(String::new()), "None".into())]) }]; + copy.design.domains = vec![Domain { + field: text.name.clone(), + kind: DomainKind::Coded(vec![none.clone(), (Stored::Text("cap".into()), "Capital".into())]), + }]; + assert_eq!(choices(©, &text), Some(vec![("cap".into(), "Capital".into())])); + // With no code left to offer, the field is typed into, as one without a list is. + copy.design.domains = vec![Domain { field: text.name.clone(), kind: DomainKind::Coded(vec![none]) }]; assert_eq!(choices(©, &text), None); // A template chosen and since removed is let go by the sheet, with a notice. set_form(&ctx, Form { shown: Some(cities.instance), template: Some("Gone".into()), ..Form::default() });