Skip to content
2 changes: 2 additions & 0 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,8 @@ fn mcp(s: &mut Session, args: &[String]) -> Result<(), String> {

/// Runs the command line, then stops the session plugins' programs its commands started.
fn main() -> ExitCode {
// A bug caught in a command says so, with a reference to its details.
rustgis_engine::data::incident::install();
let code = cli();
// Session plugins' programs a command started end with the command line.
rustgis_engine::plugins::session::stop_all();
Expand Down
230 changes: 208 additions & 22 deletions apps/rustgis/src/main.rs

Large diffs are not rendered by default.

12 changes: 10 additions & 2 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,11 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result<ToolResult,
with_pole_loop_notes(result, spec, inputs, &p)
})
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.name)))
.unwrap_or_else(|payload| {
// A bug in a tool, said as one, with a reference to its details.
let incident = rustgis_data::incident::caught(payload.as_ref());
Err(rustgis_data::incident::message(spec.name, false, &incident.id))
})
}

/// `work` in the plane of the system `inputs` are given in ([`Inputs::work_crs`]): the analysis
Expand Down Expand Up @@ -1013,7 +1017,11 @@ pub fn run_resolved(
with_pole_loop_notes(result, tool.spec, inputs, &params)
})
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", tool.spec.name)))
.unwrap_or_else(|payload| {
// A bug in a tool, said as one, with a reference to its details.
let incident = rustgis_data::incident::caught(payload.as_ref());
Err(rustgis_data::incident::message(tool.spec.name, false, &incident.id))
})
})
}

Expand Down
4 changes: 2 additions & 2 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11853,7 +11853,7 @@ mod tests {
ds.push(Some(Geometry::Line(vec![off.to_vec()])), vec![]);
let m = Map(HashMap::from([("f".to_string(), ds)]));
let r = crate::run("buffer", &m, &serde_json::json!({"input": "f", "distance": 1}));
assert!(!matches!(&r, Err(e) if e.ends_with("failed unexpectedly")), "{:?}", r.err());
assert!(!matches!(&r, Err(e) if e.contains("failed unexpectedly")), "{:?}", r.err());
}

/// Buffers are geodesic (#394): Web Mercator's scale changes with latitude, so one scale for
Expand Down Expand Up @@ -13393,7 +13393,7 @@ mod tests {
for p in &junk {
// A panic is caught and becomes this error, which would pass unnoticed.
let r = crate::run(t.id, &m, p);
assert!(!matches!(&r, Err(e) if e.ends_with("failed unexpectedly")), "{} panicked on {p}", t.id);
assert!(!matches!(&r, Err(e) if e.contains("failed unexpectedly")), "{} panicked on {p}", t.id);
}
}
}
Expand Down
25 changes: 21 additions & 4 deletions crates/data/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ pub fn set_clock(clock: fn() -> u64) {
*lock(&CLOCK) = Some(clock);
}

/// Milliseconds since 1970 by the application's clock ([`set_clock`]).
pub(crate) fn now_ms() -> u64 {
timestamp_ms()
}

