Files
capri-core-rust/crates/capri-computer/src/error.rs
T

92 lines
3.1 KiB
Rust

//! Native failure taxonomy: plain failures, and preflight refusals carrying a
//! `COMPUTER_*` code with `inputPerformed:false`.
use serde_json::{json, Value};
#[derive(Debug, Clone, PartialEq)]
pub struct Fail {
pub message: String,
pub code: Option<&'static str>,
/// `Some(false)` = refused before any input (may be replanned).
pub input_performed: Option<bool>,
}
pub fn fail(message: impl Into<String>) -> Fail {
Fail { message: message.into().chars().take(320).collect(), code: None, input_performed: None }
}
pub fn preflight(code: &'static str, message: impl Into<String>) -> Fail {
Fail { code: Some(code), input_performed: Some(false), ..fail(message) }
}
pub const FOREGROUND_CHANGED: &str = "COMPUTER_FOREGROUND_CHANGED";
pub const APPLICATION_UNAVAILABLE: &str = "COMPUTER_APPLICATION_UNAVAILABLE";
pub const OBSERVATION_CHANGED: &str = "COMPUTER_OBSERVATION_CHANGED";
pub const FIELD_STALE: &str = "COMPUTER_FIELD_STALE";
pub const FIELD_FOCUS_CHANGED: &str = "COMPUTER_FIELD_FOCUS_CHANGED";
pub const FULLSCREEN_TOOLBAR: &str = "COMPUTER_FULLSCREEN_TOOLBAR";
pub const TARGET_COVERED: &str = "COMPUTER_TARGET_COVERED";
pub const INPUT_BUSY: &str = "COMPUTER_INPUT_BUSY";
pub const INPUT_UNAVAILABLE: &str = "COMPUTER_INPUT_UNAVAILABLE";
pub const BROWSER_WINDOW_UNVERIFIED: &str = "COMPUTER_BROWSER_WINDOW_UNVERIFIED";
/// Codes that may be replanned when no input was sent.
pub const REPLANNABLE: [&str; 5] = [FIELD_STALE, FIELD_FOCUS_CHANGED, FULLSCREEN_TOOLBAR, TARGET_COVERED, FOREGROUND_CHANGED];
impl Fail {
pub fn replannable(&self) -> bool {
self.input_performed == Some(false) && self.code.is_some_and(|c| REPLANNABLE.contains(&c))
}
pub fn to_json(&self) -> Value {
let mut v = json!({"ok": false, "error": self.message});
if let Some(code) = self.code {
v["errorCode"] = json!(code);
}
if let Some(p) = self.input_performed {
v["inputPerformed"] = json!(p);
}
v
}
}
impl std::fmt::Display for Fail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Fail {}
impl From<anyhow::Error> for Fail {
fn from(e: anyhow::Error) -> Self {
match e.downcast::<Fail>() {
Ok(f) => f,
Err(e) => fail(e.to_string()),
}
}
}
impl From<zbus::Error> for Fail {
fn from(e: zbus::Error) -> Self {
fail(format!("The desktop refused the request: {}", e.to_string().chars().take(120).collect::<String>()))
}
}
pub type NResult<T> = Result<T, Fail>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shapes() {
let p = preflight(TARGET_COVERED, "covered");
assert!(p.replannable());
assert_eq!(p.to_json(), json!({"ok": false, "error": "covered", "errorCode": TARGET_COVERED, "inputPerformed": false}));
assert!(!preflight(INPUT_BUSY, "x").replannable());
assert!(!fail("x").replannable());
let back: Fail = anyhow::Error::new(p.clone()).into();
assert_eq!(back, p);
}
}