1use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9use bytes::Bytes;
10use http::header::{
11 ACCEPT_ENCODING, ACCEPT_RANGES, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE,
12 CONTENT_TYPE, ETAG, VARY,
13};
14use http::{HeaderMap, HeaderValue, Method, Request, Response, StatusCode};
15use http_body::Body as HttpBody;
16use navree_kernel::BoxError;
17use pin_project_lite::pin_project;
18use tower::{Layer, Service};
19
20use crate::body::Body;
21use crate::route::RouteMeta;
22
23mod gzip;
24
25use gzip::GzipBody;
26
27const MIN_SIZE: u64 = 32;
29
30#[derive(Clone, Copy, Debug, Default)]
84pub struct CompressionLayer {
85 _private: (),
86}
87
88impl CompressionLayer {
89 pub fn new() -> Self {
91 Self::default()
92 }
93}
94
95impl<S> Layer<S> for CompressionLayer {
96 type Service = Compression<S>;
97
98 fn layer(&self, inner: S) -> Compression<S> {
99 Compression { inner }
100 }
101}
102
103#[derive(Clone, Copy, Debug)]
105pub struct Compression<S> {
106 inner: S,
107}
108
109impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for Compression<S>
110where
111 S: Service<Request<ReqBody>, Response = Response<ResBody>>,
112 ResBody: HttpBody<Data = Bytes> + Send + 'static,
113 ResBody::Error: Into<BoxError>,
114{
115 type Response = Response<Body>;
116 type Error = S::Error;
117 type Future = ResponseFuture<S::Future>;
118
119 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
120 self.inner.poll_ready(cx)
121 }
122
123 fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
124 let gzip = accepts_gzip(request.headers());
125 let head = request.method() == Method::HEAD;
126 ResponseFuture {
127 future: self.inner.call(request),
128 gzip,
129 head,
130 }
131 }
132}
133
134pin_project! {
135 pub struct ResponseFuture<F> {
137 #[pin]
138 future: F,
139 gzip: bool,
140 head: bool,
141 }
142}
143
144impl<F, B, E> Future for ResponseFuture<F>
145where
146 F: Future<Output = Result<Response<B>, E>>,
147 B: HttpBody<Data = Bytes> + Send + 'static,
148 B::Error: Into<BoxError>,
149{
150 type Output = Result<Response<Body>, E>;
151
152 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
153 let this = self.project();
154 let response = match this.future.poll(cx) {
155 Poll::Ready(Ok(response)) => response,
156 Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
157 Poll::Pending => return Poll::Pending,
158 };
159 Poll::Ready(Ok(compress(response, *this.gzip, *this.head)))
160 }
161}
162
163fn compress<B>(response: Response<B>, gzip: bool, head: bool) -> Response<Body>
167where
168 B: HttpBody<Data = Bytes> + Send + 'static,
169 B::Error: Into<BoxError>,
170{
171 let compressible = compressible(&response, head);
172 let varies = compressible || stands_in_for_a_varying_response(&response);
173 let (mut parts, body) = response.into_parts();
174 if varies && !varies_with_accept_encoding(&parts.headers) {
175 parts
176 .headers
177 .append(VARY, HeaderValue::from_static("accept-encoding"));
178 }
179 if !(compressible && gzip) {
180 return Response::from_parts(parts, Body::new(body));
181 }
182 parts.headers.remove(ACCEPT_RANGES);
183 parts.headers.remove(CONTENT_LENGTH);
184 weaken_etag(&mut parts.headers);
185 parts
186 .headers
187 .insert(CONTENT_ENCODING, HeaderValue::from_static("gzip"));
188 if head {
189 return Response::from_parts(parts, Body::new(body));
190 }
191 Response::from_parts(parts, Body::new(GzipBody::new(body)))
192}
193
194fn weaken_etag(headers: &mut HeaderMap) {
197 let weak = headers.get(ETAG).and_then(|etag| {
198 let etag = etag.as_bytes();
199 let strong = etag.starts_with(b"\"");
200 strong.then(|| HeaderValue::from_bytes(&[b"W/", etag].concat()).ok())?
201 });
202 if let Some(weak) = weak {
203 headers.insert(ETAG, weak);
204 }
205}
206
207pub fn may_compress<B>(response: &Response<B>) -> bool {
229 !opted_out(response) && !no_transform(response.headers())
230}
231
232fn opted_out<B>(response: &Response<B>) -> bool {
234 response
235 .extensions()
236 .get::<Arc<RouteMeta>>()
237 .is_some_and(|route| route.no_compression)
238}
239
240fn stands_in_for_a_varying_response<B>(response: &Response<B>) -> bool {
244 let headers = response.headers();
245 response.status() == StatusCode::NOT_MODIFIED
246 && !opted_out(response)
247 && !headers.contains_key(CONTENT_ENCODING)
248 && !no_transform(headers)
249}
250
251fn compressible<B: HttpBody>(response: &Response<B>, head: bool) -> bool {
255 let headers = response.headers();
256 if !may_compress(response)
257 || !has_a_body(response.status())
258 || response.status() == StatusCode::PARTIAL_CONTENT
260 || headers.contains_key(CONTENT_ENCODING)
261 || headers.contains_key(CONTENT_RANGE)
262 {
263 return false;
264 }
265 let length = || {
266 headers
267 .get(CONTENT_LENGTH)
268 .and_then(|value| value.to_str().ok())
269 .and_then(|value| value.parse::<u64>().ok())
270 };
271 let size = if head {
272 length()
273 } else {
274 response.body().size_hint().exact().or_else(length)
275 };
276 if size.is_some_and(|size| size < MIN_SIZE) {
277 return false;
278 }
279 let content_type = headers
280 .get(CONTENT_TYPE)
281 .map(HeaderValue::as_bytes)
282 .unwrap_or_default();
283 let is = |prefix: &str| {
285 content_type
286 .get(..prefix.len())
287 .is_some_and(|start| start.eq_ignore_ascii_case(prefix.as_bytes()))
288 };
289 let excluded = |prefix: &str, except: Option<&str>| is(prefix) && !except.is_some_and(is);
290 !(excluded("application/grpc", Some("application/grpc-web"))
291 || excluded("image/", Some("image/svg+xml"))
292 || excluded("text/event-stream", None))
293}
294
295fn has_a_body(status: StatusCode) -> bool {
298 !(status.is_informational()
299 || matches!(
300 status,
301 StatusCode::NO_CONTENT | StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED
302 ))
303}
304
305fn no_transform(headers: &HeaderMap) -> bool {
308 headers
309 .get_all(CACHE_CONTROL)
310 .iter()
311 .flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
312 .any(|directive| directive.trim_ascii().eq_ignore_ascii_case(b"no-transform"))
313}
314
315fn varies_with_accept_encoding(headers: &HeaderMap) -> bool {
318 const NAME: &[u8] = b"accept-encoding";
319 headers.get_all(VARY).iter().any(|value| {
320 value
321 .as_bytes()
322 .windows(NAME.len())
323 .any(|window| window.eq_ignore_ascii_case(NAME))
324 })
325}
326
327#[derive(Clone, Copy, PartialEq)]
329enum Coding {
330 Identity,
331 Gzip,
332}
333
334pub(crate) fn accepts_gzip(headers: &HeaderMap) -> bool {
337 let mut gzip = 0;
338 let mut identity = 0;
339 let items = headers
340 .get_all(ACCEPT_ENCODING)
341 .iter()
342 .filter_map(|value| value.to_str().ok())
343 .flat_map(|value| value.split(','));
344 for item in items {
345 let (name, weight) = match item.split_once(';') {
346 Some((name, weight)) => (name, weight_of(weight.trim())),
347 None => (item, Some(1000)),
348 };
349 let coding = match name.trim() {
350 name if name.eq_ignore_ascii_case("gzip") || name.eq_ignore_ascii_case("x-gzip") => {
351 Coding::Gzip
352 }
353 name if name.eq_ignore_ascii_case("identity") => Coding::Identity,
354 _ => continue,
355 };
356 let Some(weight) = weight else { continue };
357 let best = match coding {
358 Coding::Gzip => &mut gzip,
359 Coding::Identity => &mut identity,
360 };
361 *best = (*best).max(weight);
362 }
363 gzip > 0 && gzip >= identity
365}
366
367fn weight_of(text: &str) -> Option<u16> {
370 let rest = text
371 .strip_prefix("q=")
372 .or_else(|| text.strip_prefix("Q="))?;
373 let mut chars = rest.chars();
374 let mut weight = match chars.next()? {
375 '0' => 0,
376 '1' => 1000,
377 _ => return None,
378 };
379 match chars.next() {
380 None => return Some(weight),
381 Some('.') => {}
382 Some(_) => return None,
383 }
384 let mut factor = 100;
385 for char in chars {
386 let digit = char.to_digit(10)?;
387 if factor == 0 {
388 return None;
389 }
390 weight += factor * digit as u16;
391 factor /= 10;
392 }
393 (weight <= 1000).then_some(weight)
394}
395
396#[cfg(test)]
397mod tests;