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
use std::future::Future;
use std::pin::Pin;

#[cfg(feature = "brotli")]
use async_compression::futures::bufread::BrotliEncoder;
#[cfg(feature = "deflate")]
use async_compression::futures::bufread::DeflateEncoder;
#[cfg(feature = "gzip")]
use async_compression::futures::bufread::GzipEncoder;
use futures_util::io::BufReader;
use http_types::{headers, Body};
use regex::Regex;
use tide::http::Method;
use tide::{Middleware, Next, Request, Response};

use crate::Encoding;

const THRESHOLD: usize = 1024;

/// A middleware for compressing response body data.
#[derive(Debug, Clone)]
pub struct CompressMiddleware {
    threshold: usize,
}

impl Default for CompressMiddleware {
    fn default() -> Self {
        CompressMiddleware {
            threshold: THRESHOLD,
        }
    }
}

impl CompressMiddleware {
    /// Creates a new CompressMiddleware.
    ///
    /// Uses the default minimum body size threshold (1024 bytes).
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new CompressMiddleware with a custom minimum body size threshold.
    ///
    /// # Arguments
    ///
    /// * `threshold` - minimum body size in bytes.
    pub fn with_threshold(threshold: usize) -> Self {
        CompressMiddleware { threshold }
    }
}

impl<State: Send + Sync + 'static> Middleware<State> for CompressMiddleware {
    fn handle<'a>(
        &'a self,
        req: Request<State>,
        next: Next<'a, State>,
    ) -> Pin<Box<dyn Future<Output = tide::Result> + Send + 'a>> {
        Box::pin(async move {
            // Incoming Request data
            // Need to grab these things before the request is consumed by `next.run()`.
            let is_head = req.method() == Method::Head;
            let accepts_encoding = accepts_encoding(&req);

            // Propagate to route
            let mut res: Response = next.run(req).await?;

            // Head requests should have no body to compress.
            // Can't tell if we can compress if there is no Accepts-Encoding header.
            if is_head || accepts_encoding.is_none() {
                return Ok(res);
            }

            // Should we transform?
            if let Some(cache_control) = res.header(headers::CACHE_CONTROL) {
                // No compression for `Cache-Control: no-transform`
                // https://tools.ietf.org/html/rfc7234#section-5.2.2.4
                let regex = Regex::new(r"(?:^|,)\s*?no-transform\s*?(?:,|$)").unwrap();
                if regex.is_match(cache_control.as_str()) {
                    return Ok(res);
                }
            }

            // Check if an encoding may already exist.
            // Can't tell if we should compress if an encoding set.
            if let Some(previous_encoding) = res.header(headers::CONTENT_ENCODING) {
                if previous_encoding.iter().any(|v| v.as_str() != "identity") {
                    return Ok(res);
                }
            }

            let body = res.take_body();

            // Check body length against threshold.
            if let Some(body_len) = body.len() {
                if body_len < self.threshold {
                    res.set_body(body);
                    return Ok(res);
                }
            }

            let encoding = accepts_encoding.unwrap();

            // Get a new Body backed by an appropriate encoder, if one is available.
            res.set_body(get_encoder(body, &encoding));
            let mut res = res.set_header(headers::CONTENT_ENCODING, get_encoding_name(&encoding));

            // End size no longer matches body size, so any existing Content-Length is useless.
            res.remove_header(headers::CONTENT_LENGTH);

            Ok(res)
        })
    }
}

/// Gets an `Encoding` that matches up to the Accept-Encoding value.
fn accepts_encoding<State: Send + Sync + 'static>(req: &Request<State>) -> Option<Encoding> {
    let header = req.header(headers::ACCEPT_ENCODING);

    if header.is_none() {
        return None;
    }

    let header_values = header.unwrap();

    #[cfg(feature = "brotli")]
    {
        if header_values.iter().any(|v| v.as_str() == "br") {
            return Some(Encoding::BROTLI);
        }
    }

    #[cfg(feature = "gzip")]
    {
        if header_values.iter().any(|v| v.as_str() == "gzip") {
            return Some(Encoding::GZIP);
        }
    }

    #[cfg(feature = "deflate")]
    {
        if header_values.iter().any(|v| v.as_str() == "deflate") {
            return Some(Encoding::DEFLATE);
        }
    }

    None
}

/// Returns a `Body` made from an encoder chosen from the `Encoding`.
fn get_encoder(body: Body, encoding: &Encoding) -> Body {
    #[cfg(feature = "brotli")]
    {
        if *encoding == Encoding::BROTLI {
            return Body::from_reader(BufReader::new(BrotliEncoder::new(body)), None);
        }
    }

    #[cfg(feature = "gzip")]
    {
        if *encoding == Encoding::GZIP {
            return Body::from_reader(BufReader::new(GzipEncoder::new(body)), None);
        }
    }

    #[cfg(feature = "deflate")]
    {
        if *encoding == Encoding::DEFLATE {
            return Body::from_reader(BufReader::new(DeflateEncoder::new(body)), None);
        }
    }

    body
}

/// Maps an `Encoding` to a Content-Encoding string.
fn get_encoding_name(encoding: &Encoding) -> String {
    (match *encoding {
        Encoding::BROTLI => "br",
        Encoding::GZIP => "gzip",
        Encoding::DEFLATE => "deflate",
    })
    .to_string()
}