aioduct 0.2.5

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
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
use super::*;

use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};

use bytes::Bytes;
use http::header::{CACHE_CONTROL, ETAG, EXPIRES, LAST_MODIFIED};
use http::{HeaderMap, Method, StatusCode, Uri};

#[path = "tests/expires_freshness.rs"]
mod expires_freshness;
#[path = "tests/helpers.rs"]
mod helpers;
#[path = "tests/store_behavior.rs"]
mod store_behavior;
#[path = "tests/vary.rs"]
mod vary;

#[test]
fn test_cache_store_and_fresh_lookup() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/test".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    let body = Bytes::from("hello");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(resp) => {
            assert_eq!(resp.status, StatusCode::OK);
            assert_eq!(resp.body, Bytes::from("hello"));
        }
        _ => panic!("expected fresh cache hit"),
    }
}

#[test]
fn test_cache_no_store() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/secret".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "no-store".parse().unwrap());
    let body = Bytes::from("secret");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );
    assert!(cache.is_empty());
}

#[test]
fn test_cache_stale_with_etag() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/data".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=0".parse().unwrap());
    headers.insert(ETAG, "\"abc123\"".parse().unwrap());
    let body = Bytes::from("data");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { validators, .. } => {
            assert_eq!(validators.etag.as_deref(), Some("\"abc123\""));
        }
        _ => panic!("expected stale cache hit with validators"),
    }
}

#[test]
fn test_cache_post_not_cached() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/api".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    let body = Bytes::from("result");

    cache.store(
        &Method::POST,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );
    assert!(cache.is_empty());
}

#[test]
fn test_cache_invalidation_on_post() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/resource".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    let body = Bytes::from("data");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );
    assert_eq!(cache.len(), 1);

    cache.invalidate(&Method::POST, &uri);
    assert!(cache.is_empty());
}

#[test]
fn test_max_entries_eviction() {
    let cache = HttpCache::with_config(CacheConfig { max_entries: 2 });
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());

    for i in 0..3 {
        let uri: Uri = format!("http://example.com/{i}").parse().unwrap();
        cache.store(
            &Method::GET,
            &uri,
            StatusCode::OK,
            &headers,
            &Bytes::from("x"),
            &HeaderMap::new(),
        );
    }

    assert_eq!(cache.len(), 2);
}

#[test]
fn test_cache_clear() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    assert!(!cache.is_empty());
    cache.clear();
    assert!(cache.is_empty());
}

#[test]
fn test_cache_config_default() {
    let config = CacheConfig::default();
    assert_eq!(config.max_entries, 256);
}

#[test]
fn test_cache_private_not_stored() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/private".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "private, max-age=60".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    assert!(cache.is_empty());
}

#[test]
fn test_cache_must_revalidate() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/reval".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        CACHE_CONTROL,
        "max-age=3600, must-revalidate".parse().unwrap(),
    );
    headers.insert(ETAG, "\"v1\"".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { validators, .. } => {
            assert_eq!(validators.etag.as_deref(), Some("\"v1\""));
        }
        _ => panic!("expected stale due to must-revalidate"),
    }
}

#[test]
fn test_cache_no_cache_forces_revalidation() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/nc".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "no-cache".parse().unwrap());
    headers.insert(ETAG, "\"v2\"".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { .. } => {}
        _ => panic!("expected stale due to no-cache"),
    }
}

#[test]
fn test_cache_immutable() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/immut".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600, immutable".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(_) => {}
        _ => panic!("expected fresh for immutable entry"),
    }
}

#[test]
fn test_cache_stale_while_revalidate() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/swr".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        CACHE_CONTROL,
        "max-age=0, stale-while-revalidate=3600".parse().unwrap(),
    );
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("stale-ok"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(resp) => {
            assert_eq!(resp.body, Bytes::from("stale-ok"));
        }
        _ => panic!("expected fresh via stale-while-revalidate"),
    }
}

#[test]
fn test_cache_stale_if_error_propagated() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/sie".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        CACHE_CONTROL,
        "max-age=0, stale-if-error=600".parse().unwrap(),
    );
    headers.insert(ETAG, "\"sie\"".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { stale_if_error, .. } => {
            assert_eq!(stale_if_error, Some(Duration::from_secs(600)));
        }
        _ => panic!("expected stale with stale_if_error"),
    }
}

#[test]
fn test_cache_head_method() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/head".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    cache.store(
        &Method::HEAD,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::new(),
        &HeaderMap::new(),
    );
    assert_eq!(cache.len(), 1);
}

