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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use fuchsia_async::{self as fasync, DurationExt};
use futures::Future;
use std::time::Duration;

/// Execute the async task. If it errs out, attempt to run the task again after a delay if the
/// `backoff` yields a duration. Otherwise, return the first error that occurred to the caller.
///
/// # Examples
///
/// `retry_or_first_error` will succeed if the task returns `Ok` before the `backoff` returns None.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_first_error(
///     repeat(Duration::from_secs(1)),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         if count == 5 {
///             Ok(count)
///         } else {
///             Err(count)
///         }
///     }),
/// ).await;
/// assert_eq!(result, Ok(5));
/// ```
///
/// If the task fails, the `retry_or_first_error` will return the first error.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_first_error(
///     repeat(Duration::from_secs(1)).take(5),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         Err(count)
///     }),
/// ).await;
/// assert_eq!(result, Err(0));
/// ```
pub async fn retry_or_first_error<B, T>(mut backoff: B, task: T) -> Result<T::Ok, T::Error>
where
    B: Backoff<T::Error>,
    T: Task,
{
    match next(&mut backoff, task).await {
        Ok(value) => Ok(value),
        Err((err, None)) => Err(err),
        Err((err, Some(task))) => match retry_or_last_error(backoff, task).await {
            Ok(value) => Ok(value),
            Err(_) => Err(err),
        },
    }
}

/// Execute the async task. If it errs out, attempt to run the task again after a delay if the
/// `backoff` yields a duration. Otherwise, return the last error that occurred to the caller.
///
/// # Examples
///
/// `retry_or_last_error` will succeed if the task returns `Ok` before the `backoff` returns None.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_last_error(
///     repeat(Duration::from_secs(1)),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         if count == 5 {
///             Ok(count)
///         } else {
///             Err(count)
///         }
///     }),
/// ).await;
/// assert_eq!(result, Ok(5));
/// ```
///
/// If the task fails, the `retry_or_last_error` will return the last error.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_last_error(
///     repeat(Duration::from_secs(1)).take(5),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         Err(count)
///     }),
/// ).await;
/// assert_eq!(result, Err(5));
/// ```
pub async fn retry_or_last_error<B, T>(mut backoff: B, mut task: T) -> Result<T::Ok, T::Error>
where
    B: Backoff<T::Error>,
    T: Task,
{
    loop {
        match next(&mut backoff, task).await {
            Ok(value) => {
                return Ok(value);
            }
            Err((err, None)) => {
                return Err(err);
            }
            Err((_, Some(next))) => {
                task = next;
            }
        }
    }
}

/// Execute the async task. If it errs out, attempt to run the task again after a delay if the
/// `backoff` yields a duration. Otherwise, collect all the errors and return them to the caller.
///
/// # Examples
///
/// `retry_or_last_error` will succeed if it returns `Ok` before the `backoff` returns None.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_collect_errors(
///     repeat(Duration::from_secs(1)),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         if count == 5 {
///             Ok(count)
///         } else {
///             Err(count)
///         }
///     }),
/// ).await;
/// assert_eq!(result, Ok(5));
/// ```
///
/// If the task fails, it will return all the errors.
///
/// ```
/// # use std::iter::repeat;
/// # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
/// let counter = Arc::new(AtomicUsize::new(0));
/// let result = retry_or_last_error(
///     repeat(Duration::from_secs(1)).take(5),
///     || async {
///         let count = counter.fetch_add(1, Ordering::SeqCst);
///         Err(count)
///     }),
/// ).await;
/// assert_eq!(result, Err(vec![0, 1, 2, 3, 4]));
/// ```
pub async fn retry_or_collect_errors<B, T, C>(mut backoff: B, mut task: T) -> Result<T::Ok, C>
where
    B: Backoff<T::Error>,
    T: Task,
    C: Default + Extend<T::Error>,
{
    let mut collection = C::default();
    loop {
        match next(&mut backoff, task).await {
            Ok(value) => {
                return Ok(value);
            }
            Err((err, next)) => {
                collection.extend(Some(err));
                match next {
                    Some(next) => {
                        task = next;
                    }
                    None => {
                        return Err(collection);
                    }
                }
            }
        }
    }
}

async fn next<B, T>(backoff: &mut B, mut task: T) -> Result<T::Ok, (T::Error, Option<T>)>
where
    B: Backoff<T::Error>,
    T: Task,
{
    match task.run().await {
        Ok(value) => Ok(value),
        Err(err) => match backoff.next_backoff(&err) {
            Some(delay) => {
                let delay = delay.after_now();
                fasync::Timer::new(delay).await;
                Err((err, Some(task)))
            }
            None => Err((err, None)),
        },
    }
}

/// A task produces an asynchronous computation that can be retried if the returned future fails
/// with some error.
pub trait Task {
    /// The type of successful values yielded by the task future.
    type Ok;

    /// The type of failures yielded by the task future.
    type Error;

