1
//! Definitions for [`SleepProviderExt`] and related types.
2

            
3
use crate::traits::SleepProvider;
4
use futures::{Future, FutureExt};
5
use pin_project::pin_project;
6
use std::{
7
    pin::Pin,
8
    task::{Context, Poll},
9
};
10
use web_time_compat::{Duration, Instant, SystemTime};
11

            
12
/// An error value given when a function times out.
13
///
14
/// This value is generated when the timeout from
15
/// [`SleepProviderExt::timeout`] expires before the provided future
16
/// is ready.
17
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
18
#[allow(clippy::exhaustive_structs)]
19
pub struct TimeoutError;
20
impl std::error::Error for TimeoutError {}
21
impl std::fmt::Display for TimeoutError {
22
4
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23
4
        write!(f, "Timeout expired")
24
4
    }
25
}
26

            
27
impl From<TimeoutError> for std::io::Error {
28
    fn from(err: TimeoutError) -> std::io::Error {
29
        std::io::Error::new(std::io::ErrorKind::TimedOut, err)
30
    }
31
}
32

            
33
/// An extension trait on [`SleepProvider`] for timeouts and clock delays.
34
pub trait SleepProviderExt: SleepProvider {
35
    /// Wrap a [`Future`] with a timeout.
36
    ///
37
    /// The output of the new future will be the returned value of
38
    /// `future` if it completes within `duration`.  Otherwise, it
39
    /// will be `Err(TimeoutError)`.
40
    ///
41
    /// This uses [`SleepProvider::sleep`] for its timer.
42
    #[must_use = "timeout() returns a future, which does nothing unless used"]
43
749
    fn timeout<F: Future>(&self, duration: Duration, future: F) -> Timeout<F, Self::SleepFuture> {
44
749
        let sleep_future = self.sleep(duration);
45

            
46
749
        Timeout {
47
749
            future,
48
749
            sleep_future,
49
749
        }
50
749
    }
51

            
52
    /// Pause until the wall-clock is at `when` or later, trying to
53
    /// recover from clock jumps.
54
    ///
55
    /// This uses [`SleepProvider::sleep`] for its timer.
56
    /// Unlike [`SleepProvider::sleep()`], the future returned by this function will
57
    /// wake up periodically to check the current time, and see if
58
    /// it is at or past the target.
59
    ///
60
    /// # Limitations
61
    ///
62
    /// The ability of this function to detect clock jumps is limited
63
    /// to its granularity; it may finish a while after the declared
64
    /// wallclock time if the system clock jumps forward.
65
    ///
66
    /// This function does not detect backward clock jumps; arguably,
67
    /// we should have another function to do that.
68
    #[must_use = "sleep_until_wallclock() returns a future, which does nothing unless used"]
69
89
    fn sleep_until_wallclock(&self, when: SystemTime) -> SleepUntilWallclock<'_, Self> {
70
89
        SleepUntilWallclock {
71
89
            provider: self,
72
89
            target: when,
73
89
            sleep_future: None,
74
89
        }
75
89
    }
76

            
77
    /// Return a future that will be ready when `deadline` is reached.
78
    ///
79
    /// This uses [`SleepProvider::sleep`] for its timer.
80
    #[must_use = "sleep_until() returns a future, which does nothing unless used"]
81
668
    fn sleep_until(&self, deadline: Instant) -> Self::SleepFuture {
82
668
        self.sleep(deadline.saturating_duration_since(self.now()))
83
668
    }
84
}
85

            
86
impl<T: SleepProvider> SleepProviderExt for T {}
87

            
88
/// A timeout returned by [`SleepProviderExt::timeout`].
89
#[pin_project]
90
pub struct Timeout<T, S> {
91
    /// The future we want to execute.
92
    #[pin]
93
    future: T,
94
    /// The future implementing the timeout.
95
    #[pin]
96
    sleep_future: S,
97
}
98

            
99
impl<T, S> Future for Timeout<T, S>
100
where
101
    T: Future,
102
    S: Future<Output = ()>,
103
{
104
    type Output = Result<T::Output, TimeoutError>;
105

            
106
1127
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
107
1127
        let this = self.project();
108
1127
        if let Poll::Ready(x) = this.future.poll(cx) {
109
711
            return Poll::Ready(Ok(x));
110
416
        }
111

            
112
416
        match this.sleep_future.poll(cx) {
113
384
            Poll::Pending => Poll::Pending,
114
32
            Poll::Ready(()) => Poll::Ready(Err(TimeoutError)),
115
        }
116
1127
    }
117
}
118

            
119
/// A future implementing [`SleepProviderExt::sleep_until_wallclock`].
120
pub struct SleepUntilWallclock<'a, SP: SleepProvider> {
121
    /// Reference to the provider that we use to make new SleepFutures.
