Skip to main content

flareapp_core/
transport.rs

1//! The [`Transport`] trait that sends requests to Flare, and the request and
2//! response types it uses.
3
4use std::error::Error;
5use std::fmt;
6use std::time::{Duration, SystemTime};
7
8/// The kind of data in a request. Each kind goes to its own endpoint.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum Signal {
12    /// Error reports, sent to `/v1/errors`.
13    Errors,
14    /// OTLP log records, sent to `/v1/logs`.
15    Logs,
16    /// OTLP spans, sent to `/v1/traces`.
17    Traces,
18}
19
20impl Signal {
21    /// Returns the URL path for this kind of data, like `/v1/logs`.
22    pub fn path(self) -> &'static str {
23        match self {
24            Self::Errors => "/v1/errors",
25            Self::Logs => "/v1/logs",
26            Self::Traces => "/v1/traces",
27        }
28    }
29}
30
31/// An HTTP `POST` request to Flare, ready to send.
32#[derive(Debug, Clone)]
33#[non_exhaustive]
34pub struct Request {
35    /// What kind of data the body holds.
36    pub signal: Signal,
37    /// The full URL, like `https://ingress.flareapp.io/v1/logs`.
38    pub url: String,
39    /// Header names and values. They include the API key.
40    pub headers: Vec<(&'static str, String)>,
41    /// The body, in the format that the `content-type` header names: JSON for
42    /// error reports, and OTLP protobuf or JSON for logs and traces.
43    pub body: Vec<u8>,
44}
45
46/// The parts of an HTTP response that the Flare client needs: the status, the retry
47/// time and the body.
48#[derive(Debug, Clone, PartialEq, Eq)]
49#[non_exhaustive]
50#[must_use]
51pub struct Response {
52    /// The HTTP status code.
53    pub status: u16,
54    /// How long the server asks the Flare client to wait before it tries again.
55    /// Comes from the `Retry-After` header.
56    pub retry_after: Option<Duration>,
57    /// The response body. In debug mode, the Flare client reads the partial
58    /// success of an OTLP response from it, and prints the body of a failed request.
59    pub body: Vec<u8>,
60}
61
62impl Response {
63    /// Creates a response with a status code and no body.
64    pub fn new(status: u16) -> Self {
65        Self {
66            status,
67            retry_after: None,
68            body: Vec::new(),
69        }
70    }
71
72    /// Reads the wait time from the value of a `Retry-After` header.
73    ///
74    /// The value can be a number of seconds or an HTTP date. An invalid value is
75    /// ignored. A date in the past means no wait.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use std::time::Duration;
81    ///
82    /// use flareapp_core::Response;
83    ///
84    /// let seconds = Response::new(429).with_retry_after_header("120");
85    /// assert_eq!(seconds.retry_after, Some(Duration::from_secs(120)));
86    ///
87    /// let date = Response::new(503).with_retry_after_header("Wed, 21 Oct 2015 07:28:00 GMT");
88    /// assert_eq!(date.retry_after, Some(Duration::ZERO));
89    ///
90    /// let invalid = Response::new(503).with_retry_after_header("soon");
91    /// assert_eq!(invalid.retry_after, None);
92    /// ```
93    pub fn with_retry_after_header(mut self, value: &str) -> Self {
94        self.retry_after = parse_retry_after(value);
95
96        self
97    }
98
99    /// Sets the response body. The body can be bytes, like a protobuf body, or a
100    /// `String` or a `&str`.
101    pub fn with_body<B: Into<Vec<u8>>>(mut self, body: B) -> Self {
102        self.body = body.into();
103
104        self
105    }
106}
107
108/// Turns a `Retry-After` value into a wait time. Returns `None` for an invalid
109/// value. A date in the past means no wait.
110///
111/// `parse_retry_after` in `cargo-flareapp/src/upload.rs` is a copy of this
112/// function, because the CLI does not depend on this crate. Keep both copies the
113/// same.
114fn parse_retry_after(value: &str) -> Option<Duration> {
115    let value = value.trim();
116
117    if let Ok(seconds) = value.parse::<u64>() {
118        return Some(Duration::from_secs(seconds));
119    }
120
121    let date = httpdate::parse_http_date(value).ok()?;
122
123    Some(date.duration_since(SystemTime::now()).unwrap_or_default())
124}
125
126/// Sends requests to Flare. Implement this trait to send data with your own HTTP
127/// client.
128///
129/// The Flare client handles retries and rate limits. A transport only sends one
130/// request and returns the response. A transport follows two rules:
131///
132/// - Return every HTTP response as a [`Response`], also a response with an error
133///   status like 503. Copy the `Retry-After` header with
134///   [`Response::with_retry_after_header`]. The Flare client then decides if it
135///   tries again, and when.
136/// - Return a [`TransportError`] only when no HTTP response came back, for example
137///   when the connection failed or timed out.
138///
139/// # Examples
140///
141/// `post` stands for the function of your HTTP client that sends the request.
142///
143/// ```
144/// use flareapp_core::{Config, Request, Response, Transport, TransportError};
145///
146/// #[derive(Debug)]
147/// struct MyHttpClient;
148///
149/// impl Transport for MyHttpClient {
150///     fn send(&self, request: &Request) -> Result<Response, TransportError> {
151///         // A connection error becomes a `TransportError`.
152///         let answer = post(&request.url, &request.headers, &request.body)
153///             .map_err(TransportError::new)?;
154///
155///         // Every HTTP status becomes a response, also an error status.
156///         let mut response = Response::new(answer.status).with_body(answer.body);
157///         if let Some(retry_after) = &answer.retry_after {
158///             response = response.with_retry_after_header(retry_after);
159///         }
160///
161///         Ok(response)
162///     }
163/// }
164///
165/// let config = Config::new().transport(MyHttpClient);
166/// # struct Answer {
167/// #     status: u16,
168/// #     retry_after: Option<String>,
169/// #     body: Vec<u8>,
170/// # }
171/// # fn post(_: &str, _: &[(&str, String)], _: &[u8]) -> Result<Answer, std::io::Error> {
172/// #     Ok(Answer { status: 503, retry_after: Some("120".to_owned()), body: b"busy".to_vec() })
173/// # }
174/// ```
175pub trait Transport: Send + Sync + fmt::Debug + 'static {
176    /// Sends one request and returns the response.
177    ///
178    /// # Errors
179    ///
180    /// Returns an error when no HTTP response came back, for example when the
181    /// connection failed or timed out. An HTTP error status, like 500, is not an
182    /// error here: return it as a [`Response`], so the Flare client can decide
183    /// whether to try again.
184    fn send(&self, request: &Request) -> Result<Response, TransportError>;
185}
186
187/// The error for a request that got no HTTP response, like a connection failure or a timeout.
188///
189/// The error shows the message of the wrapped error, and returns the cause of the
190/// wrapped error as its [`Error::source`]. So a tool that prints the whole chain of
191/// causes shows each message once.
192#[derive(Debug)]
193pub struct TransportError {
194    error: Box<dyn Error + Send + Sync>,
195}
196
197impl TransportError {
198    /// Wraps the error of your HTTP client.
199    pub fn new<E: Into<Box<dyn Error + Send + Sync>>>(error: E) -> Self {
200        Self {
201            error: error.into(),
202        }
203    }
204}
205
206impl fmt::Display for TransportError {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        fmt::Display::fmt(&self.error, f)
209    }
210}
211
212impl Error for TransportError {
213    fn source(&self) -> Option<&(dyn Error + 'static)> {
214        self.error.source()
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn retry_after_in_seconds() {
224        assert_eq!(parse_retry_after("60"), Some(Duration::from_secs(60)));
225    }
226
227    #[test]
228    fn retry_after_ignores_whitespace() {
229        assert_eq!(parse_retry_after(" 5 "), Some(Duration::from_secs(5)));
230    }
231
232    #[test]
233    fn retry_after_as_http_date() {
234        let in_two_minutes = SystemTime::now() + Duration::from_secs(120);
235        let header = httpdate::fmt_http_date(in_two_minutes);
236
237        let wait = parse_retry_after(&header).unwrap();
238
239        assert!(wait > Duration::from_secs(110) && wait <= Duration::from_secs(120));
240    }
241
242    #[test]
243    fn retry_after_in_the_past_means_no_wait() {
244        assert_eq!(
245            parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"),
246            Some(Duration::ZERO)
247        );
248    }
249
250    #[test]
251    fn invalid_retry_after_is_ignored() {
252        assert_eq!(parse_retry_after("soon"), None);
253    }
254
255    #[test]
256    fn transport_errors_show_the_message_of_the_wrapped_error() {
257        let error = TransportError::new("connection refused");
258
259        assert_eq!(error.to_string(), "connection refused");
260    }
261
262    /// An error with a cause, like the errors of most HTTP clients.
263    #[derive(Debug)]
264    struct ConnectError(std::io::Error);
265
266    impl fmt::Display for ConnectError {
267        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268            f.write_str("could not connect")
269        }
270    }
271
272    impl Error for ConnectError {
273        fn source(&self) -> Option<&(dyn Error + 'static)> {
274            Some(&self.0)
275        }
276    }
277
278    #[test]
279    fn transport_errors_return_the_cause_of_the_wrapped_error() {
280        let error = TransportError::new(ConnectError(std::io::Error::other("connection refused")));
281
282        assert_eq!(
283            error.source().map(ToString::to_string),
284            Some("connection refused".to_owned())
285        );
286    }
287}