Skip to main content

docsrs_cli/retry/
classify.rs

1//! Failure classification: HTTP status, transport layer, and `Retry-After`.
2
3use std::time::{Duration, SystemTime};
4
5use reqwest::StatusCode;
6use reqwest::header::HeaderMap;
7
8use super::{HARD_MAX_DELAY_MS, MILLIS_PER_SECOND};
9
10/// Clock-skew tolerance for past HTTP-date `Retry-After` values.
11const RETRY_AFTER_SKEW_SECS: u64 = 1;
12
13/// Classification of an HTTP status for the retry gate.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum RetryClass {
16    /// Do not retry (4xx client errors, success, unknown permanent).
17    Permanent,
18    /// Retry with exponential full-jitter backoff (5xx / 408).
19    Transient,
20    /// Retry respecting optional `Retry-After` (429, and 503 with header).
21    RateLimited {
22        /// Parsed `Retry-After` delta-seconds or HTTP-date delta when present.
23        retry_after: Option<Duration>,
24    },
25}
26
27/// Detailed retry category exposed on errors (Rules checklist `retry_kind`).
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum RetryKind {
30    /// Never auto-retry (validation, 4xx, parse, budget, cancel).
31    Permanent,
32    /// Transport / connect failure (may retry).
33    TransientNetwork,
34    /// Remote 5xx / temporary unavailability (may retry).
35    TransientServer,
36    /// HTTP 429 with optional `Retry-After` (may retry).
37    RateLimited,
38    /// Wall or request timeout (may retry).
39    Timeout,
40}
41
42/// Transport / protocol layer of a failure (Rules checklist `ErrorLayer`).
43///
44/// Reqwest/hyper does not always separate DNS from TCP or TLS handshake from
45/// connect; `TcpConnect` covers DNS+TCP+TLS establishment when only
46/// `is_connect()` is available.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum ErrorLayer {
49    /// Name resolution (when distinguishable; else folded into [`Self::TcpConnect`]).
50    Dns,
51    /// TCP connect / peer unreachable (includes DNS when not separated).
52    TcpConnect,
53    /// TLS handshake failure (when distinguishable).
54    Tls,
55    /// HTTP/1.1 or HTTP/2 protocol error after connect.
56    HttpProtocol,
57    /// HTTP status from a completed response.
58    HttpStatus,
59    /// Application / parse / budget after a successful body read.
60    Application,
61    /// Unclassified.
62    Unknown,
63}
64
65impl ErrorLayer {
66    /// Stable snake_case label for logs and doctor detail.
67    pub fn as_str(self) -> &'static str {
68        match self {
69            Self::Dns => "dns",
70            Self::TcpConnect => "tcp_connect",
71            Self::Tls => "tls",
72            Self::HttpProtocol => "http_protocol",
73            Self::HttpStatus => "http_status",
74            Self::Application => "application",
75            Self::Unknown => "unknown",
76        }
77    }
78}
79
80impl RetryKind {
81    /// Stable snake_case label.
82    pub fn as_str(self) -> &'static str {
83        match self {
84            Self::Permanent => "permanent",
85            Self::TransientNetwork => "transient_network",
86            Self::TransientServer => "transient_server",
87            Self::RateLimited => "rate_limited",
88            Self::Timeout => "timeout",
89        }
90    }
91
92    /// Whether this kind is eligible for in-process or agent retry.
93    pub fn is_retryable(self) -> bool {
94        !matches!(self, Self::Permanent)
95    }
96}
97
98/// Classify HTTP status for in-process retry (GET-only product).
99pub fn classify_http_status(status: StatusCode, retry_after: Option<Duration>) -> RetryClass {
100    match status.as_u16() {
101        429 => RetryClass::RateLimited { retry_after },
102        // 408 Request Timeout — transient by design (client may retry).
103        408 | 500 | 502 | 504 => RetryClass::Transient,
104        // 503: prefer Retry-After when present (same as many CDNs).
105        503 => {
106            if retry_after.is_some() {
107                RetryClass::RateLimited { retry_after }
108            } else {
109                RetryClass::Transient
110            }
111        }
112        // Success and permanent client / other statuses: never retry.
113        _ => RetryClass::Permanent,
114    }
115}
116
117/// True when any error in the source chain is a [`rustls::Error`].
118///
119/// Does not string-match messages (Rules Rust — classification). When hyper
120/// folds TLS into a plain connect I/O error without a rustls source, the
121/// caller still reports [`ErrorLayer::TcpConnect`] (documented fold).
122pub(crate) fn source_chain_has_rustls(err: &(dyn std::error::Error + 'static)) -> bool {
123    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
124    while let Some(e) = cur {
125        if e.downcast_ref::<rustls::Error>().is_some() {
126            return true;
127        }
128        cur = e.source();
129    }
130    false
131}
132
133/// Classify a reqwest transport error without string-matching messages.
134///
135/// Returns `(app ErrorKind, layer, in_process_retryable)`.
136///
137/// When a [`rustls::Error`] appears in the source chain, the layer is
138/// [`ErrorLayer::Tls`] even if reqwest also flags timeout/connect/request
139/// (prefer precise TLS labeling for agent diagnostics).
140pub fn classify_reqwest_error(err: &reqwest::Error) -> (crate::error::ErrorKind, ErrorLayer, bool) {
141    use crate::error::ErrorKind;
142
143    let tls = source_chain_has_rustls(err as &(dyn std::error::Error + 'static));
144
145    if err.is_timeout() {
146        // Connect or total timeout — both are transient for GET.
147        let layer = if tls {
148            ErrorLayer::Tls
149        } else {
150            ErrorLayer::TcpConnect
151        };
152        return (ErrorKind::Timeout, layer, true);
153    }
154    if tls {
155        // Handshake / cert validation failures when discriminable via rustls.
156        return (ErrorKind::Network, ErrorLayer::Tls, true);
157    }
158    if err.is_connect() {
159        // Hyper folds DNS + TCP (+ often TLS without rustls source) into connect.
160        return (ErrorKind::Network, ErrorLayer::TcpConnect, true);
161    }
162    if err.is_request() {
163        // Protocol / request construction / HTTP/2 stream issues after dial.
164        return (ErrorKind::Network, ErrorLayer::HttpProtocol, true);
165    }
166    if err.is_body() || err.is_decode() {
167        // Incomplete body after headers — rare; treat as network, non-retry in
168        // send path (body path is separate). Keep retryable=false here.
169        return (ErrorKind::Network, ErrorLayer::HttpProtocol, false);
170    }
171    (ErrorKind::Network, ErrorLayer::Unknown, false)
172}
173
174/// Parse `Retry-After` as **delta-seconds** or **HTTP-date** (RFC 7231).
175///
176/// - Pure non-negative integer → seconds (capped at [`HARD_MAX_DELAY_MS`]).
177/// - IMF-fixdate via `httpdate` → duration until that instant.
178/// - Past date within `RETRY_AFTER_SKEW_SECS` → `Duration::ZERO`.
179/// - Older past date or unparseable → `None` (caller falls back to formula).
180pub fn parse_retry_after(headers: &HeaderMap) -> Option<Duration> {
181    let raw = headers
182        .get(reqwest::header::RETRY_AFTER)
183        .and_then(|v| v.to_str().ok())?
184        .trim();
185    if raw.is_empty() {
186        return None;
187    }
188    // Delta-seconds (preferred when the value is purely numeric).
189    if raw.bytes().all(|b| b.is_ascii_digit()) {
190        let secs: u64 = raw.parse().ok()?;
191        return Some(Duration::from_secs(
192            secs.min(HARD_MAX_DELAY_MS / MILLIS_PER_SECOND),
193        ));
194    }
195    // HTTP-date form.
196    let when = httpdate::parse_http_date(raw).ok()?;
197    let now = SystemTime::now();
198    match when.duration_since(now) {
199        Ok(d) => Some(d.min(Duration::from_millis(HARD_MAX_DELAY_MS))),
200        Err(e) => {
201            // Clock skew: slightly past → treat as immediate; deep past → formula.
202            if e.duration() <= Duration::from_secs(RETRY_AFTER_SKEW_SECS) {
203                Some(Duration::ZERO)
204            } else {
205                None
206            }
207        }
208    }
209}