serdir 0.3.0

helpers for conditional GET, HEAD, byte range serving, and gzip content encoding for static files and more with hyper and tokio
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// Copyright (c) 2016-2021 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Response compression settings.

use http::header::{self, HeaderMap, HeaderValue};
#[cfg(feature = "runtime-compression")]
use std::collections::HashSet;
use std::fs::File;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

trait PathBufExt {
    fn append_extension(&self, extension: impl AsRef<std::ffi::OsStr>) -> PathBuf;
}

impl PathBufExt for Path {
    fn append_extension(&self, extension: impl AsRef<std::ffi::OsStr>) -> PathBuf {
        match self.file_name() {
            Some(file_name) => {
                let mut new_file_name = file_name.to_os_string();
                new_file_name.push(".");
                new_file_name.push(extension.as_ref());
                self.with_file_name(new_file_name)
            }
            None => self.to_path_buf(),
        }
    }
}

#[cfg(feature = "runtime-compression")]
use crate::brotli_cache::BrotliCache;
use crate::SerdirError;

/// Settings for using static (i.e. pre-compressed) compression.
///
/// The static compression strategy allows you to provide pre-compressed
/// versions of your files, by giving the compressed versions an appropriate
/// extension. The supported compression algorithms and extensions are:
///
/// - GZip (`.gz`)
/// - Brotli (`.br`)
/// - ZStandard (`.zstd`)
///
/// For example, if you have a servable file at path `pages/mailbox.html`, you
/// can enable it to be served with GZip compression by providing a pre-compressed file at
/// `pages/mailbox.html.gz`, or with Brotli compression by providing a pre-compressed file at
/// `pages/mailbox.html.br`.
///
/// Clients will only be served a compressed variant if they indicate support
/// for that encoding via the `Accept-Encoding` request header. If multiple
/// client-compatible compressed versions are provided, the prioritization will
/// always be Brotli, then ZStandard, then GZip, regardless of what q-values the
/// client's `Accept-Encoding` header provided.
///
/// Note that compression strategies are mutually exclusive; if you enable
/// static compression, no cached (i.e.) runtime compression will be performed,
/// and vice-versa.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub struct StaticCompression {
    gzip: bool,
    br: bool,
    zstd: bool,
}

impl StaticCompression {
    /// Creates a new static compression settings value with all encodings disabled.
    pub fn none() -> Self {
        Self::default()
    }

    /// Creates a new static compression settings value with all encodings enabled.
    pub fn all() -> Self {
        Self::default().gzip(true).brotli(true).zstd(true)
    }

    /// Sets whether Brotli (`.br`) files should be considered.
    pub fn brotli(mut self, enabled: bool) -> Self {
        self.br = enabled;
        self
    }

    /// Sets whether gzip (`.gz`) files should be considered.
    pub fn gzip(mut self, enabled: bool) -> Self {
        self.gzip = enabled;
        self
    }

    /// Sets whether zstandard (`.zstd`) files should be considered.
    pub fn zstd(mut self, enabled: bool) -> Self {
        self.zstd = enabled;
        self
    }
}

#[cfg(feature = "runtime-compression")]
const DEFAULT_CACHE_SIZE: u16 = 128;
#[cfg(feature = "runtime-compression")]
const DEFAULT_COMPRESSION_LEVEL: BrotliLevel = BrotliLevel::L5;
#[cfg(feature = "runtime-compression")]
const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;

/// Brotli compression level (0-11).
///
/// Lower levels are faster but compress less, while higher levels are slower but compress more.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum BrotliLevel {
    /// Level 0
    L0 = 0,
    /// Level 1
    L1 = 1,
    /// Level 2
    L2 = 2,
    /// Level 3
    L3 = 3,
    /// Level 4
    L4 = 4,
    /// Level 5
    #[default]
    L5 = 5,
    /// Level 6
    L6 = 6,
    /// Level 7
    L7 = 7,
    /// Level 8
    L8 = 8,
    /// Level 9
    L9 = 9,
    /// Level 10
    L10 = 10,
    /// Level 11
    L11 = 11,
}

