apollo-router 2.16.0

A configurable, high-performance routing runtime for Apollo Federation 🚀
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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use http::HeaderMap;
use http::HeaderValue;
use http::header::AGE;
use http::header::CACHE_CONTROL;
use serde::Deserialize;
use serde::Serialize;
use tower::BoxError;

/// Represents a parsed `Cache-Control` header, used in both request and response contexts:
///
/// - **Request**: sent from the client to the router, or from the router to a subgraph,
///   to control how caches should handle the request.
/// - **Response**: returned from a subgraph to the router, or from the router to the client,
///   to control how caches should store and serve the response.
///
/// Fields are annotated to indicate whether they are request-only, response-only, or shared.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CacheControl {
    // -- shared between request and response --
    /// Unix timestamp (seconds) at which this struct was created. Used to compute elapsed time
    /// for TTL calculations.
    created: u64,

    /// `max-age=N`: in a response, indicates the response remains fresh for N seconds after it
    /// was generated. In a request, indicates the client prefers a response whose age is less
    /// than or equal to N seconds (RFC 9111 §5.2.1.1, §5.2.2.1).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    max_age: Option<u64>,

    /// `no-cache`: the cache must revalidate with the origin before serving a stored response.
    ///
    /// In a request, asks caches to bypass stored responses and revalidate.
    /// In a response, requires revalidation before each reuse even when disconnected from origin.
    #[serde(skip_serializing_if = "is_false", default)]
    no_cache: bool,

    /// `no-store`: caches must not store the request or response.
    ///
    /// In a request, asks caches to refrain from storing the request and corresponding response.
    /// In a response, indicates that caches of any kind should not store this response.
    #[serde(skip_serializing_if = "is_false", default)]
    no_store: bool,

    /// `no-transform`: intermediaries must not transform the content, in both request and response
    /// contexts (RFC 9111 §5.2.1.6, §5.2.2.6).
    ///
    /// The router does not transform content, so this directive does not affect its caching
    /// behavior. It is parsed and propagated to the client for downstream caches to honor.
    #[serde(skip_serializing_if = "is_false", default)]
    no_transform: bool,

    /// `stale-if-error=N`: the cache may reuse a stale response when an upstream error occurs
    /// (HTTP 500, 502, 503, or 504), for up to N seconds after the response went stale.
    ///
    /// Older schema versions stored this field as a boolean; the custom deserializer handles both.
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        deserialize_with = "deserialize_option_u64_or_bool"
    )]
    stale_if_error: Option<u64>,

    // -- request only --
    /// `max-stale[=N]`: the client accepts a stale response, optionally capped at N seconds past
    /// expiry. A bare `max-stale` (no value) is stored as `u64::MAX` (~584 billion years).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    max_stale: Option<u64>,

    /// `min-fresh=N`: the client requires a response that will remain fresh for at least N more seconds.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    min_fresh: Option<u64>,

    /// `only-if-cached`: the client wants a stored response; returns 504 if none is available.
    #[serde(skip_serializing_if = "is_false", default)]
    only_if_cached: bool,

    // -- response only --
    /// Value of the `Age` response header, indicating how many seconds old the response is.
    /// Used to offset `max_age` when computing the remaining TTL.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    age: Option<u64>,

    /// `s-maxage=N`: overrides `max-age` for shared caches. Takes precedence over `max-age`
    /// in [`max_age()`] and TTL calculations since the router acts as a shared cache.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    s_max_age: Option<u64>,

    /// `must-revalidate`: once stale, the cache must not serve the response without revalidating.
    #[serde(skip_serializing_if = "is_false", default)]
    must_revalidate: bool,

    /// `proxy-revalidate`: equivalent to `must-revalidate` but applies only to shared caches.
    #[serde(skip_serializing_if = "is_false", default)]
    proxy_revalidate: bool,

    /// `must-understand`: the cache should only store the response if it understands the
    /// caching requirements for the response's status code. The router does not enforce this;
    /// it is parsed and propagated to the client.
    #[serde(skip_serializing_if = "is_false", default)]
    must_understand: bool,

    /// `private`: the response MUST NOT be stored by a shared cache; it may be stored in a
    /// private cache (e.g., a browser cache). Takes precedence over `public` — see [`public()`].
    /// (RFC 9111 §5.2.2.7)
    #[serde(skip_serializing_if = "is_false", default)]
    private: bool,

    /// `public`: the response may be stored in a shared cache even when it would otherwise
    /// not be cacheable (e.g., when an `Authorization` header is present).
    #[serde(skip_serializing_if = "is_false", default)]
    public: bool,

    /// `immutable`: indicates the response body will not change while it is fresh.
    /// The router does not currently use this to skip revalidation; it is parsed and propagated.
    #[serde(skip_serializing_if = "is_false", default)]
    immutable: bool,

    /// `stale-while-revalidate=N`: the cache may serve a stale response for up to N seconds
    /// while revalidating in the background. The router does not currently honor this directive.
    ///
    /// Older schema versions stored this field as a boolean; the custom deserializer handles both.
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        deserialize_with = "deserialize_option_u64_or_bool"
    )]
    stale_while_revalidate: Option<u64>,
}

/// Deserializes an `Option<u64>` field that may appear as a `u64` (current schema) or a `bool`
/// (legacy schema). A boolean value is treated as `None` since no duration is available.
fn deserialize_option_u64_or_bool<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum BoolOrU64 {
        Duration(u64),
        #[allow(dead_code)]
        Bool(bool),
    }

    Ok(match Option::<BoolOrU64>::deserialize(deserializer)? {
        Some(BoolOrU64::Duration(n)) => Some(n),
        Some(BoolOrU64::Bool(_)) | None => None,
    })
}

