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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
//! Easily retry futures.
//!
//! ## Example usage
//!
//! ```
//! // some async function that can fail
//! async fn read_file(path: &str) -> Result<String, std::io::Error> {
//!     // ...
//!     # Ok("tryhard".to_string())
//! }
//!
//! # futures::executor::block_on(async_try_main()).unwrap();
//! #
//! # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
//! let contents = tryhard::retry_fn(|| read_file("Cargo.toml"))
//!     // retry at most 10 times
//!     .retries(10)
//!     .await?;
//!
//! assert!(contents.contains("tryhard"));
//! # Ok(())
//! # }
//! ```
//!
//! You can also customize which backoff strategy to use and what the max retry delay should be:
//!
//! ```
//! use std::time::Duration;
//!
//! # async fn read_file(path: &str) -> Result<String, std::io::Error> {
//! #     Ok("tryhard".to_string())
//! # }
//! # futures::executor::block_on(async_try_main()).unwrap();
//! #
//! # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
//! let contents = tryhard::retry_fn(|| read_file("Cargo.toml"))
//!     .retries(10)
//!     .exponential_backoff(Duration::from_millis(10))
//!     .max_delay(Duration::from_secs(1))
//!     .await?;
//!
//! assert!(contents.contains("tryhard"));
//! # Ok(())
//! # }
//! ```
//!
//! You can also customize which backoff strategy to use and what the max retry delay should be:
//!
//! ```
//! use std::time::Duration;
//!
//! # async fn read_file(path: &str) -> Result<String, std::io::Error> {
//! #     Ok("tryhard".to_string())
//! # }
//! # futures::executor::block_on(async_try_main()).unwrap();
//! #
//! # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
//! let contents = tryhard::retry_fn(|| read_file("Cargo.toml"))
//!     .retries(10)
//!     .exponential_backoff(Duration::from_millis(10))
//!     .max_delay(Duration::from_secs(1))
//!     .await?;
//!
//! assert!(contents.contains("tryhard"));
//! # Ok(())
//! # }
//! ```
//!
//! ## Retrying several futures in the same way
//!
//! Using [`RetryFutureConfig`] you're able to retry several futures in the same way:
//!
//! ```
//! # use std::time::Duration;
//! # async fn read_file(path: &str) -> Result<String, std::io::Error> {
//! #     Ok("tryhard".to_string())
//! # }
//! #
//! # futures::executor::block_on(async_try_main()).unwrap();
//! #
//! # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
//! use tryhard::RetryFutureConfig;
//!
//! let config = RetryFutureConfig::new(10)
//!     .exponential_backoff(Duration::from_millis(10))
//!     .max_delay(Duration::from_secs(3));
//!
//! tryhard::retry_fn(|| read_file("Cargo.toml"))
//!     .with_config(config)
//!     .await?;
//!
//! // retry another future in the same way
//! tryhard::retry_fn(|| read_file("src/lib.rs"))
//!     .with_config(config)
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## How many times will my future run?
//!
//! The future is always run at least once, so if you do `.retries(0)` your future will run once.
//! If you do `.retries(10)` and your future always fails it'll run 11 times.
//!
//! ## Why do you require a closure?
//!
//! Due to how futures work in Rust you're not able to retry a bare `F where F: Future`. A future
//! can possibly fail at any point in its execution and might be in an inconsistent state after the
//! failing. Therefore retrying requires making a fresh future for each attempt.
//!
//! This means you cannot move values into the closure that produces the futures. You'll have to
//! clone instead:
//!
//! ```
//! async fn future_with_owned_data(data: Vec<u8>) -> Result<(), std::io::Error> {
//!     // ...
//!     # Ok(())
//! }
//!
//! # futures::executor::block_on(async_try_main()).unwrap();
//! #
//! # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
//! let data: Vec<u8> = vec![1, 2, 3];
//!
//! tryhard::retry_fn(|| {
//!     // We need to clone `data` here. Otherwise we would have to move `data` into the closure.
//!     // `move` closures can only be called once (they only implement `FnOnce`)
//!     // and therefore cannot be used to create more than one future.
//!     let data = data.clone();
//!
//!     async {
//!         future_with_owned_data(data).await
//!     }
//! }).retries(10).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Be careful what you retry
//!
//! This library is meant to make it straight forward to retry simple futures, such as sending a
//! single request to some service that occationally fails. If you have some complex operation that
//! consists of multiple futures each of which can fail, this library might be not appropriate. You
//! risk repeating the same operation more than once because some later operation keeps failing.
//!
//! ## Tokio only for now
//!
//! This library currently expects to be used from within a [tokio](https://tokio.rs) runtime. That
//! is because it makes use of async timers. Feel free to open an issue if you need support for
//! other runtimes.
//!
//! By default it uses Tokio 1.0. You can switch to Tokio 0.2 by disabling default features and
//! enabling the `tokio-02` feature:
//!
//! ```toml
//! tryhard = { version = "your-version", default-features = false, features = ["tokio-02"] }
//! ```
//!
//! Note that enabling both Tokio 1.0 and 0.2 will cause a compilation error.
//!
//! Tokio 0.3 is not supported.
//!
//! [`RetryFuture`]: struct.RetryFuture.html

