Skip to main content

lychee_lib/types/
response.rs

1use std::{fmt::Display, time::Duration};
2
3use http::StatusCode;
4use serde::Serialize;
5
6use crate::{InputSource, Status, Uri, types::uri::raw::RawUriSpan};
7
8/// Response type returned by lychee after checking a URI
9//
10// Body is public to allow inserting into stats maps (error_map, success_map,
11// etc.) without `Clone`, because the inner `ErrorKind` in `response.status` is
12// not `Clone`. Use `body()` to access the body in the rest of the code.
13//
14// `pub(crate)` is insufficient, because the `stats` module is in the `bin`
15// crate crate.
16#[derive(Debug)]
17pub struct Response {
18    input_source: InputSource,
19    response_body: ResponseBody,
20}
21
22impl Response {
23    #[inline]
24    #[must_use]
25    /// Create new response
26    pub const fn new(
27        uri: Uri,
28        status: Status,
29        input_source: InputSource,
30        span: Option<RawUriSpan>,
31        duration: Option<Duration>,
32    ) -> Self {
33        Response {
34            input_source,
35            response_body: ResponseBody {
36                uri,
37                status,
38                span,
39                duration,
40            },
41        }
42    }
43
44    #[inline]
45    #[must_use]
46    /// Retrieve the underlying status of the response
47    pub const fn status(&self) -> &Status {
48        &self.response_body.status
49    }
50
51    #[inline]
52    #[must_use]
53    /// Retrieve the underlying source of the response
54    /// (e.g. the input file or the URL)
55    pub const fn source(&self) -> &InputSource {
56        &self.input_source
57    }
58
59    #[inline]
60    #[must_use]
61    /// Retrieve the body of the response
62    pub const fn body(&self) -> &ResponseBody {
63        &self.response_body
64    }
65
66    #[inline]
67    #[must_use]
68    /// Retrieve the body of the response by consuming `self`
69    pub fn into_body(self) -> ResponseBody {
70        self.response_body
71    }
72}
73
74impl Display for Response {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        <ResponseBody as Display>::fmt(&self.response_body, f)
77    }
78}
79
80impl Serialize for Response {
81    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
82    where
83        S: serde::Serializer,
84    {
85        <ResponseBody as Serialize>::serialize(&self.response_body, s)
86    }
87}
88
89/// Encapsulates the state of a [`Uri`] check result
90#[allow(clippy::module_name_repetitions)]
91#[derive(Debug, Serialize, Hash, PartialEq, Eq)]
92pub struct ResponseBody {
93    #[serde(flatten)]
94    /// The URI which was checked
95    pub uri: Uri,
96    /// The status of the check
97    pub status: Status,
98    /// The location of the URI
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub span: Option<RawUriSpan>,
101    /// The time it took to perform the request and produce this [`ResponseBody`]
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub duration: Option<Duration>,
104}
105
106// Extract as much information from the underlying error conditions as possible
107// without being too verbose. Some dependencies (rightfully) don't expose all
108// error fields to downstream crates, which is why we have to defer to pattern
109// matching in these cases.
110impl Display for ResponseBody {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        // Always write the URI
113        write!(f, "{}", self.uri)?;
114
115        if let Some(span) = self.span {
116            write!(f, " (at {span})")?;
117        }
118
119        // Early return for OK status to avoid verbose output
120        if matches!(self.status, Status::Ok(StatusCode::OK)) {
121            return Ok(());
122        }
123
124        // Format status and return early if empty
125        let status_output = self.status.to_string();
126        if status_output.is_empty() {
127            return Ok(());
128        }
129
130        // Write status with separator
131        write!(f, " | {status_output}")?;
132
133        // Add details if available
134        if let Some(details) = self.status.details() {
135            write!(f, ": {details}")
136        } else {
137            Ok(())
138        }
139    }
140}