Skip to main content

aft_base/
shared_timer.rs

1//! Process-wide deadlines. Callbacks only check state or enqueue work: blocking
2//! I/O and cache destruction belong on the caller's existing work pool.
3
4use std::collections::{BTreeMap, HashMap};
5use std::io;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Condvar, Mutex, OnceLock};
8use std::time::Instant;
9
10type Callback = Box<dyn FnMut() -> Option<Instant> + Send>;
11type Key = (Instant, u64);
12
13struct Entry {
14    active: Arc<AtomicBool>,
15    fire: Callback,
16}
17
18#[derive(Default)]
19struct Queue {
20    next_id: u64,
21    deadlines: BTreeMap<Key, Entry>,
22    keys: HashMap<u64, Key>,
23}
24
25#[derive(Default)]
26struct Service {
27    queue: Mutex<Queue>,
28    wake: Condvar,
29}
30
31fn service() -> io::Result<&'static Arc<Service>> {
32    static SERVICE: OnceLock<Result<Arc<Service>, String>> = OnceLock::new();
33    SERVICE
34        .get_or_init(|| {
35            let service = Arc::new(Service::default());
36            let worker = Arc::clone(&service);
37            std::thread::Builder::new()
38                .name("aft-shared-timer".into())
39                .spawn(move || worker.run())
40                .map_err(|error| error.to_string())?;
41            Ok(service)
42        })
43        .as_ref()
44        .map_err(|error| io::Error::other(error.clone()))
45}
46
47impl Service {
48    fn run(&self) {
49        loop {
50            let mut queue = self.queue.lock().unwrap_or_else(|e| e.into_inner());
51            let Some((&(at, id), _)) = queue.deadlines.first_key_value() else {
52                drop(self.wake.wait(queue).unwrap_or_else(|e| e.into_inner()));
53                continue;
54            };
55            let now = Instant::now();
56            if now < at {
57                drop(
58                    self.wake
59                        .wait_timeout(queue, at - now)
60                        .unwrap_or_else(|e| e.into_inner()),
61                );
62                continue;
63            }
64            let mut entry = queue.deadlines.remove(&(at, id)).unwrap();
65            queue.keys.remove(&id);
66            drop(queue);
67            if !entry.active.load(Ordering::Acquire) {
68                continue;
69            }
70            // A bad callback must not disable every root's deadlines.
71            let next = std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut entry.fire));
72            if let Ok(Some(at)) = next {
73                let mut queue = self.queue.lock().unwrap_or_else(|e| e.into_inner());
74                if entry.active.load(Ordering::Acquire) {
75                    queue.keys.insert(id, (at, id));
76                    queue.deadlines.insert((at, id), entry);
77                }
78            }
79        }
80    }
81}
82
83/// Cancels a pending deadline on drop, removing its callback immediately. A
84/// callback already being dispatched must also fence its work with the root's
85/// lifecycle (usually a weak owner and the executor's cancellation token).
86pub struct Timer {
87    service: &'static Arc<Service>,
88    id: u64,
89    active: Arc<AtomicBool>,
90}
91
92impl Timer {
93    #[cfg(any(test, feature = "test-support"))]
94    pub fn registration_for_test(&self) -> u64 {
95        self.id
96    }
97
98    #[cfg(any(test, feature = "test-support"))]
99    pub fn registered_for_test(id: u64) -> bool {
100        service()
101            .unwrap()
102            .queue
103            .lock()
104            .unwrap()
105            .keys
106            .contains_key(&id)
107    }
108
109    #[cfg(all(any(test, feature = "test-support"), target_os = "linux"))]
110    pub fn deadline_for_test(id: u64) -> Option<Instant> {
111        service()
112            .unwrap()
113            .queue
114            .lock()
115            .unwrap()
116            .keys
117            .get(&id)
118            .map(|key| key.0)
119    }
120
121    pub fn at(
122        at: Instant,
123        fire: impl FnMut() -> Option<Instant> + Send + 'static,
124    ) -> io::Result<Self> {
125        let service = service()?;
126        let active = Arc::new(AtomicBool::new(true));
127        let mut queue = service.queue.lock().unwrap_or_else(|e| e.into_inner());
128        let id = queue.next_id;
129        queue.next_id = queue.next_id.checked_add(1).expect("timer id exhausted");
130        queue.keys.insert(id, (at, id));
131        queue.deadlines.insert(
132            (at, id),
133            Entry {
134                active: Arc::clone(&active),
135                fire: Box::new(fire),
136            },
137        );
138        service.wake.notify_one();
139        Ok(Self {
140            service,
141            id,
142            active,
143        })
144    }
145}
146
147impl Drop for Timer {
148    fn drop(&mut self) {
149        self.active.store(false, Ordering::Release);
150        let mut queue = self.service.queue.lock().unwrap_or_else(|e| e.into_inner());
151        let removed = queue
152            .keys
153            .remove(&self.id)
154            .and_then(|key| queue.deadlines.remove(&key));
155        self.service.wake.notify_one();
156        drop(queue);
157        drop(removed);
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use std::sync::mpsc;
165    use std::time::Duration;
166
167    #[test]
168    fn deadlines_rearm_cancel_and_survive_panics() {
169        let (tx, rx) = mpsc::channel();
170        let start = Instant::now();
171        let mut count = 0;
172        let _timer = Timer::at(start, move || {
173            count += 1;
174            tx.send((count, Instant::now())).unwrap();
175            (count == 1).then_some(start + Duration::from_millis(30))
176        })
177        .unwrap();
178        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap().0, 1);
179        let (count, at) = rx.recv_timeout(Duration::from_secs(2)).unwrap();
180        assert_eq!(count, 2);
181        assert!(at >= start + Duration::from_millis(30));
182
183        let (tx, rx) = mpsc::channel();
184        let timer = Timer::at(Instant::now() + Duration::from_millis(30), move || {
185            tx.send(()).unwrap();
186            None
187        })
188        .unwrap();
189        drop(timer);
190        assert!(rx.recv_timeout(Duration::from_millis(60)).is_err());
191
192        let _panic = Timer::at(Instant::now(), || panic!("isolated callback panic")).unwrap();
193        let (tx, rx) = mpsc::channel();
194        let _later = Timer::at(Instant::now() + Duration::from_millis(10), move || {
195            tx.send(()).unwrap();
196            None
197        })
198        .unwrap();
199        rx.recv_timeout(Duration::from_secs(2)).unwrap();
200    }
201}