glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Running work again when it fails: `retry times: 3, wait: 1.seconds()
//! do … end` in `.glacier`, as Laravel's `retry` and Ruby's `retry`.

use chrono::TimeDelta;

use crate::error::Result;
use crate::jobs::Delay;

/// How many times to try, and how long to wait between tries.
#[derive(Debug, Clone, Copy)]
pub struct Retry {
    times: u32,
    wait: TimeDelta,
}

impl Retry {
    /// At most `times` tries in all (at least one).
    pub fn new(times: u32) -> Self {
        Self {
            times: times.max(1),
            wait: TimeDelta::zero(),
        }
    }

    /// Waits this long after the first failure, twice as long after the
    /// second, and so on.
    #[must_use]
    pub fn wait(mut self, wait: impl Delay) -> Self {
        self.wait = wait.delay();
        self
    }

    /// Runs `attempt` until it succeeds or the tries run out, returning
    /// the last error then.
    ///
    /// # Errors
    ///
    /// The last try's error.
    pub async fn run<T>(self, mut attempt: impl AsyncFnMut() -> Result<T>) -> Result<T> {
        let mut tried = 0;
        loop {
            tried += 1;
            match attempt().await {
                Ok(value) => return Ok(value),
                Err(error) if tried < self.times => {
                    tracing::warn!(target: "glacier", "try {tried} of {} failed: {error}", self.times);
                    let wait = self.wait * i32::try_from(tried).unwrap_or(i32::MAX);
                    if let Ok(wait) = wait.to_std() {
                        tokio::time::sleep(wait).await;
                    }
                }
                Err(error) => return Err(error),
            }
        }
    }
}

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

    #[tokio::test]
    async fn tries_until_it_works_or_runs_out() {
        let mut calls = 0;
        let value = Retry::new(3)
            .run(async || {
                calls += 1;
                if calls < 3 {
                    Err(Error::internal("not yet"))
                } else {
                    Ok(calls)
                }
            })
            .await
            .unwrap();
        assert_eq!(value, 3);

        let mut calls = 0;
        let error = Retry::new(2)
            .run(async || -> Result<()> {
                calls += 1;
                Err(Error::internal(format!("failure {calls}")))
            })
            .await
            .unwrap_err();
        assert_eq!(calls, 2);
        assert!(error.to_string().contains("failure 2"), "{error}");
    }
}