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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository, or online at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Retry utilities.
//!
//! This module provides an API for retrying fallible asynchronous operations
//! until they succeed or until some criteria for giving up has been reached,
//! using exponential backoff between retries.
//!
//! # Examples
//!
//! Retry a contrived fallible operation until it succeeds:
//!
//! ```
//! use std::time::Duration;
//! use mz_ore::retry::Retry;
//!
//! let res = Retry::default().retry(|state| {
//!    if state.i == 3 {
//!        Ok(())
//!    } else {
//!        Err("contrived failure")
//!    }
//! });
//! assert_eq!(res, Ok(()));
//! ```
//!
//! Limit the number of retries such that success is never observed:
//!
//! ```
//! use std::time::Duration;
//! use mz_ore::retry::Retry;
//!
//! let res = Retry::default().max_tries(2).retry(|state| {
//!    if state.i == 3 {
//!        Ok(())
//!    } else {
//!        Err("contrived failure")
//!    }
//! });
//! assert_eq!(res, Err("contrived failure"));
//! ```

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{cmp, thread};

use futures::{ready, Stream, StreamExt};
use pin_project::pin_project;
use tokio::io::{AsyncRead, ReadBuf};
use tokio::time::error::Elapsed;
use tokio::time::{self, Duration, Instant, Sleep};

/// The state of a retry operation constructed with [`Retry`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RetryState {
    /// The retry counter, starting from zero on the first try.
    pub i: usize,
    /// The duration that the retry operation will sleep for before the next
    /// retry if this try fails.
    ///
    /// If this is the last attempt, then this field will be `None`.
    pub next_backoff: Option<Duration>,
}

/// The result of a retryable operation.
#[derive(Debug)]
pub enum RetryResult<T, E> {
    /// The operation was successful and does not need to be retried.
    Ok(T),
    /// The operation was unsuccessful but can be retried.
    RetryableErr(E),
    /// The operation was unsuccessful but cannot be retried.
    FatalErr(E),
}

impl<T, E> From<Result<T, E>> for RetryResult<T, E> {
    fn from(res: Result<T, E>) -> RetryResult<T, E> {
        match res {
            Ok(t) => RetryResult::Ok(t),
            Err(e) => RetryResult::RetryableErr(e),
        }
    }
}

/// Configures a retry operation.
///
/// See the [module documentation](self) for usage examples.
#[pin_project]
#[derive(Debug)]
pub struct Retry {
    initial_backoff: Duration,
    factor: f64,
    clamp_backoff: Duration,
    max_duration: Duration,
    max_tries: usize,
}

impl Retry {
    /// Sets the initial backoff for the retry operation.
    ///
    /// The initial backoff is the amount of time to wait if the first try
    /// fails.
    pub fn initial_backoff(mut self, initial_backoff: Duration) -> Self {
        self.initial_backoff = initial_backoff;
        self
    }

    /// Clamps the maximum backoff for the retry operation.
    ///
    /// The maximum backoff is the maximum amount of time to wait between tries.
    pub fn clamp_backoff(mut self, clamp_backoff: Duration) -> Self {
        self.clamp_backoff = clamp_backoff;
        self
    }

    /// Sets the exponential backoff factor for the retry operation.
    ///
    /// The time to wait is multiplied by this factor after each failed try. The
    /// default factor is two.
    pub fn factor(mut self, factor: f64) -> Self {
        self.factor = factor;
        self
    }

    /// Sets the maximum number of tries.
    ///
    /// If the operation is still failing after `max_tries`, then
    /// [`retry`](Retry::retry) will return the last error.
    ///
    /// Calls to `max_tries` will override any previous calls to `max_tries`.
    ///
    /// # Panics
    ///
    /// Panics if `max_tries` is zero.
    pub fn max_tries(mut self, max_tries: usize) -> Self {
        if max_tries == 0 {
            panic!("max tries must be greater than zero");
        }
        self.max_tries = max_tries;
        self
    }

