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
1 change: 1 addition & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod kml;
pub mod landxml;
pub mod lidar;
pub mod login_address;
pub mod loss;
pub mod mapinfo;
pub mod mbtiles;
pub mod memory;
Expand Down
57 changes: 57 additions & 0 deletions crates/data/src/loss.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! Shared classification for data-loss notices, independent of their wording.

/// What happened to the data.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LossKind {
Dropped,
Changed,
Approximated,
Assumed,
}

impl LossKind {
/// A language-independent name for this kind of loss.
pub const fn id(self) -> &'static str {
match self {
Self::Dropped => "dropped",
Self::Changed => "changed",
Self::Approximated => "approximated",
Self::Assumed => "assumed",
}
}
}

/// The specific cause of a loss. Add causes here so producers use the same code for the same loss.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LossCode {
DroppedLegend,
DroppedTime,
DroppedValue,
DroppedCalculationResult,
ChangedTruncated,
}

/// A code's identifier, effect on the data, and what the user can do about it.
pub struct LossSpec {
pub id: &'static str,
pub kind: LossKind,
pub action: &'static str,
}

impl LossCode {
/// The registry entry that supplies the untranslated identifier and remediation.
pub const fn spec(self) -> LossSpec {
use LossKind::{Changed, Dropped};
let (id, kind, action) = match self {
Self::DroppedLegend => ("dropped.legend", Dropped, "Use a service with short HTTP or HTTPS addresses for its legend pictures."),
Self::DroppedTime => ("dropped.time", Dropped, "Write to a date-time field to keep the time of day."),
Self::DroppedValue => ("dropped.value", Dropped, "Correct the value or use a destination field that can hold it."),
Self::DroppedCalculationResult => {
("dropped.calculation-result", Dropped, "Correct the expression or check the input rows named in the notice.")
}
Self::ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."),
};
LossSpec { id, kind, action }
}
}
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,8 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
// Said once the edit is kept: a rejected one changed nothing.
for (rule, field, losses, ty) in cuts {
let by = crate::notice_text::NoticeText::format("Attribute rule {rule}", [("rule", rule.into())]);
for notice in losses.notices(by, &field, ty) {
s.notify_text(notice, false);
for (code, notice) in losses.notices(by, &field, ty) {
s.notify_loss(code, notice);
}
}
Ok(())
Expand Down
66 changes: 41 additions & 25 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Edit tab: create and delete features, edit attributes and fields, of a layer or of a
//! standalone table (`"table"`).

use rustgis_data::loss::LossCode;
use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value};
use serde_json::{Value as Json, json};
use std::borrow::Cow;
Expand Down Expand Up @@ -396,22 +397,30 @@ impl Cuts {
/// The notices for what writing the whole-number or date field `field` cut, each starting with `by`
/// (the command or rule that wrote it). Empty when nothing was cut.
pub(crate) fn notices(&self, by: &str, field: &str) -> Vec<String> {

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.

Classification is applied on one path only (medium confidence, probably a follow-up): the same loss categories are still published as unclassified Info elsewhere in this file and in clipboard.rs:

  • Paste calls cuts.notices("Paste", ...) and then s.notify(..., false), so pasted truncations and date-time losses lose their code and become Info.
  • new_row and the per-cell notice (around edit.rs:282-295) report numeric truncation and "kept only its day" through notify_text as Info, with no code. Cuts::classified already has the same kinds.

The PR says this first migration covers calculations, rules and legend images, so this may be intended. If so, name the remaining paths in the PR description and link them to #2371. Otherwise, the same loss gets a different severity depending on how the user entered the value.

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 first migration covers Calculate Field, attribute rules, and service legends. Paste, new-row defaults, and direct cell edits are part of the remaining producer migration in #2371. I’ve named those paths in the PR description.

self.classified(by, field).into_iter().map(|(_, text)| text).collect()
}

/// Pairs each coercion message with its cause at the point the loss is counted.
fn classified(&self, by: &str, field: &str) -> Vec<(LossCode, String)> {
let results = |n: usize| if n == 1 { "1 result".to_string() } else { format!("{n} results") };
let mut out = Vec::new();
if self.fractions > 0 {
let their = if self.fractions == 1 { "its" } else { "their" };
out.push(format!("{by}: '{field}' holds whole numbers, so {} lost {their} fraction", results(self.fractions)));
out.push((
LossCode::ChangedTruncated,
format!("{by}: '{field}' holds whole numbers, so {} lost {their} fraction", results(self.fractions)),
));
}
if self.past > 0 {
out.push(format!("{by}: '{field}' is null for {} past the 64-bit integer range", results(self.past)));
out.push((LossCode::DroppedValue, format!("{by}: '{field}' is null for {} past the 64-bit integer range", results(self.past))));
}
if self.not_numbers > 0 {
let are = if self.not_numbers == 1 { "isn't a number" } else { "aren't numbers" };
out.push(format!("{by}: '{field}' is null for {} that {are}", results(self.not_numbers)));
out.push((LossCode::DroppedValue, format!("{by}: '{field}' is null for {} that {are}", results(self.not_numbers))));
}
if self.times > 0 {
let their = if self.times == 1 { "its" } else { "their" };
out.push(format!("{by}: '{field}' holds dates, so {} kept only {their} day", results(self.times)));
out.push((LossCode::DroppedTime, format!("{by}: '{field}' holds dates, so {} kept only {their} day", results(self.times))));
}
out
}
Expand Down Expand Up @@ -487,12 +496,15 @@ impl WriteLosses {
/// The notices for what writing `field`, of type `ty`, lost, each starting with `by` (the
/// command or rule that wrote it). Rows are numbered from 1, as `@row_number` numbers them.
/// The error notices are templates a translated interface shows in its language.
pub(crate) fn notices(&self, by: NoticeText, field: &str, ty: FieldType) -> Vec<NoticeText> {
pub(crate) fn notices(&self, by: NoticeText, field: &str, ty: FieldType) -> Vec<(LossCode, NoticeText)> {
let rows = |n: usize| if n == 1 { "1 row".to_string() } else { format!("{n} rows") };
let english = by.english();
let mut out: Vec<NoticeText> = self.cuts.notices(&english, field).into_iter().map(NoticeText::from).collect();
let mut out: Vec<_> = self.cuts.classified(&english, field).into_iter().map(|(code, text)| (code, text.into())).collect();
if self.unread > 0 {
out.push(format!("{english}: '{field}' is null in {}, whose result isn't a {} value", rows(self.unread), ty.label()).into());
out.push((
LossCode::DroppedValue,
format!("{english}: '{field}' is null in {}, whose result isn't a {} value", rows(self.unread), ty.label()).into(),
));
}
for (fault, n, listed) in &self.errors {
let numbers: Vec<String> = listed.iter().map(|r| r.saturating_add(1).to_string()).collect();
Expand All @@ -501,15 +513,18 @@ impl WriteLosses {
(_, false) => "{by}: '{field}' is null in {count} rows because of {cause} (rows {rows})",
(_, true) => "{by}: '{field}' is null in {count} rows because of {cause} (rows {rows}…)",
};
out.push(NoticeText::format(
key,
[
("by", by.clone()),
("field", field.to_string().into()),
("count", n.to_string().into()),
("cause", NoticeText::term(fault.describe())),
("rows", numbers.join(", ").into()),
],
out.push((
LossCode::DroppedCalculationResult,
NoticeText::format(
key,
[
("by", by.clone()),
("field", field.to_string().into()),
("count", n.to_string().into()),
("cause", NoticeText::term(fault.describe())),
("rows", numbers.join(", ").into()),
],
),
));
}
out
Expand Down Expand Up @@ -1416,10 +1431,7 @@ fn land_table_edit(s: &mut Session, p: &Json, command: &str) -> Option<CmdResult
let (output, answer, notices) = ahead.result?;
(table.dataset.fields, table.dataset.features) = (output.fields, output.features);
for notice in notices {
match notice.localized {
Some(text) => s.notify_text(text, notice.error),
None => s.notify(notice.text, notice.error),
}
s.relay_notice(notice);
}
Ok(answer)
})())
Expand Down Expand Up @@ -1510,8 +1522,8 @@ fn evaluate(calc: &Calculation, ds: &Dataset, rows: Vec<usize>, ty: FieldType) -
/// Says what Calculate Field's results lost in `field` ([`evaluate`]), even when a calculation
/// rule writes the field afterwards: the rule may read the cut value, and says what it cuts itself.
fn calculation_notices(s: &mut Session, field: &str, ty: FieldType, losses: &WriteLosses) {
for notice in losses.notices(NoticeText::term("Calculate Field"), field, ty) {
s.notify_text(notice, false);
for (code, notice) in losses.notices(NoticeText::term("Calculate Field"), field, ty) {
s.notify_loss(code, notice);
}
}

Expand Down Expand Up @@ -1715,8 +1727,11 @@ mod tests {
p["expression"] = json!(expression);
let mark = s.notice_mark();
s.run("edit.calculateField", &p).unwrap();
let notices: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert_eq!(notices, said, "{expression}, table {table}");
let notices = s.notices_since(mark);
assert_eq!(notices.iter().map(|n| n.text.as_str()).collect::<Vec<_>>(), said, "{expression}, table {table}");
assert!(notices.iter().all(|n| n.loss() == Some(LossCode::DroppedCalculationResult)
&& n.severity == rustgis_data::diagnostics::Severity::Warning
&& !n.error));
}
}
// The earlier calculator doesn't join a stored infinity as text either.
Expand All @@ -1733,7 +1748,8 @@ mod tests {
for row in [4, 4] {
losses.write(row, (Value::Null, Some(rustgis_data::query::Fault::DivisionByZero)), FieldType::Double);
}
let said: Vec<String> = losses.notices(NoticeText::term("Rule"), "n", FieldType::Double).iter().map(NoticeText::english).collect();
let said: Vec<String> =
losses.notices(NoticeText::term("Rule"), "n", FieldType::Double).iter().map(|(_, text)| text.english()).collect();
assert_eq!(said, ["Rule: 'n' is null in 1 row because of a division by zero (row 5)"]);
let calc = Calc::parse("'pop ' + Pop Est", &ds).unwrap();
assert_eq!(calc.eval_or_fault(&ds, 0), (Value::Null, Some(rustgis_data::query::Fault::NotANumber)));
Expand Down
20 changes: 12 additions & 8 deletions crates/engine/src/cmd/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,9 @@ const MAX_SERVICE_DOCUMENTS: usize = 32;
/// well as its document count. The 32-document count is shared by all discovery kinds;
/// this byte budget applies only to the linked dataset documents.
pub(crate) const MAX_DATASET_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
/// A notice for legend pictures a service listed that its layer cannot keep (an address too long).
const LEGENDS_LEFT_OUT_NOTICE: &str = "{n} legend picture(s) the service listed were left out: their addresses are too long";
/// A notice for legend pictures the layer cannot keep because of their addresses.
const LEGENDS_LEFT_OUT_NOTICE: &str =
"{n} legend picture(s) the service listed were left out: their addresses are too long or do not use HTTP or HTTPS";

/// 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).
Expand Down Expand Up @@ -968,10 +969,10 @@ pub(crate) fn adding_ahead(s: &mut Session, p: &Value) -> Result<Option<super::r
fn prepared_discovery(s: &mut Session, command: &str) -> Option<Result<Discovery, String>> {
super::reads::take::<DiscoveryRead>(s, command).map(|(result, notices, losses)| {
for loss in losses {
s.notify_loss(loss.template, loss.count);
s.notify_counted(loss.code, loss.template, loss.count);
}
for notice in notices {
s.notify(notice.text, notice.error);
s.relay_notice(notice);
}
result
})
Expand Down Expand Up @@ -1096,7 +1097,7 @@ fn layer_source(layer: &mut Value, source: CapabilitySource) {

/// Counts destinations, not pairs; clean discovery emits no credential-forwarding notice.
fn notify_withheld(s: &mut Session, count: u32) {
s.notify_loss(rustgis_data::ogc::QUERY_WITHHELD_NOTICE, count);
s.notify_counted(None, rustgis_data::ogc::QUERY_WITHHELD_NOTICE, count);
}

/// Adds one of a service's layers: map layers as tiles (an overlay), a style as a style, features
Expand Down Expand Up @@ -1296,11 +1297,14 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis
}
}
}
// (Those the layer wouldn't keep, an address too long, are left out, not refused,
// and counted in a notice.)
// Count pictures left out because their addresses fail the layer's checks.
let legends = rustgis_map::tiles::checked_legends(layer.legends.iter().cloned());
let offered = layer.legends.len().min(rustgis_data::ogc::MAX_LEGENDS);
s.notify_loss(LEGENDS_LEFT_OUT_NOTICE, u32::try_from(offered.saturating_sub(legends.len())).unwrap_or(u32::MAX));
s.notify_counted(
Some(rustgis_data::loss::LossCode::DroppedLegend),
LEGENDS_LEFT_OUT_NOTICE,
u32::try_from(offered.saturating_sub(legends.len())).unwrap_or(u32::MAX),
);
if !legends.is_empty() {
add["legend"] = json!(legends);
}
Expand Down
Loading
Loading