Skip to content

Commit 3962dba

Browse files
boukjlizen
andauthored
Do compress grpc-web responses (#408)
* Do compress grpc-web responses * fix: use Infallible instead of unresolved Error type in test --------- Co-authored-by: Jess Izen <44884346+jlizen@users.noreply.github.com>
1 parent f0b3bb6 commit 3962dba

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

tower-http/src/compression/mod.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,31 @@ mod tests {
388388
assert_eq!(res.headers()[CONTENT_ENCODING], "gzip");
389389
}
390390

391+
#[tokio::test]
392+
async fn does_compress_grpc_web() {
393+
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
394+
let mut res = Response::new(Body::from(
395+
"a".repeat((SizeAbove::DEFAULT_MIN_SIZE * 2) as usize),
396+
));
397+
res.headers_mut()
398+
.insert(CONTENT_TYPE, "application/grpc-web+proto".parse().unwrap());
399+
Ok(res)
400+
}
401+
402+
let svc = Compression::new(service_fn(handle));
403+
404+
let res = svc
405+
.oneshot(
406+
Request::builder()
407+
.header(ACCEPT_ENCODING, "gzip")
408+
.body(Body::empty())
409+
.unwrap(),
410+
)
411+
.await
412+
.unwrap();
413+
assert_eq!(res.headers()[CONTENT_ENCODING], "gzip");
414+
}
415+
391416
#[tokio::test]
392417
async fn compress_with_quality() {
393418
const DATA: &str = "Check compression quality level! Check compression quality level! Check compression quality level!";

tower-http/src/compression/predicate.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,10 @@ pub struct NotForContentType {
196196

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

201204
/// Predicate that wont compress images.
202205
pub const IMAGES: Self = Self {
@@ -229,13 +232,14 @@ impl Predicate for NotForContentType {
229232
where
230233
B: Body,
231234
{
235+
let cty = content_type(response);
232236
if let Some(except) = &self.exception {
233-
if content_type(response) == except.as_str() {
237+
if cty.starts_with(except.as_str()) {
234238
return true;
235239
}
236240
}
237241

238-
!content_type(response).starts_with(self.content_type.as_str())
242+
!cty.starts_with(self.content_type.as_str())
239243
}
240244
}
241245

0 commit comments

Comments
 (0)