fn timestamp_ms() -> u64 {
let clock = *lock(&CLOCK);
if let Some(clock) = clock {
Expand Down Expand Up @@ -247,7 +252,7 @@ impl History {
message: &Redacted,
loss: Option<crate::loss::LossCode>,
run: Option<Run>,
) {
) -> u64 {
self.retain(Record {
id: 0,
timestamp_ms: timestamp_ms(),
Expand All @@ -258,11 +263,12 @@ impl History {
network: None,
loss,
run,
});
})
}

fn retain(&self, record: Record) {
store(&mut lock(&self.0), record);
/// Keeps `record`, and gives the id it was kept under.
fn retain(&self, record: Record) -> u64 {
store(&mut lock(&self.0), record)
}

/// Records the state the run `id` left the project in ([`Run::after`]) on the messages it said,
Expand All @@ -280,6 +286,17 @@ impl History {
}
}

/// Adds `details` (redacted and bounded) to the record kept as `id`, if it still is: what a
/// bug's failure keeps for a report ([`crate::incident::Incident::details`]). By id, so a record
/// another thread keeps meanwhile isn't given them.
pub fn detail(&self, id: u64, details: &str) {
let mut state = lock(&self.0);
if let Some(record) = state.records.iter_mut().rev().find(|r| r.id == id) {
record.details = bounded(&redact(details), MAX_DETAILS_BYTES);
}
state.generation = state.generation.wrapping_add(1);
}

/// Oldest first; both the count and every string in this independent snapshot are bounded.
pub fn records(&self) -> Vec<Record> {
lock(&self.0).records.iter().cloned().collect()
Expand Down
205 changes: 205 additions & 0 deletions crates/data/src/incident.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
//! A bug in RustGIS met while a command or a tool ran, caught before it could take the app down:
//! a short reference that ties the message the user sees to the details kept for a bug report
//! (the panic's message and where in the code it happened) and to the app's crash log.
//!
//! [`install`] records each panic as it happens, on whatever thread, then hands it on to the hook
//! that was there before (the desktop app's crash log). A catch site turns what it caught into an
//! [`Incident`] with [`caught`], and says [`message`]; [`find`] gives the details back by reference.

use std::collections::VecDeque;
use std::sync::{Mutex, MutexGuard, Once};

/// The incidents kept for their details: a session meets few, and a long one keeps the newest.
const KEPT: usize = 16;

/// A bug met and caught: its reference, the panic's message and where it happened.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Incident {
/// Six hexadecimal digits, as the user sees them and the crash log names them.
pub id: String,
pub message: String,
/// `file:line` in RustGIS's source, when the panic gave it.
pub location: Option<String>,
}

impl Incident {
/// The details a bug report needs, as Messages shows them under the failure.
pub fn details(&self) -> String {
let at = self.location.as_deref().map(|at| format!("\nat {at}")).unwrap_or_default();
format!("Incident {} in RustGIS {}\n{}{at}", self.id, env!("CARGO_PKG_VERSION"), self.message)
}
}

static RECENT: Mutex<VecDeque<Incident>> = Mutex::new(VecDeque::new());
static COUNT: Mutex<u64> = Mutex::new(0);
static INSTALLED: Once = Once::new();

std::thread_local! {
/// The reference of the last panic on this thread, for the catch site and the crash log.
static LAST: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// A reference no incident kept has: the time and a count, mixed, as six hexadecimal digits.
fn new_id() -> String {
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
loop {
let id = mixed_id();
if find(&id).is_none() {
return id;
}
}
}

/// A reference from the time and a count, mixed, as six hexadecimal digits.
fn mixed_id() -> String {
let n = {
let mut count = lock(&COUNT);
*count = count.wrapping_add(1);
*count
};
let mixed = crate::diagnostics::now_ms().wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(n.wrapping_mul(0xBF58_476D_1CE4_E5B9));
format!("{:06X}", (mixed >> 40) & 0xFF_FFFF)
}

/// Keeps `incident` for its details, the oldest let go past [`KEPT`].
fn keep(incident: Incident) {
let mut recent = lock(&RECENT);
if recent.len() >= KEPT {
recent.pop_front();
}
recent.push_back(incident);
}

/// A panic's message, whole: matched whole to tell one panic from another, and scrubbed whole
/// (a login cut in two isn't recognised) before Messages bounds it for showing. A session keeps
/// [`KEPT`] at most.
fn payload_text(payload: &(dyn std::any::Any + Send)) -> String {
payload
.downcast_ref::<&str>()
.map(|s| (*s).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "a panic without a message".to_string())
}

/// Records every panic as an incident before the hook that was there runs (the app's crash log,
/// which can name it by [`last_id`]). Installing it again does nothing.
pub fn install() {
INSTALLED.call_once(|| {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let id = new_id();
let message = payload_text(info.payload());
let location = info.location().map(|l| format!("{}:{}", l.file(), l.line()));
LAST.with(|last| *last.borrow_mut() = Some(id.clone()));
keep(Incident { id, message, location });
previous(info);
}));
});
}

/// The reference of the last panic on this thread, if [`install`] recorded one.
pub fn last_id() -> Option<String> {
LAST.with(|last| last.borrow().clone())
}

