Skip to main content

ntpsec_rs_core/
ntp_filegen.rs

1// ──── ntp_filegen.rs ────────────────────────────────────────────────────────
2// Forensic reconstruction of ntpd/ntp_filegen.c
3//
4// Statistics file generation: manages `filegen` directives for loopstats,
5// peerstats, and clockstats output files.
6// =============================================================================
7
8use std::io::Write;
9use std::path::Path;
10use std::time::SystemTime;
11
12use crate::ntp_peer::Peer;
13use crate::ntp_proto::SystemState;
14#[cfg(test)]
15use crate::ntp_types::{NtpMode, NtpVersion};
16
17/// File generation type (matches ntpsec).
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum FileGenType {
20    Day,   // Rotate daily
21    Week,  // Rotate weekly
22    Month, // Rotate monthly
23    Year,  // Rotate yearly
24    Age,   // Age-based deletion
25    Pid,   // Include PID in filename
26}
27
28/// File generation entry.
29#[derive(Debug, Clone)]
30pub struct FileGenEntry {
31    pub name: String,
32    pub file_name: String,
33    pub gen_type: FileGenType,
34    pub enabled: bool,
35}
36
37/// Maximum number of rotated backup files to keep.
38pub const FILEGEN_MAX_BACKUP: u32 = 8;
39
40/// Open file handles for active file generation entries.
41#[derive(Debug, Default)]
42pub struct FileGenRegistry {
43    entries: Vec<FileGenEntry>,
44    /// Open file handles for active statistics writers.
45    files: Vec<(String, Option<std::fs::File>)>,
46}
47
48/// Helper: get a stable time-zone–agnostic calendar day number (days since epoch).
49fn calendar_day(t: &SystemTime) -> u64 {
50    t.duration_since(std::time::UNIX_EPOCH)
51        .unwrap_or_default()
52        .as_secs()
53        / 86400
54}
55
56/// Helper: get a week key (days/7 since epoch) for rotation comparison.
57/// Changes every ~7 days, sufficient for "different week" detection.
58fn week_key(t: &SystemTime) -> i64 {
59    let days = t
60        .duration_since(std::time::UNIX_EPOCH)
61        .unwrap_or_default()
62        .as_secs()
63        / 86400;
64    (days / 7) as i64
65}
66
67/// Helper: days since epoch for a given year/month/day.
68/// Returns i64 to handle dates before 1970 (e.g., for ISO week calculations).
69fn days_since_epoch(year: u32, month: u32, day: u32) -> i64 {
70    let y = year as i64;
71    let m = month as i64;
72    let d = day as i64;
73    let a = (14 - m) / 12;
74    let yy = y + 4800 - a;
75    let mm = m + 12 * a - 3;
76    let jdn = d + (153 * mm + 2) / 5 + 365 * yy + yy / 4 - yy / 100 + yy / 400 - 32045;
77    jdn - 2440588 // offset to Unix epoch
78}
79
80impl FileGenRegistry {
81    pub fn new() -> Self {
82        Self {
83            entries: Vec::new(),
84            files: Vec::new(),
85        }
86    }
87
88    pub fn add(&mut self, entry: FileGenEntry) {
89        self.entries.push(entry);
90    }
91
92    pub fn get(&self, name: &str) -> Option<&FileGenEntry> {
93        self.entries.iter().find(|e| e.name == name)
94    }
95
96    pub fn get_mut(&mut self, name: &str) -> Option<&mut FileGenEntry> {
97        self.entries.iter_mut().find(|e| e.name == name)
98    }
99
100    /// Open a file for a specific entry by name.
101    /// Creates the parent directory if it doesn't exist.
102    pub fn open(&mut self, name: &str, stat_dir: &Path) -> Result<(), String> {
103        if let Some(entry) = self.entries.iter().find(|e| e.name == name) {
104            if entry.enabled {
105                let path = stat_dir.join(&entry.file_name);
106                if let Some(parent) = path.parent() {
107                    std::fs::create_dir_all(parent).map_err(|e| {
108                        format!("cannot create stats dir '{}': {}", parent.display(), e)
109                    })?;
110                }
111                let file = std::fs::OpenOptions::new()
112                    .create(true)
113                    .append(true)
114                    .open(&path)
115                    .map_err(|e| format!("cannot open stats file '{}': {}", path.display(), e))?;
116                // Remove any existing handle for this name
117                self.files.retain(|(n, _)| n != name);
118                self.files.push((name.to_string(), Some(file)));
119            }
120        }
121        Ok(())
122    }
123
124    /// Check if the file for an entry needs rotation based on its `FileGenType`
125    /// and the current time. If rotation is needed, the current file is renamed
126    /// to a numbered backup (name.0, name.1, ...) and a new file is opened.
127    ///
128    /// Rotation rules:
129    /// - `Day`:   rotate if the file was last written on a different calendar day
130    /// - `Week`:  rotate if the file was last written in a different ISO week
131    /// - `Month`: rotate if the file was last written in a different month
132    /// - `Year`:  rotate if the file was last written in a different year
133    /// - `Age`:   time-based rotation is not performed (age-based deletion is separate)
134    /// - `Pid`:   rotation is not performed (PID-based filenames are unique per run)
135    pub fn rotate_if_needed(&mut self, name: &str, stat_dir: &Path) -> Result<(), String> {
136        // Find the entry
137        let entry = match self.entries.iter().find(|e| e.name == name) {
138            Some(e) => e.clone(),
139            None => return Ok(()),
140        };
141
142        if !entry.enabled {
143            return Ok(());
144        }
145
146        // Determine whether rotation is needed based on gen_type
147        let now = SystemTime::now();
148        let path = stat_dir.join(&entry.file_name);
149
150        // Get the file's modification time; if the file doesn't exist, no rotation needed
151        let mtime = match std::fs::metadata(&path) {
152            Ok(meta) => match meta.modified() {
153                Ok(t) => t,
154                Err(_) => return Ok(()), // Can't determine mtime; skip rotation
155            },
156            Err(_) => return Ok(()), // File doesn't exist yet; no rotation
157        };
158
159        let needs_rotation = match entry.gen_type {
160            FileGenType::Day => calendar_day(&now) != calendar_day(&mtime),
161            FileGenType::Week => week_key(&now) != week_key(&mtime),
162            FileGenType::Month => {
163                // Compare (year, month) pairs
164                month_key(&now) != month_key(&mtime)
165            }
166            FileGenType::Year => year_of(&now) != year_of(&mtime),
167            FileGenType::Age | FileGenType::Pid => false,
168        };
169
170        if !needs_rotation {
171            return Ok(());
172        }
173
174        // ── Perform the rotation ────────────────────────────────────────
175        // Close the current file handle for this name
176        if let Some((_, ref mut file_opt)) = self.files.iter_mut().find(|(n, _)| n == name) {
177            let _ = file_opt.take(); // Close by dropping the handle
178        }
179
180        // Shift backups: name.7 -> name.8, ..., name.0 -> name.1
181        for i in (0..FILEGEN_MAX_BACKUP).rev() {
182            let src = path.with_extension(format!("{}", i));
183            let dst = path.with_extension(format!("{}", i + 1));
184            let _ = std::fs::rename(&src, &dst);
185        }
186
187        // Rename current file to name.0
188        if path.exists() {
189            let backup = path.with_extension("0");
190            let _ = std::fs::rename(&path, &backup);
191        }
192
193        // Open a new file
194        self.open(name, stat_dir)?;
195
196        Ok(())
197    }
198
199    /// Format a loopstats line: MJD secs offset freq_ppm jitter
200    /// Returns the formatted line WITHOUT the write/rotation side effects.
201    pub fn format_loopstats(&self, sys: &SystemState, freq_ppm: f64) -> String {
202        let now = std::time::SystemTime::now()
203            .duration_since(std::time::UNIX_EPOCH)
204            .unwrap_or_default();
205        let mjd = now.as_secs() / 86400 + 40587;
206        let secs = now.as_secs() % 86400;
207        format!(
208            "{} {} {} {:.6} {:.3} {:.6}",
209            mjd, secs, 0i64, sys.sys_offset, freq_ppm, sys.sys_jitter
210        )
211    }
212
213    /// Format a peerstats line: MJD secs associd offset delay dispersion reach
214    pub fn format_peerstats(&self, peer: &Peer) -> String {
215        let now = std::time::SystemTime::now()
216            .duration_since(std::time::UNIX_EPOCH)
217            .unwrap_or_default();
218        let mjd = now.as_secs() / 86400 + 40587;
219        let secs = now.as_secs() % 86400;
220        format!(
221            "{} {} {} {:.6} {:.6} {:.6} {}",
222            mjd,
223            secs,
224            peer.associd,
225            peer.offset,
226            peer.delay,
227            peer.dispersion,
228            peer.reach.register()
229        )
230    }
231
232    /// Write a loopstats entry: MJD secs offset freq_ppm jitter
233    pub fn write_loopstats(
234        &mut self,
235        path: &Path,
236        sys: &SystemState,
237        freq_ppm: f64,
238    ) -> Result<(), String> {
239        // Check and perform rotation before writing
240        if let Some(parent) = path.parent() {
241            self.rotate_if_needed("loopstats", parent)?;
242        }
243        let content = self.format_loopstats(sys, freq_ppm);
244        let mut line = content;
245        line.push('\n');
246        write_stat_file_ex(
247            path,
248            &line,
249            self.files.iter_mut().find(|(n, _)| n == "loopstats"),
250        )
251    }
252
253    /// Write a peerstats entry: MJD secs associd offset delay dispersion reach
254    pub fn write_peerstats(&mut self, path: &Path, peer: &Peer) -> Result<(), String> {
255        // Check and perform rotation before writing
256        if let Some(parent) = path.parent() {
257            self.rotate_if_needed("peerstats", parent)?;
258        }
259        let content = self.format_peerstats(peer);
260        let mut line = content;
261        line.push('\n');
262        write_stat_file_ex(
263            path,
264            &line,
265            self.files.iter_mut().find(|(n, _)| n == "peerstats"),
266        )
267    }
268
269    /// Write a clockstats entry: MJD secs associd log message
270    pub fn write_clockstats(
271        &mut self,
272        path: &Path,
273        associd: u16,
274        message: &str,
275    ) -> Result<(), String> {
276        // Check and perform rotation before writing
277        if let Some(parent) = path.parent() {
278            self.rotate_if_needed("clockstats", parent)?;
279        }
280        let now = std::time::SystemTime::now()
281            .duration_since(std::time::UNIX_EPOCH)
282            .unwrap_or_default();
283        let mjd = now.as_secs() / 86400 + 40587;
284        let secs = now.as_secs() % 86400;
285        let content = format!("{} {} {} {}\n", mjd, secs, associd, message);
286        write_stat_file_ex(
287            path,
288            &content,
289            self.files.iter_mut().find(|(n, _)| n == "clockstats"),
290        )
291    }
292
293    /// Flush all open file handles by calling `sync_all()` on each.
294    pub fn flush_all(&mut self) -> Result<(), String> {
295        for (_, file_opt) in self.files.iter_mut() {
296            if let Some(file) = file_opt {
297                file.sync_all()
298                    .map_err(|e| format!("flush_all failed: {}", e))?;
299            }
300        }
301        Ok(())
302    }
303
304    /// Close all open file handles by taking them (dropping replaces with None)
305    /// and then clearing the list. Each file's Drop impl will flush and close.
306    pub fn close_all(&mut self) {
307        for (_, file_opt) in self.files.iter_mut() {
308            let _ = file_opt.take();
309        }
310        self.files.clear();
311    }
312}
313
314/// Maximum file size before rotation (10MB default).
315pub const FILEGEN_MAX_SIZE: u64 = 10 * 1024 * 1024;
316
317/// Rotate a statistics file when it exceeds `FILEGEN_MAX_SIZE`.
318pub fn rotate_file(path: &Path) -> Result<(), String> {
319    if let Ok(meta) = std::fs::metadata(path) {
320        if meta.len() > FILEGEN_MAX_SIZE {
321            // Rotate: file -> file.0, file.0 -> file.1, etc.
322            for i in (1..=9).rev() {
323                let old = path.with_extension(format!("{}", i));
324                let new = path.with_extension(format!("{}", i + 1));
325                let _ = std::fs::rename(&old, &new);
326            }
327            let backup = path.with_extension("1");
328            let _ = std::fs::rename(path, &backup);
329        }
330    }
331    Ok(())
332}
333
334/// Open and write to a statistics file.
335pub fn write_stat_file(path: &Path, content: &str) -> Result<(), String> {
336    if let Some(parent) = path.parent() {
337        std::fs::create_dir_all(parent)
338            .map_err(|e| format!("cannot create stats dir '{}': {}", parent.display(), e))?;
339    }
340    let mut file = std::fs::OpenOptions::new()
341        .create(true)
342        .append(true)
343        .open(path)
344        .map_err(|e| format!("cannot open stats file '{}': {}", path.display(), e))?;
345    writeln!(file, "{}", content)
346        .map_err(|e| format!("cannot write to stats file '{}': {}", path.display(), e))?;
347    // Rotate if needed
348    let _ = rotate_file(path);
349    Ok(())
350}
351
352/// Write to a statistics file, using an open file handle if available.
353/// If a file handle is provided, writes to it and checks rotation;
354/// otherwise falls back to the standard open-write-rotate path.
355fn write_stat_file_ex(
356    path: &Path,
357    content: &str,
358    handle: Option<&mut (String, Option<std::fs::File>)>,
359) -> Result<(), String> {
360    if let Some((_, Some(ref mut file))) = handle {
361        use std::io::Write;
362        file.write_all(content.as_bytes())
363            .map_err(|e| format!("cannot write to stats file '{}': {}", path.display(), e))?;
364        // Check rotation after write
365        let _ = rotate_file(path);
366        Ok(())
367    } else {
368        write_stat_file(path, content)
369    }
370}
371
372/// Helper: extract a month key (year * 12 + month) from a SystemTime.
373fn month_key(t: &SystemTime) -> i64 {
374    let dur = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
375    let days = dur.as_secs() / 86400;
376    let y = 1970f64 + days as f64 / 365.2425;
377    let year = y as i64;
378    // Number of days from year start
379    let year_start_days = days_since_epoch(year as u32, 1, 1);
380    let day_of_year = (days as i64).saturating_sub(year_start_days);
381    let month = (day_of_year as f64 / 30.44).floor() as i64;
382    let month = month.clamp(0, 11);
383    year * 12 + month
384}
385
386/// Helper: extract a year from a SystemTime.
387fn year_of(t: &SystemTime) -> i64 {
388    let dur = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
389    let secs = dur.as_secs();
390    // Average seconds per Gregorian year = 365.2425 * 86400 = 31556952
391    let y = 1970f64 + (secs as f64) / 31_556_952.0;
392    y as i64
393}
394
395// ── Tests ──────────────────────────────────────────────────────────────────
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use std::path::PathBuf;
401    use std::time::Duration;
402
403    /// A helper that creates a temporary directory and returns its path.
404    /// Uses a unique subdirectory per call to avoid race conditions in parallel tests.
405    fn tmp_dir() -> PathBuf {
406        let base = std::env::temp_dir().join(format!("ntp_filegen_test_{}", std::process::id()));
407        let _ = std::fs::create_dir_all(&base);
408        // Create a unique subdirectory using a timestamp + counter
409        let unique = format!(
410            "test_{}",
411            std::time::SystemTime::now()
412                .duration_since(std::time::UNIX_EPOCH)
413                .unwrap_or_default()
414                .as_nanos()
415        );
416        let path = base.join(unique);
417        let _ = std::fs::create_dir_all(&path);
418        path
419    }
420
421    fn cleanup(dir: &Path) {
422        let _ = std::fs::remove_dir_all(dir);
423    }
424
425    #[test]
426    fn test_filegen_registry_new() {
427        let reg = FileGenRegistry::new();
428        assert!(reg.entries.is_empty());
429        assert!(reg.files.is_empty());
430    }
431
432    #[test]
433    fn test_filegen_add_and_get() {
434        let mut reg = FileGenRegistry::new();
435        reg.add(FileGenEntry {
436            name: "loopstats".to_string(),
437            file_name: "loopstats".to_string(),
438            gen_type: FileGenType::Day,
439            enabled: true,
440        });
441        assert!(reg.get("loopstats").is_some());
442        assert!(reg.get("peerstats").is_none());
443    }
444
445    #[test]
446    fn test_filegen_open_and_write_loopstats() {
447        let dir = tmp_dir();
448        let mut reg = FileGenRegistry::new();
449        reg.add(FileGenEntry {
450            name: "loopstats".to_string(),
451            file_name: "loopstats".to_string(),
452            gen_type: FileGenType::Day,
453            enabled: true,
454        });
455        reg.open("loopstats", &dir).unwrap();
456        let sys = SystemState::new();
457        reg.write_loopstats(&dir.join("loopstats"), &sys, 0.0)
458            .unwrap();
459        let content = std::fs::read_to_string(dir.join("loopstats")).unwrap();
460        assert!(!content.is_empty());
461        cleanup(&dir);
462    }
463
464    #[test]
465    fn test_filegen_open_and_write_peerstats() {
466        let dir = tmp_dir();
467        let mut reg = FileGenRegistry::new();
468        reg.add(FileGenEntry {
469            name: "peerstats".to_string(),
470            file_name: "peerstats".to_string(),
471            gen_type: FileGenType::Day,
472            enabled: true,
473        });
474        reg.open("peerstats", &dir).unwrap();
475
476        // Create a minimal peer
477        let sa: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
478        let mut peer = Peer::new(sa, NtpMode::Client, NtpVersion::V4, 4, 10);
479        peer.associd = 1;
480        reg.write_peerstats(&dir.join("peerstats"), &peer).unwrap();
481        let content = std::fs::read_to_string(dir.join("peerstats")).unwrap();
482        assert!(!content.is_empty());
483        cleanup(&dir);
484    }
485
486    #[test]
487    fn test_filegen_open_and_write_clockstats() {
488        let dir = tmp_dir();
489        let mut reg = FileGenRegistry::new();
490        reg.add(FileGenEntry {
491            name: "clockstats".to_string(),
492            file_name: "clockstats".to_string(),
493            gen_type: FileGenType::Day,
494            enabled: true,
495        });
496        reg.open("clockstats", &dir).unwrap();
497        reg.write_clockstats(&dir.join("clockstats"), 1, "refclock sample 0.001")
498            .unwrap();
499        let content = std::fs::read_to_string(dir.join("clockstats")).unwrap();
500        assert!(!content.is_empty());
501        cleanup(&dir);
502    }
503
504    #[test]
505    fn test_rotate_if_needed_no_rotation_for_same_day() {
506        let dir = tmp_dir();
507        let mut reg = FileGenRegistry::new();
508        reg.add(FileGenEntry {
509            name: "loopstats".to_string(),
510            file_name: "loopstats".to_string(),
511            gen_type: FileGenType::Day,
512            enabled: true,
513        });
514        reg.open("loopstats", &dir).unwrap();
515
516        // Write once (creates the file with current mtime)
517        let sys = SystemState::new();
518        reg.write_loopstats(&dir.join("loopstats"), &sys, 0.0)
519            .unwrap();
520        assert!(dir.join("loopstats").exists());
521
522        // rotate_if_needed should not rotate (same day)
523        reg.rotate_if_needed("loopstats", &dir).unwrap();
524
525        // The file should still exist (not rotated)
526        assert!(dir.join("loopstats").exists());
527        // The backup should NOT exist
528        assert!(!dir.join("loopstats.0").exists());
529
530        cleanup(&dir);
531    }
532
533    #[test]
534    fn test_flush_and_close_all() {
535        let dir = tmp_dir();
536        let mut reg = FileGenRegistry::new();
537        reg.add(FileGenEntry {
538            name: "loopstats".to_string(),
539            file_name: "loopstats".to_string(),
540            gen_type: FileGenType::Day,
541            enabled: true,
542        });
543        reg.open("loopstats", &dir).unwrap();
544        assert_eq!(reg.files.len(), 1);
545        assert!(reg.files[0].1.is_some());
546
547        reg.flush_all().unwrap();
548        reg.close_all();
549        assert_eq!(reg.files.len(), 0);
550        cleanup(&dir);
551    }
552
553    #[test]
554    fn test_rotate_file_size_based() {
555        let dir = tmp_dir();
556        let path = dir.join("teststats");
557        // Write enough content to exceed size threshold
558        let content = "x".repeat((FILEGEN_MAX_SIZE + 100) as usize);
559        std::fs::write(&path, &content).unwrap();
560
561        rotate_file(&path).unwrap();
562        // Original should be renamed to .1
563        assert!(dir.join("teststats.1").exists());
564        // Original path should be gone (rotate_file doesn't recreate it)
565        // The write functions recreate the file after rotation
566        cleanup(&dir);
567    }
568
569    #[test]
570    fn test_rotate_file_does_not_rotate_small_file() {
571        let dir = tmp_dir();
572        let path = dir.join("smallstats");
573        std::fs::write(&path, "small content").unwrap();
574        rotate_file(&path).unwrap();
575        // Should NOT be rotated
576        assert!(dir.join("smallstats").exists());
577        assert!(!dir.join("smallstats.1").exists());
578        cleanup(&dir);
579    }
580
581    #[test]
582    fn test_filegen_disabled_entry() {
583        let dir = tmp_dir();
584        let mut reg = FileGenRegistry::new();
585        reg.add(FileGenEntry {
586            name: "loopstats".to_string(),
587            file_name: "loopstats".to_string(),
588            gen_type: FileGenType::Day,
589            enabled: false,
590        });
591        // Opening a disabled entry should not create a file
592        reg.open("loopstats", &dir).unwrap();
593        assert!(!dir.join("loopstats").exists());
594        cleanup(&dir);
595    }
596
597    #[test]
598    fn test_rotate_if_needed_disabled_entry() {
599        let dir = tmp_dir();
600        let mut reg = FileGenRegistry::new();
601        reg.add(FileGenEntry {
602            name: "loopstats".to_string(),
603            file_name: "loopstats".to_string(),
604            gen_type: FileGenType::Day,
605            enabled: false,
606        });
607        // Should not panic or error for disabled entries
608        reg.rotate_if_needed("loopstats", &dir).unwrap();
609        cleanup(&dir);
610    }
611
612    #[test]
613    fn test_rotate_if_needed_nonexistent_entry() {
614        let dir = tmp_dir();
615        let mut reg = FileGenRegistry::new();
616        // No entry added, so rotate_if_needed should be a no-op
617        reg.rotate_if_needed("nonexistent", &dir).unwrap();
618        cleanup(&dir);
619    }
620
621    #[test]
622    fn test_filegen_type_age_and_pid_no_rotation() {
623        let dir = tmp_dir();
624        for &gen_type in &[FileGenType::Age, FileGenType::Pid] {
625            let mut reg = FileGenRegistry::new();
626            let name = format!("{:?}stats", gen_type).to_lowercase();
627            reg.add(FileGenEntry {
628                name: name.clone(),
629                file_name: name.clone(),
630                gen_type,
631                enabled: true,
632            });
633            reg.open(&name, &dir).unwrap();
634
635            // Write to create the file
636            let _sys = SystemState::new();
637            // Use write_stat_file_ex with no handle to create the file
638            write_stat_file(&dir.join(&name), "test content").unwrap();
639            assert!(dir.join(&name).exists());
640
641            // Rotate should be a no-op for Age and Pid
642            reg.rotate_if_needed(&name, &dir).unwrap();
643            assert!(dir.join(&name).exists());
644            assert!(!dir.join(format!("{}.0", name)).exists());
645        }
646        cleanup(&dir);
647    }
648
649    #[test]
650    fn test_write_stat_file_creates_parent_dir() {
651        let dir = tmp_dir();
652        let nested = dir.join("subdir").join("stats");
653        write_stat_file(&nested, "hello").unwrap();
654        assert!(nested.exists());
655        let content = std::fs::read_to_string(&nested).unwrap();
656        assert!(content.contains("hello"));
657        cleanup(&dir);
658    }
659
660    #[test]
661    fn test_filegen_multiple_entries() {
662        let dir = tmp_dir();
663        let mut reg = FileGenRegistry::new();
664        reg.add(FileGenEntry {
665            name: "loopstats".to_string(),
666            file_name: "loopstats".to_string(),
667            gen_type: FileGenType::Day,
668            enabled: true,
669        });
670        reg.add(FileGenEntry {
671            name: "peerstats".to_string(),
672            file_name: "peerstats".to_string(),
673            gen_type: FileGenType::Week,
674            enabled: true,
675        });
676        reg.add(FileGenEntry {
677            name: "clockstats".to_string(),
678            file_name: "clockstats".to_string(),
679            gen_type: FileGenType::Month,
680            enabled: true,
681        });
682
683        assert_eq!(reg.entries.len(), 3);
684
685        reg.open("loopstats", &dir).unwrap();
686        reg.open("peerstats", &dir).unwrap();
687        reg.open("clockstats", &dir).unwrap();
688
689        // Write to all three
690        let sys = SystemState::new();
691        reg.write_loopstats(&dir.join("loopstats"), &sys, 0.0)
692            .unwrap();
693
694        let sa: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
695        let mut peer = Peer::new(sa, NtpMode::Client, NtpVersion::V4, 4, 10);
696        peer.associd = 42;
697        reg.write_peerstats(&dir.join("peerstats"), &peer).unwrap();
698        reg.write_clockstats(&dir.join("clockstats"), 7, "test")
699            .unwrap();
700
701        assert!(dir.join("loopstats").exists());
702        assert!(dir.join("peerstats").exists());
703        assert!(dir.join("clockstats").exists());
704
705        cleanup(&dir);
706    }
707
708    #[test]
709    fn test_rotate_file_max_backup_count() {
710        let dir = tmp_dir();
711        let path = dir.join("backuptest");
712
713        // Write a large file and rotate multiple times
714        let big_content = "x".repeat((FILEGEN_MAX_SIZE + 10) as usize);
715        for _ in 0..(FILEGEN_MAX_BACKUP + 2) {
716            std::fs::write(&path, &big_content).unwrap();
717            rotate_file(&path).unwrap();
718        }
719
720        // We should have at most FILEGEN_MAX_BACKUP + 1 backup files
721        // (name.1 through name.9)
722        for i in 1..=9 {
723            let _backup = dir.join(format!("backuptest.{}", i));
724            if i as u32 <= FILEGEN_MAX_BACKUP {
725                // The backups may or may not exist depending on the exact sequence
726            }
727        }
728
729        cleanup(&dir);
730    }
731
732    #[test]
733    fn test_calendar_day_helper() {
734        let epoch = std::time::UNIX_EPOCH;
735        assert_eq!(calendar_day(&epoch), 0);
736
737        let one_day = SystemTime::UNIX_EPOCH + Duration::from_secs(86400);
738        assert_eq!(calendar_day(&one_day), 1);
739
740        let one_year = SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 86400);
741        assert_eq!(calendar_day(&one_year), 365);
742    }
743
744    #[test]
745    fn test_days_since_epoch() {
746        // 1970-01-01 should be 0
747        assert_eq!(days_since_epoch(1970, 1, 1), 0);
748        // 1970-01-02 should be 1
749        assert_eq!(days_since_epoch(1970, 1, 2), 1);
750        // 2024-01-01 should be 19723 (approximate, but verifiable)
751        let days = days_since_epoch(2024, 1, 1);
752        assert!(days > 19000 && days < 21000);
753    }
754
755    #[test]
756    fn test_week_key_epoch() {
757        let epoch = SystemTime::UNIX_EPOCH;
758        let wk = week_key(&epoch);
759        // days=0 => week_key = 0/7 = 0
760        assert_eq!(wk, 0);
761        // One week later (7 days)
762        let week_later = SystemTime::UNIX_EPOCH + Duration::from_secs(7 * 86400);
763        let wk2 = week_key(&week_later);
764        // days=7 => week_key = 7/7 = 1
765        assert_eq!(wk2, 1);
766        // 6 days is still the same week as epoch
767        let six_days = SystemTime::UNIX_EPOCH + Duration::from_secs(6 * 86400);
768        assert_eq!(week_key(&six_days), 0);
769    }
770
771    #[test]
772    fn test_month_key() {
773        let epoch = SystemTime::UNIX_EPOCH;
774        let mk = month_key(&epoch);
775        // 1970-01 has key = 1970 * 12 + 0 = 23640
776        assert_eq!(mk, 1970 * 12);
777
778        // About one year later
779        let one_year = SystemTime::UNIX_EPOCH + Duration::from_secs(366 * 86400);
780        let mk2 = month_key(&one_year);
781        assert!(mk2 > mk);
782    }
783
784    #[test]
785    fn test_year_of() {
786        let epoch = SystemTime::UNIX_EPOCH;
787        let y_epoch = year_of(&epoch);
788        eprintln!("year_of(epoch) = {}", y_epoch);
789        assert_eq!(y_epoch, 1970);
790
791        let future = SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 86400 * 30);
792        let y = year_of(&future);
793        eprintln!("year_of(future) = {}", y);
794        assert!(y >= 1999, "year {} should be >= 1999", y);
795    }
796
797    #[test]
798    fn test_filegen_mut_entry() {
799        let mut reg = FileGenRegistry::new();
800        reg.add(FileGenEntry {
801            name: "loopstats".to_string(),
802            file_name: "loopstats".to_string(),
803            gen_type: FileGenType::Day,
804            enabled: true,
805        });
806
807        // Disable via get_mut
808        if let Some(entry) = reg.get_mut("loopstats") {
809            entry.enabled = false;
810        }
811        assert!(!reg.get("loopstats").unwrap().enabled);
812    }
813
814    #[test]
815    fn test_stat_file_write_ex_without_handle() {
816        let dir = tmp_dir();
817        let path = dir.join("ex_test");
818        write_stat_file_ex(&path, "direct write\n", None).unwrap();
819        assert!(path.exists());
820        let content = std::fs::read_to_string(&path).unwrap();
821        assert!(content.contains("direct write"));
822        cleanup(&dir);
823    }
824}