    /// Sets the maximum duration.
    ///
    /// If the operation is still failing after the specified `duration`, then
    /// the operation will be retried once more and [`retry`](Retry::retry) will
    /// return the last error.
    ///
    /// Calls to `max_duration` will override any previous calls to
    /// `max_duration`.
    pub fn max_duration(mut self, duration: Duration) -> Self {
        self.max_duration = duration;
        self
    }

    /// Retries the fallible operation `f` according to the configured policy.
    ///
    /// The `retry` method invokes `f` repeatedly until it returns either
    /// [`RetryResult::Ok`] or [`RetryResult::FatalErr`], or until the maximum
    /// duration or tries have been reached, as configured via
    /// [`max_duration`](Retry::max_duration) or
    /// [`max_tries`](Retry::max_tries). If the last invocation of `f` returns
    /// `RetryResult::Ok(t)`, then `retry` returns `Ok(t)`. If the last
    /// invocation of `f` returns `RetryResult::RetriableErr(e)` or
    /// `RetryResult::FatalErr(e)`, then `retry` returns `Err(e)`.
    ///
    /// As a convenience, `f` can return any type that is convertible to a
    /// `RetryResult`. The conversion from [`Result`] to `RetryResult` converts
    /// `Err(e)` to `RetryResult::RetryableErr(e)`, that is, it considers all
    /// errors retryable.
    ///
    /// After the first failure, `retry` sleeps for the initial backoff
    /// configured via [`initial_backoff`](Retry::initial_backoff). After each
    /// successive failure, `retry` sleeps for twice the last backoff. If the
    /// backoff would ever exceed the maximum backoff configured viq
    /// [`Retry::clamp_backoff`], then the backoff is clamped to the specified
    /// maximum.
    ///
    /// The operation does not attempt to forcibly time out `f`, even if there
    /// is a maximum duration. If there is the possibility of `f` blocking
    /// forever, consider adding a timeout internally.
    pub fn retry<F, R, T, E>(self, mut f: F) -> Result<T, E>
    where
        F: FnMut(RetryState) -> R,
        R: Into<RetryResult<T, E>>,
    {
        let start = Instant::now();
        let mut i = 0;
        let mut next_backoff = Some(cmp::min(self.initial_backoff, self.clamp_backoff));
        loop {
            let elapsed = start.elapsed();
            if elapsed > self.max_duration || i + 1 >= self.max_tries {
                next_backoff = None;
            } else if elapsed + next_backoff.unwrap() > self.max_duration {
                next_backoff = Some(self.max_duration - elapsed);
            }
            let state = RetryState { i, next_backoff };
            match f(state).into() {
                RetryResult::Ok(t) => return Ok(t),
                RetryResult::FatalErr(e) => return Err(e),
                RetryResult::RetryableErr(e) => match &mut next_backoff {
                    None => return Err(e),
                    Some(next_backoff) => {
                        thread::sleep(*next_backoff);
                        *next_backoff =
                            cmp::min(next_backoff.mul_f64(self.factor), self.clamp_backoff);
                    }
                },
            }
            i += 1;
        }
    }

    /// Like [`Retry::retry`] but for asynchronous operations.
    pub async fn retry_async<F, U, R, T, E>(self, mut f: F) -> Result<T, E>
    where
        F: FnMut(RetryState) -> U,
        U: Future<Output = R>,
        R: Into<RetryResult<T, E>>,
    {
        let stream = self.into_retry_stream();
        tokio::pin!(stream);
        let mut err = None;
        while let Some(state) = stream.next().await {
            match f(state).await.into() {
                RetryResult::Ok(v) => return Ok(v),
                RetryResult::FatalErr(e) => return Err(e),
                RetryResult::RetryableErr(e) => err = Some(e),
            }
        }
        Err(err.expect("retry produces at least one element"))
    }