fn is_false(b: &bool) -> bool {
    !b
}

impl Default for CacheControl {
    fn default() -> Self {
        Self {
            created: now_epoch_seconds(),
            age: None,
            max_age: None,
            s_max_age: None,
            no_cache: false,
            no_store: false,
            no_transform: false,
            must_revalidate: false,
            proxy_revalidate: false,
            must_understand: false,
            private: false,
            public: false,
            immutable: false,
            stale_while_revalidate: None,
            stale_if_error: None,
            max_stale: None,
            min_fresh: None,
            only_if_cached: false,
        }
    }
}

impl TryFrom<&HeaderMap> for CacheControl {
    type Error = BoxError;

    fn try_from(headers: &HeaderMap) -> Result<Self, Self::Error> {
        let mut cache_control = Self::default();

        if let Some(age) = headers.get(AGE) {
            let age = age.to_str()?.trim().parse()?;
            cache_control.age = Some(age);
        }

        let mut header_values = headers.get_all(CACHE_CONTROL).iter().peekable();

        // if there is no cache-control header at all, return early, setting no_store to true
        if header_values.peek().is_none() {
            // TODO: defaulting to no_store here is correct for subgraph responses (no header = don't
            // cache), but wrong for client requests (no header = no preference). TryFrom is currently
            // used for both. In practice this is harmless because all callsites that parse request
            // headers are guarded with contains_key(CACHE_CONTROL) before calling TryFrom, so the
            // no_store default is never reached for requests. Still, splitting into separate
            // constructors would make this contract explicit and eliminate the latent risk.
            cache_control.no_store = true;
            return Ok(cache_control);
        }

        for header_value in header_values {
            for directive in header_value.to_str()?.split(',') {
                let (key, value) = parse_directive(directive)?;

                let parse_value = |value: Option<&str>| -> Result<u64, BoxError> {
                    let value = value.ok_or_else(|| {
                        format!("invalid Cache-Control header value: {directive}")
                    })?;
                    Ok(value.parse()?)
                };

                match key {
                    "immutable" => cache_control.immutable = true,
                    "must-revalidate" => cache_control.must_revalidate = true,
                    "must-understand" => cache_control.must_understand = true,
                    // RFC 9111 §5.2.2.4: bare no-cache means "always revalidate before serving".
                    // The field-specific form no-cache="Authorization" means "you may cache this
                    // response, but strip the listed header fields before forwarding". Since the
                    // router does not forward raw subgraph headers as part of cached responses,
                    // the field list has no actionable meaning and we can treat the response as
                    // freely cacheable.
                    "no-cache" if value.is_none() => cache_control.no_cache = true,
                    "no-store" => cache_control.no_store = true,
                    "no-transform" => cache_control.no_transform = true,
                    "only-if-cached" => cache_control.only_if_cached = true,
                    "private" => cache_control.private = true,
                    "proxy-revalidate" => cache_control.proxy_revalidate = true,
                    "public" => cache_control.public = true,

                    "max-age" => cache_control.max_age = Some(parse_value(value)?),
                    "s-maxage" => cache_control.s_max_age = Some(parse_value(value)?),
                    "stale-if-error" => {
                        // RFC 5861 requires a delta-seconds argument, but old router versions
                        // accepted the bare form (no value) and cached the response normally.
                        // To avoid regressing those deployments, treat bare stale-if-error as
                        // u64::MAX, mirroring the max-stale handling above.
                        let value = value.map_or(Ok(u64::MAX), |v| v.parse())?;
                        cache_control.stale_if_error = Some(value);
                    }
                    // Unlike stale-if-error, bare stale-while-revalidate (no =N) is not
                    // given a u64::MAX fallback because it was never accepted by old router
                    // versions (old code also returned Err here). Erroring is intentional.
                    "stale-while-revalidate" => {
                        cache_control.stale_while_revalidate = Some(parse_value(value)?)
                    }
                    "min-fresh" => cache_control.min_fresh = Some(parse_value(value)?),

                    "max-stale" => {
                        // max-stale without a value means to accept any age, so use u64::MAX if no
                        // value is provided (works out to 584 billion years)
                        let value = value.map_or(Ok(u64::MAX), |v| v.parse())?;
                        cache_control.max_stale = Some(value);
                    }

                    // RFC 9111 §5.2 allows extension directives, so don't error on unrecognized keys
                    _ => {}
                }
            }
        }

        // private overrules public
        if cache_control.public && cache_control.private {
            cache_control.public = false;
        }

        // If every directive was an unrecognized extension, we have no basis for caching.
        if !cache_control.has_caching_directives() {
            cache_control.no_store = true;
        }

        Ok(cache_control)
    }
}

impl CacheControl {
    // --- Construction ---

    pub(crate) fn default_no_store() -> Self {
        Self {
            no_store: true,
            ..Self::default()
        }
    }

    /// Sets `max_age` to the given TTL if `max_age` is not already present in the header.
    /// Has no effect if `no_store` is set.
    pub(crate) fn with_default_ttl(mut self, ttl: Option<Duration>) -> Self {
        if self.no_store {
            return self;
        }

        let ttl: Option<u64> = ttl.as_ref().map(Duration::as_secs);
        self.max_age = self.max_age.or(ttl);

        self
    }

    // --- Serialization ---

