Lines
100 %
Functions
Branches
//! Typed marker for native failures that originate in host infrastructure.
//!
//! A native turns a [`CmdError`] into a `wasmtime::Error`; the infrastructure
//! variants (database, config, server) ride as a [`CommandFailure`] cause so
//! callers can tell them from failures the script author caused, without
//! parsing messages.
use std::fmt::Display;
use finance::error::{BalanceError, FinanceError, ReportError};
use scripting::runtime::{EvalValue, HostCondition};
use server::command::CmdError;
use server::config::ConfigError;
use server::error::{ServerError, root_message};
use crate::envelope::ErrorCode;
use crate::natives::forms::args_error;
use crate::status::{UNPROCESSABLE, cmd_status};
use thiserror::Error;
#[derive(Debug, Error)]
#[error("{context}: {command}")]
pub struct CommandFailure {
context: String,
command: CmdError,
}
/// Converts a command failure into a native's `wasmtime::Error`: a write
/// conflict is the `busy` condition, an unreachable database the `unavailable` one,
/// other infrastructure failures are tagged as
/// [`CommandFailure`].
pub(crate) fn cmd_failure(context: impl Display, err: CmdError) -> wasmtime::Error {
if let Some(busy) = err.busy() {
return busy_condition(busy.to_string());
if err.is_unavailable() {
return unavailable_condition(root_message(&err));
if is_missing_price(&err) {
return no_conversion_condition(root_message(&err));
if let CmdError::Args(message) = &err {
return args_error(message.clone());
if let Some(message) = rule_violation(&err) {
return args_error(message);
if err.is_missing_row() {
return not_found_condition(format!("{context}: not found"), Some(context.to_string()));
if matches!(err, CmdError::NotFound(_)) {
return not_found_condition(err.to_string(), Some(context.to_string()));
wasmtime::Error::new(CommandFailure {
context: context.to_string(),
command: err,
})
/// No price links two commodities: a conversion the script cannot fix by changing its call.
pub(crate) fn is_missing_price(err: &CmdError) -> bool {
match err {
CmdError::NoPrice { .. } => true,
CmdError::Finance(err) | CmdError::Server(ServerError::Finance(err)) => matches!(
err,
FinanceError::Balance(BalanceError::MissingConversion { .. })
| FinanceError::Report(ReportError::MissingConversion { .. })
),
_ => false,
/// A domain rule the caller broke: the user-fixable (422) failures other than a missing price,
/// with the command's message.
pub(crate) fn rule_violation(err: &CmdError) -> Option<String> {
if is_infrastructure(err) || is_missing_price(err) {
return None;
if cmd_status(err) != UNPROCESSABLE {
Some(root_message(err))
pub(crate) fn is_infrastructure(err: &CmdError) -> bool {
CmdError::DB(_) | CmdError::Script(_) => true,
CmdError::Server(err) => server_is_infrastructure(err),
CmdError::Config(err) => !matches!(err, ConfigError::NoConfig(_)),
CmdError::Finance(err) => finance_is_infrastructure(err),
CmdError::Args(_)
| CmdError::NoPrice { .. }
| CmdError::NotFound(_)
| CmdError::Unkeepable(_)
| CmdError::Refused(_)
| CmdError::ParentGone(_)
| CmdError::Disabled => false,
fn server_is_infrastructure(err: &ServerError) -> bool {
ServerError::Creation | ServerError::TagClash { .. } => false,
ServerError::Finance(err) => finance_is_infrastructure(err),
_ => true,
fn finance_is_infrastructure(err: &FinanceError) -> bool {
matches!(err, FinanceError::DB(_) | FinanceError::Internal(_))
/// The `busy` condition: a write met concurrent ones on every attempt.
pub fn busy_condition(message: impl Into<String>) -> wasmtime::Error {
wasmtime::Error::new(HostCondition {
code: ErrorCode::BUSY.to_string(),
message: message.into(),
detail: None,
/// The `unavailable` condition: the database cannot be reached right now.
pub fn unavailable_condition(message: impl Into<String>) -> wasmtime::Error {
code: ErrorCode::UNAVAILABLE.to_string(),
fn no_conversion_condition(message: String) -> wasmtime::Error {
code: ErrorCode::NO_CONVERSION.to_string(),
message,
/// The `not-found` condition: the named entity does not exist; `detail` names the native.
pub fn not_found_condition(message: impl Into<String>, detail: Option<String>) -> wasmtime::Error {
code: ErrorCode::NOT_FOUND.to_string(),
detail: detail.map(EvalValue::String),
fn first_condition(err: &wasmtime::Error) -> Option<&HostCondition> {
err.chain()
.find_map(|cause| cause.downcast_ref::<HostCondition>())
/// The code of the first host condition in `err`'s causes.
pub fn condition_code(err: &wasmtime::Error) -> Option<&str> {
first_condition(err).map(|condition| condition.code.as_str())
/// The message of the first host condition in `err`'s causes.
pub fn condition_text(err: &wasmtime::Error) -> Option<String> {
first_condition(err).map(|condition| condition.message.clone())
/// The command error of the first [`CommandFailure`] in `err`'s causes.
pub(crate) fn command_source(err: &wasmtime::Error) -> Option<&CmdError> {
.find_map(|cause| cause.downcast_ref::<CommandFailure>())
.map(|failure| &failure.command)
/// True when `err` or any of its causes is a [`CommandFailure`].
pub fn is_host_failure(err: &wasmtime::Error) -> bool {
command_source(err).is_some_and(is_infrastructure)
#[cfg(test)]
#[path = "host_failure_tests.rs"]
mod tests;