#[test]
fn test_cache_invalidation_on_delete() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/resource".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    assert_eq!(cache.len(), 1);
    cache.invalidate(&Method::DELETE, &uri);
    assert!(cache.is_empty());
}

#[test]
fn test_cache_get_does_not_invalidate() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/safe".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    cache.invalidate(&Method::GET, &uri);
    assert_eq!(cache.len(), 1);
}

#[test]
fn test_cache_s_maxage() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/smaxage".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "s-maxage=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(_) => {}
        _ => panic!("expected fresh from s-maxage"),
    }
}

#[test]
fn test_validators_apply_to_request() {
    let validators = Validators {
        etag: Some("\"abc\"".to_string()),
        last_modified: Some("Sun, 06 Nov 1994 08:49:37 GMT".to_string()),
    };
    let mut headers = HeaderMap::new();
    validators.apply_to_request(&mut headers);
    assert!(headers.contains_key(IF_NONE_MATCH));
    assert!(headers.contains_key(IF_MODIFIED_SINCE));
}

#[test]
fn test_cache_lookup_post_is_miss() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/".parse().unwrap();
    match cache.lookup(&Method::POST, &uri, &HeaderMap::new()) {
        CacheLookup::Miss => {}
        _ => panic!("expected miss for POST"),
    }
}

#[test]
fn test_cache_debug() {
    let cache = HttpCache::new();
    let dbg = format!("{cache:?}");
    assert!(dbg.contains("HttpCache"));
}

#[test]
fn test_cache_default() {
    let cache: HttpCache = Default::default();
    assert!(cache.is_empty());
}

#[test]
fn test_cache_expires_based_freshness() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/expires".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(EXPIRES, "Thu, 01 Jan 2099 00:00:00 GMT".parse().unwrap());
    let body = Bytes::from("expires-fresh");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(resp) => {
            assert_eq!(resp.body, Bytes::from("expires-fresh"));
        }
        _ => panic!("expected fresh from Expires header"),
    }
}

#[test]
fn test_cache_expires_based_staleness_with_etag() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/stale-expires".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(EXPIRES, "Thu, 01 Jan 2020 00:00:00 GMT".parse().unwrap());
    headers.insert(ETAG, "\"exp-v1\"".parse().unwrap());
    let body = Bytes::from("expired");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { validators, .. } => {
            assert_eq!(validators.etag.as_deref(), Some("\"exp-v1\""));
        }
        _ => panic!("expected stale due to expired Expires header"),
    }
}

#[test]
fn test_cache_stale_without_validators_is_miss() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/no-validators".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=0".parse().unwrap());
    let body = Bytes::from("no validators");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Miss => {}
        _ => panic!("expected miss for stale entry without validators"),
    }
}

#[test]
fn cache_max_age_zero_without_validators_is_miss() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/max-age-zero-no-validators"
        .parse()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=0".parse().unwrap());
    // No ETag or Last-Modified — no validators

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("should not be retrievable"),
        &HeaderMap::new(),
    );

    // Immediate lookup — max-age=0 means stale right away, no validators → Miss
    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Miss => {}
        CacheLookup::Fresh(_) => panic!("expected Miss, got Fresh"),
        CacheLookup::Stale { .. } => panic!("expected Miss, got Stale"),
    }
}

#[test]
fn test_cache_immutable_with_must_revalidate() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/immut-mr".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        CACHE_CONTROL,
        "max-age=3600, immutable, must-revalidate".parse().unwrap(),
    );
    let body = Bytes::from("immut");

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &body,
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(resp) => {
            assert_eq!(resp.body, Bytes::from("immut"));
        }
        _ => panic!("expected fresh for immutable+must_revalidate entry"),
    }
}

#[test]
fn test_httpdate_parse_november() {
    let result = httpdate_parse("Sun, 06 Nov 1994 08:49:37 GMT");
    assert!(result.is_some());
}

#[test]
fn test_httpdate_parse_december() {
    let result = httpdate_parse("Sun, 25 Dec 2022 12:00:00 GMT");
    assert!(result.is_some());
}

#[test]
fn test_httpdate_parse_all_months() {
    let months = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    for m in &months {
        let date = format!("Mon, 15 {m} 2023 10:30:00 GMT");
        assert!(httpdate_parse(&date).is_some(), "month {m} should parse");
    }
}

#[test]
fn test_httpdate_leap_year() {
    let result = httpdate_parse("Mon, 01 Mar 2024 00:00:00 GMT");
    assert!(result.is_some());
}

#[test]
fn test_cache_config_debug() {
    let config = CacheConfig::default();
    let dbg = format!("{config:?}");
    assert!(dbg.contains("CacheConfig"));
}

