pingora-cache 0.9.0

HTTP caching APIs for Pingora proxy.
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
// Copyright 2026 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Functions and utilities to help parse Cache-Control headers

use super::*;

use http::header::HeaderName;
use http::HeaderValue;
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use pingora_error::{Error, ErrorType};
use regex::bytes::Regex;
use std::fmt;
use std::num::IntErrorKind;
use std::slice;
use std::str;

/// The max delta-second per [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111#section-1.2.2)
// "If a cache receives a delta-seconds value
// greater than the greatest integer it can represent, or if any of its
// subsequent calculations overflows, the cache MUST consider the value
// to be 2147483648 (2^31) or the greatest positive integer it can
// conveniently represent.
//
//    |  *Note:* The value 2147483648 is here for historical reasons,
//    |  represents infinity (over 68 years), and does not need to be
//    |  stored in binary form; an implementation could produce it as a
//    |  string if any overflow occurs, even if the calculations are
//    |  performed with an arithmetic type incapable of directly
//    |  representing that number.  What matters here is that an
//    |  overflow be detected and not treated as a negative value in
//    |  later calculations."
//
// We choose to use i32::MAX for our overflow value to stick to the letter of the RFC.
pub const DELTA_SECONDS_OVERFLOW_VALUE: u32 = i32::MAX as u32;
pub const DELTA_SECONDS_OVERFLOW_DURATION: Duration =
    Duration::from_secs(DELTA_SECONDS_OVERFLOW_VALUE as u64);

/// Cache-Control directive key.
///
/// Known RFC 9111 (and common extension) directives are represented as enum variants,
/// avoiding a heap allocation for every parsed directive. Unknown or extension
/// directives are preserved via the [`Unknown`](Self::Unknown) variant.
///
/// Directive keys are always stored in lowercase, matching the case-insensitive
/// comparison required by the HTTP specification.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum DirectiveKey {
    /// `max-age`
    MaxAge,
    /// `s-maxage`
    SMaxAge,
    /// `no-cache`
    NoCache,
    /// `no-store`
    NoStore,
    /// `private`
    Private,
    /// `public`
    Public,
    /// `must-revalidate`
    MustRevalidate,
    /// `proxy-revalidate`
    ProxyRevalidate,
    /// `must-understand`
    MustUnderstand,
    /// `no-transform`
    NoTransform,
    /// `immutable`
    Immutable,
    /// `stale-while-revalidate`
    StaleWhileRevalidate,
    /// `stale-if-error`
    StaleIfError,
    /// `only-if-cached`
    OnlyIfCached,
    /// An unknown or extension directive, stored as the original (lowercased) name.
    Unknown(String),
}

impl DirectiveKey {
    /// Return the wire-format name of this directive as a `&str`.
    ///
    /// Known variants return a `&'static str`; [`Unknown`](Self::Unknown)
    /// returns a borrow of the inner `String`.
    pub fn as_str(&self) -> &str {
        match self {
            Self::MaxAge => "max-age",
            Self::SMaxAge => "s-maxage",
            Self::NoCache => "no-cache",
            Self::NoStore => "no-store",
            Self::Private => "private",
            Self::Public => "public",
            Self::MustRevalidate => "must-revalidate",
            Self::ProxyRevalidate => "proxy-revalidate",
            Self::MustUnderstand => "must-understand",
            Self::NoTransform => "no-transform",
            Self::Immutable => "immutable",
            Self::StaleWhileRevalidate => "stale-while-revalidate",
            Self::StaleIfError => "stale-if-error",
            Self::OnlyIfCached => "only-if-cached",
            Self::Unknown(s) => s.as_str(),
        }
    }

    /// Construct a [`DirectiveKey`] from a **lowercase** `&str`.
    ///
    /// Known directive names are mapped to their enum variant (zero allocation).
    /// Anything else produces [`Unknown`](Self::Unknown) with an owned copy of
    /// the string.
    ///
    /// The caller is responsible for lowercasing the input first; this function
    /// does **not** perform case folding.
    ///
    /// See also [`from_lowercase_owned`](Self::from_lowercase_owned) to avoid a
    /// re-allocation when the caller already has an owned `String`.
    pub fn from_lowercase(s: &str) -> Self {
        match s {
            "max-age" => Self::MaxAge,
            "s-maxage" => Self::SMaxAge,
            "no-cache" => Self::NoCache,
            "no-store" => Self::NoStore,
            "private" => Self::Private,
            "public" => Self::Public,
            "must-revalidate" => Self::MustRevalidate,
            "proxy-revalidate" => Self::ProxyRevalidate,
            "must-understand" => Self::MustUnderstand,
            "no-transform" => Self::NoTransform,
            "immutable" => Self::Immutable,
            "stale-while-revalidate" => Self::StaleWhileRevalidate,
            "stale-if-error" => Self::StaleIfError,
            "only-if-cached" => Self::OnlyIfCached,
            other => Self::Unknown(other.to_owned()),
        }
    }

    /// Construct a [`DirectiveKey`] from a **lowercase** owned `String`.
    ///
    /// Behaves identically to [`from_lowercase`](Self::from_lowercase) but
    /// takes ownership of the `String`, avoiding a re-allocation when the
    /// input maps to [`Unknown`](Self::Unknown).
    pub fn from_lowercase_owned(s: String) -> Self {
        // Check against known names first (the string is borrowed for matching).
        match s.as_str() {
            "max-age" => Self::MaxAge,
            "s-maxage" => Self::SMaxAge,
            "no-cache" => Self::NoCache,
            "no-store" => Self::NoStore,
            "private" => Self::Private,
            "public" => Self::Public,
            "must-revalidate" => Self::MustRevalidate,
            "proxy-revalidate" => Self::ProxyRevalidate,
            "must-understand" => Self::MustUnderstand,
            "no-transform" => Self::NoTransform,
            "immutable" => Self::Immutable,
            "stale-while-revalidate" => Self::StaleWhileRevalidate,
            "stale-if-error" => Self::StaleIfError,
            "only-if-cached" => Self::OnlyIfCached,
            _ => Self::Unknown(s),
        }
    }
}

