futures_retry/
stream.rs

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
use crate::{ErrorHandler, RetryPolicy};
use futures::{ready, Stream, TryStream};
use pin_project_lite::pin_project;
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};
use tokio::time;

pin_project! {
    /// Provides a way to handle errors during a `Stream` execution, i.e. it gives you an ability to
    /// poll for future stream's items with a delay.
    ///
    /// This type is similar to [`FutureRetry`](struct.FutureRetry.html), but with a different
    /// semantics. For example, if for [`FutureRetry`](struct.FutureRetry.html) we need a factory that
    /// creates `Future`s, we don't need one for `Stream`s, since `Stream` itself is a natural producer
    /// of new items, so we don't have to recreated it if an error is encountered.
    ///
    /// A typical usage might be recovering from connection errors while trying to accept a connection
    /// on a TCP server.
    ///
    /// A `tcp-listener` example is available in the `examples` folder.
    ///
    /// Also have a look at [`StreamRetryExt`](trait.StreamRetryExt.html) trait for a more convenient
    /// usage.
    pub struct StreamRetry<F, S> {
        error_action: F,
        #[pin]
        stream: S,
        attempt: usize,
        #[pin]
        state: RetryState,
    }
}

/// An extention trait for `Stream` which allows to use `StreamRetry` in a chain-like manner.
///
/// # Example
///
/// This magic trait allows you to handle errors on streams in a very neat manner:
///
/// ```
/// // ...
/// use futures_retry::{RetryPolicy, StreamRetryExt};
/// # use futures::{TryStreamExt, TryFutureExt, future::{ok, select}, FutureExt, stream};
/// # use std::io;
/// # use std::time::Duration;
/// # use tokio::net::{TcpListener, TcpStream};
///
/// fn handle_error(e: io::Error) -> RetryPolicy<io::Error> {
///   match e.kind() {
///     io::ErrorKind::Interrupted => RetryPolicy::Repeat,
///     io::ErrorKind::PermissionDenied => RetryPolicy::ForwardError(e),
///     _ => RetryPolicy::WaitRetry(Duration::from_millis(5)),
///   }
/// }
///
/// async fn serve_connection(stream: TcpStream) {
///   // ...
/// }
///
/// #[tokio::main]
/// async fn main() {
///   let mut listener: TcpListener = // ...
///   # TcpListener::bind("[::]:0").await.unwrap();
///   let server = stream::try_unfold(listener, |listener| async move {
///     Ok(Some((listener.accept().await?.0, listener)))
///   })
///   .retry(handle_error)
///   .and_then(|(stream, _attempt)| {
///     tokio::spawn(serve_connection(stream));
///     ok(())
///   })
///   .try_for_each(|_| ok(()))
///   .map_err(|(e, _attempt)| eprintln!("Caught an error {}", e));
///
///   # // This nasty hack is required to exit immediately when running the doc tests.
///   # futures::pin_mut!(server);
///   # let server = select(ok::<_, ()>(()), server).map(|_| ());
///   server.await
/// }
/// ```
pub trait StreamRetryExt: TryStream {
    /// Converts the stream into a **retry stream**. See `StreamRetry::new` for details.
    fn retry<F>(self, error_action: F) -> StreamRetry<F, Self>
    where
        Self: Sized,
    {
        StreamRetry::new(self, error_action)
    }
}

impl<S: ?Sized> StreamRetryExt for S where S: TryStream {}

pin_project! {
    #[project = RetryStateProj]
    enum RetryState {
        WaitingForStream,
        TimerActive { #[pin] delay: time::Sleep },
    }
}

impl<F, S> StreamRetry<F, S> {
    /// Creates a `StreamRetry` using a provided stream and an object of `ErrorHandler` type that
    /// decides on a retry-policy depending on an encountered error.
    ///
    /// Please refer to the `tcp-listener` example in the `examples` folder to have a look at a
    /// possible usage or to a very convenient extension trait
    /// [`StreamRetryExt`](trait.StreamRetryExt.html).
    ///
    /// # Arguments
    ///
    /// * `stream`: a stream of future items,
    /// * `error_action`: a type that handles an error and decides which route to take: simply
    ///                   try again, wait and then try, or give up (on a critical error for
    ///                   exapmle).
    pub fn new(stream: S, error_action: F) -> Self
    where
        S: TryStream,
    {
        Self::with_counter(stream, error_action, 1)
    }

    /// Like a `new` method, but a custom attempt counter initial value might be provided.
    pub fn with_counter(stream: S, error_action: F, attempt_counter: usize) -> Self {
        Self {
            error_action,
            stream,
            attempt: attempt_counter,
            state: RetryState::WaitingForStream,
        }
    }
}

impl<F, S> Stream for StreamRetry<F, S>
where
    S: TryStream,
    F: ErrorHandler<S::Error>,
{
    type Item = Result<(S::Ok, usize), (F::OutError, usize)>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        loop {
            let this = self.as_mut().project();
            let attempt = *this.attempt;
            let new_state = match this.state.project() {
                RetryStateProj::TimerActive { delay } => {
                    ready!(delay.poll(cx));
                    RetryState::WaitingForStream
                }
                RetryStateProj::WaitingForStream => match ready!(this.stream.try_poll_next(cx)) {
                    Some(Ok(x)) => {
                        *this.attempt = 1;
                        this.error_action.ok(attempt);
                        return Poll::Ready(Some(Ok((x, attempt))));
                    }
                    None => {
                        return Poll::Ready(None);
                    }
                    Some(Err(e)) => {
                        *this.attempt += 1;
                        match this.error_action.handle(attempt, e) {
                            RetryPolicy::ForwardError(e) => {
                                return Poll::Ready(Some(Err((e, attempt))))
                            }
                            RetryPolicy::Repeat => RetryState::WaitingForStream,
                            RetryPolicy::WaitRetry(duration) => RetryState::TimerActive {
                                delay: time::sleep(duration),
                            },
                        }
                    }
                },
            };
            self.as_mut().project().state.set(new_state);
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use futures::{pin_mut, prelude::*};
    use std::time::Duration;

    #[tokio::test]
    async fn naive() {
        let stream = stream::iter(vec![Ok::<_, u8>(17u8), Ok(19u8)]);
        let retry = StreamRetry::new(stream, |_| RetryPolicy::Repeat::<()>);
        assert_eq!(
            Ok(vec![(17, 1), (19, 1)]),
            retry.try_collect::<Vec<_>>().await,
        );
    }

    #[tokio::test]
    async fn repeat() {
        let stream = stream::iter(vec![Ok(1), Err(17), Ok(19)]);
        let retry = StreamRetry::new(stream, |_| RetryPolicy::Repeat::<()>);
        assert_eq!(
            Ok(vec![(1, 1), (19, 2)]),
            retry.try_collect::<Vec<_>>().await,
        );
    }

    #[tokio::test]
    async fn wait() {
        let stream = stream::iter(vec![Err(17), Ok(19)]);
        let retry = StreamRetry::new(stream, |_| {
            RetryPolicy::WaitRetry::<()>(Duration::from_millis(10))
        })
        .try_collect()
        .into_future();
        assert_eq!(Ok(vec!((19, 2))), retry.await);
    }

    #[tokio::test]
    async fn propagate() {
        let stream = stream::iter(vec![Err(17u8), Ok(19u16)]);
        let retry = StreamRetry::new(stream, RetryPolicy::ForwardError);
        pin_mut!(retry);
        assert_eq!(Some(Err((17u8, 1))), retry.next().await,);
    }
}