Skip to main content

rpc/
host_failure.rs

1//! Typed marker for native failures that originate in host infrastructure.
2//!
3//! A native turns a [`CmdError`] into a `wasmtime::Error`; the infrastructure
4//! variants (database, config, server) ride as a [`CommandFailure`] cause so
5//! callers can tell them from failures the script author caused, without
6//! parsing messages.
7
8use std::fmt::Display;
9
10use finance::error::{BalanceError, FinanceError, ReportError};
11use scripting::runtime::{EvalValue, HostCondition};
12use server::command::CmdError;
13use server::config::ConfigError;
14use server::error::{ServerError, root_message};
15
16use crate::envelope::ErrorCode;
17use crate::natives::forms::args_error;
18use crate::status::{UNPROCESSABLE, cmd_status};
19use thiserror::Error;
20
21#[derive(Debug, Error)]
22#[error("{context}: {command}")]
23pub struct CommandFailure {
24    context: String,
25    command: CmdError,
26}
27
28/// Converts a command failure into a native's `wasmtime::Error`: a write
29/// conflict is the `busy` condition, an unreachable database the `unavailable` one,
30/// other infrastructure failures are tagged as
31/// [`CommandFailure`].
32pub(crate) fn cmd_failure(context: impl Display, err: CmdError) -> wasmtime::Error {
33    if let Some(busy) = err.busy() {
34        return busy_condition(busy.to_string());
35    }
36    if err.is_unavailable() {
37        return unavailable_condition(root_message(&err));
38    }
39    if is_missing_price(&err) {
40        return no_conversion_condition(root_message(&err));
41    }
42    if let CmdError::Args(message) = &err {
43        return args_error(message.clone());
44    }
45    if let Some(message) = rule_violation(&err) {
46        return args_error(message);
47    }
48    if err.is_missing_row() {
49        return not_found_condition(format!("{context}: not found"), Some(context.to_string()));
50    }
51    if matches!(err, CmdError::NotFound(_)) {
52        return not_found_condition(err.to_string(), Some(context.to_string()));
53    }
54    wasmtime::Error::new(CommandFailure {
55        context: context.to_string(),
56        command: err,
57    })
58}
59
60/// No price links two commodities: a conversion the script cannot fix by changing its call.
61pub(crate) fn is_missing_price(err: &CmdError) -> bool {
62    match err {
63        CmdError::NoPrice { .. } => true,
64        CmdError::Finance(err) | CmdError::Server(ServerError::Finance(err)) => matches!(
65            err,
66            FinanceError::Balance(BalanceError::MissingConversion { .. })
67                | FinanceError::Report(ReportError::MissingConversion { .. })
68        ),
69        _ => false,
70    }
71}
72
73/// A domain rule the caller broke: the user-fixable (422) failures other than a missing price,
74/// with the command's message.
75pub(crate) fn rule_violation(err: &CmdError) -> Option<String> {
76    if is_infrastructure(err) || is_missing_price(err) {
77        return None;
78    }
79    if cmd_status(err) != UNPROCESSABLE {
80        return None;
81    }
82    Some(root_message(err))
83}
84
85pub(crate) fn is_infrastructure(err: &CmdError) -> bool {
86    match err {
87        CmdError::DB(_) | CmdError::Script(_) => true,
88        CmdError::Server(err) => server_is_infrastructure(err),
89        CmdError::Config(err) => !matches!(err, ConfigError::NoConfig(_)),
90        CmdError::Finance(err) => finance_is_infrastructure(err),
91        CmdError::Args(_)
92        | CmdError::NoPrice { .. }
93        | CmdError::NotFound(_)
94        | CmdError::Unkeepable(_)
95        | CmdError::Refused(_)
96        | CmdError::ParentGone(_)
97        | CmdError::Disabled => false,
98    }
99}
100
101fn server_is_infrastructure(err: &ServerError) -> bool {
102    match err {
103        ServerError::Creation | ServerError::TagClash { .. } => false,
104        ServerError::Finance(err) => finance_is_infrastructure(err),
105        _ => true,
106    }
107}
108
109fn finance_is_infrastructure(err: &FinanceError) -> bool {
110    matches!(err, FinanceError::DB(_) | FinanceError::Internal(_))
111}
112
113/// The `busy` condition: a write met concurrent ones on every attempt.
114pub fn busy_condition(message: impl Into<String>) -> wasmtime::Error {
115    wasmtime::Error::new(HostCondition {
116        code: ErrorCode::BUSY.to_string(),
117        message: message.into(),
118        detail: None,
119    })
120}
121
122/// The `unavailable` condition: the database cannot be reached right now.
123pub fn unavailable_condition(message: impl Into<String>) -> wasmtime::Error {
124    wasmtime::Error::new(HostCondition {
125        code: ErrorCode::UNAVAILABLE.to_string(),
126        message: message.into(),
127        detail: None,
128    })
129}
130
131fn no_conversion_condition(message: String) -> wasmtime::Error {
132    wasmtime::Error::new(HostCondition {
133        code: ErrorCode::NO_CONVERSION.to_string(),
134        message,
135        detail: None,
136    })
137}
138
139/// The `not-found` condition: the named entity does not exist; `detail` names the native.
140pub fn not_found_condition(message: impl Into<String>, detail: Option<String>) -> wasmtime::Error {
141    wasmtime::Error::new(HostCondition {
142        code: ErrorCode::NOT_FOUND.to_string(),
143        message: message.into(),
144        detail: detail.map(EvalValue::String),
145    })
146}
147
148fn first_condition(err: &wasmtime::Error) -> Option<&HostCondition> {
149    err.chain()
150        .find_map(|cause| cause.downcast_ref::<HostCondition>())
151}
152
153/// The code of the first host condition in `err`'s causes.
154pub fn condition_code(err: &wasmtime::Error) -> Option<&str> {
155    first_condition(err).map(|condition| condition.code.as_str())
156}
157
158/// The message of the first host condition in `err`'s causes.
159pub fn condition_text(err: &wasmtime::Error) -> Option<String> {
160    first_condition(err).map(|condition| condition.message.clone())
161}
162
163/// The command error of the first [`CommandFailure`] in `err`'s causes.
164pub(crate) fn command_source(err: &wasmtime::Error) -> Option<&CmdError> {
165    err.chain()
166        .find_map(|cause| cause.downcast_ref::<CommandFailure>())
167        .map(|failure| &failure.command)
168}
169
170/// True when `err` or any of its causes is a [`CommandFailure`].
171pub fn is_host_failure(err: &wasmtime::Error) -> bool {
172    command_source(err).is_some_and(is_infrastructure)
173}
174
175#[cfg(test)]
176#[path = "host_failure_tests.rs"]
177mod tests;