impl fmt::Display for DirectiveKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl PartialEq<str> for DirectiveKey {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for DirectiveKey {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

/// Cache control directive value type
#[derive(Debug)]
pub struct DirectiveValue(pub Vec<u8>);

impl AsRef<[u8]> for DirectiveValue {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl DirectiveValue {
    /// A [DirectiveValue] without quotes (`"`).
    pub fn parse_as_bytes(&self) -> &[u8] {
        self.0
            .strip_prefix(b"\"")
            .and_then(|bytes| bytes.strip_suffix(b"\""))
            .unwrap_or(&self.0[..])
    }

    /// A [DirectiveValue] without quotes (`"`) as `str`.
    pub fn parse_as_str(&self) -> Result<&str> {
        str::from_utf8(self.parse_as_bytes()).or_else(|e| {
            Error::e_because(ErrorType::InternalError, "could not parse value as utf8", e)
        })
    }

    /// Parse the [DirectiveValue] as delta seconds
    ///
    /// `"`s are ignored. The value is capped to [DELTA_SECONDS_OVERFLOW_VALUE].
    pub fn parse_as_delta_seconds(&self) -> Result<u32> {
        match self.parse_as_str()?.parse::<u32>() {
            Ok(value) => Ok(value),
            Err(e) => {
                // delta-seconds expect to handle positive overflow gracefully
                if e.kind() == &IntErrorKind::PosOverflow {
                    Ok(DELTA_SECONDS_OVERFLOW_VALUE)
                } else {
                    Error::e_because(ErrorType::InternalError, "could not parse value as u32", e)
                }
            }
        }
    }

    /// Parse the [DirectiveValue] as delta seconds, permitting a fractional component.
    ///
    /// Values with a fractional part are rounded down (floored) to the nearest
    /// non-negative integer: e.g. `1.9` -> `1`, `0.5` -> `0`. This is useful
    /// for compatibility with upstreams that emit fractional ttls (which
    /// RFC 9111 strict integer parsing rejects).
    ///
    /// Integer parsing is attempted first, so strictly-numeric values (including
    /// overflow-capped values and quoted integers) behave identically to
    /// [Self::parse_as_delta_seconds]. Negative, non-finite, or non-numeric
    /// values still return an error.
    ///
    /// `"`s are ignored. The value is capped to [DELTA_SECONDS_OVERFLOW_VALUE].
    pub fn parse_as_delta_seconds_floor(&self) -> Result<u32> {
        // UTF-8 validate once; on non-UTF8 input, propagate the same error as
        // [Self::parse_as_delta_seconds].
        let s = self.parse_as_str()?;
        match s.parse::<u32>() {
            Ok(value) => Ok(value),
            Err(e) if e.kind() == &IntErrorKind::PosOverflow => Ok(DELTA_SECONDS_OVERFLOW_VALUE),
            Err(int_err) => {
                // Fall back to parsing as a non-negative finite float and floor.
                // On any failure, return an error equivalent to the strict
                // [Self::parse_as_delta_seconds] u32-parse error.
                match s.parse::<f64>() {
                    Ok(f) if f.is_finite() && f >= 0.0 => {
                        if f >= DELTA_SECONDS_OVERFLOW_VALUE as f64 {
                            Ok(DELTA_SECONDS_OVERFLOW_VALUE)
                        } else {
                            // Safe cast: `f` is finite, non-negative, and strictly
                            // less than `DELTA_SECONDS_OVERFLOW_VALUE` (i32::MAX),
                            // which fits in `u32` after flooring.
                            Ok(f.floor() as u32)
                        }
                    }
                    _ => Error::e_because(
                        ErrorType::InternalError,
                        "could not parse value as u32",
                        int_err,
                    ),
                }
            }
        }
    }
}

/// An ordered map to store cache control key value pairs.
pub type DirectiveMap = IndexMap<DirectiveKey, Option<DirectiveValue>>;

/// Parsed Cache-Control directives
#[derive(Debug)]
pub struct CacheControl {
    /// The parsed directives
    pub directives: DirectiveMap,
    /// When set, delta-seconds directives (`max-age`, `s-maxage`,
    /// `stale-while-revalidate`, `stale-if-error`) accept fractional values
    /// and round them down to the nearest non-negative integer.
    ///
    /// Defaults to `false`, matching RFC 9111 strict integer parsing. Enable
    /// via [CacheControl::with_float_seconds] (or by assigning the field
    /// directly) for contexts that need to interoperate with upstreams that
    /// emit fractional ttls.
    pub allow_float_seconds: bool,
}

/// Cacheability calculated from cache control.
#[derive(Debug, PartialEq, Eq)]
pub enum Cacheable {
    /// Cacheable
    Yes,
    /// Not cacheable
    No,
    /// No directive found for explicit cacheability
    Default,
}

/// An iter over all the cache control directives
pub struct ListValueIter<'a>(slice::Split<'a, u8, fn(&u8) -> bool>);

impl<'a> ListValueIter<'a> {
    pub fn from(value: &'a DirectiveValue) -> Self {
        ListValueIter(value.parse_as_bytes().split(|byte| byte == &b','))
    }
}

// https://datatracker.ietf.org/doc/html/rfc9110#name-whitespace
// optional whitespace OWS = *(SP / HTAB); SP = 0x20, HTAB = 0x09
fn trim_ows(bytes: &[u8]) -> &[u8] {
    fn not_ows(b: &u8) -> bool {
        b != &b'\x20' && b != &b'\x09'
    }
    // find first non-OWS char from front (head) and from end (tail)
    let head = bytes.iter().position(not_ows).unwrap_or(0);
    let tail = bytes
        .iter()
        .rposition(not_ows)
        .map(|rpos| rpos + 1)
        .unwrap_or(head);
    &bytes[head..tail]
}

impl<'a> Iterator for ListValueIter<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        Some(trim_ows(self.0.next()?))
    }
}