#![warn(missing_docs)]
#![forbid(unsafe_code)]

use backoff_strategies::{
    BackoffStrategy, CustomBackoffStrategy, ExponentialBackoff, FixedBackoff, LinearBackoff,
    NoBackoff,
};
use futures::future::Ready;
use futures::ready;
use pin_project::pin_project;
use std::{convert::Infallible, time::Duration};
use std::{
    fmt,
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

#[cfg(all(feature = "tokio-02", feature = "tokio-1"))]
compile_error!("Cannot enable both tokio-02 and tokio-1 features");

#[cfg(feature = "tokio-1")]
use tokio_1 as tokio;

#[cfg(feature = "tokio-02")]
use tokio_02 as tokio;

pub mod backoff_strategies;

/// Create a `RetryFn` which produces retryable futures.
pub fn retry_fn<F>(f: F) -> RetryFn<F> {
    RetryFn { f }
}

/// A type that produces retryable futures.
#[derive(Debug)]
pub struct RetryFn<F> {
    f: F,
}

impl<F, Fut, T, E> RetryFn<F>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>>,
{
    /// Specify the number of times to retry the future.
    pub fn retries(self, max_retries: u32) -> RetryFuture<F, Fut, NoBackoff, NoOnRetry> {
        self.with_config(RetryFutureConfig::new(max_retries))
    }

    /// Create a retryable future from the given configuration.
    pub fn with_config<BackoffT, OnRetryT>(
        self,
        config: RetryFutureConfig<BackoffT, OnRetryT>,
    ) -> RetryFuture<F, Fut, BackoffT, OnRetryT> {
        RetryFuture {
            make_future: self.f,
            attempts_remaining: config.max_retries,
            state: RetryState::NotStarted,
            attempt: 0,
            config,
        }
    }
}

/// A retryable future.
///
/// Can be created by calling [`retry_fn`](fn.retry_fn.html).
#[pin_project]
pub struct RetryFuture<MakeFutureT, FutureT, BackoffT, OnRetryT> {
    make_future: MakeFutureT,
    attempts_remaining: u32,
    #[pin]
    state: RetryState<FutureT>,
    attempt: u32,
    config: RetryFutureConfig<BackoffT, OnRetryT>,
}

impl<MakeFutureT, FutureT, BackoffT, T, E, OnRetryT>
    RetryFuture<MakeFutureT, FutureT, BackoffT, OnRetryT>
where
    MakeFutureT: FnMut() -> FutureT,
    FutureT: Future<Output = Result<T, E>>,
{
    /// Set the max duration to sleep between each attempt.
    #[inline]
    pub fn max_delay(mut self, delay: Duration) -> Self {
        self.config = self.config.max_delay(delay);
        self
    }

    /// Remove the backoff strategy.
    ///
    /// This will make the future be retried immediately without any delay in between attempts.
    #[inline]
    pub fn no_backoff(self) -> RetryFuture<MakeFutureT, FutureT, NoBackoff, OnRetryT> {
        self.with_backoff(NoBackoff)
    }

    /// Use exponential backoff for retrying the future.
    ///
    /// The first delay will be `initial_delay` and afterwards the delay will double every time.
    #[inline]
    pub fn exponential_backoff(
        self,
        initial_delay: Duration,
    ) -> RetryFuture<MakeFutureT, FutureT, ExponentialBackoff, OnRetryT> {
        self.with_backoff(ExponentialBackoff {
            delay: initial_delay,
        })
    }

    /// Use a fixed backoff for retrying the future.
    ///
    /// The delay between attempts will always be `delay`.
    #[inline]
    pub fn fixed_backoff(
        self,
        delay: Duration,
    ) -> RetryFuture<MakeFutureT, FutureT, FixedBackoff, OnRetryT> {
        self.with_backoff(FixedBackoff { delay })
    }

    /// Use a linear backoff for retrying the future.
    ///
    /// The delay will be `delay * attempt` so it'll scale linear with the attempt.
    #[inline]
    pub fn linear_backoff(
        self,
        delay: Duration,
    ) -> RetryFuture<MakeFutureT, FutureT, LinearBackoff, OnRetryT> {
        self.with_backoff(LinearBackoff { delay })
    }

    /// Use a custom backoff specified by some function.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// # async fn read_file(path: &str) -> Result<String, std::io::Error> {
    /// #     todo!()
    /// # }
    /// #
    /// # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
    /// tryhard::retry_fn(|| read_file("Cargo.toml"))
    ///     .retries(10)
    ///     .custom_backoff(|attempt, _error| {
    ///         if attempt < 5 {
    ///             Duration::from_millis(100)
    ///         } else {
    ///             Duration::from_millis(500)
    ///         }
    ///     })
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// You can also stop retrying early:
    ///
    /// ```
    /// use std::time::Duration;
    /// use tryhard::RetryPolicy;
    ///
    /// # async fn read_file(path: &str) -> Result<String, std::io::Error> {
    /// #     todo!()
    /// # }
    /// #
    /// # async fn async_try_main() -> Result<(), Box<dyn std::error::Error>> {
    /// tryhard::retry_fn(|| read_file("Cargo.toml"))
    ///     .retries(10)
    ///     .custom_backoff(|attempt, error| {
    ///         if error.to_string().contains("foobar") {
    ///             // returning this will cancel the loop and
    ///             // return the most recent error
    ///             RetryPolicy::Break
    ///         } else {
    ///             RetryPolicy::Delay(Duration::from_millis(50))
    ///         }
    ///     })
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn custom_backoff<F, R>(
        self,
        f: F,
    ) -> RetryFuture<MakeFutureT, FutureT, CustomBackoffStrategy<F>, OnRetryT>
    where
        F: FnMut(u32, &E) -> R,
        R: Into<RetryPolicy>,
    {
        self.with_backoff(CustomBackoffStrategy { f })
    }

    /// Some async computation that will be spawned before each retry.
    ///
    /// This can for example be used for telemtry such as logging or other kinds of tracking.
    ///
    /// The future returned will be given to `tokio::spawn` so wont impact the actual retrying.
    ///
    /// ## Example
    ///
    /// For example to print and gather all the errors you can do:
    ///
    /// ```
    /// use std::sync::Arc;
    /// #[cfg(feature = "tokio-1")]
    /// use tokio_1 as tokio;
    /// #[cfg(feature = "tokio-02")]
    /// use tokio_02 as tokio;
    /// use tokio::sync::Mutex;
    ///
    /// # #[cfg_attr(feature = "tokio-1", tokio::main(flavor = "current_thread"))]
    /// # #[cfg_attr(feature = "tokio-02", tokio::main)]
    /// # async fn main() {
    /// let all_errors = Arc::new(Mutex::new(Vec::new()));
    ///
    /// tryhard::retry_fn(|| async {
    ///     // just some dummy computation that always fails
    ///     Err::<(), _>("fail")
    /// })
    ///     .retries(10)
    ///     .on_retry(|_attempt, _next_delay, error| {
    ///         // the future must be `'static` so it cannot contain references
    ///         let all_errors = Arc::clone(&all_errors);
    ///         let error = error.clone();
    ///         async move {
    ///             eprintln!("Something failed: {}", error);
    ///             all_errors.lock().await.push(error);
    ///         }
    ///     })
    ///     .await
    ///     .unwrap_err();
    ///
    /// assert_eq!(all_errors.lock().await.len(), 10);
    /// # }
    /// ```
    #[inline]
    pub fn on_retry<F, OnRetryFuture>(self, f: F) -> RetryFuture<MakeFutureT, FutureT, BackoffT, F>
    where
        F: FnMut(u32, Option<Duration>, &E) -> OnRetryFuture,
        OnRetryFuture: Future + Send + 'static,
        OnRetryFuture::Output: Send + 'static,
    {
        RetryFuture {
            make_future: self.make_future,
            attempts_remaining: self.attempts_remaining,
            state: self.state,
            attempt: self.attempt,
            config: self.config.on_retry(f),
        }
    }

    #[inline]
    fn with_backoff<BackoffT2>(
        self,
        backoff_strategy: BackoffT2,
    ) -> RetryFuture<MakeFutureT, FutureT, BackoffT2, OnRetryT> {
        RetryFuture {
            make_future: self.make_future,
            attempts_remaining: self.attempts_remaining,
            state: self.state,
            attempt: self.attempt,
            config: self.config.with_backoff(backoff_strategy),
        }
    }
}

/// Configuration describing how to retry a future.
///
/// This is useful if you have many futures you want to retry in the same way.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct RetryFutureConfig<BackoffT, OnRetryT> {
    backoff_strategy: BackoffT,
    max_delay: Option<Duration>,
    on_retry: Option<OnRetryT>,
    max_retries: u32,
}

