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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions crates/data/src/esripbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub struct Losses {
pub no_crs: bool,
/// Values that don't fit their field's type.
pub unreadable: usize,
/// Values or field names that aren't valid UTF-8.
/// Values, field names or aliases that aren't valid UTF-8.
pub not_utf8: usize,
/// Polygon rings without area.
pub flat_rings: usize,
Expand Down Expand Up @@ -156,7 +156,7 @@ impl Losses {
}
if self.not_utf8 > 0 {
out.push(format!(
"{} values or field names aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD",
"{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD",
self.not_utf8
));
}
Expand Down Expand Up @@ -276,22 +276,23 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
let (mut repeated, mut not_read, mut unknown) = (0usize, 0usize, 0usize);
let mut object_id_field = None;
for Declared { name, number, utf8, alias } in declared {
tally.not_utf8 += usize::from(!utf8);
let Some(read_as) = kind(number) else {
not_read += 1;
columns.push(None);
continue;
};
unknown += usize::from(number > LAST_FIELD_TYPE);
// Fields are found by name whatever its case, so the first of a name keeps it.
if !names.insert(name.to_lowercase()) {
repeated += 1;
columns.push(None);
continue;
}
unknown += usize::from(number > LAST_FIELD_TYPE);
Comment thread
giswqs marked this conversation as resolved.
Resolved
if number == OID && object_id_field.is_none() {
object_id_field = Some(fields.len());
}
// Only a field that's kept counts toward the UTF-8 notice: a left-out name isn't shown.
tally.not_utf8 += usize::from(!utf8);
columns.push(Some((fields.len(), read_as)));
fields.push(Field { name, ty: read_as.field_type(), alias });
}
Expand Down Expand Up @@ -726,7 +727,7 @@ struct Tally {
unreadable: usize,
/// Polygon rings without area.
flat_rings: usize,
/// Text values and field names that aren't valid UTF-8.
/// Text values, field names and aliases that aren't valid UTF-8.
not_utf8: usize,
/// Bytes left of [`MAX_GEOMETRY_BYTES`].
geometry_room: usize,
Expand Down
26 changes: 25 additions & 1 deletion crates/data/src/esripbf/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,10 @@ fn text_that_isnt_utf8_is_read_with_replacements_and_said() {
assert_eq!(ds.fields[0].name, "N\u{FFFD}AME");
assert_eq!(ds.features[0].attrs, [Value::Text("a\u{FFFD}b".into())]);
assert_eq!(ds.features[1].attrs, [Value::Text("ok".into())]);
assert_eq!(report.messages, ["2 values or field names aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"]);
assert_eq!(
report.messages,
["2 values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"]
);
}

#[test]
Expand Down Expand Up @@ -594,6 +597,27 @@ fn a_field_type_rustgis_doesnt_know_is_read_as_text_and_said() {
assert!(report.messages.is_empty(), "{:?}", report.messages);
}

#[test]
fn a_repeated_field_of_an_unknown_type_is_only_said_left_out() {
// The repeat is dropped, so it isn't also said to be read as text.
let bytes = answer(&[field("NAME", 4), field("name", 17), feature(&[text("a"), uint(5)])]);
let (ds, report) = read(&bytes, "t").unwrap();
assert_eq!(ds.fields.len(), 1);
assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]);
}

#[test]
fn a_left_out_field_whose_name_isnt_utf8_is_only_said_left_out() {
// The name isn't shown, so it isn't said to be read with replacements.
let repeat = message(13, &[message(1, b"N\xffame"), number(2, 4)].concat());
let bytes = answer(&[field("N\u{FFFD}AME", 4), repeat, feature(&[text("a"), text("b")])]);
let (_, report) = read(&bytes, "t").unwrap();
assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]);
let geometry = message(13, &[message(1, b"G\xff"), number(2, 7)].concat());
let (_, report) = read(&answer(&[field("NAME", 4), geometry, feature(&[text("a")])]), "t").unwrap();
assert_eq!(report.messages, ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"]);
}