/// The incident a catch site caught: the one [`install`] recorded for this panic, or, without the
/// hook, one made from what was caught. The panic is told by its message: this thread's last one
/// when it matches (a catch site that drops what it caught leaves an older one there), else the
/// newest kept with that message, as a worker's panic raised again on its caller's thread is
/// (`analysis::parallel`), so it keeps the reference the crash log gave it.
pub fn caught(payload: &(dyn std::any::Any + Send)) -> Incident {
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
let message = payload_text(payload);
let last = LAST.with(|last| last.borrow_mut().take());
let found = last
.and_then(|id| find(&id))
.filter(|found| found.message == message)
.or_else(|| lock(&RECENT).iter().rev().find(|i| i.message == message).cloned());
if let Some(found) = found {
return found;
}
let incident = Incident { id: new_id(), message, location: None };
keep(incident.clone());
incident
}

/// An incident kept by its reference.
pub fn find(id: &str) -> Option<Incident> {
lock(&RECENT).iter().rev().find(|i| i.id == id).cloned()
}

/// What a caught bug says: what failed, that it is a bug in RustGIS, its reference, and, when the
/// project was put back as it was (`restored`), that nothing it did was kept. It keeps the words
/// "failed unexpectedly", which tests and scripts look for to tell a bug from a refusal.
pub fn message(what: &str, restored: bool, id: &str) -> String {
let kept = if restored { "; the project is as it was before" } else { "" };
format!(
"{what} failed unexpectedly, a bug in RustGIS (incident {id}){kept}. The details are in Messages; please include them in a bug report"
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
)
}

/// What a bug caught while doing `what` says ([`message`]), its incident taken from the panic
/// `payload` ([`caught`]): for a catch site that rolls nothing back.
pub fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String {
let incident = caught(payload);
message(what, false, &incident.id)
}

/// The kept incident `text` names by its reference (`… (incident 7F3A2C)…`, in any language the
/// message is said in), the newest if several.
pub fn named(text: &str) -> Option<Incident> {
lock(&RECENT).iter().rev().find(|i| text.contains(&format!("{})", i.id))).cloned()
}

/// The reference a message from [`message`] names, if it names one.
pub fn named_in(text: &str) -> Option<&str> {
let (_, rest) = text.split_once("(incident ")?;
let id = rest.get(..6)?;
id.bytes().all(|b| b.is_ascii_hexdigit()).then_some(id)
}

#[cfg(test)]
mod tests {
use super::*;

fn find_by_message(message: &str) -> Option<Incident> {
lock(&RECENT).iter().rev().find(|i| i.message == message).cloned()
}

#[test]
fn a_caught_panic_is_an_incident_with_its_place_and_a_message_naming_it() {
install();
let payload = std::panic::catch_unwind(|| panic!("the bug")).unwrap_err();
let incident = caught(payload.as_ref());
assert_eq!(incident.message, "the bug");
assert!(incident.location.as_deref().is_some_and(|at| at.contains("incident.rs")), "{incident:?}");
assert_eq!(find(&incident.id).as_ref(), Some(&incident));
let said = message("Buffer", true, &incident.id);
assert!(said.contains("failed unexpectedly"), "the words tests look for: {said}");
assert!(said.starts_with("Buffer failed unexpectedly, a bug in RustGIS (incident "), "{said}");
assert!(said.contains("the project is as it was before"), "{said}");
assert_eq!(named_in(&said), Some(incident.id.as_str()));
assert!(incident.details().contains("the bug") && incident.details().contains(&incident.id));
// Caught once: the next catch on this thread doesn't take it again.
assert_eq!(last_id(), None);
// Raised on another thread and caught here (a worker's, raised again on its caller), it
// keeps its reference.
let worker = std::thread::scope(|s| {
std::thread::Builder::new()
.spawn_scoped(s, || std::panic::catch_unwind(|| panic!("the worker's bug")).unwrap_err())
.unwrap()
.join()
})
.unwrap();
let on_worker = find_by_message("the worker's bug");
assert_eq!(Some(caught(worker.as_ref()).id), on_worker.map(|i| i.id));
// A stale reference from an earlier panic, its payload dropped, isn't given to another.
let _ = std::panic::catch_unwind(|| panic!("dropped"));
let other = caught(&"a different payload");
assert_eq!(other.message, "a different payload");
assert_eq!(other.location, None);
assert_eq!(named_in("Buffer failed: no layer"), None);
}
}
42 changes: 41 additions & 1 deletion crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub mod gml;
pub mod gpx;
#[cfg(not(target_arch = "wasm32"))]
pub mod http;
pub mod incident;
pub mod interop;
pub mod io;
pub mod kml;
Expand Down Expand Up @@ -90,7 +91,9 @@ pub fn no_programs_here() -> &'static str {

