tower_http/classify/
grpc_errors_as_failures.rs

1use super::{ClassifiedResponse, ClassifyEos, ClassifyResponse, SharedClassifier};
2use bitflags::bitflags;
3use http::{HeaderMap, Response};
4use std::{fmt, num::NonZeroI32};
5
6/// gRPC status codes.
7///
8/// These variants match the [gRPC status codes].
9///
10/// [gRPC status codes]: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md#status-codes-and-their-use-in-grpc
11#[derive(Clone, Copy, Debug)]
12pub enum GrpcCode {
13    /// The operation completed successfully.
14    Ok,
15    /// The operation was cancelled.
16    Cancelled,
17    /// Unknown error.
18    Unknown,
19    /// Client specified an invalid argument.
20    InvalidArgument,
21    /// Deadline expired before operation could complete.
22    DeadlineExceeded,
23    /// Some requested entity was not found.
24    NotFound,
25    /// Some entity that we attempted to create already exists.
26    AlreadyExists,
27    /// The caller does not have permission to execute the specified operation.
28    PermissionDenied,
29    /// Some resource has been exhausted.
30    ResourceExhausted,
31    /// The system is not in a state required for the operation's execution.
32    FailedPrecondition,
33    /// The operation was aborted.
34    Aborted,
35    /// Operation was attempted past the valid range.
36    OutOfRange,
37    /// Operation is not implemented or not supported.
38    Unimplemented,
39    /// Internal error.
40    Internal,
41    /// The service is currently unavailable.
42    Unavailable,
43    /// Unrecoverable data loss or corruption.
44    DataLoss,
45    /// The request does not have valid authentication credentials
46    Unauthenticated,
47}
48
49impl GrpcCode {
50    pub(crate) fn into_bitmask(self) -> GrpcCodeBitmask {
51        match self {
52            Self::Ok => GrpcCodeBitmask::OK,
53            Self::Cancelled => GrpcCodeBitmask::CANCELLED,
54            Self::Unknown => GrpcCodeBitmask::UNKNOWN,
55            Self::InvalidArgument => GrpcCodeBitmask::INVALID_ARGUMENT,
56            Self::DeadlineExceeded => GrpcCodeBitmask::DEADLINE_EXCEEDED,
57            Self::NotFound => GrpcCodeBitmask::NOT_FOUND,
58            Self::AlreadyExists => GrpcCodeBitmask::ALREADY_EXISTS,
59            Self::PermissionDenied => GrpcCodeBitmask::PERMISSION_DENIED,
60            Self::ResourceExhausted => GrpcCodeBitmask::RESOURCE_EXHAUSTED,
61            Self::FailedPrecondition => GrpcCodeBitmask::FAILED_PRECONDITION,
62            Self::Aborted => GrpcCodeBitmask::ABORTED,
63            Self::OutOfRange => GrpcCodeBitmask::OUT_OF_RANGE,
64            Self::Unimplemented => GrpcCodeBitmask::UNIMPLEMENTED,
65            Self::Internal => GrpcCodeBitmask::INTERNAL,
66            Self::Unavailable => GrpcCodeBitmask::UNAVAILABLE,
67            Self::DataLoss => GrpcCodeBitmask::DATA_LOSS,
68            Self::Unauthenticated => GrpcCodeBitmask::UNAUTHENTICATED,
69        }
70    }
71}
72
73bitflags! {
74    #[derive(Debug, Clone, Copy)]
75    pub(crate) struct GrpcCodeBitmask: u32 {
76        const OK                  = 0b00000000000000001;
77        const CANCELLED           = 0b00000000000000010;
78        const UNKNOWN             = 0b00000000000000100;
79        const INVALID_ARGUMENT    = 0b00000000000001000;
80        const DEADLINE_EXCEEDED   = 0b00000000000010000;
81        const NOT_FOUND           = 0b00000000000100000;
82        const ALREADY_EXISTS      = 0b00000000001000000;
83        const PERMISSION_DENIED   = 0b00000000010000000;
84        const RESOURCE_EXHAUSTED  = 0b00000000100000000;
85        const FAILED_PRECONDITION = 0b00000001000000000;
86        const ABORTED             = 0b00000010000000000;
87        const OUT_OF_RANGE        = 0b00000100000000000;
88        const UNIMPLEMENTED       = 0b00001000000000000;
89        const INTERNAL            = 0b00010000000000000;
90        const UNAVAILABLE         = 0b00100000000000000;
91        const DATA_LOSS           = 0b01000000000000000;
92        const UNAUTHENTICATED     = 0b10000000000000000;
93    }
94}
95
96impl GrpcCodeBitmask {
97    fn try_from_u32(code: u32) -> Option<Self> {
98        match code {
99            0 => Some(Self::OK),
100            1 => Some(Self::CANCELLED),
101            2 => Some(Self::UNKNOWN),
102            3 => Some(Self::INVALID_ARGUMENT),
103            4 => Some(Self::DEADLINE_EXCEEDED),
104            5 => Some(Self::NOT_FOUND),
105            6 => Some(Self::ALREADY_EXISTS),
106            7 => Some(Self::PERMISSION_DENIED),
107            8 => Some(Self::RESOURCE_EXHAUSTED),
108            9 => Some(Self::FAILED_PRECONDITION),
109            10 => Some(Self::ABORTED),
110            11 => Some(Self::OUT_OF_RANGE),
111            12 => Some(Self::UNIMPLEMENTED),
112            13 => Some(Self::INTERNAL),
113            14 => Some(Self::UNAVAILABLE),
114            15 => Some(Self::DATA_LOSS),
115            16 => Some(Self::UNAUTHENTICATED),
116            _ => None,
117        }
118    }
119}
120
121/// Response classifier for gRPC responses.
122///
123/// gRPC doesn't use normal HTTP statuses for indicating success or failure but instead a special
124/// header that might appear in a trailer.
125///
126/// Responses are considered successful if
127///
128/// - `grpc-status` header value contains a success value.
129/// - `grpc-status` header is missing.
130/// - `grpc-status` header value isn't a valid `String`.
131/// - `grpc-status` header value can't parsed into an `i32`.
132///
133/// All others are considered failures.
134#[derive(Debug, Clone)]
135pub struct GrpcErrorsAsFailures {
136    success_codes: GrpcCodeBitmask,
137}
138
139impl Default for GrpcErrorsAsFailures {
140    fn default() -> Self {
141        Self::new()
142    }
143}
144
145impl GrpcErrorsAsFailures {
146    /// Create a new [`GrpcErrorsAsFailures`].
147    pub fn new() -> Self {
148        Self {
149            success_codes: GrpcCodeBitmask::OK,
150        }
151    }
152
153    /// Change which gRPC codes are considered success.
154    ///
155    /// Defaults to only considering `Ok` as success.
156    ///
157    /// `Ok` will always be considered a success.
158    ///
159    /// # Example
160    ///
161    /// Servers might not want to consider `Invalid Argument` or `Not Found` as failures since
162    /// thats likely the clients fault:
163    ///
164    /// ```rust
165    /// use tower_http::classify::{GrpcErrorsAsFailures, GrpcCode};
166    ///
167    /// let classifier = GrpcErrorsAsFailures::new()
168    ///     .with_success(GrpcCode::InvalidArgument)
169    ///     .with_success(GrpcCode::NotFound);
170    /// ```
171    pub fn with_success(mut self, code: GrpcCode) -> Self {
172        self.success_codes |= code.into_bitmask();
173        self
174    }
175
176    /// Returns a [`MakeClassifier`](super::MakeClassifier) that produces `GrpcErrorsAsFailures`.
177    ///
178    /// This is a convenience function that simply calls `SharedClassifier::new`.
179    pub fn make_classifier() -> SharedClassifier<Self> {
180        SharedClassifier::new(Self::new())
181    }
182}
183
184impl ClassifyResponse for GrpcErrorsAsFailures {
185    type FailureClass = GrpcFailureClass;
186    type ClassifyEos = GrpcEosErrorsAsFailures;
187
188    fn classify_response<B>(
189        self,
190        res: &Response<B>,
191    ) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
192        match classify_grpc_metadata(res.headers(), self.success_codes) {
193            ParsedGrpcStatus::Success
194            | ParsedGrpcStatus::HeaderNotString
195            | ParsedGrpcStatus::HeaderNotInt => ClassifiedResponse::Ready(Ok(())),
196            ParsedGrpcStatus::NonSuccess(status) => {
197                ClassifiedResponse::Ready(Err(GrpcFailureClass::Code(status)))
198            }
199            ParsedGrpcStatus::GrpcStatusHeaderMissing => {
200                ClassifiedResponse::RequiresEos(GrpcEosErrorsAsFailures {
201                    success_codes: self.success_codes,
202                })
203            }
204        }
205    }
206
207    fn classify_error<E>(self, error: &E) -> Self::FailureClass
208    where
209        E: fmt::Display + 'static,
210    {
211        GrpcFailureClass::Error(error.to_string())
212    }
213}
214
215/// The [`ClassifyEos`] for [`GrpcErrorsAsFailures`].
216#[derive(Debug, Clone)]
217pub struct GrpcEosErrorsAsFailures {
218    success_codes: GrpcCodeBitmask,
219}
220
221impl ClassifyEos for GrpcEosErrorsAsFailures {
222    type FailureClass = GrpcFailureClass;
223
224    fn classify_eos(self, trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass> {
225        if let Some(trailers) = trailers {
226            match classify_grpc_metadata(trailers, self.success_codes) {
227                ParsedGrpcStatus::Success
228                | ParsedGrpcStatus::GrpcStatusHeaderMissing
229                | ParsedGrpcStatus::HeaderNotString
230                | ParsedGrpcStatus::HeaderNotInt => Ok(()),
231                ParsedGrpcStatus::NonSuccess(status) => Err(GrpcFailureClass::Code(status)),
232            }
233        } else {
234            Ok(())
235        }
236    }
237
238    fn classify_error<E>(self, error: &E) -> Self::FailureClass
239    where
240        E: fmt::Display + 'static,
241    {
242        GrpcFailureClass::Error(error.to_string())
243    }
244}
245
246/// The failure class for [`GrpcErrorsAsFailures`].
247#[derive(Debug)]
248pub enum GrpcFailureClass {
249    /// A gRPC response was classified as a failure with the corresponding status.
250    Code(std::num::NonZeroI32),
251    /// A gRPC response was classified as an error with the corresponding error description.
252    Error(String),
253}
254
255impl fmt::Display for GrpcFailureClass {
256    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257        match self {
258            Self::Code(code) => write!(f, "Code: {}", code),
259            Self::Error(error) => write!(f, "Error: {}", error),
260        }
261    }
262}
263
264pub(crate) fn classify_grpc_metadata(
265    headers: &HeaderMap,
266    success_codes: GrpcCodeBitmask,
267) -> ParsedGrpcStatus {
268    macro_rules! or_else {
269        ($expr:expr, $other:ident) => {
270            if let Some(value) = $expr {
271                value
272            } else {
273                return ParsedGrpcStatus::$other;
274            }
275        };
276    }
277
278    let status = or_else!(headers.get("grpc-status"), GrpcStatusHeaderMissing);
279    let status = or_else!(status.to_str().ok(), HeaderNotString);
280    let status = or_else!(status.parse::<i32>().ok(), HeaderNotInt);
281
282    if GrpcCodeBitmask::try_from_u32(status as _)
283        .filter(|code| success_codes.contains(*code))
284        .is_some()
285    {
286        ParsedGrpcStatus::Success
287    } else {
288        ParsedGrpcStatus::NonSuccess(NonZeroI32::new(status).unwrap())
289    }
290}
291
292#[derive(Debug, PartialEq, Eq)]
293pub(crate) enum ParsedGrpcStatus {
294    Success,
295    NonSuccess(NonZeroI32),
296    GrpcStatusHeaderMissing,
297    // these two are treated as `Success` but kept separate for clarity
298    HeaderNotString,
299    HeaderNotInt,
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    macro_rules! classify_grpc_metadata_test {
307        (
308            name: $name:ident,
309            status: $status:expr,
310            success_flags: $success_flags:expr,
311            expected: $expected:expr,
312        ) => {
313            #[test]
314            fn $name() {
315                let mut headers = HeaderMap::new();
316                headers.insert("grpc-status", $status.parse().unwrap());
317                let status = classify_grpc_metadata(&headers, $success_flags);
318                assert_eq!(status, $expected);
319            }
320        };
321    }
322
323    classify_grpc_metadata_test! {
324        name: basic_ok,
325        status: "0",
326        success_flags: GrpcCodeBitmask::OK,
327        expected: ParsedGrpcStatus::Success,
328    }
329
330    classify_grpc_metadata_test! {
331        name: basic_error,
332        status: "1",
333        success_flags: GrpcCodeBitmask::OK,
334        expected: ParsedGrpcStatus::NonSuccess(NonZeroI32::new(1).unwrap()),
335    }
336
337    classify_grpc_metadata_test! {
338        name: two_success_codes_first_matches,
339        status: "0",
340        success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
341        expected: ParsedGrpcStatus::Success,
342    }
343
344    classify_grpc_metadata_test! {
345        name: two_success_codes_second_matches,
346        status: "3",
347        success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
348        expected: ParsedGrpcStatus::Success,
349    }
350
351    classify_grpc_metadata_test! {
352        name: two_success_codes_none_matches,
353        status: "16",
354        success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
355        expected: ParsedGrpcStatus::NonSuccess(NonZeroI32::new(16).unwrap()),
356    }
357}