twurst_error/
lib.rs

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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#![doc = include_str!("../README.md")]
#![doc(test(attr(deny(warnings))))]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::sync::Arc;

/// A Twirp [error](https://twitchtv.github.io/twirp/docs/spec_v7.html#errors)
///
/// It is composed of three elements:
/// - An error `code` that is member of a fixed list [`TwirpErrorCode`]
/// - A human error `message` describing the error as a string
/// - A set of "`meta`" key-value pairs as strings holding arbitrary metadata describing the error.
///
/// ```
/// # use twurst_error::{TwirpError, TwirpErrorCode};
/// let error = TwirpError::not_found("Object foo not found").with_meta("id", "foo");
/// assert_eq!(error.code(), TwirpErrorCode::NotFound);
/// assert_eq!(error.message(), "Object foo not found");
/// assert_eq!(error.meta("id"), Some("foo"));
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TwirpError {
    /// The [error code](https://twitchtv.github.io/twirp/docs/spec_v7.html#error-codes)
    code: TwirpErrorCode,
    /// The error message (human description of the error)
    msg: String,
    /// Some metadata describing the error
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "HashMap::is_empty")
    )]
    meta: HashMap<String, String>,
    #[cfg_attr(feature = "serde", serde(default, skip))]
    source: Option<Arc<dyn Error + Send + Sync>>,
}

impl TwirpError {
    #[inline]
    pub fn code(&self) -> TwirpErrorCode {
        self.code
    }

    #[inline]
    pub fn message(&self) -> &str {
        &self.msg
    }

    #[inline]
    pub fn into_message(self) -> String {
        self.msg
    }

    /// Get an associated metadata
    #[inline]
    pub fn meta(&self, key: &str) -> Option<&str> {
        self.meta.get(key).map(|s| s.as_str())
    }

    /// Get all associated metadata
    #[inline]
    pub fn meta_iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.meta.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }

    #[inline]
    pub fn new(code: TwirpErrorCode, msg: impl Into<String>) -> Self {
        Self {
            code,
            msg: msg.into(),
            meta: HashMap::new(),
            source: None,
        }
    }

    #[inline]
    pub fn wrap(
        code: TwirpErrorCode,
        msg: impl Into<String>,
        e: impl Error + Send + Sync + 'static,
    ) -> Self {
        Self {
            code,
            msg: msg.into(),
            meta: HashMap::new(),
            source: Some(Arc::new(e)),
        }
    }

    /// Set an associated metadata
    #[inline]
    pub fn with_meta(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.meta.insert(key.into(), value.into());
        self
    }

    #[inline]
    pub fn aborted(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Aborted, msg)
    }

    #[inline]
    pub fn already_exists(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::AlreadyExists, msg)
    }

    #[inline]
    pub fn canceled(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Canceled, msg)
    }

    #[inline]
    pub fn dataloss(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Dataloss, msg)
    }

    #[inline]
    pub fn invalid_argument(argument: impl Into<String>, msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::InvalidArgument, msg).with_meta("argument", argument)
    }

    #[inline]
    pub fn internal(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Internal, msg)
    }

    #[inline]
    pub fn deadline_exceeded(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::DeadlineExceeded, msg)
    }

    #[inline]
    pub fn failed_precondition(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::FailedPrecondition, msg)
    }

    #[inline]
    pub fn malformed(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Malformed, msg)
    }

    #[inline]
    pub fn not_found(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::NotFound, msg)
    }

    #[inline]
    pub fn out_of_range(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::OutOfRange, msg)
    }

    #[inline]
    pub fn permission_denied(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::PermissionDenied, msg)
    }

    #[inline]
    pub fn required_argument(argument: &str) -> Self {
        Self::invalid_argument(argument, format!("{argument} is required"))
    }

    #[inline]
    pub fn resource_exhausted(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::ResourceExhausted, msg)
    }

    #[inline]
    pub fn unauthenticated(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Unauthenticated, msg)
    }

    #[inline]
    pub fn unavailable(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Unavailable, msg)
    }

    #[inline]
    pub fn unimplemented(msg: impl Into<String>) -> Self {
        Self::new(TwirpErrorCode::Unimplemented, msg)
    }
}

impl fmt::Display for TwirpError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Twirp {:?} error: {}", self.code, self.msg)
    }
}

impl Error for TwirpError {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self.source.as_ref()?)
    }
}

impl PartialEq for TwirpError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.code == other.code && self.msg == other.msg && self.meta == other.meta
    }
}

impl Eq for TwirpError {}