#[derive(Debug, thiserror::Error)]
pub enum DataError {
#[error("i/o: {0}")]
/// A failure of the computer rather than the data (a full disk, a read-only folder, no
/// permission, no memory) says so, and what to do, before the system's own words.
#[error("{}", io_text(.0))]
Io(#[source] std::io::Error),
#[error("{0}")]
Format(String),
Expand Down Expand Up @@ -118,6 +121,24 @@ impl DataError {
}
}

/// An I/O error in words: what the computer ran into and what to do, for a failure of the computer
/// rather than the data, then the system's own words; `i/o: …` for any other.
pub fn io_text(e: &std::io::Error) -> String {
use std::io::ErrorKind as K;
let plain = match e.kind() {
K::StorageFull => "the disk is full: free some space, or save somewhere else",
K::QuotaExceeded => "the storage quota on this disk is used up: free some space, or save somewhere else",
K::FileTooLarge => "the file is larger than this disk or system allows: save it in pieces, or to a disk that holds larger files",
K::ReadOnlyFilesystem => "the disk or folder is read-only: save somewhere else",
K::PermissionDenied => "RustGIS isn't allowed to use this file or folder: check its permissions, or choose another",
K::OutOfMemory => {
"the computer ran out of memory: close other programs, or work on a smaller part of the data, such as by filtering or clipping it first"
}
_ => return format!("i/o: {e}"),
};
format!("{plain} ({e})")
}

/// An I/O error, or [`DataError::Cancelled`] when it carries one: a write that only returns I/O
/// errors stops with it for a cancelled run ([`progress`]).
impl From<std::io::Error> for DataError {
Expand Down Expand Up @@ -168,6 +189,25 @@ impl DataError {
#[cfg(test)]
mod unplaced_out_tests;

#[cfg(test)]
mod io_text_tests {
use super::*;

#[test]
fn a_failure_of_the_computer_says_what_to_do_and_keeps_the_systems_words() {
use std::io::{Error, ErrorKind as K};
let full = DataError::Io(Error::from(K::StorageFull)).to_string();
assert!(full.starts_with("the disk is full: free some space, or save somewhere else ("), "{full}");
assert!(full.ends_with(&format!("{})", Error::from(K::StorageFull))), "{full}");
for kind in [K::QuotaExceeded, K::FileTooLarge, K::ReadOnlyFilesystem, K::PermissionDenied, K::OutOfMemory] {
let said = DataError::Io(Error::from(kind)).to_string();
assert!(!said.starts_with("i/o:") && said.contains(':'), "{kind:?}: {said}");
}
// Any other failure is said as before.
assert_eq!(DataError::Io(Error::other("unchanged")).to_string(), "i/o: unchanged");
}
}

#[cfg(test)]
mod secret_redaction_tests {
use super::*;
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1271,7 +1271,8 @@ fn test(s: &mut Session, p: &Value) -> CmdResult {
let c = tested(s, p)?;
// An unsaved web service reads anonymously, whatever saved connection shares its origin.
let anonymous = web::is_service(&c) && c.id.is_empty();
web::anonymously(s, anonymous, |s| test_connection(s, p, c)).unwrap_or_else(|_| Err("connection.test failed unexpectedly".into()))
web::anonymously(s, anonymous, |s| test_connection(s, p, c))
.unwrap_or_else(|payload| Err(crate::bug("Test Connection", payload.as_ref())))
}

fn test_connection(s: &mut Session, p: &Value, c: Connection) -> CmdResult {
Expand Down
Loading
Loading