tower_http/decompression/request/
future.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
use crate::body::UnsyncBoxBody;
use crate::compression_utils::AcceptEncoding;
use crate::BoxError;
use bytes::Buf;
use http::{header, HeaderValue, Response, StatusCode};
use http_body::Body;
use http_body_util::BodyExt;
use http_body_util::Empty;
use pin_project_lite::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

pin_project! {
    #[derive(Debug)]
    /// Response future of [`RequestDecompression`]
    pub struct RequestDecompressionFuture<F, B, E>
    where
        F: Future<Output = Result<Response<B>, E>>,
        B: Body
    {
        #[pin]
        kind: Kind<F, B, E>,
    }
}

pin_project! {
    #[derive(Debug)]
    #[project = StateProj]
    enum Kind<F, B, E>
    where
        F: Future<Output = Result<Response<B>, E>>,
        B: Body
    {
        Inner {
            #[pin]
            fut: F
        },
        Unsupported {
            #[pin]
            accept: AcceptEncoding
        },
    }
}

impl<F, B, E> RequestDecompressionFuture<F, B, E>
where
    F: Future<Output = Result<Response<B>, E>>,
    B: Body,
{
    #[must_use]
    pub(super) fn unsupported_encoding(accept: AcceptEncoding) -> Self {
        Self {
            kind: Kind::Unsupported { accept },
        }
    }

    #[must_use]
    pub(super) fn inner(fut: F) -> Self {
        Self {
            kind: Kind::Inner { fut },
        }
    }
}

impl<F, B, E> Future for RequestDecompressionFuture<F, B, E>
where
    F: Future<Output = Result<Response<B>, E>>,
    B: Body + Send + 'static,
    B::Data: Buf + 'static,
    B::Error: Into<BoxError> + 'static,
{
    type Output = Result<Response<UnsyncBoxBody<B::Data, BoxError>>, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.project().kind.project() {
            StateProj::Inner { fut } => fut.poll(cx).map_ok(|res| {
                res.map(|body| UnsyncBoxBody::new(body.map_err(Into::into).boxed_unsync()))
            }),
            StateProj::Unsupported { accept } => {
                let res = Response::builder()
                    .header(
                        header::ACCEPT_ENCODING,
                        accept
                            .to_header_value()
                            .unwrap_or(HeaderValue::from_static("identity")),
                    )
                    .status(StatusCode::UNSUPPORTED_MEDIA_TYPE)
                    .body(UnsyncBoxBody::new(
                        Empty::new().map_err(Into::into).boxed_unsync(),
                    ))
                    .unwrap();
                Poll::Ready(Ok(res))
            }
        }
    }
}