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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! # Easy Retry
//!
//! `easy_retry` is a Rust library that provides utilities for retrying operations with different strategies.
//!
//! This library provides several retry strategies, including linear, exponential, and their asynchronous versions. You can choose the strategy that best fits your needs.
//!
//! The library is designed to be simple and easy to use. It provides a single enum, `EasyRetry`, that represents different retry strategies. You can create a new retry strategy by calling one of the `new_*` methods on the `EasyRetry` enum.
//!
//! The library provides a `run` method that takes a closure and runs the operation with the specified retry strategy. The `run` method returns the result of the operation, or an error if the operation fails after all retries.
//!
//! The run method expects the closure to return a `Result` type. The `Ok` variant should contain the result of the operation, and the `Err` variant should contain the error that occurred during the operation.
//!
//! # Features
//!
//! * **Linear Retry**: In this strategy, the delay between retries is constant.
//! * **Exponential Retry**: In this strategy, the delay between retries doubles after each retry.
//! * **Linear Async Retry**: This is an asynchronous version of the linear retry strategy. This feature is only available when the `async` feature is enabled.
//! * **Exponential Async Retry**: This is an asynchronous version of the exponential retry strategy. This feature is only available when the `async` feature is enabled.
//!
//! # Examples
//!
//! ```
//! use easy_retry::EasyRetry;
//!
//! fn my_sync_fn(_n: &str) -> Result<(), std::io::Error> {
//!     Err(std::io::Error::new(std::io::ErrorKind::Other, "generic error"))
//! }
//!
//! // Retry the operation with a linear strategy (1 second delay, 2 retries)
//! let retry_strategy = EasyRetry::new_linear(1, 2);
//! let result = retry_strategy.run(|| my_sync_fn("Hi"));
//! assert!(result.is_err());
//!
//! ```
//!
//! # Asynchronous Example
//!
//! ```rust
//! use easy_retry::EasyRetry;
//!
//! async fn my_async_fn(_n: u64) -> Result<(), std::io::Error> {
//!    Err(std::io::Error::new(std::io::ErrorKind::Other, "generic error"))
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     // Retry the operation with an exponential strategy (1 second delay, 2 retries)
//!     let retry_strategy = EasyRetry::new_exponential_async(1, 2);
//!     let result = retry_strategy.run_async(|| my_async_fn(42)).await;
//!     assert!(result.is_err());
//!
//! }
//! ```
//! # Usage
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! easy_retry = "0.1.0"
//! ```
//!
//! Then, add this to your crate root (`main.rs` or `lib.rs`):
//!
//! ```rust
//! extern crate easy_retry;
//! ```
//!
//! Now, you can use the `EasyRetry` enum to create a retry strategy:
//!
//! ```rust
//! use easy_retry::EasyRetry;
//!
//! let retry_strategy = EasyRetry::new_linear(100, 5);
//! ```
//!
//! # License
//!
//! This project is licensed under the MIT License.

#![deny(missing_docs)]
use std::fmt::Debug;
#[cfg(feature = "async")]
use std::future::Future;
#[derive(Debug, Copy, Clone)]

/// `EasyRetry` is an enum representing different kinds of retry strategies.
pub enum EasyRetry {
    /// Represents a linear retry strategy.
    Linear {
        #[doc(hidden)]
        /// The delay between retries in seconds.
        delay: u64,
        #[doc(hidden)]
        /// The number of retries.
        retries: u64,
    },
    /// Represents an exponential retry strategy.
    Exponential {
        /// The delay between retries in seconds.
        #[doc(hidden)]
        delay: u64,
        /// The number of retries.
        #[doc(hidden)]
        retries: u64,
    },
    /// Represents an asynchronous version of the linear retry strategy.
    ///
    /// This variant is only available when the `async` feature is enabled.
    #[cfg(feature = "async")]
    LinearAsync {
        /// The delay between retries in seconds.
        #[doc(hidden)]
        delay: u64,
        /// The number of retries.
        #[doc(hidden)]
        retries: u64,
    },
    /// Represents an asynchronous version of the exponential retry strategy.
    ///
    /// This variant is only available when the `async` feature is enabled.
    #[cfg(feature = "async")]
    ExponentialAsync {
        /// The delay between retries in seconds.
        #[doc(hidden)]
        delay: u64,
        /// The number of retries.
        #[doc(hidden)]
        retries: u64,
    },
}