    /// Formats this cache control as a `Cache-Control` response header value.
    ///
    /// `max-age` and `s-maxage` are decremented by elapsed time since this struct was created,
    /// so the emitted value reflects the remaining freshness at the time of serialization.
    /// `stale-while-revalidate` and `stale-if-error` are emitted as their raw stored values —
    /// these windows are measured from when the response goes stale, not from receipt.
    ///
    /// Request-only directives (`min-fresh`, `max-stale`, `only-if-cached`) are intentionally
    /// omitted — they have no meaning in a response header.
    pub(crate) fn to_response_header_value(&self) -> String {
        let mut parts: Vec<String> = Vec::new();

        // If no-store, emit just that directive. Per RFC 9111, no-store is the strongest cache
        // directive and makes all others irrelevant. Note that max-age=0 is intentionally not
        // treated as no-store: max-age=0 means "expired, always revalidate", whereas no-store
        // means "do not cache at all". The router determines cacheability via should_store().
        // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#preventing_storing
        if self.no_store {
            return "no-store".to_string();
        }

        let elapsed = self.elapsed();

        if let Some(max_age) = self.max_age {
            parts.push(format!("max-age={}", remaining_ttl(max_age, elapsed)));
        }
        if let Some(s_max_age) = self.s_max_age {
            parts.push(format!("s-maxage={}", remaining_ttl(s_max_age, elapsed)));
        }
        if self.no_cache {
            parts.push("no-cache".to_string());
        }
        if self.no_transform {
            parts.push("no-transform".to_string());
        }
        if self.must_revalidate {
            parts.push("must-revalidate".to_string());
        }
        if self.proxy_revalidate {
            parts.push("proxy-revalidate".to_string());
        }
        if self.must_understand {
            parts.push("must-understand".to_string());
        }
        if self.private {
            parts.push("private".to_string());
        }
        if self.public && !self.private {
            parts.push("public".to_string());
        }
        if self.immutable {
            parts.push("immutable".to_string());
        }
        if let Some(stale) = self.stale_while_revalidate {
            parts.push(format!("stale-while-revalidate={stale}"));
        }
        if let Some(stale) = self.stale_if_error {
            parts.push(format!("stale-if-error={stale}"));
        }

        parts.join(",")
    }

    /// Writes the `Cache-Control` (and `Age` if applicable) headers into the given header map.
    pub(crate) fn update_response_headers(&self, headers: &mut HeaderMap) -> Result<(), BoxError> {
        let value = self.to_response_header_value();
        if !value.is_empty() {
            headers.insert(CACHE_CONTROL, HeaderValue::from_str(&value)?);
        }

        if let Some(age) = self.age
            && age > 0
        {
            headers.insert(AGE, age.into());
        }

        Ok(())
    }

    // --- Merging ---

    /// Propagates `no_store` from `other` into `self`, leaving all other fields unchanged.
    /// Used to apply a request's `no-store` directive to the accumulated response cache control.
    pub(crate) fn merge_no_store(&mut self, other: &Self) {
        self.no_store |= other.no_store;
    }

    /// Merges two `CacheControl` values, taking the most restrictive of each directive.
    /// TTL fields are decremented by elapsed time so the result reflects freshness as of now.
    pub(crate) fn merge(&self, other: &Self) -> Self {
        self.merge_inner(other, now_epoch_seconds(), true)
    }

    /// Like [`merge`], but does not account for elapsed time when computing remaining TTLs.
    /// Used when merging cached entries for telemetry, where the original TTL should be preserved.
    pub(crate) fn merge_without_ttl_update(&self, other: &Self) -> Self {
        self.merge_inner(other, now_epoch_seconds(), false)
    }

    fn merge_inner(&self, other: &Self, now_epoch: u64, update_ttl: bool) -> Self {
        // If either side has no-store, the merged result is no-store only. Per RFC 9111, no-store
        // is the strongest cache directive and makes all others irrelevant.
        // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#preventing_storing
        if self.no_store || other.no_store {
            return Self {
                created: now_epoch,
                no_store: true,
                ..Self::default()
            };
        }

        let now = update_ttl.then_some(now_epoch);

        let private = self.private || other.private;
        Self {
            created: now_epoch,
            age: None,
            max_age: minimum_optional_value(
                self.remaining_max_age(now),
                other.remaining_max_age(now),
            ),
            s_max_age: minimum_optional_value(
                self.remaining_s_max_age(now),
                other.remaining_s_max_age(now),
            ),
            no_cache: self.no_cache || other.no_cache,
            no_store: false,
            no_transform: self.no_transform || other.no_transform,
            must_revalidate: self.must_revalidate || other.must_revalidate,
            proxy_revalidate: self.proxy_revalidate || other.proxy_revalidate,
            must_understand: self.must_understand || other.must_understand,
            private,
            public: !private && (self.public || other.public),
            immutable: self.immutable || other.immutable,
            stale_while_revalidate: minimum_optional_value(
                self.stale_while_revalidate,
                other.stale_while_revalidate,
            ),
            stale_if_error: minimum_optional_value(self.stale_if_error, other.stale_if_error),
            max_stale: minimum_optional_value(
                self.remaining_max_stale(now),
                other.remaining_max_stale(now),
            ),
            min_fresh: maximum_optional_value(
                self.remaining_min_fresh(now),
                other.remaining_min_fresh(now),
            ),
            only_if_cached: self.only_if_cached || other.only_if_cached,
        }
    }

    // --- Accessors ---

    /// Returns `true` if the `no-cache` directive is set.
    pub(crate) fn no_cache(&self) -> bool {
        self.no_cache
    }

