1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! 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}");
}
}