scion_http3/error.rs
1// Copyright 2026 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The error taxonomy of the HTTP/3 client.
16//!
17//! All request-path operations ([`Client::request`](crate::Client::request)
18//! and friends, and body collection on [`Response`](crate::Response)) share
19//! one failure domain and therefore one error type, [`Error`]: whatever the
20//! operation, the caller's decisions are the same, i.e., retry, fix the request,
21//! or give up, and [`Error::is_retryable`] answers the first one directly.
22//! Constructing a [`Request`](crate::Request) is the exception. It fails with
23//! the more specific [`BuildRequestError`] before any I/O happens.
24
25use std::{borrow::Cow, error::Error as StdError, fmt, time::Duration};
26
27use scion_quic::{
28 h3::client::{
29 CollectError, CollectToStringError, EstablishError, RequestError as H3RequestError,
30 },
31 reexport::squiche,
32};
33use scion_stack::{resolver::ResolveError, stack::ScionSocketBindError};
34
35/// The phase of a request during which a timeout fired.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum TimeoutPhase {
39 /// Establishing a connection to the origin (bounded by
40 /// [`Config::with_connect_timeout`](crate::Config::with_connect_timeout)).
41 Connect,
42 /// Waiting for the response head (bounded by
43 /// [`Config::with_request_timeout`](crate::Config::with_request_timeout)
44 /// or the per-request override).
45 Request,
46 /// Collecting the response body (bounded by the remainder of the request
47 /// timeout).
48 ///
49 /// That remainder shrinks while the caller holds the
50 /// [`Response`](crate::Response), so this can also mean "the response was
51 /// held too long before being collected" rather than "the body was slow".
52 Body,
53}
54
55impl fmt::Display for TimeoutPhase {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match self {
58 TimeoutPhase::Connect => write!(f, "connect"),
59 TimeoutPhase::Request => write!(f, "request"),
60 TimeoutPhase::Body => write!(f, "response body collection"),
61 }
62 }
63}
64
65/// Any failure on the request path.
66///
67/// The variants follow the phases of a request: building connectivity,
68/// resolving the origin, connecting to it, and exchanging the request and
69/// response. [`is_retryable`](Self::is_retryable) classifies each error once,
70/// so callers branch on that instead of re-deriving the answer from the
71/// variant.
72#[derive(Debug, thiserror::Error)]
73#[non_exhaustive]
74pub enum Error {
75 /// Building SCION connectivity (the stack or the resolver) failed.
76 #[error("failed to build SCION connectivity")]
77 StackBuild {
78 /// Whether retrying may succeed (all underlying failures were
79 /// transient).
80 retryable: bool,
81 /// The underlying cause.
82 #[source]
83 source: Box<dyn StdError + Send + Sync>,
84 },
85 /// SCION name resolution for the origin's host failed: the DNS lookup
86 /// itself failed, or the host has no valid TSAR TXT records.
87 #[error("SCION name resolution failed for {host}")]
88 Resolution {
89 /// The host that failed to resolve.
90 host: String,
91 /// Whether retrying may succeed (the lookup failed, as opposed to the
92 /// host having no valid records).
93 retryable: bool,
94 /// The underlying resolver error.
95 #[source]
96 source: ResolveError,
97 },
98 /// No connection to the origin could be established: every candidate
99 /// address failed with a socket, QUIC, or handshake error.
100 #[error("could not connect to {host}:{port}")]
101 Connect {
102 /// The origin's host.
103 host: String,
104 /// The origin's port.
105 port: u16,
106 /// The underlying cause(s).
107 #[source]
108 source: Box<dyn StdError + Send + Sync>,
109 },
110 /// The TLS layer rejected the origin: every candidate negotiated an ALPN
111 /// other than HTTP/3.
112 ///
113 /// A certificate that fails to validate does *not* land here: the transport
114 /// reports it as a failed handshake, indistinguishable from an unreachable
115 /// peer, so it surfaces as [`Connect`](Self::Connect).
116 #[error("TLS failure connecting to {host}")]
117 Tls {
118 /// The origin's host (the certificate-validation identity).
119 host: String,
120 /// The underlying cause.
121 #[source]
122 source: Box<dyn StdError + Send + Sync>,
123 },
124 /// The peer reset the request stream.
125 #[error("stream reset by peer (code {code})")]
126 StreamReset {
127 /// The HTTP/3 application error code carried by the reset.
128 code: u64,
129 },
130 /// An HTTP/3 protocol violation occurred on an established connection.
131 #[error("HTTP/3 protocol error")]
132 Protocol {
133 /// The underlying cause.
134 #[source]
135 source: Box<dyn StdError + Send + Sync>,
136 },
137 /// The peer's concurrent-stream limit is exhausted; the request was never
138 /// sent.
139 #[error("peer's concurrent stream limit reached")]
140 ConnectionLimit,
141 /// The response body exceeded the size limit passed to
142 /// [`Response::bytes`](crate::Response::bytes) or
143 /// [`Response::text`](crate::Response::text).
144 #[error("response body exceeded {limit} bytes")]
145 BodyTooLarge {
146 /// The limit that was exceeded.
147 limit: usize,
148 },
149 /// A deadline expired.
150 #[error("{phase} timed out after {timeout:?}")]
151 Timeout {
152 /// The phase of the request that timed out.
153 phase: TimeoutPhase,
154 /// The deadline that expired.
155 timeout: Duration,
156 },
157 /// The response body is not valid UTF-8 (only from
158 /// [`Response::text`](crate::Response::text)).
159 #[error("response body is not valid UTF-8")]
160 InvalidBody {
161 /// The underlying UTF-8 error.
162 #[source]
163 source: std::string::FromUtf8Error,
164 },
165 /// The request is invalid (malformed URL, unsupported scheme, missing
166 /// host, or an invalid header).
167 #[error("invalid request: {reason}")]
168 InvalidRequest {
169 /// What is wrong with the request.
170 reason: Cow<'static, str>,
171 },
172 /// The client has been closed with [`Client::close`](crate::Client::close).
173 #[error("client is closed")]
174 Closed,
175}
176
177impl Error {
178 /// Whether retrying the request may succeed.
179 ///
180 /// Transient conditions (connectivity, timeouts, stream resets, stream
181 /// limits) are retryable. Deterministic ones (TLS rejection, protocol
182 /// violations, invalid requests, oversized bodies, a closed client) are
183 /// not. For [`StackBuild`](Self::StackBuild) and
184 /// [`Resolution`](Self::Resolution) the answer is decided when the error
185 /// is constructed, from the transience of the underlying failures.
186 ///
187 /// A retryable error never implies the request did not reach the server:
188 /// only the caller knows whether its request is idempotent.
189 #[must_use]
190 pub fn is_retryable(&self) -> bool {
191 match self {
192 Error::StackBuild { retryable, .. } | Error::Resolution { retryable, .. } => *retryable,
193 Error::Connect { .. }
194 | Error::StreamReset { .. }
195 | Error::ConnectionLimit
196 | Error::Timeout { .. } => true,
197 Error::Tls { .. }
198 | Error::Protocol { .. }
199 | Error::BodyTooLarge { .. }
200 | Error::InvalidBody { .. }
201 | Error::InvalidRequest { .. }
202 | Error::Closed => false,
203 }
204 }
205
206 /// Maps a transport-level request error to the taxonomy, attributing
207 /// connection-level failures to `host:port`.
208 pub(crate) fn from_h3_request_error(host: &str, port: u16, err: H3RequestError) -> Error {
209 match err {
210 H3RequestError::Establish(e) => {
211 Error::from_attempt_errors(host, port, vec![AttemptError::Establish(e)])
212 }
213 H3RequestError::Reset(code) => Error::StreamReset { code },
214 // Both shapes mean the same thing to the caller: the peer's
215 // concurrent-stream limit has no room for this request.
216 H3RequestError::StreamBlocked
217 | H3RequestError::H3(squiche::h3::Error::TransportError(squiche::Error::StreamLimit)) => {
218 Error::ConnectionLimit
219 }
220 H3RequestError::H3(_) => {
221 Error::Protocol {
222 source: Box::new(err),
223 }
224 }
225 H3RequestError::ConnectionClosed | H3RequestError::LocallyClosed => {
226 Error::Connect {
227 host: host.to_string(),
228 port,
229 source: Box::new(err),
230 }
231 }
232 }
233 }
234
235 /// Maps the failures of an attempt sequence to the taxonomy: TLS-level
236 /// rejections become [`Error::Tls`], everything else [`Error::Connect`].
237 ///
238 /// The classification is deliberately unanimous rather than "any": one
239 /// candidate rejecting the ALPN says nothing about the others, which may
240 /// have failed for transient reasons and may well work on a retry. Only
241 /// when *every* candidate rejected us is the failure deterministic, and
242 /// therefore not worth retrying.
243 pub(crate) fn from_attempt_errors(host: &str, port: u16, errors: Vec<AttemptError>) -> Error {
244 // XXX(shitz): A certificate that fails to validate should be an
245 // `Error::Tls` too, but cannot be recognized here: scion-quic's
246 // handshake loop discards the cause and reports
247 // `EstablishError::Handshake`, which is what an unreachable peer also
248 // produces. Such failures are therefore reported as retryable
249 // `Error::Connect`. Fixing this needs a distinct handshake-failure
250 // variant in scion-quic.
251 let all_tls = !errors.is_empty()
252 && errors
253 .iter()
254 .all(|e| matches!(e, AttemptError::Establish(EstablishError::AlpnMismatch)));
255 let source = Box::new(AllAttemptsFailed { errors });
256 if all_tls {
257 Error::Tls {
258 host: host.to_string(),
259 source,
260 }
261 } else {
262 Error::Connect {
263 host: host.to_string(),
264 port,
265 source,
266 }
267 }
268 }
269
270 /// Maps a resolver error to [`Error::Resolution`], taking retryability from
271 /// the resolver's own classification: a failed lookup may succeed later, a
272 /// host without valid TSAR records will not.
273 pub(crate) fn from_resolve_error(host: &str, err: ResolveError) -> Error {
274 let retryable = err.is_transient();
275 Error::Resolution {
276 host: host.to_string(),
277 retryable,
278 source: err,
279 }
280 }
281
282 /// Maps a body-collection error to the taxonomy.
283 pub(crate) fn from_collect_error(err: CollectError, limit: Option<usize>) -> Error {
284 match err {
285 CollectError::TooLarge => {
286 Error::BodyTooLarge {
287 limit: limit.unwrap_or(usize::MAX),
288 }
289 }
290 _ => {
291 Error::Protocol {
292 source: Box::new(err),
293 }
294 }
295 }
296 }
297
298 /// Maps a body-to-string collection error to the taxonomy.
299 pub(crate) fn from_collect_to_string_error(
300 err: CollectToStringError,
301 limit: Option<usize>,
302 ) -> Error {
303 match err {
304 CollectToStringError::TooLarge => {
305 Error::BodyTooLarge {
306 limit: limit.unwrap_or(usize::MAX),
307 }
308 }
309 CollectToStringError::Utf8(source) => Error::InvalidBody { source },
310 CollectToStringError::H3(_) => {
311 Error::Protocol {
312 source: Box::new(err),
313 }
314 }
315 }
316 }
317}
318
319impl From<BuildRequestError> for Error {
320 /// An invalid request is an [`Error::InvalidRequest`], so the convenience
321 /// entry points ([`Client::get`](crate::Client::get),
322 /// [`Client::post`](crate::Client::post)) report builder failures through
323 /// the same taxonomy as the rest of the request path.
324 fn from(error: BuildRequestError) -> Self {
325 Error::InvalidRequest {
326 reason: error.to_string().into(),
327 }
328 }
329}
330
331/// One failed connection attempt: binding the socket, or establishing the
332/// connection over it.
333#[derive(Debug, thiserror::Error)]
334pub(crate) enum AttemptError {
335 /// Binding a fresh socket for the attempt failed.
336 #[error("binding a socket failed")]
337 Bind(#[source] ScionSocketBindError),
338 /// Establishing the connection failed.
339 #[error("establishing the connection failed")]
340 Establish(#[source] EstablishError),
341}
342
343/// Aggregate of the failures of one attempt sequence, in completion order.
344/// The [`Error::Connect`] / [`Error::Tls`] source when every candidate
345/// failed.
346#[derive(Debug)]
347struct AllAttemptsFailed {
348 errors: Vec<AttemptError>,
349}
350
351impl fmt::Display for AllAttemptsFailed {
352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353 write!(
354 f,
355 "all {} connection attempt(s) failed: ",
356 self.errors.len()
357 )?;
358 for (i, err) in self.errors.iter().enumerate() {
359 if i > 0 {
360 write!(f, "; ")?;
361 }
362 write!(f, "{err}")?;
363 }
364 Ok(())
365 }
366}
367
368impl StdError for AllAttemptsFailed {
369 fn source(&self) -> Option<&(dyn StdError + 'static)> {
370 self.errors.first().map(|e| e as &(dyn StdError + 'static))
371 }
372}
373
374/// A [`Request`](crate::Request) could not be built.
375#[derive(Debug, thiserror::Error)]
376#[non_exhaustive]
377pub enum BuildRequestError {
378 /// No URL was provided to the builder.
379 #[error("no URL was provided")]
380 MissingUrl,
381 /// The URL could not be parsed.
382 #[error("invalid URL")]
383 InvalidUrl {
384 /// The underlying parse error.
385 #[source]
386 source: Box<dyn StdError + Send + Sync>,
387 },
388 /// The URL's scheme is not `https`. This is an HTTP/3-only client;
389 /// requests are never sent over cleartext or fall back to TCP.
390 #[error("unsupported URL scheme `{scheme}`, only `https` is supported")]
391 UnsupportedScheme {
392 /// The offending scheme.
393 scheme: String,
394 },
395 /// The URL has no host.
396 #[error("URL has no host")]
397 MissingHost,
398 /// The URL contains userinfo (`user:password@host`). HTTP/3 forbids
399 /// userinfo in `:authority` (RFC 9114 ยง4.3.1), and sending it would leak
400 /// the credentials on the wire; pass credentials in an `authorization`
401 /// header instead.
402 #[error("URL must not contain userinfo (credentials)")]
403 UserinfoNotAllowed,
404 /// A header name or value is invalid.
405 #[error("invalid header")]
406 InvalidHeader {
407 /// The underlying cause.
408 #[source]
409 source: Box<dyn StdError + Send + Sync>,
410 },
411 /// An empty target list was provided. Targets assert "resolution returned
412 /// exactly this", and an empty resolution result is an error, not a
413 /// wildcard.
414 #[error("target list must not be empty")]
415 EmptyTargets,
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421
422 #[test]
423 fn retryable_classification() {
424 let retryable = [
425 Error::StackBuild {
426 retryable: true,
427 source: "boom".into(),
428 },
429 Error::Connect {
430 host: "example.org".into(),
431 port: 443,
432 source: "boom".into(),
433 },
434 Error::StreamReset { code: 0x10c },
435 Error::ConnectionLimit,
436 Error::Timeout {
437 phase: TimeoutPhase::Request,
438 timeout: Duration::from_secs(1),
439 },
440 ];
441 for err in retryable {
442 assert!(err.is_retryable(), "{err}");
443 }
444
445 let not_retryable = [
446 Error::StackBuild {
447 retryable: false,
448 source: "boom".into(),
449 },
450 Error::Tls {
451 host: "example.org".into(),
452 source: "boom".into(),
453 },
454 Error::Protocol {
455 source: "boom".into(),
456 },
457 Error::BodyTooLarge { limit: 16 },
458 Error::InvalidRequest {
459 reason: "bad".into(),
460 },
461 Error::Closed,
462 ];
463 for err in not_retryable {
464 assert!(!err.is_retryable(), "{err}");
465 }
466 }
467
468 #[test]
469 fn resolution_retryability_follows_failure_kind() {
470 let lookup = Error::from_resolve_error(
471 "example.org",
472 ResolveError::DnsLookup("timed out".to_string()),
473 );
474 assert!(lookup.is_retryable());
475
476 let no_entries = Error::from_resolve_error(
477 "example.org",
478 ResolveError::NoValidEntries {
479 domain: "example.org".to_string(),
480 invalid_entries: vec![],
481 },
482 );
483 assert!(!no_entries.is_retryable());
484 }
485
486 #[test]
487 fn establish_errors_map_to_tls_only_when_uniform() {
488 let tls = Error::from_attempt_errors(
489 "example.org",
490 443,
491 vec![
492 AttemptError::Establish(EstablishError::AlpnMismatch),
493 AttemptError::Establish(EstablishError::AlpnMismatch),
494 ],
495 );
496 assert!(matches!(tls, Error::Tls { .. }));
497
498 let mixed = Error::from_attempt_errors(
499 "example.org",
500 443,
501 vec![
502 AttemptError::Establish(EstablishError::AlpnMismatch),
503 AttemptError::Establish(EstablishError::Handshake),
504 ],
505 );
506 assert!(matches!(mixed, Error::Connect { .. }));
507 }
508
509 #[test]
510 fn stream_level_request_errors_do_not_become_connect() {
511 let reset = Error::from_h3_request_error("example.org", 443, H3RequestError::Reset(7));
512 assert!(matches!(reset, Error::StreamReset { code: 7 }));
513
514 let blocked =
515 Error::from_h3_request_error("example.org", 443, H3RequestError::StreamBlocked);
516 assert!(matches!(blocked, Error::ConnectionLimit));
517 }
518}