htrio 0.2.0

A reqwest-compatible native HTTP/1, HTTP/2 and HTTP/3 client with Alt-Svc discovery
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
//! Bounded, origin-scoped HTTP/3 alternative service cache (RFC 7838).
//!
//! RFC 7838 discovery requires authenticated HTTPS responses. A preconfigured
//! TLS verifier must enforce origin authentication. Share a cache with
//! [`crate::ClientBuilder::alt_svc_cache`]. Call
//! [`AltSvcCache::network_changed`] when the application detects a network change.
//! Persistence is application-controlled through snapshots; the client never writes to disk.

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

use http::uri::Authority;
use http::{HeaderMap, StatusCode, Uri};

const DEFAULT_MAX_AGE: u64 = 86_400;
const MAX_HEADER_BYTES: usize = 16 * 1024;
const MAX_ALTERNATIVES: usize = 8;
#[cfg(test)]
const BROKEN_BACKOFF: Duration = Duration::from_secs(300);

/// A bounded HTTP/3 alternative service cache shared by cloned clients.
///
/// Entries are scoped to the HTTPS origin's host and effective port. Cache
/// controls affect future route selection; they do not close active connections.
/// Authenticated response headers and HTTP/2 ALTSVC frames share this cache.
/// Persistence uses explicit, application-owned snapshots.
#[derive(Clone, Debug)]
pub struct AltSvcCache {
    inner: Arc<Mutex<State>>,
    capacity: usize,
}

#[derive(Debug, Default)]
struct State {
    origins: HashMap<String, Entry>,
    sequence: u64,
    generation: u64,
}

#[derive(Debug)]
struct Entry {
    alternatives: Vec<Alternative>,
    sequence: u64,
}

#[derive(Clone, Debug)]
pub(crate) struct Alternative {
    pub(crate) authority: Authority,
    pub(crate) from_dns: bool,
    pub(crate) requires_ech: bool,
    expires: Instant,
    persist: bool,
    broken_until: Option<Instant>,
}

/// A single alternative suitable for application-controlled persistence.
///
/// Store records in trusted, origin-scoped application storage. Importing a
/// record never bypasses origin certificate verification. Failure backoff and
/// network state are deliberately not persisted.
#[derive(Clone, Debug)]
pub struct Record {
    /// HTTPS origin, including its effective port.
    pub origin: String,
    /// Alternative host and port.
    pub authority: String,
    /// Absolute expiration; import caps freshness at one year.
    pub expires_at: SystemTime,
    /// Whether the alternative survives network changes.
    pub persist: bool,
}

impl Alternative {
    pub(crate) fn service(authority: Authority, ttl: Duration, requires_ech: bool) -> Self {
        Self {
            authority,
            from_dns: true,
            requires_ech,
            expires: Instant::now() + ttl.min(Duration::from_secs(86_400)),
            persist: false,
            broken_until: None,
        }
    }
}

impl Default for AltSvcCache {
    fn default() -> Self {
        Self::with_capacity(256)
    }
}

impl AltSvcCache {
    /// Create a cache holding at most 256 origins and eight alternatives per origin.
    pub fn new() -> Self {
        Self::default()
    }