// Originally from https://github.com/hapijs/wreck which has the following comments:
// Cache-Control   = 1#cache-directive
// cache-directive = token [ "=" ( token / quoted-string ) ]
// token           = [^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+
// quoted-string   = "(?:[^"\\]|\\.)*"
//
// note the `token` implementation excludes disallowed ASCII ranges
// and disallowed delimiters: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
// though it does not forbid `obs-text`: %x80-FF
static RE_CACHE_DIRECTIVE: Lazy<Regex> =
    // to break our version down further:
    // `(?-u)`: unicode support disabled, which puts the regex into "ASCII compatible mode" for specifying literal bytes like \x7F: https://docs.rs/regex/1.10.4/regex/bytes/index.html#syntax
    // `(?:^|(?:\s*[,;]\s*)`: allow either , or ; as a delimiter
    // `([^\x00-\x20\(\)<>@,;:\\"/\[\]\?=\{\}\x7F]+)`: token (directive name capture group)
    // `(?:=((?:[^\x00-\x20\(\)<>@,;:\\"/\[\]\?=\{\}\x7F]+|(?:"(?:[^"\\]|\\.)*"))))`: token OR quoted-string (directive value capture-group)
    Lazy::new(|| {
        Regex::new(r#"(?-u)(?:^|(?:\s*[,;]\s*))([^\x00-\x20\(\)<>@,;:\\"/\[\]\?=\{\}\x7F]+)(?:=((?:[^\x00-\x20\(\)<>@,;:\\"/\[\]\?=\{\}\x7F]+|(?:"(?:[^"\\]|\\.)*"))))?"#).unwrap()
    });

impl CacheControl {
    // Our parsing strategy is more permissive than the RFC in a few ways:
    // - Allows semicolons as delimiters (in addition to commas). See the regex above.
    // - Allows octets outside of visible ASCII in `token`s, and in later RFCs, octets outside of
    //   the `quoted-string` range: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
    //   See the regex above.
    // - Doesn't require no-value for "boolean directives," such as must-revalidate
    // - Allows quoted-string format for numeric values.
    fn from_headers(headers: http::header::GetAll<HeaderValue>) -> Option<Self> {
        let mut directives = IndexMap::new();
        // should iterate in header line insertion order
        for line in headers {
            for captures in RE_CACHE_DIRECTIVE.captures_iter(line.as_bytes()) {
                // directive key
                // header values don't have to be utf-8, but we store keys as
                // strings for case-insensitive matching. Known directive names
                // are mapped to enum variants (zero allocation).
                let key = captures.get(1).and_then(|cap| {
                    str::from_utf8(cap.as_bytes())
                        .ok()
                        .map(|token| DirectiveKey::from_lowercase_owned(token.to_lowercase()))
                });
                if key.is_none() {
                    continue;
                }
                // directive value
                // match token or quoted-string
                let value = captures
                    .get(2)
                    .map(|cap| DirectiveValue(cap.as_bytes().to_vec()));
                directives.insert(key.unwrap(), value);
            }
        }
        Some(CacheControl {
            directives,
            allow_float_seconds: false,
        })
    }

    /// Builder setter: enable fractional delta-seconds parsing.
    ///
    /// See [CacheControl::allow_float_seconds] for semantics. Returns `self`
    /// so it can be chained onto a parser call, e.g.
    /// `CacheControl::from_resp_headers(&resp).map(|cc| cc.with_float_seconds())`.
    pub fn with_float_seconds(mut self) -> Self {
        self.allow_float_seconds = true;
        self
    }

    /// Parse from the given header name in `headers`
    pub fn from_headers_named(header_name: &str, headers: &http::HeaderMap) -> Option<Self> {
        if !headers.contains_key(header_name) {
            return None;
        }

        Self::from_headers(headers.get_all(header_name))
    }

    /// Parse from the given header name in the [ReqHeader]
    pub fn from_req_headers_named(header_name: &str, req_header: &ReqHeader) -> Option<Self> {
        Self::from_headers_named(header_name, &req_header.headers)
    }

    /// Parse `Cache-Control` header name from the [ReqHeader]
    pub fn from_req_headers(req_header: &ReqHeader) -> Option<Self> {
        Self::from_req_headers_named("cache-control", req_header)
    }

    /// Parse from the given header name in the [RespHeader]
    pub fn from_resp_headers_named(header_name: &str, resp_header: &RespHeader) -> Option<Self> {
        Self::from_headers_named(header_name, &resp_header.headers)
    }

    /// Parse `Cache-Control` header name from the [RespHeader]
    pub fn from_resp_headers(resp_header: &RespHeader) -> Option<Self> {
        Self::from_resp_headers_named("cache-control", resp_header)
    }

    /// Whether the given directive is in the cache control.
    ///
    /// Accepts a string for convenience; known directive names are matched
    /// without allocation. Prefer [`has_directive`](Self::has_directive) when
    /// you already have a [`DirectiveKey`].
    ///
    /// **Note:** `key` must already be lowercase (e.g. `"max-age"`, not
    /// `"Max-Age"`). Directive names are stored in wire-format lowercase;
    /// a mixed-case input will silently miss.
    pub fn has_key(&self, key: &str) -> bool {
        self.has_directive(&DirectiveKey::from_lowercase(key))
    }

    /// Whether the given [`DirectiveKey`] is in the cache control.
    pub fn has_directive(&self, key: &DirectiveKey) -> bool {
        self.directives.contains_key(key)
    }

    /// Whether the `public` directive is in the cache control.
    pub fn public(&self) -> bool {
        self.has_directive(&DirectiveKey::Public)
    }

    /// Whether the given directive exists, and it has no value.
    fn has_key_without_value(&self, key: &DirectiveKey) -> bool {
        matches!(self.directives.get(key), Some(None))
    }

    /// Whether the standalone `private` exists in the cache control
    // RFC 7234: using the #field-name versions of `private`
    // means a shared cache "MUST NOT store the specified field-name(s),
    // whereas it MAY store the remainder of the response."
    // It must be a boolean form (no value) to apply to the whole response.
    // https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.2.6
    pub fn private(&self) -> bool {
        self.has_key_without_value(&DirectiveKey::Private)
    }

    fn get_field_names(&self, key: &DirectiveKey) -> Option<ListValueIter<'_>> {
        let value = self.directives.get(key)?.as_ref()?;
        Some(ListValueIter::from(value))
    }

    /// Get the values of `private=`
    pub fn private_field_names(&self) -> Option<ListValueIter<'_>> {
        self.get_field_names(&DirectiveKey::Private)
    }

    /// Whether the standalone `no-cache` exists in the cache control
    pub fn no_cache(&self) -> bool {
        self.has_key_without_value(&DirectiveKey::NoCache)
    }

    /// Get the values of `no-cache=`
    pub fn no_cache_field_names(&self) -> Option<ListValueIter<'_>> {
        self.get_field_names(&DirectiveKey::NoCache)
    }

    /// Whether `no-store` exists.
    pub fn no_store(&self) -> bool {
        self.has_directive(&DirectiveKey::NoStore)
    }

    fn parse_delta_seconds(&self, key: &DirectiveKey) -> Result<Option<u32>> {
        if let Some(Some(dir_value)) = self.directives.get(key) {
            let value = if self.allow_float_seconds {
                dir_value.parse_as_delta_seconds_floor()?
            } else {
                dir_value.parse_as_delta_seconds()?
            };
            Ok(Some(value))
        } else {
            Ok(None)
        }
    }

    /// Return the `max-age` seconds
    pub fn max_age(&self) -> Result<Option<u32>> {
        self.parse_delta_seconds(&DirectiveKey::MaxAge)
    }

    /// Return the `s-maxage` seconds
    pub fn s_maxage(&self) -> Result<Option<u32>> {
        self.parse_delta_seconds(&DirectiveKey::SMaxAge)
    }

    /// Return the `stale-while-revalidate` seconds
    pub fn stale_while_revalidate(&self) -> Result<Option<u32>> {
        self.parse_delta_seconds(&DirectiveKey::StaleWhileRevalidate)
    }

    /// Return the `stale-if-error` seconds
    pub fn stale_if_error(&self) -> Result<Option<u32>> {
        self.parse_delta_seconds(&DirectiveKey::StaleIfError)
    }

    /// Whether `must-revalidate` exists.
    pub fn must_revalidate(&self) -> bool {
        self.has_directive(&DirectiveKey::MustRevalidate)
    }

    /// Whether `proxy-revalidate` exists.
    pub fn proxy_revalidate(&self) -> bool {
        self.has_directive(&DirectiveKey::ProxyRevalidate)
    }

    /// Whether `only-if-cached` exists.
    pub fn only_if_cached(&self) -> bool {
        self.has_directive(&DirectiveKey::OnlyIfCached)
    }
}

