Skip to main content

ntp_timer/
config.rs

1use serde::{Deserialize, Serialize};
2
3/// NTP 计时器的配置
4///
5/// 支持 Builder 模式,便于自定义
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct Config {
8    /// 后台同步间隔(秒),默认值:600
9    pub sync_interval_secs: u64,
10
11    /// 时钟跳跃检测阈值(秒),默认值:5
12    pub clock_jump_threshold_secs: i64,
13
14    /// NTP 服务器列表
15    pub ntp_servers: Vec<String>,
16
17    /// 最大重试次数,默认值:10
18    pub max_retries: usize,
19
20    /// 套接字超时时间(秒),默认值:5
21    pub socket_timeout_secs: u64,
22
23    /// 初始重试间隔(秒),默认值:1
24    pub initial_retry_interval_secs: u64,
25}
26
27impl Default for Config {
28    fn default() -> Self {
29        Self {
30            sync_interval_secs: 600,
31            clock_jump_threshold_secs: 5,
32            ntp_servers: vec![
33                "ntp.ntsc.ac.cn".to_string(),
34                "time1.ntsc.ac.cn".to_string(),
35                "time2.ntsc.ac.cn".to_string(),
36            ],
37            max_retries: 10,
38            socket_timeout_secs: 5,
39            initial_retry_interval_secs: 1,
40        }
41    }
42}
43
44impl Config {
45    /// 创建一个带有默认值的新配置
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// 设置后台同步间隔
51    pub fn with_sync_interval(mut self, secs: u64) -> Self {
52        self.sync_interval_secs = secs;
53        self
54    }
55
56    /// 设置时钟跳跃检测阈值
57    pub fn with_jump_threshold(mut self, secs: i64) -> Self {
58        self.clock_jump_threshold_secs = secs;
59        self
60    }
61
62    /// 设置 NTP 服务器列表
63    pub fn with_ntp_servers(mut self, servers: Vec<String>) -> Self {
64        self.ntp_servers = servers;
65        self
66    }
67
68    /// 设置最大重试次数
69    pub fn with_max_retries(mut self, retries: usize) -> Self {
70        self.max_retries = retries;
71        self
72    }
73
74    /// 设置套接字超时
75    pub fn with_socket_timeout(mut self, secs: u64) -> Self {
76        self.socket_timeout_secs = secs;
77        self
78    }
79
80    /// 设置初始重试间隔
81    pub fn with_initial_retry_interval(mut self, secs: u64) -> Self {
82        self.initial_retry_interval_secs = secs;
83        self
84    }
85
86    /// 验证配置合法性
87    pub fn validate(&self) -> Result<(), String> {
88        if self.sync_interval_secs == 0 {
89            return Err("同步间隔必须 > 0".to_string());
90        }
91        if self.clock_jump_threshold_secs < 0 {
92            return Err("时钟跳跃阈值必须 >= 0".to_string());
93        }
94        if self.ntp_servers.is_empty() {
95            return Err("NTP 服务器列表不能为空".to_string());
96        }
97        if self.max_retries == 0 {
98            return Err("最大重试次数必须 > 0".to_string());
99        }
100        if self.socket_timeout_secs == 0 {
101            return Err("套接字超时必须 > 0".to_string());
102        }
103        if self.initial_retry_interval_secs == 0 {
104            return Err("初始重试间隔必须 > 0".to_string());
105        }
106        Ok(())
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_default_config() {
116        let config = Config::default();
117        assert_eq!(config.sync_interval_secs, 600);
118        assert_eq!(config.clock_jump_threshold_secs, 5);
119        assert_eq!(config.max_retries, 10);
120        assert_eq!(config.socket_timeout_secs, 5);
121        assert_eq!(config.initial_retry_interval_secs, 1);
122    }
123
124    #[test]
125    fn test_builder_pattern() {
126        let config = Config::new()
127            .with_sync_interval(300)
128            .with_jump_threshold(3)
129            .with_max_retries(5)
130            .with_initial_retry_interval(2);
131
132        assert_eq!(config.sync_interval_secs, 300);
133        assert_eq!(config.clock_jump_threshold_secs, 3);
134        assert_eq!(config.max_retries, 5);
135        assert_eq!(config.initial_retry_interval_secs, 2);
136    }
137
138    #[test]
139    fn test_config_validation() {
140        let config = Config::default();
141        assert!(config.validate().is_ok());
142
143        let invalid = Config {
144            sync_interval_secs: 0,
145            ..Default::default()
146        };
147        assert!(invalid.validate().is_err());
148    }
149}