    /// Limit the number of cached origins. A zero capacity disables storage.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            inner: Arc::new(Mutex::new(State::default())),
            capacity,
        }
    }

    /// Remove every cached alternative, including persistent alternatives.
    pub fn clear(&self) {
        self.inner.lock().unwrap().origins.clear();
    }

    /// Discard expired alternatives and those without `persist=1`.
    ///
    /// Network change detection is left to the embedding application.
    /// Persistent alternatives keep their existing expiry. Client route failure state resets.
    pub fn network_changed(&self) {
        let now = Instant::now();
        let mut state = self.inner.lock().unwrap();
        state.generation = state.generation.wrapping_add(1);
        state.origins.retain(|_, entry| {
            entry
                .alternatives
                .retain(|alt| alt.persist && alt.expires > now);
            !entry.alternatives.is_empty()
        });
    }

    /// Return the number of origins with unexpired alternatives.
    pub fn len(&self) -> usize {
        let mut state = self.inner.lock().unwrap();
        prune(&mut state, Instant::now());
        state.origins.len()
    }

    /// Return whether the cache contains no unexpired alternatives.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Export unexpired alternatives without writing to disk.
    pub fn snapshot(&self) -> Vec<Record> {
        let now = Instant::now();
        let wall = SystemTime::now();
        let mut state = self.inner.lock().unwrap();
        prune(&mut state, now);
        state
            .origins
            .iter()
            .flat_map(|(origin, entry)| {
                entry.alternatives.iter().map(|alt| Record {
                    origin: origin.clone(),
                    authority: alt.authority.to_string(),
                    expires_at: wall + alt.expires.saturating_duration_since(now),
                    persist: alt.persist,
                })
            })
            .collect()
    }

    /// Restore trusted records, validating syntax, freshness, and cache bounds.
    ///
    /// Existing records for an imported origin are replaced as a complete set.
    pub fn restore(&self, records: impl IntoIterator<Item = Record>) {
        let mut grouped: HashMap<String, Vec<Alternative>> = HashMap::new();
        let now = Instant::now();
        for record in records
            .into_iter()
            .take(self.capacity.saturating_mul(MAX_ALTERNATIVES))
        {
            let Ok(origin) = record.origin.parse::<Uri>() else {
                continue;
            };
            let Some(key) = origin_key(&origin) else {
                continue;
            };
            let Ok(age) = record.expires_at.duration_since(SystemTime::now()) else {
                continue;
            };
            let age = age.min(Duration::from_secs(31_536_000));
            let item = format!(
                "h3=\"{}\";ma={};persist={}",
                record.authority,
                age.as_secs(),
                u8::from(record.persist)
            );
            let Some(alt) = parse_alternative(&origin, &item, Duration::ZERO, now) else {
                continue;
            };
            if !grouped.contains_key(&key) && grouped.len() >= self.capacity {
                continue;
            }
            let alternatives = grouped.entry(key).or_default();
            if alternatives.len() < MAX_ALTERNATIVES
                && !alternatives
                    .iter()
                    .any(|existing| existing.authority == alt.authority)
            {
                alternatives.push(alt);
            }
        }
        let mut state = self.inner.lock().unwrap();
        prune(&mut state, now);
        for (origin, alternatives) in grouped {
            if state.origins.len() >= self.capacity && !state.origins.contains_key(&origin) {
                if let Some(oldest) = state
                    .origins
                    .iter()
                    .min_by_key(|(_, entry)| entry.sequence)
                    .map(|(key, _)| key.clone())
                {
                    state.origins.remove(&oldest);
                }
            }
            state.sequence = state.sequence.wrapping_add(1);
            let sequence = state.sequence;
            state.origins.insert(
                origin,
                Entry {
                    alternatives,
                    sequence,
                },
            );
        }
    }

    pub(crate) fn generation(&self) -> u64 {
        self.inner.lock().unwrap().generation
    }

    pub(crate) fn candidates(&self, origin: &Uri) -> Vec<Alternative> {
        let Some(key) = origin_key(origin) else {
            return Vec::new();
        };
        let mut state = self.inner.lock().unwrap();
        let Some(entry) = state.origins.get_mut(&key) else {
            return Vec::new();
        };
        // Route selection only needs this origin. Writes and cache observers
        // reclaim expired entries across the full, bounded cache.
        let now = Instant::now();
        entry.alternatives.retain(|alt| alt.expires > now);
        if entry.alternatives.is_empty() {
            state.origins.remove(&key);
            return Vec::new();
        }
        entry.alternatives.clone()
    }

    #[cfg(test)]
    pub(crate) fn get(&self, origin: &Uri) -> Option<Alternative> {
        let key = origin_key(origin)?;
        let now = Instant::now();
        let mut state = self.inner.lock().unwrap();
        prune(&mut state, now);
        state
            .origins
            .get(&key)?
            .alternatives
            .iter()
            .find_map(|alt| {
                if alt.broken_until.is_some_and(|until| until > now) {
                    None
                } else {
                    Some(alt.clone())
                }
            })
    }

    #[cfg(test)]
    pub(crate) fn mark_broken(&self, origin: &Uri, alternative: &Alternative) {
        let Some(key) = origin_key(origin) else {
            return;
        };
        if let Some(entry) = self.inner.lock().unwrap().origins.get_mut(&key) {
            for alt in &mut entry.alternatives {
                if alt.authority == alternative.authority {
                    alt.broken_until = Some(Instant::now() + BROKEN_BACKOFF);
                }
            }
        }
    }

    pub(crate) fn remove(&self, origin: &Uri, alternative: &Alternative) {
        let Some(key) = origin_key(origin) else {
            return;
        };
        let mut state = self.inner.lock().unwrap();
        if let Some(entry) = state.origins.get_mut(&key) {
            entry
                .alternatives
                .retain(|alt| alt.authority != alternative.authority);
            if entry.alternatives.is_empty() {
                state.origins.remove(&key);
            }
        }
    }

    pub(crate) fn observe(
        &self,
        origin: &Uri,
        status: StatusCode,
        headers: &HeaderMap,
        response_delay: Duration,
    ) {
        if self.capacity == 0 || status == StatusCode::MISDIRECTED_REQUEST {
            return;
        }
        let Some(key) = origin_key(origin) else {
            return;
        };
        if !headers.contains_key("alt-svc") {
            return;
        }

        let now = Instant::now();
        let age = response_age(headers, response_delay);
        let mut alternatives = Vec::new();
        let mut bytes = 0_usize;
        let values = headers.get_all("alt-svc");
        let mut clear = false;
        for value in &values {
            bytes = bytes.saturating_add(value.as_bytes().len());
            if bytes > MAX_HEADER_BYTES {
                return;
            }
            let Ok(value) = value.to_str() else {
                return;
            };
            if value.trim() == "clear" {
                clear = true;
                continue;
            }
            let Some(items) = split_quoted(value, b',') else {
                return;
            };
            for item in items {
                if item.trim().is_empty() {
                    continue;
                }
                let Some(alt) = parse_alternative(origin, item, age, now) else {
                    continue;
                };
                if alternatives.len() < MAX_ALTERNATIVES
                    && !alternatives
                        .iter()
                        .any(|old: &Alternative| old.authority == alt.authority)
                {
                    alternatives.push(alt);
                }
            }
        }

        let mut state = self.inner.lock().unwrap();
        prune(&mut state, now);
        // A new field replaces the complete set, even if none of its protocols
        // are supported. Re-advertising a broken endpoint must not erase backoff.
        if let Some(old) = state.origins.remove(&key) {
            for alt in &mut alternatives {
                if let Some(previous) = old
                    .alternatives
                    .iter()
                    .find(|previous| previous.authority == alt.authority)
                {
                    alt.broken_until = previous.broken_until;
                }
            }
        }
        if clear || alternatives.is_empty() {
            return;
        }
        if state.origins.len() >= self.capacity {
            if let Some(oldest) = state
                .origins
                .iter()
                .min_by_key(|(_, entry)| entry.sequence)
                .map(|(key, _)| key.clone())
            {
                state.origins.remove(&oldest);
            }
        }
        state.sequence = state.sequence.wrapping_add(1);
        let sequence = state.sequence;
        state.origins.insert(
            key,
            Entry {
                alternatives,
                sequence,
            },
        );
    }
}

