Better compression choices

This commit is contained in:
Alex 2021-12-09 16:03:19 +01:00
parent 9b30f2b7d1
commit 64cfb30a85
No known key found for this signature in database
GPG key ID: EDABF9711E244EB1
2 changed files with 28 additions and 6 deletions

View file

@ -115,7 +115,7 @@ async fn handle(
.to_str()? .to_str()?
}; };
let path = req.uri().path(); let path = req.uri().path();
let accept_encoding = accept_encoding_fork::parse(req.headers()).unwrap_or(None); let accept_encoding = accept_encoding_fork::encodings(req.headers()).unwrap_or(vec![]);
let best_match = proxy_config let best_match = proxy_config
.entries .entries
@ -179,11 +179,29 @@ async fn handle(
fn try_compress( fn try_compress(
response: Response<Body>, response: Response<Body>,
accept_encoding: Option<Encoding>, accept_encoding: Vec<(Option<Encoding>, f32)>,
https_config: &HttpsConfig, https_config: &HttpsConfig,
) -> Result<Response<Body>> { ) -> Result<Response<Body>> {
// Check if a compression encoding is accepted let max_q: f32 = accept_encoding
let encoding = match accept_encoding { .iter()
.max_by_key(|(_, q)| (q * 10000f32) as i64)
.unwrap_or(&(None, 1.))
.1;
let preference = [
Encoding::Zstd,
Encoding::Brotli,
Encoding::Deflate,
Encoding::Gzip,
];
let encoding_opt = accept_encoding
.iter()
.filter(|(_, q)| *q == max_q)
.filter_map(|(enc, _)| *enc)
.filter(|enc| preference.contains(enc))
.min_by_key(|enc| preference.iter().position(|x| x == enc).unwrap());
// If preferred encoding is none, return as is
let encoding = match encoding_opt {
None | Some(Encoding::Identity) => return Ok(response), None | Some(Encoding::Identity) => return Ok(response),
Some(enc) => enc, Some(enc) => enc,
}; };
@ -197,7 +215,11 @@ fn try_compress(
match response.headers().get(header::CONTENT_TYPE) { match response.headers().get(header::CONTENT_TYPE) {
Some(ct) => { Some(ct) => {
let ct_str = ct.to_str()?; let ct_str = ct.to_str()?;
if !https_config.compress_mime_types.iter().any(|x| x == ct_str) { let mime_type = match ct_str.split_once(';') {
Some((mime_type, _params)) => mime_type,
None => ct_str,
};
if !https_config.compress_mime_types.iter().any(|x| x == mime_type) {
return Ok(response); return Ok(response);
} }
} }

View file

@ -67,7 +67,7 @@ struct Opt {
#[structopt( #[structopt(
long = "compress-mime-types", long = "compress-mime-types",
env = "TRICOT_COMPRESS_MIME_TYPES", env = "TRICOT_COMPRESS_MIME_TYPES",
default_value = "text/html,text/plain,text/css,text/javascript,application/javascript,image/svg+xml" default_value = "text/html,text/plain,text/css,text/javascript,application/javascript,image/svg+xml,font/ttf"
)] )]
pub compress_mime_types: String, pub compress_mime_types: String,
} }