feedparser_rs/http/
error.rs1use crate::error::UrlParseError;
4use crate::util::ssrf::{SsrfRejection, UrlRejection};
5use std::error::Error;
6use std::fmt;
7use std::io;
8use std::sync::Arc;
9use thiserror::Error;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct HttpStatus(u16);
23
24impl HttpStatus {
25 #[must_use]
27 pub const fn new(code: u16) -> Option<Self> {
28 match code {
29 400..=999 => Some(Self(code)),
30 _ => None,
31 }
32 }
33
34 #[must_use]
36 pub const fn as_u16(self) -> u16 {
37 self.0
38 }
39}
40
41impl fmt::Display for HttpStatus {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 write!(f, "{}", self.0)
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum HeaderField {
51 UserAgent,
53 IfNoneMatch,
55 IfModifiedSince,
57}
58
59impl fmt::Display for HeaderField {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.write_str(match self {
62 Self::UserAgent => "User-Agent",
63 Self::IfNoneMatch => "If-None-Match",
64 Self::IfModifiedSince => "If-Modified-Since",
65 })
66 }
67}
68
69pub fn error_chain(error: &(dyn Error + 'static)) -> String {
83 use std::fmt::Write as _;
84
85 let mut message = error.to_string();
86 let mut source = error.source();
87 while let Some(err) = source {
88 let _ = write!(message, ": {err}");
89 source = err.source();
90 }
91 message
92}
93
94fn io_error_is_timeout(error: &io::Error) -> bool {
99 error.kind() == io::ErrorKind::TimedOut
100 || error
101 .get_ref()
102 .and_then(|inner| inner.downcast_ref::<reqwest::Error>())
103 .is_some_and(reqwest::Error::is_timeout)
104}
105
106#[derive(Debug, Clone)]
108pub struct TransportError {
109 source: Arc<dyn Error + Send + Sync>,
110}
111
112impl TransportError {
113 pub(crate) fn new(source: impl Error + Send + Sync + 'static) -> Self {
114 Self {
115 source: Arc::new(source),
116 }
117 }
118
119 #[must_use]
136 pub fn is_timeout(&self) -> bool {
137 let root: &(dyn Error + 'static) = &*self.source;
138 std::iter::successors(Some(root), |err| (*err).source()).any(|err| {
139 err.downcast_ref::<reqwest::Error>()
140 .is_some_and(reqwest::Error::is_timeout)
141 || err
142 .downcast_ref::<io::Error>()
143 .is_some_and(io_error_is_timeout)
144 })
145 }
146}
147
148impl fmt::Display for TransportError {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 self.source.fmt(f)
151 }
152}
153
154impl Error for TransportError {
157 fn source(&self) -> Option<&(dyn Error + 'static)> {
158 self.source.source()
159 }
160}
161
162#[derive(Debug, Clone, Error)]
175#[non_exhaustive]
176pub enum FetchError {
177 #[error("HTTP {status} for URL: {url}")]
179 Status {
180 status: HttpStatus,
182 url: String,
184 },
185 #[error("{reason}")]
187 BlockedAddress {
188 reason: SsrfRejection,
190 },
191 #[error("Too many redirects")]
193 TooManyRedirects,
194 #[error("Response body exceeds the limit of {limit} bytes")]
196 BodyTooLarge {
197 limit: usize,
199 },
200 #[error("Invalid {name} header value")]
202 InvalidHeader {
203 name: HeaderField,
205 },
206 #[error("Invalid URL: {0}")]
208 InvalidUrl(UrlParseError),
209 #[error("HTTP request failed")]
211 Transport(#[source] TransportError),
212}
213
214impl From<UrlRejection> for FetchError {
215 fn from(rejection: UrlRejection) -> Self {
216 match rejection {
217 UrlRejection::Invalid(e) => Self::InvalidUrl(UrlParseError::new(e)),
218 UrlRejection::Blocked(reason) => Self::BlockedAddress { reason },
219 }
220 }
221}
222
223impl FetchError {
224 pub(crate) fn from_request_error(error: reqwest::Error) -> Self {
230 let root: &(dyn Error + 'static) = &error;
231 let typed = std::iter::successors(Some(root), |err| (*err).source())
232 .find_map(|err| err.downcast_ref::<Self>().cloned());
233 typed.unwrap_or_else(|| Self::Transport(TransportError::new(error)))
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 #[test]
242 fn http_status_accepts_only_400_to_999() {
243 assert!(HttpStatus::new(399).is_none());
244 assert_eq!(HttpStatus::new(400).map(HttpStatus::as_u16), Some(400));
245 assert_eq!(HttpStatus::new(999).map(HttpStatus::as_u16), Some(999));
246 assert!(HttpStatus::new(1000).is_none());
247 }
248
249 #[test]
250 fn transport_timeout_is_detected_through_the_source_chain() {
251 let timed_out = TransportError::new(io::Error::new(io::ErrorKind::TimedOut, "slow"));
252 assert!(timed_out.is_timeout());
253 let refused = TransportError::new(io::Error::new(io::ErrorKind::ConnectionRefused, "no"));
254 assert!(!refused.is_timeout());
255 }
256
257 #[expect(
258 clippy::significant_drop_tightening,
259 reason = "the mockito server must outlive the request under test"
260 )]
261 #[test]
262 fn typed_error_in_the_chain_is_recovered_without_wrapping() {
263 let client = reqwest::blocking::Client::builder()
264 .redirect(reqwest::redirect::Policy::custom(|attempt| {
265 attempt.error(FetchError::TooManyRedirects)
266 }))
267 .build()
268 .expect("client");
269 let mut server = mockito::Server::new();
270 let _mock = server
271 .mock("GET", "/r")
272 .with_status(302)
273 .with_header("location", "/r2")
274 .create();
275 let err = client
276 .get(format!("{}/r", server.url()))
277 .send()
278 .expect_err("redirect is rejected");
279 assert!(matches!(
280 FetchError::from_request_error(err),
281 FetchError::TooManyRedirects
282 ));
283 }
284
285 #[expect(
286 clippy::significant_drop_tightening,
287 reason = "the mockito server must outlive the request under test"
288 )]
289 #[test]
290 fn body_read_timeout_is_detected() {
291 use std::io::Read as _;
292 use std::time::Duration;
293
294 let mut server = mockito::Server::new();
295 let _mock = server
296 .mock("GET", "/slow-body")
297 .with_chunked_body(|w| {
298 w.write_all(b"<rss>")?;
299 w.flush()?;
300 std::thread::sleep(Duration::from_millis(600));
301 w.write_all(b"</rss>")
302 })
303 .create();
304 let client = reqwest::blocking::Client::builder()
305 .timeout(Duration::from_millis(200))
306 .build()
307 .expect("client");
308 let response = client
309 .get(format!("{}/slow-body", server.url()))
310 .send()
311 .expect("headers arrive before the timeout");
312 let mut bytes = Vec::new();
313 let err = response
314 .take(1 << 20)
315 .read_to_end(&mut bytes)
316 .expect_err("the body read times out");
317
318 assert!(TransportError::new(err).is_timeout());
319 }
320
321 #[test]
322 fn untyped_request_error_is_a_transport_failure() {
323 let client = reqwest::blocking::Client::new();
324 let err = client
325 .get("http://127.0.0.1:1/")
326 .send()
327 .expect_err("nothing listens on port 1");
328 assert!(matches!(
329 FetchError::from_request_error(err),
330 FetchError::Transport(_)
331 ));
332 }
333}