Skip to main content

tower_http/compression/
predicate.rs

1//! Predicates for disabling compression of responses.
2//!
3//! Predicates are applied with [`Compression::compress_when`] or
4//! [`CompressionLayer::compress_when`].
5//!
6//! [`Compression::compress_when`]: super::Compression::compress_when
7//! [`CompressionLayer::compress_when`]: super::CompressionLayer::compress_when
8
9use http::{header, Extensions, HeaderMap, StatusCode, Version};
10use http_body::Body;
11use std::{fmt, sync::Arc};
12
13/// Predicate used to determine if a response should be compressed or not.
14pub trait Predicate: Clone {
15    /// Should this response be compressed or not?
16    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
17    where
18        B: Body;
19
20    /// Combine two predicates into one.
21    ///
22    /// The resulting predicate enables compression if both inner predicates do.
23    fn and<Other>(self, other: Other) -> And<Self, Other>
24    where
25        Self: Sized,
26        Other: Predicate,
27    {
28        And {
29            lhs: self,
30            rhs: other,
31        }
32    }
33}
34
35impl<F> Predicate for F
36where
37    F: Fn(StatusCode, Version, &HeaderMap, &Extensions) -> bool + Clone,
38{
39    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
40    where
41        B: Body,
42    {
43        let status = response.status();
44        let version = response.version();
45        let headers = response.headers();
46        let extensions = response.extensions();
47        self(status, version, headers, extensions)
48    }
49}
50
51impl<T> Predicate for Option<T>
52where
53    T: Predicate,
54{
55    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
56    where
57        B: Body,
58    {
59        self.as_ref()
60            .map(|inner| inner.should_compress(response))
61            .unwrap_or(true)
62    }
63}
64
65/// Two predicates combined into one.
66///
67/// Created with [`Predicate::and`]
68#[derive(Debug, Clone, Default, Copy)]
69pub struct And<Lhs, Rhs> {
70    lhs: Lhs,
71    rhs: Rhs,
72}
73
74impl<Lhs, Rhs> Predicate for And<Lhs, Rhs>
75where
76    Lhs: Predicate,
77    Rhs: Predicate,
78{
79    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
80    where
81        B: Body,
82    {
83        self.lhs.should_compress(response) && self.rhs.should_compress(response)
84    }
85}
86
87/// The default predicate used by [`Compression`] and [`CompressionLayer`].
88///
89/// This will compress responses unless:
90///
91/// - They're gRPC, which has its own protocol specific compression scheme.
92/// - It's an image as determined by the `content-type` starting with `image/`.
93/// - They're Server-Sent Events (SSE) as determined by the `content-type` being `text/event-stream`.
94/// - The response is less than 32 bytes.
95///
96/// # Configuring the defaults
97///
98/// `DefaultPredicate` doesn't support any configuration. Instead you can build your own predicate
99/// by combining types in this module:
100///
101/// ```rust
102/// use tower_http::compression::predicate::{SizeAbove, NotForContentType, Predicate};
103///
104/// // slightly large min size than the default 32
105/// let predicate = SizeAbove::new(256)
106///     // still don't compress gRPC
107///     .and(NotForContentType::GRPC)
108///     // still don't compress images
109///     .and(NotForContentType::IMAGES)
110///     // also don't compress JSON
111///     .and(NotForContentType::const_new("application/json"));
112/// ```
113///
114/// [`Compression`]: super::Compression
115/// [`CompressionLayer`]: super::CompressionLayer
116#[derive(Clone)]
117pub struct DefaultPredicate(
118    And<And<And<SizeAbove, NotForContentType>, NotForContentType>, NotForContentType>,
119);
120
121impl DefaultPredicate {
122    /// Create a new `DefaultPredicate`.
123    pub fn new() -> Self {
124        let inner = SizeAbove::new(SizeAbove::DEFAULT_MIN_SIZE)
125            .and(NotForContentType::GRPC)
126            .and(NotForContentType::IMAGES)
127            .and(NotForContentType::SSE);
128        Self(inner)
129    }
130}
131
132impl Default for DefaultPredicate {
133    fn default() -> Self {
134        Self::new()
135    }
136}
137
138impl Predicate for DefaultPredicate {
139    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
140    where
141        B: Body,
142    {
143        self.0.should_compress(response)
144    }
145}
146
147/// [`Predicate`] that will only allow compression of responses above a certain size.
148#[derive(Clone, Copy, Debug)]
149pub struct SizeAbove(u16);
150
151impl SizeAbove {
152    pub(crate) const DEFAULT_MIN_SIZE: u16 = 32;
153
154    /// Create a new `SizeAbove` predicate that will only compress responses larger than
155    /// `min_size_bytes`.
156    ///
157    /// The response will be compressed if the exact size cannot be determined through either the
158    /// `content-length` header or [`Body::size_hint`].
159    pub const fn new(min_size_bytes: u16) -> Self {
160        Self(min_size_bytes)
161    }
162}
163
164impl Default for SizeAbove {
165    fn default() -> Self {
166        Self(Self::DEFAULT_MIN_SIZE)
167    }
168}
169
170impl Predicate for SizeAbove {
171    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
172    where
173        B: Body,
174    {
175        let content_size = response.body().size_hint().exact().or_else(|| {
176            response
177                .headers()
178                .get(header::CONTENT_LENGTH)
179                .and_then(|h| h.to_str().ok())
180                .and_then(|val| val.parse().ok())
181        });
182
183        match content_size {
184            Some(size) => size >= (self.0 as u64),
185            _ => true,
186        }
187    }
188}
189
190/// Predicate that wont allow responses with a specific `content-type` to be compressed.
191#[derive(Clone, Debug)]
192pub struct NotForContentType {
193    content_type: Str,
194    exception: Option<Str>,
195}
196
197impl NotForContentType {
198    /// Predicate that wont compress gRPC responses.
199    pub const GRPC: Self = Self {
200        content_type: Str::Static("application/grpc"),
201        exception: Some(Str::Static("application/grpc-web")),
202    };
203
204    /// Predicate that wont compress images.
205    pub const IMAGES: Self = Self {
206        content_type: Str::Static("image/"),
207        exception: Some(Str::Static("image/svg+xml")),
208    };
209
210    /// Predicate that wont compress Server-Sent Events (SSE) responses.
211    pub const SSE: Self = Self::const_new("text/event-stream");
212
213    /// Create a new `NotForContentType`.
214    pub fn new(content_type: &str) -> Self {
215        Self {
216            content_type: Str::Shared(content_type.into()),
217            exception: None,
218        }
219    }
220
221    /// Create a new `NotForContentType` from a static string.
222    pub const fn const_new(content_type: &'static str) -> Self {
223        Self {
224            content_type: Str::Static(content_type),
225            exception: None,
226        }
227    }
228}
229
230impl Predicate for NotForContentType {
231    fn should_compress<B>(&self, response: &http::Response<B>) -> bool
232    where
233        B: Body,
234    {
235        let cty = content_type(response);
236        if let Some(except) = &self.exception {
237            if cty.starts_with(except.as_str()) {
238                return true;
239            }
240        }
241
242        !cty.starts_with(self.content_type.as_str())
243    }
244}
245
246#[derive(Clone)]
247enum Str {
248    Static(&'static str),
249    Shared(Arc<str>),
250}
251
252impl Str {
253    fn as_str(&self) -> &str {
254        match self {
255            Str::Static(s) => s,
256            Str::Shared(s) => s,
257        }
258    }
259}
260
261impl fmt::Debug for Str {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        match self {
264            Self::Static(inner) => inner.fmt(f),
265            Self::Shared(inner) => inner.fmt(f),
266        }
267    }
268}
269
270fn content_type<B>(response: &http::Response<B>) -> &str {
271    response
272        .headers()
273        .get(header::CONTENT_TYPE)
274        .and_then(|h| h.to_str().ok())
275        .unwrap_or_default()
276}