impl InterpretCacheControl for CacheControl {
    fn is_cacheable(&self) -> Cacheable {
        if self.no_store() || self.private() {
            return Cacheable::No;
        }
        if self.has_directive(&DirectiveKey::SMaxAge)
            || self.has_directive(&DirectiveKey::MaxAge)
            || self.public()
        {
            return Cacheable::Yes;
        }
        Cacheable::Default
    }

    fn allow_caching_authorized_req(&self) -> bool {
        // RFC 7234 https://datatracker.ietf.org/doc/html/rfc7234#section-3
        // "MUST NOT" store requests with Authorization header
        // unless response contains one of these directives
        self.must_revalidate() || self.public() || self.has_directive(&DirectiveKey::SMaxAge)
    }

    fn fresh_duration(&self) -> Option<Duration> {
        if self.no_cache() {
            // always treated as stale
            return Some(Duration::ZERO);
        }
        let seconds = self
            .s_maxage()
            .ok()?
            // s-maxage not present
            .or_else(|| self.max_age().unwrap_or(None))
            .map(|duration| Duration::from_secs(duration as u64))?;
        Some(seconds)
    }

    fn serve_stale_while_revalidate_duration(&self) -> Option<Duration> {
        // RFC 7234: these directives forbid serving stale.
        // https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.4
        if self.must_revalidate()
            || self.proxy_revalidate()
            || self.has_directive(&DirectiveKey::SMaxAge)
        {
            return Some(Duration::ZERO);
        }
        self.stale_while_revalidate()
            .unwrap_or(None)
            .map(|secs| Duration::from_secs(secs as u64))
    }