impl From<BrotliLevel> for i32 {
    fn from(level: BrotliLevel) -> Self {
        level as i32
    }
}

impl TryFrom<u8> for BrotliLevel {
    type Error = SerdirError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::L0),
            1 => Ok(Self::L1),
            2 => Ok(Self::L2),
            3 => Ok(Self::L3),
            4 => Ok(Self::L4),
            5 => Ok(Self::L5),
            6 => Ok(Self::L6),
            7 => Ok(Self::L7),
            8 => Ok(Self::L8),
            9 => Ok(Self::L9),
            10 => Ok(Self::L10),
            11 => Ok(Self::L11),
            _ => Err(SerdirError::ConfigError(format!(
                "invalid Brotli level: {value}, must be between 0 and 11"
            ))),
        }
    }
}

impl TryFrom<u32> for BrotliLevel {
    type Error = SerdirError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        u8::try_from(value)
            .map_err(|_| {
                SerdirError::ConfigError(format!(
                    "invalid Brotli level: {value}, must be between 0 and 11"
                ))
            })?
            .try_into()
    }
}

/// Settings for cached Brotli compression at runtime.
#[cfg(feature = "runtime-compression")]
#[derive(Debug, Clone)]
pub struct CachedCompression {
    pub(crate) cache_size: u16,
    pub(crate) compression_level: BrotliLevel,
    pub(crate) supported_extensions: Option<HashSet<&'static str>>,
    pub(crate) max_file_size: u64,
}

#[cfg(feature = "runtime-compression")]
impl CachedCompression {
    /// Creates runtime compression settings with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the maximum number of items in the cache.
    ///
    /// Must be at least 4 and a power of 2.
    ///
    /// # Panics
    ///
    /// Panics if the value is invalid.
    pub fn max_size(mut self, size: u16) -> Self {
        assert!(size >= 4, "cache_size must be at least 4");
        assert!(size.is_power_of_two(), "cache_size must be a power of two");
        self.cache_size = size;
        self
    }

    /// Sets the Brotli compression level (0-11).
    pub fn compression_level(mut self, level: BrotliLevel) -> Self {
        self.compression_level = level;
        self
    }

    /// Sets the file extensions that are eligible for compression.
    ///
    /// If `None`, all file extensions will be compressed.
    pub fn supported_extensions(mut self, extensions: Option<HashSet<&'static str>>) -> Self {
        self.supported_extensions = extensions;
        self
    }

    /// Sets the maximum file size for compression.
    ///
    /// Files larger than this value will skip compression and be served
    /// in their original form.
    pub fn max_file_size(mut self, size: u64) -> Self {
        self.max_file_size = size;
        self
    }
}

#[cfg(feature = "runtime-compression")]
impl Default for CachedCompression {
    fn default() -> Self {
        Self {
            cache_size: DEFAULT_CACHE_SIZE,
            compression_level: DEFAULT_COMPRESSION_LEVEL,
            supported_extensions: None,
            max_file_size: DEFAULT_MAX_FILE_SIZE,
        }
    }
}

/// Parses an RFC 7231 section 5.3.1 `qvalue` into an integer in [0, 1000].
/// ```text
/// qvalue = ( "0" [ "." 0*3DIGIT ] )
///        / ( "1" [ "." 0*3("0") ] )
/// ```
pub(crate) fn parse_qvalue(s: &str) -> Result<u16, ()> {
    match s {
        "1" | "1." | "1.0" | "1.00" | "1.000" => return Ok(1000),
        "0" | "0." => return Ok(0),
        s if !s.starts_with("0.") => return Err(()),
        _ => {}
    };
    let v = &s[2..];
    let factor = match v.len() {
        1 /* 0.x */ => 100,
        2 /* 0.xx */ => 10,
        3 /* 0.xxx */ => 1,
        _ => return Err(()),
    };
    let v = u16::from_str(v).map_err(|_| ())?;
    let q = v * factor;
    Ok(q)
}

