rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! Bounded repetitions after transient errors.
//!
//! A request is repeated at most `retries` times, and only after a
//! connection error, a timeout, or a status 500, 502, 503 or 504 without a
//! HAFAS error code. Never after another status, a HAFAS error code (like
//! `API_QUOTA` or `API_TOO_MANY_REQUESTS`) or an unexpected answer: those do
//! not change by asking again, and every request counts against the quota of
//! the access key.
//!
//! The waits double from [`Policy::delay`] with some jitter, or follow
//! `Retry-After`. All attempts and waits together stay within
//! [`Policy::timeout`]: what does not fit is not tried.

use std::future::Future;
use std::time::Duration;

use tokio::time::Instant;

/// The first wait before a repetition.
pub const DEFAULT_DELAY: Duration = Duration::from_millis(500);

/// How to repeat a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Policy {
    /// The most repetitions after the first attempt.
    pub retries: u32,
    /// The time for all attempts and waits together.
    pub timeout: Duration,
    /// The first wait, doubled for each further one.
    pub delay: Duration,
}

/// Why the attempts ended without an answer.
#[derive(Debug)]
pub(crate) enum Failure {
    /// The last error of the client.
    Hafas(hafas::Error),
    /// The time ran out during an attempt.
    OutOfTime,
}

impl From<Failure> for crate::Error {
    fn from(failure: Failure) -> Self {
        match failure {
            Failure::Hafas(error) => error.into(),
            Failure::OutOfTime => Self::Timeout,
        }
    }
}

/// Whether asking again can help.
pub(crate) fn is_transient(error: &hafas::Error) -> bool {
    match error {
        hafas::Error::Timeout(_) | hafas::Error::Http(_) => true,
        hafas::Error::Status { status, .. } => matches!(status, 500 | 502 | 503 | 504),
        _ => false,
    }
}

/// The wait before repetition `attempt` (1 for the first): `delay` doubled
/// for each earlier one, plus up to half of it as jitter, or what the server
/// asked for.
fn wait(policy: &Policy, attempt: u32, error: &hafas::Error) -> Duration {
    if let Some(wait) = error.retry_after() {
        return wait;
    }
    let base = policy
        .delay
        .saturating_mul(2u32.saturating_pow(attempt.saturating_sub(1)));
    // Enough to keep clients from asking at the same moment.
    let nanos = jiff::Timestamp::now().subsec_nanosecond().unsigned_abs();
    let jitter = base.mul_f64(f64::from(nanos % 1000) / 2000.0);
    base + jitter
}

