summaryrefslogtreecommitdiff
path: root/cli/util/retry.rs
blob: a8febe60dedf335c935ee5254573afc0509f9a96 (plain)
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use std::future::Future;
use std::time::Duration;

pub fn retry<
  F: FnMut() -> Fut,
  T,
  E,
  Fut: Future<Output = Result<T, E>>,
  ShouldRetry: FnMut(&E) -> bool,
>(
  mut f: F,
  mut should_retry: ShouldRetry,
) -> impl Future<Output = Result<T, E>> {
  const WAITS: [Duration; 3] = [
    Duration::from_millis(100),
    Duration::from_millis(250),
    Duration::from_millis(500),
  ];

  let mut waits = WAITS.into_iter();
  async move {
    let mut first_result = None;
    loop {
      let result = f().await;
      match result {
        Ok(r) => return Ok(r),
        Err(e) if !should_retry(&e) => return Err(e),
        _ => {}
      }
      if first_result.is_none() {
        first_result = Some(result);
      }
      let Some(wait) = waits.next() else {
        return first_result.unwrap();
      };
      tokio::time::sleep(wait).await;
    }
  }
}