summary refs log tree commit diff
path: root/async_core/src/timerfd.rs
blob: e8ae172629b36f127a77b98315a3e58875954d46 (plain) (blame)
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::future::Future;
use std::os::unix::io::AsRawFd;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use libc::{EWOULDBLOCK, O_NONBLOCK};

use cros_async::Error as ExecutorError;
use cros_async::{add_read_waker, cancel_waker, WakerToken};
use sys_util::{self, add_fd_flags};

/// Errors generated while polling for events.
#[derive(Debug)]
pub enum Error {
    /// An error occurred attempting to register a waker with the executor.
    AddingWaker(ExecutorError),
    /// An error occurred when reading the timer FD.
    TimerFdRead(sys_util::Error),
    /// An error occurred when resetting the timer FD.
    TimerFdReset(sys_util::Error),
    /// An error occurred when setting the timer FD non-blocking.
    SettingNonBlocking(sys_util::Error),
}
pub type Result<T> = std::result::Result<T, Error>;

impl std::error::Error for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::Error::*;

        match self {
            AddingWaker(e) => write!(
                f,
                "An error occurred attempting to register a waker with the executor: {}.",
                e
            ),
            TimerFdRead(e) => write!(f, "An error occurred when reading the timer FD: {}.", e),
            TimerFdReset(e) => write!(f, "An error occurred when resetting the timer FD: {}.", e),
            SettingNonBlocking(e) => {
                write!(f, "An error occurred setting the FD non-blocking: {}.", e)
            }
        }
    }
}

/// Asynchronous version of `sys_util::TimerFd`. Provides a method for asynchronously waiting for a
/// timer to fire.
///
/// # Example
///
/// ```
/// use std::convert::TryInto;
///
/// use async_core::TimerFd;
/// use sys_util::{self, Result};
/// async fn process_events() -> Result<()> {
///     let mut async_timer: TimerFd = sys_util::TimerFd::new()?.try_into().unwrap();
///     while let Ok(e) = async_timer.next_expiration().await {
///         // Handle timer here.
///     }
///     Ok(())
/// }
/// ```
pub struct TimerFd(sys_util::TimerFd);

impl TimerFd {
    /// Reset the inner timer to a new duration.
    pub fn reset(&self, dur: Duration, interval: Option<Duration>) -> Result<()> {
        self.0.reset(dur, interval).map_err(Error::TimerFdReset)
    }

    /// Asynchronously wait for the timer to fire.
    /// Returns a Future that can be `awaited` for the next interval.
    ///
    /// # Example
    ///
    /// ```
    /// use async_core::TimerFd;
    /// async fn print_events(mut timer_fd: TimerFd) {
    ///     loop {
    ///         match timer_fd.next_expiration().await {
    ///             Ok(_) => println!("timer fired"),
    ///             Err(e) => break,
    ///         }
    ///     }
    /// }
    /// ```
    pub fn next_expiration(&self) -> TimerFuture {
        TimerFuture::new(&self.0)
    }
}

impl TryFrom<sys_util::TimerFd> for TimerFd {
    type Error = Error;

    fn try_from(timerfd: sys_util::TimerFd) -> Result<TimerFd> {
        let fd = timerfd.as_raw_fd();
        add_fd_flags(fd, O_NONBLOCK).map_err(Error::SettingNonBlocking)?;
        Ok(TimerFd(timerfd))
    }
}

/// A Future that yields completes when the timer has fired the next time.
pub struct TimerFuture<'a> {
    inner: &'a sys_util::TimerFd,
    waker_token: Option<WakerToken>,
}

impl<'a> TimerFuture<'a> {
    fn new(inner: &'a sys_util::TimerFd) -> TimerFuture<'a> {
        TimerFuture {
            inner,
            waker_token: None,
        }
    }
}

impl<'a> Future for TimerFuture<'a> {
    type Output = Result<u64>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        if let Some(token) = self.waker_token.take() {
            let _ = cancel_waker(token);
        }

        match self.inner.wait() {
            Ok(count) => Poll::Ready(Ok(count)),
            Err(e) => {
                if e.errno() == EWOULDBLOCK {
                    match add_read_waker(self.inner.as_raw_fd(), cx.waker().clone()) {
                        Ok(token) => {
                            self.waker_token = Some(token);
                            Poll::Pending
                        }
                        Err(e) => Poll::Ready(Err(Error::AddingWaker(e))),
                    }
                } else {
                    // Indicate something went wrong and no more events will be provided.
                    Poll::Ready(Err(Error::TimerFdRead(e)))
                }
            }
        }
    }
}

impl<'a> Drop for TimerFuture<'a> {
    fn drop(&mut self) {
        if let Some(token) = self.waker_token.take() {
            let _ = cancel_waker(token);
        }
    }
}

impl AsRef<sys_util::TimerFd> for TimerFd {
    fn as_ref(&self) -> &sys_util::TimerFd {
        &self.0
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use cros_async::{run_one, select2, SelectResult};
    use futures::future::pending;
    use futures::future::Either;
    use futures::pin_mut;

    use super::*;

    #[test]
    fn timer_timeout() {
        async fn timeout(duration: Duration) -> u64 {
            let t = sys_util::TimerFd::new().unwrap();
            let async_timer = TimerFd::try_from(t).unwrap();
            async_timer.reset(duration, None).unwrap();
            async_timer.next_expiration().await.unwrap()
        }

        let to = timeout(Duration::from_millis(10));
        pin_mut!(to);
        if let Ok((SelectResult::Finished(timer_count), SelectResult::Pending(_pend_fut))) =
            select2(to, pending::<()>())
        {
            assert_eq!(timer_count, 1);
        } else {
            panic!("wrong futures returned from select2");
        }
    }

    #[test]
    fn select_with_eventfd() {
        async fn async_test() {
            let mut e = crate::eventfd::EventFd::new().unwrap();
            let t = sys_util::TimerFd::new().unwrap();
            let async_timer = TimerFd::try_from(t).unwrap();
            async_timer.reset(Duration::from_millis(10), None).unwrap();
            let timer = async_timer.next_expiration();
            let event = e.read_next();
            pin_mut!(timer);
            pin_mut!(event);
            match futures::future::select(timer, event).await {
                Either::Left((_timer, _event)) => (),
                _ => panic!("unexpected select result"),
            }
        }

        let fut = async_test();

        run_one(Box::pin(fut)).unwrap();
    }

    #[test]
    fn pend_unarmed_cancel() {
        async fn async_test() {
            let t = sys_util::TimerFd::new().unwrap();
            let async_timer = TimerFd::try_from(t).unwrap();
            let done = async {
                std::thread::sleep(Duration::from_millis(10));
                5usize
            };
            let timer = async_timer.next_expiration();
            pin_mut!(done);
            pin_mut!(timer);
            match futures::future::select(timer, done).await {
                Either::Right((_, _timer)) => (),
                _ => panic!("unexpected select result"),
            }
        }

        let fut = async_test();

        run_one(Box::pin(fut)).unwrap();
    }
}