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

Do compress grpc-web responses #408

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions tower-http/src/compression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,31 @@ mod tests {
assert_eq!(res.headers()[CONTENT_ENCODING], "gzip");
}

#[tokio::test]
async fn does_compress_grpc_web() {
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Error> {
let mut res = Response::new(Body::from(
"a".repeat((SizeAbove::DEFAULT_MIN_SIZE * 2) as usize),
));
res.headers_mut()
.insert(CONTENT_TYPE, "application/grpc-web+proto".parse().unwrap());
Ok(res)
}

let svc = Compression::new(service_fn(handle));

let res = svc
.oneshot(
Request::builder()
.header(ACCEPT_ENCODING, "gzip")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.headers()[CONTENT_ENCODING], "gzip");
}

#[tokio::test]
async fn compress_with_quality() {
const DATA: &str = "Check compression quality level! Check compression quality level! Check compression quality level!";
Expand Down
10 changes: 7 additions & 3 deletions tower-http/src/compression/predicate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,10 @@ pub struct NotForContentType {

impl NotForContentType {
/// Predicate that wont compress gRPC responses.
pub const GRPC: Self = Self::const_new("application/grpc");
pub const GRPC: Self = Self {
content_type: Str::Static("application/grpc"),
exception: Some(Str::Static("application/grpc-web")),
};

/// Predicate that wont compress images.
pub const IMAGES: Self = Self {
Expand Down Expand Up @@ -222,13 +225,14 @@ impl Predicate for NotForContentType {
where
B: Body,
{
let cty = content_type(response);
if let Some(except) = &self.exception {
if content_type(response) == except.as_str() {
if cty.starts_with(except.as_str()) {
return true;
}
}

!content_type(response).starts_with(self.content_type.as_str())
!cty.starts_with(self.content_type.as_str())
}
}

Expand Down