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
use std::future::Future;
use std::time::Duration;

use indicatif::{ProgressBar, ProgressStyle};

pub async fn spin_until_ready<F, FO>(future: F) -> FO
where
    F: Future<Output = FO>,
{
    //     const LOADING: &str = "
    // x     xxxxx   x   xxxx   xxx  xx  x xxxxx
    // x     x   x  x x  x   x   x   x x x x
    // x     x   x xxxxx x   x   x   x x x x  xx
    // x     x   x x   x x   x   x   x  xx x   x
    // xxxxx xxxxx x   x xxxx   xxx  x  xx xxxxx
    //         ";
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(ProgressStyle::default_spinner());
    let result = tokio::select! {
        _ = spin_endless(&spinner) => { unreachable!("future running indefinitely"); }
        output = future => { output }
    };
    spinner.finish_and_clear();
    result
}

async fn spin_endless(spinner: &ProgressBar) -> ! {
    loop {
        spinner.tick();
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

pub async fn spin_and_try_every_second_for<F, FG, FO>(
    future: FG,
    num_tries: usize,
) -> anyhow::Result<FO>
where
    FG: Fn() -> F,
    F: Future<Output = anyhow::Result<FO>>,
{
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(ProgressStyle::default_spinner());
    let result = tokio::select! {
        _ = spin_endless(&spinner) => { unreachable!("future running indefinitely"); }
        output = try_future_x_times(future, num_tries) => { output }
    };
    spinner.finish_and_clear();
    result
}

async fn try_future_x_times<F, FG, FO>(future: FG, num_tries: usize) -> anyhow::Result<FO>
where
    FG: Fn() -> F,
    F: Future<Output = anyhow::Result<FO>>,
{
    let mut tries = num_tries;
    loop {
        tries -= 1;
        tokio::time::sleep(Duration::from_secs(1)).await;
        let res = future().await;
        if res.is_ok() || tries == 0 {
            return res;
        }
    }
}