122
    provider: &'a SP,
123
    /// The time that we are waiting for.
124
    target: SystemTime,
125
    /// The future representing our current delay.
126
    sleep_future: Option<Pin<Box<SP::SleepFuture>>>,
127
}
128

            
129
impl<'a, SP> Future for SleepUntilWallclock<'a, SP>
130
where
131
    SP: SleepProvider,
132
{
133
    type Output = ();
134

            
135
3970
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
136
        // Strategy: we implement sleep_until_wallclock by
137
        // waiting in increments of up to MAX_SLEEP, checking the
138
        // wall clock before and after each increment.  This makes
139
        // us wake up a bit more frequently, but enables us to detect it
140
        // if the system clock jumps forward.
141
3970
        let target = self.target;
142
        loop {
143
3970
            let now = self.provider.wallclock();
144
3970
            if now >= target {
145
18
                return Poll::Ready(());
146
3952
            }
147

            
148
3952
            let (last_delay, delay) = calc_next_delay(now, target);
149

            
150
            // Note that we store this future to keep it from being
151
            // cancelled, even though we don't ever poll it more than
152
            // once.
153
            //
154
            // TODO: I'm not sure that it's actually necessary to keep
155
            // this future around.
156
3952
            self.sleep_future.take();
157

            
158
3952
            let mut sleep_future = Box::pin(self.provider.sleep(delay));
159
3952
            match sleep_future.poll_unpin(cx) {
160
                Poll::Pending => {
161
3952
                    self.sleep_future = Some(sleep_future);
162
3952
                    return Poll::Pending;
163
                }
164
                Poll::Ready(()) => {
165
                    if last_delay {
166
                        return Poll::Ready(());
167
                    }
168
                }
169
            }
170
        }
171
3970
    }
172
}
173

            
174
/// We never sleep more than this much, in case our system clock jumps.
175
///
176
/// Note that there's a tradeoff here: Making this duration
177
/// shorter helps our accuracy, but makes us wake up more
178
/// frequently and consume more CPU.
179
const MAX_SLEEP: Duration = Duration::from_secs(600);
180

            
181
/// Return the amount of time we should wait next, when running
182
/// sleep_until_wallclock().  Also return a boolean indicating whether we
183
/// expect this to be the final delay.
184
///
185
/// (This is a separate function for testing.)
186
311902
pub(crate) fn calc_next_delay(now: SystemTime, when: SystemTime) -> (bool, Duration) {
187
311902
    let remainder = when
188
311902
        .duration_since(now)
189
1
        .unwrap_or_else(|_| Duration::from_secs(0));
190
311902
    if remainder > MAX_SLEEP {
191
299017
        (false, MAX_SLEEP)
192
    } else {
193
12885
        (true, remainder)
194
    }
195
311902
}
196

            
197
#[cfg(test)]
198
mod test {
199
    // @@ begin test lint list maintained by maint/add_warning @@
200
    #![allow(clippy::bool_assert_comparison)]
201
    #![allow(clippy::clone_on_copy)]
202
    #![allow(clippy::dbg_macro)]
203
    #![allow(clippy::mixed_attributes_style)]
204
    #![allow(clippy::print_stderr)]
205
    #![allow(clippy::print_stdout)]
206
    #![allow(clippy::single_char_pattern)]
207
    #![allow(clippy::unwrap_used)]
208
    #![allow(clippy::unchecked_time_subtraction)]
209
    #![allow(clippy::useless_vec)]
210
    #![allow(clippy::needless_pass_by_value)]
211
    #![allow(clippy::string_slice)] // See arti#2571
212
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
213
    #![allow(clippy::erasing_op)]
214
    use web_time_compat::SystemTimeExt;
215

            
216
    #[cfg(not(miri))]
217
    use super::*;
218

            
219
    #[cfg(not(miri))] // This uses a real SystemTime, which doesn't work in miri
220
    #[test]
221
    fn sleep_delay() {
222
        fn calc(now: SystemTime, when: SystemTime) -> Duration {
223
            calc_next_delay(now, when).1
224
        }
225
        let minute = Duration::from_secs(60);
226
        let second = Duration::from_secs(1);
227
        let start = SystemTime::get();
228

            
229
        let target = start + 30 * minute;
230

            
231
        assert_eq!(calc(start, target), minute * 10);
232
        assert_eq!(calc(target + minute, target), minute * 0);
233
        assert_eq!(calc(target, target), minute * 0);
234
        assert_eq!(calc(target - second, target), second);
235
        assert_eq!(calc(target - minute * 9, target), minute * 9);
236
        assert_eq!(calc(target - minute * 11, target), minute * 10);
237
    }
238
}