Skip to main content

hyperlane_plugin_negotiate/
impl.rs

1use super::*;
2
3/// Default construction for [`CompressConfig`].
4impl Default for CompressConfig {
5    /// Builds the configuration with the default body length threshold.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - The configuration the middleware works from by default.
10    fn default() -> Self {
11        Self::new(DEFAULT_MIN_LENGTH)
12    }
13}
14
15/// Inherent implementation of [`CompressConfig`].
16impl CompressConfig {
17    /// Builds the configuration from a body length threshold.
18    ///
19    /// # Arguments
20    ///
21    /// - `usize` - The body length below which a response is answered without a
22    ///   content coding.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - The configuration.
27    pub fn new(min_length: usize) -> Self {
28        Self { min_length }
29    }
30
31    /// The body length below which a response is answered without a content coding.
32    ///
33    /// # Returns
34    ///
35    /// - `usize` - The threshold.
36    pub fn get_min_length(&self) -> usize {
37        self.min_length
38    }
39
40    /// Updates the body length threshold in place.
41    ///
42    /// # Arguments
43    ///
44    /// - `usize` - New minimum response body length for compression.
45    ///
46    /// # Returns
47    ///
48    /// - `&mut Self` - Mutable reference for fluent chaining.
49    pub fn set_min_length(&mut self, min_length: usize) -> &mut Self {
50        self.min_length = min_length;
51        self
52    }
53
54    /// Returns a copy of this configuration with an updated body length threshold.
55    ///
56    /// # Arguments
57    ///
58    /// - `usize` - New minimum response body length for compression.
59    ///
60    /// # Returns
61    ///
62    /// - `Self` - Updated configuration.
63    pub fn with_min_length(mut self, min_length: usize) -> Self {
64        self.set_min_length(min_length);
65        self
66    }
67}
68
69/// Inherent implementation of [`CompressMiddleware`].
70impl CompressMiddleware {
71    /// Installs the configuration the middleware works from.
72    ///
73    /// The configuration is process wide, because the framework registers a
74    /// middleware by its type and a hook is built per request rather than per
75    /// server, so a server cannot carry a configuration of its own.
76    ///
77    /// # Arguments
78    ///
79    /// - `CompressConfig` - The configuration to work from.
80    ///
81    /// # Returns
82    ///
83    /// - `Result<(), String>` - Nothing, or the reason the configuration was refused.
84    pub fn init(config: CompressConfig) -> Result<(), String> {
85        CONFIG
86            .set(config)
87            .map_err(|_: CompressConfig| COMPRESS_CONFIG_ALREADY_SET.to_owned())
88    }
89
90    /// Returns the installed global [`CompressConfig`], when [`CompressMiddleware::init`] was called.
91    ///
92    /// # Returns
93    ///
94    /// - `Option<&'static CompressConfig>` - Installed configuration, or `None`.
95    pub fn get() -> Option<&'static CompressConfig> {
96        CONFIG.get()
97    }
98
99    /// The configuration the middleware works from.
100    ///
101    /// # Returns
102    ///
103    /// - `CompressConfig` - The installed configuration, or the default one.
104    #[inline(always)]
105    fn config() -> CompressConfig {
106        CONFIG.get().copied().unwrap_or_default()
107    }
108
109    /// Reads the coding the client accepts best out of every `Accept-Encoding` field.
110    ///
111    /// A request may carry the field more than once, and every occurrence names
112    /// the codings the client accepts, so the occurrences are read together.
113    ///
114    /// # Arguments
115    ///
116    /// - `&Request` - The request to read the field from.
117    ///
118    /// # Returns
119    ///
120    /// - `Option<Compress>` - The coding, or `None` when the client accepts none.
121    #[inline]
122    fn negotiated_coding(request: &Request) -> Option<Compress> {
123        let headers: &RequestHeaders = request.get_headers();
124        if let Some(values) = headers.get(ACCEPT_ENCODING) {
125            return parse_accept_encoding_values(values);
126        }
127        let mut total_values: usize = 0;
128        let mut total_len: usize = 0;
129        let mut has_qvalue: bool = false;
130        let mut single: Option<&str> = None;
131        for (key, values) in headers {
132            if key.len() != ACCEPT_ENCODING.len() || !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
133                continue;
134            }
135            for value in values {
136                total_values += 1;
137                total_len = total_len.saturating_add(value.len());
138                if value.as_bytes().contains(&BYTE_SEMICOLON) {
139                    has_qvalue = true;
140                }
141                if total_values == 1 {
142                    single = Some(value.as_str());
143                }
144            }
145        }
146        if total_values == 0 {
147            return None;
148        }
149        if total_values == 1 {
150            return single.and_then(parse_accept_encoding_fast);
151        }
152        if !has_qvalue {
153            let mut best: Option<Compress> = None;
154            for (key, values) in headers {
155                if key.len() != ACCEPT_ENCODING.len() || !key.eq_ignore_ascii_case(ACCEPT_ENCODING)
156                {
157                    continue;
158                }
159                for value in values {
160                    if scan_accept_encoding_tokens(value, &mut best) {
161                        return best;
162                    }
163                }
164            }
165            return best;
166        }
167        let mut joined: String = String::with_capacity(total_len + total_values);
168        let mut first: bool = true;
169        for (key, values) in headers {
170            if key.len() != ACCEPT_ENCODING.len() || !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
171                continue;
172            }
173            for value in values {
174                if !first {
175                    joined.push_str(COMMA);
176                }
177                joined.push_str(value);
178                first = false;
179            }
180        }
181        Compress::from_accept_encoding(&joined)
182    }
183}
184
185/// Implements [`ServerHook`] for [`CompressMiddleware`].
186impl ServerHook for CompressMiddleware {
187    /// Builds the middleware.
188    ///
189    /// # Arguments
190    ///
191    /// - `&mut Stream` - The stream the request arrived on.
192    /// - `&mut Context` - The context of the request.
193    ///
194    /// # Returns
195    ///
196    /// - `Self` - The middleware.
197    async fn new(_: &mut Stream, _: &mut Context) -> Self {
198        Self
199    }
200
201    /// Negotiates the content coding of the response the pipeline is about to send.
202    ///
203    /// The middleware never writes to the stream: it only declares the coding on
204    /// the response, and the response builder applies the coding when the sender
205    /// serializes the response. A response that already declares a coding is left
206    /// alone, because coding a coded body produces bytes no client can read.
207    ///
208    /// # Arguments
209    ///
210    /// - `Self` - The middleware.
211    /// - `&mut Stream` - The stream the request arrived on.
212    /// - `&mut Context` - The context of the request.
213    ///
214    /// # Returns
215    ///
216    /// - `Status` - Whether the pipeline continues.
217    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
218        let response: &Response = ctx.get_response();
219        if has_no_body(response.get_status_code())
220            || response.get_body().len() < Self::config().get_min_length()
221        {
222            return Status::Continue;
223        }
224        let Some(coding) = Self::negotiated_coding(ctx.get_request()) else {
225            return Status::Continue;
226        };
227        let state: u8 = inspect_response_for_compress(ctx.get_response());
228        if state == COMPRESS_STATE_SKIP {
229            return Status::Continue;
230        }
231        let response_mut: &mut Response = ctx.get_mut_response();
232        if state == COMPRESS_STATE_SET_VARY {
233            response_mut.set_headers_batch(&[
234                (CONTENT_ENCODING, coding.as_str()),
235                (VARY, VARY_ACCEPT_ENCODING),
236            ]);
237        } else if state == COMPRESS_STATE_ADD_VARY {
238            response_mut.set_header(CONTENT_ENCODING, coding.as_str());
239            response_mut.add_header(VARY, VARY_ACCEPT_ENCODING);
240        } else {
241            response_mut.set_header(CONTENT_ENCODING, coding.as_str());
242        }
243        Status::Continue
244    }
245}
246
247/// Inherent implementation of [`EntityTag`].
248impl EntityTag {
249    /// Writes a 64-bit digest as 16 lowercase hexadecimal ASCII bytes into `dst` using a 2-byte LUT.
250    ///
251    /// # Arguments
252    ///
253    /// - `u64` - 64-bit hash digest.
254    /// - `&mut [u8]` - Destination slice of at least 16 bytes.
255    #[inline(always)]
256    fn write_hex_digest(digest: u64, dst: &mut [u8]) {
257        let bytes: [u8; 8] = digest.to_be_bytes();
258        let p0: [u8; 2] = HEX_ENCODE_PAIRS[bytes[0] as usize];
259        let p1: [u8; 2] = HEX_ENCODE_PAIRS[bytes[1] as usize];
260        let p2: [u8; 2] = HEX_ENCODE_PAIRS[bytes[2] as usize];
261        let p3: [u8; 2] = HEX_ENCODE_PAIRS[bytes[3] as usize];
262        let p4: [u8; 2] = HEX_ENCODE_PAIRS[bytes[4] as usize];
263        let p5: [u8; 2] = HEX_ENCODE_PAIRS[bytes[5] as usize];
264        let p6: [u8; 2] = HEX_ENCODE_PAIRS[bytes[6] as usize];
265        let p7: [u8; 2] = HEX_ENCODE_PAIRS[bytes[7] as usize];
266        dst[0] = p0[0];
267        dst[1] = p0[1];
268        dst[2] = p1[0];
269        dst[3] = p1[1];
270        dst[4] = p2[0];
271        dst[5] = p2[1];
272        dst[6] = p3[0];
273        dst[7] = p3[1];
274        dst[8] = p4[0];
275        dst[9] = p4[1];
276        dst[10] = p5[0];
277        dst[11] = p5[1];
278        dst[12] = p6[0];
279        dst[13] = p6[1];
280        dst[14] = p7[0];
281        dst[15] = p7[1];
282    }
283
284    /// Formats a 64-bit digest into a quoted 18-byte ASCII strong tag without `format!`.
285    ///
286    /// # Arguments
287    ///
288    /// - `u64` - 64-bit hash digest.
289    ///
290    /// # Returns
291    ///
292    /// - `[u8; 18]` - ASCII bytes `\"<16 lowercase hex digits>\"`.
293    #[inline(always)]
294    fn format_strong_bytes(digest: u64) -> [u8; 18] {
295        let mut buf: [u8; 18] = [BYTE_QUOTE; 18];
296        Self::write_hex_digest(digest, &mut buf[1..17]);
297        buf
298    }
299
300    /// Formats a 64-bit digest into a 20-byte ASCII weak tag (`W/"<16 hex>"`) on the stack.
301    ///
302    /// # Arguments
303    ///
304    /// - `u64` - 64-bit hash digest.
305    ///
306    /// # Returns
307    ///
308    /// - `[u8; 20]` - ASCII bytes `W/"<16 lowercase hex digits>"`.
309    #[inline(always)]
310    fn format_weak_bytes(digest: u64) -> [u8; 20] {
311        let mut buf: [u8; 20] = [BYTE_QUOTE; 20];
312        buf[0] = BYTE_UPPER_W;
313        buf[1] = BYTE_SLASH;
314        Self::write_hex_digest(digest, &mut buf[3..19]);
315        buf
316    }
317
318    /// Builds the strong entity-tag of a representation.
319    ///
320    /// The tag is the quoted hexadecimal digest of the data, so the same data
321    /// always produces the same tag, across processes and across restarts.
322    ///
323    /// # Arguments
324    ///
325    /// - `&[u8]` - The representation to tag.
326    ///
327    /// # Returns
328    ///
329    /// - `Self` - The entity-tag.
330    #[inline]
331    pub fn strong(data: &[u8]) -> Self {
332        let buf: [u8; 18] = Self::format_strong_bytes(xxhash3_64_oneshot(data));
333        let tag: String = from_utf8(&buf).unwrap_or_default().to_owned();
334        Self(tag)
335    }
336
337    /// Builds a weak entity-tag (`W/"<hex>"`) of a representation per RFC 9110.
338    ///
339    /// # Arguments
340    ///
341    /// - `&[u8]` - The representation to tag.
342    ///
343    /// # Returns
344    ///
345    /// - `Self` - The weak entity-tag.
346    #[inline]
347    pub fn weak(data: &[u8]) -> Self {
348        let buf: [u8; 20] = Self::format_weak_bytes(xxhash3_64_oneshot(data));
349        let tag: String = from_utf8(&buf).unwrap_or_default().to_owned();
350        Self(tag)
351    }
352
353    /// Reports whether this entity-tag carries the weak `W/` prefix.
354    ///
355    /// # Returns
356    ///
357    /// - `bool` - `true` when weak.
358    pub fn is_weak(&self) -> bool {
359        self.as_str().starts_with(WEAK_ETAG_PREFIX)
360    }
361
362    /// Returns the opaque quoted portion of the tag without any `W/` prefix.
363    ///
364    /// # Returns
365    ///
366    /// - `&str` - Opaque quoted tag slice.
367    pub fn opaque_tag(&self) -> &str {
368        self.as_str()
369            .strip_prefix(WEAK_ETAG_PREFIX)
370            .unwrap_or(self.as_str())
371    }
372
373    /// Performs RFC 9110 §8.8.3.2 weak comparison against `other`.
374    ///
375    /// # Arguments
376    ///
377    /// - `&Self` - Other entity-tag to compare.
378    ///
379    /// # Returns
380    ///
381    /// - `bool` - `true` when opaque tags match.
382    pub fn weak_eq(&self, other: &Self) -> bool {
383        self.opaque_tag() == other.opaque_tag()
384    }
385
386    /// Performs RFC 9110 §8.8.3.2 strong comparison against `other`.
387    ///
388    /// # Arguments
389    ///
390    /// - `&Self` - Other entity-tag to compare.
391    ///
392    /// # Returns
393    ///
394    /// - `bool` - `true` when both tags are strong and opaque tags match.
395    pub fn strong_eq(&self, other: &Self) -> bool {
396        !self.is_weak() && !other.is_weak() && self.opaque_tag() == other.opaque_tag()
397    }
398
399    /// The entity-tag as the `ETag` field carries it.
400    ///
401    /// # Returns
402    ///
403    /// - `&str` - The quoted tag.
404    pub fn as_str(&self) -> &str {
405        &self.0
406    }
407}
408
409/// Inherent implementation of [`ConditionalMiddleware`].
410impl ConditionalMiddleware {
411    /// Finds an existing `ETag` header slice on `response` without allocating.
412    ///
413    /// # Arguments
414    ///
415    /// - `&Response` - Response to inspect.
416    ///
417    /// # Returns
418    ///
419    /// - `Option<&str>` - Existing `ETag` header value if declared.
420    #[inline]
421    fn existing_etag(response: &Response) -> Option<&str> {
422        let headers: &ResponseHeaders = response.get_headers();
423        if let Some(values) = headers.get(ETAG) {
424            return values.back().map(String::as_str);
425        }
426        headers
427            .iter()
428            .find(|(key, _): &(&String, &VecDeque<String>)| {
429                key.len() == ETAG.len() && key.eq_ignore_ascii_case(ETAG)
430            })
431            .and_then(|(_, values): (&String, &VecDeque<String>)| values.back().map(String::as_str))
432    }
433}
434
435/// Implements [`ServerHook`] for [`ConditionalMiddleware`].
436impl ServerHook for ConditionalMiddleware {
437    /// Builds the middleware.
438    ///
439    /// # Arguments
440    ///
441    /// - `&mut Stream` - The stream the request arrived on.
442    /// - `&mut Context` - The context of the request.
443    ///
444    /// # Returns
445    ///
446    /// - `Self` - The middleware.
447    async fn new(_: &mut Stream, _: &mut Context) -> Self {
448        Self
449    }
450
451    /// Answers a conditional request with `304 Not Modified` while the validator matches.
452    ///
453    /// Only a safe method can be answered with `304`, because a request that
454    /// changes state has to reach the handler whether or not the representation
455    /// it addresses still matches. The body is dropped, so the response carries
456    /// the status and the representation metadata alone.
457    ///
458    /// # Arguments
459    ///
460    /// - `Self` - The middleware.
461    /// - `&mut Stream` - The stream the request arrived on.
462    /// - `&mut Context` - The context of the request.
463    ///
464    /// # Returns
465    ///
466    /// - `Status` - Whether the pipeline continues.
467    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
468        let method: &Method = ctx.get_request().get_method();
469        if !method.is_get() && !method.is_head() {
470            return Status::Continue;
471        }
472        let status_code: usize = ctx.get_response().get_status_code();
473        if !(200..300).contains(&status_code) || has_no_body(status_code) {
474            return Status::Continue;
475        }
476        let matched: bool = if let Some(existing) = Self::existing_etag(ctx.get_response()) {
477            matches_if_none_match_fast(ctx.get_request(), existing)
478        } else {
479            let digest: u64 = xxhash3_64_oneshot(ctx.get_response().get_body());
480            let buf: [u8; 18] = EntityTag::format_strong_bytes(digest);
481            let etag_str: &str = from_utf8(&buf).unwrap_or_default();
482            let is_match: bool = matches_if_none_match_fast(ctx.get_request(), etag_str);
483            ctx.get_mut_response().set_header(ETAG, etag_str);
484            is_match
485        };
486        if matched {
487            let response: &mut Response = ctx.get_mut_response();
488            response.set_status_code(HttpStatus::NotModified.code());
489            response.get_mut_body().clear();
490        }
491        Status::Continue
492    }
493}