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
use super::*;
impl Default for CompressionConfig {
/// Builds the configuration the plugin uses when none is given.
///
/// # Returns
///
/// - `Self` - The default configuration.
fn default() -> Self {
Self {
min_size: DEFAULT_MIN_SIZE,
encodings: vec![Compress::Gzip, Compress::Br],
}
}
}
impl CompressionConfig {
/// The encoding the client asked for, when one of the offered encodings
/// is accepted.
///
/// The offered encodings are tried in the order they are preferred, so the
/// first one the client accepts is the one that is used.
///
/// # Arguments
///
/// - `&str` - The `accept-encoding` header of the request.
///
/// # Returns
///
/// - `Option<Compress>` - The encoding to answer with, when the client
/// accepts one of the offered encodings.
pub fn pick(&self, accept: &str) -> Option<Compress> {
let tokens: Vec<String> = Self::accepted(accept);
for encoding in self.get_encodings().iter() {
if encoding.is_unknown() {
continue;
}
let name: String = encoding.to_string();
if tokens
.iter()
.any(|token: &String| token == TOKEN_ANY || token == &name)
{
return Some(*encoding);
}
}
None
}
/// Whether a body of that content type is worth compressing.
///
/// A body that is already compressed is sent as it is, and the stream of
/// events is never compressed.
///
/// # Arguments
///
/// - `&str` - The content type of the answer.
///
/// # Returns
///
/// - `bool` - Whether the body may be compressed.
pub fn is_compressible(&self, content_type: &str) -> bool {
let content_type: String = content_type.trim().to_lowercase();
if content_type.is_empty() {
return true;
}
if content_type == TEXT_EVENT_STREAM {
return false;
}
if CONTENT_TYPES_COMPRESSED.contains(&content_type.as_str()) {
return false;
}
!CONTENT_TYPE_PREFIXES_COMPRESSED
.iter()
.any(|prefix: &&str| content_type.starts_with(*prefix))
}
/// The encodings the client accepts, without the ones it refused.
///
/// # Arguments
///
/// - `&str` - The `accept-encoding` header of the request.
///
/// # Returns
///
/// - `Vec<String>` - The tokens the client accepts.
fn accepted(accept: &str) -> Vec<String> {
let mut tokens: Vec<String> = Vec::new();
for part in accept.split(SEPARATOR_COMMA) {
let token: String = part.split(';').next().unwrap_or("").trim().to_lowercase();
if token.is_empty() {
continue;
}
let refused: bool = part.split(';').skip(1).any(|parameter: &str| {
let quality: Option<&str> = parameter.trim().strip_prefix(PARAMETER_QUALITY);
match quality {
Some(quality) => quality
.parse::<f32>()
.map(|value: f32| value <= 0.0)
.unwrap_or(false),
None => false,
}
});
if !refused {
tokens.push(token);
}
}
tokens
}
}
impl CompressionPlugin {
/// Stores the configuration the plugin works from.
///
/// # Arguments
///
/// - `CompressionConfig` - The configuration to store.
///
/// # Returns
///
/// - `Result<(), String>` - Nothing, or the reason the configuration was
/// refused.
pub fn init(config: CompressionConfig) -> Result<(), String> {
CONFIG.set(config).map_err(|_: CompressionConfig| {
"the compression configuration was already set".to_owned()
})
}
/// The configuration the plugin works from.
///
/// # Returns
///
/// - `Option<&'static CompressionConfig>` - The configuration, when it was
/// set.
pub fn get() -> Option<&'static CompressionConfig> {
CONFIG.get()
}
}
impl ServerHook for CompressionMiddleware {
/// Builds the middleware.
///
/// # Arguments
///
/// - `&mut Stream` - The stream the request arrived on.
/// - `&mut Context` - The context of the request.
///
/// # Returns
///
/// - `Self` - The middleware.
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
/// Marks the answer with the encoding the client asked for.
///
/// The body is compressed when the answer is built, so the middleware only
/// writes the header that names the encoding.
///
/// # Arguments
///
/// - `Self` - The middleware.
/// - `&mut Stream` - The stream the request arrived on.
/// - `&mut Context` - The context of the request.
///
/// # Returns
///
/// - `Status` - Whether the pipeline continues.
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let config: &CompressionConfig = match CONFIG.get() {
Some(config) => config,
None => return Status::Continue,
};
let accept: String = match ctx.get_request().try_get_header(ACCEPT_ENCODING) {
Some(values) => match values.front() {
Some(value) => value.clone(),
None => return Status::Continue,
},
None => return Status::Continue,
};
let encoding: Compress = match config.pick(&accept) {
Some(encoding) => encoding,
None => return Status::Continue,
};
let response: &mut Response = ctx.get_mut_response();
if response.try_get_header_back(CONTENT_ENCODING).is_some() {
return Status::Continue;
}
if response.get_body().len() < config.get_min_size() {
return Status::Continue;
}
let content_type: String = response
.try_get_header_back(CONTENT_TYPE)
.unwrap_or_default();
if !config.is_compressible(&content_type) {
return Status::Continue;
}
response.set_header(CONTENT_ENCODING, encoding.to_string());
response.set_header(VARY, VARY_ACCEPT_ENCODING);
Status::Continue
}
}