/// A struct representing which compression encodings are supported by the
/// client or the server.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub(crate) struct CompressionSupport {
    gzip: bool,
    br: bool,
    zstd: bool,
}

impl CompressionSupport {
    /// Returns a new `CompressionSupport` with the given settings.
    pub fn new(br: bool, gzip: bool, zstd: bool) -> Self {
        Self { gzip, br, zstd }
    }

    /// Returns true if Brotli compression is supported.
    pub fn brotli(&self) -> bool {
        self.br
    }

    /// Returns true if Gzip compression is supported.
    pub fn gzip(&self) -> bool {
        self.gzip
    }

    /// Returns true if Zstandard compression is supported.
    pub fn zstd(&self) -> bool {
        self.zstd
    }

    /// Returns the preferred compression to use when responding to the given request, if any.
    ///
    /// Follows the rules of [RFC 7231 section
    /// 5.3.4](https://tools.ietf.org/html/rfc7231#section-5.3.4).
    ///
    /// Note that if both gzip and brotli are supported, brotli will be preferred by the server.
    pub fn detect(headers: &HeaderMap) -> CompressionSupport {
        let v = match headers.get(header::ACCEPT_ENCODING) {
            None => return CompressionSupport::default(),
            Some(v) if v.is_empty() => return CompressionSupport::default(),
            Some(v) => v,
        };
        let (mut gzip_q, mut br_q, mut zstd_q, mut identity_q, mut star_q) =
            (None, None, None, None, None);
        let parts = match v.to_str() {
            Ok(s) => s.split(','),
            Err(_) => return CompressionSupport::default(),
        };
        for qi in parts {
            // Parse.
            let coding;
            let quality;
            match qi.split_once(';') {
                None => {
                    coding = qi.trim();
                    quality = 1000;
                }
                Some((c, q)) => {
                    coding = c.trim();
                    let Some(q) = q
                        .trim()
                        .strip_prefix("q=")
                        .and_then(|q| parse_qvalue(q).ok())
                    else {
                        return CompressionSupport::default(); // unparseable.
                    };
                    quality = q;
                }
            };

            if coding == "gzip" {
                gzip_q = Some(quality);
            } else if coding == "br" {
                br_q = Some(quality);
            } else if coding == "zstd" {
                zstd_q = Some(quality);
            } else if coding == "identity" {
                identity_q = Some(quality);
            } else if coding == "*" {
                star_q = Some(quality);
            }
        }

        let gzip_q = gzip_q.or(star_q).unwrap_or(0);
        let br_q = br_q.or(star_q).unwrap_or(0);
        let zstd_q = zstd_q.or(star_q).unwrap_or(0);

        // "If the representation has no content-coding, then it is
        // acceptable by default unless specifically excluded by the
        // Accept-Encoding field stating either "identity;q=0" or "*;q=0"
        // without a more specific entry for "identity"."
        let identity_q = identity_q.or(star_q).unwrap_or(0);

        // The server will always have identity coding available, so if it's
        // higher priority than another coding, there's no need to enable
        // the other coding. According to the RFC, it's possible for a client
        // to support other codings while not supporting identity coding, but
        // that seems very unlikely in practice and we don't support that.
        let use_gzip = gzip_q > 0 && gzip_q >= identity_q;
        let use_br = br_q > 0 && br_q >= identity_q;
        let use_zstd = zstd_q > 0 && zstd_q >= identity_q;

        CompressionSupport {
            gzip: use_gzip,
            br: use_br,
            zstd: use_zstd,
        }
    }
}

