1use bytes::{Buf, Bytes};
33use http::{Request, Response, header};
34use http_body::Body;
35use pin_project_lite::pin_project;
36use std::{
37 future::Future,
38 pin::Pin,
39 task::{Context, Poll, ready},
40};
41use tower::Layer;
42use tower::Service;
43use tower_http::BoxError;
44use tower_http::compression::Predicate;
45use tower_http::compression::predicate::DefaultPredicate;
46
47pub mod compression_utils;
48pub mod content_encoding;
49
50use compression_utils::{
51 AcceptEncoding, AsyncReadBody, CompressionLevel, DecorateAsyncRead,
52 WrapBody,
53};
54use content_encoding::Encoding;
55
56use async_compression::tokio::bufread::BrotliEncoder;
57use async_compression::tokio::bufread::GzipEncoder;
58use async_compression::tokio::bufread::ZlibEncoder;
59
60#[derive(Clone, Debug, Default)]
65pub struct CompressionLayer<P = DefaultPredicate> {
66 accept: AcceptEncoding,
67 predicate: P,
68 quality: CompressionLevel,
69}
70
71impl<S, P> Layer<S> for CompressionLayer<P>
72where
73 P: Predicate,
74{
75 type Service = Compression<S, P>;
76
77 fn layer(&self, inner: S) -> Self::Service {
78 Compression {
79 inner,
80 accept: self.accept,
81 predicate: self.predicate.clone(),
82 quality: self.quality,
83 }
84 }
85}
86
87impl CompressionLayer {
88 pub fn new() -> Self {
90 Self::default()
91 }
92
93 pub fn gzip(mut self, enable: bool) -> Self {
95 self.accept.set_gzip(enable);
96 self
97 }
98
99 pub fn deflate(mut self, enable: bool) -> Self {
101 self.accept.set_deflate(enable);
102 self
103 }
104
105 pub fn br(mut self, enable: bool) -> Self {
107 self.accept.set_br(enable);
108 self
109 }
110
111 pub fn quality(mut self, quality: CompressionLevel) -> Self {
113 self.quality = quality;
114 self
115 }
116
117 pub fn no_gzip(mut self) -> Self {
119 self.accept.set_gzip(false);
120 self
121 }
122
123 pub fn no_deflate(mut self) -> Self {
125 self.accept.set_deflate(false);
126 self
127 }
128
129 pub fn no_br(mut self) -> Self {
131 self.accept.set_br(false);
132 self
133 }
134
135 pub fn no_zstd(mut self) -> Self {
137 self.accept.set_zstd(false);
138 self
139 }
140
141 pub fn compress_when<C>(self, predicate: C) -> CompressionLayer<C>
143 where
144 C: Predicate,
145 {
146 CompressionLayer {
147 accept: self.accept,
148 predicate,
149 quality: self.quality,
150 }
151 }
152}
153
154#[derive(Clone, Copy)]
156pub struct Compression<S, P = DefaultPredicate> {
157 inner: S,
158 accept: AcceptEncoding,
159 predicate: P,
160 quality: CompressionLevel,
161}
162
163impl<S> Compression<S, DefaultPredicate> {
164 pub fn new(service: S) -> Compression<S, DefaultPredicate> {
166 Self {
167 inner: service,
168 accept: AcceptEncoding::default(),
169 predicate: DefaultPredicate::default(),
170 quality: CompressionLevel::default(),
171 }
172 }
173}
174
175impl<S, P> Compression<S, P> {
176 pub fn gzip(mut self, enable: bool) -> Self {
178 self.accept.set_gzip(enable);
179 self
180 }
181
182 pub fn deflate(mut self, enable: bool) -> Self {
184 self.accept.set_deflate(enable);
185 self
186 }
187
188 pub fn br(mut self, enable: bool) -> Self {
190 self.accept.set_br(enable);
191 self
192 }
193
194 pub fn quality(mut self, quality: CompressionLevel) -> Self {
196 self.quality = quality;
197 self
198 }
199
200 pub fn no_gzip(mut self) -> Self {
202 self.accept.set_gzip(false);
203 self
204 }
205
206 pub fn no_deflate(mut self) -> Self {
208 self.accept.set_deflate(false);
209 self
210 }
211
212 pub fn no_br(mut self) -> Self {
214 self.accept.set_br(false);
215 self
216 }
217
218 pub fn no_zstd(mut self) -> Self {
220 self.accept.set_zstd(false);
221 self
222 }
223
224 pub fn compress_when<C>(self, predicate: C) -> Compression<S, C>
226 where
227 C: Predicate,
228 {
229 Compression {
230 inner: self.inner,
231 accept: self.accept,
232 predicate,
233 quality: self.quality,
234 }
235 }
236}
237
238impl<ReqBody, ResBody, S, P> Service<Request<ReqBody>> for Compression<S, P>
239where
240 S: Service<Request<ReqBody>, Response = Response<ResBody>>,
241 ResBody: Body,
242 P: Predicate,
243{
244 type Response = Response<CompressionBody<ResBody>>;
245 type Error = S::Error;
246 type Future = ResponseFuture<S::Future, P>;
247
248 #[inline]
249 fn poll_ready(
250 &mut self,
251 cx: &mut Context<'_>,
252 ) -> Poll<Result<(), S::Error>> {
253 self.inner.poll_ready(cx)
254 }
255
256 fn call(&mut self, req: Request<ReqBody>) -> ResponseFuture<S::Future, P> {
257 let encoding = Encoding::from_headers(req.headers(), self.accept);
258
259 ResponseFuture {
260 inner: self.inner.call(req),
261 encoding,
262 predicate: self.predicate.clone(),
263 quality: self.quality,
264 }
265 }
266}
267
268pin_project! {
269 #[derive(Debug)]
271 pub struct ResponseFuture<F, P> {
272 #[pin]
273 pub(crate) inner: F,
274 pub(crate) encoding: Option<Encoding>,
275 pub(crate) predicate: P,
276 pub(crate) quality: CompressionLevel,
277 }
278}
279
280impl<F, B, E, P> Future for ResponseFuture<F, P>
281where
282 F: Future<Output = Result<Response<B>, E>>,
283 B: Body,
284 P: Predicate,
285{
286 type Output = Result<Response<CompressionBody<B>>, E>;
287
288 fn poll(
289 mut self: Pin<&mut Self>,
290 cx: &mut Context<'_>,
291 ) -> Poll<Self::Output> {
292 let res = ready!(self.as_mut().project().inner.poll(cx)?);
293
294 let should_compress =
296 !res.headers().contains_key(header::CONTENT_ENCODING)
297 && self.predicate.should_compress(&res);
298
299 let (mut parts, body) = res.into_parts();
300
301 if should_compress
302 && !parts.headers.get_all(header::VARY).iter().any(|value| {
303 contains_ignore_ascii_case(
304 value.as_bytes(),
305 header::ACCEPT_ENCODING.as_str().as_bytes(),
306 )
307 })
308 {
309 parts
310 .headers
311 .append(header::VARY, header::ACCEPT_ENCODING.into());
312 }
313
314 let body = match (should_compress, self.encoding) {
315 (false, _)
316 | (_, None | Some(Encoding::Identity | Encoding::Zstd)) => {
317 CompressionBody::new(BodyInner::identity(body))
318 }
319
320 (_, Some(Encoding::Gzip)) => CompressionBody::new(BodyInner::gzip(
321 WrapBody::new(body, self.quality),
322 )),
323 (_, Some(Encoding::Deflate)) => CompressionBody::new(
324 BodyInner::deflate(WrapBody::new(body, self.quality)),
325 ),
326 (_, Some(Encoding::Brotli)) => CompressionBody::new(
327 BodyInner::brotli(WrapBody::new(body, self.quality)),
328 ),
329 };
330
331 parts.headers.remove(header::CONTENT_LENGTH);
333
334 if should_compress {
335 if let Some(enc) = self.encoding {
336 if enc != Encoding::Identity && enc != Encoding::Zstd {
337 parts.headers.insert(
338 header::CONTENT_ENCODING,
339 enc.into_header_value(),
340 );
341 }
342 }
343 }
344
345 let res = Response::from_parts(parts, body);
346 Poll::Ready(Ok(res))
347 }
348}
349
350fn contains_ignore_ascii_case(haystack: &[u8], needle: &[u8]) -> bool {
351 if needle.is_empty() {
352 return true;
353 }
354 haystack
355 .windows(needle.len())
356 .any(|window| window.eq_ignore_ascii_case(needle))
357}
358
359pin_project! {
360 pub struct CompressionBody<B>
362 where
363 B: Body,
364 {
365 #[pin]
366 pub(crate) inner: BodyInner<B>,
367 }
368}
369
370impl<B> Default for CompressionBody<B>
371where
372 B: Body + Default,
373{
374 fn default() -> Self {
375 Self {
376 inner: BodyInner::Identity {
377 inner: B::default(),
378 },
379 }
380 }
381}
382
383impl<B> CompressionBody<B>
384where
385 B: Body,
386{
387 pub(crate) fn new(inner: BodyInner<B>) -> Self {
388 Self { inner }
389 }
390}
391
392pin_project! {
393 #[project = BodyInnerProj]
394 pub(crate) enum BodyInner<B>
395 where
396 B: Body,
397 {
398 Gzip {
399 #[pin]
400 inner: WrapBody<GzipEncoder<B>>,
401 },
402 Deflate {
403 #[pin]
404 inner: WrapBody<ZlibEncoder<B>>,
405 },
406 Brotli {
407 #[pin]
408 inner: WrapBody<BrotliEncoder<B>>,
409 },
410 Identity {
411 #[pin]
412 inner: B,
413 },
414 }
415}
416
417impl<B: Body> BodyInner<B> {
418 pub(crate) fn gzip(inner: WrapBody<GzipEncoder<B>>) -> Self {
419 Self::Gzip { inner }
420 }
421
422 pub(crate) fn deflate(inner: WrapBody<ZlibEncoder<B>>) -> Self {
423 Self::Deflate { inner }
424 }
425
426 pub(crate) fn brotli(inner: WrapBody<BrotliEncoder<B>>) -> Self {
427 Self::Brotli { inner }
428 }
429
430 pub(crate) fn identity(inner: B) -> Self {
431 Self::Identity { inner }
432 }
433}
434
435impl<B> Body for CompressionBody<B>
436where
437 B: Body,
438 B::Error: Into<BoxError>,
439{
440 type Data = Bytes;
441 type Error = BoxError;
442
443 fn poll_frame(
444 self: Pin<&mut Self>,
445 cx: &mut Context<'_>,
446 ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
447 match self.project().inner.project() {
448 BodyInnerProj::Gzip { inner } => inner.poll_frame(cx),
449 BodyInnerProj::Deflate { inner } => inner.poll_frame(cx),
450 BodyInnerProj::Brotli { inner } => inner.poll_frame(cx),
451 BodyInnerProj::Identity { inner } => {
452 match ready!(inner.poll_frame(cx)) {
453 Some(Ok(frame)) => {
454 let frame = frame.map_data(|mut buf| {
455 buf.copy_to_bytes(buf.remaining())
456 });
457 Poll::Ready(Some(Ok(frame)))
458 }
459 Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
460 None => Poll::Ready(None),
461 }
462 }
463 }
464 }
465
466 fn size_hint(&self) -> http_body::SizeHint {
467 if let BodyInner::Identity { inner } = &self.inner {
468 inner.size_hint()
469 } else {
470 http_body::SizeHint::new()
471 }
472 }
473
474 fn is_end_stream(&self) -> bool {
475 if let BodyInner::Identity { inner } = &self.inner {
476 inner.is_end_stream()
477 } else {
478 false
479 }
480 }
481}
482
483impl<B> DecorateAsyncRead for GzipEncoder<B>
484where
485 B: Body,
486{
487 type Input = AsyncReadBody<B>;
488 type Output = GzipEncoder<Self::Input>;
489
490 fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output {
491 GzipEncoder::with_quality(input, quality.into_async_compression())
492 }
493
494 fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input> {
495 pinned.get_pin_mut()
496 }
497}
498
499impl<B> DecorateAsyncRead for ZlibEncoder<B>
500where
501 B: Body,
502{
503 type Input = AsyncReadBody<B>;
504 type Output = ZlibEncoder<Self::Input>;
505
506 fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output {
507 ZlibEncoder::with_quality(input, quality.into_async_compression())
508 }
509
510 fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input> {
511 pinned.get_pin_mut()
512 }
513}
514
515impl<B> DecorateAsyncRead for BrotliEncoder<B>
516where
517 B: Body,
518{
519 type Input = AsyncReadBody<B>;
520 type Output = BrotliEncoder<Self::Input>;
521
522 fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output {
523 let level = match quality {
524 CompressionLevel::Default => async_compression::Level::Precise(4),
525 other => other.into_async_compression(),
526 };
527 BrotliEncoder::with_quality(input, level)
528 }
529
530 fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input> {
531 pinned.get_pin_mut()
532 }
533}
534
535#[cfg(test)]
536#[allow(
537 clippy::panic,
538 clippy::expect_used,
539 clippy::unwrap_used,
540 clippy::unwrap_in_result,
541 clippy::panic_in_result_fn,
542 clippy::indexing_slicing,
543 clippy::arithmetic_side_effects,
544 reason = "Standard repository test boilerplate"
545)]
546mod tests {
547 use super::*;
548 use axum::body::Body as AxumBody;
549 use http::{Request, Response, header::ACCEPT_ENCODING};
550 use http_body_util::BodyExt;
551 use std::convert::Infallible;
552 use tower::{Service, ServiceBuilder, ServiceExt};
553
554 const TEST_PAYLOAD: &[u8] = b"This is a sample payload to verify compression layer deflate and brotli roundtrip encoding.";
555
556 async fn handle(
557 _req: Request<AxumBody>,
558 ) -> Result<Response<AxumBody>, Infallible> {
559 Ok(Response::new(AxumBody::from(TEST_PAYLOAD)))
560 }
561
562 #[crate::ctb_test("tokio")]
563 async fn accept_encoding_configuration_works()
564 -> Result<(), tower_http::BoxError> {
565 use std::io::Read;
566
567 fn decode<R: Read>(mut r: R) -> std::io::Result<Vec<u8>> {
568 let mut buf = Vec::new();
569 r.read_to_end(&mut buf)?;
570 Ok(buf)
571 }
572
573 let expected = TEST_PAYLOAD.to_vec();
574
575 let deflate_only_layer = CompressionLayer::new()
578 .quality(CompressionLevel::Best)
579 .no_br()
580 .no_gzip();
581
582 let mut service = ServiceBuilder::new()
583 .layer(deflate_only_layer)
584 .service_fn(handle);
585
586 let request = Request::builder()
587 .header(ACCEPT_ENCODING, "gzip, deflate, br")
588 .body(AxumBody::empty())?;
589
590 let response = service.ready().await?.call(request).await?;
591
592 assert_eq!(response.headers()["content-encoding"], "deflate");
593
594 let deflate_body = response.into_body().collect().await?.to_bytes();
595
596 let decoded =
599 decode(flate2::bufread::ZlibDecoder::new(&deflate_body[..]))?;
600 assert_eq!(decoded, expected);
601
602 let br_only_layer = CompressionLayer::new()
604 .quality(CompressionLevel::Best)
605 .no_gzip()
606 .no_deflate();
607
608 let mut service = ServiceBuilder::new()
609 .layer(br_only_layer)
610 .service_fn(handle);
611
612 let request = Request::builder()
613 .header(ACCEPT_ENCODING, "gzip, deflate, br")
614 .body(AxumBody::empty())?;
615
616 let response = service.ready().await?.call(request).await?;
617
618 assert_eq!(response.headers()["content-encoding"], "br");
619
620 let br_body = response.into_body().collect().await?.to_bytes();
621
622 let decoded = decode(brotli::Decompressor::new(&br_body[..], 4096))?;
624 assert_eq!(decoded, expected);
625
626 Ok(())
627 }
628}
629
630