hyperlane-plugin-negotiate 22.14.0

A response negotiation plugin for the Hyperlane framework, answering with the content coding the client accepts and with 304 Not Modified while a validator still matches.
Documentation
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use super::*;

/// Default construction for [`CompressConfig`].
impl Default for CompressConfig {
    /// Builds the configuration with the default body length threshold.
    ///
    /// # Returns
    ///
    /// - `Self` - The configuration the middleware works from by default.
    fn default() -> Self {
        Self::new(DEFAULT_MIN_LENGTH)
    }
}

/// Inherent implementation of [`CompressConfig`].
impl CompressConfig {
    /// Builds the configuration from a body length threshold.
    ///
    /// # Arguments
    ///
    /// - `usize` - The body length below which a response is answered without a
    ///   content coding.
    ///
    /// # Returns
    ///
    /// - `Self` - The configuration.
    pub fn new(min_length: usize) -> Self {
        Self { min_length }
    }

    /// The body length below which a response is answered without a content coding.
    ///
    /// # Returns
    ///
    /// - `usize` - The threshold.
    pub fn get_min_length(&self) -> usize {
        self.min_length
    }

    /// Updates the body length threshold in place.
    ///
    /// # Arguments
    ///
    /// - `usize` - New minimum response body length for compression.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_min_length(&mut self, min_length: usize) -> &mut Self {
        self.min_length = min_length;
        self
    }

    /// Returns a copy of this configuration with an updated body length threshold.
    ///
    /// # Arguments
    ///
    /// - `usize` - New minimum response body length for compression.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_min_length(mut self, min_length: usize) -> Self {
        self.set_min_length(min_length);
        self
    }
}

/// Inherent implementation of [`CompressMiddleware`].
impl CompressMiddleware {
    /// Installs the configuration the middleware works from.
    ///
    /// The configuration is process wide, because the framework registers a
    /// middleware by its type and a hook is built per request rather than per
    /// server, so a server cannot carry a configuration of its own.
    ///
    /// # Arguments
    ///
    /// - `CompressConfig` - The configuration to work from.
    ///
    /// # Returns
    ///
    /// - `Result<(), String>` - Nothing, or the reason the configuration was refused.
    pub fn init(config: CompressConfig) -> Result<(), String> {
        CONFIG
            .set(config)
            .map_err(|_: CompressConfig| COMPRESS_CONFIG_ALREADY_SET.to_owned())
    }

    /// Returns the installed global [`CompressConfig`], when [`CompressMiddleware::init`] was called.
    ///
    /// # Returns
    ///
    /// - `Option<&'static CompressConfig>` - Installed configuration, or `None`.
    pub fn get() -> Option<&'static CompressConfig> {
        CONFIG.get()
    }

    /// The configuration the middleware works from.
    ///
    /// # Returns
    ///
    /// - `CompressConfig` - The installed configuration, or the default one.
    fn config() -> CompressConfig {
        CONFIG.get().copied().unwrap_or_default()
    }

    /// Reads the coding the client accepts best out of every `Accept-Encoding` field.
    ///
    /// A request may carry the field more than once, and every occurrence names
    /// the codings the client accepts, so the occurrences are read together.
    ///
    /// # Arguments
    ///
    /// - `&Request` - The request to read the field from.
    ///
    /// # Returns
    ///
    /// - `Option<Compress>` - The coding, or `None` when the client accepts none.
    #[inline]
    fn negotiated_coding(request: &Request) -> Option<Compress> {
        let headers: &RequestHeaders = request.get_headers();
        if let Some(values) = headers.get(ACCEPT_ENCODING) {
            return parse_accept_encoding_values(values);
        }
        let mut total_values: usize = 0;
        let mut total_len: usize = 0;
        let mut single: Option<&str> = None;
        for (key, values) in headers {
            if key.len() != ACCEPT_ENCODING.len() || !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
                continue;
            }
            for value in values {
                total_values += 1;
                total_len = total_len.saturating_add(value.len());
                if total_values == 1 {
                    single = Some(value.as_str());
                }
            }
        }
        if total_values == 0 {
            return None;
        }
        if total_values == 1 {
            return single.and_then(parse_accept_encoding_fast);
        }
        let mut joined: String = String::with_capacity(total_len + total_values);
        let mut first: bool = true;
        for (key, values) in headers {
            if key.len() != ACCEPT_ENCODING.len() || !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
                continue;
            }
            for value in values {
                if !first {
                    joined.push_str(COMMA);
                }
                joined.push_str(value);
                first = false;
            }
        }
        parse_accept_encoding_fast(&joined)
    }
}