    /// Returns `true` if the `no-store` directive is literally set in the parsed header.
    ///
    /// Use this when you need to check the specific directive (e.g., for telemetry or generating
    /// cache-control warnings). For caching decisions, prefer [`should_store()`], which also
    /// accounts for TTL expiry.
    pub(crate) fn no_store(&self) -> bool {
        self.no_store
    }

    /// Returns `true` if the `private` directive is set.
    pub(crate) fn private(&self) -> bool {
        self.private
    }

    /// Returns `true` if the `public` directive is set.
    /// Note: `private` takes precedence — both will not be true simultaneously.
    pub(crate) fn public(&self) -> bool {
        self.public
    }

    /// Returns `true` if this response should be stored in the cache.
    ///
    /// A response should be stored if `no-store` is not set and the TTL (if present) has not
    /// already expired. Prefer this over [`no_store()`] for caching decisions.
    pub(crate) fn should_store(&self) -> bool {
        !self.no_store && self.ttl().is_none_or(|ttl| ttl > 0)
    }

    /// Returns `true` if a cached response can be served to the client right now.
    /// A response can be used if `no-cache` is not set and the remaining TTL (if present) is > 0.
    ///
    /// Note: entries at exactly `remaining_ttl = 0` are treated as expired. This is stricter than
    /// the old behavior (which allowed serving at the boundary) but matches RFC 9111 §4.2, which
    /// defines freshness as `freshness_lifetime > current_age` (strict greater-than).
    // TODO: honor stale-while-revalidate
    pub(crate) fn can_use(&self) -> bool {
        !self.no_cache && self.remaining_ttl().is_none_or(|ttl| ttl > 0)
    }

    /// Returns `true` if any directive that carries caching intent is present.
    /// Used after parsing to detect headers that contain only unrecognized extension directives
    /// (e.g. `cdn-cache-control=300`), which should be treated as `no-store` since there are no
    /// freshness or cacheability instructions the router can act on.
    ///
    /// `immutable`, `no-transform`, and `must-understand` are intentionally excluded: without an
    /// accompanying `max-age` or `s-maxage`, `immutable` provides no TTL and would cause the
    /// response to be cached indefinitely. The other two have no effect on caching decisions.
    fn has_caching_directives(&self) -> bool {
        self.max_age.is_some()
            || self.s_max_age.is_some()
            || self.no_cache
            || self.no_store
            || self.public
            || self.private
            || self.must_revalidate
            || self.proxy_revalidate
            || self.stale_while_revalidate.is_some()
            || self.stale_if_error.is_some()
    }

    /// Returns the value of the `Age` header, if present.
    pub(crate) fn age(&self) -> Option<u64> {
        self.age
    }

    /// Returns the effective max age in seconds, preferring `s-maxage` over `max-age`.
    /// `s-maxage` is used because the router acts as a shared cache.
    pub(crate) fn max_age(&self) -> Option<u64> {
        self.s_max_age.or(self.max_age)
    }

    /// Returns the remaining TTL in seconds, computed as `max_age - age`.
    /// This accounts for the `Age` header (how old the response was when received) but not
    /// for time elapsed since this struct was created. Use [`remaining_ttl`] for a fully time-relative TTL.
    pub(crate) fn ttl(&self) -> Option<u64> {
        self.remaining_duration(self.max_age(), None)
    }

    /// Returns the remaining TTL in seconds as of now, computed as `max_age - age - elapsed`
    /// where `elapsed` is the time since this struct was created.
    pub(crate) fn remaining_ttl(&self) -> Option<u64> {
        self.remaining_duration(self.max_age(), Some(now_epoch_seconds()))
    }

    // --- Private helpers ---

    /// Returns the number of seconds elapsed since this struct was created.
    fn elapsed(&self) -> u64 {
        now_epoch_seconds().saturating_sub(self.created)
    }

    /// Computes a remaining duration in seconds, subtracting `age` and optionally elapsed time.
    ///
    /// If `now` is `Some`, elapsed time since `created` is also subtracted. If `None`, only
    /// the `Age` header offset is applied (useful for merge operations that don't update the TTL).
    fn remaining_duration(&self, value: Option<u64>, now: Option<u64>) -> Option<u64> {
        let value = value?;
        // A future-dated created (clock skew) means elapsed would be negative; treat as expired.
        if let Some(now) = now
            && now < self.created
        {
            return Some(0);
        }
        let elapsed = now.map(|now| now.saturating_sub(self.created));
        let subtrahend = self.age.unwrap_or(0).saturating_add(elapsed.unwrap_or(0));
        Some(value.saturating_sub(subtrahend))
    }

    fn remaining_max_age(&self, now: Option<u64>) -> Option<u64> {
        self.remaining_duration(self.max_age, now)
    }

    fn remaining_s_max_age(&self, now: Option<u64>) -> Option<u64> {
        self.remaining_duration(self.s_max_age, now)
    }

    fn remaining_max_stale(&self, now: Option<u64>) -> Option<u64> {
        self.remaining_duration(self.max_stale, now)
    }

    fn remaining_min_fresh(&self, now: Option<u64>) -> Option<u64> {
        self.remaining_duration(self.min_fresh, now)
    }
}

/// Returns the smaller of two optional values. If one is `None`, the other is returned.
fn minimum_optional_value<T: Ord>(x: Option<T>, y: Option<T>) -> Option<T> {
    match (x, y) {
        (None, None) => None,
        (Some(x), None) => Some(x),
        (None, Some(y)) => Some(y),
        (Some(x), Some(y)) => Some(std::cmp::min(x, y)),
    }
}