impl RetryFutureConfig<NoBackoff, NoOnRetry> {
    /// Create a new configuration with a max number of retries and no backoff strategy.
    pub fn new(max_retries: u32) -> Self {
        Self {
            backoff_strategy: NoBackoff,
            max_delay: None,
            on_retry: None::<NoOnRetry>,
            max_retries,
        }
    }
}

impl<BackoffT, OnRetryT> RetryFutureConfig<BackoffT, OnRetryT> {
    /// Set the max duration to sleep between each attempt.
    #[inline]
    pub fn max_delay(mut self, delay: Duration) -> Self {
        self.max_delay = Some(delay);
        self
    }

    /// Remove the backoff strategy.
    ///
    /// This will make the future be retried immediately without any delay in between attempts.
    #[inline]
    pub fn no_backoff(self) -> RetryFutureConfig<NoBackoff, OnRetryT> {
        self.with_backoff(NoBackoff)
    }

    /// Use exponential backoff for retrying the future.
    ///
    /// The first delay will be `initial_delay` and afterwards the delay will double every time.
    #[inline]
    pub fn exponential_backoff(
        self,
        initial_delay: Duration,
    ) -> RetryFutureConfig<ExponentialBackoff, OnRetryT> {
        self.with_backoff(ExponentialBackoff {
            delay: initial_delay,
        })
    }