impl EasyRetry {
    /// Creates a new `EasyRetry::Linear` variant with the specified delay and number of retries.
    ///
    /// # Arguments
    ///
    /// * `delay` - The delay between retries in seconds.
    /// * `retries` - The number of retries.
    ///
    /// # Examples
    ///
    /// ```
    /// use easy_retry::EasyRetry;
    ///
    /// let retry_strategy = EasyRetry::new_linear(100, 5);
    /// ```
    pub fn new_linear(delay: u64, retries: u64) -> Self {
        EasyRetry::Linear { delay, retries }
    }

    /// Creates a new `EasyRetry::Exponential` variant with the specified initial delay and number of retries.
    ///
    /// # Arguments
    ///
    /// * `delay` - The delay between retries in . The delay doubles after each retry.
    /// * `retries` - The number of retries.
    ///
    /// # Examples
    ///
    /// ```
    /// use easy_retry::EasyRetry;
    ///
    /// let retry_strategy = EasyRetry::new_exponential(100, 5);
    /// ```
    pub fn new_exponential(delay: u64, retries: u64) -> Self {
        EasyRetry::Exponential { delay, retries }
    }

    /// Creates a new `EasyRetry::LinearAsync` variant with the specified delay and number of retries.
    ///
    /// # Arguments
    ///
    /// * `delay` - The delay between retries in seconds.
    /// * `retries` - The number of retries.
    ///
    /// # Examples
    ///
    /// ```
    /// use easy_retry::EasyRetry;
    ///
    /// let retry_strategy = EasyRetry::new_linear_async(100, 5);
    /// ```
    #[cfg(feature = "async")]
    pub fn new_linear_async(delay: u64, retries: u64) -> Self {
        EasyRetry::LinearAsync { delay, retries }
    }

    /// Creates a new `EasyRetry::ExponentialAsync` variant with the specified initial delay and number of retries.
    ///
    /// # Arguments
    ///
    /// * `delay` - The delay between retries in seconds. The delay doubles after each retry.
    /// * `retries` - The number of retries.
    ///
    /// # Examples
    ///
    /// ```
    /// use easy_retry::EasyRetry;
    ///
    /// let retry_strategy = EasyRetry::new_exponential_async(100, 5);
    /// ```
    #[cfg(feature = "async")]
    pub fn new_exponential_async(delay: u64, retries: u64) -> Self {
        EasyRetry::ExponentialAsync { delay, retries }
    }

    /// Runs the provided function `f` with a retry strategy.
    ///
    /// This function takes a function `f` that implements the `SyncReturn` trait and runs it with a retry strategy. The `SyncReturn` trait is implemented for `FnMut` closures, which can mutate their captured variables and can be called multiple times.
    ///
    /// The function `f` should return a `Result` with the operation's result or error. The types of the result and error are determined by the `SyncReturn` trait's associated types `Item` and `Error`.
    ///
    /// # Errors
    ///
    /// Will return an error if the operation fails after all retries.
    pub fn run<T>(&self, f: T) -> Result<<T as SyncReturn>::Item, <T as SyncReturn>::Error>
    where
        T: SyncReturn,
    {
        Retry::run(f, *self)
    }

    /// Runs the provided function `f` with a retry strategy.
    ///
    /// This function takes a function `f` that implements the `AsyncReturn` trait and runs it with a retry strategy. The `AsyncReturn` trait is implemented for `FnMut` closures, which can mutate their captured variables and can be called multiple times. This function is only available when the `async` feature is enabled.
    ///
    /// The function `f` should return a `Result` with the operation's result or error. The types of the result and error are determined by the `SyncReturn` trait's associated types `Item` and `Error`.
    /// # Errors
    ///
    /// Will return an error if the operation fails after all retries.
    #[cfg(feature = "async")]
    pub async fn run_async<'a, T>(
        &'a self,
        f: T,
    ) -> Result<<T as AsyncReturn>::Item, <T as AsyncReturn>::Error>
    where
        T: AsyncReturn + 'a + 'static,
    {
        Retry::run_async(f, *self).await
    }

    fn get_retries(&self) -> u64 {
        match self {
            EasyRetry::Linear { retries, .. } => *retries,
            EasyRetry::Exponential { retries, .. } => *retries,
            #[cfg(feature = "async")]
            EasyRetry::LinearAsync { retries, .. } => *retries,
            #[cfg(feature = "async")]
            EasyRetry::ExponentialAsync { retries, .. } => *retries,
        }
    }

    fn get_delay(&self) -> u64 {
        match self {
            EasyRetry::Linear { delay, .. } => *delay,
            EasyRetry::Exponential { delay, .. } => *delay,
            #[cfg(feature = "async")]
            EasyRetry::LinearAsync { delay, .. } => *delay,
            #[cfg(feature = "async")]
            EasyRetry::ExponentialAsync { delay, .. } => *delay,
        }
    }

    fn linear(x: u64) -> u64 {
        x
    }

    fn exponential(x: u64) -> u64 {
        2u64.pow(x.try_into().unwrap_or_default())
    }

    fn retry_fn(&self) -> fn(u64) -> u64 {
        match self {
            EasyRetry::Linear { .. } => Self::linear,
            EasyRetry::Exponential { .. } => Self::exponential,
            #[cfg(feature = "async")]
            EasyRetry::LinearAsync { .. } => Self::linear,
            #[cfg(feature = "async")]
            EasyRetry::ExponentialAsync { .. } => Self::exponential,
        }
    }
}

