flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! The [`Transport`] trait that sends requests to Flare, and the request and
//! response types it uses.

use std::error::Error;
use std::fmt;
use std::time::{Duration, SystemTime};

/// The kind of data in a request. Each kind goes to its own endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Signal {
    /// Error reports, sent to `/v1/errors`.
    Errors,
    /// OTLP log records, sent to `/v1/logs`.
    Logs,
    /// OTLP spans, sent to `/v1/traces`.
    Traces,
}

impl Signal {
    /// Returns the URL path for this kind of data, like `/v1/logs`.
    pub fn path(self) -> &'static str {
        match self {
            Self::Errors => "/v1/errors",
            Self::Logs => "/v1/logs",
            Self::Traces => "/v1/traces",
        }
    }
}

/// An HTTP `POST` request to Flare, ready to send.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Request {
    /// What kind of data the body holds.
    pub signal: Signal,
    /// The full URL, like `https://ingress.flareapp.io/v1/logs`.
    pub url: String,
    /// Header names and values. They include the API key.
    pub headers: Vec<(&'static str, String)>,
    /// The body, in the format that the `content-type` header names: JSON for
    /// error reports, and OTLP protobuf or JSON for logs and traces.
    pub body: Vec<u8>,
}

/// The parts of an HTTP response that the Flare client needs: the status, the retry
/// time and the body.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[must_use]
pub struct Response {
    /// The HTTP status code.
    pub status: u16,
    /// How long the server asks the Flare client to wait before it tries again.
    /// Comes from the `Retry-After` header.
    pub retry_after: Option<Duration>,
    /// The response body. In debug mode, the Flare client reads the partial
    /// success of an OTLP response from it, and prints the body of a failed request.
    pub body: Vec<u8>,
}

impl Response {
    /// Creates a response with a status code and no body.
    pub fn new(status: u16) -> Self {
        Self {
            status,
            retry_after: None,
            body: Vec::new(),
        }
    }

    /// Reads the wait time from the value of a `Retry-After` header.
    ///
    /// The value can be a number of seconds or an HTTP date. An invalid value is
    /// ignored. A date in the past means no wait.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use flareapp_core::Response;
    ///
    /// let seconds = Response::new(429).with_retry_after_header("120");
    /// assert_eq!(seconds.retry_after, Some(Duration::from_secs(120)));
    ///
    /// let date = Response::new(503).with_retry_after_header("Wed, 21 Oct 2015 07:28:00 GMT");
    /// assert_eq!(date.retry_after, Some(Duration::ZERO));
    ///
    /// let invalid = Response::new(503).with_retry_after_header("soon");
    /// assert_eq!(invalid.retry_after, None);
    /// ```
    pub fn with_retry_after_header(mut self, value: &str) -> Self {
        self.retry_after = parse_retry_after(value);

        self
    }

    /// Sets the response body. The body can be bytes, like a protobuf body, or a
    /// `String` or a `&str`.
    pub fn with_body<B: Into<Vec<u8>>>(mut self, body: B) -> Self {
        self.body = body.into();

        self
    }
}

/// Turns a `Retry-After` value into a wait time. Returns `None` for an invalid
/// value. A date in the past means no wait.
///
/// `parse_retry_after` in `cargo-flareapp/src/upload.rs` is a copy of this
/// function, because the CLI does not depend on this crate. Keep both copies the
/// same.
fn parse_retry_after(value: &str) -> Option<Duration> {
    let value = value.trim();

    if let Ok(seconds) = value.parse::<u64>() {
        return Some(Duration::from_secs(seconds));
    }

    let date = httpdate::parse_http_date(value).ok()?;

    Some(date.duration_since(SystemTime::now()).unwrap_or_default())
}