/// The strategy used to obtain compressed files compatible with the request's
/// supported encodings.
///
/// Currently 3 strategies are supported: `Static` (i.e. user-provided pre-compressed
/// files), `Cached` (compressed files generated on demand and cached at runtime) and
/// `None`. The `Cached` strategy is only available when the `runtime-compression`
/// feature is enabled.
#[derive(Debug, Clone)]
pub enum CompressionStrategy {
    /// Look for pre-compressed versions of the original file by adding the appropriate filename
    /// extension to the original file name.
    Static(StaticCompression),

    /// Compresses supported file types at runtime using Brotli, and caches the
    /// compressed versions for reuse.
    #[cfg(feature = "runtime-compression")]
    Cached(CachedCompression),

    /// Do not use compression, only return the original file, if available.
    None,
}

impl CompressionStrategy {
    /// Returns a strategy that only serves the original uncompressed file.
    pub fn none() -> Self {
        Self::None
    }

    /// Returns a static compression strategy with all encodings disabled.
    ///
    /// Enable specific encodings by converting a [`StaticCompression`] value
    /// into a strategy.
    pub fn static_compression() -> Self {
        Self::Static(StaticCompression::none())
    }

    /// Returns a strategy that performs runtime Brotli compression with caching.
    #[cfg(feature = "runtime-compression")]
    pub fn cached_compression() -> Self {
        Self::Cached(CachedCompression::new())
    }

    pub(crate) fn into_inner(self) -> CompressionStrategyInner {
        match self {
            Self::Static(value) => CompressionStrategyInner::Static(CompressionSupport::new(
                value.br, value.gzip, value.zstd,
            )),
            #[cfg(feature = "runtime-compression")]
            Self::Cached(value) => {
                let cache = BrotliCache::from(value);
                CompressionStrategyInner::Cached(Arc::new(cache))
            }
            Self::None => CompressionStrategyInner::None,
        }
    }
}

impl Default for CompressionStrategy {
    fn default() -> Self {
        Self::none()
    }
}

impl From<StaticCompression> for CompressionStrategy {
    fn from(value: StaticCompression) -> Self {
        Self::Static(value)
    }
}

#[cfg(feature = "runtime-compression")]
impl From<CachedCompression> for CompressionStrategy {
    fn from(value: CachedCompression) -> Self {
        Self::Cached(value)
    }
}

/// The internal strategy used to obtain compressed files compatible with the
/// request's supported encodings.
#[derive(Debug, Clone)]
pub(crate) enum CompressionStrategyInner {
    /// Look for pre-compressed versions of the original file by adding the appropriate filename
    /// extension to the original file name.
    Static(CompressionSupport),

    /// Compresses supported file types at runtime using Brotli, and caches the
    /// compressed versions for reuse.
    #[cfg(feature = "runtime-compression")]
    Cached(Arc<BrotliCache>),

    /// Do not use compression, only return the original file, if available.
    None,
}

impl CompressionStrategyInner {
    pub(crate) fn is_none(&self) -> bool {
        matches!(self, CompressionStrategyInner::None)
    }

    pub(crate) async fn find_file(
        &self,
        path: &Path,
        supported: crate::compression::CompressionSupport,
    ) -> Result<MatchedFile, SerdirError> {
        match self {
            CompressionStrategyInner::Static(server_support) => {
                if supported.brotli() && server_support.brotli() {
                    let br_path = path.append_extension("br");
                    match Self::try_path(&br_path, ContentEncoding::Brotli) {
                        Ok(f) => return Ok(f),
                        Err(SerdirError::NotFound(_)) | Err(SerdirError::IsDirectory(_)) => {}
                        Err(e) => return Err(e),
                    }
                }

                if supported.zstd() && server_support.zstd() {
                    let zstd_path = path.append_extension("zstd");
                    match Self::try_path(&zstd_path, ContentEncoding::Zstd) {
                        Ok(f) => return Ok(f),
                        Err(SerdirError::NotFound(_)) | Err(SerdirError::IsDirectory(_)) => {}
                        Err(e) => return Err(e),
                    }
                }

                if supported.gzip() && server_support.gzip() {
                    let gz_path = path.append_extension("gz");
                    match Self::try_path(&gz_path, ContentEncoding::Gzip) {
                        Ok(f) => return Ok(f),
                        Err(SerdirError::NotFound(_)) | Err(SerdirError::IsDirectory(_)) => {}
                        Err(e) => return Err(e),
                    }
                }
            }
            #[cfg(feature = "runtime-compression")]
            CompressionStrategyInner::Cached(cache) => {
                if supported.brotli() {
                    let matched = cache.get(path).await?;
                    return Ok(matched);
                }
            }
            CompressionStrategyInner::None => {}
        }

        Self::try_path(path, ContentEncoding::Identity)
    }

