Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override default brotli compression level 11 -> 4 #356

Merged
merged 2 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion tower-http/src/compression/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,16 @@ where
type Output = BrotliEncoder<Self::Input>;

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> {
Expand Down
10 changes: 8 additions & 2 deletions tower-http/src/compression/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ mod tests {

#[tokio::test]
async fn accept_encoding_configuration_works() -> Result<(), crate::BoxError> {
let deflate_only_layer = CompressionLayer::new().no_br().no_gzip();
let deflate_only_layer = CompressionLayer::new()
.quality(CompressionLevel::Best)
.no_br()
.no_gzip();

let mut service = ServiceBuilder::new()
// Compress responses based on the `Accept-Encoding` header.
Expand All @@ -173,7 +176,10 @@ mod tests {

let deflate_bytes_len = bytes.len();

let br_only_layer = CompressionLayer::new().no_gzip().no_deflate();
let br_only_layer = CompressionLayer::new()
.quality(CompressionLevel::Best)
.no_gzip()
.no_deflate();

let mut service = ServiceBuilder::new()
// Compress responses based on the `Accept-Encoding` header.
Expand Down