fn do_retry<F, T, E>(mut f: F, t: EasyRetry) -> Result<T, E>
where
    F: FnMut() -> Result<T, E>,
{
    let mut retries: u64 = 0;
    loop {
        match f() {
            Ok(v) => return Ok(v),
            Err(e) => {
                if retries >= t.get_retries() {
                    return Err(e);
                }
                retries += 1;
                std::thread::sleep(std::time::Duration::from_secs((t.retry_fn())(
                    t.get_delay(),
                )));
            }
        }
    }
}

#[cfg(feature = "async")]
async fn do_retry_async<F, T, E>(mut f: F, t: EasyRetry) -> Result<T, E>
where
    F: FnMut() -> std::pin::Pin<Box<dyn Future<Output = Result<T, E>>>>,
{
    let mut retries = 0;
    loop {
        match f().await {
            Ok(v) => return Ok(v),
            Err(e) => {
                if retries >= t.get_retries() {
                    return Err(e);
                }
                retries += 1;
                tokio::time::sleep(std::time::Duration::from_secs((t.retry_fn())(
                    t.get_delay(),
                )))
                .await;
            }
        }
    }
}
struct Retry;
impl Retry {
    #[cfg(feature = "async")]
    async fn run_async<T>(
        mut f: T,
        t: EasyRetry,
    ) -> Result<<T as AsyncReturn>::Item, <T as AsyncReturn>::Error>
    where
        T: AsyncReturn + 'static,
    {
        do_retry_async(move || Box::pin(f.run()), t).await
    }

    fn run<T>(mut f: T, t: EasyRetry) -> Result<<T as SyncReturn>::Item, <T as SyncReturn>::Error>
    where
        T: SyncReturn,
    {
        do_retry(move || f.run(), t)
    }
}
/// The `AsyncReturn` trait is used for operations that need to return a value asynchronously.
///
/// This trait provides a single method, `run`, which takes no arguments and returns a `Future` that resolves to a `Result` with the operation's result or error. Both the result and error types must implement the `Debug` trait.
///
/// This trait is only available when the `async` feature is enabled.
///
/// # Associated Types
///
/// * `Item`: The type of the value returned by the `run` method. This type must implement the `Debug` trait.
/// * `Error`: The type of the error returned by the `run` method. This type must also implement the `Debug` trait.
/// * `Future`: The type of the `Future` returned by the `run` method. This `Future` should resolve to a `Result<Item, Error>`.
///
/// # Methods
///
/// * `run`: Performs the operation and returns a `Future` that resolves to the result.
///
/// # Examples
///
/// ```
/// use easy_retry::AsyncReturn;
/// use std::fmt::Debug;
/// use futures::future::ready;
///
/// struct MyOperation;
///
/// impl AsyncReturn for MyOperation {
///     type Item = i32;
///     type Error = &'static str;
///     type Future = futures::future::Ready<Result<Self::Item, Self::Error>>;
///
///     fn run(&mut self) -> Self::Future {
///         // Perform the operation and return the result...
///         ready(Ok(42))
///     }
/// }
///
/// let mut operation = MyOperation;
/// let future = operation.run();
/// ```
#[cfg(feature = "async")]
pub trait AsyncReturn {
    /// The type of the value returned by the `run` method.
    type Item: Debug;
    /// The type of the error returned by the `run` method.
    type Error: Debug;
    /// The type of the `Future` returned by the `run` method.
    type Future: Future<Output = Result<Self::Item, Self::Error>>;

    /// Performs the operation and returns a `Future` that resolves to the result.
    fn run(&mut self) -> Self::Future;
}