/// Returns the larger of two optional values. If one is `None`, the other is returned.
fn maximum_optional_value<T: Ord>(x: Option<T>, y: Option<T>) -> Option<T> {
    match (x, y) {
        (None, None) => None,
        (Some(x), None) => Some(x),
        (None, Some(y)) => Some(y),
        (Some(x), Some(y)) => Some(std::cmp::max(x, y)),
    }
}

/// Returns the current time as seconds since the Unix epoch.
fn now_epoch_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("we should not run before EPOCH")
        .as_secs()
}

/// Parses a single Cache-Control directive of the form `key` or `key=value`.
/// Parses a single Cache-Control directive of the form `key` or `key=value`.
/// Values may themselves contain `=` (e.g. base64 or extension directives); everything
/// after the first `=` is treated as the value.
fn parse_directive(directive: &str) -> Result<(&str, Option<&str>), BoxError> {
    let mut parts = directive.trim().splitn(2, '=');
    let key = parts
        .next()
        .filter(|k| !k.is_empty())
        .ok_or("invalid Cache-Control header value")?;
    Ok((key, parts.next()))
}

fn remaining_ttl(ttl: u64, elapsed: u64) -> u64 {
    ttl.saturating_sub(elapsed)
}

#[cfg(test)]
impl CacheControl {
    /// Returns the remaining TTL in seconds at the given Unix timestamp.
    /// Used in tests to assert TTL values at a specific point in time without depending on the current clock.
    fn remaining_ttl_at(&self, now: u64) -> Option<u64> {
        self.remaining_duration(self.max_age(), Some(now))
    }

    /// Sets `created` to 0, making time-dependent fields deterministic in snapshot tests.
    #[allow(dead_code)]
    pub(crate) fn zero_out_created(&mut self) {
        self.created = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn merge_ttl() {
        let now = now_epoch_seconds();

        let first = CacheControl {
            created: now - 10,
            max_age: Some(40),
            ..Default::default()
        };

        let second = CacheControl {
            created: now - 20,
            max_age: Some(60),
            ..Default::default()
        };

        assert_eq!(first.remaining_ttl_at(now), Some(30));
        assert_eq!(second.remaining_ttl_at(now), Some(40));

        let merged = first.merge_inner(&second, now, true);

        assert_eq!(merged.ttl(), Some(30));
        assert_eq!(merged.remaining_ttl_at(now), Some(30));
        assert!(merged.can_use());
    }

    #[test]
    fn merge_nostore() {
        let now = now_epoch_seconds();

        let first = CacheControl {
            created: now,
            max_age: Some(40),
            no_store: true,
            ..Default::default()
        };

        let second = CacheControl {
            created: now,
            max_age: Some(60),
            no_store: false,
            public: true,
            ..Default::default()
        };

        let merged = first.merge_inner(&second, now, true);
        assert!(merged.no_store);
        assert!(!merged.public);
        assert!(merged.can_use());
    }

    #[test]
    fn merge_nocache() {
        let now = now_epoch_seconds();

        let first = CacheControl {
            no_cache: true,
            ..Default::default()
        };

        let second = CacheControl {
            no_cache: false,
            ..Default::default()
        };

        let merged = first.merge_inner(&second, now, true);
        assert!(merged.no_cache);
        assert!(!merged.can_use());
    }

    #[test]
    fn remove_conflicts() {
        let now = now_epoch_seconds();

        let first = CacheControl {
            created: now,
            max_age: Some(40),
            no_store: true,
            must_revalidate: true,
            no_cache: true,
            private: true,
            ..Default::default()
        };
        let cache_control_header = first.to_response_header_value();
        assert_eq!(cache_control_header, "no-store".to_string());
    }

    #[test]
    fn merge_public_private() {
        let now = now_epoch_seconds();

        let first = CacheControl {
            created: now,
            max_age: Some(40),
            public: true,
            private: false,
            ..Default::default()
        };

        let second = CacheControl {
            created: now,
            max_age: Some(60),
            public: false,
            private: true,
            ..Default::default()
        };

        let merged = first.merge_inner(&second, now, true);
        assert!(!merged.public());
        assert!(merged.private());
        assert!(merged.can_use());
    }

    #[test]
    fn create_expired_cache_control() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now,
            max_age: Some(40),
            age: Some(50),
            public: true,
            private: false,
            ..Default::default()
        };
        assert!(!cc.should_store()); // Because age is bigger than max_age

