hyperlane_plugin_compression/impl.rs
1use super::*;
2
3impl Default for CompressionConfig {
4 /// Builds the configuration the plugin uses when none is given.
5 ///
6 /// # Returns
7 ///
8 /// - `Self` - The default configuration.
9 fn default() -> Self {
10 Self {
11 min_size: DEFAULT_MIN_SIZE,
12 encodings: vec![Compress::Gzip, Compress::Br],
13 }
14 }
15}
16
17impl CompressionConfig {
18 /// The encoding the client asked for, when one of the offered encodings
19 /// is accepted.
20 ///
21 /// The offered encodings are tried in the order they are preferred, so the
22 /// first one the client accepts is the one that is used.
23 ///
24 /// # Arguments
25 ///
26 /// - `&str` - The `accept-encoding` header of the request.
27 ///
28 /// # Returns
29 ///
30 /// - `Option<Compress>` - The encoding to answer with, when the client
31 /// accepts one of the offered encodings.
32 pub fn pick(&self, accept: &str) -> Option<Compress> {
33 let tokens: Vec<String> = Self::accepted(accept);
34 for encoding in self.get_encodings().iter() {
35 if encoding.is_unknown() {
36 continue;
37 }
38 let name: String = encoding.to_string();
39 if tokens
40 .iter()
41 .any(|token: &String| token == TOKEN_ANY || token == &name)
42 {
43 return Some(*encoding);
44 }
45 }
46 None
47 }
48
49 /// Whether a body of that content type is worth compressing.
50 ///
51 /// A body that is already compressed is sent as it is, and the stream of
52 /// events is never compressed.
53 ///
54 /// # Arguments
55 ///
56 /// - `&str` - The content type of the answer.
57 ///
58 /// # Returns
59 ///
60 /// - `bool` - Whether the body may be compressed.
61 pub fn is_compressible(&self, content_type: &str) -> bool {
62 let content_type: String = content_type.trim().to_lowercase();
63 if content_type.is_empty() {
64 return true;
65 }
66 if content_type == TEXT_EVENT_STREAM {
67 return false;
68 }
69 if CONTENT_TYPES_COMPRESSED.contains(&content_type.as_str()) {
70 return false;
71 }
72 !CONTENT_TYPE_PREFIXES_COMPRESSED
73 .iter()
74 .any(|prefix: &&str| content_type.starts_with(*prefix))
75 }
76
77 /// The encodings the client accepts, without the ones it refused.
78 ///
79 /// # Arguments
80 ///
81 /// - `&str` - The `accept-encoding` header of the request.
82 ///
83 /// # Returns
84 ///
85 /// - `Vec<String>` - The tokens the client accepts.
86 fn accepted(accept: &str) -> Vec<String> {
87 let mut tokens: Vec<String> = Vec::new();
88 for part in accept.split(SEPARATOR_COMMA) {
89 let token: String = part.split(';').next().unwrap_or("").trim().to_lowercase();
90 if token.is_empty() {
91 continue;
92 }
93 let refused: bool = part.split(';').skip(1).any(|parameter: &str| {
94 let quality: Option<&str> = parameter.trim().strip_prefix(PARAMETER_QUALITY);
95 match quality {
96 Some(quality) => quality
97 .parse::<f32>()
98 .map(|value: f32| value <= 0.0)
99 .unwrap_or(false),
100 None => false,
101 }
102 });
103 if !refused {
104 tokens.push(token);
105 }
106 }
107 tokens
108 }
109}
110
111impl CompressionPlugin {
112 /// Stores the configuration the plugin works from.
113 ///
114 /// # Arguments
115 ///
116 /// - `CompressionConfig` - The configuration to store.
117 ///
118 /// # Returns
119 ///
120 /// - `Result<(), String>` - Nothing, or the reason the configuration was
121 /// refused.
122 pub fn init(config: CompressionConfig) -> Result<(), String> {
123 CONFIG.set(config).map_err(|_: CompressionConfig| {
124 "the compression configuration was already set".to_owned()
125 })
126 }
127
128 /// The configuration the plugin works from.
129 ///
130 /// # Returns
131 ///
132 /// - `Option<&'static CompressionConfig>` - The configuration, when it was
133 /// set.
134 pub fn get() -> Option<&'static CompressionConfig> {
135 CONFIG.get()
136 }
137}
138
139impl ServerHook for CompressionMiddleware {
140 /// Builds the middleware.
141 ///
142 /// # Arguments
143 ///
144 /// - `&mut Stream` - The stream the request arrived on.
145 /// - `&mut Context` - The context of the request.
146 ///
147 /// # Returns
148 ///
149 /// - `Self` - The middleware.
150 async fn new(_: &mut Stream, _: &mut Context) -> Self {
151 Self
152 }
153
154 /// Marks the answer with the encoding the client asked for.
155 ///
156 /// The body is compressed when the answer is built, so the middleware only
157 /// writes the header that names the encoding.
158 ///
159 /// # Arguments
160 ///
161 /// - `Self` - The middleware.
162 /// - `&mut Stream` - The stream the request arrived on.
163 /// - `&mut Context` - The context of the request.
164 ///
165 /// # Returns
166 ///
167 /// - `Status` - Whether the pipeline continues.
168 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
169 let config: &CompressionConfig = match CONFIG.get() {
170 Some(config) => config,
171 None => return Status::Continue,
172 };
173 let accept: String = match ctx.get_request().try_get_header(ACCEPT_ENCODING) {
174 Some(values) => match values.front() {
175 Some(value) => value.clone(),
176 None => return Status::Continue,
177 },
178 None => return Status::Continue,
179 };
180 let encoding: Compress = match config.pick(&accept) {
181 Some(encoding) => encoding,
182 None => return Status::Continue,
183 };
184 let response: &mut Response = ctx.get_mut_response();
185 if response.try_get_header_back(CONTENT_ENCODING).is_some() {
186 return Status::Continue;
187 }
188 if response.get_body().len() < config.get_min_size() {
189 return Status::Continue;
190 }
191 let content_type: String = response
192 .try_get_header_back(CONTENT_TYPE)
193 .unwrap_or_default();
194 if !config.is_compressible(&content_type) {
195 return Status::Continue;
196 }
197 response.set_header(CONTENT_ENCODING, encoding.to_string());
198 response.set_header(VARY, VARY_ACCEPT_ENCODING);
199 Status::Continue
200 }
201}