    fn try_path(p: &Path, encoding: ContentEncoding) -> Result<MatchedFile, SerdirError> {
        // we want to read the file metadata from the open file handle, rather than calling
        // `std::fs::metadata` on the path, to guarantee that the metadata and the file contents
        // are consistent (otherwise, if the file is modified, there could be a race condition
        // that causes a mismatch between etag values and file contents, which could cause corrupt
        // behavior for clients)
        match crate::platform::open_file(p) {
            Ok(file) => {
                let file_info = crate::FileInfo::open_file(p, &file)?;
                let extension = p
                    .extension()
                    .and_then(|s| s.to_str())
                    .unwrap_or_default()
                    .to_string();
                Ok(MatchedFile {
                    file: Arc::new(file),
                    file_info,
                    content_encoding: encoding,
                    extension,
                })
            }
            Err(e) if e.kind() == ErrorKind::NotFound => Err(SerdirError::NotFound(None)),
            Err(e) => Err(SerdirError::IOError(e)),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum ContentEncoding {
    Gzip,
    Brotli,
    Zstd,
    Identity,
}

impl ContentEncoding {
    /// Returns the encoding this file is assumed to have applied to the caller's request.
    /// E.g., if automatic gzip compression is enabled and `index.html.gz` was found when the
    /// caller requested `index.html`, this will return `Some("gzip")`. If the caller requests
    /// `index.html.gz`, this will return `None` because the gzip encoding is built in to the
    /// caller's request.
    pub(crate) fn get_header_value(&self) -> Option<HeaderValue> {
        match self {
            ContentEncoding::Gzip => Some(HeaderValue::from_static("gzip")),
            ContentEncoding::Brotli => Some(HeaderValue::from_static("br")),
            ContentEncoding::Zstd => Some(HeaderValue::from_static("zstd")),
            ContentEncoding::Identity => None,
        }
    }
}

/// An opened file handle to a file, as returned by `ServedDir::open`.
///
/// This is not necessarily a plain file; it could also be a directory, for example.
///
/// The caller can inspect it as desired. If it is a directory, the caller might pass the result of
/// `into_file()` to `nix::dir::Dir::from`.
#[derive(Clone)]
pub(crate) struct MatchedFile {
    pub(crate) file_info: crate::FileInfo,
    pub(crate) file: Arc<File>,
    pub(crate) content_encoding: ContentEncoding,
    pub(crate) extension: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::HeaderValue;
    use http::{self, header};

    fn ae_hdrs(value: &'static str) -> http::HeaderMap {
        let mut h = http::HeaderMap::new();
        h.insert(header::ACCEPT_ENCODING, HeaderValue::from_static(value));
        h
    }

    #[test]
    fn test_brotli_level_conversions() {
        assert_eq!(i32::from(BrotliLevel::L0), 0);
        assert_eq!(i32::from(BrotliLevel::L11), 11);

        assert_eq!(BrotliLevel::try_from(0u8).unwrap(), BrotliLevel::L0);
        assert_eq!(BrotliLevel::try_from(5u8).unwrap(), BrotliLevel::L5);
        assert_eq!(BrotliLevel::try_from(11u8).unwrap(), BrotliLevel::L11);
        assert!(BrotliLevel::try_from(12u8).is_err());

        assert_eq!(BrotliLevel::try_from(0u32).unwrap(), BrotliLevel::L0);
        assert_eq!(BrotliLevel::try_from(11u32).unwrap(), BrotliLevel::L11);
        assert!(BrotliLevel::try_from(12u32).is_err());
    }

    #[test]
    fn test_parse_qvalue() {
        assert_eq!(parse_qvalue("0"), Ok(0));
        assert_eq!(parse_qvalue("0."), Ok(0));
        assert_eq!(parse_qvalue("0.0"), Ok(0));
        assert_eq!(parse_qvalue("0.00"), Ok(0));
        assert_eq!(parse_qvalue("0.000"), Ok(0));
        assert_eq!(parse_qvalue("0.0000"), Err(()));
        assert_eq!(parse_qvalue("0.2"), Ok(200));
        assert_eq!(parse_qvalue("0.23"), Ok(230));
        assert_eq!(parse_qvalue("0.234"), Ok(234));
        assert_eq!(parse_qvalue("1"), Ok(1000));
        assert_eq!(parse_qvalue("1."), Ok(1000));
        assert_eq!(parse_qvalue("1.0"), Ok(1000));
        assert_eq!(parse_qvalue("1.1"), Err(()));
        assert_eq!(parse_qvalue("1.00"), Ok(1000));
        assert_eq!(parse_qvalue("1.000"), Ok(1000));
        assert_eq!(parse_qvalue("1.001"), Err(()));
        assert_eq!(parse_qvalue("1.0000"), Err(()));
        assert_eq!(parse_qvalue("2"), Err(()));
    }

    #[test]
    fn test_detect_compression_support() {
        // "A request without an Accept-Encoding header field implies that the
        // user agent has no preferences regarding content-codings. Although
        // this allows the server to use any content-coding in a response, it
        // does not imply that the user agent will be able to correctly process
        // all encodings." Identity seems safer; don't compress.
        let detect = CompressionSupport::detect(&header::HeaderMap::new());
        assert!(!detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.zstd());

        // "If the representation's content-coding is one of the
        // content-codings listed in the Accept-Encoding field, then it is
        // acceptable unless it is accompanied by a qvalue of 0.  (As
        // defined in Section 5.3.1, a qvalue of 0 means "not acceptable".)"
        let detect = CompressionSupport::detect(&ae_hdrs("gzip"));
        assert!(detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("gzip;q=0.001"));
        assert!(detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("br;q=0.001"));
        assert!(!detect.gzip());
        assert!(detect.brotli());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("zstd;q=0.001"));
        assert!(!detect.gzip());
        assert!(!detect.brotli());
        assert!(detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("br, gzip, zstd"));
        assert!(detect.brotli());
        assert!(detect.gzip());
        assert!(detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("gzip;q=0"));
        assert!(!detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.gzip());

        // "An Accept-Encoding header field with a combined field-value that is
        // empty implies that the user agent does not want any content-coding in
        // response."
        let detect = CompressionSupport::detect(&ae_hdrs(""));
        assert!(!detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.zstd());

        // The asterisk "*" symbol matches any available content-coding not
        // explicitly listed. identity is a content-coding.
        // If * is q=1000, then identity_q=1000, and neither gzip nor br is
        // strictly greater than 1000.
        let detect = CompressionSupport::detect(&ae_hdrs("*"));
        assert!(detect.gzip());
        assert!(detect.brotli());
        assert!(detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("gzip;q=0, *"));
        assert!(!detect.gzip());
        assert!(detect.brotli());
        assert!(detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("identity;q=0, *"));
        assert!(detect.gzip());
        assert!(detect.brotli());
        assert!(detect.zstd());

        // "If multiple content-codings are acceptable, then the acceptable
        // content-coding with the highest non-zero qvalue is preferred."
        let detect = CompressionSupport::detect(&ae_hdrs("identity;q=0.5, gzip;q=1.0"));
        assert!(detect.gzip());

        let detect = CompressionSupport::detect(&ae_hdrs("identity;q=1.0, gzip;q=0.5"));
        assert!(!detect.gzip());

        let detect = CompressionSupport::detect(&ae_hdrs("br;q=1.0, gzip;q=0.5, identity;q=0.1"));
        assert!(detect.brotli());
        assert!(detect.gzip());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("zstd;q=1.0, gzip;q=0.5, identity;q=0.1"));
        assert!(!detect.brotli());
        assert!(detect.gzip());
        assert!(detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("br;q=0.5, gzip;q=1.0, identity;q=0.1"));
        assert!(detect.brotli());
        assert!(detect.gzip());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("zstd;q=1.0, gzip;q=0.5, identity;q=0.1"));
        assert!(detect.zstd());
        assert!(detect.gzip());
        assert!(!detect.brotli());

        // "If an Accept-Encoding header field is present in a request
        // and none of the available representations for the response have a
        // content-coding that is listed as acceptable, the origin server SHOULD
        // send a response without any content-coding."
        let detect = CompressionSupport::detect(&ae_hdrs("*;q=0"));
        assert!(!detect.gzip());
        assert!(!detect.brotli());
        assert!(!detect.zstd());

        let detect = CompressionSupport::detect(&ae_hdrs("gzip;q=0.002")); // q=2
        assert!(detect.gzip());
    }

