1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use crate::types;
use std::borrow::Cow;

#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
    #[error("Unauthorized: {0}")]
    Unauthorized(Cow<'static, str>),

    #[error("{0}")]
    MalformedJson(String),

    #[error("Internal Server error: {0}")]
    InternalServer(Cow<'static, str>),

    #[error("{0}")]
    Client(#[from] ClientError),

    #[error("{0}")]
    Server(#[from] ServerError),

    #[error("{0}")]
    Hub(#[from] HubError),
}

impl Error {
    pub fn http_status_code(&self) -> http::StatusCode {
        match self {
            Self::Unauthorized(_) => http::StatusCode::UNAUTHORIZED,
            Self::MalformedJson(_) => http::StatusCode::BAD_REQUEST,
            Self::InternalServer(_) => http::StatusCode::INTERNAL_SERVER_ERROR,
            _ => http::StatusCode::OK,
        }
    }

    pub fn code(&self) -> u32 {
        match self {
            // Special case. To make sure that the HTTP status is communicated
            // properly.
            Self::Unauthorized(_) => 2001,
            Self::MalformedJson(_) => 2001,
            Self::InternalServer(_) => 3000,

            Self::Client(ClientError::Generic { .. }) => 2000,
            Self::Client(ClientError::InvalidParams { .. }) => 2001,
            Self::Client(ClientError::NotEnoughInformation { .. }) => 2002,
            Self::Client(ClientError::UnknownLocation { .. }) => 2003,
            Self::Client(ClientError::UnknownToken { .. }) => 2004,

            Self::Server(ServerError::Generic { .. }) => 3000,
            Self::Server(ServerError::UnusableApi { .. }) => 3001,
            Self::Server(ServerError::UnsupportedVersion { .. }) => 3002,
            Self::Server(ServerError::IncompatibleEndpoints { .. }) => 3003,

            Self::Hub(HubError::UnknownReceiver { .. }) => 4001,
            Self::Hub(HubError::Timeout { .. }) => 4002,
            Self::Hub(HubError::Connection { .. }) => 4003,
        }
    }

    pub fn unauthorized(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Unauthorized(message.into())
    }

    pub fn json_input(err: &serde_json::Error) -> Self {
        if err.is_data() {
            Self::invalid_params(format!("malformed body: {}", err))
        } else {
            Self::MalformedJson(format!("invalid json in body: {}", err))
        }
    }

    pub fn invalid_params(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Client(ClientError::InvalidParams {
            message: message.into(),
        })
    }

    pub fn client_generic(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Client(ClientError::Generic {
            message: message.into(),
        })
    }

    pub fn internal_server(message: impl Into<Cow<'static, str>>) -> Self {
        Self::InternalServer(message.into())
    }
}

/// # 5.2. 2xxx: Client errors
/// Errors detected by the server in the message sent by a client
/// where the client did something wrong.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum ClientError {
    /// # 2000
    /// Generic client error
    #[error("{message}")]
    Generic { message: Cow<'static, str> },

    /// # 2001
    /// Invalid or missing Params
    #[error("Invalid or missing parameters: {message}")]
    InvalidParams {
        /// Comma-separated list of missing or invalid params.
        message: Cow<'static, str>,
    },

    /// # 2002
    /// Not enough information, for example:
    /// Authorization request with too little information.
    #[error("Missing information: {message}")]
    NotEnoughInformation { message: Cow<'static, str> },

    /// # 2003
    /// Unknown Location, for example:
    /// Command: START_SESSION with unknown location.
    #[error("Unknown location `{id}`")]
    UnknownLocation { id: String },

    /// # 2004
    /// Unknown Token, for example:
    /// 'real-time' authorization of an unknown Token.
    #[error("Unknown token")]
    UnknownToken,
}

/// # 5.3. 3xxx: Server errors
/// Error during processing of the OCPI payload in the server.
/// The message was syntactically correct but could not be processed by the server.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum ServerError {
    /// # 3000
    /// Generic server error
    #[error("{message}")]
    Generic { message: Cow<'static, str> },

    /// # 3001
    /// Unable to use the client’s API.
    /// For example during the credentials registration:
    /// When the initializing party requests data from the other party during the
    /// open POST call to its credentials endpoint.
    /// If one of the GETs can not be processed, the party should return this
    /// error in the POST response.
    #[error("{message}")]
    UnusableApi { message: Cow<'static, String> },

    /// # 3002
    /// Unsupported version
    #[error("Unsupported version: {0}")]
    UnsupportedVersion(types::VersionNumber),

    /// # 3003
    /// No matching endpoints or expected endpoints missing between parties.
    /// Used during the registration process if the two parties do not have any
    /// mutual modules or endpoints available, or the minimal implementation expected by
    /// the other party is not been met.
    #[error("Minimal required implementation not met")]
    IncompatibleEndpoints,
}

impl ServerError {
    pub fn unusable_api(message: impl Into<String>) -> Self {
        Self::UnusableApi {
            message: Cow::Owned(message.into()),
        }
    }
}

/// # 5.4. 4xxx: Hub errors
/// When a server encounters an error,
/// client side error (2xxx) or
/// server side error (3xxx),
/// it sends the status code to the Hub. The Hub SHALL then forward this error
/// to the client which sent the request (when the request was not a Broadcast Push).
/// For errors that a Hub encounters while routing messages,
/// the following OCPI status codes shall be used.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum HubError {
    /// # 4001
    /// Unknown receiver (TO address is unknown)
    #[error("Unknown receiver `{target}`")]
    UnknownReceiver { target: types::Url },

    /// # 4002
    /// Timeout on forwarded request (message is forwarded, but request times out)
    #[error("Timeout calling `{target}`. Elapsed after {elapsed}")]
    Timeout {
        target: types::Url,
        elapsed: types::Duration,
    },

    /// # 4003
    /// Connection problem (receiving party is not connected)
    #[error("Could not connect to `{target}`. Target is down")]
    Connection { target: types::Url },
}

#[cfg(feature = "axum")]
mod axum_extensions {
    use super::Error;
    use axum::{
        response::{IntoResponse, Response},
        Json,
    };

    impl IntoResponse for Error {
        fn into_response(self) -> Response {
            let http_status = self.http_status_code();
            let body = serde_json::to_value(&crate::Response::<()>::from_err(self))
                .expect("Serializing body");

            (http_status, Json(body)).into_response()
        }
    }
}

#[cfg(feature = "warp")]
mod warp_extensions {
    impl warp::reject::Reject for super::Error {}
}