    /// Like [`Retry::retry_async`] but the operation will be canceled if the
    /// maximum duration is reached.
    ///
    /// Specifically, if the maximum duration is reached, the operation `f` will
    /// be forcibly canceled by dropping it. Canceling `f` can be surprising if
    /// the operation is not programmed to expect the possibility of not
    /// resuming from an `await` point; if you wish to always run `f` to
    /// completion, use [`Retry::retry_async`] instead.
    ///
    /// If `f` is forcibly canceled, the error returned will be the error
    /// returned by the prior invocation of `f`. If there is no prior invocation
    /// of `f`, then an `Elapsed` error is returned. The idea is that if `f`
    /// fails three times in a row with a useful error message, and then the
    /// fourth attempt is canceled because the timeout is reached, the caller
    /// would rather see the useful error message from the third attempt, rather
    /// than the "deadline exceeded" message from the fourth attempt.
    pub async fn retry_async_canceling<F, U, T, E>(self, mut f: F) -> Result<T, E>
    where
        F: FnMut(RetryState) -> U,
        U: Future<Output = Result<T, E>>,
        E: From<Elapsed> + std::fmt::Debug,
    {
        let start = Instant::now();
        let max_duration = self.max_duration;
        let stream = self.into_retry_stream();
        tokio::pin!(stream);
        let mut err = None;
        while let Some(state) = stream.next().await {
            let fut = time::timeout(max_duration.saturating_sub(start.elapsed()), f(state));
            match fut.await {
                Ok(Ok(t)) => return Ok(t),
                Ok(Err(e)) => err = Some(e),
                Err(e) => return Err(err.unwrap_or_else(|| e.into())),
            }
        }
        Err(err.expect("retry produces at least one element"))
    }

    /// Like [`Retry::retry_async`] but can pass around user specified state.
    pub async fn retry_async_with_state<F, S, U, R, T, E>(
        self,
        mut user_state: S,
        mut f: F,
    ) -> (S, Result<T, E>)
    where
        F: FnMut(RetryState, S) -> U,
        U: Future<Output = (S, R)>,
        R: Into<RetryResult<T, E>>,
    {
        let stream = self.into_retry_stream();
        tokio::pin!(stream);
        let mut err = None;
        while let Some(retry_state) = stream.next().await {
            let (s, r) = f(retry_state, user_state).await;
            match r.into() {
                RetryResult::Ok(v) => return (s, Ok(v)),
                RetryResult::FatalErr(e) => return (s, Err(e)),
                RetryResult::RetryableErr(e) => {
                    err = Some(e);
                    user_state = s;
                }
            }
        }
        (
            user_state,
            Err(err.expect("retry produces at least one element")),
        )
    }

    /// Convert into [`RetryStream`]
    pub fn into_retry_stream(self) -> RetryStream {
        RetryStream {
            retry: self,
            start: Instant::now(),
            i: 0,
            next_backoff: None,
            sleep: time::sleep(Duration::default()),
        }
    }
}

impl Default for Retry {
    /// Constructs a retry operation that will retry forever with backoff
    /// defaults that are reasonable for a fallible network operation.
    fn default() -> Self {
        Retry {
            initial_backoff: Duration::from_millis(125),
            factor: 2.0,
            clamp_backoff: Duration::MAX,
            max_tries: usize::MAX,
            max_duration: Duration::MAX,
        }
    }
}

/// Opaque type representing the stream of retries that continues to back off.
#[pin_project]
#[derive(Debug)]
pub struct RetryStream {
    retry: Retry,
    start: Instant,
    i: usize,
    next_backoff: Option<Duration>,
    #[pin]
    sleep: Sleep,
}

impl RetryStream {
    fn reset(self: Pin<&mut Self>) {
        let this = self.project();
        *this.start = Instant::now();
        *this.i = 0;
        *this.next_backoff = None;
    }
}

impl Stream for RetryStream {
    type Item = RetryState;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut this = self.project();
        let retry = this.retry;

        match this.next_backoff {
            None if *this.i == 0 => {
                *this.next_backoff = Some(cmp::min(retry.initial_backoff, retry.clamp_backoff));
            }
            None => return Poll::Ready(None),
            Some(next_backoff) => {
                ready!(this.sleep.as_mut().poll(cx));
                *next_backoff = cmp::min(next_backoff.mul_f64(retry.factor), retry.clamp_backoff);
            }
        }