    /// Use a fixed backoff for retrying the future.
    ///
    /// The delay between attempts will always be `delay`.
    #[inline]
    pub fn fixed_backoff(self, delay: Duration) -> RetryFutureConfig<FixedBackoff, OnRetryT> {
        self.with_backoff(FixedBackoff { delay })
    }

    /// Use a linear backoff for retrying the future.
    ///
    /// The delay will be `delay * attempt` so it'll scale linear with the attempt.
    #[inline]
    pub fn linear_backoff(self, delay: Duration) -> RetryFutureConfig<LinearBackoff, OnRetryT> {
        self.with_backoff(LinearBackoff { delay })
    }

    /// Use a custom backoff specified by some function.
    ///
    /// See [`RetryFuture::custom_backoff`] for more details.
    #[inline]
    pub fn custom_backoff<F, R, E>(
        self,
        f: F,
    ) -> RetryFutureConfig<CustomBackoffStrategy<F>, OnRetryT>
    where
        F: FnMut(u32, &E) -> R,
        R: Into<RetryPolicy>,
    {
        self.with_backoff(CustomBackoffStrategy { f })
    }

    /// Some async computation that will be spawned before each retry.
    ///
    /// See [`RetryFuture::on_retry`] for more details.
    #[inline]
    pub fn on_retry<F, OnRetryFuture, E>(self, f: F) -> RetryFutureConfig<BackoffT, F>
    where
        F: FnMut(u32, Option<Duration>, &E) -> OnRetryFuture,
        OnRetryFuture: Future + Send + 'static,
        OnRetryFuture::Output: Send + 'static,
    {
        RetryFutureConfig {
            backoff_strategy: self.backoff_strategy,
            max_delay: self.max_delay,
            max_retries: self.max_retries,
            on_retry: Some(f),
        }
    }

