1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use crate::compression_utils::AcceptEncoding;
use http::{header, HeaderMap, HeaderValue};
mod body;
mod future;
mod layer;
mod service;
pub use self::{
body::CompressionBody, future::ResponseFuture, layer::CompressionLayer, service::Compression,
};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum Encoding {
#[cfg(feature = "compression-gzip")]
Gzip,
#[cfg(feature = "compression-deflate")]
Deflate,
#[cfg(feature = "compression-br")]
Brotli,
Identity,
}
impl Encoding {
fn to_str(self) -> &'static str {
match self {
#[cfg(feature = "compression-gzip")]
Encoding::Gzip => "gzip",
#[cfg(feature = "compression-deflate")]
Encoding::Deflate => "deflate",
#[cfg(feature = "compression-br")]
Encoding::Brotli => "br",
Encoding::Identity => "identity",
}
}
fn into_header_value(self) -> HeaderValue {
HeaderValue::from_static(self.to_str())
}
#[allow(unused_variables)]
fn parse(s: &str, accept: AcceptEncoding) -> Option<Encoding> {
match s {
#[cfg(feature = "compression-gzip")]
"gzip" if accept.gzip() => Some(Encoding::Gzip),
#[cfg(feature = "compression-deflate")]
"deflate" if accept.deflate() => Some(Encoding::Deflate),
#[cfg(feature = "compression-br")]
"br" if accept.br() => Some(Encoding::Brotli),
"identity" => Some(Encoding::Identity),
_ => None,
}
}
fn from_headers(headers: &HeaderMap, accept: AcceptEncoding) -> Self {
let mut preferred_encoding = None;
let mut max_qval = 0.0;
for (encoding, qval) in encodings(headers, accept) {
if (qval - 1.0f32).abs() < 0.01 {
preferred_encoding = Some(encoding);
break;
} else if qval > max_qval {
preferred_encoding = Some(encoding);
max_qval = qval;
}
}
preferred_encoding.unwrap_or(Encoding::Identity)
}
}
fn encodings(headers: &HeaderMap, accept: AcceptEncoding) -> Vec<(Encoding, f32)> {
headers
.get_all(header::ACCEPT_ENCODING)
.iter()
.filter_map(|hval| hval.to_str().ok())
.flat_map(|s| s.split(',').map(str::trim))
.filter_map(|v| {
let mut v = v.splitn(2, ";q=");
let encoding = match Encoding::parse(v.next().unwrap(), accept) {
Some(encoding) => encoding,
None => return None,
};
let qval = if let Some(qval) = v.next() {
let qval = match qval.parse::<f32>() {
Ok(f) => f,
Err(_) => return None,
};
if qval > 1.0 {
return None;
}
qval
} else {
1.0f32
};
Some((encoding, qval))
})
.collect::<Vec<(Encoding, f32)>>()
}
#[cfg(test)]
mod tests {
use super::*;
use async_compression::tokio::write::{BrotliDecoder, BrotliEncoder};
use bytes::BytesMut;
use flate2::read::GzDecoder;
use http_body::Body as _;
use hyper::{Body, Error, Request, Response, Server};
use std::{io::Read, net::SocketAddr};
use tokio::io::AsyncWriteExt;
use tower::{make::Shared, service_fn, Service, ServiceExt};
#[tokio::test]
async fn works() {
let svc = service_fn(handle);
let mut svc = Compression::new(svc);
let req = Request::builder()
.header("accept-encoding", "gzip")
.body(Body::empty())
.unwrap();
let res = svc.ready().await.unwrap().call(req).await.unwrap();
let mut body = res.into_body();
let mut data = BytesMut::new();
while let Some(chunk) = body.data().await {
let chunk = chunk.unwrap();
data.extend_from_slice(&chunk[..]);
}
let compressed_data = data.freeze().to_vec();
let mut decoder = GzDecoder::new(&compressed_data[..]);
let mut decompressed = String::new();
decoder.read_to_string(&mut decompressed).unwrap();
assert_eq!(decompressed, "Hello, World!");
}
#[allow(dead_code)]
async fn is_compatible_with_hyper() {
let svc = service_fn(handle);
let svc = Compression::new(svc);
let make_service = Shared::new(svc);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let server = Server::bind(&addr).serve(make_service);
server.await.unwrap();
}
#[tokio::test]
async fn no_recompress() {
const DATA: &str = "Hello, World! I'm already compressed with br!";
let svc = service_fn(|_| async {
let buf = {
let mut buf = Vec::new();
let mut enc = BrotliEncoder::new(&mut buf);
enc.write_all(DATA.as_bytes()).await?;
enc.flush().await?;
buf
};
let resp = Response::builder()
.header("content-encoding", "br")
.body(Body::from(buf))
.unwrap();
Ok::<_, std::io::Error>(resp)
});
let mut svc = Compression::new(svc);
let req = Request::builder()
.header("accept-encoding", "gzip")
.body(Body::empty())
.unwrap();
let res = svc.ready().await.unwrap().call(req).await.unwrap();
assert_eq!(
res.headers()
.get("content-encoding")
.and_then(|h| h.to_str().ok())
.unwrap_or_default(),
"br",
);
let mut body = res.into_body();
let mut data = BytesMut::new();
while let Some(chunk) = body.data().await {
let chunk = chunk.unwrap();
data.extend_from_slice(&chunk[..]);
}
let data = {
let mut output_buf = Vec::new();
let mut decoder = BrotliDecoder::new(&mut output_buf);
decoder
.write_all(&data)
.await
.expect("couldn't brotli-decode");
decoder.flush().await.expect("couldn't flush");
output_buf
};
assert_eq!(data, DATA.as_bytes());
}
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Error> {
Ok(Response::new(Body::from("Hello, World!")))
}
}