flareapp 0.2.0

Report errors, logs and traces from Rust applications to Flare.
Documentation
//! The default [`Transport`], built on the `ureq` HTTP client.

use std::time::Duration;

use ureq::tls::{RootCerts, TlsConfig};

use super::{Request, Response, Transport, TransportError};

/// The Flare client reads the response body only in debug mode, so the transport
/// reads at most 16 KB of the body.
const MAX_BODY_BYTES: u64 = 16 * 1024;

/// The default transport, which sends requests with the `ureq` HTTP client.
#[derive(Debug)]
pub(crate) struct UreqTransport {
    agent: ureq::Agent,
}

impl UreqTransport {
    /// Creates a transport whose requests time out after `timeout`.
    ///
    /// The transport checks certificates against the trust store of the operating
    /// system, so local development certificates and company proxies work too.
    pub(crate) fn new(timeout: Duration) -> Self {
        let tls = TlsConfig::builder()
            .root_certs(RootCerts::PlatformVerifier)
            .build();

        let agent = ureq::Agent::config_builder()
            .timeout_global(Some(timeout))
            .http_status_as_error(false)
            .tls_config(tls)
            .build()
            .new_agent();

        Self { agent }
    }
}

impl Transport for UreqTransport {
    fn send(&self, request: &Request) -> Result<Response, TransportError> {
        let mut builder = self.agent.post(&request.url);
        for (name, value) in &request.headers {
            builder = builder.header(*name, value.as_str());
        }

        let mut response = builder
            .send(request.body.as_slice())
            .map_err(TransportError::new)?;

        let mut result = Response::new(response.status().as_u16());

        if let Some(value) = response
            .headers()
            .get("retry-after")
            .and_then(|value| value.to_str().ok())
        {
            result = result.with_retry_after_header(value);
        }

        // Reading the body lets ureq reuse the connection for the next request. A
        // read error does not matter, because the status is already known.
        let body = response
            .body_mut()
            .with_config()
            .limit(MAX_BODY_BYTES)
            .read_to_vec()
            .unwrap_or_default();

        Ok(result.with_body(body))
    }
}