Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
@@ -0,0 +1,417 @@
|
||||
use super::{ClassifiedResponse, ClassifyEos, ClassifyResponse, SharedClassifier};
|
||||
use bitflags::bitflags;
|
||||
use http::{HeaderMap, Response};
|
||||
use std::{fmt, num::NonZeroI32};
|
||||
|
||||
/// gRPC status codes.
|
||||
///
|
||||
/// These variants match the [gRPC status codes].
|
||||
///
|
||||
/// [gRPC status codes]: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md#status-codes-and-their-use-in-grpc
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum GrpcCode {
|
||||
/// The operation completed successfully.
|
||||
Ok,
|
||||
/// The operation was cancelled.
|
||||
Cancelled,
|
||||
/// Unknown error.
|
||||
Unknown,
|
||||
/// Client specified an invalid argument.
|
||||
InvalidArgument,
|
||||
/// Deadline expired before operation could complete.
|
||||
DeadlineExceeded,
|
||||
/// Some requested entity was not found.
|
||||
NotFound,
|
||||
/// Some entity that we attempted to create already exists.
|
||||
AlreadyExists,
|
||||
/// The caller does not have permission to execute the specified operation.
|
||||
PermissionDenied,
|
||||
/// Some resource has been exhausted.
|
||||
ResourceExhausted,
|
||||
/// The system is not in a state required for the operation's execution.
|
||||
FailedPrecondition,
|
||||
/// The operation was aborted.
|
||||
Aborted,
|
||||
/// Operation was attempted past the valid range.
|
||||
OutOfRange,
|
||||
/// Operation is not implemented or not supported.
|
||||
Unimplemented,
|
||||
/// Internal error.
|
||||
Internal,
|
||||
/// The service is currently unavailable.
|
||||
Unavailable,
|
||||
/// Unrecoverable data loss or corruption.
|
||||
DataLoss,
|
||||
/// The request does not have valid authentication credentials
|
||||
Unauthenticated,
|
||||
}
|
||||
|
||||
impl GrpcCode {
|
||||
pub(crate) fn into_bitmask(self) -> GrpcCodeBitmask {
|
||||
match self {
|
||||
Self::Ok => GrpcCodeBitmask::OK,
|
||||
Self::Cancelled => GrpcCodeBitmask::CANCELLED,
|
||||
Self::Unknown => GrpcCodeBitmask::UNKNOWN,
|
||||
Self::InvalidArgument => GrpcCodeBitmask::INVALID_ARGUMENT,
|
||||
Self::DeadlineExceeded => GrpcCodeBitmask::DEADLINE_EXCEEDED,
|
||||
Self::NotFound => GrpcCodeBitmask::NOT_FOUND,
|
||||
Self::AlreadyExists => GrpcCodeBitmask::ALREADY_EXISTS,
|
||||
Self::PermissionDenied => GrpcCodeBitmask::PERMISSION_DENIED,
|
||||
Self::ResourceExhausted => GrpcCodeBitmask::RESOURCE_EXHAUSTED,
|
||||
Self::FailedPrecondition => GrpcCodeBitmask::FAILED_PRECONDITION,
|
||||
Self::Aborted => GrpcCodeBitmask::ABORTED,
|
||||
Self::OutOfRange => GrpcCodeBitmask::OUT_OF_RANGE,
|
||||
Self::Unimplemented => GrpcCodeBitmask::UNIMPLEMENTED,
|
||||
Self::Internal => GrpcCodeBitmask::INTERNAL,
|
||||
Self::Unavailable => GrpcCodeBitmask::UNAVAILABLE,
|
||||
Self::DataLoss => GrpcCodeBitmask::DATA_LOSS,
|
||||
Self::Unauthenticated => GrpcCodeBitmask::UNAUTHENTICATED,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts an `i32` gRPC status code into a [`GrpcCode`].
|
||||
///
|
||||
/// Unrecognized codes (outside 0-16) map to [`GrpcCode::Unknown`].
|
||||
impl From<i32> for GrpcCode {
|
||||
fn from(value: i32) -> Self {
|
||||
match value {
|
||||
0 => GrpcCode::Ok,
|
||||
1 => GrpcCode::Cancelled,
|
||||
2 => GrpcCode::Unknown,
|
||||
3 => GrpcCode::InvalidArgument,
|
||||
4 => GrpcCode::DeadlineExceeded,
|
||||
5 => GrpcCode::NotFound,
|
||||
6 => GrpcCode::AlreadyExists,
|
||||
7 => GrpcCode::PermissionDenied,
|
||||
8 => GrpcCode::ResourceExhausted,
|
||||
9 => GrpcCode::FailedPrecondition,
|
||||
10 => GrpcCode::Aborted,
|
||||
11 => GrpcCode::OutOfRange,
|
||||
12 => GrpcCode::Unimplemented,
|
||||
13 => GrpcCode::Internal,
|
||||
14 => GrpcCode::Unavailable,
|
||||
15 => GrpcCode::DataLoss,
|
||||
16 => GrpcCode::Unauthenticated,
|
||||
|
||||
_ => GrpcCode::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<NonZeroI32> for GrpcCode {
|
||||
fn from(value: NonZeroI32) -> Self {
|
||||
GrpcCode::from(value.get())
|
||||
}
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct GrpcCodeBitmask: u32 {
|
||||
const OK = 0b00000000000000001;
|
||||
const CANCELLED = 0b00000000000000010;
|
||||
const UNKNOWN = 0b00000000000000100;
|
||||
const INVALID_ARGUMENT = 0b00000000000001000;
|
||||
const DEADLINE_EXCEEDED = 0b00000000000010000;
|
||||
const NOT_FOUND = 0b00000000000100000;
|
||||
const ALREADY_EXISTS = 0b00000000001000000;
|
||||
const PERMISSION_DENIED = 0b00000000010000000;
|
||||
const RESOURCE_EXHAUSTED = 0b00000000100000000;
|
||||
const FAILED_PRECONDITION = 0b00000001000000000;
|
||||
const ABORTED = 0b00000010000000000;
|
||||
const OUT_OF_RANGE = 0b00000100000000000;
|
||||
const UNIMPLEMENTED = 0b00001000000000000;
|
||||
const INTERNAL = 0b00010000000000000;
|
||||
const UNAVAILABLE = 0b00100000000000000;
|
||||
const DATA_LOSS = 0b01000000000000000;
|
||||
const UNAUTHENTICATED = 0b10000000000000000;
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcCodeBitmask {
|
||||
fn try_from_u32(code: u32) -> Option<Self> {
|
||||
match code {
|
||||
0 => Some(Self::OK),
|
||||
1 => Some(Self::CANCELLED),
|
||||
2 => Some(Self::UNKNOWN),
|
||||
3 => Some(Self::INVALID_ARGUMENT),
|
||||
4 => Some(Self::DEADLINE_EXCEEDED),
|
||||
5 => Some(Self::NOT_FOUND),
|
||||
6 => Some(Self::ALREADY_EXISTS),
|
||||
7 => Some(Self::PERMISSION_DENIED),
|
||||
8 => Some(Self::RESOURCE_EXHAUSTED),
|
||||
9 => Some(Self::FAILED_PRECONDITION),
|
||||
10 => Some(Self::ABORTED),
|
||||
11 => Some(Self::OUT_OF_RANGE),
|
||||
12 => Some(Self::UNIMPLEMENTED),
|
||||
13 => Some(Self::INTERNAL),
|
||||
14 => Some(Self::UNAVAILABLE),
|
||||
15 => Some(Self::DATA_LOSS),
|
||||
16 => Some(Self::UNAUTHENTICATED),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Response classifier for gRPC responses.
|
||||
///
|
||||
/// gRPC doesn't use normal HTTP statuses for indicating success or failure but instead a special
|
||||
/// header that might appear in a trailer.
|
||||
///
|
||||
/// Responses are considered successful if
|
||||
///
|
||||
/// - `grpc-status` header value contains a success value.
|
||||
/// - `grpc-status` header is missing.
|
||||
/// - `grpc-status` header value isn't a valid `String`.
|
||||
/// - `grpc-status` header value can't parsed into an `i32`.
|
||||
///
|
||||
/// All others are considered failures.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GrpcErrorsAsFailures {
|
||||
success_codes: GrpcCodeBitmask,
|
||||
}
|
||||
|
||||
impl Default for GrpcErrorsAsFailures {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcErrorsAsFailures {
|
||||
/// Create a new [`GrpcErrorsAsFailures`].
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
success_codes: GrpcCodeBitmask::OK,
|
||||
}
|
||||
}
|
||||
|
||||
/// Change which gRPC codes are considered success.
|
||||
///
|
||||
/// Defaults to only considering `Ok` as success.
|
||||
///
|
||||
/// `Ok` will always be considered a success.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// Servers might not want to consider `Invalid Argument` or `Not Found` as failures since
|
||||
/// thats likely the clients fault:
|
||||
///
|
||||
/// ```rust
|
||||
/// use tower_http::classify::{GrpcErrorsAsFailures, GrpcCode};
|
||||
///
|
||||
/// let classifier = GrpcErrorsAsFailures::new()
|
||||
/// .with_success(GrpcCode::InvalidArgument)
|
||||
/// .with_success(GrpcCode::NotFound);
|
||||
/// ```
|
||||
pub fn with_success(mut self, code: GrpcCode) -> Self {
|
||||
self.success_codes |= code.into_bitmask();
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns a [`MakeClassifier`](super::MakeClassifier) that produces `GrpcErrorsAsFailures`.
|
||||
///
|
||||
/// This is a convenience function that simply calls `SharedClassifier::new`.
|
||||
pub fn make_classifier() -> SharedClassifier<Self> {
|
||||
SharedClassifier::new(Self::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ClassifyResponse for GrpcErrorsAsFailures {
|
||||
type FailureClass = GrpcFailureClass;
|
||||
type ClassifyEos = GrpcEosErrorsAsFailures;
|
||||
|
||||
fn classify_response<B>(
|
||||
self,
|
||||
res: &Response<B>,
|
||||
) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
|
||||
match classify_grpc_metadata(res.headers(), self.success_codes) {
|
||||
ParsedGrpcStatus::Success
|
||||
| ParsedGrpcStatus::HeaderNotString
|
||||
| ParsedGrpcStatus::HeaderNotInt => ClassifiedResponse::Ready(Ok(())),
|
||||
ParsedGrpcStatus::NonSuccess(status) => {
|
||||
ClassifiedResponse::Ready(Err(GrpcFailureClass::Code(status)))
|
||||
}
|
||||
ParsedGrpcStatus::GrpcStatusHeaderMissing => {
|
||||
ClassifiedResponse::RequiresEos(GrpcEosErrorsAsFailures {
|
||||
success_codes: self.success_codes,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static,
|
||||
{
|
||||
GrpcFailureClass::Error(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`ClassifyEos`] for [`GrpcErrorsAsFailures`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GrpcEosErrorsAsFailures {
|
||||
success_codes: GrpcCodeBitmask,
|
||||
}
|
||||
|
||||
impl ClassifyEos for GrpcEosErrorsAsFailures {
|
||||
type FailureClass = GrpcFailureClass;
|
||||
|
||||
fn classify_eos(self, trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass> {
|
||||
if let Some(trailers) = trailers {
|
||||
match classify_grpc_metadata(trailers, self.success_codes) {
|
||||
ParsedGrpcStatus::Success
|
||||
| ParsedGrpcStatus::GrpcStatusHeaderMissing
|
||||
| ParsedGrpcStatus::HeaderNotString
|
||||
| ParsedGrpcStatus::HeaderNotInt => Ok(()),
|
||||
ParsedGrpcStatus::NonSuccess(status) => Err(GrpcFailureClass::Code(status)),
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static,
|
||||
{
|
||||
GrpcFailureClass::Error(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The failure class for [`GrpcErrorsAsFailures`].
|
||||
#[derive(Debug)]
|
||||
pub enum GrpcFailureClass {
|
||||
/// A gRPC response was classified as a failure with the corresponding status.
|
||||
Code(std::num::NonZeroI32),
|
||||
/// A gRPC response was classified as an error with the corresponding error description.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for GrpcFailureClass {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
Self::Code(code) => write!(f, "Code: {}", code),
|
||||
Self::Error(error) => write!(f, "Error: {}", error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn classify_grpc_metadata(
|
||||
headers: &HeaderMap,
|
||||
success_codes: GrpcCodeBitmask,
|
||||
) -> ParsedGrpcStatus {
|
||||
macro_rules! or_else {
|
||||
($expr:expr, $other:ident) => {
|
||||
if let Some(value) = $expr {
|
||||
value
|
||||
} else {
|
||||
return ParsedGrpcStatus::$other;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let status = or_else!(headers.get("grpc-status"), GrpcStatusHeaderMissing);
|
||||
let status = or_else!(status.to_str().ok(), HeaderNotString);
|
||||
let status = or_else!(status.parse::<i32>().ok(), HeaderNotInt);
|
||||
|
||||
if GrpcCodeBitmask::try_from_u32(status as _)
|
||||
.filter(|code| success_codes.contains(*code))
|
||||
.is_some()
|
||||
{
|
||||
ParsedGrpcStatus::Success
|
||||
} else {
|
||||
ParsedGrpcStatus::NonSuccess(NonZeroI32::new(status).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ParsedGrpcStatus {
|
||||
Success,
|
||||
NonSuccess(NonZeroI32),
|
||||
GrpcStatusHeaderMissing,
|
||||
// these two are treated as `Success` but kept separate for clarity
|
||||
HeaderNotString,
|
||||
HeaderNotInt,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
macro_rules! classify_grpc_metadata_test {
|
||||
(
|
||||
name: $name:ident,
|
||||
status: $status:expr,
|
||||
success_flags: $success_flags:expr,
|
||||
expected: $expected:expr,
|
||||
) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("grpc-status", $status.parse().unwrap());
|
||||
let status = classify_grpc_metadata(&headers, $success_flags);
|
||||
assert_eq!(status, $expected);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
classify_grpc_metadata_test! {
|
||||
name: basic_ok,
|
||||
status: "0",
|
||||
success_flags: GrpcCodeBitmask::OK,
|
||||
expected: ParsedGrpcStatus::Success,
|
||||
}
|
||||
|
||||
classify_grpc_metadata_test! {
|
||||
name: basic_error,
|
||||
status: "1",
|
||||
success_flags: GrpcCodeBitmask::OK,
|
||||
expected: ParsedGrpcStatus::NonSuccess(NonZeroI32::new(1).unwrap()),
|
||||
}
|
||||
|
||||
classify_grpc_metadata_test! {
|
||||
name: two_success_codes_first_matches,
|
||||
status: "0",
|
||||
success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
|
||||
expected: ParsedGrpcStatus::Success,
|
||||
}
|
||||
|
||||
classify_grpc_metadata_test! {
|
||||
name: two_success_codes_second_matches,
|
||||
status: "3",
|
||||
success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
|
||||
expected: ParsedGrpcStatus::Success,
|
||||
}
|
||||
|
||||
classify_grpc_metadata_test! {
|
||||
name: two_success_codes_none_matches,
|
||||
status: "16",
|
||||
success_flags: GrpcCodeBitmask::OK | GrpcCodeBitmask::INVALID_ARGUMENT,
|
||||
expected: ParsedGrpcStatus::NonSuccess(NonZeroI32::new(16).unwrap()),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grpc_code_from_i32_known_codes() {
|
||||
assert!(matches!(GrpcCode::from(0), GrpcCode::Ok));
|
||||
assert!(matches!(GrpcCode::from(1), GrpcCode::Cancelled));
|
||||
assert!(matches!(GrpcCode::from(4), GrpcCode::DeadlineExceeded));
|
||||
assert!(matches!(GrpcCode::from(13), GrpcCode::Internal));
|
||||
assert!(matches!(GrpcCode::from(16), GrpcCode::Unauthenticated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grpc_code_from_i32_unknown_codes() {
|
||||
assert!(matches!(GrpcCode::from(17), GrpcCode::Unknown));
|
||||
assert!(matches!(GrpcCode::from(-1), GrpcCode::Unknown));
|
||||
assert!(matches!(GrpcCode::from(9999), GrpcCode::Unknown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grpc_code_from_non_zero_i32() {
|
||||
let code = NonZeroI32::new(7).unwrap();
|
||||
assert!(matches!(GrpcCode::from(code), GrpcCode::PermissionDenied));
|
||||
|
||||
let code = NonZeroI32::new(99).unwrap();
|
||||
assert!(matches!(GrpcCode::from(code), GrpcCode::Unknown));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use super::{ClassifiedResponse, ClassifyEos, ClassifyResponse};
|
||||
use http::{HeaderMap, Response};
|
||||
use std::fmt;
|
||||
|
||||
/// Response classifier that transforms the failure class of some other
|
||||
/// classifier.
|
||||
///
|
||||
/// Created with [`ClassifyResponse::map_failure_class`] or
|
||||
/// [`ClassifyEos::map_failure_class`].
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct MapFailureClass<C, F> {
|
||||
inner: C,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<C, F> MapFailureClass<C, F> {
|
||||
pub(super) fn new(classify: C, f: F) -> Self {
|
||||
Self { inner: classify, f }
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, F> fmt::Debug for MapFailureClass<C, F>
|
||||
where
|
||||
C: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("MapFailureClass")
|
||||
.field("inner", &self.inner)
|
||||
.field("f", &format_args!("{}", std::any::type_name::<F>()))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, F, NewClass> ClassifyResponse for MapFailureClass<C, F>
|
||||
where
|
||||
C: ClassifyResponse,
|
||||
F: FnOnce(C::FailureClass) -> NewClass,
|
||||
{
|
||||
type FailureClass = NewClass;
|
||||
type ClassifyEos = MapFailureClass<C::ClassifyEos, F>;
|
||||
|
||||
fn classify_response<B>(
|
||||
self,
|
||||
res: &Response<B>,
|
||||
) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
|
||||
match self.inner.classify_response(res) {
|
||||
ClassifiedResponse::Ready(result) => ClassifiedResponse::Ready(result.map_err(self.f)),
|
||||
ClassifiedResponse::RequiresEos(classify_eos) => {
|
||||
let mapped_classify_eos = MapFailureClass::new(classify_eos, self.f);
|
||||
ClassifiedResponse::RequiresEos(mapped_classify_eos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: std::fmt::Display + 'static,
|
||||
{
|
||||
(self.f)(self.inner.classify_error(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, F, NewClass> ClassifyEos for MapFailureClass<C, F>
|
||||
where
|
||||
C: ClassifyEos,
|
||||
F: FnOnce(C::FailureClass) -> NewClass,
|
||||
{
|
||||
type FailureClass = NewClass;
|
||||
|
||||
fn classify_eos(self, trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass> {
|
||||
self.inner.classify_eos(trailers).map_err(self.f)
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: std::fmt::Display + 'static,
|
||||
{
|
||||
(self.f)(self.inner.classify_error(error))
|
||||
}
|
||||
}
|
||||
+436
@@ -0,0 +1,436 @@
|
||||
//! Tools for classifying responses as either success or failure.
|
||||
|
||||
use http::{HeaderMap, Request, Response, StatusCode};
|
||||
use std::{convert::Infallible, fmt, marker::PhantomData};
|
||||
|
||||
pub(crate) mod grpc_errors_as_failures;
|
||||
mod map_failure_class;
|
||||
mod status_in_range_is_error;
|
||||
|
||||
pub use self::{
|
||||
grpc_errors_as_failures::{
|
||||
GrpcCode, GrpcEosErrorsAsFailures, GrpcErrorsAsFailures, GrpcFailureClass,
|
||||
},
|
||||
map_failure_class::MapFailureClass,
|
||||
status_in_range_is_error::{StatusInRangeAsFailures, StatusInRangeFailureClass},
|
||||
};
|
||||
|
||||
/// Trait for producing response classifiers from a request.
|
||||
///
|
||||
/// This is useful when a classifier depends on data from the request. For example, this could
|
||||
/// include the URI or HTTP method.
|
||||
///
|
||||
/// This trait is generic over the [`Error` type] of the `Service`s used with the classifier.
|
||||
/// This is necessary for [`ClassifyResponse::classify_error`].
|
||||
///
|
||||
/// [`Error` type]: https://docs.rs/tower/latest/tower/trait.Service.html#associatedtype.Error
|
||||
pub trait MakeClassifier {
|
||||
/// The response classifier produced.
|
||||
type Classifier: ClassifyResponse<
|
||||
FailureClass = Self::FailureClass,
|
||||
ClassifyEos = Self::ClassifyEos,
|
||||
>;
|
||||
|
||||
/// The type of failure classifications.
|
||||
///
|
||||
/// This might include additional information about the error, such as
|
||||
/// whether it was a client or server error, or whether or not it should
|
||||
/// be considered retryable.
|
||||
type FailureClass;
|
||||
|
||||
/// The type used to classify the response end of stream (EOS).
|
||||
type ClassifyEos: ClassifyEos<FailureClass = Self::FailureClass>;
|
||||
|
||||
/// Returns a response classifier for this request
|
||||
fn make_classifier<B>(&self, req: &Request<B>) -> Self::Classifier;
|
||||
}
|
||||
|
||||
/// A [`MakeClassifier`] that produces new classifiers by cloning an inner classifier.
|
||||
///
|
||||
/// When a type implementing [`ClassifyResponse`] doesn't depend on information
|
||||
/// from the request, [`SharedClassifier`] can be used to turn an instance of that type
|
||||
/// into a [`MakeClassifier`].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use std::fmt;
|
||||
/// use tower_http::classify::{
|
||||
/// ClassifyResponse, ClassifiedResponse, NeverClassifyEos,
|
||||
/// SharedClassifier, MakeClassifier,
|
||||
/// };
|
||||
/// use http::Response;
|
||||
///
|
||||
/// // A response classifier that only considers errors to be failures.
|
||||
/// #[derive(Clone, Copy)]
|
||||
/// struct MyClassifier;
|
||||
///
|
||||
/// impl ClassifyResponse for MyClassifier {
|
||||
/// type FailureClass = String;
|
||||
/// type ClassifyEos = NeverClassifyEos<Self::FailureClass>;
|
||||
///
|
||||
/// fn classify_response<B>(
|
||||
/// self,
|
||||
/// _res: &Response<B>,
|
||||
/// ) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
|
||||
/// ClassifiedResponse::Ready(Ok(()))
|
||||
/// }
|
||||
///
|
||||
/// fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
/// where
|
||||
/// E: fmt::Display + 'static,
|
||||
/// {
|
||||
/// error.to_string()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Some function that requires a `MakeClassifier`
|
||||
/// fn use_make_classifier<M: MakeClassifier>(make: M) {
|
||||
/// // ...
|
||||
/// }
|
||||
///
|
||||
/// // `MyClassifier` doesn't implement `MakeClassifier` but since it doesn't
|
||||
/// // care about the incoming request we can make `MyClassifier`s by cloning.
|
||||
/// // That is what `SharedClassifier` does.
|
||||
/// let make_classifier = SharedClassifier::new(MyClassifier);
|
||||
///
|
||||
/// // We now have a `MakeClassifier`!
|
||||
/// use_make_classifier(make_classifier);
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SharedClassifier<C> {
|
||||
classifier: C,
|
||||
}
|
||||
|
||||
impl<C> SharedClassifier<C> {
|
||||
/// Create a new `SharedClassifier` from the given classifier.
|
||||
pub fn new(classifier: C) -> Self
|
||||
where
|
||||
C: ClassifyResponse + Clone,
|
||||
{
|
||||
Self { classifier }
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> MakeClassifier for SharedClassifier<C>
|
||||
where
|
||||
C: ClassifyResponse + Clone,
|
||||
{
|
||||
type FailureClass = C::FailureClass;
|
||||
type ClassifyEos = C::ClassifyEos;
|
||||
type Classifier = C;
|
||||
|
||||
fn make_classifier<B>(&self, _req: &Request<B>) -> Self::Classifier {
|
||||
self.classifier.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for classifying responses as either success or failure. Designed to support both unary
|
||||
/// requests (single request for a single response) as well as streaming responses.
|
||||
///
|
||||
/// Response classifiers are used in cases where middleware needs to determine
|
||||
/// whether a response completed successfully or failed. For example, they may
|
||||
/// be used by logging or metrics middleware to record failures differently
|
||||
/// from successes.
|
||||
///
|
||||
/// Furthermore, when a response fails, a response classifier may provide
|
||||
/// additional information about the failure. This can, for example, be used to
|
||||
/// build [retry policies] by indicating whether or not a particular failure is
|
||||
/// retryable.
|
||||
///
|
||||
/// [retry policies]: https://docs.rs/tower/latest/tower/retry/trait.Policy.html
|
||||
pub trait ClassifyResponse {
|
||||
/// The type returned when a response is classified as a failure.
|
||||
///
|
||||
/// Depending on the classifier, this may simply indicate that the
|
||||
/// request failed, or it may contain additional information about
|
||||
/// the failure, such as whether or not it is retryable.
|
||||
type FailureClass;
|
||||
|
||||
/// The type used to classify the response end of stream (EOS).
|
||||
type ClassifyEos: ClassifyEos<FailureClass = Self::FailureClass>;
|
||||
|
||||
/// Attempt to classify the beginning of a response.
|
||||
///
|
||||
/// In some cases, the response can be classified immediately, without
|
||||
/// waiting for a body to complete. This may include:
|
||||
///
|
||||
/// - When the response has an error status code.
|
||||
/// - When a successful response does not have a streaming body.
|
||||
/// - When the classifier does not care about streaming bodies.
|
||||
///
|
||||
/// When the response can be classified immediately, `classify_response`
|
||||
/// returns a [`ClassifiedResponse::Ready`] which indicates whether the
|
||||
/// response succeeded or failed.
|
||||
///
|
||||
/// In other cases, however, the classifier may need to wait until the
|
||||
/// response body stream completes before it can classify the response.
|
||||
/// For example, gRPC indicates RPC failures using the `grpc-status`
|
||||
/// trailer. In this case, `classify_response` returns a
|
||||
/// [`ClassifiedResponse::RequiresEos`] containing a type which will
|
||||
/// be used to classify the response when the body stream ends.
|
||||
fn classify_response<B>(
|
||||
self,
|
||||
res: &Response<B>,
|
||||
) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos>;
|
||||
|
||||
/// Classify an error.
|
||||
///
|
||||
/// Errors are always errors (doh) but sometimes it might be useful to have multiple classes of
|
||||
/// errors. A retry policy might allow retrying some errors and not others.
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static;
|
||||
|
||||
/// Transform the failure classification using a function.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use tower_http::classify::{
|
||||
/// ServerErrorsAsFailures, ServerErrorsFailureClass,
|
||||
/// ClassifyResponse, ClassifiedResponse
|
||||
/// };
|
||||
/// use http::{Response, StatusCode};
|
||||
/// use http_body_util::Empty;
|
||||
/// use bytes::Bytes;
|
||||
///
|
||||
/// fn transform_failure_class(class: ServerErrorsFailureClass) -> NewFailureClass {
|
||||
/// match class {
|
||||
/// // Convert status codes into u16
|
||||
/// ServerErrorsFailureClass::StatusCode(status) => {
|
||||
/// NewFailureClass::Status(status.as_u16())
|
||||
/// }
|
||||
/// // Don't change errors.
|
||||
/// ServerErrorsFailureClass::Error(error) => {
|
||||
/// NewFailureClass::Error(error)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// enum NewFailureClass {
|
||||
/// Status(u16),
|
||||
/// Error(String),
|
||||
/// }
|
||||
///
|
||||
/// // Create a classifier who's failure class will be transformed by `transform_failure_class`
|
||||
/// let classifier = ServerErrorsAsFailures::new().map_failure_class(transform_failure_class);
|
||||
///
|
||||
/// let response = Response::builder()
|
||||
/// .status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
/// .body(Empty::<Bytes>::new())
|
||||
/// .unwrap();
|
||||
///
|
||||
/// let classification = classifier.classify_response(&response);
|
||||
///
|
||||
/// assert!(matches!(
|
||||
/// classification,
|
||||
/// ClassifiedResponse::Ready(Err(NewFailureClass::Status(500)))
|
||||
/// ));
|
||||
/// ```
|
||||
fn map_failure_class<F, NewClass>(self, f: F) -> MapFailureClass<Self, F>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(Self::FailureClass) -> NewClass,
|
||||
{
|
||||
MapFailureClass::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for classifying end of streams (EOS) as either success or failure.
|
||||
pub trait ClassifyEos {
|
||||
/// The type of failure classifications.
|
||||
type FailureClass;
|
||||
|
||||
/// Perform the classification from response trailers.
|
||||
fn classify_eos(self, trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass>;
|
||||
|
||||
/// Classify an error.
|
||||
///
|
||||
/// Errors are always errors (doh) but sometimes it might be useful to have multiple classes of
|
||||
/// errors. A retry policy might allow retrying some errors and not others.
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static;
|
||||
|
||||
/// Transform the failure classification using a function.
|
||||
///
|
||||
/// See [`ClassifyResponse::map_failure_class`] for more details.
|
||||
fn map_failure_class<F, NewClass>(self, f: F) -> MapFailureClass<Self, F>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(Self::FailureClass) -> NewClass,
|
||||
{
|
||||
MapFailureClass::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of doing a classification.
|
||||
#[derive(Debug)]
|
||||
pub enum ClassifiedResponse<FailureClass, ClassifyEos> {
|
||||
/// The response was able to be classified immediately.
|
||||
Ready(Result<(), FailureClass>),
|
||||
/// We have to wait until the end of a streaming response to classify it.
|
||||
RequiresEos(ClassifyEos),
|
||||
}
|
||||
|
||||
/// A [`ClassifyEos`] type that can be used in [`ClassifyResponse`] implementations that never have
|
||||
/// to classify streaming responses.
|
||||
///
|
||||
/// `NeverClassifyEos` exists only as type. `NeverClassifyEos` values cannot be constructed.
|
||||
pub struct NeverClassifyEos<T> {
|
||||
_output_ty: PhantomData<fn() -> T>,
|
||||
_never: Infallible,
|
||||
}
|
||||
|
||||
impl<T> ClassifyEos for NeverClassifyEos<T> {
|
||||
type FailureClass = T;
|
||||
|
||||
fn classify_eos(self, _trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass> {
|
||||
// `NeverClassifyEos` contains an `Infallible` so it can never be constructed
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, _error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static,
|
||||
{
|
||||
// `NeverClassifyEos` contains an `Infallible` so it can never be constructed
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> fmt::Debug for NeverClassifyEos<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("NeverClassifyEos").finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The default classifier used for normal HTTP responses.
|
||||
///
|
||||
/// Responses with a `5xx` status code are considered failures, all others are considered
|
||||
/// successes.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ServerErrorsAsFailures {
|
||||
_priv: (),
|
||||
}
|
||||
|
||||
impl ServerErrorsAsFailures {
|
||||
/// Create a new [`ServerErrorsAsFailures`].
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Returns a [`MakeClassifier`] that produces `ServerErrorsAsFailures`.
|
||||
///
|
||||
/// This is a convenience function that simply calls `SharedClassifier::new`.
|
||||
pub fn make_classifier() -> SharedClassifier<Self> {
|
||||
SharedClassifier::new(Self::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ClassifyResponse for ServerErrorsAsFailures {
|
||||
type FailureClass = ServerErrorsFailureClass;
|
||||
type ClassifyEos = NeverClassifyEos<ServerErrorsFailureClass>;
|
||||
|
||||
fn classify_response<B>(
|
||||
self,
|
||||
res: &Response<B>,
|
||||
) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
|
||||
if res.status().is_server_error() {
|
||||
ClassifiedResponse::Ready(Err(ServerErrorsFailureClass::StatusCode(res.status())))
|
||||
} else {
|
||||
ClassifiedResponse::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: fmt::Display + 'static,
|
||||
{
|
||||
ServerErrorsFailureClass::Error(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The failure class for [`ServerErrorsAsFailures`].
|
||||
#[derive(Debug)]
|
||||
pub enum ServerErrorsFailureClass {
|
||||
/// A response was classified as a failure with the corresponding status.
|
||||
StatusCode(StatusCode),
|
||||
/// A response was classified as an error with the corresponding error description.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for ServerErrorsFailureClass {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::StatusCode(code) => write!(f, "Status code: {}", code),
|
||||
Self::Error(error) => write!(f, "Error: {}", error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Just verify that we can actually use this response classifier to determine retries as well
|
||||
#[cfg(test)]
|
||||
mod usable_for_retries {
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use http::{Request, Response};
|
||||
use tower::retry::Policy;
|
||||
|
||||
use super::{ClassifiedResponse, ClassifyResponse};
|
||||
|
||||
trait IsRetryable {
|
||||
fn is_retryable(&self) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RetryBasedOnClassification<C> {
|
||||
classifier: C,
|
||||
// ...
|
||||
}
|
||||
|
||||
impl<ReqB, ResB, E, C> Policy<Request<ReqB>, Response<ResB>, E> for RetryBasedOnClassification<C>
|
||||
where
|
||||
C: ClassifyResponse + Clone,
|
||||
E: fmt::Display + 'static,
|
||||
C::FailureClass: IsRetryable,
|
||||
ResB: http_body::Body,
|
||||
Request<ReqB>: Clone,
|
||||
E: std::error::Error + 'static,
|
||||
{
|
||||
type Future = std::future::Ready<()>;
|
||||
|
||||
fn retry(
|
||||
&mut self,
|
||||
_req: &mut Request<ReqB>,
|
||||
res: &mut Result<Response<ResB>, E>,
|
||||
) -> Option<Self::Future> {
|
||||
match res {
|
||||
Ok(res) => {
|
||||
if let ClassifiedResponse::Ready(class) =
|
||||
self.classifier.clone().classify_response(res)
|
||||
{
|
||||
if class.err()?.is_retryable() {
|
||||
return Some(std::future::ready(()));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
Err(err) => self
|
||||
.classifier
|
||||
.clone()
|
||||
.classify_error(err)
|
||||
.is_retryable()
|
||||
.then(|| std::future::ready(())),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_request(&mut self, req: &Request<ReqB>) -> Option<Request<ReqB>> {
|
||||
Some(req.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use super::{ClassifiedResponse, ClassifyResponse, NeverClassifyEos, SharedClassifier};
|
||||
use http::StatusCode;
|
||||
use std::{fmt, ops::RangeInclusive};
|
||||
|
||||
/// Response classifier that considers responses with a status code within some range to be
|
||||
/// failures.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// A client with tracing where server errors _and_ client errors are considered failures.
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tower_http::{trace::TraceLayer, classify::StatusInRangeAsFailures};
|
||||
/// use tower::{ServiceBuilder, Service, ServiceExt};
|
||||
/// use http::{Request, Method};
|
||||
/// use http_body_util::Full;
|
||||
/// use bytes::Bytes;
|
||||
/// use hyper_util::{rt::TokioExecutor, client::legacy::Client};
|
||||
///
|
||||
/// # async fn foo() -> Result<(), tower::BoxError> {
|
||||
/// let classifier = StatusInRangeAsFailures::new(400..=599);
|
||||
///
|
||||
/// let client = Client::builder(TokioExecutor::new()).build_http();
|
||||
/// let mut client = ServiceBuilder::new()
|
||||
/// .layer(TraceLayer::new(classifier.into_make_classifier()))
|
||||
/// .service(client);
|
||||
///
|
||||
/// let request = Request::builder()
|
||||
/// .method(Method::GET)
|
||||
/// .uri("https://example.com")
|
||||
/// .body(Full::<Bytes>::default())
|
||||
/// .unwrap();
|
||||
///
|
||||
/// let response = client.ready().await?.call(request).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StatusInRangeAsFailures {
|
||||
range: RangeInclusive<u16>,
|
||||
}
|
||||
|
||||
impl StatusInRangeAsFailures {
|
||||
/// Creates a new `StatusInRangeAsFailures`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the start or end of `range` aren't valid status codes as determined by
|
||||
/// [`StatusCode::from_u16`].
|
||||
///
|
||||
/// [`StatusCode::from_u16`]: https://docs.rs/http/latest/http/status/struct.StatusCode.html#method.from_u16
|
||||
pub fn new(range: RangeInclusive<u16>) -> Self {
|
||||
assert!(
|
||||
StatusCode::from_u16(*range.start()).is_ok(),
|
||||
"range start isn't a valid status code"
|
||||
);
|
||||
assert!(
|
||||
StatusCode::from_u16(*range.end()).is_ok(),
|
||||
"range end isn't a valid status code"
|
||||
);
|
||||
|
||||
Self { range }
|
||||
}
|
||||
|
||||
/// Creates a new `StatusInRangeAsFailures` that classifies client and server responses as
|
||||
/// failures.
|
||||
///
|
||||
/// This is a convenience for `StatusInRangeAsFailures::new(400..=599)`.
|
||||
pub fn new_for_client_and_server_errors() -> Self {
|
||||
Self::new(400..=599)
|
||||
}
|
||||
|
||||
/// Convert this `StatusInRangeAsFailures` into a [`MakeClassifier`].
|
||||
///
|
||||
/// [`MakeClassifier`]: super::MakeClassifier
|
||||
pub fn into_make_classifier(self) -> SharedClassifier<Self> {
|
||||
SharedClassifier::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ClassifyResponse for StatusInRangeAsFailures {
|
||||
type FailureClass = StatusInRangeFailureClass;
|
||||
type ClassifyEos = NeverClassifyEos<Self::FailureClass>;
|
||||
|
||||
fn classify_response<B>(
|
||||
self,
|
||||
res: &http::Response<B>,
|
||||
) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
|
||||
if self.range.contains(&res.status().as_u16()) {
|
||||
let class = StatusInRangeFailureClass::StatusCode(res.status());
|
||||
ClassifiedResponse::Ready(Err(class))
|
||||
} else {
|
||||
ClassifiedResponse::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_error<E>(self, error: &E) -> Self::FailureClass
|
||||
where
|
||||
E: std::fmt::Display + 'static,
|
||||
{
|
||||
StatusInRangeFailureClass::Error(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The failure class for [`StatusInRangeAsFailures`].
|
||||
#[derive(Debug)]
|
||||
pub enum StatusInRangeFailureClass {
|
||||
/// A response was classified as a failure with the corresponding status.
|
||||
StatusCode(StatusCode),
|
||||
/// A response was classified as an error with the corresponding error description.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for StatusInRangeFailureClass {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::StatusCode(code) => write!(f, "Status code: {}", code),
|
||||
Self::Error(error) => write!(f, "Error: {}", error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use http::Response;
|
||||
|
||||
#[test]
|
||||
fn basic() {
|
||||
let classifier = StatusInRangeAsFailures::new(400..=599);
|
||||
|
||||
assert!(matches!(
|
||||
classifier
|
||||
.clone()
|
||||
.classify_response(&response_with_status(200)),
|
||||
ClassifiedResponse::Ready(Ok(())),
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
classifier
|
||||
.clone()
|
||||
.classify_response(&response_with_status(400)),
|
||||
ClassifiedResponse::Ready(Err(StatusInRangeFailureClass::StatusCode(
|
||||
StatusCode::BAD_REQUEST
|
||||
))),
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
classifier.classify_response(&response_with_status(500)),
|
||||
ClassifiedResponse::Ready(Err(StatusInRangeFailureClass::StatusCode(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
))),
|
||||
));
|
||||
}
|
||||
|
||||
fn response_with_status(status: u16) -> Response<()> {
|
||||
Response::builder().status(status).body(()).unwrap()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user