#[test]
fn test_cached_response_into_http_response() {
    let cached = CachedResponse {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("resp"),
        age: Duration::from_secs(42),
    };
    let resp = cached.into_http_response();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(resp.headers().get(AGE).unwrap().to_str().unwrap(), "42");
}

#[test]
fn test_validators_apply_only_etag() {
    let validators = Validators {
        etag: Some("\"only-etag\"".to_string()),
        last_modified: None,
    };
    let mut headers = HeaderMap::new();
    validators.apply_to_request(&mut headers);
    assert!(headers.contains_key(IF_NONE_MATCH));
    assert!(!headers.contains_key(IF_MODIFIED_SINCE));
}

#[test]
fn test_validators_apply_only_last_modified() {
    let validators = Validators {
        etag: None,
        last_modified: Some("Sun, 06 Nov 1994 08:49:37 GMT".to_string()),
    };
    let mut headers = HeaderMap::new();
    validators.apply_to_request(&mut headers);
    assert!(!headers.contains_key(IF_NONE_MATCH));
    assert!(headers.contains_key(IF_MODIFIED_SINCE));
}

#[test]
fn test_is_response_cacheable_with_expires() {
    let mut headers = HeaderMap::new();
    headers.insert(EXPIRES, "Thu, 01 Jan 2099 00:00:00 GMT".parse().unwrap());
    assert!(is_response_cacheable(StatusCode::OK, &headers));
}

#[test]
fn test_non_cacheable_status_not_stored() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/500".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::INTERNAL_SERVER_ERROR,
        &headers,
        &Bytes::from("err"),
        &HeaderMap::new(),
    );
    assert!(cache.is_empty());
}

#[test]
fn test_staleness_with_expired_expires_header() {
    // Test the staleness path when expires is in the past (lines 59-67)
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/past-expires".parse().unwrap();
    let mut headers = HeaderMap::new();
    // Expires in the past (year 2020) + etag for validators
    headers.insert(EXPIRES, "Thu, 01 Jan 2020 00:00:00 GMT".parse().unwrap());
    headers.insert(ETAG, "\"expired-v1\"".parse().unwrap());

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("old data"),
        &HeaderMap::new(),
    );

    // Should be stale because expires is in the past
    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { cached, .. } => {
            assert_eq!(cached.body, Bytes::from("old data"));
        }
        CacheLookup::Fresh(_) => panic!("past expires should not be fresh"),
        CacheLookup::Miss => panic!("should find the entry (has validators)"),
    }
}

#[test]
fn test_staleness_with_max_age_zero() {
    // max-age=0 means immediately stale (covers lines 54-56)
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/immediate-stale".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=0".parse().unwrap());
    headers.insert(ETAG, "\"v1\"".parse().unwrap());

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("stale immediately"),
        &HeaderMap::new(),
    );

    // Give it a tiny bit of time to become "stale"
    std::thread::sleep(std::time::Duration::from_millis(1));

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { cached, .. } => {
            assert_eq!(cached.body, Bytes::from("stale immediately"));
        }
        CacheLookup::Fresh(_) => panic!("max-age=0 should be stale immediately"),
        CacheLookup::Miss => panic!("should find the entry (has etag)"),
    }
}

#[test]
fn test_staleness_with_future_expires_is_fresh() {
    // When expires is in the future, the entry is fresh (line 42 returns true)
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/future-expires".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(EXPIRES, "Thu, 01 Jan 2099 00:00:00 GMT".parse().unwrap());

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("future data"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(entry) => {
            assert_eq!(entry.body, Bytes::from("future data"));
        }
        _ => panic!("future expires should be fresh"),
    }
}

#[test]
fn test_staleness_via_expires_with_swr_serves_fresh() {
    // expires in the past + stale-while-revalidate: staleness() goes
    // through the expires path (lines 59-64) and serves via swr
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/exp-swr-staleness".parse().unwrap();
    let mut headers = HeaderMap::new();
    // Only expires (no max-age) so staleness() uses the expires path
    headers.insert(EXPIRES, "Thu, 01 Jan 2020 00:00:00 GMT".parse().unwrap());
    headers.insert(
        CACHE_CONTROL,
        "stale-while-revalidate=999999999".parse().unwrap(),
    );

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("swr via expires"),
        &HeaderMap::new(),
    );

    // staleness() returns Some(since_epoch - expires_since) via the expires path
    // and since staleness < swr, it should serve as Fresh
    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Fresh(entry) => {
            assert_eq!(entry.body, Bytes::from("swr via expires"));
        }
        _ => panic!("swr with past expires should still serve as fresh"),
    }
}

