Skip to main content

eggfetch_core/
http_version.rs

1//! HTTP version negotiation policy.
2
3use crate::error::Error;
4
5/// Policy controlling which HTTP protocol versions the client may negotiate.
6///
7/// The default is [`HttpVersionPolicy::Auto`], which allows the client to
8/// negotiate HTTP/2 via ALPN when available and fall back to HTTP/1.1
9/// otherwise.
10///
11/// When the `http2` feature is not enabled, only [`HttpVersionPolicy::Http1Only`]
12/// is valid; attempting to use `Http2Only` or `Auto` without the `http2`
13/// feature will result in an HTTP/1.1-only client at runtime.
14///
15/// When the `http3` feature is enabled, [`HttpVersionPolicy::Http3Only`]
16/// routes requests over QUIC using the h3 protocol. HTTP/3 uses a separate
17/// transport (Quinn) and does not share connections with HTTP/1.1 or HTTP/2.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum HttpVersionPolicy {
20    /// Only HTTP/1.1 is permitted. The client will not advertise `h2` in
21    /// ALPN and will not accept an HTTP/2 response.
22    Http1Only,
23    /// Only HTTP/2 is permitted. The client advertises `h2` via ALPN. If
24    /// the server does not negotiate HTTP/2, the connection fails.
25    Http2Only,
26    /// Only HTTP/3 is permitted. The client uses QUIC via Quinn and the h3
27    /// protocol. Requires the `http3` feature.
28    Http3Only,
29    /// Allow negotiation. The client advertises both `h2` and `http/1.1`
30    /// via ALPN and accepts whichever protocol the server selects.
31    /// When `allow_http3` is `true` and the `http3` feature is enabled,
32    /// HTTP/3 is also included in auto-negotiation. When `allow_http3`
33    /// is `false`, HTTP/3 is excluded; use `Http3Only` to explicitly
34    /// opt in.
35    Auto {
36        /// Whether to allow HTTP/3 in auto-negotiation.
37        allow_http3: bool,
38    },
39}
40
41impl Default for HttpVersionPolicy {
42    fn default() -> Self {
43        Self::Auto { allow_http3: false }
44    }
45}
46
47/// Typed evidence about the HTTP/3 capability of the running build.
48///
49/// The value is resolved from the compiled feature set so that failure
50/// classification never has to inspect a rendered message.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub(crate) enum Http3Capability {
53    /// The `http3` feature is compiled in.
54    Compiled,
55    /// The `http3` feature is not compiled in.
56    NotCompiled,
57}
58
59impl Http3Capability {
60    /// The HTTP/3 capability of the running build.
61    pub(crate) const CURRENT: Self = if cfg!(feature = "http3") {
62        Self::Compiled
63    } else {
64        Self::NotCompiled
65    };
66
67    /// Returns `true` when this build can route HTTP/3 requests.
68    pub(crate) const fn is_available(self) -> bool {
69        matches!(self, Self::Compiled)
70    }
71}
72
73/// Classify a standard-route dispatch that has no usable Hyper client.
74///
75/// Two different operator problems share one failure point:
76///
77/// - the build has no HTTP/3 support while the caller asked for HTTP/3
78///   (a build capability gap), and
79/// - the request had no usable client for any other reason (a transport
80///   failure).
81///
82/// Reporting the second for the first misreports a build capability gap as a
83/// transport failure, so the two are separated here. The decision is derived
84/// from the typed policy value and the compiled capability, never from parsing
85/// a `Display` string.
86///
87/// Both outcomes stay inside the existing [`Error::Unsupported`] domain: no
88/// public error variant is added and the transport-failure taxonomy is
89/// unchanged. Only the message differs.
90pub(crate) fn missing_client_error(policy: HttpVersionPolicy) -> Error {
91    if matches!(policy, HttpVersionPolicy::Http3Only) && !Http3Capability::CURRENT.is_available() {
92        return Error::Unsupported(
93            "HTTP/3 is not supported by this build: the http3 feature was not compiled in".into(),
94        );
95    }
96    Error::Unsupported("HTTP client not available for this protocol".into())
97}
98
99/// Internal helper that resolves which protocol versions to enable on the
100/// connector based on the policy and compiled feature flags.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102pub(crate) struct HttpVersionPolicyEnabler(HttpVersionPolicy);
103
104impl HttpVersionPolicyEnabler {
105    /// Create an enabler from a policy. When the `http2` feature is not
106    /// enabled, `Http2Only` and `Auto` are silently downgraded to
107    /// `Http1Only`. When the `http3` feature is not enabled, `Http3Only`
108    /// is silently downgraded to `Http1Only`.
109    #[must_use]
110    pub(crate) fn from_policy(policy: HttpVersionPolicy) -> Self {
111        match policy {
112            #[cfg(not(feature = "transport-http2"))]
113            HttpVersionPolicy::Http2Only => Self(HttpVersionPolicy::Http1Only),
114            #[cfg(not(feature = "http3"))]
115            HttpVersionPolicy::Http3Only => Self(HttpVersionPolicy::Http1Only),
116            #[allow(
117                unused_variables,
118                reason = "the `Auto` arm ignores the caller's HTTP/3 flag when the http2 or http3 feature is compiled out, so the binding is unused in those builds"
119            )]
120            HttpVersionPolicy::Auto { allow_http3 } => {
121                #[cfg(not(feature = "transport-http2"))]
122                return Self(HttpVersionPolicy::Http1Only);
123                #[cfg(all(feature = "transport-http2", not(feature = "http3")))]
124                return Self(HttpVersionPolicy::Auto { allow_http3: false });
125                #[cfg(all(feature = "transport-http2", feature = "http3"))]
126                return Self(HttpVersionPolicy::Auto { allow_http3 });
127            }
128            _ => Self(policy),
129        }
130    }
131
132    /// Returns `true` if HTTP/1.1 should be enabled on the connector.
133    #[must_use]
134    #[allow(
135        dead_code,
136        reason = "the HTTP/1.1 switch is only read by the ALPN and connector builders, which are compiled out when neither tls-rustls nor transport-http2 is enabled"
137    )]
138    pub(crate) const fn enable_http1(self) -> bool {
139        matches!(
140            self.0,
141            HttpVersionPolicy::Http1Only | HttpVersionPolicy::Auto { .. }
142        )
143    }
144
145    /// Returns `true` if HTTP/2 should be enabled on the connector.
146    #[must_use]
147    #[allow(
148        dead_code,
149        reason = "the HTTP/2 switch is only read by the ALPN and connector builders, which are compiled out when neither tls-rustls nor transport-http2 is enabled"
150    )]
151    pub(crate) const fn enable_http2(self) -> bool {
152        matches!(
153            self.0,
154            HttpVersionPolicy::Http2Only | HttpVersionPolicy::Auto { .. }
155        )
156    }
157
158    /// Returns `true` if HTTP/3 should be used (QUIC transport).
159    #[must_use]
160    #[allow(
161        dead_code,
162        reason = "the HTTP/3 switch is only read by the HTTP/3 connector setup, which is compiled out when the http3 feature is disabled"
163    )]
164    pub(crate) fn use_http3(self) -> bool {
165        match self.0 {
166            HttpVersionPolicy::Http3Only => true,
167            HttpVersionPolicy::Auto { allow_http3 } => allow_http3,
168            _ => false,
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn default_is_auto() {
179        assert_eq!(
180            HttpVersionPolicy::default(),
181            HttpVersionPolicy::Auto { allow_http3: false }
182        );
183    }
184
185    #[test]
186    fn http1_only_enables_http1_only() {
187        let enabler = HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Http1Only);
188        assert!(enabler.enable_http1());
189        assert!(!enabler.enable_http2());
190        assert!(!enabler.use_http3());
191    }
192
193    #[test]
194    #[cfg(feature = "transport-http2")]
195    fn auto_enables_both() {
196        let enabler =
197            HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto { allow_http3: false });
198        assert!(enabler.enable_http1());
199        assert!(enabler.enable_http2());
200        assert!(!enabler.use_http3());
201    }
202
203    #[test]
204    #[cfg(not(feature = "transport-http2"))]
205    fn auto_downgrades_without_feature() {
206        let enabler =
207            HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto { allow_http3: false });
208        assert!(enabler.enable_http1());
209        assert!(!enabler.enable_http2());
210    }
211
212    #[test]
213    #[cfg(feature = "transport-http2")]
214    fn http2_only_enables_http2_only() {
215        let enabler = HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Http2Only);
216        assert!(!enabler.enable_http1());
217        assert!(enabler.enable_http2());
218    }
219
220    #[test]
221    #[cfg(not(feature = "transport-http2"))]
222    fn http2_only_downgrades_without_feature() {
223        let enabler = HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Http2Only);
224        assert!(enabler.enable_http1());
225        assert!(!enabler.enable_http2());
226    }
227
228    #[test]
229    #[cfg(feature = "http3")]
230    fn http3_only_enables_http3_only() {
231        let enabler = HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Http3Only);
232        assert!(!enabler.enable_http1());
233        assert!(!enabler.enable_http2());
234        assert!(enabler.use_http3());
235    }
236
237    #[test]
238    #[cfg(not(feature = "http3"))]
239    fn http3_only_downgrades_without_feature() {
240        let enabler = HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Http3Only);
241        assert!(enabler.enable_http1());
242        assert!(!enabler.enable_http2());
243        assert!(!enabler.use_http3());
244    }
245
246    #[test]
247    #[cfg(not(feature = "http3"))]
248    fn missing_client_error_names_the_http3_capability_gap() {
249        let error = missing_client_error(HttpVersionPolicy::Http3Only);
250        let message = error.to_string();
251        assert!(
252            message.contains("HTTP/3"),
253            "the failure must name HTTP/3: {message}"
254        );
255        assert!(
256            !message.contains("HTTP client not available"),
257            "the failure must not reuse the generic missing-client wording: {message}"
258        );
259    }
260
261    #[test]
262    #[cfg(feature = "http3")]
263    fn missing_client_error_keeps_the_generic_wording_when_http3_is_compiled() {
264        let error = missing_client_error(HttpVersionPolicy::Http3Only);
265        let message = error.to_string();
266        assert!(
267            message.contains("HTTP client not available"),
268            "a compiled-in HTTP/3 build has no capability gap to report: {message}"
269        );
270    }
271
272    #[test]
273    fn missing_client_error_keeps_the_generic_wording_for_other_policies() {
274        for policy in [
275            HttpVersionPolicy::Http1Only,
276            HttpVersionPolicy::Http2Only,
277            HttpVersionPolicy::Auto { allow_http3: false },
278            HttpVersionPolicy::Auto { allow_http3: true },
279        ] {
280            let message = missing_client_error(policy).to_string();
281            assert!(
282                message.contains("HTTP client not available"),
283                "unexpected classification for {policy:?}: {message}"
284            );
285        }
286    }
287
288    #[test]
289    fn classification_is_typed_and_does_not_render_the_policy() {
290        // The classification is driven by the policy variant and the compiled
291        // capability, never by a rendered policy string: the produced message
292        // must not embed the policy's own rendering.
293        let message = missing_client_error(HttpVersionPolicy::Http3Only).to_string();
294        assert!(
295            !message.contains("Http3Only"),
296            "the classification must not embed a rendered policy: {message}"
297        );
298        assert!(
299            !message.contains("Auto"),
300            "the classification must not embed a rendered policy: {message}"
301        );
302    }
303
304    #[test]
305    fn http3_capability_matches_the_compiled_feature_set() {
306        assert_eq!(
307            Http3Capability::CURRENT.is_available(),
308            cfg!(feature = "http3"),
309            "the typed capability must track the compiled feature set"
310        );
311    }
312}