fn origin_key(uri: &Uri) -> Option<String> {
    if uri.scheme_str()? != "https" {
        return None;
    }
    Some(format!(
        "https://{}:{}",
        uri.host()?.to_ascii_lowercase(),
        uri.port_u16().unwrap_or(443)
    ))
}

fn prune(state: &mut State, now: Instant) {
    state.origins.retain(|_, entry| {
        entry.alternatives.retain(|alt| alt.expires > now);
        !entry.alternatives.is_empty()
    });
}

fn response_age(headers: &HeaderMap, response_delay: Duration) -> Duration {
    let age = headers
        .get(http::header::AGE)
        .and_then(|age| age.to_str().ok())
        .and_then(|age| age.parse::<u64>().ok())
        .unwrap_or(0);
    let apparent_age = headers
        .get(http::header::DATE)
        .and_then(|date| date.to_str().ok())
        .and_then(|date| httpdate::parse_http_date(date).ok())
        .and_then(|date| SystemTime::now().duration_since(date).ok())
        .unwrap_or_default();
    apparent_age.max(Duration::from_secs(age).saturating_add(response_delay))
}

fn parse_alternative(origin: &Uri, item: &str, age: Duration, now: Instant) -> Option<Alternative> {
    let fields = split_quoted(item, b';')?;
    let (protocol, authority) = fields.first()?.trim().split_once('=')?;
    let protocol = protocol.trim();
    if !protocol.bytes().all(is_token) {
        return None;
    }
    if percent_encoding::percent_decode_str(protocol).collect::<Vec<_>>() != b"h3" {
        return None;
    }
    let authority = quoted(authority.trim())?;
    let authority = if authority.starts_with(':') {
        format!("{}{}", origin.host()?, authority)
    } else {
        authority
    };
    if authority.contains('@') {
        return None;
    }
    let authority: Authority = authority.parse().ok()?;
    if authority.host().is_empty() || authority.port_u16()? == 0 {
        return None;
    }

    let mut max_age = None;
    let mut persist = None;
    for field in fields.iter().skip(1) {
        let (name, value) = field.trim().split_once('=')?;
        let name = name.trim();
        if name.is_empty() || !name.bytes().all(is_token) {
            return None;
        }
        let value = value.trim();
        let value = if value.starts_with('"') {
            quoted(value)?
        } else if !value.is_empty() && value.bytes().all(is_token) {
            value.to_owned()
        } else {
            return None;
        };
        if name.eq_ignore_ascii_case("ma") {
            if max_age.is_some() || !value.bytes().all(|b| b.is_ascii_digit()) {
                return None;
            }
            max_age = Some(value.parse::<u64>().ok()?);
        } else if name.eq_ignore_ascii_case("persist") {
            if persist.is_some() {
                return None;
            }
            persist = Some(value == "1");
        }
    }
    // Clients may discard alternatives early. Bound very large server lifetimes
    // to one year so hostile values cannot overflow a platform's monotonic clock.
    let lifetime = Duration::from_secs(max_age.unwrap_or(DEFAULT_MAX_AGE).min(31_536_000));
    let remaining = lifetime.checked_sub(age)?;
    if remaining.is_zero() {
        return None;
    }
    Some(Alternative {
        authority,
        from_dns: false,
        requires_ech: false,
        expires: now.checked_add(remaining)?,
        persist: persist.unwrap_or(false),
        broken_until: None,
    })
}