    #[test]
    fn test_static_compression_into_strategy() {
        let strategy: CompressionStrategy = StaticCompression::none()
            .brotli(true)
            .gzip(false)
            .zstd(true)
            .into();
        let inner = strategy.into_inner();

        match inner {
            CompressionStrategyInner::Static(support) => {
                assert!(support.brotli());
                assert!(!support.gzip());
                assert!(support.zstd());
            }
            _ => panic!("expected static compression strategy"),
        }
    }

    #[test]
    fn test_static_compression_constructor_disables_all_encodings() {
        let strategy = CompressionStrategy::static_compression();
        let inner = strategy.into_inner();

        match inner {
            CompressionStrategyInner::Static(support) => {
                assert!(!support.brotli());
                assert!(!support.gzip());
                assert!(!support.zstd());
            }
            _ => panic!("expected static compression strategy"),
        }
    }

    #[test]
    #[cfg(feature = "runtime-compression")]
    fn test_cached_compression_into_strategy() {
        let strategy: CompressionStrategy = CachedCompression::new()
            .max_size(16)
            .compression_level(BrotliLevel::L5)
            .into();
        let inner = strategy.into_inner();
        assert!(matches!(inner, CompressionStrategyInner::Cached(_)));
    }

    #[test]
    fn test_compression_strategy_none() {
        let strategy = CompressionStrategy::none();
        assert!(matches!(strategy, CompressionStrategy::None));

        let inner = strategy.into_inner();
        assert!(inner.is_none());
    }

    #[test]
    fn test_compression_strategy_default() {
        let strategy = CompressionStrategy::default();
        assert!(matches!(strategy, CompressionStrategy::None));
    }

    #[test]
    fn test_compression_strategy_static() {
        let strategy = CompressionStrategy::static_compression();
        if let CompressionStrategy::Static(static_comp) = strategy {
            assert!(!static_comp.br);
            assert!(!static_comp.gzip);
            assert!(!static_comp.zstd);
        } else {
            panic!("expected static compression strategy");
        }
    }

    #[test]
    #[cfg(feature = "runtime-compression")]
    fn test_compression_strategy_cached() {
        let strategy = CompressionStrategy::cached_compression();
        assert!(matches!(strategy, CompressionStrategy::Cached(_)));

        if let CompressionStrategy::Cached(cached) = strategy {
            assert_eq!(cached.cache_size, 128);
            assert_eq!(cached.compression_level, BrotliLevel::L5);
            assert_eq!(cached.max_file_size, 1024 * 1024);
            assert!(cached.supported_extensions.is_none());
        }
    }
}