/// Implements [`ServerHook`] for [`CompressMiddleware`].
impl ServerHook for CompressMiddleware {
    /// 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
    }

    /// Negotiates the content coding of the response the pipeline is about to send.
    ///
    /// The middleware never writes to the stream: it only declares the coding on
    /// the response, and the response builder applies the coding when the sender
    /// serializes the response. A response that already declares a coding is left
    /// alone, because coding a coded body produces bytes no client can read.
    ///
    /// # 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 response: &Response = ctx.get_response();
        if has_no_body(response.get_status_code())
            || response.get_body().len() < Self::config().get_min_length()
        {
            return Status::Continue;
        }
        let Some(coding) = Self::negotiated_coding(ctx.get_request()) else {
            return Status::Continue;
        };
        let state: u8 = inspect_response_for_compress(ctx.get_response());
        if state == COMPRESS_STATE_SKIP {
            return Status::Continue;
        }
        let response: &mut Response = ctx.get_mut_response();
        response.set_header(CONTENT_ENCODING, coding.as_str());
        if state == COMPRESS_STATE_ADD_VARY {
            response.add_header(VARY, VARY_ACCEPT_ENCODING);
        } else if state == COMPRESS_STATE_SET_VARY {
            response.set_header(VARY, VARY_ACCEPT_ENCODING);
        }
        Status::Continue
    }
}

/// Inherent implementation of [`EntityTag`].
impl EntityTag {
    /// Formats a 64-bit digest into a quoted 18-byte ASCII strong tag without `format!`.
    ///
    /// # Arguments
    ///
    /// - `u64` - 64-bit hash digest.
    ///
    /// # Returns
    ///
    /// - `[u8; 18]` - ASCII bytes `\"<16 lowercase hex digits>\"`.
    fn format_strong_bytes(digest: u64) -> [u8; 18] {
        let mut buf: [u8; 18] = [b'"'; 18];
        let mut idx: usize = 0;
        while idx < 16 {
            let shift: u32 = (15 - idx) as u32 * 4;
            let nibble: usize = ((digest >> shift) & 0x0f) as usize;
            buf[idx + 1] = HEX_LOWER[nibble];
            idx += 1;
        }
        buf
    }

    /// Builds the strong entity-tag of a representation.
    ///
    /// The tag is the quoted hexadecimal digest of the data, so the same data
    /// always produces the same tag, across processes and across restarts.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The representation to tag.
    ///
    /// # Returns
    ///
    /// - `Self` - The entity-tag.
    pub fn strong(data: &[u8]) -> Self {
        let mut hasher: XxHash3_64 = XxHash3_64::default();
        hasher.write(data);
        let buf: [u8; 18] = Self::format_strong_bytes(hasher.finish());
        let tag: String = from_utf8(&buf).unwrap_or_default().to_owned();
        Self(tag)
    }

    /// Builds a weak entity-tag (`W/"<hex>"`) of a representation per RFC 9110.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The representation to tag.
    ///
    /// # Returns
    ///
    /// - `Self` - The weak entity-tag.
    pub fn weak(data: &[u8]) -> Self {
        let mut hasher: XxHash3_64 = XxHash3_64::default();
        hasher.write(data);
        let buf: [u8; 18] = Self::format_strong_bytes(hasher.finish());
        let mut out: String = String::with_capacity(20);
        out.push_str(WEAK_ETAG_PREFIX);
        if let Ok(text) = from_utf8(&buf) {
            out.push_str(text);
        }
        Self(out)
    }