    #[inline]
    fn with_backoff<BackoffT2>(
        self,
        backoff_strategy: BackoffT2,
    ) -> RetryFutureConfig<BackoffT2, OnRetryT> {
        RetryFutureConfig {
            backoff_strategy,
            max_delay: self.max_delay,
            max_retries: self.max_retries,
            on_retry: self.on_retry,
        }
    }
}

impl<BackoffT, OnRetryT> fmt::Debug for RetryFutureConfig<BackoffT, OnRetryT>
where
    BackoffT: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RetryFutureConfig")
            .field("backoff_strategy", &self.backoff_strategy)
            .field("max_delay", &self.max_delay)
            .field("max_retries", &self.max_retries)
            .field(
                "on_retry",
                &format_args!("<{}>", std::any::type_name::<OnRetryT>()),
            )
            .finish()
    }
}

#[allow(clippy::large_enum_variant)]
#[pin_project(project = RetryStateProj)]
enum RetryState<F> {
    NotStarted,
    WaitingForFuture(#[pin] F),

    #[cfg(feature = "tokio-1")]
    TimerActive(#[pin] tokio::time::Sleep),

    #[cfg(feature = "tokio-02")]
    TimerActive(#[pin] tokio::time::Delay),
}

impl<F, Fut, B, T, E, OnRetryT> Future for RetryFuture<F, Fut, B, OnRetryT>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>>,
    E: fmt::Display,
    B: BackoffStrategy<E>,
    B::Output: Into<RetryPolicy>,
    OnRetryT: OnRetry<E>,
{
    type Output = Result<T, E>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            let this = self.as_mut().project();

            let new_state = match this.state.project() {
                RetryStateProj::NotStarted => RetryState::WaitingForFuture((this.make_future)()),

                RetryStateProj::TimerActive(delay) => {
                    ready!(delay.poll(cx));
                    RetryState::WaitingForFuture((this.make_future)())
                }

                RetryStateProj::WaitingForFuture(fut) => match ready!(fut.poll(cx)) {
                    Ok(value) => {
                        return Poll::Ready(Ok(value));
                    }
                    Err(error) => {
                        if *this.attempts_remaining == 0 {
                            if let Some(on_retry) = &mut this.config.on_retry {
                                tokio::spawn(on_retry.on_retry(*this.attempt, None, &error));
                            }

                            return Poll::Ready(Err(error));
                        } else {
                            *this.attempt += 1;
                            *this.attempts_remaining -= 1;

                            let delay: RetryPolicy = this
                                .config
                                .backoff_strategy
                                .delay(*this.attempt, &error)
                                .into();
                            let mut delay_duration = match delay {
                                RetryPolicy::Delay(duration) => duration,
                                RetryPolicy::Break => {
                                    if let Some(on_retry) = &mut this.config.on_retry {
                                        tokio::spawn(on_retry.on_retry(
                                            *this.attempt,
                                            None,
                                            &error,
                                        ));
                                    }

                                    return Poll::Ready(Err(error));
                                }
                            };

                            if let Some(max_delay) = this.config.max_delay {
                                delay_duration = delay_duration.min(max_delay);
                            }

                            if let Some(on_retry) = &mut this.config.on_retry {
                                tokio::spawn(on_retry.on_retry(
                                    *this.attempt,
                                    Some(delay_duration),
                                    &error,
                                ));
                            }

                            #[cfg(feature = "tokio-1")]
                            let delay = tokio::time::sleep(delay_duration);

                            #[cfg(feature = "tokio-02")]
                            let delay = tokio::time::delay_for(delay_duration);

                            RetryState::TimerActive(delay)
                        }
                    }
                },
            };

            self.as_mut().project().state.set(new_state);
        }
    }
}

/// What to do when a future returns an error. Used with [`RetryFuture::custom`].
///
/// [`RetryFuture::custom`]: struct.RetryFuture.html#method.custom_backoff
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum RetryPolicy {
    /// Try again in the specified `Duration`.
    Delay(Duration),

    /// Don't retry.
    Break,
}

impl From<Duration> for RetryPolicy {
    fn from(duration: Duration) -> Self {
        RetryPolicy::Delay(duration)
    }
}

/// Trait allowing you to run some future when a retry occurs. Could for example to be used for
/// logging or other kinds of telemetry.
///
/// You wont have to implement this trait manually. It is implemented for functions with the right
/// signature. See [`RetryFuture::on_retry`](struct.RetryFuture.html#method.on_retry) for more details.
pub trait OnRetry<E> {
    /// The type of the future you want to run.
    type Future: 'static + Future<Output = Self::Output> + Send;

