Skip to main content

ntpsec_rs_core/
ntp_timer.rs

1// ──── ntp_timer.rs ──────────────────────────────────────────────────────────
2// Forensic reconstruction of ntpd/ntp_timer.c (14K)
3//
4// NTP timer event system — manages poll timers, reachability updates,
5// housekeeping, and periodic statistics output.
6// =============================================================================
7
8use crate::ntp_types::*;
9
10/// Timer event types — matching ntpsec's timer event system.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum TimerEvent {
13    /// Send a poll to a peer (peer index).
14    Poll(usize),
15    /// Update reachability registers for all peers.
16    Reachability,
17    /// Periodic housekeeping (clock selection, combine, etc.).
18    Housekeeping,
19    /// Reload the leap second file.
20    LeapFileReload,
21    /// Write statistics to filegen files.
22    StatsWrite,
23}
24
25/// A scheduled timer entry.
26#[derive(Debug, Clone)]
27pub struct TimerEntry {
28    pub event: TimerEvent,
29    /// Absolute NTP seconds when this fires.
30    pub due: i64,
31    /// Repeating interval in seconds. 0 = one-shot.
32    pub interval: u32,
33}
34
35impl TimerEntry {
36    pub fn new(event: TimerEvent, due: i64, interval: u32) -> Self {
37        Self {
38            event,
39            due,
40            interval,
41        }
42    }
43
44    /// Advance this entry to the next due time strictly after `now`.
45    /// Returns the number of missed intervals (0 if none).
46    pub fn advance_past(&mut self, now: i64) -> u64 {
47        if self.interval == 0 || self.due > now {
48            return 0;
49        }
50        let missed = ((now - self.due) / self.interval as i64 + 1) as u64;
51        self.due += missed as i64 * self.interval as i64;
52        missed
53    }
54}
55
56/// Timer queue — manages scheduled events.
57#[derive(Debug, Default)]
58pub struct TimerQueue {
59    entries: Vec<TimerEntry>,
60}
61
62impl TimerQueue {
63    pub fn new() -> Self {
64        Self {
65            entries: Vec::new(),
66        }
67    }
68
69    pub fn add(&mut self, entry: TimerEntry) {
70        self.entries.push(entry);
71    }
72
73    /// Remove all entries matching a predicate.
74    pub fn remove(&mut self, predicate: impl Fn(&TimerEvent) -> bool) {
75        self.entries.retain(|e| !predicate(&e.event));
76    }
77
78    /// Schedule a poll for a peer (repeating).
79    pub fn schedule_poll(&mut self, peer_id: usize, now: i64, interval: u32) {
80        self.add(TimerEntry::new(
81            TimerEvent::Poll(peer_id),
82            now + interval as i64,
83            interval,
84        ));
85    }
86
87    /// Schedule a single one-shot poll for a peer (interval=0, dropped after firing).
88    pub fn schedule_poll_once(&mut self, peer_id: usize, due: i64) {
89        self.add(TimerEntry::new(TimerEvent::Poll(peer_id), due, 0));
90    }
91
92    /// Pop all due events, advancing repeating entries past `now`.
93    /// Returns the events that fired.
94    pub fn pop_due(&mut self, now: NtpTs64) -> Vec<TimerEvent> {
95        let now_secs = now.seconds;
96        let mut fired = Vec::new();
97        let mut keep = Vec::new();
98
99        for mut entry in self.entries.drain(..) {
100            if entry.due <= now_secs {
101                fired.push(entry.event);
102                if entry.interval > 0 {
103                    entry.advance_past(now_secs);
104                    keep.push(entry);
105                }
106                // one-shot entries (interval==0) are dropped
107            } else {
108                keep.push(entry);
109            }
110        }
111        self.entries = keep;
112        fired
113    }
114
115    /// Get the number of entries.
116    pub fn len(&self) -> usize {
117        self.entries.len()
118    }
119    pub fn is_empty(&self) -> bool {
120        self.entries.is_empty()
121    }
122
123    /// Get the next absolute deadline (in NTP seconds), or None if no timers.
124    pub fn next_deadline(&self) -> Option<i64> {
125        self.entries.iter().map(|e| e.due).min()
126    }
127
128    /// Get the deadline as a millisecond timeout suitable for poll/epoll.
129    /// Returns -1 (infinite) when there are no timers, or the timeout in ms
130    /// (capped at 0 minimum — never return a negative timeout for poll).
131    pub fn poll_timeout_ms(&self, now_seconds: i64) -> i32 {
132        match self.next_deadline() {
133            Some(t) => {
134                let secs = t - now_seconds;
135                if secs <= 0 {
136                    0 // Timer already due — poll returns immediately
137                } else {
138                    // Clamp to avoid overflow when converting to ms
139                    (secs.min(3600) as i32) * 1000
140                }
141            }
142            None => -1, // No timers — wait indefinitely
143        }
144    }
145
146    /// Iterate over all entries.
147    pub fn iter(&self) -> impl Iterator<Item = &TimerEntry> {
148        self.entries.iter()
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_timer_entry_new() {
158        let entry = TimerEntry::new(TimerEvent::Poll(0), 1000, 64);
159        assert_eq!(entry.due, 1000);
160        assert_eq!(entry.interval, 64);
161    }
162
163    #[test]
164    fn test_timer_advance_past() {
165        let mut entry = TimerEntry::new(TimerEvent::Poll(0), 1000, 64);
166        let missed = entry.advance_past(1100);
167        assert!(missed >= 1);
168        assert!(entry.due > 1100);
169    }
170
171    #[test]
172    fn test_timer_queue_pop_due() {
173        let mut queue = TimerQueue::new();
174        queue.add(TimerEntry::new(TimerEvent::Poll(0), 100, 64));
175        queue.add(TimerEntry::new(TimerEvent::Housekeeping, 200, 128));
176
177        let now = NtpTs64 {
178            seconds: 150,
179            fraction: 0,
180        };
181        let fired = queue.pop_due(now);
182        assert_eq!(fired.len(), 1);
183        assert!(matches!(fired[0], TimerEvent::Poll(0)));
184
185        // Entry should have been re-added for the next interval
186        assert_eq!(queue.len(), 2);
187    }
188
189    #[test]
190    fn test_timer_one_shot_dropped() {
191        let mut queue = TimerQueue::new();
192        queue.add(TimerEntry::new(TimerEvent::Poll(0), 100, 0)); // one-shot
193        let now = NtpTs64 {
194            seconds: 200,
195            fraction: 0,
196        };
197        let fired = queue.pop_due(now);
198        assert_eq!(fired.len(), 1);
199        assert_eq!(queue.len(), 0); // should be removed
200    }
201
202    #[test]
203    fn test_schedule_poll() {
204        let mut queue = TimerQueue::new();
205        queue.schedule_poll(0, 1000, 64);
206        assert_eq!(queue.len(), 1);
207    }
208}