#[test]
fn text_is_taken_from_the_room_at_its_size_once_read_before_it_is_made() {
// Each byte that isn't UTF-8 becomes U+FFFD, three bytes.
Expand Down
4 changes: 3 additions & 1 deletion crates/data/src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,9 @@ impl Geometry {
/// A point for a label or a pop-up: the point itself, the middle vertex of the longest line
/// part, or the centroid of the largest valid polygon (moved inside it if the centroid falls out).
///
/// Returns `None` if the geometry is empty or if all polygon parts contain non-finite coordinates.
/// Returns `None` if the geometry is empty (no points, no line vertices), if no polygon part
/// has only finite coordinates and a non-empty outer ring (a part with a non-finite hole is
/// left out whole), or if the chosen part's centroid isn't finite.
pub fn label_point(&self) -> Option<Coord> {
match self {
Geometry::Point(c) => Some(*c),
Expand Down
42 changes: 41 additions & 1 deletion crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2022,7 +2022,8 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Ve
let mut skipped: Vec<String> = Vec::new();
for n in shps {
if out.len() >= MAX_ZIP_LAYERS {
break;
skipped.push(format!("{n} (past the {MAX_ZIP_LAYERS}-layer limit)"));
Comment thread
giswqs marked this conversation as resolved.
Resolved
continue;
Comment thread
giswqs marked this conversation as resolved.
Resolved
}
let base = stem(&n);
let name = Path::new(&n).file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string();
Expand All @@ -2046,6 +2047,7 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Ve
let mut mifs: Vec<String> = entries.iter().flatten().filter(|(n, _)| ext_of(n) == "mif").map(|(n, _)| n.clone()).collect();
mifs.sort();
for n in mifs {
// The `.mif` files not taken stay in `entries`, so the loop below names them as past the limit.
if out.len() >= MAX_ZIP_LAYERS {
break;
}
Expand Down Expand Up @@ -2089,6 +2091,16 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Ve
Err(e) => skipped.push(format!("{n} ({e})")),
}
}
// At most this many skipped members are named; the rest are counted.
const NAMED_SKIPPED: usize = 20;
let skipped = if skipped.len() > NAMED_SKIPPED {
let more = skipped.len() - NAMED_SKIPPED;
let mut named: Vec<String> = skipped.into_iter().take(NAMED_SKIPPED).collect();
named.push(format!("and {more} more"));
named
} else {
skipped
};
if out.is_empty() {
let why = if skipped.is_empty() { String::new() } else { format!(": {}", skipped.join("; ")) };
return Err(DataError::Format(format!("{file_name}: no Shapefile or other vector data in the archive could be read{why}")));
Expand Down Expand Up @@ -3490,6 +3502,34 @@ mod tests {
}
// A .shp alone is refused with a hint to zip it.
assert!(read_bytes("x.shp", &entries[0].1).is_err());
// Shapefiles past the layer limit are named, not dropped unsaid; at the limit nothing is said.
let shapefiles = |count: usize| -> Vec<(String, Vec<u8>)> {
(0..count).flat_map(|i| entries.iter().take(4).map(move |(n, b)| (format!("s{i:02}.{}", ext(n)), b.clone()))).collect()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};
fn ext(n: &str) -> String {
n.rsplit('.').next().unwrap_or_default().to_ascii_lowercase()
}
let layers = read_zip("x.zip", &crate::zip::write(&shapefiles(MAX_ZIP_LAYERS + 2)).unwrap()).unwrap();
assert_eq!(layers.len(), MAX_ZIP_LAYERS);
assert_eq!(layers[0].1.messages, ["x.zip: skipped s32.shp (past the 32-layer limit); s33.shp (past the 32-layer limit)"]);
let layers = read_zip("x.zip", &crate::zip::write(&shapefiles(MAX_ZIP_LAYERS)).unwrap()).unwrap();
assert_eq!(layers.len(), MAX_ZIP_LAYERS);
assert!(layers.iter().all(|(_, r)| r.messages.is_empty()), "{:?}", layers[0].1.messages);
// MapInfo files past the limit are named too (by the loop over the other members, which
// they're left to), once each.
let mif = b"Version 300\nColumns 1\n id Integer\nData\nPoint 1 2\n".to_vec();
let mifs = |count: usize| -> Vec<(String, Vec<u8>)> {
(0..count).flat_map(|i| [(format!("m{i:02}.mif"), mif.clone()), (format!("m{i:02}.mid"), b"1\n".to_vec())]).collect()
};
let layers = read_zip("x.zip", &crate::zip::write(&mifs(MAX_ZIP_LAYERS + 1)).unwrap()).unwrap();
assert_eq!(layers.len(), MAX_ZIP_LAYERS);
assert_eq!(layers[0].1.messages, ["x.zip: skipped m32.mif (past the 32-layer limit)"]);
let layers = read_zip("x.zip", &crate::zip::write(&mifs(MAX_ZIP_LAYERS)).unwrap()).unwrap();
assert!(layers.iter().all(|(_, r)| r.messages.is_empty()), "{:?}", layers[0].1.messages);
// A long list of skipped members names the first ones and counts the rest.
let layers = read_zip("x.zip", &crate::zip::write(&mifs(MAX_ZIP_LAYERS + 25)).unwrap()).unwrap();
let note = &layers[0].1.messages[0];
assert!(note.contains("m51.mif") && !note.contains("m52.mif") && note.ends_with("; and 5 more"), "{note}");
}

/// A Shapefile's loose files picked or dropped together are zipped into one, which reads as a
Expand Down
8 changes: 5 additions & 3 deletions crates/data/src/ogc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,9 +462,11 @@ pub struct Service {
pub past_read_limit: Option<String>,
}

/// Most layers or collections `service.layers` lists from one document. The others are still read
/// ([`Service::listed`]), so that they can be added by name: which ones come first is up to the
/// server, and some change their order between answers (#1519).
/// Most layers or collections `service.layers` lists from one document. An OGC API collection
/// can make up to three layers (features, map tiles, vector tiles), so its listing can pass this
/// many layers. The others are still read ([`Service::listed`]), so that they can be added by
/// name: which ones come first is up to the server, and some change their order between answers
/// (#1519).
const MAX_LISTED_LAYERS: usize = 2_000;
/// Most layers or collections read from one document, which is hostile input.
const MAX_READ_LAYERS: usize = if cfg!(test) { 3_000 } else { 100_000 };
Expand Down
19 changes: 19 additions & 0 deletions crates/data/src/source/fgb/checked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ impl<R: Read> Read for Guard<R> {
let size = <[u8; 4]>::try_from(&*buf)
.map(u32::from_le_bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "an invalid feature size prefix"))?;
if size == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "a zero-size feature"));
}
let size = u64::from(size);
let remaining = self.end.map(|end| end.saturating_sub(self.pos)).unwrap_or(u64::MAX).min(super::remote::READ_BUDGET);
if size > remaining || usize::try_from(size).ok().and_then(|n| n.checked_add(4)).is_none() {
Expand Down Expand Up @@ -181,4 +184,20 @@ mod tests {
assert!(error.to_string().contains("read budget"));
assert!(guard.failure.borrow().is_some());
}

#[test]
fn a_zero_size_prefix_is_named() {
let mut guard = Guard {
input: io::Cursor::new(0u32.to_le_bytes()),
pos: 0,
end: Some(4),
start: Rc::new(Cell::new(0)),
next: None,
failure: Failure::default(),
};
let error = guard.read_exact(&mut [0; 4]).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(error.to_string(), "a zero-size feature");
assert!(guard.failure.borrow().is_some());
}
}
8 changes: 6 additions & 2 deletions crates/data/src/source/gpkg/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,16 @@ fn related(conn: &Connection, table: &str) -> Result<bool> {
}

/// The views, and triggers on other tables, whose SQL mentions `table` (by a case-blind search,
/// so a longer name containing it counts too), by name.
/// so a longer name containing it counts too), by name. Another table's own spatial index
/// triggers (`rtree_<other>_…` on `<other>`) touch only that table and its index, so they're left
/// out: replacing `parcels` doesn't name `parcels_2`'s.
fn dependents(conn: &Connection, table: &str) -> Result<Vec<String>> {
let mut st = conn
.prepare(
"SELECT name FROM sqlite_master WHERE type IN ('view', 'trigger') AND lower(tbl_name) != lower(?1)
AND instr(lower(sql), lower(?1)) > 0 ORDER BY name",
AND instr(lower(sql), lower(?1)) > 0
AND NOT (type = 'trigger' AND lower(substr(name, 1, length(tbl_name) + 7)) = 'rtree_' || lower(tbl_name) || '_')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
ORDER BY name",
)
.map_err(err)?;
let names = st.query_map([table], |r| r.get::<_, String>(0)).map_err(err)?;
Expand Down
4 changes: 2 additions & 2 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ impl SourceInfo {
self.notes.push(format!("{n} column{} {what}: {}{more}", if n == 1 { "" } else { "s" }, named.join(", ")));
}

/// The source's coordinate system, when it isn't longitude/latitude and is known by its EPSG
/// code.
/// The source's coordinate system, when it isn't longitude/latitude: one known by its EPSG
/// code or a custom one without. `None` also when `crs` isn't one RustGIS can parse.
pub fn coordinate_system(&self) -> Option<Crs> {
Crs::parse(&self.crs).ok().filter(|c| *c != Crs::LonLat)
}
Expand Down
5 changes: 3 additions & 2 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ pub struct ParquetSource {
field_cols: Vec<usize>,
/// Leaf column indices of the bbox covering's xmin, ymin, xmax, ymax.
covering: Option<[usize; 4]>,
/// The metadata declares the covering, whose null boxes then imply null geometry.
/// The metadata declares the covering, whose null boxes then mean no geometry or an empty
/// one, neither of which meets an extent.
declared_covering: bool,
reproject: Reproject,
/// The file, when it is read by its web address.
Expand Down Expand Up @@ -343,7 +344,7 @@ impl ParquetSource {

/// Whether inferred bounds may omit or count rows that only their geometry can test.
/// Unknown null counts require the same fallback as known nulls; declared coverings promise
/// that a box is present if and only if geometry is present.
/// that a box is present if and only if a non-empty geometry is present.
fn needs_geometry_filter(&self, md: &ParquetMetaData, g: usize) -> bool {
let Some(c) = self.covering else { return true };
!self.declared_covering
Expand Down
4 changes: 4 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2754,6 +2754,10 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() {
// A second table in that system reuses its entry.
let more = write_path_to(&fewer, &path, Crs::WebMercator, &to(GpkgMode::AddTable, Some("permits_2027"))).unwrap();
assert_eq!(more.1, Some(GpkgWritten { table: "permits_2027".into(), replaced: false, dependents: vec![] }));
// Its spatial index triggers mention `permits` within their own table's name, but don't use
// it, so replacing `permits` again names only the view.
let again = write_path_to(&fewer, &path, Crs::WebMercator, &to(GpkgMode::ReplaceTable, Some("permits"))).unwrap();
assert_eq!(again.1, Some(GpkgWritten { table: "permits".into(), replaced: true, dependents: vec!["recent_permits".into()] }));
// Replacing a table not there (a misspelt name) is refused rather than adding one.
let e = write_path_to(&fewer, &path, Crs::LonLat, &to(GpkgMode::ReplaceTable, Some("permit"))).unwrap_err().to_string();
assert!(e.contains("no table permit to replace"), "{e}");
Expand Down
53 changes: 46 additions & 7 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1036,12 +1036,21 @@ fn interpolate_work(s: &Session, p: &Value) -> Result<Work, String> {
let ds = feature_ds(s, p)?;
let field = ps(p, "field").ok_or("field is required")?;
let fi = ds.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?;
let pts: Vec<(Coord, f64)> = ds
.features
.iter()
.enumerate()
.filter_map(|(r, ft)| Some((ft.geometry.as_ref()?.label_point()?, ds.value(r, fi).as_f64().filter(|v| v.is_finite())?)))
.collect();
// Features without a place or a number are left out, and said (by kind, with a count).
let (mut no_point, mut no_value) = (0usize, 0usize);
let mut pts: Vec<(Coord, f64)> = Vec::with_capacity(ds.features.len());
for (r, ft) in ds.features.iter().enumerate() {
let Some(c) = ft.geometry.as_ref().and_then(|g| g.label_point()).filter(|c| c.is_finite()) else {
Comment thread
giswqs marked this conversation as resolved.
Resolved
no_point += 1;
continue;
};
let Some(v) = ds.value(r, fi).as_f64().filter(|v| v.is_finite()) else {
no_value += 1;
continue;
};
pts.push((c, v));
}
let (layer_name, field_name) = (ds.name.clone(), field.to_string());
let e = s.project.gp_env.extent.unwrap_or_else(|| {
let mut e = Extent::EMPTY;
pts.iter().for_each(|(c, _)| e.expand(*c));
Expand All @@ -1051,7 +1060,37 @@ fn interpolate_work(s: &Session, p: &Value) -> Result<Work, String> {
let name = out_name(p, format!("{}_{field}_idw", ds.name));
let power = f(p, "power").unwrap_or(2.0).clamp(0.5, 10.0);
let neighbors = p.get("neighbors").and_then(Value::as_u64).unwrap_or(12).max(1) as usize;
Ok(Box::new(move || made(rasterops::idw(&pts, &e, cell, power, neighbors, &name)?, None)))
Ok(Box::new(move || {
// A surface that can't be made says what was left out of it, so the input can be fixed.
let left_out = |e: String| {
let mut why = Vec::new();
if no_point > 0 {
why.push(format!("{no_point} features with no geometry or no usable point"));
}
if no_value > 0 {
why.push(format!("{no_value} whose value isn't a number"));
}
if why.is_empty() { e } else { format!("{e} ({} left out)", why.join(", ")) }
};
Comment thread
giswqs marked this conversation as resolved.
Resolved
let m = made(rasterops::idw(&pts, &e, cell, power, neighbors, &name).map_err(left_out)?, None)?;
if no_point == 0 && no_value == 0 {
return Ok(m);
}
let then: Then = Box::new(move |s: &mut Session, v: &mut Value| {
let mut why = Vec::new();
if no_point > 0 {
why.push(format!("{no_point} with no geometry or no usable point"));
}
if no_value > 0 {
why.push(format!("{no_value} whose {field_name} isn't a number"));
}
s.notify(format!("{layer_name}: features left out of the surface: {}", why.join(", ")), false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AGENTS.md asks for "one notice per kind with a count". This one notice covers two kinds (no place, not a number). The ESRI reader's Losses pushes one message per kind, which is the pattern to follow. Splitting it would mean changing the notify calls and the test at tests.rs ~33100, which asserts the combined text. The PR body says "one notice with a count per kind", so this may be the intended reading. Confidence: about 50%, on whether the rule means one notice per kind.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The notice lists each kind with its own count ("2 with no geometry or no finite coordinates, 1 whose depth isn't a number"), and the result's skipped object has one key per kind, so nothing is lumped together. Splitting it into two notices is a wording choice, left for the release quality pass.

if let Some(o) = v.as_object_mut() {
o.insert("skipped".into(), json!({"noPoint": no_point, "noValue": no_value}));
}
});
Ok(Made { then: Some(then), ..m })
}))
}

/// Creates a route layer and reports invalid source segments omitted from its network.
Expand Down
Loading
Loading