rama_http/layer/compression/service.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 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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
use super::body::BodyInner;
use super::predicate::{DefaultPredicate, Predicate};
use super::CompressionBody;
use super::CompressionLevel;
use crate::dep::http_body::Body;
use crate::layer::util::compression::WrapBody;
use crate::layer::util::{compression::AcceptEncoding, content_encoding::Encoding};
use crate::{header, Request, Response};
use rama_core::{Context, Service};
use rama_utils::macros::define_inner_service_accessors;
/// Compress response bodies of the underlying service.
///
/// This uses the `Accept-Encoding` header to pick an appropriate encoding and adds the
/// `Content-Encoding` header to responses.
///
/// See the [module docs](crate::layer::compression) for more details.
pub struct Compression<S, P = DefaultPredicate> {
pub(crate) inner: S,
pub(crate) accept: AcceptEncoding,
pub(crate) predicate: P,
pub(crate) quality: CompressionLevel,
}
impl<S, P> std::fmt::Debug for Compression<S, P>
where
S: std::fmt::Debug,
P: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Compression")
.field("inner", &self.inner)
.field("accept", &self.accept)
.field("predicate", &self.predicate)
.field("quality", &self.quality)
.finish()
}
}
impl<S, P> Clone for Compression<S, P>
where
S: Clone,
P: Clone,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
accept: self.accept,
predicate: self.predicate.clone(),
quality: self.quality,
}
}
}
impl<S> Compression<S, DefaultPredicate> {
/// Creates a new `Compression` wrapping the `service`.
pub fn new(service: S) -> Compression<S, DefaultPredicate> {
Self {
inner: service,
accept: AcceptEncoding::default(),
predicate: DefaultPredicate::default(),
quality: CompressionLevel::default(),
}
}
}
impl<S, P> Compression<S, P> {
define_inner_service_accessors!();
/// Sets whether to enable the gzip encoding.
pub fn gzip(mut self, enable: bool) -> Self {
self.accept.set_gzip(enable);
self
}
/// Sets whether to enable the gzip encoding.
pub fn set_gzip(&mut self, enable: bool) -> &mut Self {
self.accept.set_gzip(enable);
self
}
/// Sets whether to enable the Deflate encoding.
pub fn deflate(mut self, enable: bool) -> Self {
self.accept.set_deflate(enable);
self
}
/// Sets whether to enable the Deflate encoding.
pub fn set_deflate(&mut self, enable: bool) -> &mut Self {
self.accept.set_deflate(enable);
self
}
/// Sets whether to enable the Brotli encoding.
pub fn br(mut self, enable: bool) -> Self {
self.accept.set_br(enable);
self
}
/// Sets whether to enable the Brotli encoding.
pub fn set_br(&mut self, enable: bool) -> &mut Self {
self.accept.set_br(enable);
self
}
/// Sets whether to enable the Zstd encoding.
pub fn zstd(mut self, enable: bool) -> Self {
self.accept.set_zstd(enable);
self
}
/// Sets whether to enable the Zstd encoding.
pub fn set_zstd(&mut self, enable: bool) -> &mut Self {
self.accept.set_zstd(enable);
self
}
/// Sets the compression quality.
pub fn quality(mut self, quality: CompressionLevel) -> Self {
self.quality = quality;
self
}
/// Sets the compression quality.
pub fn set_quality(&mut self, quality: CompressionLevel) -> &mut Self {
self.quality = quality;
self
}
/// Replace the current compression predicate.
///
/// Predicates are used to determine whether a response should be compressed or not.
///
/// The default predicate is [`DefaultPredicate`]. See its documentation for more
/// details on which responses it wont compress.
///
/// # Changing the compression predicate
///
/// ```
/// use rama_http::layer::compression::{
/// Compression,
/// predicate::{Predicate, NotForContentType, DefaultPredicate},
/// };
/// use rama_core::service::service_fn;
///
/// // Placeholder service_fn
/// let service = service_fn(|_: ()| async {
/// Ok::<_, std::io::Error>(rama_http::Response::new(()))
/// });
///
/// // build our custom compression predicate
/// // its recommended to still include `DefaultPredicate` as part of
/// // custom predicates
/// let predicate = DefaultPredicate::new()
/// // don't compress responses who's `content-type` starts with `application/json`
/// .and(NotForContentType::new("application/json"));
///
/// let service = Compression::new(service).compress_when(predicate);
/// ```
///
/// See [`predicate`](super::predicate) for more utilities for building compression predicates.
///
/// Responses that are already compressed (ie have a `content-encoding` header) will _never_ be
/// recompressed, regardless what they predicate says.
pub fn compress_when<C>(self, predicate: C) -> Compression<S, C>
where
C: Predicate,
{
Compression {
inner: self.inner,
accept: self.accept,
predicate,
quality: self.quality,
}
}
}
impl<ReqBody, ResBody, S, P, State> Service<State, Request<ReqBody>> for Compression<S, P>
where
S: Service<State, Request<ReqBody>, Response = Response<ResBody>>,
ResBody: Body<Data: Send + 'static, Error: Send + 'static> + Send + 'static,
P: Predicate + Send + Sync + 'static,
ReqBody: Send + 'static,
State: Clone + Send + Sync + 'static,
{
type Response = Response<CompressionBody<ResBody>>;
type Error = S::Error;
#[allow(unreachable_code, unused_mut, unused_variables, unreachable_patterns)]
async fn serve(
&self,
ctx: Context<State>,
req: Request<ReqBody>,
) -> Result<Self::Response, Self::Error> {
let encoding = Encoding::from_headers(req.headers(), self.accept);
let res = self.inner.serve(ctx, req).await?;
// never recompress responses that are already compressed
let should_compress = !res.headers().contains_key(header::CONTENT_ENCODING)
// never compress responses that are ranges
&& !res.headers().contains_key(header::CONTENT_RANGE)
&& self.predicate.should_compress(&res);
let (mut parts, body) = res.into_parts();
if should_compress {
parts
.headers
.append(header::VARY, header::ACCEPT_ENCODING.into());
}
let body = match (should_compress, encoding) {
// if compression is _not_ supported or the client doesn't accept it
(false, _) | (_, Encoding::Identity) => {
return Ok(Response::from_parts(
parts,
CompressionBody::new(BodyInner::identity(body)),
))
}
(_, Encoding::Gzip) => {
CompressionBody::new(BodyInner::gzip(WrapBody::new(body, self.quality)))
}
(_, Encoding::Deflate) => {
CompressionBody::new(BodyInner::deflate(WrapBody::new(body, self.quality)))
}
(_, Encoding::Brotli) => {
CompressionBody::new(BodyInner::brotli(WrapBody::new(body, self.quality)))
}
(_, Encoding::Zstd) => {
CompressionBody::new(BodyInner::zstd(WrapBody::new(body, self.quality)))
}
#[allow(unreachable_patterns)]
(true, _) => {
// This should never happen because the `AcceptEncoding` struct which is used to determine
// `self.encoding` will only enable the different compression algorithms if the
// corresponding crate feature has been enabled. This means
// Encoding::[Gzip|Brotli|Deflate] should be impossible at this point without the
// features enabled.
//
// The match arm is still required though because the `fs` feature uses the
// Encoding struct independently and requires no compression logic to be enabled.
// This means a combination of an individual compression feature and `fs` will fail
// to compile without this branch even though it will never be reached.
//
// To safeguard against refactors that changes this relationship or other bugs the
// server will return an uncompressed response instead of panicking since that could
// become a ddos attack vector.
return Ok(Response::from_parts(
parts,
CompressionBody::new(BodyInner::identity(body)),
));
}
};
parts.headers.remove(header::ACCEPT_RANGES);
parts.headers.remove(header::CONTENT_LENGTH);
parts
.headers
.insert(header::CONTENT_ENCODING, encoding.into_header_value());
let res = Response::from_parts(parts, body);
Ok(res)
}
}