/// Sends requests to Flare. Implement this trait to send data with your own HTTP
/// client.
///
/// The Flare client handles retries and rate limits. A transport only sends one
/// request and returns the response. A transport follows two rules:
///
/// - Return every HTTP response as a [`Response`], also a response with an error
///   status like 503. Copy the `Retry-After` header with
///   [`Response::with_retry_after_header`]. The Flare client then decides if it
///   tries again, and when.
/// - Return a [`TransportError`] only when no HTTP response came back, for example
///   when the connection failed or timed out.
///
/// # Examples
///
/// `post` stands for the function of your HTTP client that sends the request.
///
/// ```
/// use flareapp_core::{Config, Request, Response, Transport, TransportError};
///
/// #[derive(Debug)]
/// struct MyHttpClient;
///
/// impl Transport for MyHttpClient {
///     fn send(&self, request: &Request) -> Result<Response, TransportError> {
///         // A connection error becomes a `TransportError`.
///         let answer = post(&request.url, &request.headers, &request.body)
///             .map_err(TransportError::new)?;
///
///         // Every HTTP status becomes a response, also an error status.
///         let mut response = Response::new(answer.status).with_body(answer.body);
///         if let Some(retry_after) = &answer.retry_after {
///             response = response.with_retry_after_header(retry_after);
///         }
///
///         Ok(response)
///     }
/// }
///
/// let config = Config::new().transport(MyHttpClient);
/// # struct Answer {
/// #     status: u16,
/// #     retry_after: Option<String>,
/// #     body: Vec<u8>,
/// # }
/// # fn post(_: &str, _: &[(&str, String)], _: &[u8]) -> Result<Answer, std::io::Error> {
/// #     Ok(Answer { status: 503, retry_after: Some("120".to_owned()), body: b"busy".to_vec() })
/// # }
/// ```
pub trait Transport: Send + Sync + fmt::Debug + 'static {
    /// Sends one request and returns the response.
    ///
    /// # Errors
    ///
    /// Returns an error when no HTTP response came back, for example when the
    /// connection failed or timed out. An HTTP error status, like 500, is not an
    /// error here: return it as a [`Response`], so the Flare client can decide
    /// whether to try again.
    fn send(&self, request: &Request) -> Result<Response, TransportError>;
}

/// The error for a request that got no HTTP response, like a connection failure or a timeout.
///
/// The error shows the message of the wrapped error, and returns the cause of the
/// wrapped error as its [`Error::source`]. So a tool that prints the whole chain of
/// causes shows each message once.
#[derive(Debug)]
pub struct TransportError {
    error: Box<dyn Error + Send + Sync>,
}

impl TransportError {
    /// Wraps the error of your HTTP client.
    pub fn new<E: Into<Box<dyn Error + Send + Sync>>>(error: E) -> Self {
        Self {
            error: error.into(),
        }
    }
}

impl fmt::Display for TransportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.error, f)
    }
}

impl Error for TransportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.error.source()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn retry_after_in_seconds() {
        assert_eq!(parse_retry_after("60"), Some(Duration::from_secs(60)));
    }

    #[test]
    fn retry_after_ignores_whitespace() {
        assert_eq!(parse_retry_after(" 5 "), Some(Duration::from_secs(5)));
    }

    #[test]
    fn retry_after_as_http_date() {
        let in_two_minutes = SystemTime::now() + Duration::from_secs(120);
        let header = httpdate::fmt_http_date(in_two_minutes);

        let wait = parse_retry_after(&header).unwrap();

        assert!(wait > Duration::from_secs(110) && wait <= Duration::from_secs(120));
    }

    #[test]
    fn retry_after_in_the_past_means_no_wait() {
        assert_eq!(
            parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"),
            Some(Duration::ZERO)
        );
    }

    #[test]
    fn invalid_retry_after_is_ignored() {
        assert_eq!(parse_retry_after("soon"), None);
    }

    #[test]
    fn transport_errors_show_the_message_of_the_wrapped_error() {
        let error = TransportError::new("connection refused");

        assert_eq!(error.to_string(), "connection refused");
    }

    /// An error with a cause, like the errors of most HTTP clients.
    #[derive(Debug)]
    struct ConnectError(std::io::Error);

    impl fmt::Display for ConnectError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("could not connect")
        }
    }

    impl Error for ConnectError {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&self.0)
        }
    }

    #[test]
    fn transport_errors_return_the_cause_of_the_wrapped_error() {
        let error = TransportError::new(ConnectError(std::io::Error::other("connection refused")));

        assert_eq!(
            error.source().map(ToString::to_string),
            Some("connection refused".to_owned())
        );
    }
}