From f5b487b439981ff392335ef4c2d42c7f76704259 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:08:55 -0500 Subject: [PATCH 01/11] fix(data): a deleted dBASE record no longer shifts Shapefile attributes dBASE's record iterator passes over records marked deleted, so pairing it with the shapes gave every later shape the next record's attributes and dropped the last shapes. The marks are now cleared before reading and the records left out by position, each with its shape, and counted in one notice. The streamed provider counts the ones it leaves out too, and a table's unreadable-record notice has a singular form. --- crates/data/src/dbf.rs | 22 +++++ crates/data/src/io.rs | 146 +++++++++++++++++++++++++--- crates/data/src/source/shp.rs | 23 ++++- crates/data/src/source/shp/tests.rs | 28 ++++++ 4 files changed, 202 insertions(+), 17 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 8ba9411373..56c569a5d8 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -286,6 +286,28 @@ fn retype_columns(dbf: &mut [u8], from: u8, to: u8) -> Vec { changed } +/// The records of a `.dbf` marked deleted (`*`), by their position, with their marks cleared so +/// dBASE's reader gives every record the header counts, one for each shape: it passes over a +/// deleted record, which would pair every later shape with the next record. Only the records the +/// header counts that the file holds are looked at. +pub(crate) fn take_deleted(dbf: &mut [u8]) -> Vec { + let le16 = |at: usize| Some(usize::from(u16::from_le_bytes([*dbf.get(at)?, *dbf.get(at + 1)?]))); + let (Some(header_len), Some(record_len)) = (le16(8), le16(10)) else { return Vec::new() }; + let count = dbf.get(4..8).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, u32::from_le_bytes); + if record_len == 0 { + return Vec::new(); + } + let Some(body) = dbf.get_mut(header_len..) else { return Vec::new() }; + let mut deleted = Vec::new(); + for (k, record) in body.chunks_exact_mut(record_len).take(usize::try_from(count).unwrap_or(usize::MAX)).enumerate() { + if let Some(flag) = record.first_mut().filter(|f| **f == b'*') { + *flag = b' '; + deleted.push(k); + } + } + deleted +} + /// A column of a `.dbf` as its header describes it: its name's bytes (up to the first NUL), /// type letter, length in bytes and decimals. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2d4cf160ee..254eb3598c 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3480,6 +3480,9 @@ struct DbfRead { /// For each field, its text values that aren't UTF-8 in a table read as UTF-8 /// ([`crate::dbf::not_utf8`]). not_utf8: Vec, + /// The records marked deleted, by position, ascending: the reader gives them as any other + /// ([`crate::dbf::take_deleted`]), and they are left out by position. + deleted: Vec, } /// Opens dBASE attributes with the Shapefile reader's code-page and date/number handling. @@ -3490,6 +3493,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { // Counted before a date column is marked a character one below: its values aren't text. let (names, not_utf8) = if encoding.is_utf8() { crate::dbf::not_utf8(&bytes) } else { (Vec::new(), Vec::new()) }; encoding_notes.extend(crate::dbf::not_utf8_names_note(&names)); + let deleted = crate::dbf::take_deleted(&mut bytes); crate::dbf::readable_header_date(&mut bytes); let date_columns = crate::dbf::dates_as_text(&mut bytes); crate::dbf::floats_as_numeric(&mut bytes); @@ -3499,7 +3503,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { // A date's year may be padded with spaces on the left (` 10101`): keep them. .with_options(shapefile::dbase::ReadingOptions::default().character_trim(shapefile::dbase::TrimOption::End)) .build(Cursor::new(bytes)) - .map_err(|e| DataError::Format(format!("Shapefile: the .dbf: {e}")))?; + .map_err(|e| DataError::Format(format!("the .dbf: {e}")))?; // Field order comes from the .dbf header (records are unordered maps). let order: Vec<(String, FieldType)> = dbf .fields() @@ -3519,7 +3523,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { }) .collect(); let fields = order.into_iter().map(|(n, t)| Field::new(n, t)).collect(); - Ok(DbfRead { reader: dbf, fields, decimals, report: ReadReport { messages: encoding_notes, ..Default::default() }, not_utf8 }) + Ok(DbfRead { reader: dbf, fields, decimals, report: ReadReport { messages: encoding_notes, ..Default::default() }, not_utf8, deleted }) } /// Reads a geometry-free dBASE table, checking cancellation and counting progress per record. @@ -3527,14 +3531,19 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { /// same budget as delimited tables; archive members share the remaining allowance. /// The bounded file read and header decoding finish before cancellation can be observed. fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { - let DbfRead { mut reader, fields, decimals, mut report, not_utf8 } = dbf_reader(bytes, cpg)?; + let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(bytes, cpg)?; let mut ds = Dataset::new(name, GeometryType::None, fields); let mut counts = DbfCounts::new(ds.fields.len(), not_utf8); let allowance = *budget; let mut left = allowance; crate::progress::begin(reader.header().num_records as usize); - for record in reader.iter_records() { + let (mut is_deleted, mut left_out) = (deleted_by_position(&deleted), 0); + for (k, record) in reader.iter_records().enumerate() { crate::progress::step(1)?; + if is_deleted(k) { + left_out += 1; + continue; + } match record { Ok(record) => { let attrs = dbf_attrs(&record, &ds.fields, &mut counts); @@ -3564,20 +3573,43 @@ fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, name: &str, budget: &mut usize) Err(_) => report.skipped += 1, } } - // The iterator passes over records marked deleted; the header still counts them. - let deleted = (reader.header().num_records as usize).saturating_sub(ds.features.len() + report.skipped); - if deleted > 0 { - report.messages.push(format!("{name}: {deleted} dBASE records marked deleted were left out")); - } + report.messages.extend(deleted_records_note(name, left_out, false)); dbf_notices(&ds, &mut report, &counts); integral_numeric_to_integer(&mut ds, &decimals); - if report.skipped > 0 { - report.messages.push(format!("{name}: {} dBASE records were unreadable and left out", report.skipped)); + match report.skipped { + 0 => {} + 1 => report.messages.push(format!("{name}: 1 dBASE record was unreadable and left out")), + n => report.messages.push(format!("{name}: {n} dBASE records were unreadable and left out")), } *budget = left; Ok((ds, report)) } +/// Whether the record at a position, asked in ascending order, is one of `deleted` (ascending). +fn deleted_by_position(deleted: &[usize]) -> impl FnMut(usize) -> bool + '_ { + let mut next = deleted.iter().peekable(); + move |k| { + while next.next_if(|d| **d < k).is_some() {} + next.next_if(|d| **d == k).is_some() + } +} + +/// The notice for `n` records of `name`'s `.dbf` marked deleted and left out, and for a +/// Shapefile (`with_shapes`), their shapes with them. +fn deleted_records_note(name: &str, n: usize, with_shapes: bool) -> Option { + deleted_records_text(n, with_shapes).map(|t| format!("{name}: {t}")) +} + +/// [`deleted_records_note`] without the layer's name. +pub(crate) fn deleted_records_text(n: usize, with_shapes: bool) -> Option { + let (what, shapes) = match n { + 0 => return None, + 1 => ("1 dBASE record marked deleted was left out".to_string(), ", with its shape"), + n => (format!("{n} dBASE records marked deleted were left out"), ", with their shapes"), + }; + Some(if with_shapes { format!("{what}{shapes}") } else { what }) +} + /// Converts one record to typed values, sharing loss counts with the containing dataset. fn dbf_attrs(record: &shapefile::dbase::Record, fields: &[Field], counts: &mut DbfCounts) -> Vec { use shapefile::dbase::FieldValue; @@ -3667,7 +3699,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio use shapefile::Shape; use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); - let DbfRead { reader: dbf, fields, decimals, mut report, not_utf8 } = dbf_reader(parts.dbf, parts.cpg.as_deref())?; + let DbfRead { reader: dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref())?; let shapes = match parts.shx { Some(shx) => shapefile::ShapeReader::with_shx(Cursor::new(parts.shp), Cursor::new(shx)), None => shapefile::ShapeReader::new(Cursor::new(parts.shp)), @@ -3692,7 +3724,13 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio let mut counts = DbfCounts::new(ds.fields.len(), not_utf8); let mut source_kind = GeometryType::None; let pt = |x: f64, y: f64| Coord::new(x, y); - for item in reader.iter_shapes_and_records() { + // Paired by position: a record marked deleted is read as any other, and left out with its shape. + let (mut is_deleted, mut left_out) = (deleted_by_position(&deleted), 0); + for (k, item) in reader.iter_shapes_and_records().enumerate() { + if is_deleted(k) { + left_out += 1; + continue; + } let Ok((shape, record)) = item else { report.skipped += 1; continue; @@ -3758,6 +3796,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio ds.push_next(geom, attrs); } ds.drop_zm(&mut report, zm_shapes); + report.messages.extend(deleted_records_note(name, left_out, true)); dbf_notices(&ds, &mut report, &counts); ds.geometry_type = dominant_type(&ds); // A bad .prj must not turn a spatial layer into an attribute-only table and hide the @@ -8762,4 +8801,85 @@ mod tests { assert!(own.iter().any(|n| n.contains("1 vertex with a missing or infinite coordinate")), "{own:?}"); assert!(shapefile_geometry_notes(&line, "out.shp", Crs::Epsg(25832)).is_empty()); } + + /// The `.dbf` of three points, named `a`, `b` and `c`, with a numeric `n` of 1, 2 and 3. + fn three_named_points(dir: &Path) -> std::path::PathBuf { + let path = dir.join("pts.shp"); + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut ds = Dataset::new("pts", GeometryType::Point, fields); + for (k, name) in ["a", "b", "c"].iter().enumerate() { + let x = k as f64; + ds.push(Some(Geometry::Point(Coord::new(x, x))), vec![Value::Text((*name).into()), Value::Int(k as i64 + 1)]); + } + write_path(&ds, &path).unwrap(); + path + } + + /// Where record `k` of a `.dbf` starts (its deletion flag). + fn dbf_record_at(dbf: &[u8], k: usize) -> usize { + let header = usize::from(u16::from_le_bytes([dbf[8], dbf[9]])); + let len = usize::from(u16::from_le_bytes([dbf[10], dbf[11]])); + header + k * len + } + + /// A Shapefile whose `.dbf` marks its middle record deleted: that record's shape is left out + /// with it, each kept shape keeps its own attributes (dBASE's reader passing over the record + /// once paired every later shape with the next record, and dropped the last shape), and one + /// notice gives the count. A clean file says nothing of it. + #[test] + fn a_deleted_dbf_record_leaves_its_shape_out_and_says_so() { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + let deleted = |r: &ReadReport| r.messages.iter().filter(|m| m.contains("marked deleted")).count(); + let (clean, report) = read_shapefile_in(&path, "pts", None).unwrap(); + assert_eq!(clean.features.len(), 3); + assert_eq!(deleted(&report), 0, "{:?}", report.messages); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + let at = dbf_record_at(&dbf, 1); + dbf[at] = b'*'; + std::fs::write(&dbf_path, &dbf).unwrap(); + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + let kept: Vec<_> = ds + .features + .iter() + .map(|f| { + let Some(Geometry::Point(p)) = f.geometry.clone() else { panic!("a point") }; + (p.x, f.attrs[0].clone()) + }) + .collect(); + assert_eq!(kept, [(0.0, Value::Text("a".into())), (2.0, Value::Text("c".into()))]); + assert_eq!(deleted(&report), 1, "{:?}", report.messages); + assert!(report.messages.iter().any(|m| m == "pts: 1 dBASE record marked deleted was left out, with its shape"), "{:?}", report.messages); + assert_eq!(report.skipped, 0); + } + + /// A standalone table: a record marked deleted is left out and counted, and one dBASE can't + /// read (a number that isn't one) is left out and said, with the rows on both sides kept. + /// Clean input says neither. + #[test] + fn a_dbf_table_counts_deleted_and_unreadable_records() { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + let clean = std::fs::read(path.with_extension("dbf")).unwrap(); + let notes = |r: &ReadReport| r.messages.iter().filter(|m| m.contains("marked deleted") || m.contains("unreadable")).cloned().collect::>(); + let (ds, report) = read_bytes("t.dbf", &clean).unwrap(); + assert_eq!(ds.features.len(), 3); + assert!(notes(&report).is_empty(), "{:?}", report.messages); + let mut one_deleted = clean.clone(); + let at = dbf_record_at(&one_deleted, 1); + one_deleted[at] = b'*'; + let (ds, report) = read_bytes("t.dbf", &one_deleted).unwrap(); + assert_eq!(ds.features.iter().map(|f| f.attrs[0].clone()).collect::>(), [Value::Text("a".into()), Value::Text("c".into())]); + assert_eq!(notes(&report), ["t: 1 dBASE record marked deleted was left out"]); + // The `n` column follows the 1-byte flag and the `name` column. + let mut unreadable = clean.clone(); + let name_len = usize::from(unreadable[32 + 16]); + let at = dbf_record_at(&unreadable, 1) + 1 + name_len; + let n_len = usize::from(unreadable[64 + 16]); + unreadable[at..at + n_len].fill(b'x'); + let (ds, report) = read_bytes("t.dbf", &unreadable).unwrap(); + assert_eq!(ds.features.iter().map(|f| f.attrs[0].clone()).collect::>(), [Value::Text("a".into()), Value::Text("c".into())]); + assert_eq!(notes(&report), ["t: 1 dBASE record was unreadable and left out"]); + } } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index e02c60e8c5..dfd7609580 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -242,6 +242,7 @@ impl FeatureSource for ShpSource { let mut row = vec![0u8; self.table.row_len]; let mut features = Vec::new(); let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); + let mut deleted = 0usize; let utf8 = self.encoding.is_utf8(); // An extent the file's system couldn't bound (#1925) has no boxes for the index to sample // by: every record is visited, tested, and the matches sampled as they come. @@ -298,8 +299,9 @@ impl FeatureSource for ShpSource { skipped += 1; return Ok(()); } - // A deleted row: its shape is left out too. + // A deleted row: its shape is left out too, and counted. if row.first() == Some(&b'*') { + deleted += 1; return Ok(()); } if late && !sample.wants() { @@ -337,7 +339,7 @@ impl FeatureSource for ShpSource { null_text, // A sampled read visits only some of the matches, so its count is of those; a late one // visits the whole layer, so its count is of the layer. - notes: boxed_off_note(boxed_off, !late && !complete, late), + notes: boxed_off_note(boxed_off, !late && !complete, late).into_iter().chain(deleted_note(deleted, !late && !complete)).collect(), not_utf8, }) } @@ -362,6 +364,7 @@ impl FeatureSource for ShpSource { let mut buf = Vec::new(); let mut row = vec![0u8; self.table.row_len]; let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); + let mut deleted = 0usize; let utf8 = self.encoding.is_utf8(); // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing @@ -414,8 +417,9 @@ impl FeatureSource for ShpSource { skipped += 1; return Ok(()); } - // A deleted row: its shape is left out too. + // A deleted row: its shape is left out too, and counted. if row.first() == Some(&b'*') { + deleted += 1; return Ok(()); } self.table.values(&row, &encoding, &mut unread_dates, &mut null_text, utf8.then_some(&mut not_utf8)) @@ -433,7 +437,7 @@ impl FeatureSource for ShpSource { unread_dates, rounded_dates: Vec::new(), null_text, - notes: boxed_off_note(boxed_off, false, late), + notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(), not_utf8, }) } @@ -463,6 +467,17 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { )] } +/// The note for `n` records marked deleted in the `.dbf`, left out with their shapes; of those +/// read when the read is `sampled`. +fn deleted_note(n: usize, sampled: bool) -> Option { + if sampled && n > 0 { + return Some(format!( + "{n} of the records read (a sample of the layer, which may hold more) are marked deleted in the .dbf: they're left out, with their shapes" + )); + } + crate::io::deleted_records_text(n, true) +} + /// A file read at offsets, through a buffer that a nearby offset reuses. struct Cursor { f: BufReader, diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 0b541e3f2d..38d95f382a 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -804,3 +804,31 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { }); std::fs::remove_dir_all(fixture).unwrap(); } +/// A streamed Shapefile leaves a record marked deleted out with its shape, as a whole read does, +/// and counts it; a clean one says nothing of it. +#[test] +fn a_streamed_shapefile_counts_its_deleted_records() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("pts.shp"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![crate::Field::new("name", crate::FieldType::Text)]); + for (k, name) in ["a", "b", "c"].iter().enumerate() { + ds.push(Some(Geometry::Point(Coord::new(k as f64, k as f64))), vec![crate::Value::Text((*name).into())]); + } + write_shapefile(&ds, &path); + let said = |r: &crate::ReadReport| r.messages.iter().filter(|m| m.contains("marked deleted")).cloned().collect::>(); + cache::with_index_dir(tmp.path().join("cache"), || { + let (clean, report) = crate::source::materialize(&ShpSource::open_path(&path, "pts").unwrap()).unwrap(); + assert_eq!(clean.features.len(), 3); + assert!(said(&report).is_empty(), "{:?}", report.messages); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + let header = usize::from(u16::from_le_bytes([dbf[8], dbf[9]])); + let len = usize::from(u16::from_le_bytes([dbf[10], dbf[11]])); + dbf[header + len] = b'*'; + std::fs::write(&dbf_path, &dbf).unwrap(); + let (ds, report) = crate::source::materialize(&ShpSource::open_path(&path, "pts").unwrap()).unwrap(); + let names: Vec<_> = ds.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(names, [crate::Value::Text("a".into()), crate::Value::Text("c".into())]); + assert_eq!(said(&report), ["pts: 1 dBASE record marked deleted was left out, with its shape"]); + }); +} From b2c722339320c75c5d771b2d0c3d4fa12daf05ab Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:29:50 -0500 Subject: [PATCH 02/11] fix(data): dBASE table messages name the layer, not Shapefile A standalone .dbf's open error and an unreadable .cpg said "Shapefile:"; they now name the layer. The CSV export notice for several multi-point features says "were written". --- crates/data/src/dbf.rs | 2 +- crates/data/src/io.rs | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 56c569a5d8..6266aea955 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -403,7 +403,7 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut Vec) -> Optio match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { - notes.push(format!("Shapefile: could not read .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable")); + notes.push(format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable")); None } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 254eb3598c..38a7131126 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -520,7 +520,7 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { let mut notes = Vec::new(); let cpg = crate::dbf::read_cpg(path, &mut notes); let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; - report.messages.extend(notes); + report.messages.extend(notes.into_iter().map(|n| format!("{name}: {n}"))); (ds, report) } "shp" => read_shapefile_in(path, &name, None)?, @@ -3075,7 +3075,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D cpg: crate::dbf::read_cpg(path, &mut notes), }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; - report.messages.extend(notes); + report.messages.extend(notes.into_iter().map(|n| format!("{name}: {n}"))); Ok((ds, report)) } @@ -3486,7 +3486,8 @@ struct DbfRead { } /// Opens dBASE attributes with the Shapefile reader's code-page and date/number handling. -fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { +/// `name` is the layer's, for the error of a `.dbf` it can't open. +fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result { use std::io::Cursor; let mut encoding_notes = Vec::new(); let encoding = crate::dbf::encoding(cpg, bytes.get(29).copied().unwrap_or(0), &mut encoding_notes); @@ -3503,7 +3504,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { // A date's year may be padded with spaces on the left (` 10101`): keep them. .with_options(shapefile::dbase::ReadingOptions::default().character_trim(shapefile::dbase::TrimOption::End)) .build(Cursor::new(bytes)) - .map_err(|e| DataError::Format(format!("the .dbf: {e}")))?; + .map_err(|e| DataError::Format(format!("{name}: the .dbf: {e}")))?; // Field order comes from the .dbf header (records are unordered maps). let order: Vec<(String, FieldType)> = dbf .fields() @@ -3531,7 +3532,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { /// same budget as delimited tables; archive members share the remaining allowance. /// The bounded file read and header decoding finish before cancellation can be observed. fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { - let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(bytes, cpg)?; + let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(bytes, cpg, name)?; let mut ds = Dataset::new(name, GeometryType::None, fields); let mut counts = DbfCounts::new(ds.fields.len(), not_utf8); let allowance = *budget; @@ -3699,7 +3700,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio use shapefile::Shape; use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); - let DbfRead { reader: dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref())?; + let DbfRead { reader: dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; let shapes = match parts.shx { Some(shx) => shapefile::ShapeReader::with_shx(Cursor::new(parts.shp), Cursor::new(shx)), None => shapefile::ShapeReader::new(Cursor::new(parts.shp)), @@ -4436,10 +4437,12 @@ impl CsvLosses { pub fn notes(&self, fields: &[Field], target: &str) -> Vec { let mut notes = Vec::new(); if self.as_one_point > 0 { - let what = if self.as_one_point == 1 { "1 feature has".to_string() } else { format!("{} features have", self.as_one_point) }; - notes.push(format!( - "{target}: {what} more than one point (a multipoint, line or polygon) and was written as one, as CSV holds a point a row" - )); + let what = if self.as_one_point == 1 { + "1 feature has more than one point (a multipoint, line or polygon) and was".to_string() + } else { + format!("{} features have more than one point (a multipoint, line or polygon) and were", self.as_one_point) + }; + notes.push(format!("{target}: {what} written as one, as CSV holds a point a row")); } if self.unwritten > 0 { let what = if self.unwritten == 1 { "1 feature".to_string() } else { format!("{} features", self.unwritten) }; @@ -8850,7 +8853,11 @@ mod tests { .collect(); assert_eq!(kept, [(0.0, Value::Text("a".into())), (2.0, Value::Text("c".into()))]); assert_eq!(deleted(&report), 1, "{:?}", report.messages); - assert!(report.messages.iter().any(|m| m == "pts: 1 dBASE record marked deleted was left out, with its shape"), "{:?}", report.messages); + assert!( + report.messages.iter().any(|m| m == "pts: 1 dBASE record marked deleted was left out, with its shape"), + "{:?}", + report.messages + ); assert_eq!(report.skipped, 0); } @@ -8862,7 +8869,9 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = three_named_points(dir.path()); let clean = std::fs::read(path.with_extension("dbf")).unwrap(); - let notes = |r: &ReadReport| r.messages.iter().filter(|m| m.contains("marked deleted") || m.contains("unreadable")).cloned().collect::>(); + let notes = |r: &ReadReport| { + r.messages.iter().filter(|m| m.contains("marked deleted") || m.contains("unreadable")).cloned().collect::>() + }; let (ds, report) = read_bytes("t.dbf", &clean).unwrap(); assert_eq!(ds.features.len(), 3); assert!(notes(&report).is_empty(), "{:?}", report.messages); From ae35488cee44290fefe318b96e21acd2605ba948 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:29:50 -0500 Subject: [PATCH 03/11] fix(data): count Z/M features, say COG overview losses, keep caches - A GDAL layer that declares Z or M counts the features that carry them, not every feature of the layer. - A COG overview whose alpha role differs from the full image's is left out and said (geotiff's overview pick skips it too), and the scan says when it stops at its most levels. - A lost PostGIS connection while bounding a view is reported as the error it is, not as a view that can't be bounded. - A user cache folder named reload-* is no longer taken for a disposable workspace: its owner lock must be there. --- crates/data/src/raster/cog.rs | 26 ++++++++-- crates/data/src/raster/geotiff.rs | 81 ++++++++++++++++++++++++++---- crates/data/src/source/external.rs | 32 +++++++++++- crates/data/src/source/gdal.rs | 32 ++++++++---- crates/data/src/source/postgis.rs | 35 +++++++------ 5 files changed, 161 insertions(+), 45 deletions(-) diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index c2c3c11f00..aeefa0d900 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -441,8 +441,10 @@ fn read_layout(r: Sparse) -> Result { let mut index = 0usize; let mut allowance = MAX_TOTAL_TILES; // Overviews left out for a sample count other than the full image's (its tag's, which a - // JPEG YCbCr image's decoded bands may differ from), and how many. + // JPEG YCbCr image's decoded bands may differ from), or another alpha role for the sample past + // the colour ones (an RGBA overview of an RGBI image would show its NIR as alpha), and how many. let full_samples = dec.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1); + let full_alpha = super::geotiff::extra_alpha(&mut dec); let mut mismatched: Vec = Vec::new(); let mut mismatched_count = 0usize; // Images no smaller than the full image in both width and height (not overviews), and how many. @@ -483,6 +485,7 @@ fn read_layout(r: Sparse) -> Result { // passed over too. All are said, and skipped before a tile size is checked or their // tiles count against the budget. let samples = dec.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1); + let alpha = super::geotiff::extra_alpha(&mut dec); let passed = match levels.first().map(|l| (l.width, l.height)) { // The full image itself. None => false, @@ -493,10 +496,17 @@ fn read_layout(r: Sparse) -> Result { } true } - Some(_) if samples != full_samples => { + Some(_) if samples != full_samples || alpha != full_alpha => { mismatched_count += 1; if mismatched.len() < 5 { - mismatched.push(format!("image {index} ({samples})")); + let role = if alpha == full_alpha { + "" + } else if alpha { + ", with alpha" + } else { + ", without alpha" + }; + mismatched.push(format!("image {index} ({samples}{role})")); } true } @@ -556,7 +566,12 @@ fn read_layout(r: Sparse) -> Result { counts.truncate(n); levels.push(Level { ifd: index, width: w, height: h, tile_width: tw, tile_height: th, offsets, counts }); } - if levels.len() >= MAX_LEVELS || !dec.more_images() { + if !dec.more_images() { + break; + } + // Sorted below, so a file storing its overviews smallest first loses its finest: said. + if levels.len() >= MAX_LEVELS { + lost.push(format!("the scan for overviews stopped at {MAX_LEVELS} levels: later images aren't read")); break; } dec.next_image().map_err(err)?; @@ -577,7 +592,8 @@ fn read_layout(r: Sparse) -> Result { if mismatched_count > 0 { let more = if mismatched_count > mismatched.len() { ", …" } else { "" }; lost.push(format!( - "{mismatched_count} overview(s) with samples per pixel other than the full image's {full_samples} are left out: {}{more}", + "{mismatched_count} overview(s) with samples per pixel or an alpha sample other than the full image's ({full_samples}{}) are left out: {}{more}", + if full_alpha { ", with alpha" } else { "" }, mismatched.join(", ") )); } diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 592fc32cd4..e397b65011 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1463,6 +1463,7 @@ pub(super) fn read_limited_with_nodata( Err(e) => (None, Some(format!("its Copyright tag: it can't be read ({e}), so it is left out"))), }; let spp = samples(&mut dec); + let full_alpha = extra_alpha(&mut dec); let bytes = sample_bytes(&mut dec); // The decoded image is held at its own pixel size before conversion to f32, so bound bytes // as well as samples. @@ -1492,9 +1493,14 @@ pub(super) fn read_limited_with_nodata( } let Ok((ow, oh)) = dec.dimensions() else { continue }; let (ospp, obytes) = (samples(&mut dec), sample_bytes(&mut dec)); - // An overview with another sample count (three of an RGBI image's four) would read - // as another kind of image: the full image is read sparsely instead. - if ospp == spp && fits(ow, oh, ospp, obytes) && best.is_none_or(|(_, bw, bh)| ow as u64 * oh as u64 > bw as u64 * bh as u64) { + // An overview with another sample count (three of an RGBI image's four), or another + // alpha role for the sample past the colour ones (an RGBA overview of an RGBI image), + // would read as another kind of image: the full image is read sparsely instead. + if ospp == spp + && extra_alpha(&mut dec) == full_alpha + && fits(ow, oh, ospp, obytes) + && best.is_none_or(|(_, bw, bh)| ow as u64 * oh as u64 > bw as u64 * bh as u64) + { best = Some((index, ow, oh)); } } @@ -1925,8 +1931,10 @@ pub fn write(r: &Raster, band: usize) -> Result> { } /// Writes every band of a raster, for a layer whose pixels the project keeps: as [`write`] does -/// when that keeps them all, otherwise as 32-bit float samples (RGB first for a colour raster, -/// and alpha after them when it has one), which [`read`] reads back as the same bands. +/// when that keeps them all. Otherwise: 8-bit samples when the raster is `UInt8` and every valid +/// value is a whole number in 0–255 (an empty cell only where no-data can mark it), else 32-bit +/// float samples (RGB first for a colour raster, and alpha after them when it has one). [`read`] +/// reads them back as the same bands. pub fn write_all(r: &Raster) -> Result> { encode(r, 0, true) } @@ -3611,6 +3619,58 @@ mod tests { } } + /// Sets the ExtraSamples value of each image with one, in turn, of a file + /// [`rgb_tiled_samples`] wrote. + fn set_extra_samples(bytes: &mut [u8], values: &[u16]) { + // The tag's entry: 338, type 3 (short), count 1, the value 0 as written. + let entry = [0x52, 0x01, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0]; + let at: Vec = (0..bytes.len().saturating_sub(12)).filter(|i| bytes[*i..*i + 12] == entry).collect(); + assert_eq!(at.len(), values.len()); + for (at, value) in at.iter().zip(values) { + bytes[at + 8..at + 10].copy_from_slice(&value.to_le_bytes()); + } + } + + /// An overview with the full image's sample count but another alpha role (an RGBA overview of + /// an RGBI image, or the reverse) is left out and said, not decoded with the full image's + /// colour layout; one with the same role is a level, with nothing said. + #[test] + fn cog_overviews_require_a_matching_alpha_sample() { + use super::super::cog::{self, Parse, Sparse}; + for (full, overview) in [(0, 0), (2, 2), (0, 2), (2, 0)] { + let mut bytes = rgb_tiled_samples(&[(40, 16, 4), (20, 16, 4)], 8, 1, |b, x, y| (b * 10 + x + y) as u16); + set_extra_samples(&mut bytes, &[full, overview]); + let whole = Sparse::default().with_len(bytes.len() as u64).with(0, bytes); + let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") }; + let said: Vec<_> = layout.lost.iter().filter(|n| n.contains("overview(s)")).collect(); + if full == overview { + assert_eq!(layout.levels.len(), 2); + assert!(said.is_empty(), "{:?}", layout.lost); + } else { + assert_eq!(layout.levels.len(), 1); + let role = if overview == 2 { "image 1 (4, with alpha)" } else { "image 1 (4, without alpha)" }; + assert!(said.len() == 1 && said[0].contains("an alpha sample") && said[0].contains(role), "{:?}", layout.lost); + } + } + } + + /// The scan stops at its most levels, and says so when the file holds more images; a file + /// with fewer says nothing of it. + #[test] + fn cog_says_when_it_stops_at_its_most_levels() { + use super::super::cog::{self, Parse, Sparse}; + const STOPPED: &str = "the scan for overviews stopped at 32 levels"; + for (images, cut) in [(32u32, false), (33, true)] { + // The full image 64 wide, its overviews 63, 62, … wide, smallest last. + let sizes: Vec<(u32, u32, u16)> = (0..images).map(|k| (64 - k, 16, 3)).collect(); + let bytes = rgb_tiled_samples(&sizes, 8, 1, |b, x, y| (b + x + y) as u16); + let whole = Sparse::default().with_len(bytes.len() as u64).with(0, bytes); + let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") }; + assert_eq!(layout.levels.len(), 32.min(images as usize)); + assert_eq!(layout.lost.iter().any(|n| n.contains(STOPPED)), cut, "{:?}", layout.lost); + } + } + #[test] fn cog_overviews_require_matching_sample_counts() { use super::super::cog::{self, Parse, Sparse}; @@ -3628,11 +3688,9 @@ mod tests { let Parse::Done(layout) = cog::layout(&whole).unwrap() else { panic!("not a COG") }; assert_eq!((layout.levels.len(), layout.bands), (1, usize::from(full))); assert!( - layout - .lost - .iter() - .any(|n| n.contains(&format!("1 overview(s) with samples per pixel other than the full image's {full}")) - && n.contains(&format!("image 1 ({overview})"))), + layout.lost.iter().any(|n| n.contains(&format!( + "1 overview(s) with samples per pixel or an alpha sample other than the full image's ({full})" + )) && n.contains(&format!("image 1 ({overview})"))), "{:?}", layout.lost ); @@ -3649,7 +3707,8 @@ mod tests { layout .lost .iter() - .any(|n| n.contains("1 overview(s) with samples per pixel other than the full image's 4") && n.contains("image 2 (3)")), + .any(|n| n.contains("1 overview(s) with samples per pixel or an alpha sample other than the full image's (4)") + && n.contains("image 2 (3)")), "{:?}", layout.lost ); diff --git a/crates/data/src/source/external.rs b/crates/data/src/source/external.rs index 7540f3c1a3..f769a241bf 100644 --- a/crates/data/src/source/external.rs +++ b/crates/data/src/source/external.rs @@ -45,9 +45,22 @@ impl ReloadWorkspace { self.dir.path() } - /// Whether a saved conversion belongs to a disposable workspace rather than a durable cache. + /// Whether a saved conversion belongs to a disposable workspace rather than a durable cache: + /// in a folder named as a workspace that holds its owner lock, marked as one. A user's cache + /// folder that only has such a name (`RUSTGIS_GDAL_CACHE=/data/reload-2024`) isn't one. A lock + /// that can't be read is held by a live owner (Windows refuses reads of a locked range). pub fn contains_file(path: &Path) -> bool { - path.parent().and_then(Path::file_name).is_some_and(|name| name.to_string_lossy().starts_with(RELOAD_PREFIX)) + use std::io::Read; + let Some(parent) = path.parent() else { return false }; + if !parent.file_name().is_some_and(|name| name.to_string_lossy().starts_with(RELOAD_PREFIX)) { + return false; + } + let Ok(mut lock) = std::fs::File::open(parent.join("owner.lock")) else { return false }; + let mut marker = [0; RELOAD_OWNER_MARKER.len()]; + match lock.read_exact(&mut marker) { + Ok(()) => marker.as_slice() == RELOAD_OWNER_MARKER, + Err(e) => e.kind() != std::io::ErrorKind::UnexpectedEof, + } } } @@ -329,6 +342,21 @@ mod tests { .unwrap(); } + /// A durable cache folder that is only named as a workspace keeps its conversions; a real + /// workspace's are disposable. + #[test] + fn only_a_real_workspace_contains_its_files() { + let cache = tempfile::tempdir().unwrap(); + let durable = cache.path().join("reload-2024"); + std::fs::create_dir_all(&durable).unwrap(); + assert!(!ReloadWorkspace::contains_file(&durable.join("layer.fgb"))); + std::fs::write(durable.join("owner.lock"), b"something else").unwrap(); + assert!(!ReloadWorkspace::contains_file(&durable.join("layer.fgb"))); + let workspace = reload_workspace(cache.path()).unwrap(); + assert!(ReloadWorkspace::contains_file(&workspace.path().join("layer.fgb"))); + assert!(!ReloadWorkspace::contains_file(&cache.path().join("layer.fgb"))); + } + #[test] fn reload_collection_preserves_a_new_unlocked_owner_lock_then_reclaims_it_after_grace() { let cache = tempfile::tempdir().unwrap(); diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index c977505e3a..8b9943c606 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -454,14 +454,10 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option converted.notes.push(format!("{}: couldn't check how many features GDAL's conversion kept ({error})", info.name)), } - let mut zm_dropped = info.has_zm && !converted.empty; - if zm_dropped { - let count = info.count.filter(|n| *n >= 0).map_or_else(|| "an unknown number of".into(), |n| n.to_string()); - converted.notes.push(format!( - "GDAL: '{layer}' declares Z or M coordinates on {count} source feature(s); conversion keeps only XY coordinates" - )); - } - if !info.has_zm && info.family.is_none() && !converted.empty { + let mut zm_dropped = false; + // A layer declaring Z or M may still hold features with only XY: those that carry them are + // counted, as for a layer of several types. + if (info.has_zm || info.family.is_none()) && !converted.empty { match count_zm_features(src, info, family) { Ok(0) => {} Ok(count) => { @@ -470,9 +466,13 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option converted.notes.push(format!( - "GDAL: '{layer}': an unknown number of source feature(s) may have had Z or M coordinates dropped; conversion keeps only XY coordinates" - )), + Err(_) => { + // A layer that declares them had them dropped, though how many is unknown. + zm_dropped = info.has_zm; + converted.notes.push(format!( + "GDAL: '{layer}': an unknown number of source feature(s) may have had Z or M coordinates dropped; conversion keeps only XY coordinates" + )); + } } } Ok(FreshConverted { path: converted.path, notes: converted.notes, empty: converted.empty, zm_dropped, workspace }) @@ -1055,6 +1055,16 @@ mod tests { let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); assert_eq!(batch.features[0].geometry.as_ref().unwrap().extent().center().x, if lossy { 2.0 } else { 8.0 }); } + // A layer of points with Z, two of its three features with only XY: the one with Z is + // counted, not the layer. + let mixed = ["[2,48]", "[3,48,100]", "[4,48]"] + .map(|c| format!(r#"{{"type":"Feature","properties":{{"rank":1}},"geometry":{{"type":"Point","coordinates":{c}}}}}"#)); + std::fs::write(&path, mixed.join("\n")).unwrap(); + let fresh = convert_one_fresh_in(&dir.join("cache"), &path, "points", None, None).unwrap(); + let said: Vec<_> = fresh.notes.iter().filter(|n| n.contains("Z or M")).collect(); + assert_eq!(said.len(), 1, "{:?}", fresh.notes); + assert!(said[0].contains("Z or M coordinates on 1 source feature(s)"), "{said:?}"); + assert!(fresh.zm_dropped); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index f4a423c21d..a6d2a17de2 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1201,7 +1201,7 @@ impl PostgisSource { if let Some(r) = &self.reproject { return r.extent_to_lonlat(e); } - self.server_transform(e, self.srid, 4326).unwrap_or(Extent::EMPTY) + self.server_transform(e, self.srid, 4326).ok().flatten().unwrap_or(Extent::EMPTY) } /// A longitude/latitude extent in the table's coordinates; a refused box is an error, @@ -1211,26 +1211,29 @@ impl PostgisSource { return r.database_extent(e); } let c = Extent::new(e.min_x.max(-180.0), e.min_y.max(-89.9), e.max_x.min(180.0), e.max_y.min(89.9)); - self.server_transform(&c, 4326, self.srid).ok_or_else(super::unbounded_database_view) + self.server_transform(&c, 4326, self.srid)?.ok_or_else(super::unbounded_database_view) } - /// An extent converted by the server: its edges, densified, transformed. - fn server_transform(&self, e: &Extent, from: i32, to: i32) -> Option { + /// An extent converted by the server: its edges, densified, transformed. `Ok(None)` when it + /// has none there: empty, or a box the server refuses to transform; a lost connection or + /// another failure to reach the server is an error, not a box that can't be bounded. + fn server_transform(&self, e: &Extent, from: i32, to: i32) -> Result> { if e.is_empty() { - return None; + return Ok(None); } let step = (e.width().max(e.height()) / 16.0).max(1e-9); - self.conn - .with(|c| { - c.query_opt( - "SELECT ST_XMin(b), ST_YMin(b), ST_XMax(b), ST_YMax(b) FROM \ - (SELECT ST_Transform(ST_Segmentize(ST_MakeEnvelope($1, $2, $3, $4, $5), $6), $7)::box2d AS b) s", - &[&e.min_x, &e.min_y, &e.max_x, &e.max_y, &from, &step, &to], - ) - }) - .ok() - .flatten() - .and_then(|r| row_extent(&r)) + let row = self.conn.with(|c| { + match c.query_opt( + "SELECT ST_XMin(b), ST_YMin(b), ST_XMax(b), ST_YMax(b) FROM \ + (SELECT ST_Transform(ST_Segmentize(ST_MakeEnvelope($1, $2, $3, $4, $5), $6), $7)::box2d AS b) s", + &[&e.min_x, &e.min_y, &e.max_x, &e.max_y, &from, &step, &to], + ) { + // The server's own refusal (a box its projection can't take): no box there. + Err(e) if e.as_db_error().is_some() => Ok(None), + r => r, + } + })?; + Ok(row.and_then(|r| row_extent(&r))) } /// The `WHERE` condition: a geometry, of the family read, and with `in_extent`, in the extent From beb96340fe11c8fe6118b4c1c8469bc9b23baa54 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:29:58 -0500 Subject: [PATCH 04/11] fix(engine): notice text for windows, unread rows and catalog links - Zarr window notices give the last column and row read, not the window's exclusive ends. - Export says "1 row couldn't be read" through unread_notice. - STAC's final info line says the reads cap before refused links. - One helper writes the catalog-link notices, with singular forms. - An ArcGIS 400 says the where clause or area may be the cause. - service.layers shares the data crate's address budget. --- crates/data/src/ogc.rs | 7 +++- crates/engine/src/cmd/connection_browse.rs | 12 ++---- crates/engine/src/cmd/mod.rs | 2 +- crates/engine/src/cmd/service.rs | 4 +- crates/engine/src/cmd/stac.rs | 43 +++++++++++++--------- crates/engine/src/cmd/whole.rs | 2 +- crates/engine/src/cmd/zarr.rs | 9 +++-- crates/engine/src/tests.rs | 4 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/stacui.rs | 9 +++-- 10 files changed, 53 insertions(+), 41 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 87db826f40..2fdb8fb40a 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -479,7 +479,8 @@ pub const MAX_LISTED_LAYERS: usize = 2_000; const MAX_READ_LAYERS: usize = if cfg!(test) { 3_000 } else { 100_000 }; /// Most bytes of a document's own request addresses (its GetMap's, GetFeature's…) copied into /// its layers together: each layer's address repeats them, so long ones lower how many are read. -const MAX_COPIED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { 64 << 20 }; +/// The same budget bounds the document addresses a listing repeats (`service.layers`). +pub const MAX_COPIED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { 64 << 20 }; /// How many layers are read from a document whose layers each copy `per_layer` bytes of its /// request addresses: [`MAX_READ_LAYERS`], fewer for long addresses, at least one. (Fewer than @@ -3879,7 +3880,9 @@ impl Pages { && !matches!(self.phase, Phase::Offsets { pbf: true, .. }) && query_value(&self.url, "where").is_some_and(|w| !w.eq_ignore_ascii_case("1%3D1") && w != "1=1") { - return Step::Failed(self.page_failure(&format!("the server rejected the query with its where clause: {error}"))); + return Step::Failed( + self.page_failure(&format!("the server rejected the query (its where clause or area may be the cause): {error}")), + ); } } if matches!(self.phase, Phase::Offsets { pbf: true, .. }) { diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index a3108638c8..1ed557c5e7 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -773,15 +773,9 @@ fn catalogs(s: &mut Session, bytes: &[u8], origin: &address::Origin) -> Result 0 { - s.notify(format!("{refused} catalog links were refused by the document's network reach"), false); - } - if skipped > 0 { - s.notify(format!("{skipped} catalog links were left out because their addresses are missing, invalid or not HTTP(S)"), false); - } omitted += children.len().saturating_sub(MAX_CHILDREN); - if omitted > 0 { - s.notify(format!("{omitted} catalog links were left out because the listing limit was reached"), false); + for note in crate::cmd::stac::catalog_link_notes(refused, skipped, omitted) { + s.notify(note, false); } if dropped > 0 { s.notify( @@ -1063,7 +1057,7 @@ mod tests { let notices = session.notices_since(mark); assert_eq!(notices.len(), usize::from(omitted > 0)); if omitted > 0 { - assert!(notices[0].text.contains(&format!("{omitted} catalog links were left out"))); + assert!(notices[0].text.contains(&format!("{omitted} catalog link")) && notices[0].text.contains("listing limit")); } } } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 30e86f96d3..3763b5b45c 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -66,7 +66,7 @@ pub mod tiles; pub mod time; pub mod view; pub mod webdata; -pub(crate) mod whole; +pub mod whole; pub mod workflows; pub mod workspace; pub mod zarr; diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 84fc34d5b9..bc1542adf3 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -147,7 +147,9 @@ const LEGENDS_LEFT_OUT_NOTICE: &str = /// Most bytes of document addresses a listing repeats: each listed layer's `source_url` is its /// document's address, which nothing bounds (a landing page links to any collections address). -const MAX_LISTED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { 64 << 20 }; +/// The budget [`rustgis_data::ogc::MAX_COPIED_ADDRESS_BYTES`] gives a document's own addresses; +/// the engine's tests list 8 MiB, as the data crate's do (its `cfg!(test)` is off for them). +const MAX_LISTED_ADDRESS_BYTES: usize = if cfg!(test) { 8 << 20 } else { rustgis_data::ogc::MAX_COPIED_ADDRESS_BYTES }; /// Whether what this `service.add` would wait for is left off the frame: it is a plugin command's, /// run by the desktop app, which runs the command again when it has come (#1319). diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 4d069703c2..78efa23cca 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -138,6 +138,25 @@ pub(super) fn collections_json(s: &mut Session, api: &str, bytes: &[u8]) -> CmdR collections_json_from_origin(s, api, bytes, &crate::render::rustgis_tiles::address::Origin::named(api)) } +/// The notices for the catalog links a listing left out: `refused` by the document's network +/// reach, `skipped` for their addresses, and `omitted` past the listing limit, in that order and +/// only those that happened. Callers give them the severity they need. +pub(crate) fn catalog_link_notes(refused: usize, skipped: usize, omitted: usize) -> Vec { + [ + (refused, "was refused by the document's network reach", "were refused by the document's network reach"), + ( + skipped, + "was left out because its address is missing, invalid or not HTTP(S)", + "were left out because their addresses are missing, invalid or not HTTP(S)", + ), + (omitted, "was left out because the listing limit was reached", "were left out because the listing limit was reached"), + ] + .into_iter() + .filter(|(n, ..)| *n > 0) + .map(|(n, one, many)| if n == 1 { format!("1 catalog link {one}") } else { format!("{n} catalog links {many}") }) + .collect() +} + fn collections_json_from_origin( s: &mut Session, api: &str, @@ -146,14 +165,8 @@ fn collections_json_from_origin( ) -> CmdResult { if stac::catalog::is_static(api) { let listing = stac::catalog::parse_children_noted(bytes, origin)?; - if listing.refused > 0 { - s.warn(format!("{} catalog links were refused by the document's network reach", listing.refused)); - } - if listing.skipped > 0 { - s.warn(format!("{} catalog links were left out because their addresses are missing, invalid or not HTTP(S)", listing.skipped)); - } - if listing.omitted > 0 { - s.warn(format!("{} catalog links were left out because the listing limit was reached", listing.omitted)); + for note in catalog_link_notes(listing.refused, listing.skipped, listing.omitted) { + s.warn(note); } let c = listing.links; let mut out = json!({"count": c.len(), "static": true, "collections": c.iter().map(|c| json!({"id": c.url, "title": c.title})).collect::>()}); @@ -309,13 +322,9 @@ fn search_static(s: &mut Session, p: &Value, root: &str) -> CmdResult { let walk = stac::catalog::walk_blocking(root, filter, search.limit); let complete = walk.complete(); let (read, failed) = (walk.reads, walk.failed); - let refused = walk.refused(); - if refused > 0 { - s.warn(format!("{refused} catalog links were refused by the document's network reach")); - } - let skipped = walk.skipped(); - if skipped > 0 { - s.warn(format!("{skipped} catalog links were left out because their addresses are missing, invalid or not HTTP(S)")); + let (refused, skipped) = (walk.refused(), walk.skipped()); + for note in catalog_link_notes(refused, skipped, 0) { + s.warn(note); } let items = walk.into_items(); let all = b(p, "properties").unwrap_or(false); @@ -1842,8 +1851,8 @@ mod deferred_asset_tests { let notices = session.notices_since(mark); assert_eq!(notices.len(), if refused { 3 } else { 0 }); if refused { - assert!(notices.iter().any(|n| n.text.contains("1 catalog links were refused"))); - assert!(notices.iter().any(|n| n.text.contains("1 catalog links were left out because their addresses"))); + assert!(notices.iter().any(|n| n.text.contains("1 catalog link was refused"))); + assert!(notices.iter().any(|n| n.text.contains("1 catalog link was left out because its address"))); } } } diff --git a/crates/engine/src/cmd/whole.rs b/crates/engine/src/cmd/whole.rs index 6001946cf5..6a6c2503a6 100644 --- a/crates/engine/src/cmd/whole.rs +++ b/crates/engine/src/cmd/whole.rs @@ -168,7 +168,7 @@ pub(crate) fn load_into(l: &mut Layer) -> Result { } /// The notice for `unread` rows of `layer`'s source that couldn't be read. -pub(crate) fn unread_notice(layer: &str, unread: usize) -> String { +pub fn unread_notice(layer: &str, unread: usize) -> String { match unread { 1 => format!("{layer}: 1 row couldn't be read and was left out"), n => format!("{layer}: {n} rows couldn't be read and were left out"), diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 9481424e1f..93ebc1c31b 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -304,7 +304,8 @@ fn read_store(url: &str, variable: &str) -> Result<(zarr::Store, bool), String> /// `raster.zarrInfo`. It reads the store's metadata and coordinates on the UI thread, with no /// Cancel, as it did before windows: the Add Data › Zarr dialog reads them off the frame, and none /// of the background paths takes a command that answers with what a store holds yet. A `"bbox"` -/// adds the variable's two map coordinates, read whole: at most `MAX_COORDS` values each (32 MB +/// adds the variable's two map coordinates, read whole (none for a grid its `spatial:transform` +/// places): at most `MAX_COORDS` values each (32 MB /// as Float64), each file a download of at most 60 s. A store whose root lists no arrays is read /// in up to [`MEMBER_ROUNDS`] more rounds of metadata files ([`store_at`]), each at most /// `zarr::member_keys`' 163 names (one or two files each), fetched several at a time. @@ -441,7 +442,8 @@ fn place_window(root: &str, store: &zarr::Store, sel: &mut zarr::Selection, aske let coords = store_files(root, &zarr::window_keys(store, &sel.variable).map_err(at)?)?; let (w, cut, widened) = zarr::window_of(store, &sel.variable, &coords, bbox).map_err(at)?; sel.window = Some(w); - let cells = format!("columns {}–{} and rows {}–{}", w.x0, w.x1, w.y0, w.y1); + // A window's ends are exclusive; the text gives the last column and row read. + let cells = format!("columns {}–{} and rows {}–{}", w.x0, w.x1.saturating_sub(1), w.y0, w.y1.saturating_sub(1)); let mut said = Vec::new(); if cut { said.push(format!("the bbox reaches past the grid: only {cells} within it are read")); @@ -458,7 +460,8 @@ fn place_window(root: &str, store: &zarr::Store, sel: &mut zarr::Selection, aske /// as it did before windows: the Add Data › Zarr dialog reads its slices off the frame and hands /// them over (`"ran"`), and none of the background paths takes a command that adds a layer from a /// store yet. A window bounds the read: `"cells"` reads only the chunks it touches and its part of -/// the coordinates; `"bbox"` first reads the variable's two map coordinates whole, at most +/// the coordinates; `"bbox"` first reads the variable's two map coordinates whole (none for a grid +/// its `spatial:transform` places), at most /// `MAX_COORDS` values each (32 MB as Float64), each file a download of at most 60 s. pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { let asked = asked_window(p)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4a026cc68..d0ae368e73 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -55094,7 +55094,7 @@ fn a_zarr_window_reads_only_its_chunks_by_range() { let mark = s.notice_mark(); s.run("layer.addZarr", &json!({"url": url, "variable": "v", "index": {"time": 1}, "bbox": [2.2, 5.2, 2.4, 7.8]})).unwrap(); assert!( - s.notices_since(mark).iter().any(|n| n.text.contains("within one cell along an axis") && n.text.contains("columns 2–4")), + s.notices_since(mark).iter().any(|n| n.text.contains("within one cell along an axis") && n.text.contains("columns 2–3 and rows")), "{:?}", s.notices_since(mark) ); @@ -55107,7 +55107,7 @@ fn a_zarr_window_reads_only_its_chunks_by_range() { let mark = s.notice_mark(); s.run("layer.addZarr", &json!({"url": url, "variable": "v", "bbox": [-20.0, 5.2, 4.8, 7.8]})).unwrap(); assert!( - s.notices_since(mark).iter().any(|n| n.text.contains("the bbox reaches past the grid: only columns 0–5")), + s.notices_since(mark).iter().any(|n| n.text.contains("the bbox reaches past the grid: only columns 0–4 and rows")), "{:?}", s.notices_since(mark) ); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3e383aadd9..61693b4d0f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5184,7 +5184,7 @@ impl RustGisApp { dbf_notes.extend(io::dates_as_text_note(&ds.fields, &name)); dbf_notes.extend(rustgis_engine::cmd::share::gpkg_dates_note(&ds, &ext, &name)); if lost.rows > 0 { - dbf_notes.push(format!("{name}: {} rows couldn't be read and were left out", lost.rows)); + dbf_notes.push(rustgis_engine::cmd::whole::unread_notice(&name, lost.rows)); } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); // CSV holds a point a row, GPX a name for each feature and no areas; reading text back trims it or reads blanks as null. diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index eea8dee4cf..de854acb04 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -629,12 +629,9 @@ fn poll_walk(app: &mut RustGisApp, ctx: &egui::Context) { } let st = &mut app.ui.stac; let n = walk.items().len().to_string(); + // Refused and skipped links have their own notices above: the stops they don't say come first. st.info = Some(if walk.complete() { i18n::fmt("Showing {n} items", &[("n", &n)]) - } else if walk.refused() > 0 { - i18n::fmt("Showing {n} items ({f} catalog links were refused)", &[("n", &n), ("f", &walk.refused().to_string())]) - } else if walk.skipped() > 0 { - i18n::fmt("Showing {n} items ({s} catalog links were skipped)", &[("n", &n), ("s", &walk.skipped().to_string())]) } else if walk.reads >= catalog::MAX_READS { i18n::fmt( "Showing {n} items (stopped after reading {r} documents: pick a catalog further down)", @@ -644,6 +641,10 @@ fn poll_walk(app: &mut RustGisApp, ctx: &egui::Context) { i18n::fmt("Showing {n} items ({f} documents couldn't be read)", &[("n", &n), ("f", &walk.failed.to_string())]) } else if walk.cut && walk.items().len() < 50 { i18n::fmt("Showing {n} items (some catalogs were too deep or too large to read: pick a catalog further down)", &[("n", &n)]) + } else if walk.refused() > 0 { + i18n::fmt("Showing {n} items ({f} catalog links were refused)", &[("n", &n), ("f", &walk.refused().to_string())]) + } else if walk.skipped() > 0 { + i18n::fmt("Showing {n} items ({s} catalog links were skipped)", &[("n", &n), ("s", &walk.skipped().to_string())]) } else { i18n::fmt("Showing {n} items (more match: narrow the search)", &[("n", &n)]) }); From a398c37f3a4cf07387e67daa308ec23353b5f555 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:29:58 -0500 Subject: [PATCH 05/11] chore(data): doc fixes and dead code from the release quality pass Doc comments for memory sources, Zarr window keys, geotiff write_all, Reproject::planetary, max_id and the authalic radius (Snyder 1987); the WFS and GML rows of the formats guide; lerc-core acknowledged. Removed Ground::water_coarse, an unreachable date arm, and STAC link wrappers that drop their counts (now test-only); the STAC date check uses rustgis_data::date::days_in_month. --- crates/data/src/date.rs | 4 ++-- crates/data/src/lib.rs | 5 +++-- crates/data/src/memory.rs | 10 ++++++---- crates/data/src/raster/wkt.rs | 4 +++- crates/data/src/raster/zarr.rs | 3 ++- crates/data/src/source/mod.rs | 4 ++-- crates/data/src/source/shp.rs | 9 +++++++-- crates/render/src/terrain.rs | 12 +++--------- crates/render/src/terrain/water.rs | 4 +++- crates/tiles/src/stac/catalog.rs | 16 +++++++--------- docs/acknowledgements.md | 2 +- docs/user-guide/analysis.md | 2 +- docs/user-guide/data-formats.md | 4 ++-- 13 files changed, 42 insertions(+), 37 deletions(-) diff --git a/crates/data/src/date.rs b/crates/data/src/date.rs index b2ad90fec8..140e56cfc9 100644 --- a/crates/data/src/date.rs +++ b/crates/data/src/date.rs @@ -328,8 +328,8 @@ fn leap(y: i64) -> bool { (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 } -/// The days in a month of the proleptic Gregorian calendar. -pub(crate) fn days_in_month(y: i64, m: i64) -> i64 { +/// The days in a month (1 to 12) of the proleptic Gregorian calendar; 31 for another month. +pub fn days_in_month(y: i64, m: i64) -> i64 { match m { 2 if leap(y) => 29, 2 => 28, diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 385a177b56..ded9bc7156 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -303,8 +303,9 @@ impl Features { } } - /// Appends a row with the id one past the largest. `max_id` stays right only because every - /// other change to `rows` goes through `DerefMut`, which clears it. + /// Appends a row with the id one past the largest. `max_id` stays right because every change + /// that removes or reorders rows clears it (`DerefMut`, `remove_row`, `retain_rows`, + /// `truncate_rows`), and the pushes keep it. fn push_with_new_id(&mut self, geometry: Option, attrs: Vec) { let max = self.max_id.unwrap_or_else(|| self.rows.iter().map(|f| f.id).max().unwrap_or(0)); let id = max.saturating_add(1); diff --git a/crates/data/src/memory.rs b/crates/data/src/memory.rs index b513a20637..e673a09856 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -2,7 +2,8 @@ //! //! On the desktop a memory limit plans for a share of the physical memory ([`SHARE`]): never below //! the fixed value it had before (its floor, still the browser's limit), never above a ceiling. A -//! container's memory limit counts, when it is lower. The memory is read once, at the first limit +//! control-group limit (a container's, or a service's such as systemd's `MemoryMax`) counts, when +//! it is lower. The memory is read once, at the first limit //! asked for; [`scaled`] takes it as an argument, so tests pass fixed amounts. Most limits plan for //! what is left once the process holds more than half the memory ([`planned`], #2431 fix 3), so //! they can be lower later in a session, never below their floors. @@ -26,7 +27,8 @@ pub fn physical() -> Option { } /// Where [`physical`]'s figure came from: `"override"` ([`OVERRIDE`]), `"container"` (a -/// container's limit, lower than the computer's memory), `"computer"`, or `"unknown"` (the browser, +/// control-group limit, a container's or a service's such as systemd's `MemoryMax`, lower than +/// the computer's memory), `"computer"`, or `"unknown"` (the browser, /// a fuzzing build, or memory that couldn't be read), so a leftover override doesn't change the /// limits unnoticed. pub fn source() -> &'static str { @@ -59,8 +61,8 @@ fn overridden(value: Option<&str>) -> Option { value?.trim().parse::().ok().filter(|m| *m > 0) } -/// The memory to plan for: the override when it is set, else physical memory, or a container's -/// limit when that is lower. +/// The memory to plan for: the override when it is set, else physical memory, or a control-group +/// limit (a container's, or a service's such as systemd's `MemoryMax`) when that is lower. #[cfg(all(not(fuzzing), not(target_arch = "wasm32")))] fn read() -> (Option, &'static str) { if let Some(m) = overridden(std::env::var(OVERRIDE).ok().as_deref()) { diff --git a/crates/data/src/raster/wkt.rs b/crates/data/src/raster/wkt.rs index 3860b1f3d7..824919dad3 100644 --- a/crates/data/src/raster/wkt.rs +++ b/crates/data/src/raster/wkt.rs @@ -2385,7 +2385,9 @@ const ELLIPSOIDS: &[(&str, &str, f64)] = &[ ("sphere", "Sphere", 0.0), ]; -/// The radius of the sphere with the area of the ellipsoid of axes `a` and `b` (PROJ's `+R_A`). +/// The radius of the sphere with the area of the ellipsoid of axes `a` and `b` (PROJ's `+R_A`): +/// `a √(q_p / 2)`, with `q_p` the authalic `q` at the pole, as in Snyder, *Map Projections: A +/// Working Manual*, USGS Professional Paper 1395 (1987), for the radius of the authalic sphere. fn authalic_radius(a: f64, b: f64) -> f64 { let e2 = 1.0 - (b / a).powi(2); let e = e2.sqrt(); diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index da6d8270d3..8d08d2bc30 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -2324,7 +2324,8 @@ fn grid_axes(store: &Store, a: &Array, chunks: &HashMap>) -> Res /// The chunk keys of `variable`'s map coordinates, for [`window_of`]: each is read whole (its /// first [`MAX_CHUNKS`] chunks, as any coordinate), so longer ones than [`MAX_COORDS`] can't place -/// a box (a window is given in cells instead). None for a grid its `spatial:transform` places. +/// a box (a window is given in cells instead). Empty for a grid its `spatial:transform` places +/// (a box is placed by arithmetic). pub fn window_keys(store: &Store, variable: &str) -> Result> { let a = store.array(variable).ok_or_else(|| bad(format!("no variable named {variable}")))?; // A grid placed by its spatial:transform places a box by arithmetic, however long its axes. diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 000ad5eb9f..b4ce4f53d4 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -835,8 +835,8 @@ pub(crate) struct Reproject { } impl Reproject { - /// For a reader that converts only EPSG codes: a coordinate system declared without one, by - /// `authority` and `code` or by a `wkt` definition, when it is another body's + /// For [`declared_reproject`]: a coordinate system declared by `authority` and `code` or by a + /// `wkt` definition, when it is another body's /// ([`crate::raster::planetary::declared`]). `None` when it isn't. /// - Its longitude/latitude are read as they are, with a note. The layer keeps the system when /// the definition gives it. diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index dfd7609580..64d2044601 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -339,7 +339,10 @@ impl FeatureSource for ShpSource { null_text, // A sampled read visits only some of the matches, so its count is of those; a late one // visits the whole layer, so its count is of the layer. - notes: boxed_off_note(boxed_off, !late && !complete, late).into_iter().chain(deleted_note(deleted, !late && !complete)).collect(), + notes: boxed_off_note(boxed_off, !late && !complete, late) + .into_iter() + .chain(deleted_note(deleted, !late && !complete)) + .collect(), not_utf8, }) } @@ -829,7 +832,9 @@ fn value(c: &Column, b: &[u8], encoding: &dyn shapefile::dbase::Encoding) -> Val Some(b'0' | b'F' | b'f' | b'N' | b'n') => Value::Bool(false), _ => Value::Null, }, - b'D' => crate::dbf::date(b).ok().flatten().map_or(Value::Null, Value::Date), + // Dates are read, and those that aren't ones counted, by `Table::values`, which never + // passes a date column here. + b'D' => Value::Null, // Memos (in a `.dbt` beside the file), date-times and binary fields aren't read. b'M' | b'T' | b'@' | b'B' | b'G' | b'P' => Value::Null, _ => { diff --git a/crates/render/src/terrain.rs b/crates/render/src/terrain.rs index 521ae15fce..b99eb8e04a 100644 --- a/crates/render/src/terrain.rs +++ b/crates/render/src/terrain.rs @@ -166,8 +166,9 @@ impl Ground { } /// How many polygons of `map`'s water layer have their shore read at wider steps than half a - /// cell of the heights a view of `camera` reads (#1915; see [`Ground::water_coarse`]), from - /// their shapes alone: nothing is read, no elevation tile asked for. 0 without water. + /// cell of the heights a view of `camera` reads, to keep a long shore's reading bounded, so + /// their level may lie a little above their lowest shore (#1915). From their shapes alone: + /// nothing is read, no elevation tile asked for. 0 without water. pub fn water_coarse_unread(map: &Map, camera: &Camera) -> usize { Ground::heights_of(map, camera).map_or(0, |g| water::coarse_shores(map, camera, &g)) } @@ -249,13 +250,6 @@ impl Ground { self.water.as_ref().map_or(0, |w| w.unlevelled) } - /// How many polygons of the terrain's water layer had their shore read at wider steps than - /// half the ground's cell, to keep a long shore's reading bounded: their level may lie a - /// little above their lowest shore (#1915). 0 without water. - pub fn water_coarse(&self) -> usize { - self.water.as_ref().map_or(0, |w| w.coarse) - } - /// How high the ground stands at `m` in a view of `cam`, in logical pixels at the centre's /// scale (what `Camera::project_raised` takes): its height over the metres a map unit spans /// there (Web Mercator stretches the ground toward the poles). 0 where nothing is known. diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 6fc3a1533e..3a2728da6a 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -59,7 +59,9 @@ pub(crate) struct Water { /// Polygons left on the ground: no height read along their shore and no level given. pub(super) unlevelled: usize, /// Polygons whose shore was read at wider steps than half a cell of the ground, to keep - /// within [`MAX_SHORE_SAMPLES`]: their lowest shore may lie between two steps. + /// within [`MAX_SHORE_SAMPLES`]: their lowest shore may lie between two steps. Read by the + /// tests: the app counts them from the shapes alone ([`coarse_shores`]). + #[cfg_attr(not(test), expect(dead_code, reason = "the tests check the budget's count"))] pub(super) coarse: usize, /// When to read it again: over elevation tiles, soon while a tile along the shores is on its /// way, after the tile cache's wait when one failed; never otherwise. diff --git a/crates/tiles/src/stac/catalog.rs b/crates/tiles/src/stac/catalog.rs index 8eb81da692..06cdb7c794 100644 --- a/crates/tiles/src/stac/catalog.rs +++ b/crates/tiles/src/stac/catalog.rs @@ -56,12 +56,15 @@ pub fn label_of(url: &str) -> String { } /// The children (`child` links) of a catalog's document fetched from `from`: web addresses only, -/// sorted by title. +/// sorted by title. For tests: it drops the counts of the links left out, which code that shows +/// a listing reports ([`parse_children_noted`]). +#[cfg(test)] pub fn parse_children(bytes: &[u8], from: &str) -> Result, String> { parse_children_from_origin(bytes, &crate::address::Origin::named(from)) } /// Like [`parse_children`], carrying the observed post-redirect [`crate::address::Origin`] and reach. +#[cfg(test)] pub fn parse_children_from_origin(bytes: &[u8], origin: &crate::address::Origin) -> Result, String> { parse_children_noted(bytes, origin).map(|listing| listing.links) } @@ -87,7 +90,8 @@ pub fn parse_children_noted(bytes: &[u8], origin: &crate::address::Origin) -> Re } /// The items (`item` links) of a catalog's or collection's document fetched from `from`: web -/// addresses only, in the order the document gives them. +/// addresses only, in the order the document gives them. For tests, as [`parse_children`]. +#[cfg(test)] pub fn parse_item_links(bytes: &[u8], from: &str) -> Result, String> { parse_item_links_noted(bytes, &crate::address::Origin::named(from)).map(|listing| listing.links) } @@ -253,13 +257,7 @@ pub fn instant(s: &str) -> Option { return None; } let (y, m, d) = (num(0, 4)?, num(5, 2)?, num(8, 2)?); - let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; - let month_days = match m { - 2 if leap => 29, - 2 => 28, - 4 | 6 | 9 | 11 => 30, - _ => 31, - }; + let month_days = rustgis_data::date::days_in_month(y, m); if !(1..=12).contains(&m) || !(1..=month_days).contains(&d) { return None; } diff --git a/docs/acknowledgements.md b/docs/acknowledgements.md index a4988a1a91..e0348082b1 100644 --- a/docs/acknowledgements.md +++ b/docs/acknowledgements.md @@ -60,7 +60,7 @@ RustGIS is written in Rust, built on these crates, among others: | [tiff](https://github.com/image-rs/image-tiff), [laz](https://crates.io/crates/laz) | GeoTIFF and LAZ | | [Apache Parquet and Arrow](https://github.com/apache/arrow-rs), [flatgeobuf](https://crates.io/crates/flatgeobuf), [rusqlite](https://github.com/rusqlite/rusqlite) ([SQLite](https://sqlite.org)), [calamine](https://crates.io/crates/calamine), [csv](https://crates.io/crates/csv), [roxmltree](https://crates.io/crates/roxmltree) | GeoParquet (Arrow writes test fixtures), FlatGeobuf, GeoPackage, spreadsheets, CSV and XML | | [postgres](https://crates.io/crates/postgres), [mysql](https://crates.io/crates/mysql), [tiberius](https://crates.io/crates/tiberius), [rustls](https://github.com/rustls/rustls) | PostgreSQL/PostGIS, MySQL/MariaDB, SQL Server and TLS | -| [miniz_oxide](https://crates.io/crates/miniz_oxide), [brotli-decompressor](https://crates.io/crates/brotli-decompressor), [ruzstd](https://crates.io/crates/ruzstd), [zstd](https://crates.io/crates/zstd), [lz4_flex](https://crates.io/crates/lz4_flex), [weezl](https://crates.io/crates/weezl), [lerc-reader](https://crates.io/crates/lerc-reader), [zip](https://crates.io/crates/zip) | Compression for rasters, Zarr chunks, map tiles, GeoParquet and plugin packages | +| [miniz_oxide](https://crates.io/crates/miniz_oxide), [brotli-decompressor](https://crates.io/crates/brotli-decompressor), [ruzstd](https://crates.io/crates/ruzstd), [zstd](https://crates.io/crates/zstd), [lz4_flex](https://crates.io/crates/lz4_flex), [weezl](https://crates.io/crates/weezl), [lerc-reader](https://crates.io/crates/lerc-reader), [lerc-core](https://crates.io/crates/lerc-core), [zip](https://crates.io/crates/zip) | Compression for rasters, Zarr chunks, map tiles, GeoParquet and plugin packages | | [wasmi](https://github.com/wasmi-labs/wasmi) | Sandboxed WebAssembly plugins | | [ureq](https://crates.io/crates/ureq), [serde](https://serde.rs) | HTTP and JSON | | [PyO3](https://pyo3.rs), [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen), [rfd](https://crates.io/crates/rfd) | The Python package, the web app and file dialogs | diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1920cb81f4..0c2e901f6e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1584,7 +1584,7 @@ cores; `gp.env` returns the threads and cores as `limits.threads` and `limits.co runs on one thread. `gp.env` also returns the memory limits on this computer (`limits`). On the desktop they follow the -computer's memory, or a memory limit set on RustGIS (a container's, or a service's such as systemd's `MemoryMax`) when it is lower: each plans for a quarter of it, never +computer's memory, or a control-group limit on Linux (a container's, or a service's such as systemd's `MemoryMax`) when it is lower: each plans for a quarter of it, never below the web app's fixed limits and never above a ceiling. `limits.memorySource` says what they follow: `computer`, `container` (such a limit, lower than the computer's memory), `override` or `unknown`. For tests, or to reproduce a smaller computer, set the environment diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 1a0bf7cf74..e13cafaa49 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said. | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | @@ -327,7 +327,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | --- | --- | --- | | WMS 1.1.1 / 1.3.0 | Named layers offered in Web Mercator or in a coordinate system RustGIS can transform (an EPSG code, CRS:84) | A layer of GetMap images (PNG when the service offers it, else JPEG): one picture of the view, or tiles; see [One picture of the view, or tiles](#one-picture-of-the-view-or-tiles) and [Services in other coordinate systems](#services-in-other-coordinate-systems) | | WMTS | Layers whose tile matrix set is Web Mercator's pyramid, or a tile matrix set in a coordinate system RustGIS can transform | A tile layer from the tile template (or KVP GetTile) | -| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000); reaching that limit produces an incomplete-read notice. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages and interrupted reads produce a notice | +| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice | | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | | WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in EPSG:4326, at most 2048 pixels on a side | From e418bae74f60174754ef1e73f3ab434f05756823 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 00:05:07 -0500 Subject: [PATCH 06/11] Address review feedback - Shapefile: read each shape with its own record, a shape that can't be read too; shapefile's pairing read no record for it and shifted every later one. Tested with and without a deleted record. - PostGIS: connection (08), operator (57) and resource (53) errors stay errors so the connection is retried; a comment says why the shown extent stays empty on failure. - Reload workspace: a lock that is there but can't be opened counts as held; the reload integration test's fake workspace now holds its owner lock, as a real one does. - Formats guide: repeated ids are counted across offset pages; GML centre-point segments are read as a vertex. --- crates/data/src/io.rs | 37 ++++++++++++++++--- crates/data/src/source/external.rs | 8 +++- crates/data/src/source/postgis.rs | 8 +++- .../integration/portable_projects/reload.rs | 3 ++ docs/user-guide/data-formats.md | 4 +- 5 files changed, 49 insertions(+), 11 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 38a7131126..b85b78dbdc 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3700,13 +3700,12 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio use shapefile::Shape; use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); - let DbfRead { reader: dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; - let shapes = match parts.shx { + let DbfRead { reader: mut dbf, fields, decimals, mut report, not_utf8, deleted } = dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; + let mut shapes = match parts.shx { Some(shx) => shapefile::ShapeReader::with_shx(Cursor::new(parts.shp), Cursor::new(shx)), None => shapefile::ShapeReader::new(Cursor::new(parts.shp)), } .map_err(fmt)?; - let mut reader = shapefile::Reader::new(shapes, dbf); let mut ds = Dataset::new(name, GeometryType::None, fields); let to_lonlat = match crs { Some(c) => { @@ -3727,12 +3726,14 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio let pt = |x: f64, y: f64| Coord::new(x, y); // Paired by position: a record marked deleted is read as any other, and left out with its shape. let (mut is_deleted, mut left_out) = (deleted_by_position(&deleted), 0); - for (k, item) in reader.iter_shapes_and_records().enumerate() { + // Each shape is read with its record, a shape that can't be read too: `shapefile`'s own pairing + // returns a shape's error before reading its record, which shifts every later record. + for (k, (shape, record)) in shapes.iter_shapes().zip(dbf.iter_records()).enumerate() { if is_deleted(k) { left_out += 1; continue; } - let Ok((shape, record)) = item else { + let (Ok(shape), Ok(record)) = (shape, record) else { report.skipped += 1; continue; }; @@ -8861,6 +8862,32 @@ mod tests { assert_eq!(report.skipped, 0); } + /// A shape that can't be read is left out with its own record, counted: the later shapes keep + /// theirs (`shapefile`'s pairing read no record for it, shifting every later one), whether or + /// not the record is also marked deleted. + #[test] + fn an_unreadable_shape_leaves_its_own_record_out() { + for deleted in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + // The first record's shape type (after the 100-byte header and 8-byte record header). + let mut shp = std::fs::read(&path).unwrap(); + shp[108..112].copy_from_slice(&99i32.to_le_bytes()); + std::fs::write(&path, &shp).unwrap(); + if deleted { + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + let at = dbf_record_at(&dbf, 0); + dbf[at] = b'*'; + std::fs::write(&dbf_path, &dbf).unwrap(); + } + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + let names: Vec<_> = ds.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(names, [Value::Text("b".into()), Value::Text("c".into())], "deleted: {deleted}"); + assert_eq!(report.skipped, usize::from(!deleted), "{:?}", report.messages); + } + } + /// A standalone table: a record marked deleted is left out and counted, and one dBASE can't /// read (a number that isn't one) is left out and said, with the rows on both sides kept. /// Clean input says neither. diff --git a/crates/data/src/source/external.rs b/crates/data/src/source/external.rs index f769a241bf..ba906bcbaf 100644 --- a/crates/data/src/source/external.rs +++ b/crates/data/src/source/external.rs @@ -48,14 +48,18 @@ impl ReloadWorkspace { /// Whether a saved conversion belongs to a disposable workspace rather than a durable cache: /// in a folder named as a workspace that holds its owner lock, marked as one. A user's cache /// folder that only has such a name (`RUSTGIS_GDAL_CACHE=/data/reload-2024`) isn't one. A lock - /// that can't be read is held by a live owner (Windows refuses reads of a locked range). + /// that is there but can't be opened or read is held by a live owner (Windows refuses reads of + /// a locked range). pub fn contains_file(path: &Path) -> bool { use std::io::Read; let Some(parent) = path.parent() else { return false }; if !parent.file_name().is_some_and(|name| name.to_string_lossy().starts_with(RELOAD_PREFIX)) { return false; } - let Ok(mut lock) = std::fs::File::open(parent.join("owner.lock")) else { return false }; + let mut lock = match std::fs::File::open(parent.join("owner.lock")) { + Ok(lock) => lock, + Err(e) => return e.kind() != std::io::ErrorKind::NotFound, + }; let mut marker = [0; RELOAD_OWNER_MARKER.len()]; match lock.read_exact(&mut marker) { Ok(()) => marker.as_slice() == RELOAD_OWNER_MARKER, diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index a6d2a17de2..f355c0f3d5 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1201,6 +1201,8 @@ impl PostgisSource { if let Some(r) = &self.reproject { return r.extent_to_lonlat(e); } + // The layer's extent is only shown: a box the server can't give, or a lost connection + // (which the next read reports), leaves it empty. self.server_transform(e, self.srid, 4326).ok().flatten().unwrap_or(Extent::EMPTY) } @@ -1228,8 +1230,10 @@ impl PostgisSource { (SELECT ST_Transform(ST_Segmentize(ST_MakeEnvelope($1, $2, $3, $4, $5), $6), $7)::box2d AS b) s", &[&e.min_x, &e.min_y, &e.max_x, &e.max_y, &from, &step, &to], ) { - // The server's own refusal (a box its projection can't take): no box there. - Err(e) if e.as_db_error().is_some() => Ok(None), + // The server's own refusal (a box its projection can't take): no box there. Not a + // connection ending (08), the server stopping it (57) or running out of resources + // (53): those stay errors, so the connection is tried again. + Err(e) if e.as_db_error().is_some_and(|d| !matches!(d.code().code().get(..2), Some("08" | "57" | "53"))) => Ok(None), r => r, } })?; diff --git a/crates/engine/tests/integration/portable_projects/reload.rs b/crates/engine/tests/integration/portable_projects/reload.rs index 941c6c8d2d..f88cb6a6ce 100644 --- a/crates/engine/tests/integration/portable_projects/reload.rs +++ b/crates/engine/tests/integration/portable_projects/reload.rs @@ -1290,6 +1290,9 @@ fn saved_conversion_cannot_borrow_another_sessions_reload_workspace_when_origina let original = f.file(if duckdb { "removed.duckdb" } else { "removed.gdb" }); let workspace = f.file("reload-another-session"); std::fs::create_dir(&workspace).unwrap(); + // Another session's workspace holds its owner lock, marked as one: a folder that only has + // such a name is a durable cache. + std::fs::write(workspace.join("owner.lock"), b"RustGIS reload workspace v1\n1\n").unwrap(); let converted = workspace.join(if duckdb { "converted.parquet" } else { "converted.fgb" }); io::write_path(&points(&["rank"], Some(8.0)), &converted).unwrap(); let handle = rustgis_engine::data::source::open_path(&converted, None).unwrap(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index e13cafaa49..5087604c7c 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said. | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said. | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | @@ -327,7 +327,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | --- | --- | --- | | WMS 1.1.1 / 1.3.0 | Named layers offered in Web Mercator or in a coordinate system RustGIS can transform (an EPSG code, CRS:84) | A layer of GetMap images (PNG when the service offers it, else JPEG): one picture of the view, or tiles; see [One picture of the view, or tiles](#one-picture-of-the-view-or-tiles) and [Services in other coordinate systems](#services-in-other-coordinate-systems) | | WMTS | Layers whose tile matrix set is Web Mercator's pyramid, or a tile matrix set in a coordinate system RustGIS can transform | A tile layer from the tile template (or KVP GetTile) | -| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice | +| WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice | | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | | WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in EPSG:4326, at most 2048 pixels on a side | From 65c1b37f7e0d070184eb81b7dadb1f37fa4e6b2e Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 00:54:20 -0500 Subject: [PATCH 07/11] Address Claude review feedback - Shapefile: shapes past the .dbf's last record, and records past the .shp's last shape, are counted and said instead of dropped quietly. - Reload workspace: the doc says a lock shorter than the marker isn't a workspace's. - connection_browse: the dropped-node notice has a singular form. --- crates/data/src/io.rs | 54 +++++++++++++++++++++- crates/data/src/source/external.rs | 2 +- crates/engine/src/cmd/connection_browse.rs | 10 ++-- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index b85b78dbdc..fda9271c97 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3727,8 +3727,19 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // Paired by position: a record marked deleted is read as any other, and left out with its shape. let (mut is_deleted, mut left_out) = (deleted_by_position(&deleted), 0); // Each shape is read with its record, a shape that can't be read too: `shapefile`'s own pairing - // returns a shape's error before reading its record, which shifts every later record. - for (k, (shape, record)) in shapes.iter_shapes().zip(dbf.iter_records()).enumerate() { + // returns a shape's error before reading its record, which shifts every later record. Shapes + // past the last record, and records past the last shape, are counted. + let records = dbf.header().num_records as usize; + let (mut shape_iter, mut record_iter) = (shapes.iter_shapes(), dbf.iter_records()); + let (mut pairs, mut extra_shapes) = (0usize, 0usize); + while let Some(shape) = shape_iter.next() { + let Some(record) = record_iter.next() else { + // Up to the first that can't be read: past it, the file can't be followed. + extra_shapes = 1 + shape_iter.by_ref().take_while(std::result::Result::is_ok).count(); + break; + }; + let k = pairs; + pairs += 1; if is_deleted(k) { left_out += 1; continue; @@ -3799,6 +3810,14 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } ds.drop_zm(&mut report, zm_shapes); report.messages.extend(deleted_records_note(name, left_out, true)); + if extra_shapes > 0 { + report.messages.push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out")); + } + if records > pairs && extra_shapes == 0 { + report + .messages + .push(format!("{name}: {} dBASE record(s) past the .shp's last shape have no shape and were left out", records - pairs)); + } dbf_notices(&ds, &mut report, &counts); ds.geometry_type = dominant_type(&ds); // A bad .prj must not turn a spatial layer into an attribute-only table and hide the @@ -8888,6 +8907,37 @@ mod tests { } } + /// A `.dbf` one record short leaves the last shape out, and says so; one with a record more + /// than the shapes says that. A matching pair says neither. + #[test] + fn shapes_and_records_that_dont_pair_are_said() { + let said = |r: &ReadReport| r.messages.iter().filter(|m| m.contains("past the")).cloned().collect::>(); + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + assert_eq!(ds.features.len(), 3); + assert!(said(&report).is_empty(), "{:?}", report.messages); + let dbf_path = path.with_extension("dbf"); + let clean = std::fs::read(&dbf_path).unwrap(); + for (records, want) in [ + (2u32, "pts: 1 shape(s) past the .dbf's last record have no attributes and were left out"), + (4, "pts: 1 dBASE record(s) past the .shp's last shape have no shape and were left out"), + ] { + let mut dbf = clean.clone(); + dbf[4..8].copy_from_slice(&records.to_le_bytes()); + if records == 4 { + // A fourth record, a copy of the third, before the end-of-file marker. + let (at, len) = (dbf_record_at(&dbf, 2), dbf_record_at(&dbf, 1) - dbf_record_at(&dbf, 0)); + let row = dbf[at..at + len].to_vec(); + dbf.splice(at + len..at + len, row); + } + std::fs::write(&dbf_path, &dbf).unwrap(); + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + assert_eq!(ds.features.len(), records.min(3) as usize); + assert_eq!(said(&report), [want]); + } + } + /// A standalone table: a record marked deleted is left out and counted, and one dBASE can't /// read (a number that isn't one) is left out and said, with the rows on both sides kept. /// Clean input says neither. diff --git a/crates/data/src/source/external.rs b/crates/data/src/source/external.rs index ba906bcbaf..409154417e 100644 --- a/crates/data/src/source/external.rs +++ b/crates/data/src/source/external.rs @@ -49,7 +49,7 @@ impl ReloadWorkspace { /// in a folder named as a workspace that holds its owner lock, marked as one. A user's cache /// folder that only has such a name (`RUSTGIS_GDAL_CACHE=/data/reload-2024`) isn't one. A lock /// that is there but can't be opened or read is held by a live owner (Windows refuses reads of - /// a locked range). + /// a locked range); one shorter than the marker isn't a workspace's. pub fn contains_file(path: &Path) -> bool { use std::io::Read; let Some(parent) = path.parent() else { return false }; diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 1ed557c5e7..e50b07cebc 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -777,11 +777,13 @@ fn catalogs(s: &mut Session, bytes: &[u8], origin: &address::Origin) -> Result 0 { - s.notify( - format!("{dropped} catalog links were left out because their node addresses are too long or contain control characters"), + match dropped { + 0 => {} + 1 => s.notify("1 catalog link was left out because its node address is too long or contains control characters".to_string(), false), + n => s.notify( + format!("{n} catalog links were left out because their node addresses are too long or contain control characters"), false, - ); + ), } let mut found = Found::new(children); found.truncated |= dropped > 0 || refused > 0 || omitted > 0 || skipped > 0; From ce674ef7893c8da06af904dc01a20114cc6eae22 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 01:31:09 -0500 Subject: [PATCH 08/11] Address review feedback - Shapefile without a .shx: a shape that can't be read ends the pairing, and the records after it are said, rather than paired with bytes read from inside the broken shape. Tested with and without a deleted record. - Shapes past the .dbf's last record are counted up to and including the first that can't be read, which the notice says. - Formats guide: a GML curve with only a centre-point segment is kept without geometry. --- crates/data/src/io.rs | 69 ++++++++++++++++++++++++++++++--- docs/user-guide/data-formats.md | 2 +- 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index fda9271c97..c419a13393 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3729,23 +3729,45 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // Each shape is read with its record, a shape that can't be read too: `shapefile`'s own pairing // returns a shape's error before reading its record, which shifts every later record. Shapes // past the last record, and records past the last shape, are counted. + // Without a `.shx`, a shape that can't be read leaves the reader inside it: the shapes after it + // can't be found, so the pairing stops there, and the records after it are said. let records = dbf.header().num_records as usize; + let indexed = shapes.shape_count().is_ok(); let (mut shape_iter, mut record_iter) = (shapes.iter_shapes(), dbf.iter_records()); - let (mut pairs, mut extra_shapes) = (0usize, 0usize); + let (mut pairs, mut extra_shapes, mut extra_unreadable, mut lost_track) = (0usize, 0usize, false, false); while let Some(shape) = shape_iter.next() { let Some(record) = record_iter.next() else { - // Up to the first that can't be read: past it, the file can't be followed. - extra_shapes = 1 + shape_iter.by_ref().take_while(std::result::Result::is_ok).count(); + // Counted up to the first that can't be read (counted too): past it, the file can't + // be followed. + extra_shapes = 1; + if shape.is_ok() { + for s in shape_iter.by_ref() { + extra_shapes += 1; + if s.is_err() { + extra_unreadable = true; + break; + } + } + } else { + extra_unreadable = true; + } break; }; let k = pairs; pairs += 1; + lost_track = shape.is_err() && !indexed; if is_deleted(k) { left_out += 1; + if lost_track { + break; + } continue; } let (Ok(shape), Ok(record)) = (shape, record) else { report.skipped += 1; + if lost_track { + break; + } continue; }; zm_shapes += usize::from(!matches!( @@ -3811,9 +3833,17 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio ds.drop_zm(&mut report, zm_shapes); report.messages.extend(deleted_records_note(name, left_out, true)); if extra_shapes > 0 { - report.messages.push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out")); + let unreadable = if extra_unreadable { " (the last of them can't be read, and the .shp isn't followed past it)" } else { "" }; + report + .messages + .push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out{unreadable}")); } - if records > pairs && extra_shapes == 0 { + if lost_track { + report.messages.push(format!( + "{name}: shape {pairs} can't be read and the Shapefile has no .shx to find the next one by: the {} record(s) after it were left out", + records.saturating_sub(pairs) + )); + } else if records > pairs && extra_shapes == 0 { report .messages .push(format!("{name}: {} dBASE record(s) past the .shp's last shape have no shape and were left out", records - pairs)); @@ -8907,6 +8937,35 @@ mod tests { } } + /// Without a `.shx`, a shape that can't be read ends the pairing: the shapes after it can't be + /// found, so the records after it are left out and said rather than paired with what is read + /// from inside the broken shape. + #[test] + fn without_an_shx_an_unreadable_shape_ends_the_pairing() { + for deleted in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + std::fs::remove_file(path.with_extension("shx")).unwrap(); + let mut shp = std::fs::read(&path).unwrap(); + shp[108..112].copy_from_slice(&99i32.to_le_bytes()); + std::fs::write(&path, &shp).unwrap(); + if deleted { + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + let at = dbf_record_at(&dbf, 0); + dbf[at] = b'*'; + std::fs::write(&dbf_path, &dbf).unwrap(); + } + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + assert!(ds.features.is_empty(), "deleted: {deleted}"); + assert!( + report.messages.iter().any(|m| m.contains("no .shx to find the next one by: the 2 record(s) after it were left out")), + "{:?}", + report.messages + ); + } + } + /// A `.dbf` one record short leaves the last shape out, and says so; one with a record more /// than the shapes says that. A matching pair says neither. #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 5087604c7c..7a2cff9d5d 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said. | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | From 87af80e29eb3e14b838c017befe8259fc3be2160 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 01:44:27 -0500 Subject: [PATCH 09/11] Address Claude review feedback - PostGIS: only a projection's internal error (XX000) or a data exception (22) means the box has no transform; permissions and other errors stay errors. - Shapefile: with a .shx, every shape past the .dbf's last record is counted, those that can't be read too; only without one does the count stop at the first unreadable shape. --- crates/data/src/io.rs | 52 ++++++++++++++++++++++++------- crates/data/src/source/postgis.rs | 8 ++--- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2353ba8609..4d5ba7348f 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3776,23 +3776,27 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // can't be found, so the pairing stops there, and the records after it are said. let records = dbf.header().num_records as usize; let indexed = shapes.shape_count().is_ok(); + let mut lost_extra = false; let (mut shape_iter, mut record_iter) = (shapes.iter_shapes(), dbf.iter_records()); - let (mut pairs, mut extra_shapes, mut extra_unreadable, mut lost_track) = (0usize, 0usize, false, false); + let (mut pairs, mut extra_shapes, mut extra_unreadable, mut lost_track) = (0usize, 0usize, 0usize, false); while let Some(shape) = shape_iter.next() { let Some(record) = record_iter.next() else { - // Counted up to the first that can't be read (counted too): past it, the file can't - // be followed. - extra_shapes = 1; - if shape.is_ok() { - for s in shape_iter.by_ref() { - extra_shapes += 1; - if s.is_err() { - extra_unreadable = true; + // Counted, those that can't be read too; without a `.shx` up to the first of those, + // past which the file can't be followed. + let mut shape = shape; + loop { + extra_shapes += 1; + if shape.is_err() { + extra_unreadable += 1; + if !indexed { + lost_extra = true; break; } } - } else { - extra_unreadable = true; + match shape_iter.next() { + Some(next) => shape = next, + None => break, + } } break; }; @@ -3876,7 +3880,11 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio ds.drop_zm(&mut report, zm_shapes); report.messages.extend(deleted_records_note(name, left_out, true)); if extra_shapes > 0 { - let unreadable = if extra_unreadable { " (the last of them can't be read, and the .shp isn't followed past it)" } else { "" }; + let unreadable = match (extra_unreadable, lost_extra) { + (0, _) => String::new(), + (_, true) => " (the last of them can't be read, and without a .shx the .shp isn't followed past it)".to_string(), + (n, false) => format!(" ({n} of them can't be read)"), + }; report .messages .push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out{unreadable}")); @@ -9047,6 +9055,26 @@ mod tests { } } + /// With a `.shx`, the shapes past the `.dbf`'s last record are all counted, those that can't + /// be read too. + #[test] + fn shapes_past_the_last_record_are_all_counted_with_an_shx() { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + dbf[4..8].copy_from_slice(&1u32.to_le_bytes()); + std::fs::write(&dbf_path, &dbf).unwrap(); + // The second shape's type: each point record is 8 + 20 bytes. + let mut shp = std::fs::read(&path).unwrap(); + shp[136..140].copy_from_slice(&99i32.to_le_bytes()); + std::fs::write(&path, &shp).unwrap(); + let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); + assert_eq!(ds.features.len(), 1); + let want = "pts: 2 shape(s) past the .dbf's last record have no attributes and were left out (1 of them can't be read)"; + assert!(report.messages.iter().any(|m| m == want), "{:?}", report.messages); + } + /// Without a `.shx`, a shape that can't be read ends the pairing: the shapes after it can't be /// found, so the records after it are left out and said rather than paired with what is read /// from inside the broken shape. diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index f355c0f3d5..273c38ef64 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1230,10 +1230,10 @@ impl PostgisSource { (SELECT ST_Transform(ST_Segmentize(ST_MakeEnvelope($1, $2, $3, $4, $5), $6), $7)::box2d AS b) s", &[&e.min_x, &e.min_y, &e.max_x, &e.max_y, &from, &step, &to], ) { - // The server's own refusal (a box its projection can't take): no box there. Not a - // connection ending (08), the server stopping it (57) or running out of resources - // (53): those stay errors, so the connection is tried again. - Err(e) if e.as_db_error().is_some_and(|d| !matches!(d.code().code().get(..2), Some("08" | "57" | "53"))) => Ok(None), + // The server's own refusal of the box: PostGIS raises a projection's failure as an + // internal error (XX000), and a value out of range is a data exception (22). + // Anything else (permissions, a lost connection) stays an error. + Err(e) if e.as_db_error().is_some_and(|d| matches!(d.code().code().get(..2), Some("XX" | "22"))) => Ok(None), r => r, } })?; From 213d6632d5c0c92186a915f701b86aecbe07fb07 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 02:06:48 -0500 Subject: [PATCH 10/11] Address Claude review feedback - Shapefile without a .shx: an unreadable last shape no longer says that 0 records after it were left out; tested. --- crates/data/src/io.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 4d5ba7348f..e5d12bd832 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3889,12 +3889,12 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio .messages .push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out{unreadable}")); } - if lost_track { + if lost_track && records > pairs { report.messages.push(format!( "{name}: shape {pairs} can't be read and the Shapefile has no .shx to find the next one by: the {} record(s) after it were left out", records.saturating_sub(pairs) )); - } else if records > pairs && extra_shapes == 0 { + } else if records > pairs && extra_shapes == 0 && !lost_track { report .messages .push(format!("{name}: {} dBASE record(s) past the .shp's last shape have no shape and were left out", records - pairs)); @@ -9096,6 +9096,18 @@ mod tests { } let (ds, report) = read_shapefile_in(&path, "pts", None).unwrap(); assert!(ds.features.is_empty(), "deleted: {deleted}"); + let last = { + let dir = tempfile::tempdir().unwrap(); + let path = three_named_points(dir.path()); + std::fs::remove_file(path.with_extension("shx")).unwrap(); + let mut shp = std::fs::read(&path).unwrap(); + // The third shape's type: each point record is 8 + 20 bytes. + shp[164..168].copy_from_slice(&99i32.to_le_bytes()); + std::fs::write(&path, &shp).unwrap(); + read_shapefile_in(&path, "pts", None).unwrap() + }; + assert_eq!((last.0.features.len(), last.1.skipped), (2, 1)); + assert!(last.1.messages.iter().all(|m| !m.contains("no .shx") && !m.contains("past the")), "{:?}", last.1.messages); assert!( report.messages.iter().any(|m| m.contains("no .shx to find the next one by: the 2 record(s) after it were left out")), "{:?}", From 6598895a09a2a6059f71dc9de140f0d856e562da Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 02:31:02 -0500 Subject: [PATCH 11/11] Address Claude review feedback - Shapefile: counting the shapes past the .dbf's last record looks at Cancel between shapes. --- crates/data/src/io.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e5d12bd832..9c140bc1fc 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3785,6 +3785,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // past which the file can't be followed. let mut shape = shape; loop { + crate::progress::check()?; extra_shapes += 1; if shape.is_err() { extra_unreadable += 1;