withone 0.1.1

Typed Rust client for the One API: the client, webhooks and the action type every withone-<platform> crate builds on.
Documentation
use std::{fmt::Display, future::Future, time::Duration};

use tokio::time::sleep;

/// Marker trait for errors that can be classified as transient — eligible for
/// automatic retry — versus structural, where retrying is wasted work. This is
/// the *general* classifier used by [`WithRetry`]; HTTP status classification
/// (`retry_on`, `Retry-After`) is a separate concern that lives on the call.
pub trait Retryable {
    /// `true` if the failure is expected to resolve on a fresh attempt
    /// (network drop, timeout, 5xx, 429); `false` if structural (4xx, decode).
    fn is_transient(&self) -> bool;
}

/// Bounded exponential-backoff schedule — the shared *timing* vocabulary for
/// retries, used by both the call engine and (later) webhook handler retry.
/// It holds no HTTP concepts: per-attempt delay doubles up to `max_delay` and
/// total attempts are capped by `max_attempts`.
#[derive(Clone, Copy, Debug)]
pub struct RetrySchedule {
    pub max_attempts:  u32,
    pub initial_delay: Duration,
    pub max_delay:     Duration
}

impl RetrySchedule {
    /// No retries: a single attempt.
    pub const fn none() -> Self {
        Self {
            max_attempts:  1,
            initial_delay: Duration::ZERO,
            max_delay:     Duration::ZERO
        }
    }

    /// Conservative default for transient errors: 3 attempts, 100ms → 200ms →
    /// 400ms (cap 1s).
    pub const fn transient() -> Self {
        Self {
            max_attempts:  3,
            initial_delay: Duration::from_millis(100),
            max_delay:     Duration::from_secs(1)
        }
    }

    /// Sets the maximum number of attempts — a chainable tweak over a preset.
    pub fn attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    /// Sets the initial and maximum backoff delays.
    pub fn backoff(mut self, initial: Duration, max: Duration) -> Self {
        self.initial_delay = initial;
        self.max_delay = max;
        self
    }

    /// The backoff delay before retrying after the given 1-based `attempt`:
    /// `initial_delay * 2^(attempt - 1)`, capped at `max_delay`.
    pub fn delay(&self, attempt: u32) -> Duration {
        let factor = 1u32.checked_shl(attempt.saturating_sub(1)).unwrap_or(u32::MAX);
        self.initial_delay.saturating_mul(factor).min(self.max_delay)
    }
}

impl Default for RetrySchedule {
    fn default() -> Self {
        Self::transient()
    }
}

/// Postfix retry combinator over an async operation **factory** — the general
/// retry engine (e.g. for retrying a whole webhook handler). The receiver must
/// be a factory (`FnMut() -> Future`) rather than a `Future`, because a
/// `Future` is single-use — every retry attempt needs a freshly-produced one.
///
/// ```ignore
/// (|| handler())
///     .with_retry(RetrySchedule::transient())
///     .await
/// ```
///
/// Behaviour: up to `schedule.max_attempts` attempts. On `Ok`, returns
/// immediately. On `Err` whose [`Retryable::is_transient`] is `false`, returns
/// immediately. On transient `Err`, sleeps the schedule's backoff and retries;
/// the last attempt's error is returned if all fail.
pub trait WithRetry<T, E>: Sized {
    fn with_retry(self, schedule: RetrySchedule) -> impl Future<Output = Result<T, E>> + Send
    where
        Self: Send,
        T: Send,
        E: Send;
}

impl<F, Fut, T, E> WithRetry<T, E> for F
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>> + Send,
    E: Retryable + Display
{
    async fn with_retry(mut self, schedule: RetrySchedule) -> Result<T, E>
    where
        Self: Send,
        T: Send,
        E: Send
    {
        for attempt in 1..=schedule.max_attempts {
            match self().await {
                Ok(v) => return Ok(v),
                Err(e) if !e.is_transient() => return Err(e),
                Err(e) => {
                    if attempt == schedule.max_attempts {
                        return Err(e);
                    }
                    sleep(schedule.delay(attempt)).await;
                }
            }
        }
        unreachable!("loop exits via return on every iteration")
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fmt,
        sync::atomic::{AtomicUsize, Ordering}
    };

    use super::*;

    #[derive(Debug)]
    enum FakeError {
        Transient,
        Permanent
    }

    impl Display for FakeError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::Transient => f.write_str("transient"),
                Self::Permanent => f.write_str("permanent")
            }
        }
    }

    impl Retryable for FakeError {
        fn is_transient(&self) -> bool {
            matches!(self, Self::Transient)
        }
    }

    fn fast_schedule() -> RetrySchedule {
        RetrySchedule::transient()
            .attempts(5)
            .backoff(Duration::from_millis(1), Duration::from_millis(2))
    }

    #[test]
    fn test_retry_backoff_doubles_then_caps() {
        let schedule = RetrySchedule::transient()
            .attempts(6)
            .backoff(Duration::from_millis(100), Duration::from_millis(400));
        assert_eq!(schedule.delay(1), Duration::from_millis(100));
        assert_eq!(schedule.delay(2), Duration::from_millis(200));
        assert_eq!(schedule.delay(3), Duration::from_millis(400));
        assert_eq!(schedule.delay(4), Duration::from_millis(400), "capped at max_delay");
        assert_eq!(schedule.delay(99), Duration::from_millis(400), "no overflow at large attempts");
    }

    #[test]
    fn test_retry_default_is_transient() {
        assert_eq!(RetrySchedule::default().max_attempts, RetrySchedule::transient().max_attempts);
    }

    #[tokio::test]
    async fn test_retry_returns_on_first_success() {
        let calls = AtomicUsize::new(0);
        let result: Result<u32, FakeError> = (|| async {
            calls.fetch_add(1, Ordering::SeqCst);
            Ok(42)
        })
        .with_retry(fast_schedule())
        .await;
        assert_eq!(result.unwrap(), 42);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_retry_eventually_succeeds_after_transient_errors() {
        let calls = AtomicUsize::new(0);
        let result: Result<u32, FakeError> = (|| async {
            let n = calls.fetch_add(1, Ordering::SeqCst) + 1;
            if n < 3 { Err(FakeError::Transient) } else { Ok(7) }
        })
        .with_retry(fast_schedule())
        .await;
        assert_eq!(result.unwrap(), 7, "succeeds on 3rd attempt");
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn test_retry_exhausts_attempts_and_returns_last_transient_error() {
        let calls = AtomicUsize::new(0);
        let result: Result<u32, FakeError> = (|| async {
            calls.fetch_add(1, Ordering::SeqCst);
            Err(FakeError::Transient)
        })
        .with_retry(fast_schedule())
        .await;
        assert!(matches!(result, Err(FakeError::Transient)));
        assert_eq!(calls.load(Ordering::SeqCst), 5, "exhausts max_attempts");
    }

    #[tokio::test]
    async fn test_retry_bails_immediately_on_non_transient_error() {
        let calls = AtomicUsize::new(0);
        let result: Result<u32, FakeError> = (|| async {
            calls.fetch_add(1, Ordering::SeqCst);
            Err(FakeError::Permanent)
        })
        .with_retry(fast_schedule())
        .await;
        assert!(matches!(result, Err(FakeError::Permanent)));
        assert_eq!(calls.load(Ordering::SeqCst), 1, "no retry on permanent error");
    }
}