    /// Reports whether this entity-tag carries the weak `W/` prefix.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when weak.
    pub fn is_weak(&self) -> bool {
        self.as_str().starts_with(WEAK_ETAG_PREFIX)
    }

    /// Returns the opaque quoted portion of the tag without any `W/` prefix.
    ///
    /// # Returns
    ///
    /// - `&str` - Opaque quoted tag slice.
    pub fn opaque_tag(&self) -> &str {
        self.as_str()
            .strip_prefix(WEAK_ETAG_PREFIX)
            .unwrap_or(self.as_str())
    }

    /// Performs RFC 9110 §8.8.3.2 weak comparison against `other`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Other entity-tag to compare.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when opaque tags match.
    pub fn weak_eq(&self, other: &Self) -> bool {
        self.opaque_tag() == other.opaque_tag()
    }

    /// Performs RFC 9110 §8.8.3.2 strong comparison against `other`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Other entity-tag to compare.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when both tags are strong and opaque tags match.
    pub fn strong_eq(&self, other: &Self) -> bool {
        !self.is_weak() && !other.is_weak() && self.opaque_tag() == other.opaque_tag()
    }

    /// The entity-tag as the `ETag` field carries it.
    ///
    /// # Returns
    ///
    /// - `&str` - The quoted tag.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Inherent implementation of [`ConditionalMiddleware`].
impl ConditionalMiddleware {
    /// Finds an existing `ETag` header slice on `response` without allocating.
    ///
    /// # Arguments
    ///
    /// - `&Response` - Response to inspect.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Existing `ETag` header value if declared.
    #[inline]
    fn existing_etag(response: &Response) -> Option<&str> {
        let headers: &ResponseHeaders = response.get_headers();
        if let Some(values) = headers.get(ETAG) {
            return values.back().map(String::as_str);
        }
        headers
            .iter()
            .find(|(key, _): &(&String, &ResponseHeadersValue)| {
                key.len() == ETAG.len() && key.eq_ignore_ascii_case(ETAG)
            })
            .and_then(|(_, values): (&String, &ResponseHeadersValue)| {
                values.back().map(String::as_str)
            })
    }
}

/// Implements [`ServerHook`] for [`ConditionalMiddleware`].
impl ServerHook for ConditionalMiddleware {
    /// 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
    }

    /// Answers a conditional request with `304 Not Modified` while the validator matches.
    ///
    /// Only a safe method can be answered with `304`, because a request that
    /// changes state has to reach the handler whether or not the representation
    /// it addresses still matches. The body is dropped, so the response carries
    /// the status and the representation metadata alone.
    ///
    /// # 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 method: &RequestMethod = ctx.get_request().get_method();
        if !method.is_get() && !method.is_head() {
            return Status::Continue;
        }
        let status_code: ResponseStatusCode = ctx.get_response().get_status_code();
        if !(200..300).contains(&status_code) || has_no_body(status_code) {
            return Status::Continue;
        }
        let matched: bool = if let Some(existing) = Self::existing_etag(ctx.get_response()) {
            ctx.get_request().matches_if_none_match(existing)
        } else {
            let mut hasher: XxHash3_64 = XxHash3_64::default();
            hasher.write(ctx.get_response().get_body());
            let buf: [u8; 18] = EntityTag::format_strong_bytes(hasher.finish());
            let etag_str: &str = from_utf8(&buf).unwrap_or_default();
            let is_match: bool = ctx.get_request().matches_if_none_match(etag_str);
            ctx.get_mut_response().set_header(ETAG, etag_str);
            is_match
        };
        if matched {
            ctx.get_mut_response()
                .set_status_code(HttpStatus::NotModified.code())
                .set_body(EMPTY_STR);
        }
        Status::Continue
    }
}