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
// 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 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 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::cmp;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::thread;

use futures::{ready, Stream, StreamExt};
use pin_project::pin_project;
use tokio::io::{AsyncRead, ReadBuf};
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>,
}

/// 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,
    limit: RetryLimit,
}

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.
    ///
    /// Maximum durations and maximum tries are mutually exclusive within a
    /// given `Retry` operation. Calls to `max_tries` will override any
    /// previous calls to `max_tries` or [`max_duration`](Retry::max_duration).
    ////
    /// # 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.limit = RetryLimit::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.
    ///
    /// Maximum durations and maximum tries are mutually exclusive within a
    /// given `Retry` operation. Calls to `max_duration` will override any
    /// previous calls to `max_duration` or [`max_tries`](Retry::max_tries).
    pub fn max_duration(mut self, duration: Duration) -> Self {
        self.limit = RetryLimit::Duration(duration);
        self
    }

    /// Retries the fallible operation `f` according to the configured policy.
    ///
    /// The `retry` method invokes `f` repeatedly until it succeeds 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 `f` never succeeds, then `retry`
    /// returns `f`'s return value from its last invocation.
    ///
    /// 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, T, E>(self, mut f: F) -> Result<T, E>
    where
        F: FnMut(RetryState) -> Result<T, E>,
    {
        let start = Instant::now();
        let mut i = 0;
        let mut next_backoff = Some(cmp::min(self.initial_backoff, self.clamp_backoff));
        loop {
            match self.limit {
                RetryLimit::Tries(max_tries) if i + 1 >= max_tries => next_backoff = None,
                RetryLimit::Duration(max_duration) => {
                    let elapsed = start.elapsed();
                    if elapsed > max_duration {
                        next_backoff = None;
                    } else if elapsed + next_backoff.unwrap() > max_duration {
                        next_backoff = Some(max_duration - elapsed);
                    }
                }
                _ => (),
            }
            let state = RetryState { i, next_backoff };
            match f(state) {
                Ok(t) => return Ok(t),
                Err(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, T, E>(self, mut f: F) -> Result<T, E>
    where
        F: FnMut(RetryState) -> U,
        U: Future<Output = Result<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 {
                Ok(v) => return Ok(v),
                Err(e) => err = Some(e),
            }
        }
        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 with 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,
            limit: RetryLimit::Duration(Duration::from_secs(30)),
        }
    }
}

/// 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);
            }
        }

        match retry.limit {
            RetryLimit::Tries(max_tries) if *this.i + 1 >= max_tries => *this.next_backoff = None,
            RetryLimit::Duration(max_duration) => {
                let elapsed = this.start.elapsed();
                if elapsed > max_duration {
                    *this.next_backoff = None;
                } else if elapsed + this.next_backoff.unwrap() > max_duration {
                    *this.next_backoff = Some(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 detais.
    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);
                        }
                    }
                }
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum RetryLimit {
    Duration(Duration),
    Tries(usize),
}

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

    #[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))
                },
            ]
        );
    }

    #[tokio::test]
    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))
                },
            ]
        );
    }

    #[tokio::test]
    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
                },
            ]
        );
    }

    #[tokio::test]
    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
                },
            ]
        );
    }

    #[test]
    fn test_retry_fail_max_duration() {
        let mut states = vec![];
        let res = Retry::default()
            .initial_backoff(Duration::from_millis(5))
            .max_duration(Duration::from_millis(10))
            .retry(|state| {
                states.push(state);
                Err::<(), _>("injected")
            });
        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 and 5ms. 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(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,
            },
        );
    }

    #[tokio::test]
    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 and 5ms. 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(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,
            },
        );
    }

    #[test]
    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
                },
            ]
        );
    }

    #[tokio::test]
    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
                },
            ]
        );
    }

    #[tokio::test]
    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]);
    }
}