/// A Twirp [error code](https://twitchtv.github.io/twirp/docs/spec_v7.html#error-codes)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum TwirpErrorCode {
    /// The operation was cancelled.
    Canceled,
    /// An unknown error occurred. For example, this can be used when handling errors raised by APIs that do not return any error information.
    Unknown,
    /// The client specified an invalid argument. This indicates arguments that are invalid regardless of the state of the system (i.e. a malformed file name, required argument, number out of range, etc.).
    InvalidArgument,
    /// The client sent a message which could not be decoded. This may mean that the message was encoded improperly or that the client and server have incompatible message definitions.
    Malformed,
    /// Operation expired before completion. For operations that change the state of the system, this error may be returned even if the operation has completed successfully (timeout).
    DeadlineExceeded,
    /// Some requested entity was not found.
    NotFound,
    /// The requested URL path wasn't routable to a Twirp service and method. This is returned by generated server code and should not be returned by application code (use "not_found" or "unimplemented" instead).
    BadRoute,
    /// An attempt to create an entity failed because one already exists.
    AlreadyExists,
    /// The caller does not have permission to execute the specified operation. It must not be used if the caller cannot be identified (use "unauthenticated" instead).
    PermissionDenied,
    /// The request does not have valid authentication credentials for the operation.
    Unauthenticated,
    /// Some resource has been exhausted or rate-limited, perhaps a per-user quota, or perhaps the entire file system is out of space.
    ResourceExhausted,
    /// The operation was rejected because the system is not in a state required for the operation's execution. For example, doing an rmdir operation on a directory that is non-empty, or on a non-directory object, or when having conflicting read-modify-write on the same resource.
    FailedPrecondition,
    /// The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.
    Aborted,
    /// The operation was attempted past the valid range. For example, seeking or reading past end of a paginated collection. Unlike "invalid_argument", this error indicates a problem that may be fixed if the system state changes (i.e. adding more items to the collection). There is a fair bit of overlap between "failed_precondition" and "out_of_range". We recommend using "out_of_range" (the more specific error) when it applies so that callers who are iterating through a space can easily look for an "out_of_range" error to detect when they are done.
    OutOfRange,
    /// The operation is not implemented or not supported/enabled in this service.
    Unimplemented,
    /// When some invariants expected by the underlying system have been broken. In other words, something bad happened in the library or backend service. Twirp specific issues like wire and serialization problems are also reported as "internal" errors.
    Internal,
    /// The service is currently unavailable. This is most likely a transient condition and may be corrected by retrying with a backoff.
    Unavailable,
    /// The operation resulted in unrecoverable data loss or corruption.
    Dataloss,
}

/// Applies the mapping defined in [Twirp spec](https://twitchtv.github.io/twirp/docs/spec_v7.html#error-codes)
#[cfg(feature = "http")]
impl From<TwirpErrorCode> for http::StatusCode {
    #[inline]
    fn from(code: TwirpErrorCode) -> Self {
        match code {
            TwirpErrorCode::Canceled => Self::REQUEST_TIMEOUT,
            TwirpErrorCode::Unknown => Self::INTERNAL_SERVER_ERROR,
            TwirpErrorCode::InvalidArgument => Self::BAD_REQUEST,
            TwirpErrorCode::Malformed => Self::BAD_REQUEST,
            TwirpErrorCode::DeadlineExceeded => Self::REQUEST_TIMEOUT,
            TwirpErrorCode::NotFound => Self::NOT_FOUND,
            TwirpErrorCode::BadRoute => Self::NOT_FOUND,
            TwirpErrorCode::AlreadyExists => Self::CONFLICT,
            TwirpErrorCode::PermissionDenied => Self::FORBIDDEN,
            TwirpErrorCode::Unauthenticated => Self::UNAUTHORIZED,
            TwirpErrorCode::ResourceExhausted => Self::TOO_MANY_REQUESTS,
            TwirpErrorCode::FailedPrecondition => Self::PRECONDITION_FAILED,
            TwirpErrorCode::Aborted => Self::CONFLICT,
            TwirpErrorCode::OutOfRange => Self::BAD_REQUEST,
            TwirpErrorCode::Unimplemented => Self::NOT_IMPLEMENTED,
            TwirpErrorCode::Internal => Self::INTERNAL_SERVER_ERROR,
            TwirpErrorCode::Unavailable => Self::SERVICE_UNAVAILABLE,
            TwirpErrorCode::Dataloss => Self::SERVICE_UNAVAILABLE,
        }
    }
}