    fn serve_stale_if_error_duration(&self) -> Option<Duration> {
        if self.must_revalidate()
            || self.proxy_revalidate()
            || self.has_directive(&DirectiveKey::SMaxAge)
        {
            return Some(Duration::ZERO);
        }
        self.stale_if_error()
            .unwrap_or(None)
            .map(|secs| Duration::from_secs(secs as u64))
    }

    // Strip header names listed in `private` or `no-cache` directives from a response.
    fn strip_private_headers(&self, resp_header: &mut ResponseHeader) {
        fn strip_listed_headers(resp: &mut ResponseHeader, field_names: ListValueIter) {
            for name in field_names {
                if let Ok(header) = HeaderName::from_bytes(name) {
                    resp.remove_header(&header);
                }
            }
        }

        if let Some(headers) = self.private_field_names() {
            strip_listed_headers(resp_header, headers);
        }
        // We interpret `no-cache` the same way as `private`,
        // though technically it has a less restrictive requirement
        // ("MUST NOT be sent in the response to a subsequent request
        // without successful revalidation with the origin server").
        // https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.2.2
        if let Some(headers) = self.no_cache_field_names() {
            strip_listed_headers(resp_header, headers);
        }
    }
}

/// `InterpretCacheControl` provides a meaningful interface to the parsed `CacheControl`.
/// These functions actually interpret the parsed cache-control directives to return
/// the freshness or other cache meta values that cache-control is signaling.
///
/// By default `CacheControl` implements an RFC-7234 compliant reading that assumes it is being
/// used with a shared (proxy) cache.
pub trait InterpretCacheControl {
    /// Does cache-control specify this response is cacheable?
    ///
    /// Note that an RFC-7234 compliant cacheability check must also
    /// check if the request contained the Authorization header and
    /// `allow_caching_authorized_req`.
    fn is_cacheable(&self) -> Cacheable;

    /// Does this cache-control allow caching a response to
    /// a request with the Authorization header?
    fn allow_caching_authorized_req(&self) -> bool;

    /// Returns freshness ttl specified in cache-control
    ///
    /// - `Some(_)` indicates cache-control specifies a valid ttl. Some(Duration::ZERO) = always stale.
    /// - `None` means cache-control did not specify a valid ttl.
    fn fresh_duration(&self) -> Option<Duration>;

    /// Returns stale-while-revalidate ttl,
    ///
    /// The result should consider all the relevant cache directives, not just SWR header itself.
    ///
    /// Some(0) means serving such stale is disallowed by directive like `must-revalidate`
    /// or `stale-while-revalidater=0`.
    ///
    /// `None` indicates no SWR ttl was specified.
    fn serve_stale_while_revalidate_duration(&self) -> Option<Duration>;

    /// Returns stale-if-error ttl,
    ///
    /// The result should consider all the relevant cache directives, not just SIE header itself.
    ///
    /// Some(0) means serving such stale is disallowed by directive like `must-revalidate`
    /// or `stale-if-error=0`.
    ///
    /// `None` indicates no SIE ttl was specified.
    fn serve_stale_if_error_duration(&self) -> Option<Duration>;

    /// Strip header names listed in `private` or `no-cache` directives from a response,
    /// usually prior to storing that response in cache.
    fn strip_private_headers(&self, resp_header: &mut ResponseHeader);
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::CACHE_CONTROL;
    use http::{request, response};

    fn build_response(cc_key: HeaderName, cc_value: &str) -> response::Parts {
        let (parts, _) = response::Builder::new()
            .header(cc_key, cc_value)
            .body(())
            .unwrap()
            .into_parts();
        parts
    }

