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

            
8
use std::fmt::Display;
9

            
10
use finance::error::{BalanceError, FinanceError, ReportError};
11
use scripting::runtime::{EvalValue, HostCondition};
12
use server::command::CmdError;
13
use server::config::ConfigError;
14
use server::error::{ServerError, root_message};
15

            
16
use crate::envelope::ErrorCode;
17
use crate::natives::forms::args_error;
18
use crate::status::{UNPROCESSABLE, cmd_status};
19
use thiserror::Error;
20

            
21
#[derive(Debug, Error)]
22
#[error("{context}: {command}")]
23
pub 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`].
32
5436
pub(crate) fn cmd_failure(context: impl Display, err: CmdError) -> wasmtime::Error {
33
5436
    if let Some(busy) = err.busy() {
34
169
        return busy_condition(busy.to_string());
35
5267
    }
36
5267
    if err.is_unavailable() {
37
2580
        return unavailable_condition(root_message(&err));
38
2687
    }
39
2687
    if is_missing_price(&err) {
40
347
        return no_conversion_condition(root_message(&err));
41
2340
    }
42
2340
    if let CmdError::Args(message) = &err {
43
175
        return args_error(message.clone());
44
2165
    }
45
2165
    if let Some(message) = rule_violation(&err) {
46
14
        return args_error(message);
47
2151
    }
48
2151
    if err.is_missing_row() {
49
165
        return not_found_condition(format!("{context}: not found"), Some(context.to_string()));
50
1986
    }
51
1986
    if matches!(err, CmdError::NotFound(_)) {
52
1784
        return not_found_condition(err.to_string(), Some(context.to_string()));
53
202
    }
54
202
    wasmtime::Error::new(CommandFailure {
55
202
        context: context.to_string(),
56
202
        command: err,
57
202
    })
58
5436
}
59

            
60
/// No price links two commodities: a conversion the script cannot fix by changing its call.
61
5372
pub(crate) fn is_missing_price(err: &CmdError) -> bool {
62
5372
    match err {
63
332
        CmdError::NoPrice { .. } => true,
64
376
        CmdError::Finance(err) | CmdError::Server(ServerError::Finance(err)) => matches!(
65
376
            err,
66
            FinanceError::Balance(BalanceError::MissingConversion { .. })
67
                | FinanceError::Report(ReportError::MissingConversion { .. })
68
        ),
69
4664
        _ => false,
70
    }
71
5372
}
72

            
73
/// A domain rule the caller broke: the user-fixable (422) failures other than a missing price,
74
/// with the command's message.
75
4192
pub(crate) fn rule_violation(err: &CmdError) -> Option<String> {
76
4192
    if is_infrastructure(err) || is_missing_price(err) {
77
1526
        return None;
78
2666
    }
79
2666
    if cmd_status(err) != UNPROCESSABLE {
80
1816
        return None;
81
850
    }
82
850
    Some(root_message(err))
83
4192
}
84

            
85
4210
pub(crate) fn is_infrastructure(err: &CmdError) -> bool {
86
4210
    match err {
87
193
        CmdError::DB(_) | CmdError::Script(_) => true,
88
1658
        CmdError::Server(err) => server_is_infrastructure(err),
89
11
        CmdError::Config(err) => !matches!(err, ConfigError::NoConfig(_)),
90
349
        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
1999
        | CmdError::Disabled => false,
98
    }
99
4210
}
100

            
101
1658
fn server_is_infrastructure(err: &ServerError) -> bool {
102
1658
    match err {
103
333
        ServerError::Creation | ServerError::TagClash { .. } => false,
104
10
        ServerError::Finance(err) => finance_is_infrastructure(err),
105
1315
        _ => true,
106
    }
107
1658
}
108

            
109
359
fn finance_is_infrastructure(err: &FinanceError) -> bool {
110
359
    matches!(err, FinanceError::DB(_) | FinanceError::Internal(_))
111
359
}
112

            
113
/// The `busy` condition: a write met concurrent ones on every attempt.
114
172
pub fn busy_condition(message: impl Into<String>) -> wasmtime::Error {
115
172
    wasmtime::Error::new(HostCondition {
116
172
        code: ErrorCode::BUSY.to_string(),
117
172
        message: message.into(),
118
172
        detail: None,
119
172
    })
120
172
}
121

            
122
/// The `unavailable` condition: the database cannot be reached right now.
123
2742
pub fn unavailable_condition(message: impl Into<String>) -> wasmtime::Error {
124
2742
    wasmtime::Error::new(HostCondition {
125
2742
        code: ErrorCode::UNAVAILABLE.to_string(),
126
2742
        message: message.into(),
127
2742
        detail: None,
128
2742
    })
129
2742
}
130

            
131
347
fn no_conversion_condition(message: String) -> wasmtime::Error {
132
347
    wasmtime::Error::new(HostCondition {
133
347
        code: ErrorCode::NO_CONVERSION.to_string(),
134
347
        message,
135
347
        detail: None,
136
347
    })
137
347
}
138

            
139
/// The `not-found` condition: the named entity does not exist; `detail` names the native.
140
2437
pub fn not_found_condition(message: impl Into<String>, detail: Option<String>) -> wasmtime::Error {
141
2437
    wasmtime::Error::new(HostCondition {
142
2437
        code: ErrorCode::NOT_FOUND.to_string(),
143
2437
        message: message.into(),
144
2437
        detail: detail.map(EvalValue::String),
145
2437
    })
146
2437
}
147

            
148
5456
fn first_condition(err: &wasmtime::Error) -> Option<&HostCondition> {
149
5456
    err.chain()
150
5456
        .find_map(|cause| cause.downcast_ref::<HostCondition>())
151
5456
}
152

            
153
/// The code of the first host condition in `err`'s causes.
154
4289
pub fn condition_code(err: &wasmtime::Error) -> Option<&str> {
155
4289
    first_condition(err).map(|condition| condition.code.as_str())
156
4289
}
157

            
158
/// The message of the first host condition in `err`'s causes.
159
1167
pub fn condition_text(err: &wasmtime::Error) -> Option<String> {
160
1167
    first_condition(err).map(|condition| condition.message.clone())
161
1167
}
162

            
163
/// The command error of the first [`CommandFailure`] in `err`'s causes.
164
24694
pub(crate) fn command_source(err: &wasmtime::Error) -> Option<&CmdError> {
165
24694
    err.chain()
166
48660
        .find_map(|cause| cause.downcast_ref::<CommandFailure>())
167
199
        .map(|failure| &failure.command)
168
24694
}
169

            
170
/// True when `err` or any of its causes is a [`CommandFailure`].
171
11919
pub fn is_host_failure(err: &wasmtime::Error) -> bool {
172
11919
    command_source(err).is_some_and(is_infrastructure)
173
11919
}
174

            
175
#[cfg(test)]
176
#[path = "host_failure_tests.rs"]
177
mod tests;