        let cc = CacheControl {
            created: now + 1000,
            max_age: Some(40),
            age: Some(50),
            public: true,
            private: false,
            ..Default::default()
        };
        assert!(!cc.can_use()); // Because created is bigger than now
        assert!(!cc.should_store()); // Because age is bigger than max_age
    }

    #[test]
    fn future_dated_created_is_treated_as_expired() {
        // If created is in the future (clock skew), the entry must not be served.
        // age < max_age so this would be fresh under a normal clock.
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now + 1000,
            max_age: Some(60),
            age: None,
            ..Default::default()
        };
        assert_eq!(cc.remaining_ttl(), Some(0));
        assert!(!cc.can_use());
    }

    #[test]
    fn deserialize_stale_while_revalidate_as_bool_succeeds() {
        // Old Redis entries may have stored stale_while_revalidate as a boolean.
        // A boolean value is treated as None since no duration is available.
        let json = r#"{"created":0,"staleWhileRevalidate":true}"#;
        let cc: CacheControl = serde_json::from_str(json).unwrap();
        assert_eq!(cc.stale_while_revalidate, None);

        let json = r#"{"created":0,"staleWhileRevalidate":false}"#;
        let cc: CacheControl = serde_json::from_str(json).unwrap();
        assert_eq!(cc.stale_while_revalidate, None);
    }

    #[test]
    fn deserialize_stale_while_revalidate_as_number_works() {
        let json = r#"{"created":0,"staleWhileRevalidate":60}"#;
        let cc: CacheControl = serde_json::from_str(json).unwrap();
        assert_eq!(cc.stale_while_revalidate, Some(60));
    }

    // --- Parsing (TryFrom<&HeaderMap>) ---

    fn header_map(pairs: &[(&str, &str)]) -> http::HeaderMap {
        pairs
            .iter()
            .fold(http::HeaderMap::new(), |mut map, (k, v)| {
                map.insert(
                    http::header::HeaderName::from_bytes(k.as_bytes()).unwrap(),
                    http::HeaderValue::from_str(v).unwrap(),
                );
                map
            })
    }

    #[test]
    fn parse_missing_cache_control_header() {
        // No Cache-Control header should default to no_store per pre-existing behavior
        let cc = CacheControl::try_from(&http::HeaderMap::new()).unwrap();
        assert!(cc.no_store());
    }

    #[test]
    fn parse_max_age() {
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "max-age=60")])).unwrap();
        assert_eq!(cc.max_age, Some(60));
        assert_eq!(cc.s_max_age, None);
    }

    #[test]
    fn parse_s_maxage() {
        // s-maxage should be stored separately, not collapsed into max_age
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "s-maxage=30")])).unwrap();
        assert_eq!(cc.s_max_age, Some(30));
        assert_eq!(cc.max_age, None);
    }

    #[test]
    fn parse_s_maxage_and_max_age_kept_separate() {
        // Both directives present: must not be collapsed together
        let cc =
            CacheControl::try_from(&header_map(&[("cache-control", "max-age=60,s-maxage=30")]))
                .unwrap();
        assert_eq!(cc.max_age, Some(60));
        assert_eq!(cc.s_max_age, Some(30));
        // max_age() getter prefers s-maxage (router acts as shared cache)
        assert_eq!(cc.max_age(), Some(30));
    }

    #[test]
    fn parse_no_cache() {
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "no-cache")])).unwrap();
        assert!(cc.no_cache());
    }

    #[test]
    fn parse_no_store() {
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "no-store")])).unwrap();
        assert!(cc.no_store());
    }

    #[test]
    fn parse_private_overrides_public() {
        // If both private and public are present, private wins
        let cc =
            CacheControl::try_from(&header_map(&[("cache-control", "public,private")])).unwrap();
        assert!(cc.private());
        assert!(!cc.public());
    }

    #[test]
    fn parse_age_header() {
        let cc = CacheControl::try_from(&header_map(&[
            ("cache-control", "max-age=60"),
            ("age", "10"),
        ]))
        .unwrap();
        assert_eq!(cc.age(), Some(10));
        // TTL should account for age: 60 - 10 = 50
        assert_eq!(cc.ttl(), Some(50));
    }

    #[test]
    fn parse_max_stale_without_value() {
        // Bare max-stale means accept any stale age (u64::MAX sentinel)
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "max-stale")])).unwrap();
        assert_eq!(cc.max_stale, Some(u64::MAX));
    }

    #[test]
    fn parse_max_stale_with_value() {
        let cc =
            CacheControl::try_from(&header_map(&[("cache-control", "max-stale=120")])).unwrap();
        assert_eq!(cc.max_stale, Some(120));
    }

    #[test]
    fn parse_extension_directives_ignored() {
        // RFC 9111 §5.2: unknown directives must be silently ignored
        let cc = CacheControl::try_from(&header_map(&[(
            "cache-control",
            "max-age=60,cdn-cache-control=120,some-future-directive",
        )]))
        .unwrap();
        assert_eq!(cc.max_age, Some(60));
    }

    #[test]
    fn parse_extension_only_header_sets_no_store() {
        // A header with only unrecognized extension directives has no caching instructions
        // the router can act on, so has_caching_directives() returns false and no_store is set.
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "cdn-cache-control=300")]))
            .unwrap();
        assert!(cc.no_store);
        assert!(!cc.should_store());
    }

    #[test]
    fn parse_stale_if_error_with_value() {
        // Regression test for ROUTER-1830: stale-if-error=N was previously parsed as a
        // boolean-only field, causing SUBREQUEST_HTTP_ERROR when a value was present.
        let cc = CacheControl::try_from(&header_map(&[(
            "cache-control",
            "public, max-age=60, stale-if-error=600",
        )]))
        .unwrap();
        assert_eq!(cc.max_age, Some(60));
        assert!(cc.public);
        assert_eq!(cc.stale_if_error, Some(600));
    }

    #[test]
    fn parse_bare_stale_if_error_defaults_to_max() {
        // Bare stale-if-error (no =N) is not defined by RFC 5861 but was accepted by old router
        // versions. For backward compat it is treated as u64::MAX, mirroring max-stale behavior.
        let cc = CacheControl::try_from(&header_map(&[(
            "cache-control",
            "max-age=60, stale-if-error",
        )]))
        .unwrap();
        assert_eq!(cc.max_age, Some(60));
        assert_eq!(cc.stale_if_error, Some(u64::MAX));
    }

    #[test]
    fn parse_bare_stale_while_revalidate_errors() {
        // Unlike stale-if-error, bare stale-while-revalidate has never been accepted by any
        // router version, so no u64::MAX fallback is provided. Errors are intentional.
        assert!(
            CacheControl::try_from(&header_map(&[(
                "cache-control",
                "max-age=60, stale-while-revalidate",
            )]))
            .is_err()
        );
    }

    #[test]
    fn parse_multiple_cache_control_headers() {
        // Multiple Cache-Control headers should be merged
        let mut map = http::HeaderMap::new();
        map.append(
            http::header::CACHE_CONTROL,
            http::HeaderValue::from_static("max-age=60"),
        );
        map.append(
            http::header::CACHE_CONTROL,
            http::HeaderValue::from_static("no-transform"),
        );
        let cc = CacheControl::try_from(&map).unwrap();
        assert_eq!(cc.max_age, Some(60));
        assert!(cc.no_transform);
    }

    // --- s-maxage preservation through merge and display ---

    #[test]
    fn s_maxage_preserved_through_merge() {
        // The old code collapsed s-maxage into max-age during merge.
        // Verify the new code keeps them as separate fields.
        let now = now_epoch_seconds();
        let first = CacheControl {
            created: now,
            s_max_age: Some(30),
            max_age: None,
            ..Default::default()
        };
        let second = CacheControl {
            created: now,
            s_max_age: Some(60),
            max_age: Some(120),
            ..Default::default()
        };
        let merged = first.merge_inner(&second, now, true);
        assert_eq!(merged.s_max_age, Some(30));
        assert_eq!(merged.max_age, Some(120));
        // Effective TTL uses s_max_age
        assert_eq!(merged.max_age(), Some(30));
    }

    #[test]
    fn s_maxage_in_display() {
        // s-maxage and max-age should be emitted as separate directives
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now,
            s_max_age: Some(30),
            max_age: Some(60),
            ..Default::default()
        };
        let header = cc.to_response_header_value();
        assert!(header.contains("s-maxage=30"), "got: {header}");
        assert!(header.contains("max-age=60"), "got: {header}");
    }

    #[test]
    fn s_maxage_round_trip() {
        // Parse s-maxage from a header, serialize back, confirm it's preserved
        let cc =
            CacheControl::try_from(&header_map(&[("cache-control", "s-maxage=30,max-age=60")]))
                .unwrap();
        let header = cc.to_response_header_value();
        assert!(header.contains("s-maxage="), "got: {header}");
        assert!(header.contains("max-age="), "got: {header}");
    }

    // --- Display ---

    #[test]
    fn response_header_decrements_max_age_by_elapsed() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now - 10,
            max_age: Some(60),
            ..Default::default()
        };
        let header = cc.to_response_header_value();
        // elapsed is ~10s, so max-age should be ~50
        let emitted: u64 = header
            .split(',')
            .find(|d| d.starts_with("max-age="))
            .and_then(|d| d.trim_start_matches("max-age=").parse().ok())
            .unwrap();
        assert!((48..=50).contains(&emitted), "expected ~50, got {emitted}");
    }

    #[test]
    fn response_header_no_store_suppresses_other_directives() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now,
            no_store: true,
            max_age: Some(60),
            no_cache: true,
            ..Default::default()
        };
        assert_eq!(cc.to_response_header_value(), "no-store");
    }

    // --- with_default_ttl ---

    #[test]
    fn with_default_ttl_sets_max_age_when_absent() {
        let cc = CacheControl::default().with_default_ttl(Some(Duration::from_secs(60)));
        assert_eq!(cc.max_age, Some(60));
    }

    #[test]
    fn with_default_ttl_does_not_override_existing_max_age() {
        let cc = CacheControl {
            max_age: Some(30),
            ..Default::default()
        }
        .with_default_ttl(Some(Duration::from_secs(60)));
        assert_eq!(cc.max_age, Some(30));
    }

    #[test]
    fn with_default_ttl_no_op_when_no_store() {
        let cc = CacheControl::default_no_store().with_default_ttl(Some(Duration::from_secs(60)));
        assert_eq!(cc.max_age, None);
    }

    // --- should_store ---

    #[test]
    fn should_store_true_when_fresh() {
        let cc = CacheControl {
            max_age: Some(60),
            ..Default::default()
        };
        assert!(cc.should_store());
    }

    #[test]
    fn should_store_true_when_no_max_age() {
        // No max_age means no expiry, so should still store
        let cc = CacheControl::default();
        assert!(cc.should_store());
    }

    #[test]
    fn should_store_false_when_no_store() {
        assert!(!CacheControl::default_no_store().should_store());
    }

    #[test]
    fn should_store_false_when_immutable_only() {
        // immutable without max-age provides no TTL; treating it as cacheable would store the
        // entry indefinitely. has_caching_directives() intentionally excludes immutable for this
        // reason, so immutable-only headers fall through to no_store=true.
        let cc = CacheControl::try_from(&header_map(&[("cache-control", "immutable")])).unwrap();
        assert!(cc.no_store);
        assert!(!cc.should_store());
    }

    #[test]
    fn should_store_false_when_ttl_zero() {
        // Already expired at time of receipt (age >= max_age)
        let cc = CacheControl {
            max_age: Some(10),
            age: Some(10),
            ..Default::default()
        };
        assert!(!cc.should_store());
    }

    // --- update_response_headers ---

    #[test]
    fn update_response_headers_sets_cache_control() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now,
            max_age: Some(60),
            ..Default::default()
        };
        let mut headers = http::HeaderMap::new();
        cc.update_response_headers(&mut headers).unwrap();
        assert!(headers.contains_key(http::header::CACHE_CONTROL));
        let value = headers[http::header::CACHE_CONTROL].to_str().unwrap();
        assert!(value.contains("max-age="), "got: {value}");
    }

    #[test]
    fn update_response_headers_omits_cache_control_when_empty() {
        // A CacheControl with no directives (e.g. parsed from an extension-only header like
        // cdn-cache-control=300) must not write an empty Cache-Control: header.
        let cc = CacheControl::default();
        let mut headers = http::HeaderMap::new();
        cc.update_response_headers(&mut headers).unwrap();
        assert!(
            !headers.contains_key(http::header::CACHE_CONTROL),
            "expected no Cache-Control header, got: {:?}",
            headers.get(http::header::CACHE_CONTROL)
        );
    }

    #[test]
    fn update_response_headers_sets_age_when_positive() {
        let cc = CacheControl {
            age: Some(15),
            max_age: Some(60),
            ..Default::default()
        };
        let mut headers = http::HeaderMap::new();
        cc.update_response_headers(&mut headers).unwrap();
        assert!(headers.contains_key(http::header::AGE));
    }

    #[test]
    fn update_response_headers_omits_age_when_zero() {
        let cc = CacheControl {
            age: Some(0),
            max_age: Some(60),
            ..Default::default()
        };
        let mut headers = http::HeaderMap::new();
        cc.update_response_headers(&mut headers).unwrap();
        assert!(!headers.contains_key(http::header::AGE));
    }

    // --- merge_without_ttl_update ---

    #[test]
    fn merge_without_ttl_update_ignores_elapsed() {
        // The key distinction between merge and merge_without_ttl_update:
        // merge subtracts elapsed time since creation; merge_without_ttl_update does not.
        // This matters for the telemetry use case where we want to report the original TTL.
        let now = now_epoch_seconds();
        let first = CacheControl {
            created: now - 10,
            max_age: Some(60),
            ..Default::default()
        };
        let second = CacheControl {
            created: now - 10,
            max_age: Some(60),
            ..Default::default()
        };

        // merge accounts for elapsed: 60 - 10s elapsed = 50
        let with_update = first.merge_inner(&second, now, true);
        assert_eq!(with_update.ttl(), Some(50));

        // merge_without_ttl_update ignores elapsed: stays at 60
        let without_update = first.merge_inner(&second, now, false);
        assert_eq!(without_update.ttl(), Some(60));
    }

    #[test]
    fn merge_without_ttl_update_still_takes_minimum() {
        let now = now_epoch_seconds();
        let first = CacheControl {
            created: now,
            max_age: Some(30),
            ..Default::default()
        };
        let second = CacheControl {
            created: now,
            max_age: Some(60),
            ..Default::default()
        };
        let merged = first.merge_inner(&second, now, false);
        assert_eq!(merged.ttl(), Some(30));
    }

    // --- remaining_ttl (public, time-relative) ---

    #[test]
    fn remaining_ttl_accounts_for_elapsed() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now - 10,
            max_age: Some(60),
            ..Default::default()
        };
        // ttl() = 60 (age-relative only, ignores elapsed)
        assert_eq!(cc.ttl(), Some(60));
        // remaining_ttl() = 60 - 10s elapsed = ~50
        let remaining = cc.remaining_ttl().unwrap();
        assert!(
            (48..=50).contains(&remaining),
            "expected ~50, got {remaining}"
        );
    }

    #[test]
    fn remaining_ttl_accounts_for_age_and_elapsed() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now - 5,
            max_age: Some(60),
            age: Some(10),
            ..Default::default()
        };
        // remaining_ttl() = 60 - 10(age) - ~5(elapsed) = ~45
        let remaining = cc.remaining_ttl().unwrap();
        assert!(
            (43..=45).contains(&remaining),
            "expected ~45, got {remaining}"
        );
    }

    #[test]
    fn remaining_ttl_returns_zero_when_expired() {
        let now = now_epoch_seconds();
        let cc = CacheControl {
            created: now,
            max_age: Some(10),
            age: Some(20), // age > max_age: already expired at receipt
            ..Default::default()
        };
        assert_eq!(cc.remaining_ttl(), Some(0));
    }

    #[test]
    fn remaining_ttl_returns_none_without_max_age() {
        let cc = CacheControl::default();
        assert_eq!(cc.remaining_ttl(), None);
    }

    // --- merge_no_store ---

    #[test]
    fn merge_no_store_propagates_from_other() {
        let mut cc = CacheControl {
            max_age: Some(60),
            ..Default::default()
        };
        cc.merge_no_store(&CacheControl::default_no_store());
        assert!(cc.no_store());
        // Other fields should be unaffected
        assert_eq!(cc.max_age, Some(60));
    }

    #[test]
    fn merge_no_store_no_op_when_other_is_not_no_store() {
        let mut cc = CacheControl {
            max_age: Some(60),
            ..Default::default()
        };
        cc.merge_no_store(&CacheControl::default());
        assert!(!cc.no_store());
        assert_eq!(cc.max_age, Some(60));
    }

    // --- max_age() getter ---

    #[test]
    fn max_age_getter_prefers_s_max_age() {
        let cc = CacheControl {
            max_age: Some(60),
            s_max_age: Some(30),
            ..Default::default()
        };
        assert_eq!(cc.max_age(), Some(30));
    }

    #[test]
    fn max_age_getter_falls_back_to_max_age() {
        let cc = CacheControl {
            max_age: Some(60),
            s_max_age: None,
            ..Default::default()
        };
        assert_eq!(cc.max_age(), Some(60));
    }

    #[test]
    fn max_age_getter_returns_none_when_neither_set() {
        assert_eq!(CacheControl::default().max_age(), None);
    }
}