1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 21:39:26 +00:00
actix-web/src/middleware/compress.rs

280 lines
8.2 KiB
Rust
Raw Normal View History

//! For middleware documentation, see [`Compress`].
use std::{
future::Future,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
2022-01-03 13:17:57 +00:00
use actix_http::encoding::Encoder;
2019-03-05 05:37:57 +00:00
use actix_service::{Service, Transform};
use actix_utils::future::{ok, Either, Ready};
2021-01-17 05:19:32 +00:00
use futures_core::ready;
use once_cell::sync::Lazy;
use pin_project_lite::pin_project;
2019-03-02 06:51:32 +00:00
use crate::{
2022-01-03 13:17:57 +00:00
body::{EitherBody, MessageBody},
dev::BodyEncoding as _,
http::{
header::{self, AcceptEncoding, Encoding, HeaderValue},
StatusCode,
},
service::{ServiceRequest, ServiceResponse},
2022-01-03 13:17:57 +00:00
Error, HttpMessage, HttpResponse,
};
2019-03-02 06:51:32 +00:00
/// Middleware for compressing response payloads.
///
/// Use `BodyEncoding` trait for overriding response compression. To disable compression set
/// encoding to `ContentEncoding::Identity`.
///
2021-02-10 12:10:03 +00:00
/// # Examples
/// ```
/// use actix_web::{web, middleware, App, HttpResponse};
///
/// let app = App::new()
/// .wrap(middleware::Compress::default())
/// .default_service(web::to(|| HttpResponse::NotFound()));
/// ```
2022-01-03 13:17:57 +00:00
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Compress;
2019-03-02 06:51:32 +00:00
impl<S, B> Transform<S, ServiceRequest> for Compress
2019-03-05 05:37:57 +00:00
where
B: MessageBody,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-05 05:37:57 +00:00
{
2021-12-04 19:40:47 +00:00
type Response = ServiceResponse<EitherBody<Encoder<B>>>;
2019-04-25 18:14:32 +00:00
type Error = Error;
2019-03-05 05:37:57 +00:00
type Transform = CompressMiddleware<S>;
type InitError = ();
2019-11-20 17:33:22 +00:00
type Future = Ready<Result<Self::Transform, Self::InitError>>;
2019-03-05 05:37:57 +00:00
fn new_transform(&self, service: S) -> Self::Future {
2022-01-03 13:17:57 +00:00
ok(CompressMiddleware { service })
2019-03-05 05:37:57 +00:00
}
}
pub struct CompressMiddleware<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for CompressMiddleware<S>
2019-03-02 06:51:32 +00:00
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody,
2019-03-02 06:51:32 +00:00
{
2021-12-04 19:40:47 +00:00
type Response = ServiceResponse<EitherBody<Encoder<B>>>;
2019-04-25 18:14:32 +00:00
type Error = Error;
2021-12-25 04:53:51 +00:00
#[allow(clippy::type_complexity)]
type Future = Either<CompressResponse<S, B>, Ready<Result<Self::Response, Self::Error>>>;
2019-03-02 06:51:32 +00:00
actix_service::forward_ready!(service);
2019-03-02 06:51:32 +00:00
#[allow(clippy::borrow_interior_mutable_const)]
fn call(&self, req: ServiceRequest) -> Self::Future {
2019-03-02 06:51:32 +00:00
// negotiate content-encoding
2022-01-03 13:17:57 +00:00
let accept_encoding = req.get_header::<AcceptEncoding>();
let accept_encoding = match accept_encoding {
// missing header; fallback to identity
None => {
return Either::left(CompressResponse {
encoding: Encoding::identity(),
fut: self.service.call(req),
_phantom: PhantomData,
})
}
2019-03-02 06:51:32 +00:00
2022-01-03 13:17:57 +00:00
// valid accept-encoding header
Some(accept_encoding) => accept_encoding,
};
2022-01-03 13:17:57 +00:00
match accept_encoding.negotiate(SUPPORTED_ENCODINGS.iter()) {
None => {
let mut res = HttpResponse::with_body(
2021-12-04 19:40:47 +00:00
StatusCode::NOT_ACCEPTABLE,
2022-01-03 13:17:57 +00:00
SUPPORTED_ENCODINGS_STRING.as_str(),
2021-12-04 19:40:47 +00:00
);
2022-01-03 13:17:57 +00:00
res.headers_mut()
.insert(header::VARY, HeaderValue::from_static("Accept-Encoding"));
2021-12-04 19:40:47 +00:00
Either::right(ok(req
.into_response(res)
.map_into_boxed_body()
.map_into_right_body()))
}
2022-01-03 13:17:57 +00:00
Some(encoding) => Either::left(CompressResponse {
fut: self.service.call(req),
encoding,
_phantom: PhantomData,
}),
2019-03-02 06:51:32 +00:00
}
}
}
pin_project! {
pub struct CompressResponse<S, B>
where
S: Service<ServiceRequest>,
{
#[pin]
fut: S::Future,
2022-01-03 13:17:57 +00:00
encoding: Encoding,
_phantom: PhantomData<B>,
}
2019-03-02 06:51:32 +00:00
}
impl<S, B> Future for CompressResponse<S, B>
2019-03-02 06:51:32 +00:00
where
B: MessageBody,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-02 06:51:32 +00:00
{
2021-12-04 19:40:47 +00:00
type Output = Result<ServiceResponse<EitherBody<Encoder<B>>>, Error>;
2019-11-20 17:33:22 +00:00
2019-12-07 18:46:51 +00:00
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2019-11-20 17:33:22 +00:00
let this = self.project();
2021-01-17 05:19:32 +00:00
match ready!(this.fut.poll(cx)) {
2019-11-20 17:33:22 +00:00
Ok(resp) => {
2022-01-03 13:17:57 +00:00
let enc = if let Some(enc) = resp.response().preferred_encoding() {
2019-12-16 11:22:26 +00:00
enc
2019-11-20 17:33:22 +00:00
} else {
2022-01-03 13:17:57 +00:00
match this.encoding {
Encoding::Known(enc) => *enc,
Encoding::Unknown(enc) => {
unimplemented!("encoding {} should not be here", enc);
}
}
2019-11-20 17:33:22 +00:00
};
Poll::Ready(Ok(resp.map_body(move |head, body| {
2021-12-04 19:40:47 +00:00
EitherBody::left(Encoder::response(enc, head, body))
})))
2019-11-20 17:33:22 +00:00
}
2021-12-04 19:40:47 +00:00
Err(err) => Poll::Ready(Err(err)),
2019-11-20 17:33:22 +00:00
}
2019-03-02 06:51:32 +00:00
}
}
2022-01-03 13:17:57 +00:00
static SUPPORTED_ENCODINGS_STRING: Lazy<String> = Lazy::new(|| {
#[allow(unused_mut)] // only unused when no compress features enabled
let mut encoding: Vec<&str> = vec![];
2019-03-02 06:51:32 +00:00
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-brotli")]
{
encoding.push("br");
}
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-gzip")]
{
encoding.push("gzip");
encoding.push("deflate");
2019-03-02 06:51:32 +00:00
}
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-zstd")]
{
encoding.push("zstd");
}
2022-01-03 13:17:57 +00:00
assert!(
!encoding.is_empty(),
"encoding can not be empty unless __compress feature has been explicitly enabled by itself"
);
2022-01-03 13:17:57 +00:00
encoding.join(", ")
});
2022-01-03 13:17:57 +00:00
static SUPPORTED_ENCODINGS: Lazy<Vec<Encoding>> = Lazy::new(|| {
let mut encodings = vec![Encoding::identity()];
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-brotli")]
{
encodings.push(Encoding::brotli());
}
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-gzip")]
{
encodings.push(Encoding::gzip());
encodings.push(Encoding::deflate());
}
2022-01-03 13:17:57 +00:00
#[cfg(feature = "compress-zstd")]
{
encodings.push(Encoding::zstd());
}
2022-01-03 13:17:57 +00:00
assert!(
!encodings.is_empty(),
"encodings can not be empty unless __compress feature has been explicitly enabled by itself"
);
2022-01-03 13:17:57 +00:00
encodings
});
2022-01-03 14:05:08 +00:00
// move cfg(feature) to prevents_double_compressing if more tests are added
#[cfg(feature = "compress-gzip")]
#[cfg(test)]
mod tests {
use super::*;
use crate::{middleware::DefaultHeaders, test, web, App};
pub fn gzip_decode(bytes: impl AsRef<[u8]>) -> Vec<u8> {
use std::io::Read as _;
let mut decoder = flate2::read::GzDecoder::new(bytes.as_ref());
let mut buf = Vec::new();
decoder.read_to_end(&mut buf).unwrap();
buf
}
#[actix_rt::test]
async fn prevents_double_compressing() {
const D: &str = "hello world ";
const DATA: &str = const_str::repeat!(D, 100);
let app = test::init_service({
App::new()
.wrap(Compress::default())
.route(
"/single",
web::get().to(move || HttpResponse::Ok().body(DATA)),
)
.service(
web::resource("/double")
.wrap(Compress::default())
.wrap(DefaultHeaders::new().add(("x-double", "true")))
.route(web::get().to(move || HttpResponse::Ok().body(DATA))),
)
})
.await;
let req = test::TestRequest::default()
.uri("/single")
.insert_header((header::ACCEPT_ENCODING, "gzip"))
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.headers().get("x-double"), None);
assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "gzip");
let bytes = test::read_body(res).await;
assert_eq!(gzip_decode(bytes), DATA.as_bytes());
let req = test::TestRequest::default()
.uri("/double")
.insert_header((header::ACCEPT_ENCODING, "gzip"))
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.headers().get("x-double").unwrap(), "true");
assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "gzip");
let bytes = test::read_body(res).await;
assert_eq!(gzip_decode(bytes), DATA.as_bytes());
}
}