Skip to main content

rocket/util/
waker.rs

1use std::{io, thread};
2use std::sync::{mpsc, Arc};
3use std::task::Poll;
4use std::time::Duration;
5
6use futures::{future::poll_fn, task::AtomicWaker};
7use tokio::runtime::{Handle, RuntimeFlavor};
8
9/// Keeps an idle worker checking I/O and timers when another worker blocks.
10pub struct RuntimeWaker {
11    stop_tx: mpsc::Sender<()>,
12    thread: Option<thread::JoinHandle<()>>,
13}
14
15impl RuntimeWaker {
16    pub(crate) fn start(interval: Duration) -> io::Result<Option<Self>> {
17        let runtime = Handle::current();
18        if interval.is_zero() || runtime.runtime_flavor() != RuntimeFlavor::MultiThread {
19            return Ok(None);
20        }
21
22        let (stop_tx, stop_rx) = mpsc::channel();
23        let thread = thread::Builder::new()
24            .name("rocket-runtime-waker".into())
25            .spawn(move || {
26                let waker = Arc::new(AtomicWaker::new());
27                let task = runtime.spawn({
28                    let waker = waker.clone();
29                    poll_fn(move |cx| {
30                        waker.register(cx.waker());
31                        Poll::<()>::Pending
32                    })
33                });
34
35                // Wake from outside Tokio so an idle worker can take over.
36                // Reusing one task coalesces ticks when no worker can make
37                // progress. See https://github.com/tokio-rs/tokio/issues/4730.
38                while let Err(mpsc::RecvTimeoutError::Timeout) = stop_rx.recv_timeout(interval) {
39                    waker.wake();
40                }
41
42                task.abort();
43            })?;
44
45        Ok(Some(Self { stop_tx, thread: Some(thread) }))
46    }
47}
48
49impl Drop for RuntimeWaker {
50    fn drop(&mut self) {
51        let _ = self.stop_tx.send(());
52        if let Some(thread) = self.thread.take() {
53            let _ = thread.join();
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[tokio::test]
63    async fn skips_current_thread_runtime() {
64        assert!(RuntimeWaker::start(Duration::from_secs(1)).unwrap().is_none());
65    }
66
67    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
68    async fn zero_interval_disables_waker() {
69        assert!(RuntimeWaker::start(Duration::ZERO).unwrap().is_none());
70    }
71
72    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
73    async fn shutdown_completes_with_blocked_worker() {
74        // Ensure that dropping the waker succeeds quickly even when Tokio's
75        // only worker is blocked and the wake interval is long.
76        let waker = RuntimeWaker::start(Duration::from_secs(60)).unwrap().unwrap();
77
78        // This test runs outside Tokio's worker pool. The task sends on
79        // `start_tx`, then occupies the only worker until we drop `release_tx`.
80        let (release_tx, release_rx) = mpsc::channel::<()>();
81        let (start_tx, start_rx) = mpsc::channel();
82        let blocker = tokio::spawn(async move {
83            start_tx.send(()).unwrap();
84            let _ = release_rx.recv();
85        });
86
87        // Wait for the task to start.
88        start_rx.recv_timeout(Duration::from_secs(2)).unwrap();
89
90        // Drop the waker on another thread so this test can enforce the timeout.
91        let (stopped_tx, stopped_rx) = mpsc::channel();
92        let thread = thread::spawn(move || {
93            drop(waker);
94            let _ = stopped_tx.send(());
95        });
96
97        // Receiving on `stopped_rx` proves the waker's destructor returned
98        // within the deadline, without Tokio's blocked worker making progress.
99        let result = stopped_rx.recv_timeout(Duration::from_secs(2));
100
101        // Drop `release_tx` to unblock the worker. Finish cleanup before
102        // asserting, even if the wait timed out.
103        drop(release_tx);
104        blocker.await.unwrap();
105        thread.join().unwrap();
106        assert!(result.is_ok());
107    }
108}