flareapp-core 0.1.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Decides what a response means for a batch, and when to try a failed request
//! again.

use std::time::Duration;

use crate::transport::{Response, TransportError};

/// The settings for trying a failed request again.
///
/// The policy follows the OTLP/HTTP rules: the wait doubles after every failed
/// try, with some randomness added, unless the server sends a `Retry-After`
/// header.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct RetryPolicy {
    /// How many times a request is tried again before its batch is dropped.
    pub(crate) max_retries: u32,
    /// The wait before the first retry.
    pub(crate) base_delay: Duration,
    /// The longest wait between two tries. A `Retry-After` header from the server
    /// can ask for a longer wait.
    pub(crate) max_delay: Duration,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_retries: 3,
            base_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(30),
        }
    }
}

impl RetryPolicy {
    /// Returns how long to wait before retry number `attempt`. The first retry is
    /// attempt 0. When the server sent `Retry-After`, that wait is used instead.
    pub(super) fn delay(&self, attempt: u32, retry_after: Option<Duration>) -> Duration {
        retry_after.unwrap_or_else(|| {
            let backoff = self
                .base_delay
                .saturating_mul(2_u32.saturating_pow(attempt))
                .min(self.max_delay);

            // Wait between 50% and 100% of the backoff. Many clients that failed at
            // the same moment then do not all retry at the same moment.
            backoff.mul_f64(fastrand::f64().mul_add(0.5, 0.5))
        })
    }
}

/// What the response to a request means for the batch that was sent.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Outcome {
    /// The server accepted the batch.
    Sent,
    /// The server refused the batch. Trying again does not help, so the batch is
    /// dropped.
    Rejected,
    /// The request failed for now. Try again later, after the wait from
    /// `Retry-After` when the server sent one.
    Retry(Option<Duration>),
}

/// Decides what to do with a batch, based on what the transport returned.
pub(super) fn classify(result: &Result<Response, TransportError>) -> Outcome {
    match result {
        Ok(response) if (200..300).contains(&response.status) => Outcome::Sent,
        // OTLP/HTTP only allows retries for these status codes.
        Ok(response) if matches!(response.status, 429 | 502 | 503 | 504) => {
            Outcome::Retry(response.retry_after)
        }
        Ok(_) => Outcome::Rejected,
        Err(_) => Outcome::Retry(None),
    }
}

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

    #[test]
    fn backoff_doubles_with_jitter() {
        let policy = RetryPolicy::default();

        for (attempt, full) in [(0, 1), (1, 2), (2, 4), (10, 30)] {
            let delay = policy.delay(attempt, None);
            assert!(
                delay >= secs(full) / 2 && delay <= secs(full),
                "attempt {attempt}: {delay:?}"
            );
        }
    }

    #[test]
    fn retry_after_overrides_the_backoff() {
        assert_eq!(RetryPolicy::default().delay(0, Some(secs(60))), secs(60));
    }

    fn outcomes(codes: &[u16]) -> Vec<Outcome> {
        codes
            .iter()
            .map(|code| classify(&Ok(Response::new(*code))))
            .collect()
    }

    #[test]
    fn success_codes_are_sent() {
        assert_eq!(outcomes(&[200, 201]), [Outcome::Sent, Outcome::Sent]);
    }

    #[test]
    fn other_client_and_server_errors_are_rejected() {
        assert_eq!(outcomes(&[400, 401, 422, 500]), [Outcome::Rejected; 4]);
    }

    #[test]
    fn throttling_and_gateway_errors_are_retried() {
        assert_eq!(outcomes(&[429, 502, 503, 504]), [Outcome::Retry(None); 4]);
    }

    #[test]
    fn retries_wait_for_retry_after() {
        assert_eq!(
            classify(&Ok(Response::new(429).with_retry_after_header("60"))),
            Outcome::Retry(Some(secs(60)))
        );
    }

    #[test]
    fn connection_errors_are_retried() {
        assert_eq!(
            classify(&Err(TransportError::new("connection refused"))),
            Outcome::Retry(None)
        );
    }
}