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
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

pub mod cid;
pub mod clock;
pub mod db;
pub mod encoding;
pub mod flume;
pub mod io;
pub mod misc;
pub mod monitoring;
pub mod net;
pub mod p2p;
pub mod proofs_api;
pub mod reqwest_resume;
pub mod stats;
pub mod stream;
pub mod version;

use anyhow::{bail, Context as _};
use futures::{
    future::{pending, FusedFuture},
    select, Future, FutureExt,
};
use multiaddr::{Multiaddr, Protocol};
use std::{pin::Pin, str::FromStr, time::Duration};
use tokio::time::sleep;
use tracing::error;
use url::Url;

/// `"hunter2:/ip4/127.0.0.1/wss" -> "wss://:hunter2@127.0.0.1/"`
#[derive(Clone, Debug)]
pub struct UrlFromMultiAddr(pub Url);

impl FromStr for UrlFromMultiAddr {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (p, s) = match s.split_once(':') {
            Some((first, rest)) => (Some(first), rest),
            None => (None, s),
        };
        let m = Multiaddr::from_str(s).context("invalid multiaddr")?;
        let mut u = multiaddr2url(&m).context("unsupported multiaddr")?;
        if u.set_password(p).is_err() {
            bail!("unsupported password")
        }
        Ok(Self(u))
    }
}

/// `"/dns/example.com/tcp/8080/http" -> "http://example.com:8080/"`
///
/// Returns [`None`] on unsupported formats, or if there is a URL parsing error.
///
/// Note that [`Multiaddr`]s do NOT support a (URL) `path`, so that must be handled
/// out-of-band.
fn multiaddr2url(m: &Multiaddr) -> Option<Url> {
    let mut components = m.iter().peekable();
    let host = match components.next()? {
        Protocol::Dns(it) | Protocol::Dns4(it) | Protocol::Dns6(it) | Protocol::Dnsaddr(it) => {
            it.to_string()
        }
        Protocol::Ip4(it) => it.to_string(),
        Protocol::Ip6(it) => it.to_string(),
        _ => return None,
    };
    let port = components
        .next_if(|it| matches!(it, Protocol::Tcp(_)))
        .map(|it| match it {
            Protocol::Tcp(port) => port,
            _ => unreachable!(),
        });
    // ENHANCEMENT: could recognise `Tcp/443/Tls` as `https`
    let scheme = match components.next()? {
        Protocol::Http => "http",
        Protocol::Https => "https",
        Protocol::Ws(it) if it == "/" => "ws",
        Protocol::Wss(it) if it == "/" => "wss",
        _ => return None,
    };
    let None = components.next() else { return None };
    let parse_me = match port {
        Some(port) => format!("{}://{}:{}", scheme, host, port),
        None => format!("{}://{}", scheme, host),
    };
    parse_me.parse().ok()
}

#[test]
fn test_url_from_multiaddr() {
    #[track_caller]
    fn do_test(input: &str, expected: &str) {
        let UrlFromMultiAddr(url) = input.parse().unwrap();
        assert_eq!(url.as_str(), expected);
    }
    do_test("/dns/example.com/http", "http://example.com/");
    do_test("/dns/example.com/tcp/8080/http", "http://example.com:8080/");
    do_test("/ip4/127.0.0.1/wss", "wss://127.0.0.1/");

    // with password
    do_test(
        "hunter2:/dns/example.com/http",
        "http://:hunter2@example.com/",
    );
    do_test(
        "hunter2:/dns/example.com/tcp/8080/http",
        "http://:hunter2@example.com:8080/",
    );
    do_test("hunter2:/ip4/127.0.0.1/wss", "wss://:hunter2@127.0.0.1/");
}

/// Keep running the future created by `make_fut` until the timeout or retry
/// limit in `args` is reached.
/// `F` _must_ be cancel safe.
#[tracing::instrument(skip_all)]
pub async fn retry<F, T, E>(
    args: RetryArgs,
    mut make_fut: impl FnMut() -> F,
) -> Result<T, RetryError>
where
    F: Future<Output = Result<T, E>>,
    E: std::fmt::Debug,
{
    let mut timeout: Pin<Box<dyn FusedFuture<Output = ()>>> = match args.timeout {
        Some(duration) => Box::pin(sleep(duration).fuse()),
        None => Box::pin(pending()),
    };
    let max_retries = args.max_retries.unwrap_or(usize::MAX);
    let mut task = Box::pin(
        async {
            for _ in 0..max_retries {
                match make_fut().await {
                    Ok(ok) => return Ok(ok),
                    Err(err) => error!("retrying operation after {err:?}"),
                }
                if let Some(delay) = args.delay {
                    sleep(delay).await;
                }
            }
            Err(RetryError::RetriesExceeded)
        }
        .fuse(),
    );
    select! {
        _ = timeout => Err(RetryError::TimeoutExceeded),
        res = task => res,
    }
}

#[derive(Debug, Clone, Copy, smart_default::SmartDefault)]
pub struct RetryArgs {
    #[default(Some(Duration::from_secs(1)))]
    pub timeout: Option<Duration>,
    #[default(Some(5))]
    pub max_retries: Option<usize>,
    #[default(Some(Duration::from_millis(200)))]
    pub delay: Option<Duration>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum RetryError {
    #[error("operation timed out")]
    TimeoutExceeded,
    #[error("retry limit exceeded")]
    RetriesExceeded,
}

#[cfg(test)]
mod tests {
    mod files;

    use std::{future::ready, sync::atomic::AtomicUsize};
    use RetryError::{RetriesExceeded, TimeoutExceeded};

    use super::*;

    impl RetryArgs {
        fn new_ms(
            timeout: impl Into<Option<u64>>,
            max_retries: impl Into<Option<usize>>,
            delay: impl Into<Option<u64>>,
        ) -> Self {
            Self {
                timeout: timeout.into().map(Duration::from_millis),
                max_retries: max_retries.into(),
                delay: delay.into().map(Duration::from_millis),
            }
        }
    }

    #[tokio::test]
    async fn timeout() {
        let res = retry(RetryArgs::new_ms(1, None, None), pending::<Result<(), ()>>).await;
        assert_eq!(Err(TimeoutExceeded), res);
    }

    #[tokio::test]
    async fn retries() {
        let res = retry(RetryArgs::new_ms(None, 1, None), || ready(Err::<(), _>(()))).await;
        assert_eq!(Err(RetriesExceeded), res);
    }

    #[tokio::test]
    async fn ok() {
        let res = retry(RetryArgs::default(), || ready(Ok::<_, ()>(()))).await;
        assert_eq!(Ok(()), res);
    }

    #[tokio::test]
    async fn needs_retry() {
        use std::sync::atomic::Ordering::SeqCst;
        let count = AtomicUsize::new(0);
        let res = retry(RetryArgs::new_ms(None, None, None), || async {
            match count.fetch_add(1, SeqCst) > 5 {
                true => Ok(()),
                false => Err(()),
            }
        })
        .await;
        assert_eq!(Ok(()), res);
        assert!(count.load(SeqCst) > 5);
    }
}