1use crate::FnTask;
2use crate::RetryTask;
3use crate::SleepDuration;
4use crate::Task;
5use ::std::future::Future;
6
7const DEFAULT_NUM_RETRIES: u32 = 3;
8const DEFAULT_SLEEP_DURATION: SleepDuration = SleepDuration::from_millis(10_000);
9
10#[derive(Copy, Clone, Debug)]
11pub struct Retry {
12 num_retries: u32,
13 sleep_duration: SleepDuration,
14}
15
16impl Retry {
17 pub fn new() -> Self {
18 Self {
19 num_retries: DEFAULT_NUM_RETRIES,
20 sleep_duration: DEFAULT_SLEEP_DURATION,
21 }
22 }
23
24 pub fn retries(self) -> u32 {
25 self.num_retries
26 }
27
28 pub fn set_retries(self, num_retries: u32) -> Self {
29 Self {
30 num_retries,
31 ..self
32 }
33 }
34
35 pub fn sleep_duration(self) -> SleepDuration {
36 self.sleep_duration
37 }
38
39 pub fn set_sleep_duration<S>(self, sleep_duration: S) -> Self
40 where
41 S: Into<SleepDuration>,
42 {
43 Self {
44 sleep_duration: sleep_duration.into(),
45 ..self
46 }
47 }
48
49 pub async fn run_fn<'a, T, F, O, E>(self, fn_task: T) -> Result<O, E>
50 where
51 T: FnMut() -> F,
52 F: Future<Output = Result<O, E>>,
53 {
54 let task = FnTask::new(fn_task);
55 self.run(task).await
56 }
57
58 pub async fn run<'a, T, O, E>(self, task: T) -> Result<O, E>
59 where
60 T: Task<Output = Result<O, E>>,
61 {
62 self.build_task(task).call().await
63 }
64
65 pub fn build_task<'a, T, O, E>(self, task: T) -> RetryTask<T>
66 where
67 T: Task<Output = Result<O, E>>,
68 {
69 RetryTask::new(task.into(), self)
70 }
71}