1
//! Why a form operation failed, and how each cause is reported.
2

            
3
use std::fmt;
4

            
5
use forms::FieldError;
6
use server::command::CmdError;
7
use thiserror::Error;
8

            
9
use crate::host_failure::{cmd_failure, rule_violation};
10
use crate::status::{cmd_status, error_status};
11

            
12
/// What a form operation addresses by id.
13
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14
pub enum Entity {
15
    Transaction,
16
    Template,
17
    Script,
18
    Account,
19
    Commodity,
20
    Tag,
21
}
22

            
23
impl Entity {
24
    /// The name opening a sentence, as the commands' not-found messages spell it.
25
2724
    fn capitalized(self) -> &'static str {
26
2724
        match self {
27
642
            Self::Transaction => "Transaction",
28
802
            Self::Template => "Template",
29
480
            Self::Script => "Script",
30
            Self::Account => "Account",
31
160
            Self::Commodity => "Commodity",
32
640
            Self::Tag => "Tag",
33
        }
34
2724
    }
35
}
36

            
37
impl fmt::Display for Entity {
38
323
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39
323
        f.write_str(match self {
40
323
            Self::Transaction => "transaction",
41
            Self::Template => "template",
42
            Self::Script => "script",
43
            Self::Account => "account",
44
            Self::Commodity => "commodity",
45
            Self::Tag => "tag",
46
        })
47
323
    }
48
}
49

            
50
#[derive(Debug, Error)]
51
pub enum Failure {
52
    #[error("{} fields invalid", .0.len())]
53
    Invalid(Vec<FieldError>),
54
    #[error("unknown form '{0}'")]
55
    UnknownForm(String),
56
    #[error("invalid {entity} id '{id}'")]
57
    MalformedId { entity: Entity, id: String },
58
    #[error("{} not found", .0.capitalized())]
59
    Missing(Entity),
60
    #[error("{0}")]
61
    Refused(String),
62
    #[error("{0}")]
63
    Internal(wasmtime::Error),
64
}
65

            
66
impl From<wasmtime::Error> for Failure {
67
323
    fn from(err: wasmtime::Error) -> Self {
68
323
        Self::Internal(err)
69
323
    }
70
}
71

            
72
impl From<FieldError> for Failure {
73
5478
    fn from(error: FieldError) -> Self {
74
5478
        Self::Invalid(vec![error])
75
5478
    }
76
}
77

            
78
impl From<Vec<FieldError>> for Failure {
79
3928
    fn from(errors: Vec<FieldError>) -> Self {
80
3928
        Self::Invalid(errors)
81
3928
    }
82
}
83

            
84
impl Failure {
85
    /// A rule violation keeps its reason (422); any other cause takes the natives' condition path.
86
2027
    pub(crate) fn from_command(context: &str, err: CmdError) -> Self {
87
2027
        match rule_violation(&err) {
88
836
            Some(reason) => Self::Refused(reason),
89
1191
            None => Self::Internal(cmd_failure(context, err)),
90
        }
91
2027
    }
92

            
93
    /// The HTTP status a web handler answers with.
94
    #[must_use]
95
6796
    pub fn http_status(&self) -> u16 {
96
6796
        match self {
97
            Self::UnknownForm(_) | Self::MalformedId { .. } => {
98
322
                cmd_status(&CmdError::Args(String::new()))
99
            }
100
2242
            Self::Missing(_) => cmd_status(&CmdError::NotFound(String::new())),
101
988
            Self::Invalid(_) | Self::Refused(_) => cmd_status(&CmdError::Refused(String::new())),
102
3244
            Self::Internal(err) => error_status(err),
103
        }
104
6796
    }
105
}