fn split_quoted(value: &str, delimiter: u8) -> Option<Vec<&str>> {
    let mut fields = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut escaped = false;
    for (index, byte) in value.bytes().enumerate() {
        if escaped {
            escaped = false;
        } else if in_quotes && byte == b'\\' {
            escaped = true;
        } else if byte == b'"' {
            in_quotes = !in_quotes;
        } else if !in_quotes && byte == delimiter {
            fields.push(&value[start..index]);
            start = index + 1;
        }
    }
    if in_quotes || escaped {
        return None;
    }
    fields.push(&value[start..]);
    Some(fields)
}

fn quoted(value: &str) -> Option<String> {
    let inner = value.strip_prefix('"')?.strip_suffix('"')?;
    let mut result = String::new();
    let mut escaped = false;
    for byte in inner.bytes() {
        if !(b' '..=b'~').contains(&byte) {
            return None;
        }
        if escaped {
            result.push(byte as char);
            escaped = false;
        } else if byte == b'\\' {
            escaped = true;
        } else if byte == b'"' {
            return None;
        } else {
            result.push(byte as char);
        }
    }
    (!escaped).then_some(result)
}

fn is_token(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)
}

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

    fn learn(cache: &AltSvcCache, origin: &str, value: &str) {
        let mut headers = HeaderMap::new();
        headers.insert("alt-svc", value.parse().unwrap());
        cache.observe(
            &origin.parse().unwrap(),
            StatusCode::OK,
            &headers,
            Duration::ZERO,
        );
    }

    fn expire(cache: &AltSvcCache, origin: &Uri, index: usize) {
        cache
            .inner
            .lock()
            .unwrap()
            .origins
            .get_mut(&origin_key(origin).unwrap())
            .unwrap()
            .alternatives[index]
            .expires = Instant::now();
    }

    #[test]
    fn candidate_lookup_expires_alternatives_and_preserves_backoff() {
        let cache = AltSvcCache::new();
        let origin: Uri = "https://example.test/".parse().unwrap();
        learn(
            &cache,
            &origin.to_string(),
            "h3=\":443\";ma=60, h3=\":8443\";ma=60;persist=1",
        );
        let alternatives = cache.candidates(&origin);
        cache.mark_broken(&origin, &alternatives[1]);
        expire(&cache, &origin, 0);

        let live = cache.candidates(&"https://EXAMPLE.test:443/path".parse().unwrap());
        assert_eq!(live.len(), 1);
        assert_eq!(live[0].authority, "example.test:8443");
        assert!(live[0].persist);
        assert!(live[0].broken_until.unwrap() > Instant::now());

        expire(&cache, &origin, 0);
        assert!(cache.candidates(&origin).is_empty());
        assert!(cache.is_empty());
    }

    #[test]
    fn insertion_reclaims_unrelated_expired_origins_before_eviction() {
        let cache = AltSvcCache::with_capacity(2);
        let fresh: Uri = "https://fresh.test/".parse().unwrap();
        let expired: Uri = "https://expired.test/".parse().unwrap();
        learn(&cache, &fresh.to_string(), "h3=\":443\"");
        learn(&cache, &expired.to_string(), "h3=\":443\"");
        expire(&cache, &expired, 0);
        assert_eq!(cache.candidates(&fresh).len(), 1);

        let added: Uri = "https://added.test/".parse().unwrap();
        learn(&cache, &added.to_string(), "h3=\":443\"");
        assert_eq!(cache.len(), 2);
        assert_eq!(cache.candidates(&fresh).len(), 1);
        assert_eq!(cache.candidates(&added).len(), 1);
        assert!(cache.candidates(&expired).is_empty());
    }

    #[test]
    fn observers_prune_expired_origins_after_lookup_misses() {
        for snapshot_first in [false, true] {
            let cache = AltSvcCache::with_capacity(2);
            learn(&cache, "https://fresh.test/", "h3=\":443\"");
            let expired: Uri = "https://expired.test/".parse().unwrap();
            learn(&cache, &expired.to_string(), "h3=\":443\"");
            expire(&cache, &expired, 0);
            assert!(cache
                .candidates(&"https://missing.test/".parse().unwrap())
                .is_empty());

            if snapshot_first {
                assert_eq!(cache.snapshot().len(), 1);
            }
            assert_eq!(cache.len(), 1);
            let records = cache.snapshot();
            assert_eq!(records.len(), 1);
            assert_eq!(records[0].origin, "https://fresh.test:443");
        }
    }

    #[test]
    fn origin_scope_and_default_port_normalization() {
        let cache = AltSvcCache::new();
        learn(&cache, "https://example.com/", "h3=\":8443\"");
        assert_eq!(
            cache
                .get(&"https://EXAMPLE.com:443/path".parse().unwrap())
                .unwrap()
                .authority,
            "example.com:8443"
        );
        for uri in [
            "http://example.com/",
            "https://other.com/",
            "https://example.com:444/",
        ] {
            assert!(cache.get(&uri.parse().unwrap()).is_none());
        }
    }

    #[test]
    fn parses_lists_escapes_parameters_and_ipv6() {
        let cache = AltSvcCache::new();
        learn(
            &cache,
            "https://[::1]/",
            "h2=\":443\", h%33=\":8443\"; ma=\"60\"; persist=1; ext=\"a,b;\\\"c\"",
        );
        let alt = cache.get(&"https://[::1]/".parse().unwrap()).unwrap();
        assert_eq!(alt.authority, "[::1]:8443");
        assert!(alt.persist);
    }

    #[test]
    fn expiration_age_replacement_and_clear() {
        let cache = AltSvcCache::new();
        let origin: Uri = "https://example.com/".parse().unwrap();
        learn(&cache, &origin.to_string(), "h3=\":443\"");
        let mut headers = HeaderMap::new();
        headers.insert("alt-svc", "h3=\":8443\"; ma=30".parse().unwrap());
        headers.insert("age", "30".parse().unwrap());
        cache.observe(&origin, StatusCode::OK, &headers, Duration::ZERO);
        assert!(cache.is_empty());
        learn(&cache, &origin.to_string(), "h3=\":443\"");
        learn(&cache, &origin.to_string(), "h2=\":443\"");
        assert!(cache.is_empty());
        learn(&cache, &origin.to_string(), "h3=\":443\"");
        learn(&cache, &origin.to_string(), "clear");
        assert!(cache.is_empty());
    }

    #[test]
    fn date_and_response_delay_reduce_freshness() {
        let cache = AltSvcCache::new();
        let origin = "https://example.com/".parse().unwrap();
        let mut headers = HeaderMap::new();
        headers.insert("alt-svc", "h3=\":443\"; ma=1".parse().unwrap());
        headers.insert("date", "Sun, 06 Nov 1994 08:49:37 GMT".parse().unwrap());
        cache.observe(&origin, StatusCode::OK, &headers, Duration::ZERO);
        assert!(cache.is_empty());
        headers.remove("date");
        cache.observe(&origin, StatusCode::OK, &headers, Duration::from_secs(2));
        assert!(cache.is_empty());
    }

    #[test]
    fn rejects_invalid_authorities_and_lifetimes() {
        let cache = AltSvcCache::new();
        for value in [
            "h3=\"evil.example\"",
            "h3=\"user@evil.example:443\"",
            "h3=\":0\"",
            "h3=\":65536\"",
            "h3=\":443\"; ma=-1",
            "h3=\":443\"; ma=0",
            "h3=\":443\"; ma=1; ma=2",
            "h3=\":443\"; ma=999999999999999999999999",
            "h3=\"evil.example:443/path\"",
            "h3=\":443",
            "h3=:443",
        ] {
            learn(&cache, "https://example.com/", value);
            assert!(cache.is_empty(), "accepted {value}");
        }
    }

    #[test]
    fn bounded_storage_network_changes_and_backoff() {
        let cache = AltSvcCache::with_capacity(2);
        learn(&cache, "https://one.test/", "h3=\":443\"");
        learn(&cache, "https://two.test/", "h3=\":443\"; persist=1");
        learn(&cache, "https://three.test/", "h3=\":443\"");
        assert_eq!(cache.len(), 2);
        assert!(cache.get(&"https://one.test/".parse().unwrap()).is_none());
        cache.network_changed();
        assert_eq!(cache.len(), 1);
        let origin: Uri = "https://two.test/".parse().unwrap();
        let alternative = cache.get(&origin).unwrap();
        cache.mark_broken(&origin, &alternative);
        learn(&cache, "https://two.test/", "h3=\":443\"");
        assert!(cache.get(&origin).is_none());
        cache.clear();
        assert!(cache.is_empty());
        let disabled = AltSvcCache::with_capacity(0);
        learn(&disabled, "https://example.com/", "h3=\":443\"");
        assert!(disabled.is_empty());
    }

    #[test]
    fn misdirected_responses_cannot_repopulate_cache() {
        let cache = AltSvcCache::new();
        let mut headers = HeaderMap::new();
        headers.insert("alt-svc", "h3=\":443\"".parse().unwrap());
        cache.observe(
            &"https://example.com/".parse().unwrap(),
            StatusCode::MISDIRECTED_REQUEST,
            &headers,
            Duration::ZERO,
        );
        assert!(cache.is_empty());
    }

    #[test]
    fn snapshots_preserve_freshness_and_validate_imported_records() {
        let source = AltSvcCache::new();
        learn(&source, "https://one.test/", "h3=\":8443\";ma=60;persist=1");
        let records = source.snapshot();
        let restored = AltSvcCache::new();
        restored.restore(records.clone());
        let snapshot = restored.snapshot();
        assert_eq!(snapshot.len(), 1);
        assert_eq!(snapshot[0].origin, records[0].origin);
        assert_eq!(snapshot[0].authority, records[0].authority);
        assert!(snapshot[0].persist);
        assert!(snapshot[0].expires_at <= records[0].expires_at);
        restored.network_changed();
        assert_eq!(restored.len(), 1);
        for (origin, authority, expires_at) in [
            (
                "http://one.test",
                "one.test:443",
                SystemTime::now() + Duration::from_secs(60),
            ),
            (
                "https://one.test",
                "user@one.test:443",
                SystemTime::now() + Duration::from_secs(60),
            ),
            ("https://one.test", "one.test:443", SystemTime::UNIX_EPOCH),
        ] {
            let cache = AltSvcCache::new();
            cache.restore([Record {
                origin: origin.into(),
                authority: authority.into(),
                expires_at,
                persist: false,
            }]);
            assert!(cache.is_empty());
        }
        let bounded = AltSvcCache::with_capacity(1);
        bounded.restore((0..100).map(|index| Record {
            origin: format!("https://origin{index}.test"),
            authority: "alternative.test:443".into(),
            expires_at: SystemTime::now() + Duration::from_secs(60),
            persist: false,
        }));
        assert_eq!(bounded.len(), 1);
    }
}