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
9pub 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 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 let waker = RuntimeWaker::start(Duration::from_secs(60)).unwrap().unwrap();
77
78 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 start_rx.recv_timeout(Duration::from_secs(2)).unwrap();
89
90 let (stopped_tx, stopped_rx) = mpsc::channel();
92 let thread = thread::spawn(move || {
93 drop(waker);
94 let _ = stopped_tx.send(());
95 });
96
97 let result = stopped_rx.recv_timeout(Duration::from_secs(2));
100
101 drop(release_tx);
104 blocker.await.unwrap();
105 thread.join().unwrap();
106 assert!(result.is_ok());
107 }
108}