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
use super::*;
impl Default for CompressionConfig {
/// Builds the configuration the compression 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 rules the configuration works from.
///
/// The encodings that are not known are left out, so the plugin never
/// answers with an encoding it cannot write.
///
/// # Returns
///
/// - `CompressionPolicy` - The rules of the configuration.
fn policy(&self) -> CompressionPolicy {
CompressionPolicy {
encodings: self
.get_encodings()
.iter()
.filter(|encoding: &&Compress| !encoding.is_unknown())
.map(|encoding: &Compress| encoding.to_string())
.collect(),
min_size: self.get_min_size(),
}
}
/// 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 encoding: String = self.policy().pick(accept)?;
encoding.parse::<Compress>().ok()
}
/// 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 {
CompressionPolicy::is_compressible(content_type)
}
}
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> {
let policy: CompressionPolicy = config.policy();
CONFIG
.set(config)
.map_err(|_: CompressionConfig| MESSAGE_ALREADY_SET.to_owned())?;
POLICY
.set(policy)
.map_err(|_: CompressionPolicy| MESSAGE_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 policy: &CompressionPolicy = match POLICY.get() {
Some(policy) => policy,
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: String = match policy.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() < policy.get_min_size() {
return Status::Continue;
}
let content_type: String = response
.try_get_header_back(CONTENT_TYPE)
.unwrap_or_default();
if !CompressionPolicy::is_compressible(&content_type) {
return Status::Continue;
}
response.set_header(CONTENT_ENCODING, encoding);
response.set_header(VARY, VARY_ACCEPT_ENCODING);
Status::Continue
}
}