#[test]
fn test_cacheable_status_codes() {
    let cacheable = [200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501];
    for code in cacheable {
        assert!(
            is_cacheable_status(StatusCode::from_u16(code).unwrap()),
            "status {code} should be cacheable"
        );
    }
    let not_cacheable = [201, 202, 302, 303, 307, 400, 401, 403, 500, 502, 503];
    for code in not_cacheable {
        assert!(
            !is_cacheable_status(StatusCode::from_u16(code).unwrap()),
            "status {code} should not be cacheable"
        );
    }
}

#[test]
fn test_cache_last_modified_validator() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/lm".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=0".parse().unwrap());
    headers.insert(
        LAST_MODIFIED,
        "Sun, 06 Nov 1994 08:49:37 GMT".parse().unwrap(),
    );

    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("modified"),
        &HeaderMap::new(),
    );

    match cache.lookup(&Method::GET, &uri, &HeaderMap::new()) {
        CacheLookup::Stale { validators, .. } => {
            assert_eq!(
                validators.last_modified.as_deref(),
                Some("Sun, 06 Nov 1994 08:49:37 GMT")
            );
            assert!(validators.etag.is_none());
        }
        _ => panic!("expected stale with last_modified validator"),
    }
}

#[test]
fn test_parse_cache_control_non_ascii_returns_defaults() {
    // When Cache-Control header value is non-ASCII, to_str() fails and
    // parse_cache_control returns default directives (line 509)
    let mut headers = HeaderMap::new();
    // Insert raw bytes that are not valid UTF-8
    headers.insert(
        CACHE_CONTROL,
        http::HeaderValue::from_bytes(b"max-age=3600, \xff\xfe").unwrap(),
    );
    let directives = parse_cache_control(&headers);
    // All fields should be at their defaults since parsing bailed
    assert!(directives.max_age.is_none());
    assert!(!directives.no_store);
    assert!(!directives.no_cache);
    assert!(!directives.private);
    assert!(!directives.must_revalidate);
    assert!(!directives.immutable);
    assert!(directives.stale_while_revalidate.is_none());
    assert!(directives.stale_if_error.is_none());
}

#[test]
fn test_vary_matches_with_vary_but_no_stored_headers_returns_true() {
    // When entry has `vary` set but `request_vary_headers` is None,
    // vary_matches should return true (line 629)
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("data"),
        stored_at: Instant::now(),
        max_age: Some(Duration::from_secs(3600)),
        expires_at: None,
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: Some(vec!["accept-encoding".to_string()]),
        request_vary_headers: None, // <-- this is the key: vary is Some but stored headers is None
    };
    let request_headers = HeaderMap::new();
    assert!(vary_matches(&entry, &request_headers));
}

#[test]
fn test_staleness_returns_none_when_max_age_not_exceeded() {
    // When age < max_age, staleness() returns None (covers line 57)
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("fresh"),
        stored_at: Instant::now(), // just created, age ~0
        max_age: Some(Duration::from_secs(3600)),
        expires_at: None,
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: None,
        request_vary_headers: None,
    };
    // staleness should be None since entry is fresh
    assert!(entry.staleness().is_none());
}

#[test]
fn test_staleness_returns_none_when_expires_in_future() {
    // When expires is in the future, staleness() returns None (covers lines 66-68)
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("fresh-expires"),
        stored_at: Instant::now(),
        max_age: None, // no max-age, so staleness checks expires
        expires_at: Some(SystemTime::now() + Duration::from_secs(3600)),
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: None,
        request_vary_headers: None,
    };
    // staleness should be None since expires is in the future
    assert!(entry.staleness().is_none());
}

#[test]
fn test_staleness_returns_none_when_no_max_age_no_expires() {
    // When there is neither max_age nor expires_at, staleness() returns None
    // (covers the final None at line 68)
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("no-info"),
        stored_at: Instant::now(),
        max_age: None,
        expires_at: None,
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: None,
        request_vary_headers: None,
    };
    assert!(entry.staleness().is_none());
}