    #[test]
    fn test_simple_cache_control() {
        let resp = build_response(CACHE_CONTROL, "public, max-age=10000");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.public());
        assert_eq!(cc.max_age().unwrap().unwrap(), 10000);
    }

    #[test]
    fn test_private_cache_control() {
        let resp = build_response(CACHE_CONTROL, "private");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();

        assert!(cc.private());
        assert!(cc.max_age().unwrap().is_none());
    }

    #[test]
    fn test_directives_across_header_lines() {
        let (parts, _) = response::Builder::new()
            .header(CACHE_CONTROL, "public,")
            .header("cache-Control", "max-age=10000")
            .body(())
            .unwrap()
            .into_parts();
        let cc = CacheControl::from_resp_headers(&parts).unwrap();

        assert!(cc.public());
        assert_eq!(cc.max_age().unwrap().unwrap(), 10000);
    }

    #[test]
    fn test_recognizes_semicolons_as_delimiters() {
        let resp = build_response(CACHE_CONTROL, "public; max-age=0");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();

        assert!(cc.public());
        assert_eq!(cc.max_age().unwrap().unwrap(), 0);
    }

    #[test]
    fn test_unknown_directives() {
        let resp = build_response(CACHE_CONTROL, "public,random1=random2, rand3=\"\"");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        let mut directive_iter = cc.directives.iter();

        let first = directive_iter.next().unwrap();
        assert_eq!(first.0, &"public");
        assert!(first.1.is_none());

        let second = directive_iter.next().unwrap();
        assert_eq!(second.0, &"random1");
        assert_eq!(second.1.as_ref().unwrap().0, "random2".as_bytes());

        let third = directive_iter.next().unwrap();
        assert_eq!(third.0, &"rand3");
        assert_eq!(third.1.as_ref().unwrap().0, "\"\"".as_bytes());

        assert!(directive_iter.next().is_none());
    }

    #[test]
    fn test_case_insensitive_directive_keys() {
        let resp = build_response(
            CACHE_CONTROL,
            "Public=\"something\", mAx-AGe=\"10000\", foo=cRaZyCaSe, bAr=\"inQuotes\"",
        );
        let cc = CacheControl::from_resp_headers(&resp).unwrap();

        assert!(cc.public());
        assert_eq!(cc.max_age().unwrap().unwrap(), 10000);

        let mut directive_iter = cc.directives.iter();
        let first = directive_iter.next().unwrap();
        assert_eq!(first.0, &"public");
        assert_eq!(first.1.as_ref().unwrap().0, "\"something\"".as_bytes());

        let second = directive_iter.next().unwrap();
        assert_eq!(second.0, &"max-age");
        assert_eq!(second.1.as_ref().unwrap().0, "\"10000\"".as_bytes());

        // values are still stored with casing
        let third = directive_iter.next().unwrap();
        assert_eq!(third.0, &"foo");
        assert_eq!(third.1.as_ref().unwrap().0, "cRaZyCaSe".as_bytes());

        let fourth = directive_iter.next().unwrap();
        assert_eq!(fourth.0, &"bar");
        assert_eq!(fourth.1.as_ref().unwrap().0, "\"inQuotes\"".as_bytes());

        assert!(directive_iter.next().is_none());
    }

    #[test]
    fn test_non_ascii() {
        let resp = build_response(CACHE_CONTROL, "püblic=💖, max-age=\"💯\"");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();

        // Not considered valid registered directive keys / values
        assert!(!cc.public());
        assert_eq!(
            cc.max_age().unwrap_err().context.unwrap().to_string(),
            "could not parse value as u32"
        );

        let mut directive_iter = cc.directives.iter();
        let first = directive_iter.next().unwrap();
        assert_eq!(first.0, &"püblic");
        assert_eq!(first.1.as_ref().unwrap().0, "💖".as_bytes());

        let second = directive_iter.next().unwrap();
        assert_eq!(second.0, &"max-age");
        assert_eq!(second.1.as_ref().unwrap().0, "\"💯\"".as_bytes());

        assert!(directive_iter.next().is_none());
    }

    #[test]
    fn test_non_utf8_key() {
        let mut resp = response::Builder::new().body(()).unwrap();
        resp.headers_mut().insert(
            CACHE_CONTROL,
            HeaderValue::from_bytes(b"bar\xFF=\"baz\", a=b").unwrap(),
        );
        let (parts, _) = resp.into_parts();
        let cc = CacheControl::from_resp_headers(&parts).unwrap();

        // invalid bytes for key
        let mut directive_iter = cc.directives.iter();
        let first = directive_iter.next().unwrap();
        assert_eq!(first.0, &"a");
        assert_eq!(first.1.as_ref().unwrap().0, "b".as_bytes());

        assert!(directive_iter.next().is_none());
    }

    #[test]
    fn test_non_utf8_value() {
        // RFC 7230: 0xFF is part of obs-text and is officially considered a valid octet in quoted-strings
        let mut resp = response::Builder::new().body(()).unwrap();
        resp.headers_mut().insert(
            CACHE_CONTROL,
            HeaderValue::from_bytes(b"max-age=ba\xFFr, bar=\"baz\xFF\", a=b").unwrap(),
        );
        let (parts, _) = resp.into_parts();
        let cc = CacheControl::from_resp_headers(&parts).unwrap();

        assert_eq!(
            cc.max_age().unwrap_err().context.unwrap().to_string(),
            "could not parse value as utf8"
        );

        let mut directive_iter = cc.directives.iter();

        let first = directive_iter.next().unwrap();
        assert_eq!(first.0, &"max-age");
        assert_eq!(first.1.as_ref().unwrap().0, b"ba\xFFr");

        let second = directive_iter.next().unwrap();
        assert_eq!(second.0, &"bar");
        assert_eq!(second.1.as_ref().unwrap().0, b"\"baz\xFF\"");

        let third = directive_iter.next().unwrap();
        assert_eq!(third.0, &"a");
        assert_eq!(third.1.as_ref().unwrap().0, "b".as_bytes());

        assert!(directive_iter.next().is_none());
    }

    #[test]
    fn test_age_overflow() {
        let resp = build_response(
            CACHE_CONTROL,
            "max-age=-99999999999999999999999999, s-maxage=99999999999999999999999999",
        );
        let cc = CacheControl::from_resp_headers(&resp).unwrap();

        assert_eq!(
            cc.s_maxage().unwrap().unwrap(),
            DELTA_SECONDS_OVERFLOW_VALUE
        );
        // negative ages still result in errors even with overflow handling
        assert_eq!(
            cc.max_age().unwrap_err().context.unwrap().to_string(),
            "could not parse value as u32"
        );
    }

    #[test]
    fn test_fresh_sec() {
        let resp = build_response(CACHE_CONTROL, "");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.fresh_duration().is_none());

        let resp = build_response(CACHE_CONTROL, "max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(12345));

        let resp = build_response(CACHE_CONTROL, "max-age=99999,s-maxage=123");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        // prefer s-maxage over max-age
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(123));
    }

    #[test]
    fn test_cacheability() {
        let resp = build_response(CACHE_CONTROL, "");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::Default);

        // uncacheable
        let resp = build_response(CACHE_CONTROL, "private, max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::No);

        let resp = build_response(CACHE_CONTROL, "no-store, max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::No);

        // cacheable
        let resp = build_response(CACHE_CONTROL, "public");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::Yes);

        let resp = build_response(CACHE_CONTROL, "max-age=0");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::Yes);
    }

    #[test]
    fn test_no_cache() {
        let resp = build_response(CACHE_CONTROL, "no-cache, max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.is_cacheable(), Cacheable::Yes);
        assert_eq!(cc.fresh_duration().unwrap(), Duration::ZERO);
    }

    #[test]
    fn test_no_cache_field_names() {
        let resp = build_response(CACHE_CONTROL, "no-cache=\"set-cookie\", max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(!cc.private());
        assert_eq!(cc.is_cacheable(), Cacheable::Yes);
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(12345));
        let mut field_names = cc.no_cache_field_names().unwrap();
        assert_eq!(
            str::from_utf8(field_names.next().unwrap()).unwrap(),
            "set-cookie"
        );
        assert!(field_names.next().is_none());

        let mut resp = response::Builder::new().body(()).unwrap();
        resp.headers_mut().insert(
            CACHE_CONTROL,
            HeaderValue::from_bytes(
                b"private=\"\", no-cache=\"a\xFF, set-cookie, Baz\x09 , c,d  ,, \"",
            )
            .unwrap(),
        );
        let (parts, _) = resp.into_parts();
        let cc = CacheControl::from_resp_headers(&parts).unwrap();
        let mut field_names = cc.private_field_names().unwrap();
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "");
        assert!(field_names.next().is_none());
        let mut field_names = cc.no_cache_field_names().unwrap();
        assert!(str::from_utf8(field_names.next().unwrap()).is_err());
        assert_eq!(
            str::from_utf8(field_names.next().unwrap()).unwrap(),
            "set-cookie"
        );
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "Baz");
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "c");
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "d");
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "");
        assert_eq!(str::from_utf8(field_names.next().unwrap()).unwrap(), "");
        assert!(field_names.next().is_none());
    }

    #[test]
    fn test_strip_private_headers() {
        let mut resp = ResponseHeader::build(200, None).unwrap();
        resp.append_header(
            CACHE_CONTROL,
            "no-cache=\"x-private-header\", max-age=12345",
        )
        .unwrap();
        resp.append_header("X-Private-Header", "dropped").unwrap();

        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        cc.strip_private_headers(&mut resp);
        assert!(!resp.headers.contains_key("X-Private-Header"));
    }

    #[test]
    fn test_stale_while_revalidate() {
        let resp = build_response(CACHE_CONTROL, "max-age=12345, stale-while-revalidate=5");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.stale_while_revalidate().unwrap().unwrap(), 5);
        assert_eq!(
            cc.serve_stale_while_revalidate_duration().unwrap(),
            Duration::from_secs(5)
        );
        assert!(cc.serve_stale_if_error_duration().is_none());
    }

    #[test]
    fn test_stale_if_error() {
        let resp = build_response(CACHE_CONTROL, "max-age=12345, stale-if-error=3600");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.stale_if_error().unwrap().unwrap(), 3600);
        assert_eq!(
            cc.serve_stale_if_error_duration().unwrap(),
            Duration::from_secs(3600)
        );
        assert!(cc.serve_stale_while_revalidate_duration().is_none());
    }

    #[test]
    fn test_must_revalidate() {
        let resp = build_response(
            CACHE_CONTROL,
            "max-age=12345, stale-while-revalidate=60, stale-if-error=30, must-revalidate",
        );
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.must_revalidate());
        assert_eq!(cc.stale_while_revalidate().unwrap().unwrap(), 60);
        assert_eq!(cc.stale_if_error().unwrap().unwrap(), 30);
        assert_eq!(
            cc.serve_stale_while_revalidate_duration().unwrap(),
            Duration::ZERO
        );
        assert_eq!(cc.serve_stale_if_error_duration().unwrap(), Duration::ZERO);
    }

    #[test]
    fn test_proxy_revalidate() {
        let resp = build_response(
            CACHE_CONTROL,
            "max-age=12345, stale-while-revalidate=60, stale-if-error=30, proxy-revalidate",
        );
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.proxy_revalidate());
        assert_eq!(cc.stale_while_revalidate().unwrap().unwrap(), 60);
        assert_eq!(cc.stale_if_error().unwrap().unwrap(), 30);
        assert_eq!(
            cc.serve_stale_while_revalidate_duration().unwrap(),
            Duration::ZERO
        );
        assert_eq!(cc.serve_stale_if_error_duration().unwrap(), Duration::ZERO);
    }

    #[test]
    fn test_s_maxage_stale() {
        let resp = build_response(
            CACHE_CONTROL,
            "s-maxage=0, stale-while-revalidate=60, stale-if-error=30",
        );
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert_eq!(cc.stale_while_revalidate().unwrap().unwrap(), 60);
        assert_eq!(cc.stale_if_error().unwrap().unwrap(), 30);
        assert_eq!(
            cc.serve_stale_while_revalidate_duration().unwrap(),
            Duration::ZERO
        );
        assert_eq!(cc.serve_stale_if_error_duration().unwrap(), Duration::ZERO);
    }

    #[test]
    fn test_authorized_request() {
        let resp = build_response(CACHE_CONTROL, "max-age=10");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(!cc.allow_caching_authorized_req());

        let resp = build_response(CACHE_CONTROL, "s-maxage=10");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.allow_caching_authorized_req());

        let resp = build_response(CACHE_CONTROL, "public");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.allow_caching_authorized_req());

        let resp = build_response(CACHE_CONTROL, "must-revalidate, max-age=0");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(cc.allow_caching_authorized_req());

        let resp = build_response(CACHE_CONTROL, "");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(!cc.allow_caching_authorized_req());
    }

    fn build_request(cc_key: HeaderName, cc_value: &str) -> request::Parts {
        let (parts, _) = request::Builder::new()
            .header(cc_key, cc_value)
            .body(())
            .unwrap()
            .into_parts();
        parts
    }

    #[test]
    fn test_request_only_if_cached() {
        let req = build_request(CACHE_CONTROL, "only-if-cached=1");
        let cc = CacheControl::from_req_headers(&req).unwrap();
        assert!(cc.only_if_cached())
    }

    #[test]
    fn test_parse_as_delta_seconds_floor() {
        // Integer values behave identically to the strict parser
        let v = DirectiveValue(b"10".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 10);

        let v = DirectiveValue(b"\"10\"".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 10);

        // Quoted fractional values are unwrapped by parse_as_str and floored.
        let v = DirectiveValue(b"\"1.5\"".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 1);

        let v = DirectiveValue(b"0".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 0);

        // Integer positive overflow is still capped
        let v = DirectiveValue(b"99999999999999999999".to_vec());
        assert_eq!(
            v.parse_as_delta_seconds_floor().unwrap(),
            DELTA_SECONDS_OVERFLOW_VALUE
        );

        // Floats are floored
        let v = DirectiveValue(b"1.5".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 1);

        let v = DirectiveValue(b"1.9".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 1);

        let v = DirectiveValue(b"0.5".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 0);

        let v = DirectiveValue(b"3600.0".to_vec());
        assert_eq!(v.parse_as_delta_seconds_floor().unwrap(), 3600);

        // Float positive overflow is capped
        let v = DirectiveValue(b"99999999999.5".to_vec());
        assert_eq!(
            v.parse_as_delta_seconds_floor().unwrap(),
            DELTA_SECONDS_OVERFLOW_VALUE
        );

        // Negative values are rejected (matches strict behavior)
        assert!(DirectiveValue(b"-1".to_vec())
            .parse_as_delta_seconds_floor()
            .is_err());
        assert!(DirectiveValue(b"-1.5".to_vec())
            .parse_as_delta_seconds_floor()
            .is_err());

        // Non-finite / non-numeric values are rejected
        assert!(DirectiveValue(b"NaN".to_vec())
            .parse_as_delta_seconds_floor()
            .is_err());
        assert!(DirectiveValue(b"inf".to_vec())
            .parse_as_delta_seconds_floor()
            .is_err());
        assert!(DirectiveValue(b"abc".to_vec())
            .parse_as_delta_seconds_floor()
            .is_err());

        // Non-UTF8 bytes are rejected with the same utf-8 error as the strict parser.
        let v = DirectiveValue(b"ba\xFFr".to_vec());
        assert_eq!(
            v.parse_as_delta_seconds_floor()
                .unwrap_err()
                .context
                .unwrap()
                .to_string(),
            "could not parse value as utf8",
        );
    }

    #[test]
    fn test_cache_control_allow_float_seconds_non_utf8_value() {
        // Non-UTF8 bytes inside `max-age` should still produce the utf-8 error
        // when the float-permitting flag is on, matching the strict parser.
        let mut resp = response::Builder::new().body(()).unwrap();
        resp.headers_mut().insert(
            CACHE_CONTROL,
            HeaderValue::from_bytes(b"max-age=ba\xFFr").unwrap(),
        );
        let (parts, _) = resp.into_parts();
        let cc = CacheControl::from_resp_headers(&parts)
            .unwrap()
            .with_float_seconds();
        assert_eq!(
            cc.max_age().unwrap_err().context.unwrap().to_string(),
            "could not parse value as utf8",
        );
    }

    #[test]
    fn test_cache_control_allow_float_seconds_default_off() {
        // Default (strict) parsing: fractional values produce an error, and
        // [InterpretCacheControl::fresh_duration] returns None, matching the
        // pre-existing behavior.
        let resp = build_response(CACHE_CONTROL, "max-age=10.7");
        let cc = CacheControl::from_resp_headers(&resp).unwrap();
        assert!(!cc.allow_float_seconds);
        assert!(cc.max_age().is_err());
        assert!(cc.fresh_duration().is_none());
    }

    #[test]
    fn test_cache_control_with_float_seconds() {
        // `max-age` with a fractional value is floored when the flag is on.
        let resp = build_response(CACHE_CONTROL, "max-age=10.7");
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert!(cc.allow_float_seconds);
        assert_eq!(cc.max_age().unwrap().unwrap(), 10);
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(10));

        // `s-maxage` still wins over `max-age` and is also floored.
        let resp = build_response(CACHE_CONTROL, "s-maxage=3600.99, max-age=1800");
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert_eq!(cc.s_maxage().unwrap().unwrap(), 3600);
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(3600));

        // `stale-while-revalidate` and `stale-if-error` also pick up flooring.
        let resp = build_response(
            CACHE_CONTROL,
            "max-age=10, stale-while-revalidate=60.5, stale-if-error=30.9",
        );
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert_eq!(cc.stale_while_revalidate().unwrap().unwrap(), 60);
        assert_eq!(cc.stale_if_error().unwrap().unwrap(), 30);
        assert_eq!(
            cc.serve_stale_while_revalidate_duration().unwrap(),
            Duration::from_secs(60)
        );
        assert_eq!(
            cc.serve_stale_if_error_duration().unwrap(),
            Duration::from_secs(30)
        );

        // Integer values are unaffected when the flag is on.
        let resp = build_response(CACHE_CONTROL, "max-age=12345");
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert_eq!(cc.fresh_duration().unwrap(), Duration::from_secs(12345));

        // Invalid (non-numeric, negative) values still fail to parse under the flag.
        let resp = build_response(CACHE_CONTROL, "max-age=abc");
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert!(cc.max_age().is_err());

        let resp = build_response(CACHE_CONTROL, "max-age=-1.5");
        let cc = CacheControl::from_resp_headers(&resp)
            .unwrap()
            .with_float_seconds();
        assert!(cc.max_age().is_err());
    }
}