#[cfg(feature = "async")]
impl<I: Debug, E: Debug, T: Future<Output = Result<I, E>>, F: FnMut() -> T> AsyncReturn for F {
    type Item = I;
    type Error = E;
    type Future = T;
    fn run(&mut self) -> Self::Future {
        self()
    }
}

/// The `SyncReturn` trait is used for operations that need to return a value synchronously.
///
/// This trait provides a single method, `run`, which takes no arguments and returns a `Result` with the operation's result or error. Both the result and error types must implement the `Debug` trait.
///
/// # Type Parameters
///
/// * `Item`: The type of the value returned by the `run` method. This type must implement the `Debug` trait.
/// * `Error`: The type of the error returned by the `run` method. This type must also implement the `Debug` trait.
///
/// # Methods
///
/// * `run`: Performs the operation and returns the result.
///
/// # Errors
///
/// If the operation fails, this method returns `Err` containing the error. The type of the error is defined by the `Error` associated type.
///
/// # Examples
///
/// ```
/// use easy_retry::SyncReturn;
/// use std::fmt::Debug;
///
/// struct MyOperation;
///
/// impl SyncReturn for MyOperation {
///     type Item = i32;
///     type Error = &'static str;
///
///     fn run(&mut self) -> Result<Self::Item, Self::Error> {
///         // Perform the operation and return the result...
///         Ok(42)
///     }
/// }
///
/// let mut operation = MyOperation;
/// assert_eq!(operation.run(), Ok(42));
/// ```
pub trait SyncReturn {
    /// The type of the value returned by the `run` method.
    type Item: Debug;
    /// The type of the error returned by the `run` method.
    type Error: Debug;

    /// Performs the operation and returns the result.
    fn run(&mut self) -> Result<Self::Item, Self::Error>;
}

impl<I: Debug, E: Debug, F: FnMut() -> Result<I, E>> SyncReturn for F {
    type Item = I;
    type Error = E;
    fn run(&mut self) -> Result<Self::Item, Self::Error> {
        self()
    }
}

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

    #[derive(Debug, Clone)]
    struct NotCopy {
        pub _n: usize,
    }

    fn to_retry_not_copy(n: &NotCopy) -> Result<(), std::io::Error> {
        let _r = n.clone();

        Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            "generic error",
        ))
    }

    fn to_retry(_n: usize) -> Result<(), std::io::Error> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            "generic error",
        ))
    }

    #[cfg(feature = "async")]
    async fn to_retry_async(n: usize) -> Result<(), std::io::Error> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            "generic error",
        ))
    }

    #[test]
    fn test_linear() {
        let retries = 2;
        let delay = 1;
        let instant = std::time::Instant::now();
        let s = EasyRetry::Linear { retries, delay }.run(|| to_retry(1));
        assert!(s.is_err());
        let elapsed = instant.elapsed();
        assert!(elapsed.as_secs() >= retries * delay);
    }

    #[test]
    fn test_expontential() {
        let retries = 2;
        let delay = 1;
        let instant = std::time::Instant::now();
        let s = EasyRetry::Exponential { retries, delay }.run(|| to_retry(1));
        assert!(s.is_err());
        let elapsed = instant.elapsed();
        assert!(elapsed.as_secs() >= retries * delay);
    }

    #[test]
    fn test_not_copy() {
        let retries = 2;
        let delay = 1;
        let not_copy = NotCopy { _n: 1 };
        let instant = std::time::Instant::now();

        let s = EasyRetry::Linear { retries, delay }.run(|| to_retry_not_copy(&not_copy));
        assert!(s.is_err());
        let elapsed = instant.elapsed();
        assert!(elapsed.as_secs() >= retries * delay);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_linear_async() {
        let retries = 2;
        let delay = 1;
        let instant = std::time::Instant::now();
        let s = EasyRetry::LinearAsync { retries, delay }
            .run_async(|| to_retry_async(1))
            .await;
        assert!(s.is_err());
        let elapsed = instant.elapsed();
        assert!(elapsed.as_secs() >= retries * delay);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_expontential_async() {
        let retries = 2;
        let delay = 1;
        let instant = std::time::Instant::now();
        let s = EasyRetry::ExponentialAsync { retries, delay }
            .run_async(|| to_retry_async(1))
            .await;
        assert!(s.is_err());
        let elapsed = instant.elapsed();
        assert!(elapsed.as_secs() >= retries * delay);
    }
}