#[test]
fn test_staleness_returns_some_when_max_age_exceeded() {
    // When age > max_age, staleness() returns Some(age - max_age)
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("stale"),
        stored_at: Instant::now() - Duration::from_secs(120), // 120s old
        max_age: Some(Duration::from_secs(60)),               // max-age is 60s
        expires_at: None,
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: None,
        request_vary_headers: None,
    };
    let staleness = entry.staleness();
    assert!(staleness.is_some());
    // Should be ~60s of staleness
    let staleness = staleness.unwrap();
    assert!(staleness >= Duration::from_secs(59));
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_poisoned_lock_get_returns_none() {
    // Poison the mutex by panicking inside a lock scope
    let store = std::sync::Arc::new(InMemoryCacheStore::new(256));
    let store_clone = store.clone();
    let _ = std::thread::spawn(move || {
        let _lock = store_clone.inner.lock().unwrap();
        panic!("intentional panic to poison mutex");
    })
    .join();

    // Now the mutex is poisoned
    let uri: Uri = "http://example.com/poisoned".parse().unwrap();
    // get should return empty on poisoned lock
    assert!(store.get(&Method::GET, &uri).is_empty());
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_poisoned_lock_put_is_noop() {
    let store = std::sync::Arc::new(InMemoryCacheStore::new(256));
    let store_clone = store.clone();
    let _ = std::thread::spawn(move || {
        let _lock = store_clone.inner.lock().unwrap();
        panic!("intentional panic to poison mutex");
    })
    .join();

    let uri: Uri = "http://example.com/poisoned-put".parse().unwrap();
    let entry = CacheEntry {
        status: StatusCode::OK,
        headers: HeaderMap::new(),
        body: Bytes::from("data"),
        stored_at: Instant::now(),
        max_age: Some(Duration::from_secs(60)),
        expires_at: None,
        etag: None,
        last_modified: None,
        must_revalidate: false,
        immutable: false,
        stale_while_revalidate: None,
        stale_if_error: None,
        vary: None,
        request_vary_headers: None,
    };
    // put should silently return on poisoned lock
    store.put(&Method::GET, &uri, entry);
    // len should return 0 on poisoned lock
    assert_eq!(store.len(), 0);
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_poisoned_lock_remove_is_noop() {
    let store = std::sync::Arc::new(InMemoryCacheStore::new(256));
    let store_clone = store.clone();
    let _ = std::thread::spawn(move || {
        let _lock = store_clone.inner.lock().unwrap();
        panic!("intentional panic to poison mutex");
    })
    .join();

    let uri: Uri = "http://example.com/poisoned-rm".parse().unwrap();
    // remove should silently return on poisoned lock
    store.remove(&Method::GET, &uri);
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_poisoned_lock_clear_is_noop() {
    let store = std::sync::Arc::new(InMemoryCacheStore::new(256));
    let store_clone = store.clone();
    let _ = std::thread::spawn(move || {
        let _lock = store_clone.inner.lock().unwrap();
        panic!("intentional panic to poison mutex");
    })
    .join();

    // clear should silently return on poisoned lock
    store.clear();
    // is_empty via len should return 0 (default on poisoned lock)
    assert!(store.is_empty());
}

#[test]
fn test_cache_no_header_returns_default_directives() {
    // When there is no Cache-Control header at all, parse_cache_control
    // returns default directives (covers line 506-507)
    let headers = HeaderMap::new();
    let directives = parse_cache_control(&headers);
    assert!(directives.max_age.is_none());
    assert!(!directives.no_store);
    assert!(!directives.no_cache);
    assert!(!directives.private);
    assert!(!directives.must_revalidate);
    assert!(!directives.immutable);
}

#[test]
fn test_s_maxage_takes_precedence_over_max_age() {
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "s-maxage=3600, max-age=60".parse().unwrap());
    let directives = parse_cache_control(&headers);
    assert_eq!(directives.max_age, Some(Duration::from_secs(3600)));
}

#[test]
fn test_s_maxage_precedence_reverse_order() {
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "max-age=60, s-maxage=3600".parse().unwrap());
    let directives = parse_cache_control(&headers);
    assert_eq!(directives.max_age, Some(Duration::from_secs(3600)));
}

#[test]
fn test_no_cache_without_validators_not_stored() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/nc-no-val".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "no-cache, max-age=3600".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    assert!(
        cache.is_empty(),
        "no-cache without validators should not be stored"
    );
}

#[test]
fn test_no_cache_with_etag_is_stored() {
    let cache = HttpCache::new();
    let uri: Uri = "http://example.com/nc-etag".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(CACHE_CONTROL, "no-cache".parse().unwrap());
    headers.insert(ETAG, "\"v1\"".parse().unwrap());
    cache.store(
        &Method::GET,
        &uri,
        StatusCode::OK,
        &headers,
        &Bytes::from("x"),
        &HeaderMap::new(),
    );
    assert_eq!(
        cache.len(),
        1,
        "no-cache with etag validator should be stored"
    );
}