Skip to main content

ntp_timer/
sync.rs

1use crate::config::Config;
2use crate::error::TimerError;
3use crate::ntp;
4use crate::timer::GlobalTimer;
5use lazy_static::lazy_static;
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8use tracing::{debug, info, warn};
9
10lazy_static! {
11    static ref GLOBAL_TIMER: Arc<Mutex<Option<GlobalTimer>>> = Arc::new(Mutex::new(None));
12    static ref CONFIG: Arc<Mutex<Option<Arc<Config>>>> = Arc::new(Mutex::new(None));
13}
14
15/// Global timer manager providing unified interface for time synchronization and access
16pub struct TimerManager;
17
18impl TimerManager {
19    /// Initializes the global timer (lazy initialization).
20    ///
21    /// On first call, fetches NTP timestamp and starts background sync task.
22    /// Subsequent calls are no-op if already initialized.
23    pub async fn init_global_timer(config: Arc<Config>) -> Result<(), TimerError> {
24        config.validate().map_err(TimerError::ConfigError)?;
25
26        let mut config_guard = CONFIG
27            .lock()
28            .map_err(|e| TimerError::LockError(e.to_string()))?;
29
30        if config_guard.is_none() {
31            *config_guard = Some(Arc::clone(&config));
32        }
33        drop(config_guard);
34
35        let mut timer_guard = GLOBAL_TIMER
36            .lock()
37            .map_err(|e| TimerError::LockError(e.to_string()))?;
38
39        if timer_guard.is_none() {
40            let base_timestamp = ntp::get_ntp_timestamp(&config)?;
41            let mut timer = GlobalTimer::new(base_timestamp);
42            timer.set_initialized(true);
43            *timer_guard = Some(timer);
44            drop(timer_guard);
45
46            TimerManager::spawn_background_sync();
47            info!("全局计时器初始化成功,已标记为已初始化");
48        }
49
50        Ok(())
51    }
52
53    /// Gets the current timestamp via fast local path (<0.1ms).
54    ///
55    /// # Errors
56    /// Returns `TimerError::NotInitialized` if `init_global_timer` was not called.
57    pub fn get_timestamp() -> Result<i64, TimerError> {
58        let timer_guard = GLOBAL_TIMER
59            .lock()
60            .map_err(|e| TimerError::LockError(e.to_string()))?;
61
62        match timer_guard.as_ref() {
63            Some(timer) => Ok(timer.get_current_timestamp()),
64            None => Err(TimerError::NotInitialized),
65        }
66    }
67
68    /// 检查计时器是否已初始化
69    pub fn is_initialized() -> bool {
70        match GLOBAL_TIMER.lock() {
71            Ok(timer_guard) => match timer_guard.as_ref() {
72                Some(timer) => timer.is_initialized(),
73                None => false,
74            },
75            Err(_) => false,
76        }
77    }
78
79    /// 手动同步 NTP
80    pub async fn manual_sync() -> Result<i64, TimerError> {
81        let config_opt = {
82            let config_guard = CONFIG
83                .lock()
84                .map_err(|e| TimerError::LockError(e.to_string()))?;
85            config_guard.as_ref().map(Arc::clone)
86        };
87
88        let config = config_opt.ok_or(TimerError::NotInitialized)?;
89
90        let new_ntp_timestamp = ntp::get_ntp_timestamp(&config)?;
91
92        let mut timer_guard = GLOBAL_TIMER
93            .lock()
94            .map_err(|e| TimerError::LockError(e.to_string()))?;
95
96        match timer_guard.as_mut() {
97            Some(timer) => {
98                if timer.detect_clock_jump(new_ntp_timestamp, config.clock_jump_threshold_secs) {
99                    timer.update_timestamp(new_ntp_timestamp, true);
100                } else {
101                    timer.update_timestamp(new_ntp_timestamp, false);
102                }
103                
104                timer.set_initialized(true);
105                let timestamp = timer.get_current_timestamp();
106                info!(timestamp, "NTP 同步完成,已标记为已初始化");
107                Ok(timestamp)
108            }
109            None => Err(TimerError::NotInitialized),
110        }
111    }
112
113    /// 启动后台同步任务
114    fn spawn_background_sync() {
115        tokio::spawn(async {
116            loop {
117                let sync_interval = {
118                    let config_guard = CONFIG.lock().ok();
119                    config_guard.and_then(|g| g.as_ref().map(|c| c.sync_interval_secs))
120                };
121
122                if let Some(interval) = sync_interval {
123                    tokio::time::sleep(Duration::from_secs(interval)).await;
124
125                    match TimerManager::manual_sync().await {
126                        Ok(_) => {
127                            debug!("后台同步完成");
128                        }
129                        Err(e) => {
130                            warn!("后台同步失败,继续使用本地计时器: {}", e);
131                        }
132                    }
133                } else {
134                    tokio::time::sleep(Duration::from_secs(1)).await;
135                }
136            }
137        });
138    }
139
140    /// 重置计时器(用于测试)
141    #[cfg(test)]
142    pub fn reset() {
143        if let Ok(mut timer_guard) = GLOBAL_TIMER.lock() {
144            *timer_guard = None;
145        }
146        if let Ok(mut config_guard) = CONFIG.lock() {
147            *config_guard = None;
148        }
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[tokio::test]
157    async fn test_manual_sync_without_init() {
158        TimerManager::reset();
159        let result = TimerManager::manual_sync().await;
160        assert!(result.is_err());
161    }
162}