hookburn-core 0.2.2

Shared HTTP client and WebhookSender trait for the Hookburn crates
Documentation
// crates/hookburn-core/src/retry.rs
use std::time::Duration;

/// Policy controlling how [`HttpClient::post_json_with_retry`] retries failed
/// requests.
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    /// Maximum total attempts (including the first try). Clamped to at least 1.
    pub max_attempts: u32,

    /// Delay before the first retry. Each subsequent retry doubles this value.
    pub base_delay: Duration,

    /// When `true`, add a random sub-delay ≤ the current step to spread out
    /// concurrent retries.
    pub jitter: bool,
}

impl RetryPolicy {
    /// Calculate the delay for a given attempt number (0-indexed).
    ///
    /// Uses exponential backoff: delay = `base_delay` * 2^attempt
    /// With optional jitter: adds random value up to the base delay.
    ///
    /// # Example
    ///
    /// ```rust
    /// use hookburn_core::RetryPolicy;
    /// use std::time::Duration;
    ///
    /// let policy = RetryPolicy::default();
    /// let delay = policy.calculate_delay(2); // third attempt
    /// ```
    #[must_use]
    pub fn calculate_delay(&self, attempt: u32) -> Duration {
        let factor = 1u32 << attempt; // 2^attempt
        let base = self.base_delay * factor;

        if self.jitter {
            // Add random jitter (0-100% of the base delay)
            let jitter_factor = rand::random::<f64>(); // 0.0 to 1.0
            let jitter = Duration::from_secs_f64(base.as_secs_f64() * jitter_factor);
            base + jitter
        } else {
            base
        }
    }

    /// Calculate the delay for a given attempt with a custom jitter source.
    ///
    /// # Example
    ///
    /// ```rust
    /// use hookburn_core::RetryPolicy;
    /// use std::time::Duration;
    ///
    /// let policy = RetryPolicy::default();
    /// let delay = policy.calculate_delay_with_jitter(2, || 0.5);
    /// ```
    #[must_use]
    pub fn calculate_delay_with_jitter<F>(&self, attempt: u32, jitter_fn: F) -> Duration
    where
        F: Fn() -> f64,
    {
        let factor = 1u32 << attempt;
        let base = self.base_delay * factor;

        if self.jitter {
            let jitter_factor = jitter_fn();
            let jitter = Duration::from_secs_f64(base.as_secs_f64() * jitter_factor);
            base + jitter
        } else {
            base
        }
    }
}

impl Default for RetryPolicy {
    
    fn default() -> Self {
        Self {
            max_attempts: 3,
            base_delay: Duration::from_millis(500),
            jitter: true,
        }
    }
}

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

    #[test]
    fn default_values_are_sensible() {
        let p = RetryPolicy::default();
        assert_eq!(p.max_attempts, 3);
        assert_eq!(p.base_delay, Duration::from_millis(500));
        assert!(p.jitter, "jitter should be on by default");
    }

    #[test]
    fn clone_is_independent() {
        let a = RetryPolicy {
            max_attempts: 5,
            base_delay: Duration::from_millis(100),
            jitter: false,
        };
        let b = a.clone();
        assert_eq!(b.max_attempts, 5);
        assert_eq!(b.base_delay, Duration::from_millis(100));
        assert!(!b.jitter);
    }

    #[test]
    fn custom_values_are_preserved() {
        let p = RetryPolicy {
            max_attempts: 10,
            base_delay: Duration::from_secs(2),
            ..Default::default()
        };
        assert_eq!(p.max_attempts, 10);
        assert_eq!(p.base_delay, Duration::from_secs(2));
        assert!(p.jitter); // inherited from Default
    }

    #[test]
    fn test_delay_calculation_no_jitter() {
        let policy = RetryPolicy {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
            jitter: false,
        };

        assert_eq!(policy.calculate_delay(0), Duration::from_millis(100));
        assert_eq!(policy.calculate_delay(1), Duration::from_millis(200));
        assert_eq!(policy.calculate_delay(2), Duration::from_millis(400));
        assert_eq!(policy.calculate_delay(3), Duration::from_millis(800));
    }

    #[test]
    fn test_delay_calculation_with_jitter() {
        let policy = RetryPolicy {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
            jitter: true,
        };

        // With jitter, delays should be >= base
        let delay0 = policy.calculate_delay(0);
        assert!(delay0 >= Duration::from_millis(100));
        assert!(delay0 < Duration::from_millis(200)); // Should be < 200ms

        let delay1 = policy.calculate_delay(1);
        assert!(delay1 >= Duration::from_millis(200));
        assert!(delay1 < Duration::from_millis(400));
    }

    #[test]
    fn test_calculate_delay_with_custom_jitter() {
        let policy = RetryPolicy {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
            jitter: true,
        };

        // Use a deterministic jitter function for testing
        let delay = policy.calculate_delay_with_jitter(0, || 0.5);
        assert_eq!(delay, Duration::from_millis(150)); // 100 + (100 * 0.5)

        let delay = policy.calculate_delay_with_jitter(1, || 0.25);
        assert_eq!(delay, Duration::from_millis(250)); // 200 + (200 * 0.25)
    }
}