#[cfg(feature = "http")]
impl<B: From<String>> From<TwirpError> for http::Response<B> {
    fn from(error: TwirpError) -> Self {
        let json = serde_json::to_string(&error).unwrap();
        http::Response::builder()
            .status(error.code)
            .header(http::header::CONTENT_TYPE, "application/json")
            .extension(error)
            .body(json.into())
            .unwrap()
    }
}

#[cfg(feature = "http")]
impl<B: AsRef<[u8]>> From<http::Response<B>> for TwirpError {
    fn from(response: http::Response<B>) -> Self {
        if let Some(error) = response.extensions().get::<Self>() {
            // We got a ready to use error in the extensions, let's use it
            return error.clone();
        }
        // We are lenient here, a bad error is better than no error at all
        let status = response.status();
        let body = response.into_body();
        if let Ok(error) = serde_json::from_slice::<TwirpError>(body.as_ref()) {
            // The body is an error, we use it
            return error;
        }
        // We don't have a Twirp error, we build a fallback
        let code = if status == http::StatusCode::REQUEST_TIMEOUT {
            TwirpErrorCode::DeadlineExceeded
        } else if status == http::StatusCode::FORBIDDEN {
            TwirpErrorCode::PermissionDenied
        } else if status == http::StatusCode::UNAUTHORIZED {
            TwirpErrorCode::Unauthenticated
        } else if status == http::StatusCode::TOO_MANY_REQUESTS {
            TwirpErrorCode::ResourceExhausted
        } else if status == http::StatusCode::PRECONDITION_FAILED {
            TwirpErrorCode::FailedPrecondition
        } else if status == http::StatusCode::NOT_IMPLEMENTED {
            TwirpErrorCode::Unimplemented
        } else if status == http::StatusCode::TOO_MANY_REQUESTS
            || status == http::StatusCode::BAD_GATEWAY
            || status == http::StatusCode::SERVICE_UNAVAILABLE
            || status == http::StatusCode::GATEWAY_TIMEOUT
        {
            TwirpErrorCode::Unavailable
        } else if status == http::StatusCode::NOT_FOUND {
            TwirpErrorCode::NotFound
        } else if status.is_server_error() {
            TwirpErrorCode::Internal
        } else if status.is_client_error() {
            TwirpErrorCode::Malformed
        } else {
            TwirpErrorCode::Unknown
        };
        TwirpError::new(code, String::from_utf8_lossy(body.as_ref()))
    }
}

#[cfg(feature = "axum-07")]
impl axum_core_04::response::IntoResponse for TwirpError {
    #[inline]
    fn into_response(self) -> axum_core_04::response::Response {
        self.into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "http")]
    use std::error::Error;

    #[test]
    fn test_accessors() {
        let error = TwirpError::invalid_argument("foo", "foo is wrong");
        assert_eq!(error.code(), TwirpErrorCode::InvalidArgument);
        assert_eq!(error.message(), "foo is wrong");
        assert_eq!(error.meta("argument"), Some("foo"));
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_to_response() -> Result<(), Box<dyn Error>> {
        let object =
            TwirpError::permission_denied("Thou shall not pass").with_meta("target", "Balrog");
        let response = http::Response::<Vec<u8>>::from(object);
        assert_eq!(response.status(), http::StatusCode::FORBIDDEN);
        assert_eq!(
            response.headers().get(http::header::CONTENT_TYPE),
            Some(&http::HeaderValue::from_static("application/json"))
        );
        assert_eq!(
            response.into_body(), b"{\"code\":\"permission_denied\",\"msg\":\"Thou shall not pass\",\"meta\":{\"target\":\"Balrog\"}}"
        );
        Ok(())
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_from_valid_response() -> Result<(), Box<dyn Error>> {
        let response = http::Response::builder()
            .header(http::header::CONTENT_TYPE, "application/json")
            .body("{\"code\":\"permission_denied\",\"msg\":\"Thou shall not pass\",\"meta\":{\"target\":\"Balrog\"}}")?;
        assert_eq!(
            TwirpError::from(response),
            TwirpError::permission_denied("Thou shall not pass").with_meta("target", "Balrog")
        );
        Ok(())
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_from_plain_response() -> Result<(), Box<dyn Error>> {
        let response = http::Response::builder()
            .status(http::StatusCode::FORBIDDEN)
            .body("Thou shall not pass")?;
        assert_eq!(
            TwirpError::from(response),
            TwirpError::permission_denied("Thou shall not pass")
        );
        Ok(())
    }
}