From 9381c9a555826f763d9b423b3af32d517e48d685 Mon Sep 17 00:00:00 2001 From: Casey Primozic Date: Thu, 13 Apr 2023 18:33:42 -0600 Subject: [PATCH] Override default brotli compression level 11 -> 4 The `brotli` crate used by `async-compression` has a default compression level of 11, which is the maximum for brotli. This causes extremely slow compression performance for many response bodies and is definitely an inappropriate compression level for dynamic content. There's currently an open issue (https://github.com/dropbox/rust-brotli/issues/93) on the `brotli` crate's repo to change this default, but it hasn't happened at this time. This change adds a special case to convert a provided compression level of default to a compression level of 4, which is a reasonable default for dynamic content. --- tower-http/src/compression/body.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tower-http/src/compression/body.rs b/tower-http/src/compression/body.rs index eeb798ba..d2a7c549 100644 --- a/tower-http/src/compression/body.rs +++ b/tower-http/src/compression/body.rs @@ -332,7 +332,16 @@ where type Output = BrotliEncoder; fn apply(input: Self::Input, quality: CompressionLevel) -> Self::Output { - BrotliEncoder::with_quality(input, quality.into_async_compression()) + // The brotli crate used under the hood here has a default compression level of 11, + // which is the max for brotli. This causes extremely slow compression times, so we + // manually set a default of 4 here. + // + // This is the same default used by NGINX for on-the-fly brotli compression. + let level = match quality { + CompressionLevel::Default => async_compression::Level::Precise(4), + other => other.into_async_compression(), + }; + BrotliEncoder::with_quality(input, level) } fn get_pin_mut(pinned: Pin<&mut Self::Output>) -> Pin<&mut Self::Input> {