forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB0d793e7Tahinli2 hours ago359 commits

compression.rs256 lines, 7.9 KiBHistoryRawDownload
1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use http::header::{CONTENT_ENCODING, CONTENT_RANGE, CONTENT_TYPE};
5use http::{Request, Response};
6use tower_http::CompressionLevel;
7use tower_http::compression::predicate::Predicate;
8
9pub const MIN_BODY: u64 = 32;
10
11pub const MAX_BODY: u64 = 4 * 1024 * 1024;
12
13#[derive(Clone, Copy, Debug)]
14struct NoCompression;
15
16fn is_excluded_path(path: &str) -> bool {
17 path.contains("/api/v1/ci/")
18 || path.contains("/info/refs")
19 || path.contains("/git-upload-pack")
20 || path.contains("/git-receive-pack")
21 || path.contains("/info/lfs")
22 || path.split('/').any(|segment| {
23 matches!(
24 segment,
25 "lfs" | "raw" | "archive" | "download" | "downloads"
26 )
27 })
28}
29
30fn is_compressible(content_type: &str) -> bool {
31 let media = content_type
32 .split(';')
33 .next()
34 .unwrap_or_default()
35 .trim()
36 .to_ascii_lowercase();
37 matches!(
38 media.as_str(),
39 "text/html"
40 | "text/css"
41 | "text/plain"
42 | "text/javascript"
43 | "application/javascript"
44 | "application/json"
45 | "image/svg+xml"
46 )
47}
48
49#[derive(Clone, Copy, Debug)]
50pub struct Policy;
51
52impl Predicate for Policy {
53 fn should_compress<B>(&self, response: &Response<B>) -> bool
54 where
55 B: http_body::Body,
56 {
57 if response.extensions().get::<NoCompression>().is_some() {
58 return false;
59 }
60 let headers = response.headers();
61 if headers.contains_key(CONTENT_ENCODING) || headers.contains_key(CONTENT_RANGE) {
62 return false;
63 }
64 let Some(content_type) = headers.get(CONTENT_TYPE).and_then(|v| v.to_str().ok()) else {
65 return false;
66 };
67 if !is_compressible(content_type) {
68 return false;
69 }
70 let size = response.body().size_hint();
71 size.lower() >= MIN_BODY && size.upper().is_some_and(|upper| upper <= MAX_BODY)
72 }
73}
74
75#[derive(Clone, Copy, Debug)]
76pub struct ResponseCompression;
77
78impl<S> tower::Layer<S> for ResponseCompression {
79 type Service = tower_http::compression::Compression<PathMark<S>, Policy>;
80
81 fn layer(&self, inner: S) -> Self::Service {
82 tower_http::compression::Compression::new(PathMark(inner))
83 .gzip(true)
84 .br(true)
85 .quality(CompressionLevel::Default)
86 .compress_when(Policy)
87 }
88}
89
90#[derive(Clone, Debug)]
91pub struct PathMark<S>(S);
92
93impl<S, B, ResB> tower::Service<Request<B>> for PathMark<S>
94where
95 S: tower::Service<Request<B>, Response = Response<ResB>>,
96 S::Future: Send + 'static,
97 S::Error: Send + 'static,
98 ResB: Send + 'static,
99{
100 type Response = Response<ResB>;
101 type Error = S::Error;
102 type Future =
103 Pin<Box<dyn std::future::Future<Output = Result<Self::Response, S::Error>> + Send>>;
104
105 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
106 self.0.poll_ready(cx)
107 }
108
109 fn call(&mut self, request: Request<B>) -> Self::Future {
110 let excluded = is_excluded_path(request.uri().path());
111 let future = self.0.call(request);
112 Box::pin(async move {
113 let mut response = future.await?;
114 if excluded {
115 response.extensions_mut().insert(NoCompression);
116 }
117 Ok(response)
118 })
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125 use http::Method;
126 use http::header::{ACCEPT_ENCODING, CONTENT_TYPE};
127 use topcoat::context::Cx;
128 use topcoat::router::tower::TowerLayer;
129 use topcoat::router::{Body, Compression, RouteFn, RouteFuture, Router};
130
131 const BIG: &str = "forge compression test body line\n";
132
133 fn big_body() -> String {
134 BIG.repeat(64)
135 }
136
137 macro_rules! typed_route {
138 ($name:ident, $content_type:expr) => {
139 fn $name(_cx: &Cx, _body: Body) -> RouteFuture<'_> {
140 Box::pin(async move {
141 Ok(http::Response::builder()
142 .header(CONTENT_TYPE, $content_type)
143 .body(Body::from(big_body()))
144 .expect("static response"))
145 })
146 }
147 };
148 }
149
150 typed_route!(html_page, "text/html; charset=utf-8");
151 typed_route!(git_refs, "text/html; charset=utf-8");
152 typed_route!(git_pack, "application/x-git-upload-pack-result");
153 typed_route!(raw_text, "text/plain; charset=utf-8");
154 typed_route!(binary, "application/octet-stream");
155
156 fn router() -> Router {
157 Router::builder()
158 .route(RouteFn::new(Method::GET, "/tahinli/demo/page", html_page))
159 .route(RouteFn::new(
160 Method::GET,
161 "/tahinli/demo.git/info/refs",
162 git_refs,
163 ))
164 .route(RouteFn::new(
165 Method::GET,
166 "/tahinli/demo/git-upload-pack",
167 git_pack,
168 ))
169 .route(RouteFn::new(
170 Method::GET,
171 "/tahinli/demo/raw/main/a.txt",
172 raw_text,
173 ))
174 .route(RouteFn::new(Method::GET, "/tahinli/demo/blob.bin", binary))
175 .layer(TowerLayer::new(ResponseCompression))
176 .with(Compression::disable())
177 .build()
178 }
179
180 async fn encoding(router: &Router, path: &str) -> Option<String> {
181 let request = http::Request::builder()
182 .uri(path)
183 .header(ACCEPT_ENCODING, "gzip")
184 .body(Body::empty())
185 .expect("request");
186 let response = router.handle(request).await;
187 response
188 .headers()
189 .get(http::header::CONTENT_ENCODING)
190 .map(|v| v.to_str().expect("ascii").to_owned())
191 }
192
193 #[tokio::test]
194 async fn html_page_is_gzipped() {
195 let router = router();
196 assert_eq!(
197 encoding(&router, "/tahinli/demo/page").await.as_deref(),
198 Some("gzip")
199 );
200 }
201
202 #[tokio::test]
203 async fn git_smart_http_is_never_compressed() {
204 let router = router();
205 assert_eq!(encoding(&router, "/tahinli/demo.git/info/refs").await, None);
206 assert_eq!(
207 encoding(&router, "/tahinli/demo/git-upload-pack").await,
208 None
209 );
210 }
211
212 #[tokio::test]
213 async fn raw_and_binary_are_not_compressed() {
214 let router = router();
215 assert_eq!(
216 encoding(&router, "/tahinli/demo/raw/main/a.txt").await,
217 None
218 );
219 assert_eq!(encoding(&router, "/tahinli/demo/blob.bin").await, None);
220 }
221
222 #[test]
223 fn policy_skips_small_streamed_and_already_encoded_bodies() {
224 let small = Response::builder()
225 .header(CONTENT_TYPE, "text/html")
226 .body(Body::from("tiny"))
227 .expect("response");
228 assert!(!Policy.should_compress(&small));
229
230 let encoded = Response::builder()
231 .header(CONTENT_TYPE, "text/html")
232 .header(CONTENT_ENCODING, "br")
233 .body(Body::from(big_body()))
234 .expect("response");
235 assert!(!Policy.should_compress(&encoded));
236
237 let plain = Response::builder()
238 .header(CONTENT_TYPE, "text/html")
239 .body(Body::from(big_body()))
240 .expect("response");
241 assert!(Policy.should_compress(&plain));
242 }
243
244 #[test]
245 fn path_exclusions_cover_git_lfs_raw_and_archives() {
246 assert!(is_excluded_path("/tahinli/demo.git/info/refs"));
247 assert!(is_excluded_path("/tahinli/demo.git/git-receive-pack"));
248 assert!(is_excluded_path("/tahinli/demo.git/info/lfs/objects/batch"));
249 assert!(is_excluded_path("/tahinli/demo/raw/main/a.txt"));
250 assert!(is_excluded_path("/tahinli/demo/archive/main.zip"));
251 assert!(is_excluded_path(
252 "/tahinli/demo/releases/download/v1/x.tar.gz"
253 ));
254 assert!(!is_excluded_path("/tahinli/demo/tree/main"));
255 }
256}