/// Runs `attempt` until it succeeds, fails for good, the repetitions are
/// used up or the time runs out.
pub(crate) async fn run<T, F, Fut>(policy: &Policy, mut attempt: F) -> Result<T, Failure>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, hafas::Error>>,
{
    let deadline = Instant::now() + policy.timeout;
    let mut repetition = 0;
    loop {
        let remaining = deadline.saturating_duration_since(Instant::now());
        let error = match tokio::time::timeout(remaining, attempt()).await {
            Ok(Ok(value)) => return Ok(value),
            Ok(Err(error)) => error,
            Err(_) => return Err(Failure::OutOfTime),
        };
        if repetition >= policy.retries || !is_transient(&error) {
            return Err(Failure::Hafas(error));
        }
        repetition += 1;
        let wait = wait(policy, repetition, &error);
        // Compared as durations: a huge `Retry-After` must not overflow.
        if wait >= deadline.saturating_duration_since(Instant::now()) {
            return Err(Failure::Hafas(error));
        }
        let wait_ms = u64::try_from(wait.as_millis()).unwrap_or(u64::MAX);
        tracing::warn!(attempt = repetition, wait_ms, %error, "repeating the request");
        tokio::time::sleep(wait).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn status(status: u16, retry_after: Option<Duration>) -> hafas::Error {
        hafas::Error::Status {
            status,
            message: "text".into(),
            retry_after,
        }
    }

    fn policy(retries: u32) -> Policy {
        Policy {
            retries,
            timeout: Duration::from_secs(5),
            delay: Duration::from_millis(1),
        }
    }

    /// Runs with `errors` as the answers of the first attempts, then
    /// success. Returns the result and the number of attempts.
    async fn attempts(policy: &Policy, errors: Vec<hafas::Error>) -> (Result<u8, Failure>, u32) {
        let count = AtomicU32::new(0);
        let errors = std::sync::Mutex::new(errors.into_iter());
        let result = run(policy, || {
            count.fetch_add(1, Ordering::SeqCst);
            let next = errors.lock().unwrap().next();
            async move { next.map_or(Ok(7), Err) }
        })
        .await;
        (result, count.load(Ordering::SeqCst))
    }

    #[test]
    fn only_transient_errors_are_repeated() {
        for code in [500, 502, 503, 504] {
            assert!(is_transient(&status(code, None)), "{code}");
        }
        for code in [400, 401, 403, 404, 429, 501] {
            assert!(!is_transient(&status(code, None)), "{code}");
        }
        let api = hafas::Error::Api {
            status: Some(503),
            code: "INT_TIMEOUT".into(),
            text: String::new(),
            retry_after: None,
        };
        assert!(!is_transient(&api));
        assert!(!is_transient(&hafas::Error::Decode("x".into())));
        assert!(!is_transient(&hafas::Error::AccessIdMissing));
    }

    #[tokio::test]
    async fn repeats_until_it_works() {
        let (result, count) =
            attempts(&policy(2), vec![status(503, None), status(502, None)]).await;
        assert_eq!(result.unwrap(), 7);
        assert_eq!(count, 3);
    }

    #[tokio::test]
    async fn stops_after_the_last_repetition() {
        let errors = vec![status(503, None), status(503, None), status(500, None)];
        let (result, count) = attempts(&policy(2), errors).await;
        assert!(
            matches!(
                result,
                Err(Failure::Hafas(hafas::Error::Status { status: 500, .. }))
            ),
            "{result:?}"
        );
        assert_eq!(count, 3);
        let (result, count) = attempts(&policy(0), vec![status(503, None)]).await;
        assert!(result.is_err());
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn does_not_repeat_a_final_error() {
        let (result, count) = attempts(&policy(2), vec![status(400, None)]).await;
        assert!(result.is_err());
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn a_wait_beyond_the_time_is_not_taken() {
        let wait = Some(Duration::from_secs(60));
        let (result, count) = attempts(&policy(2), vec![status(503, wait)]).await;
        assert!(result.is_err());
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn a_huge_retry_after_does_not_overflow() {
        let wait = Some(Duration::from_secs(u64::MAX));
        let (result, count) = attempts(&policy(2), vec![status(503, wait)]).await;
        assert!(result.is_err());
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn follows_retry_after() {
        let wait = Some(Duration::from_millis(20));
        let start = Instant::now();
        let (result, count) = attempts(&policy(1), vec![status(503, wait)]).await;
        assert_eq!(result.unwrap(), 7);
        assert_eq!(count, 2);
        assert!(start.elapsed() >= Duration::from_millis(20));
    }

    #[tokio::test]
    async fn an_attempt_beyond_the_time_is_cut() {
        let policy = Policy {
            timeout: Duration::from_millis(20),
            ..policy(2)
        };
        let result: Result<u8, Failure> =
            run(&policy, std::future::pending::<Result<u8, hafas::Error>>).await;
        assert!(matches!(result, Err(Failure::OutOfTime)), "{result:?}");
        assert_eq!(crate::Error::from(Failure::OutOfTime).status(), "timeout");
    }

    #[test]
    fn the_waits_double() {
        let policy = Policy {
            delay: Duration::from_millis(100),
            ..policy(3)
        };
        let error = status(503, None);
        for (attempt, base) in [(1, 100), (2, 200), (3, 400)] {
            let wait = wait(&policy, attempt, &error);
            let base = Duration::from_millis(base);
            assert!(wait >= base && wait <= base * 3 / 2, "{attempt}: {wait:?}");
        }
    }
}