    /// The output type of your future.
    type Output: 'static + Send;

    /// Create another future to run.
    ///
    /// If `next_delay` is `None` then your future is out of retries and wont be called again.
    fn on_retry(
        &mut self,
        attempt: u32,
        next_delay: Option<Duration>,
        previous_error: &E,
    ) -> Self::Future;
}

/// A sentinel value that represents doing nothing in between retries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NoOnRetry {
    _cannot_exist: Infallible,
}

impl<E> OnRetry<E> for NoOnRetry {
    type Future = Ready<Infallible>;
    type Output = Infallible;

    #[inline]
    fn on_retry(&mut self, _: u32, _: Option<Duration>, _: &E) -> Self::Future {
        // this is safe because `NoOnRetry` contains an `Infallible` so it cannot be created
        unreachable!()
    }
}

impl<F, E, FutureT> OnRetry<E> for F
where
    F: FnMut(u32, Option<Duration>, &E) -> FutureT,
    FutureT: Future + Send + 'static,
    FutureT::Output: Send + 'static,
{
    type Output = FutureT::Output;
    type Future = FutureT;

    #[inline]
    fn on_retry(
        &mut self,
        attempts: u32,
        next_delay: Option<Duration>,
        previous_error: &E,
    ) -> Self::Future {
        self(attempts, next_delay, previous_error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::{convert::Infallible, time::Instant};

    #[tokio::test]
    async fn succeed() {
        retry_fn(|| async { Ok::<_, Infallible>(true) })
            .retries(10)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn retrying_correct_amount_of_times() {
        let counter = AtomicUsize::new(0);

        let err = retry_fn(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Err::<Infallible, _>("error")
        })
        .retries(10)
        .await
        .unwrap_err();

        assert_eq!(err, "error");
        assert_eq!(counter.load(Ordering::Relaxed), 11);
    }

    #[tokio::test]
    async fn retry_0_times() {
        let counter = AtomicUsize::new(0);

        retry_fn(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Err::<Infallible, _>("error")
        })
        .retries(0)
        .await
        .unwrap_err();

        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn the_backoff_strategy_gets_used() {
        async fn make_future() -> Result<Infallible, &'static str> {
            Err("foo")
        }

        let start = Instant::now();
        retry_fn(make_future)
            .retries(10)
            .no_backoff()
            .await
            .unwrap_err();
        let time_with_none = start.elapsed();

        let start = Instant::now();
        retry_fn(make_future)
            .retries(10)
            .fixed_backoff(Duration::from_millis(10))
            .await
            .unwrap_err();
        let time_with_fixed = start.elapsed();

        // assertions about what the exact times are are very finicky so lets just assert that the
        // one without backoff is slower.
        assert!(time_with_fixed > time_with_none);
    }

    // `RetryFuture` must be `Send` to be used with `async_trait`
    // Generally we also want our futures to be `Send`
    #[test]
    fn is_send() {
        fn assert_send<T: Send>(_: T) {}
        async fn some_future() -> Result<(), Infallible> {
            Ok(())
        }
        assert_send(retry_fn(some_future).retries(10));
    }

    #[tokio::test]
    async fn stop_retrying() {
        let mut n = 0;
        let make_future = || {
            n += 1;
            if n == 8 {
                panic!("retried too many times");
            }
            async { Err::<Infallible, _>("foo") }
        };

        let error = retry_fn(make_future)
            .retries(10)
            .custom_backoff(|n, _| {
                if n >= 3 {
                    RetryPolicy::Break
                } else {
                    RetryPolicy::Delay(Duration::from_nanos(10))
                }
            })
            .await
            .unwrap_err();

        assert_eq!(error, "foo");
    }

    #[tokio::test]
    async fn custom_returning_duration() {
        retry_fn(|| async { Ok::<_, Infallible>(true) })
            .retries(10)
            .custom_backoff(|_, _| Duration::from_nanos(10))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn retry_hook_succeed() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        let errors = Arc::new(Mutex::new(Vec::new()));

        retry_fn(|| async { Err::<Infallible, String>("error".to_string()) })
            .retries(10)
            .on_retry(|attempt, next_delay, error| {
                let errors = Arc::clone(&errors);
                let error = error.clone();
                async move {
                    errors.lock().await.push((attempt, next_delay, error));
                }
            })
            .await
            .unwrap_err();

        let errors = errors.lock().await;
        assert_eq!(errors.len(), 10);
        for n in 1_u32..=10 {
            assert_eq!(
                &errors[(n - 1) as usize],
                &(n, Some(Duration::new(0, 0)), "error".to_string())
            );
        }
    }

    #[tokio::test]
    async fn reusing_the_config() {
        let counter = Arc::new(AtomicUsize::new(0));

        let config = RetryFutureConfig::new(10)
            .max_delay(Duration::from_secs(1))
            .linear_backoff(Duration::from_millis(10))
            .on_retry(|_, _, _| {
                let counter = Arc::clone(&counter);
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            });

        let ok_value = retry_fn(|| async { Ok::<_, &str>(true) })
            .with_config(config)
            .await
            .unwrap();
        assert!(ok_value);
        assert_eq!(counter.load(Ordering::SeqCst), 0);

        let err_value = retry_fn(|| async { Err::<(), _>("foo") })
            .with_config(config)
            .await
            .unwrap_err();
        assert_eq!(err_value, "foo");
        assert_eq!(counter.load(Ordering::SeqCst), 10);
    }
}