use std::io::Write as _;
use axum::Router;
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::header::{self, HeaderValue};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use flate2::Compression as GzipLevel;
use flate2::write::GzEncoder;
const MAX_BODY: usize = 64 * 1024 * 1024;
#[derive(Clone, Copy)]
struct Settings {
threshold: u64,
}
pub(super) fn layer(router: Router, threshold: u64) -> Router {
router.layer(axum::middleware::from_fn_with_state(
Settings { threshold },
apply,
))
}
async fn apply(State(settings): State<Settings>, request: Request, next: Next) -> Response {
let accepts = accepts_gzip(request.headers());
let head = request.method() == http::Method::HEAD;
let response = next.run(request).await;
if !accepts
|| head
|| response.headers().contains_key(header::CONTENT_ENCODING)
|| !is_compressible(&response)
|| matches!(
response.status(),
http::StatusCode::NO_CONTENT | http::StatusCode::NOT_MODIFIED
)
{
return response;
}
let (parts, body) = response.into_parts();
let bytes = match axum::body::to_bytes(body, MAX_BODY).await {
Ok(bytes) => bytes,
Err(error) => {
tracing::error!(%error, "the HTTP response body is not collected for compression");
return http::StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
};
let mut parts = parts;
vary(&mut parts.headers);
if settings.threshold > 0 && (bytes.len() as u64) < settings.threshold {
parts.headers.insert(
header::CONTENT_LENGTH,
HeaderValue::from_str(&bytes.len().to_string())
.unwrap_or(HeaderValue::from_static("0")),
);
return Response::from_parts(parts, Body::from(bytes));
}
let compressed = match gzip(&bytes) {
Ok(compressed) => compressed,
Err(error) => {
tracing::error!(%error, "the HTTP response body is not compressed");
return http::StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
};
parts.headers.remove(header::CONTENT_LENGTH);
parts
.headers
.insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip"));
Response::from_parts(parts, Body::from(compressed))
}
fn accepts_gzip(headers: &http::HeaderMap) -> bool {
let Some(value) = headers.get(header::ACCEPT_ENCODING) else {
return false;
};
let Ok(value) = value.to_str() else {
return false;
};
value.split(',').any(|entry| {
let mut parts = entry.trim().split(';');
let name = parts.next().unwrap_or("").trim();
if !name.eq_ignore_ascii_case("gzip") && name != "*" {
return false;
}
parts.all(|parameter| {
let parameter = parameter.trim();
!parameter
.strip_prefix("q=")
.and_then(|weight| weight.parse::<f32>().ok())
.is_some_and(|weight| weight <= 0.0)
})
})
}
fn is_compressible(response: &Response) -> bool {
let Some(value) = response.headers().get(header::CONTENT_TYPE) else {
return false;
};
let Ok(value) = value.to_str() else {
return false;
};
let value = value.split(';').next().unwrap_or(value).trim();
if value.eq_ignore_ascii_case("text/event-stream") {
return false;
}
value.starts_with("text/")
|| value.eq_ignore_ascii_case("application/json")
|| value.eq_ignore_ascii_case("application/javascript")
|| value.eq_ignore_ascii_case("application/xml")
|| (value.starts_with("application/")
&& (value.ends_with("+json") || value.ends_with("+xml")))
}
fn vary(headers: &mut http::HeaderMap) {
let value = headers
.get(header::VARY)
.and_then(|value| value.to_str().ok())
.map_or_else(
|| "Accept-Encoding".to_owned(),
|value| format!("{value}, Accept-Encoding"),
);
if let Ok(value) = HeaderValue::from_str(&value) {
headers.insert(header::VARY, value);
}
}
fn gzip(bytes: &[u8]) -> std::io::Result<Vec<u8>> {
let mut encoder = GzEncoder::new(Vec::new(), GzipLevel::default());
encoder.write_all(bytes)?;
encoder.finish()
}