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
use crate::{
transport::{Transport, TransportError},
Multiaddr,
};
use futures::{
future::{BoxFuture, Future},
ready,
stream::{FuturesUnordered, StreamExt},
};
use std::{
num::NonZeroU8,
pin::Pin,
task::{Context, Poll},
};
type Dial<TTrans> = BoxFuture<
'static,
(
Multiaddr,
Result<<TTrans as Transport>::Output, TransportError<<TTrans as Transport>::Error>>,
),
>;
pub struct ConcurrentDial<TTrans: Transport> {
dials: FuturesUnordered<Dial<TTrans>>,
pending_dials: Box<dyn Iterator<Item = Dial<TTrans>> + Send>,
errors: Vec<(Multiaddr, TransportError<TTrans::Error>)>,
}
impl<TTrans: Transport> Unpin for ConcurrentDial<TTrans> {}
impl<TTrans> ConcurrentDial<TTrans>
where
TTrans: Transport + Send + 'static,
TTrans::Output: Send,
TTrans::Error: Send,
TTrans::Dial: Send + 'static,
{
pub(crate) fn new(pending_dials: Vec<Dial<TTrans>>, concurrency_factor: NonZeroU8) -> Self {
let mut pending_dials = pending_dials.into_iter();
let dials = FuturesUnordered::new();
for dial in pending_dials.by_ref() {
dials.push(dial);
if dials.len() == concurrency_factor.get() as usize {
break;
}
}
Self {
dials,
errors: Default::default(),
pending_dials: Box::new(pending_dials),
}
}
}
impl<TTrans> Future for ConcurrentDial<TTrans>
where
TTrans: Transport,
{
type Output = Result<
(
Multiaddr,
TTrans::Output,
Vec<(Multiaddr, TransportError<TTrans::Error>)>,
),
Vec<(Multiaddr, TransportError<TTrans::Error>)>,
>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
loop {
match ready!(self.dials.poll_next_unpin(cx)) {
Some((addr, Ok(output))) => {
let errors = std::mem::take(&mut self.errors);
return Poll::Ready(Ok((addr, output, errors)));
}
Some((addr, Err(e))) => {
self.errors.push((addr, e));
if let Some(dial) = self.pending_dials.next() {
self.dials.push(dial)
}
}
None => {
return Poll::Ready(Err(std::mem::take(&mut self.errors)));
}
}
}
}
}