        let elapsed = this.start.elapsed();
        if elapsed > retry.max_duration || *this.i + 1 >= retry.max_tries {
            *this.next_backoff = None;
        } else if elapsed + this.next_backoff.unwrap() > retry.max_duration {
            *this.next_backoff = Some(retry.max_duration - elapsed);
        }

        let state = RetryState {
            i: *this.i,
            next_backoff: *this.next_backoff,
        };
        if let Some(d) = *this.next_backoff {
            this.sleep.reset(Instant::now() + d);
        }
        *this.i += 1;
        Poll::Ready(Some(state))
    }
}

/// Wrapper of a `Reader` factory that will automatically retry and resume reading an underlying
/// resource in the events of errors according to a retry schedule.
#[pin_project]
#[derive(Debug)]
pub struct RetryReader<F, U, R> {
    factory: F,
    offset: usize,
    error: Option<std::io::Error>,
    #[pin]
    retry: RetryStream,
    #[pin]
    state: RetryReaderState<U, R>,
}

#[pin_project(project = RetryReaderStateProj)]
#[derive(Debug)]
enum RetryReaderState<U, R> {
    Waiting,
    Creating(#[pin] U),
    Reading(#[pin] R),
}

impl<F, U, R> RetryReader<F, U, R>
where
    F: FnMut(RetryState, usize) -> U,
    U: Future<Output = Result<R, std::io::Error>>,
    R: AsyncRead,
{
    /// Uses the provided `Reader` factory to construct a `RetryReader` with the default `Retry`
    /// settings.
    ///
    /// The factory will be called once at the beginning and subsequently every time a retry
    /// attempt is made. The factory will be called with a single `usize` argument representing the
    /// offset at which the returned `Reader` should resume reading from.
    pub fn new(factory: F) -> Self {
        Self::with_retry(factory, Retry::default())
    }

    /// Uses the provided `Reader` factory to construct a `RetryReader` with the passed `Retry`
    /// settings. See the documentation of [RetryReader::new] for more details.
    pub fn with_retry(factory: F, retry: Retry) -> Self {
        Self {
            factory,
            offset: 0,
            error: None,
            retry: retry.into_retry_stream(),
            state: RetryReaderState::Waiting,
        }
    }
}

impl<F, U, R> AsyncRead for RetryReader<F, U, R>
where
    F: FnMut(RetryState, usize) -> U,
    U: Future<Output = Result<R, std::io::Error>>,
    R: AsyncRead,
{
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        loop {
            let mut this = self.as_mut().project();
            use RetryReaderState::*;
            match this.state.as_mut().project() {
                RetryReaderStateProj::Waiting => match ready!(this.retry.as_mut().poll_next(cx)) {
                    None => {
                        return Poll::Ready(Err(this
                            .error
                            .take()
                            .expect("retry produces at least one element")))
                    }
                    Some(state) => {
                        this.state
                            .set(Creating((*this.factory)(state, *this.offset)));
                    }
                },
                RetryReaderStateProj::Creating(reader_fut) => match ready!(reader_fut.poll(cx)) {
                    Ok(reader) => {
                        this.state.set(Reading(reader));
                    }
                    Err(err) => {
                        *this.error = Some(err);
                        this.state.set(Waiting);
                    }
                },
                RetryReaderStateProj::Reading(reader) => {
                    let filled_end = buf.filled().len();
                    match ready!(reader.poll_read(cx, buf)) {
                        Ok(()) => {
                            if let Some(_) = this.error.take() {
                                this.retry.reset();
                            }
                            *this.offset += buf.filled().len() - filled_end;
                            return Poll::Ready(Ok(()));
                        }
                        Err(err) => {
                            *this.error = Some(err);
                            this.state.set(Waiting);
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use anyhow::{anyhow, bail};

    use super::*;

    #[crate::test]
    fn test_retry_success() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .retry(|state| {
                states.push(state);
                if state.i == 2 {
                    Ok(())
                } else {
                    Err::<(), _>("injected")
                }
            });
        assert_eq!(res, Ok(()));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
                RetryState {
                    i: 2,
                    next_backoff: Some(Duration::from_millis(4))
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_success() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .retry_async(|state| {
                states.push(state);
                async move {
                    if state.i == 2 {
                        Ok(())
                    } else {
                        Err::<(), _>("injected")
                    }
                }
            })
            .await;
        assert_eq!(res, Ok(()));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
                RetryState {
                    i: 2,
                    next_backoff: Some(Duration::from_millis(4))
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    async fn test_retry_fatal() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .retry(|state| {
                states.push(state);
                if state.i == 0 {
                    RetryResult::RetryableErr::<(), _>("retry me")
                } else {
                    RetryResult::FatalErr("injected")
                }
            });
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_fatal() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .retry_async(|state| {
                states.push(state);
                async move {
                    if state.i == 0 {
                        RetryResult::RetryableErr::<(), _>("retry me")
                    } else {
                        RetryResult::FatalErr("injected")
                    }
                }
            })
            .await;
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_fail_max_tries() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .max_tries(3)
            .retry(|state| {
                states.push(state);
                Err::<(), _>("injected")
            });
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
                RetryState {
                    i: 2,
                    next_backoff: None
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_fail_max_tries() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .max_tries(3)
            .retry_async(|state| {
                states.push(state);
                async { Err::<(), _>("injected") }
            })
            .await;
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(2))
                },
                RetryState {
                    i: 2,
                    next_backoff: None
                },
            ]
        );
    }

    #[crate::test]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    fn test_retry_fail_max_duration() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(10))
            .max_duration(Duration::from_millis(20))
            .retry(|state| {
                states.push(state);
                Err::<(), _>("injected")
            });
        assert_eq!(res, Err("injected"));

        // The first try should indicate a next backoff of exactly 10ms.
        assert_eq!(
            states[0],
            RetryState {
                i: 0,
                next_backoff: Some(Duration::from_millis(10))
            },
        );

        // The next try should indicate a next backoff of between 0 and 10ms. The
        // exact value depends on how long it took for the first try itself to
        // execute.
        assert_eq!(states[1].i, 1);
        let backoff = states[1].next_backoff.unwrap();
        assert!(backoff > Duration::from_millis(0) && backoff < Duration::from_millis(10));

        // The final try should indicate that the operation is complete with
        // a next backoff of None.
        assert_eq!(
            states[2],
            RetryState {
                i: 2,
                next_backoff: None,
            },
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    #[ignore] // TODO: Reenable when database-issues#7441 is fixed
    async fn test_retry_async_fail_max_duration() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(5))
            .max_duration(Duration::from_millis(10))
            .retry_async(|state| {
                states.push(state);
                async { Err::<(), _>("injected") }
            })
            .await;
        assert_eq!(res, Err("injected"));

        // The first try should indicate a next backoff of exactly 5ms.
        assert_eq!(
            states[0],
            RetryState {
                i: 0,
                next_backoff: Some(Duration::from_millis(5))
            },
        );

        // The next try should indicate a next backoff of between 0 (None) and 5ms. The
        // exact value depends on how long it took for the first try itself to
        // execute.
        assert_eq!(states[1].i, 1);
        assert!(match states[1].next_backoff {
            None => true,
            Some(backoff) =>
                backoff > Duration::from_millis(0) && backoff < Duration::from_millis(5),
        });

        // The final try should indicate that the operation is complete with
        // a next backoff of None.
        assert_eq!(
            states[2],
            RetryState {
                i: 2,
                next_backoff: None,
            },
        );
    }

    #[crate::test]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    fn test_retry_fail_clamp_backoff() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .clamp_backoff(Duration::from_millis(1))
            .max_tries(4)
            .retry(|state| {
                states.push(state);
                Err::<(), _>("injected")
            });
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 2,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 3,
                    next_backoff: None
                },
            ]
        );
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_fail_clamp_backoff() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(1))
            .clamp_backoff(Duration::from_millis(1))
            .max_tries(4)
            .retry_async(|state| {
                states.push(state);
                async { Err::<(), _>("injected") }
            })
            .await;
        assert_eq!(res, Err("injected"));
        assert_eq!(
            states,
            &[
                RetryState {
                    i: 0,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 1,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 2,
                    next_backoff: Some(Duration::from_millis(1))
                },
                RetryState {
                    i: 3,
                    next_backoff: None
                },
            ]
        );
    }

    /// Test that canceling retry operations surface the last error when the
    /// underlying future is not explicitly timed out.
    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_canceling_uncanceled_failure() {
        let res = Retry::default()
            .max_duration(Duration::from_millis(100))
            .retry_async_canceling(|_| async move { Err::<(), _>(anyhow!("injected")) })
            .await;
        assert_eq!(res.unwrap_err().to_string(), "injected");
    }

    /// Test that canceling retry operations surface the last error when the
    /// underlying future *is* not explicitly timed out.
    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_canceling_canceled_failure() {
        let res = Retry::default()
            .max_duration(Duration::from_millis(100))
            .retry_async_canceling(|state| async move {
                if state.i == 0 {
                    bail!("injected")
                } else {
                    time::sleep(Duration::MAX).await;
                    Ok(())
                }
            })
            .await;
        assert_eq!(res.unwrap_err().to_string(), "injected");
    }

    /// Test that the "deadline has elapsed" error is surfaced when there is
    /// no other error to surface.
    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_canceling_canceled_first_failure() {
        let res = Retry::default()
            .max_duration(Duration::from_millis(100))
            .retry_async_canceling(|_| async move {
                time::sleep(Duration::MAX).await;
                Ok::<_, anyhow::Error>(())
            })
            .await;
        assert_eq!(res.unwrap_err().to_string(), "deadline has elapsed");
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_reader() {
        use tokio::io::AsyncReadExt;

        /// Reader that errors out after the first read
        struct FlakyReader {
            offset: usize,
            should_error: bool,
        }

        impl AsyncRead for FlakyReader {
            fn poll_read(
                mut self: Pin<&mut Self>,
                _: &mut Context<'_>,
                buf: &mut ReadBuf<'_>,
            ) -> Poll<Result<(), std::io::Error>> {
                if self.should_error {
                    Poll::Ready(Err(std::io::ErrorKind::ConnectionReset.into()))
                } else if self.offset < 256 {
                    buf.put_slice(&[b'A']);
                    self.should_error = true;
                    Poll::Ready(Ok(()))
                } else {
                    Poll::Ready(Ok(()))
                }
            }
        }

        let reader = RetryReader::new(|_state, offset| async move {
            Ok(FlakyReader {
                offset,
                should_error: false,
            })
        });
        tokio::pin!(reader);

        let mut data = Vec::new();
        reader.read_to_end(&mut data).await.unwrap();
        assert_eq!(data, vec![b'A'; 256]);
    }

    #[crate::test(tokio::test)]
    #[cfg_attr(miri, ignore)] // unsupported operation: cannot write to event
    async fn test_retry_async_state() {
        struct S {
            i: i64,
        }
        impl S {
            #[allow(clippy::unused_async)]
            async fn try_inc(&mut self) -> Result<i64, ()> {
                self.i += 1;
                if self.i > 10 {
                    Ok(self.i)
                } else {
                    Err(())
                }
            }
        }

        let s = S { i: 0 };
        let (_new_s, res) = Retry::default()
            .max_tries(10)
            .clamp_backoff(Duration::from_nanos(0))
            .retry_async_with_state(s, |_, mut s| async {
                let res = s.try_inc().await;
                (s, res)
            })
            .await;
        assert_eq!(res, Err(()));

        let s = S { i: 0 };
        let (_new_s, res) = Retry::default()
            .max_tries(11)
            .clamp_backoff(Duration::from_nanos(0))
            .retry_async_with_state(s, |_, mut s| async {
                let res = s.try_inc().await;
                (s, res)
            })
            .await;
        assert_eq!(res, Ok(11));
    }
}