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
use std::fmt;
use std::io;
use std::pin::Pin;
use std::time::Duration;
use async_std::future::Future;
use async_std::stream::Stream;
use async_std::task::{sleep, Context, Poll};
use crate::is_transient_error;
pub struct HandleErrors<S> {
stream: S,
sleep_on_warning: Duration,
timeout: Option<Pin<Box<dyn Future<Output=()> + 'static + Send>>>,
}
impl<S: fmt::Debug> fmt::Debug for HandleErrors<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("HandleErrors")
.field("stream", &self.stream)
.field("sleep_on_warning", &self.sleep_on_warning)
.finish()
}
}
impl<S: Unpin> Unpin for HandleErrors<S> {}
impl<S> HandleErrors<S> {
pub(crate) fn new(stream: S, sleep_on_warning: Duration)
-> HandleErrors<S>
{
HandleErrors { stream, sleep_on_warning, timeout: None }
}
pub fn get_mut(&mut self) -> &mut S {
&mut self.stream
}
pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> {
unsafe {
self.map_unchecked_mut(|x| &mut x.stream)
}
}
pub fn into_inner(self) -> S {
self.stream
}
}
impl<I, S> Stream for HandleErrors<S>
where S: Stream<Item=Result<I, io::Error>> + Unpin,
{
type Item = I;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context)
-> Poll<Option<Self::Item>>
{
if let Some(ref mut to) = self.timeout {
match to.as_mut().poll(cx) {
Poll::Ready(_) => {}
Poll::Pending => return Poll::Pending,
}
}
self.timeout = None;
loop {
match self.as_mut().get_pin_mut().poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Some(Ok(v))) => return Poll::Ready(Some(v)),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Ready(Some(Err(ref e)))
if is_transient_error(e) => continue,
Poll::Ready(Some(Err(_))) => {
let mut timeout = Box::pin(sleep(self.sleep_on_warning));
match timeout.as_mut().poll(cx) {
Poll::Pending => {
self.timeout = Some(timeout);
return Poll::Pending;
}
Poll::Ready(()) => continue,
}
}
}
}
}
}