Skip to main content

hyperlane_plugin_compression/
impl.rs

1use super::*;
2
3/// Default construction for [`CompressionConfig`].
4impl Default for CompressionConfig {
5    /// Constructs a full-duplex compression config with `1024`-byte threshold and `16 MiB` decode cap.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default configuration.
10    fn default() -> Self {
11        Self {
12            decompress_requests: true,
13            reject_unknown_encoding: true,
14            max_decompressed_bytes: DEFAULT_MAX_DECOMPRESSED_BYTES,
15            compress_responses: true,
16            min_body_bytes: DEFAULT_MIN_COMPRESS_BYTES,
17            enable_brotli: true,
18            enable_gzip: true,
19            enable_deflate: true,
20            skip_mime_prefixes: DEFAULT_SKIP_MIME_PREFIXES
21                .iter()
22                .map(|s: &&str| (*s).to_owned())
23                .collect(),
24        }
25    }
26}
27
28/// Fluent builder helpers for [`CompressionConfig`].
29impl CompressionConfig {
30    /// Enables or disables inbound request body decompression.
31    ///
32    /// # Arguments
33    ///
34    /// - `bool` - Enable request decompression.
35    ///
36    /// # Returns
37    ///
38    /// - `Self` - Updated configuration.
39    pub fn with_decompress_requests(mut self, enabled: bool) -> Self {
40        self.set_decompress_requests(enabled);
41        self
42    }
43
44    /// Sets the maximum decompressed request body size in bytes.
45    ///
46    /// # Arguments
47    ///
48    /// - `usize` - Upper bound on decompressed bytes.
49    ///
50    /// # Returns
51    ///
52    /// - `Self` - Updated configuration.
53    pub fn with_max_decompressed_bytes(mut self, max_bytes: usize) -> Self {
54        self.set_max_decompressed_bytes(max_bytes);
55        self
56    }
57
58    /// Sets the minimum response body length eligible for compression.
59    ///
60    /// # Arguments
61    ///
62    /// - `usize` - Minimum body size in bytes.
63    ///
64    /// # Returns
65    ///
66    /// - `Self` - Updated configuration.
67    pub fn with_min_body_bytes(mut self, min_bytes: usize) -> Self {
68        self.set_min_body_bytes(min_bytes);
69        self
70    }
71
72    /// Enables or disables Brotli, Gzip, and Deflate response codecs.
73    ///
74    /// # Arguments
75    ///
76    /// - `bool` - Enable Brotli.
77    /// - `bool` - Enable Gzip.
78    /// - `bool` - Enable Deflate.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Updated configuration.
83    pub fn with_codecs(mut self, brotli: bool, gzip: bool, deflate: bool) -> Self {
84        self.set_enable_brotli(brotli)
85            .set_enable_gzip(gzip)
86            .set_enable_deflate(deflate);
87        self
88    }
89}
90
91/// Request decompression and response negotiation methods for [`CompressionPlugin`].
92impl CompressionPlugin {
93    /// Compiles a standalone [`CompressionPlugin`] from `config`.
94    ///
95    /// # Arguments
96    ///
97    /// - `CompressionConfig` - Compression configuration.
98    ///
99    /// # Returns
100    ///
101    /// - `Self` - Compiled compression plugin.
102    pub fn new(config: CompressionConfig) -> Self {
103        let skip_mime_lower: Box<[String]> = config
104            .get_skip_mime_prefixes()
105            .iter()
106            .map(|s: &String| s.trim().to_ascii_lowercase())
107            .filter(|s: &String| !s.is_empty())
108            .collect::<Vec<String>>()
109            .into_boxed_slice();
110        let mut r415: Response = Response::default();
111        r415.set_status_code(HttpStatus::UnsupportedMediaType.code())
112            .set_header(CONTENT_TYPE, DEFAULT_ERROR_CONTENT_TYPE)
113            .set_body(DEFAULT_UNSUPPORTED_ENCODING_BODY);
114        let unsupported_wire: Vec<u8> = r415.build();
115        let mut r413: Response = Response::default();
116        r413.set_status_code(HttpStatus::PayloadTooLarge.code())
117            .set_header(CONTENT_TYPE, DEFAULT_ERROR_CONTENT_TYPE)
118            .set_body(DEFAULT_DECOMPRESS_LIMIT_BODY);
119        let limit_wire: Vec<u8> = r413.build();
120        Self {
121            config,
122            skip_mime_lower,
123            unsupported_wire,
124            limit_wire,
125        }
126    }
127
128    /// Initializes the global [`CompressionPlugin`] singleton once.
129    ///
130    /// # Arguments
131    ///
132    /// - `CompressionConfig` - Compression configuration.
133    ///
134    /// # Returns
135    ///
136    /// - `&'static Self` - Reference to the global plugin.
137    pub fn init(config: CompressionConfig) -> &'static Self {
138        COMPRESSION_PLUGIN.get_or_init(|| Self::new(config))
139    }
140
141    /// Returns the initialized global [`CompressionPlugin`], if configured.
142    ///
143    /// # Returns
144    ///
145    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
146    #[inline(always)]
147    pub fn get() -> Option<&'static Self> {
148        COMPRESSION_PLUGIN.get()
149    }
150
151    /// Decompresses `request` in place when it carries a supported `Content-Encoding`.
152    ///
153    /// # Arguments
154    ///
155    /// - `&mut Request` - Incoming mutable HTTP request.
156    ///
157    /// # Returns
158    ///
159    /// - `Result<bool, HttpStatus>` - `Ok(true)` if decompressed, `Ok(false)` if untouched, or `Err(413 | 415)`.
160    pub fn decompress_request(&self, request: &mut Request) -> Result<bool, HttpStatus> {
161        let Self { config, .. } = self;
162        if !config.get_decompress_requests() || request.get_body().is_empty() {
163            return Ok(false);
164        }
165        let encoding_raw: String = match request
166            .get_headers()
167            .get(CONTENT_ENCODING)
168            .and_then(|vals: &VecDeque<String>| vals.back())
169        {
170            Some(v) => v.trim().to_owned(),
171            None => return Ok(false),
172        };
173        if encoding_raw.is_empty() || encoding_raw.eq_ignore_ascii_case(CONTENT_ENCODING_IDENTITY) {
174            return Ok(false);
175        }
176        let codec: Compress = encoding_raw.parse::<Compress>().unwrap_or_default();
177        if codec.is_unknown() {
178            if config.get_reject_unknown_encoding() {
179                return Err(HttpStatus::UnsupportedMediaType);
180            }
181            return Ok(false);
182        }
183        let decoded: Cow<'_, [u8]> = codec.decode(request.get_body(), DEFAULT_DECODE_BUFFER_SIZE);
184        let max_bytes: usize = config.get_max_decompressed_bytes();
185        if max_bytes > 0 && decoded.len() > max_bytes {
186            return Err(HttpStatus::PayloadTooLarge);
187        }
188        let owned: Vec<u8> = decoded.into_owned();
189        let new_len: usize = owned.len();
190        request.set_body(owned);
191        let _: Option<VecDeque<String>> = request.get_mut_headers().remove(CONTENT_ENCODING);
192        let mut cl_deque: VecDeque<String> = VecDeque::with_capacity(1);
193        cl_deque.push_back(new_len.to_string());
194        let _: Option<VecDeque<String>> = request
195            .get_mut_headers()
196            .insert(CONTENT_LENGTH.to_owned(), cl_deque);
197        Ok(true)
198    }
199
200    /// Applies response `Content-Encoding` negotiation and `Vary` merging onto `ctx`.
201    ///
202    /// # Arguments
203    ///
204    /// - `&mut Context` - Active request/response context.
205    ///
206    /// # Returns
207    ///
208    /// - `bool` - `true` if a content coding was selected and applied.
209    #[inline]
210    pub fn apply_response_compression(&self, ctx: &mut Context) -> bool {
211        let Self {
212            config,
213            skip_mime_lower,
214            ..
215        } = self;
216        if !config.get_compress_responses() {
217            return false;
218        }
219        let response: &Response = ctx.get_response();
220        if status_has_no_body(response.get_status_code())
221            || response.get_body().len() < config.get_min_body_bytes()
222        {
223            return false;
224        }
225        let resp_headers: &ResponseHeaders = response.get_headers();
226        if resp_headers.contains_key(CONTENT_ENCODING) {
227            return false;
228        }
229        if let Some(cc) = resp_headers
230            .get(CACHE_CONTROL)
231            .and_then(|vals: &VecDeque<String>| vals.back())
232            && has_no_transform(cc)
233        {
234            return false;
235        }
236        if let Some(ct) = resp_headers
237            .get(CONTENT_TYPE)
238            .and_then(|vals: &VecDeque<String>| vals.back())
239            && is_mime_excluded(ct, skip_mime_lower)
240        {
241            return false;
242        }
243        let Some(coding) = negotiate_response_coding(
244            ctx.get_request(),
245            config.get_enable_brotli(),
246            config.get_enable_gzip(),
247            config.get_enable_deflate(),
248        ) else {
249            return false;
250        };
251        let response_mut: &mut Response = ctx.get_mut_response();
252        if !response_mut.get_headers().contains_key(VARY) {
253            response_mut.set_headers_batch(&[
254                (CONTENT_ENCODING, coding.as_str()),
255                (VARY, VARY_ACCEPT_ENCODING),
256            ]);
257        } else {
258            response_mut.set_header(CONTENT_ENCODING, coding.as_str());
259            ensure_vary_accept_encoding(response_mut);
260        }
261        true
262    }
263}
264
265/// Implements [`ServerHook`] for [`CompressionRequestHook`].
266impl ServerHook for CompressionRequestHook {
267    /// Constructs a per-request [`CompressionRequestHook`].
268    ///
269    /// # Arguments
270    ///
271    /// - `&mut Stream` - Connection stream.
272    /// - `&mut Context` - Request context.
273    ///
274    /// # Returns
275    ///
276    /// - `Self` - Hook instance.
277    #[inline(always)]
278    async fn new(_: &mut Stream, _: &mut Context) -> Self {
279        Self
280    }
281
282    /// Decompresses inbound compressed request bodies with size and codec safety guards.
283    ///
284    /// # Arguments
285    ///
286    /// - `Self` - Hook instance.
287    /// - `&mut Stream` - Connection stream.
288    /// - `&mut Context` - Request context.
289    ///
290    /// # Returns
291    ///
292    /// - `Status` - `Status::Continue` on success; `Status::Reject` on `413` or `415`.
293    #[inline(always)]
294    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
295        let Some(plugin) = CompressionPlugin::get() else {
296            return Status::Continue;
297        };
298        match plugin.decompress_request(ctx.get_mut_request()) {
299            Ok(_) => Status::Continue,
300            Err(HttpStatus::UnsupportedMediaType) => {
301                let CompressionPlugin {
302                    unsupported_wire, ..
303                } = plugin;
304                let _: Result<(), ResponseError> = stream.try_send(unsupported_wire).await;
305                Status::Reject
306            }
307            Err(_) => {
308                let CompressionPlugin { limit_wire, .. } = plugin;
309                let _: Result<(), ResponseError> = stream.try_send(limit_wire).await;
310                Status::Reject
311            }
312        }
313    }
314}
315
316/// Implements [`ServerHook`] for [`CompressionResponseHook`].
317impl ServerHook for CompressionResponseHook {
318    /// Constructs a per-response [`CompressionResponseHook`].
319    ///
320    /// # Arguments
321    ///
322    /// - `&mut Stream` - Connection stream.
323    /// - `&mut Context` - Request context.
324    ///
325    /// # Returns
326    ///
327    /// - `Self` - Hook instance.
328    #[inline(always)]
329    async fn new(_: &mut Stream, _: &mut Context) -> Self {
330        Self
331    }
332
333    /// Negotiates response content-encoding and ensures `Vary: Accept-Encoding`.
334    ///
335    /// # Arguments
336    ///
337    /// - `Self` - Hook instance.
338    /// - `&mut Stream` - Connection stream.
339    /// - `&mut Context` - Request context.
340    ///
341    /// # Returns
342    ///
343    /// - `Status` - Always `Status::Continue`.
344    #[inline(always)]
345    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
346        let Some(plugin) = CompressionPlugin::get() else {
347            return Status::Continue;
348        };
349        let _: bool = plugin.apply_response_compression(ctx);
350        Status::Continue
351    }
352}