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
use http_encoding::{encoder, Coder, ContentEncoding};

use crate::{
    body::{BodyStream, NONE_BODY_HINT},
    http::{header::HeaderMap, BorrowReq, WebResponse},
    service::{ready::ReadyService, Service},
};

/// A compress middleware look into [WebRequest]'s `Accept-Encoding` header and
/// apply according compression to [WebResponse]'s body according to enabled compress feature.
/// `compress-x` feature must be enabled for this middleware to function correctly.
///
/// # Type mutation
/// `Compress` would mutate response body type from `B` to `Coder<B>`. Service enclosed
/// by it must be able to handle it's mutation or utilize [TypeEraser] to erase the mutation.
///
/// [WebRequest]: crate::http::WebRequest
/// [TypeEraser]: crate::middleware::eraser::TypeEraser
#[derive(Clone)]
pub struct Compress;

impl<S, E> Service<Result<S, E>> for Compress {
    type Response = CompressService<S>;
    type Error = E;

    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
        res.map(CompressService)
    }
}

pub struct CompressService<S>(S);

impl<S, Req, ResB> Service<Req> for CompressService<S>
where
    Req: BorrowReq<HeaderMap>,
    S: Service<Req, Response = WebResponse<ResB>>,
    ResB: BodyStream,
{
    type Response = WebResponse<Coder<ResB>>;
    type Error = S::Error;

    async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
        let mut encoding = ContentEncoding::from_headers(req.borrow());
        let res = self.0.call(req).await?;

        // TODO: expose encoding filter as public api.
        match res.body().size_hint() {
            (low, Some(up)) if low == up && low < 64 => encoding = ContentEncoding::NoOp,
            // this variant is a crate hack. see NONE_BODY_HINT for detail.
            NONE_BODY_HINT => encoding = ContentEncoding::NoOp,
            _ => {}
        }

        Ok(encoder(res, encoding))
    }
}

impl<S> ReadyService for CompressService<S>
where
    S: ReadyService,
{
    type Ready = S::Ready;

    #[inline]
    async fn ready(&self) -> Self::Ready {
        self.0.ready().await
    }
}

#[cfg(test)]
mod test {
    use xitca_unsafe_collection::futures::NowOrPanic;

    use crate::{handler::handler_service, http::WebRequest, App};

    use super::*;

    #[test]
    fn build() {
        async fn noop() -> &'static str {
            "noop"
        }

        App::new()
            .at("/", handler_service(noop))
            .enclosed(Compress)
            .finish()
            .call(())
            .now_or_panic()
            .unwrap()
            .call(WebRequest::default())
            .now_or_panic()
            .ok()
            .unwrap();
    }
}