Skip to main content

capsule_sdk/net/
h3.rs

1//! The opportunistic HTTP/3 policy (networking doc, HTTP Transport).
2//!
3//! HTTP/3 is an optimization the client may take, never a property the protocol depends on. This
4//! module is the whole of the decision the SDK makes about it, as plain values over an injected
5//! [`MonotonicClock`] so every rule is a deterministic unit test:
6//!
7//! - **Discovery.** The client learns of an HTTP/3 endpoint only from an `Alt-Svc` response header
8//!   ([`H3Policy::observe_alt_svc`], parsed by [`parse_alt_svc`]) or an HTTPS DNS record
9//!   ([`H3Policy::observe_https_record`]). Each advertisement expires; a bounded table holds them.
10//! - **Race at dial.** [`H3Policy::choose`] answers [`TransportChoice::Race`] for an origin with a
11//!   live advertisement on a network whose UDP is not known to be unusable. The race is between
12//!   connection attempts, never between requests: a request rides exactly one dialed connection.
13//! - **Per-network "UDP unusable" record.** A QUIC dial that fails while TCP succeeds, a race in
14//!   which both dials fail, or a QUIC path that stops making progress, records UDP as unusable on that [`PathGeneration`] for
15//!   [`UDP_UNUSABLE_TTL`] ([`H3Policy::record_udp_unusable`]). A new path starts with no record.
16//! - **Fallback at a request boundary.** The choice is taken once, when a request starts. A
17//!   request already riding QUIC is never moved mid-flight: it fails, the retry engine re-sends it,
18//!   and the re-send's [`H3Policy::choose`] answers TCP. Resume reads server truth, so the switch
19//!   costs at most the bytes in flight.
20//! - **No connection migration.** Nothing here keys on a QUIC connection; a new path generation
21//!   drops pooled connections ([`super::path::GenerationPool`]) exactly as it does for TCP.
22//! - **No early data.** [`early_data_allowed`] refuses every method: the contract permits `GET` and
23//!   `HEAD` in TLS 1.3 early data, and this build takes none of it.
24//! - **Windows cover the bandwidth-delay product** within a fixed memory budget ([`size_window`]).
25//!
26//! Only a build with the off-by-default `http3` cargo feature races: it compiles the transport
27//! adapter that consumes this policy (`transport`, over quinn, h3 and h3-quinn), and
28//! [`H3Policy::for_build`] is capable there and incapable everywhere else. The SDK's `reqwest`
29//! clients stay pinned to HTTP/1.1 ([`super::http_builder`]) in every build; under `http3` their
30//! requests are routed through the transport (`route`), whose TCP leg is that same client
31//! (`tcp_leg`).
32
33use std::collections::HashMap;
34use std::sync::{Mutex, PoisonError};
35use std::time::Duration;
36
37use tracing::instrument;
38
39use super::MonotonicClock;
40use super::path::PathGeneration;
41
42#[cfg(feature = "http3")]
43pub mod route;
44#[cfg(feature = "http3")]
45pub mod tcp_leg;
46#[cfg(feature = "http3")]
47pub mod transport;
48
49/// The ALPN protocol id an advertisement must carry. Draft ids (`h3-29` and earlier) are ignored.
50pub const H3_ALPN: &str = "h3";
51
52/// How long an `Alt-Svc` entry holds when it names no `ma` (RFC 7838 §3.1: 24 hours).
53pub const ALT_SVC_DEFAULT_MAX_AGE: Duration = Duration::from_hours(24);
54
55/// The longest any advertisement is believed, whatever it claims, so a stale endpoint cannot be
56/// pinned for days.
57pub const ALT_SVC_MAX_AGE_CAP: Duration = Duration::from_hours(24);
58
59/// The most origins whose advertisement is held at once; the soonest to expire is evicted first.
60pub const MAX_ADVERTISED_ORIGINS: usize = 64;
61
62/// How long a network keeps its "UDP unusable" record before QUIC is tried on it again.
63pub const UDP_UNUSABLE_TTL: Duration = Duration::from_mins(10);
64
65/// The most networks whose "UDP unusable" record is held at once; the oldest path is evicted first.
66pub const MAX_UDP_RECORDS: usize = 8;
67
68// ─── Alt-Svc ─────────────────────────────────────────────────────────────────
69
70/// Where an advertised HTTP/3 endpoint listens. `host` is `None` when the advertisement names
71/// only a port (`":443"`), meaning the origin's own host.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct H3Endpoint {
74    /// The alternative host, or `None` for the origin's host.
75    pub host: Option<String>,
76    /// The UDP port.
77    pub port: u16,
78}
79
80/// One `h3` alternative from an `Alt-Svc` header.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct AltService {
83    /// Where it listens.
84    pub endpoint: H3Endpoint,
85    /// How long it holds, already clamped to [`ALT_SVC_MAX_AGE_CAP`].
86    pub max_age: Duration,
87}
88
89/// A parsed `Alt-Svc` header value.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum AltSvc {
92    /// `clear`: every alternative for the origin is withdrawn.
93    Clear,
94    /// The `h3` alternatives in the order the server preferred them. Empty when the header named
95    /// none this client can use.
96    Services(Vec<AltService>),
97}
98
99/// Parse an `Alt-Svc` header value (RFC 7838 §3), keeping only `h3` alternatives.
100///
101/// Lenient as the RFC asks: an entry that does not parse, or names another protocol, is skipped
102/// rather than failing the header; unknown parameters, and an `ma` that is not a number, are
103/// ignored.
104#[must_use]
105pub fn parse_alt_svc(value: &str) -> AltSvc {
106    let value = value.trim();
107    if value.eq_ignore_ascii_case("clear") {
108        return AltSvc::Clear;
109    }
110    let services = split_outside_quotes(value, ',')
111        .into_iter()
112        .filter_map(parse_alt_value)
113        .collect();
114    AltSvc::Services(services)
115}
116
117/// One `protocol-id="alt-authority"; param=value; ...` entry, or `None` if it is not a usable
118/// `h3` alternative.
119fn parse_alt_value(entry: &str) -> Option<AltService> {
120    let mut parts = split_outside_quotes(entry, ';').into_iter();
121    let (protocol, authority) = parts.next()?.split_once('=')?;
122    if protocol.trim() != H3_ALPN {
123        return None;
124    }
125    let authority = unquote(authority.trim())?;
126    let (host, port) = authority.rsplit_once(':')?;
127    let port: u16 = port.parse().ok().filter(|p| *p != 0)?;
128    let host = (!host.is_empty()).then(|| host.to_owned());
129
130    let mut max_age = ALT_SVC_DEFAULT_MAX_AGE;
131    for param in parts {
132        let Some((name, raw)) = param.split_once('=') else {
133            continue;
134        };
135        if name.trim().eq_ignore_ascii_case("ma") {
136            let raw = raw.trim();
137            let raw = unquote(raw).unwrap_or(raw);
138            if let Ok(secs) = raw.parse() {
139                max_age = Duration::from_secs(secs);
140            }
141        }
142    }
143    Some(AltService {
144        endpoint: H3Endpoint { host, port },
145        max_age: max_age.min(ALT_SVC_MAX_AGE_CAP),
146    })
147}
148
149/// Split on `sep` wherever it is not inside a quoted string, trimming each piece and dropping
150/// empty ones.
151fn split_outside_quotes(value: &str, sep: char) -> Vec<&str> {
152    let mut pieces = Vec::new();
153    let mut start = 0;
154    let mut quoted = false;
155    let mut escaped = false;
156    for (index, ch) in value.char_indices() {
157        match ch {
158            _ if escaped => escaped = false,
159            '\\' if quoted => escaped = true,
160            '"' => quoted = !quoted,
161            c if c == sep && !quoted => {
162                pieces.push(&value[start..index]);
163                start = index + c.len_utf8();
164            }
165            _ => {}
166        }
167    }
168    pieces.push(&value[start..]);
169    pieces
170        .into_iter()
171        .map(str::trim)
172        .filter(|p| !p.is_empty())
173        .collect()
174}
175
176/// The inside of a `"..."` quoted string with no escapes, or `None` if it is not one.
177fn unquote(value: &str) -> Option<&str> {
178    let inner = value.strip_prefix('"')?.strip_suffix('"')?;
179    (!inner.contains(['"', '\\'])).then_some(inner)
180}
181
182// ─── HTTPS DNS record ────────────────────────────────────────────────────────
183
184/// The fields of an HTTPS (SVCB) DNS record the policy reads, as a resolver reports them.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct HttpsRecord {
187    /// The record's `alpn` values.
188    pub alpn: Vec<String>,
189    /// The record's `port`, or `None` for the origin's port.
190    pub port: Option<u16>,
191    /// The record's target name, or `None` for the origin's host (target `.`).
192    pub target: Option<String>,
193    /// The record's TTL.
194    pub ttl: Duration,
195}
196
197// ─── The policy ──────────────────────────────────────────────────────────────
198
199/// Why a request rides TCP.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub enum TcpReason {
202    /// This build has no HTTP/3 transport.
203    NotBuilt,
204    /// The origin advertised no live HTTP/3 endpoint.
205    NotAdvertised,
206    /// UDP is recorded unusable on the current network.
207    UdpUnusable,
208}
209
210/// How the next request to an origin is dialed. Taken once, when the request starts.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum TransportChoice {
213    /// Dial TCP only.
214    Tcp(TcpReason),
215    /// Race a QUIC dial to `endpoint` against a TCP dial; the request rides whichever connects
216    /// first.
217    Race {
218        /// The advertised HTTP/3 endpoint.
219        endpoint: H3Endpoint,
220    },
221}
222
223/// Why UDP was recorded unusable on a network.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum UdpFailure {
226    /// The QUIC dial failed while the TCP dial it raced connected.
227    DialFailed,
228    /// A QUIC path stopped making progress mid-request.
229    Stalled,
230    /// The QUIC dial and the TCP dial it raced both failed. Recorded so a network where neither
231    /// connects (a proxy-only network among them) does not wait out the QUIC dial on every
232    /// request; TCP alone decides the next one.
233    BothDialsFailed,
234}
235
236#[derive(Debug, Default)]
237struct State {
238    /// Origin → (endpoint, expiry in clock millis).
239    advertised: HashMap<String, (H3Endpoint, u64)>,
240    /// Network → expiry in clock millis.
241    udp_unusable: HashMap<PathGeneration, u64>,
242}
243
244/// The opportunistic HTTP/3 decision: what has been advertised, which networks have unusable UDP,
245/// and what the next request should dial.
246#[derive(Debug)]
247pub struct H3Policy<C> {
248    clock: C,
249    capable: bool,
250    state: Mutex<State>,
251}
252
253impl<C: MonotonicClock> H3Policy<C> {
254    /// A policy over `clock`. `capable` says whether the build has an HTTP/3 transport; an
255    /// incapable policy still records what it observes and always answers TCP.
256    pub fn new(clock: C, capable: bool) -> Self {
257        Self {
258            clock,
259            capable,
260            state: Mutex::new(State::default()),
261        }
262    }
263
264    /// The policy for this build: capable only where the `http3` feature compiled the transport
265    /// that dials QUIC, so [`H3Policy::choose`] never answers a race that nothing could dial.
266    pub fn for_build(clock: C) -> Self {
267        Self::new(clock, cfg!(feature = "http3"))
268    }
269
270    fn state(&self) -> std::sync::MutexGuard<'_, State> {
271        self.state.lock().unwrap_or_else(PoisonError::into_inner)
272    }
273
274    /// Record an `Alt-Svc` header `origin` answered with. `clear`, or a header naming no usable
275    /// `h3` alternative, withdraws the origin's advertisement; otherwise the first `h3`
276    /// alternative replaces it.
277    #[instrument(level = "debug", skip(self))]
278    pub fn observe_alt_svc(&self, origin: &str, header: &str) {
279        let first = match parse_alt_svc(header) {
280            AltSvc::Clear => None,
281            AltSvc::Services(services) => services.into_iter().next(),
282        };
283        match first {
284            Some(service) => self.advertise(origin, service.endpoint, service.max_age),
285            None => {
286                if self.state().advertised.remove(origin).is_some() {
287                    tracing::debug!(origin, "h3: advertisement withdrawn");
288                }
289            }
290        }
291    }
292
293    /// Record an HTTPS DNS record for `origin` whose port is `origin_port`. A record without `h3`
294    /// in its `alpn` changes nothing: DNS is one of two discovery sources, so its silence does
295    /// not withdraw what `Alt-Svc` advertised.
296    #[instrument(level = "debug", skip(self))]
297    pub fn observe_https_record(&self, origin: &str, origin_port: u16, record: &HttpsRecord) {
298        if !record.alpn.iter().any(|alpn| alpn == H3_ALPN) {
299            return;
300        }
301        let endpoint = H3Endpoint {
302            host: record.target.clone(),
303            port: record.port.unwrap_or(origin_port),
304        };
305        self.advertise(origin, endpoint, record.ttl.min(ALT_SVC_MAX_AGE_CAP));
306    }
307
308    fn advertise(&self, origin: &str, endpoint: H3Endpoint, max_age: Duration) {
309        let now = self.clock.now_millis();
310        let expires = now.saturating_add(max_age.as_millis() as u64);
311        let mut state = self.state();
312        state.advertised.retain(|_, (_, until)| *until > now);
313        if !state.advertised.contains_key(origin)
314            && state.advertised.len() >= MAX_ADVERTISED_ORIGINS
315        {
316            let soonest = state
317                .advertised
318                .iter()
319                .min_by_key(|(_, (_, until))| *until)
320                .map(|(key, _)| key.clone());
321            if let Some(key) = soonest {
322                state.advertised.remove(&key);
323            }
324        }
325        tracing::debug!(
326            origin,
327            ?endpoint,
328            max_age_s = max_age.as_secs(),
329            "h3: advertised"
330        );
331        state
332            .advertised
333            .insert(origin.to_owned(), (endpoint, expires));
334    }
335
336    /// Record UDP as unusable on `network` for [`UDP_UNUSABLE_TTL`]. Requests already started
337    /// keep their transport; the next [`Self::choose`] on this network answers TCP.
338    #[instrument(level = "info", skip(self))]
339    pub fn record_udp_unusable(&self, network: PathGeneration, failure: UdpFailure) {
340        let until = self
341            .clock
342            .now_millis()
343            .saturating_add(UDP_UNUSABLE_TTL.as_millis() as u64);
344        let mut state = self.state();
345        state.udp_unusable.insert(network, until);
346        while state.udp_unusable.len() > MAX_UDP_RECORDS {
347            let Some(oldest) = state.udp_unusable.keys().min().copied() else {
348                break;
349            };
350            state.udp_unusable.remove(&oldest);
351        }
352        tracing::info!(
353            network = network.0,
354            ?failure,
355            "h3: UDP recorded unusable; TCP until expiry"
356        );
357    }
358
359    /// How a request to `origin` starting now on `network` is dialed.
360    #[instrument(level = "trace", skip(self), ret)]
361    pub fn choose(&self, origin: &str, network: PathGeneration) -> TransportChoice {
362        if !self.capable {
363            return TransportChoice::Tcp(TcpReason::NotBuilt);
364        }
365        let now = self.clock.now_millis();
366        let mut state = self.state();
367        if let Some(until) = state.udp_unusable.get(&network).copied() {
368            if until > now {
369                return TransportChoice::Tcp(TcpReason::UdpUnusable);
370            }
371            state.udp_unusable.remove(&network);
372            tracing::debug!(network = network.0, "h3: UDP-unusable record expired");
373        }
374        match state.advertised.get(origin) {
375            Some((endpoint, until)) if *until > now => TransportChoice::Race {
376                endpoint: endpoint.clone(),
377            },
378            Some(_) => {
379                state.advertised.remove(origin);
380                TransportChoice::Tcp(TcpReason::NotAdvertised)
381            }
382            None => TransportChoice::Tcp(TcpReason::NotAdvertised),
383        }
384    }
385}
386
387// ─── Early data ──────────────────────────────────────────────────────────────
388
389/// Whether a request with `method` may ride TLS 1.3 early data. Never, in this build: the
390/// contract forbids it for every non-safe method and only permits it for `GET` and `HEAD`, which
391/// this client does not take.
392#[must_use]
393pub fn early_data_allowed(_method: &http::Method) -> bool {
394    false
395}
396
397// ─── Bandwidth-delay product ─────────────────────────────────────────────────
398
399/// The fixed memory a transport may spend on flow-control and socket windows.
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401pub struct WindowBudget {
402    /// The smallest window worth opening, so a slow first estimate cannot starve a connection.
403    pub floor: u64,
404    /// The most bytes all connections' windows may hold together.
405    pub total: u64,
406}
407
408/// 64 KiB floor, 32 MiB across every connection.
409pub const DEFAULT_WINDOW_BUDGET: WindowBudget = WindowBudget {
410    floor: 64 * 1024,
411    total: 32 * 1024 * 1024,
412};
413
414/// The window for one of `connections` connections carrying `bandwidth` bytes per second over a
415/// round trip of `rtt`: the bandwidth-delay product, cut to the connection's equal share of the
416/// budget, and raised to the floor only where that share allows it. The windows of all
417/// `connections` never sum past [`WindowBudget::total`].
418#[must_use]
419pub fn size_window(bandwidth: u64, rtt: Duration, connections: u32, budget: WindowBudget) -> u64 {
420    let share = budget.total / u64::from(connections.max(1));
421    let bdp =
422        (u128::from(bandwidth) * rtt.as_micros() / 1_000_000).min(u128::from(u64::MAX)) as u64;
423    bdp.max(budget.floor).min(share)
424}
425
426#[cfg(test)]
427mod tests;