    /// The future returned when executing this task.
    type Future: Future<Output = Result<Self::Ok, Self::Error>>;

    /// Return a future.
    fn run(&mut self) -> Self::Future;
}

impl<F, Fut, T, E> Task for F
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>>,
{
    type Ok = T;
    type Error = E;
    type Future = Fut;

    fn run(&mut self) -> Self::Future {
        (self)()
    }
}

/// A backoff policy for deciding to retry an operation.
pub trait Backoff<E> {
    fn next_backoff(&mut self, err: &E) -> Option<Duration>;
}

impl<E, I> Backoff<E> for I
where
    I: Iterator<Item = Duration>,
{
    fn next_backoff(&mut self, _: &E) -> Option<Duration> {
        self.next()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::prelude::*;
    use std::iter;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    const BACKOFF_DURATION: u64 = 100;

    #[derive(Clone)]
    struct Counter {
        counter: Arc<AtomicUsize>,
        ok_at: Option<usize>,
    }

    impl Counter {
        fn ok_at(count: usize) -> Self {
            Counter { counter: Arc::new(AtomicUsize::new(0)), ok_at: Some(count) }
        }

        fn never_ok() -> Self {
            Counter { counter: Arc::new(AtomicUsize::new(0)), ok_at: None }
        }
    }

    impl Task for Counter {
        type Ok = usize;
        type Error = usize;
        type Future = future::Ready<Result<usize, usize>>;

        fn run(&mut self) -> Self::Future {
            let count = self.counter.fetch_add(1, Ordering::SeqCst);
            match self.ok_at {
                Some(ok_at) if ok_at == count => future::ready(Ok(count)),
                _ => future::ready(Err(count)),
            }
        }
    }

    #[cfg(target_os = "fuchsia")]
    fn run<F>(future: F, pending_count: usize) -> F::Output
    where
        F: Future,
        F::Output: std::fmt::Debug + PartialEq + Eq,
    {
        use std::{pin::pin, task::Poll};

        let mut future = pin!(future);
        let mut executor = fasync::TestExecutor::new_with_fake_time();

        for _ in 0..pending_count {
            assert_eq!(executor.run_until_stalled(&mut future), Poll::Pending);
            assert_eq!(executor.wake_expired_timers(), false);
            executor.set_fake_time(Duration::from_millis(BACKOFF_DURATION).after_now());
            assert_eq!(executor.wake_expired_timers(), true);
        }

        match executor.run_until_stalled(&mut future) {
            Poll::Ready(value) => value,
            Poll::Pending => panic!("expected future to be ready"),
        }
    }

    #[cfg(not(target_os = "fuchsia"))]
    fn run<F>(future: F, pending_count: usize) -> F::Output
    where
        F: Future,
        F::Output: std::fmt::Debug + PartialEq + Eq,
    {
        // The host-side executor doesn't support fake time, so just run the future and make sure
        // it ran longer than the backoff duration.
        let mut executor = fasync::LocalExecutor::new();

        let start_time = fasync::Time::now();

        let result = executor.run_singlethreaded(future);

        let actual_duration = fasync::Time::now() - start_time;
        let expected_duration = Duration::from_millis(BACKOFF_DURATION) * pending_count as u32;

        assert!(expected_duration <= actual_duration);

        result
    }

    // Return `attempts` durations.
    fn backoff(attempts: usize) -> impl Iterator<Item = Duration> {
        iter::repeat(Duration::from_millis(BACKOFF_DURATION)).take(attempts)
    }

    #[test]
    fn test_should_succeed() {
        for i in 0..5 {
            // to test passing, always attempt one more attempt than necessary before Counter
            // succeeds.

            assert_eq!(run(retry_or_first_error(backoff(i + 1), Counter::ok_at(i)), i), Ok(i));
            assert_eq!(run(retry_or_last_error(backoff(i + 1), Counter::ok_at(i)), i), Ok(i));
            assert_eq!(
                run(retry_or_collect_errors(backoff(i + 1), Counter::ok_at(i)), i),
                Ok::<usize, Vec<usize>>(i)
            );

            // Check FnMut impl works. It always succeeds during the first iteration.
            let task = || future::ready(Ok::<_, ()>(i));
            assert_eq!(run(retry_or_last_error(backoff(i + 1), task), 0), Ok(i));
        }
    }

    #[test]
    fn test_should_error() {
        for i in 0..5 {
            assert_eq!(run(retry_or_first_error(backoff(i), Counter::never_ok()), i), Err(0));
            assert_eq!(run(retry_or_last_error(backoff(i), Counter::never_ok()), i), Err(i));
            assert_eq!(
                run(retry_or_collect_errors(backoff(i), Counter::never_ok()), i),
                Err::<usize, Vec<usize>>((0..=i).collect())
            );

            // Check FnMut impl works.
            let task = || future::ready(Err::<(), _>(i));
            assert_eq!(run(retry_or_last_error(backoff(i), task), i), Err(i));
        }
    }
}