1use crate::traits::SleepProvider;
4use futures::{Future, FutureExt};
5use pin_project::pin_project;
6use std::{
7 pin::Pin,
8 task::{Context, Poll},
9};
10use web_time_compat::{Duration, Instant, SystemTime};
11
12#[derive(Copy, Clone, Debug, Eq, PartialEq)]
18#[allow(clippy::exhaustive_structs)]
19pub struct TimeoutError;
20impl std::error::Error for TimeoutError {}
21impl std::fmt::Display for TimeoutError {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 write!(f, "Timeout expired")
24 }
25}
26
27impl 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
33pub trait SleepProviderExt: SleepProvider {
35 #[must_use = "timeout() returns a future, which does nothing unless used"]
43 fn timeout<F: Future>(&self, duration: Duration, future: F) -> Timeout<F, Self::SleepFuture> {
44 let sleep_future = self.sleep(duration);
45
46 Timeout {
47 future,
48 sleep_future,
49 }
50 }
51
52 #[must_use = "sleep_until_wallclock() returns a future, which does nothing unless used"]
69 fn sleep_until_wallclock(&self, when: SystemTime) -> SleepUntilWallclock<'_, Self> {
70 SleepUntilWallclock {
71 provider: self,
72 target: when,
73 sleep_future: None,
74 }
75 }
76
77 #[must_use = "sleep_until() returns a future, which does nothing unless used"]
81 fn sleep_until(&self, deadline: Instant) -> Self::SleepFuture {
82 self.sleep(deadline.saturating_duration_since(self.now()))
83 }
84}
85
86impl<T: SleepProvider> SleepProviderExt for T {}
87
88#[pin_project]
90pub struct Timeout<T, S> {
91 #[pin]
93 future: T,
94 #[pin]
96 sleep_future: S,
97}
98
99impl<T, S> Future for Timeout<T, S>
100where
101 T: Future,
102 S: Future<Output = ()>,
103{
104 type Output = Result<T::Output, TimeoutError>;
105
106 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
107 let this = self.project();
108 if let Poll::Ready(x) = this.future.poll(cx) {
109 return Poll::Ready(Ok(x));
110 }
111
112 match this.sleep_future.poll(cx) {
113 Poll::Pending => Poll::Pending,
114 Poll::Ready(()) => Poll::Ready(Err(TimeoutError)),
115 }
116 }
117}
118
119pub struct SleepUntilWallclock<'a, SP: SleepProvider> {
121 provider: &'a SP,
123 target: SystemTime,
125 sleep_future: Option<Pin<Box<SP::SleepFuture>>>,
127}
128
129impl<'a, SP> Future for SleepUntilWallclock<'a, SP>
130where
131 SP: SleepProvider,
132{
133 type Output = ();
134
135 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
136 let target = self.target;
142 loop {
143 let now = self.provider.wallclock();
144 if now >= target {
145 return Poll::Ready(());
146 }
147
148 let (last_delay, delay) = calc_next_delay(now, target);
149
150 self.sleep_future.take();
157
158 let mut sleep_future = Box::pin(self.provider.sleep(delay));
159 match sleep_future.poll_unpin(cx) {
160 Poll::Pending => {
161 self.sleep_future = Some(sleep_future);
162 return Poll::Pending;
163 }
164 Poll::Ready(()) => {
165 if last_delay {
166 return Poll::Ready(());
167 }
168 }
169 }
170 }
171 }
172}
173
174const MAX_SLEEP: Duration = Duration::from_secs(600);
180
181pub(crate) fn calc_next_delay(now: SystemTime, when: SystemTime) -> (bool, Duration) {
187 let remainder = when
188 .duration_since(now)
189 .unwrap_or_else(|_| Duration::from_secs(0));
190 if remainder > MAX_SLEEP {
191 (false, MAX_SLEEP)
192 } else {
193 (true, remainder)
194 }
195}
196
197#[cfg(test)]
198mod test {
199 #![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)] #![allow(clippy::erasing_op)]
214 use web_time_compat::SystemTimeExt;
215
216 #[cfg(not(miri))]
217 use super::*;
218
219 #[cfg(not(miri))] #[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}