Skip to main content

oxirs_cluster/
node_status_tracker.rs

1//! # Node Status Tracking with State Machine
2//!
3//! Comprehensive node lifecycle management using a finite state machine.
4//! Tracks node states, transitions, and provides integration with health
5//! monitoring for proactive cluster management.
6
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, VecDeque};
9use std::sync::Arc;
10use std::time::{Duration, SystemTime};
11use tokio::sync::RwLock;
12use tracing::{info, warn};
13
14use crate::raft::OxirsNodeId;
15
16/// Node state in the cluster lifecycle
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
18pub enum NodeState {
19    /// Node is initializing
20    Initializing,
21    /// Node is joining the cluster
22    Joining,
23    /// Node is active and healthy
24    Active,
25    /// Node is active but degraded
26    Degraded,
27    /// Node is suspected to have issues
28    Suspect,
29    /// Node has failed
30    Failed,
31    /// Node is gracefully leaving
32    Leaving,
33    /// Node has left the cluster
34    Left,
35    /// Node is under maintenance
36    Maintenance,
37}
38
39impl NodeState {
40    /// Check if the state represents an operational node
41    pub fn is_operational(&self) -> bool {
42        matches!(self, NodeState::Active | NodeState::Degraded)
43    }
44
45    /// Check if the state represents a problematic node
46    pub fn is_problematic(&self) -> bool {
47        matches!(self, NodeState::Suspect | NodeState::Failed)
48    }
49
50    /// Check if the state is transitional
51    pub fn is_transitional(&self) -> bool {
52        matches!(
53            self,
54            NodeState::Initializing | NodeState::Joining | NodeState::Leaving
55        )
56    }
57}
58
59/// State transition event
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct StateTransition {
62    /// Node ID
63    pub node_id: OxirsNodeId,
64    /// Previous state
65    pub from_state: NodeState,
66    /// New state
67    pub to_state: NodeState,
68    /// Reason for transition
69    pub reason: String,
70    /// Timestamp
71    pub timestamp: SystemTime,
72    /// Transition duration (if applicable)
73    pub duration: Option<Duration>,
74}
75
76/// Node status information
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct NodeStatus {
79    /// Node ID
80    pub node_id: OxirsNodeId,
81    /// Current state
82    pub current_state: NodeState,
83    /// Previous state
84    pub previous_state: Option<NodeState>,
85    /// Time in current state
86    pub time_in_state: Duration,
87    /// Last state change
88    pub last_state_change: SystemTime,
89    /// Total state transitions
90    pub transition_count: u64,
91    /// Node uptime (time since Initializing)
92    pub uptime: Duration,
93    /// Node start time
94    pub start_time: SystemTime,
95    /// Additional metadata
96    pub metadata: BTreeMap<String, String>,
97}
98
99/// State machine configuration
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct StateMachineConfig {
102    /// Maximum history size
103    pub max_history_size: usize,
104    /// Enable automatic state transitions
105    pub enable_auto_transitions: bool,
106    /// Suspect timeout (seconds)
107    pub suspect_timeout_secs: u64,
108    /// Failed timeout (seconds)
109    pub failed_timeout_secs: u64,
110    /// Enable state validation
111    pub enable_validation: bool,
112}
113
114impl Default for StateMachineConfig {
115    fn default() -> Self {
116        Self {
117            max_history_size: 1000,
118            enable_auto_transitions: true,
119            suspect_timeout_secs: 30,
120            failed_timeout_secs: 60,
121            enable_validation: true,
122        }
123    }
124}
125
126/// State machine statistics
127#[derive(Debug, Clone, Default, Serialize, Deserialize)]
128pub struct StateMachineStats {
129    /// Total nodes tracked
130    pub total_nodes: usize,
131    /// Nodes by state
132    pub nodes_by_state: BTreeMap<String, usize>,
133    /// Total transitions
134    pub total_transitions: u64,
135    /// Invalid transition attempts
136    pub invalid_transitions: u64,
137    /// Average time in each state (seconds)
138    pub avg_time_in_state: BTreeMap<String, f64>,
139}
140
141/// Node status tracker with state machine
142pub struct NodeStatusTracker {
143    config: StateMachineConfig,
144    /// Node statuses
145    node_statuses: Arc<RwLock<BTreeMap<OxirsNodeId, NodeStatus>>>,
146    /// Transition history
147    transition_history: Arc<RwLock<VecDeque<StateTransition>>>,
148    /// Statistics
149    stats: Arc<RwLock<StateMachineStats>>,
150    /// Valid state transitions
151    valid_transitions: BTreeMap<NodeState, Vec<NodeState>>,
152}
153
154impl NodeStatusTracker {
155    /// Create a new node status tracker
156    pub fn new(config: StateMachineConfig) -> Self {
157        // Define valid state transitions
158        let mut valid_transitions = BTreeMap::new();
159
160        valid_transitions.insert(
161            NodeState::Initializing,
162            vec![NodeState::Joining, NodeState::Failed],
163        );
164
165        valid_transitions.insert(
166            NodeState::Joining,
167            vec![NodeState::Active, NodeState::Failed],
168        );
169
170        valid_transitions.insert(
171            NodeState::Active,
172            vec![
173                NodeState::Degraded,
174                NodeState::Suspect,
175                NodeState::Leaving,
176                NodeState::Maintenance,
177            ],
178        );
179
180        valid_transitions.insert(
181            NodeState::Degraded,
182            vec![
183                NodeState::Active,
184                NodeState::Suspect,
185                NodeState::Failed,
186                NodeState::Leaving,
187            ],
188        );
189
190        valid_transitions.insert(
191            NodeState::Suspect,
192            vec![NodeState::Active, NodeState::Degraded, NodeState::Failed],
193        );
194
195        valid_transitions.insert(
196            NodeState::Failed,
197            vec![NodeState::Initializing, NodeState::Left],
198        );
199
200        valid_transitions.insert(NodeState::Leaving, vec![NodeState::Left]);
201
202        valid_transitions.insert(NodeState::Left, vec![NodeState::Initializing]);
203
204        valid_transitions.insert(
205            NodeState::Maintenance,
206            vec![NodeState::Active, NodeState::Degraded, NodeState::Failed],
207        );
208
209        Self {
210            config,
211            node_statuses: Arc::new(RwLock::new(BTreeMap::new())),
212            transition_history: Arc::new(RwLock::new(VecDeque::new())),
213            stats: Arc::new(RwLock::new(StateMachineStats::default())),
214            valid_transitions,
215        }
216    }
217
218    /// Register a new node
219    pub async fn register_node(&self, node_id: OxirsNodeId) {
220        let now = SystemTime::now();
221
222        let status = NodeStatus {
223            node_id,
224            current_state: NodeState::Initializing,
225            previous_state: None,
226            time_in_state: Duration::from_secs(0),
227            last_state_change: now,
228            transition_count: 0,
229            uptime: Duration::from_secs(0),
230            start_time: now,
231            metadata: BTreeMap::new(),
232        };
233
234        {
235            let mut statuses = self.node_statuses.write().await;
236            statuses.insert(node_id, status);
237        } // Drop write lock before calling update_stats
238
239        info!("Registered node {} in state Initializing", node_id);
240
241        self.update_stats().await;
242    }
243
244    /// Unregister a node
245    pub async fn unregister_node(&self, node_id: &OxirsNodeId) {
246        {
247            let mut statuses = self.node_statuses.write().await;
248            statuses.remove(node_id);
249        } // Drop write lock before calling update_stats
250
251        info!("Unregistered node {}", node_id);
252
253        self.update_stats().await;
254    }
255
256    /// Transition node to a new state
257    pub async fn transition_state(
258        &self,
259        node_id: OxirsNodeId,
260        new_state: NodeState,
261        reason: String,
262    ) -> Result<(), String> {
263        let old_state = {
264            let statuses = self.node_statuses.read().await;
265            statuses
266                .get(&node_id)
267                .map(|s| s.current_state)
268                .ok_or_else(|| format!("Node {} not found", node_id))?
269        };
270
271        // Validate transition
272        if self.config.enable_validation && !self.is_valid_transition(old_state, new_state) {
273            let mut stats = self.stats.write().await;
274            stats.invalid_transitions += 1;
275
276            return Err(format!(
277                "Invalid transition from {:?} to {:?}",
278                old_state, new_state
279            ));
280        }
281
282        let mut statuses = self.node_statuses.write().await;
283
284        let status = statuses
285            .get_mut(&node_id)
286            .ok_or_else(|| format!("Node {} not found", node_id))?;
287
288        // Calculate time in previous state
289        let now = SystemTime::now();
290        let duration = now
291            .duration_since(status.last_state_change)
292            .unwrap_or(Duration::from_secs(0));
293
294        // Update status
295        status.previous_state = Some(old_state);
296        status.current_state = new_state;
297        status.time_in_state = Duration::from_secs(0);
298        status.last_state_change = now;
299        status.transition_count += 1;
300
301        // Update uptime
302        status.uptime = now
303            .duration_since(status.start_time)
304            .unwrap_or(Duration::from_secs(0));
305
306        // Record transition
307        let transition = StateTransition {
308            node_id,
309            from_state: old_state,
310            to_state: new_state,
311            reason: reason.clone(),
312            timestamp: now,
313            duration: Some(duration),
314        };
315
316        drop(statuses);
317
318        // Store transition in history
319        {
320            let mut history = self.transition_history.write().await;
321            history.push_back(transition.clone());
322
323            if history.len() > self.config.max_history_size {
324                history.pop_front();
325            }
326        } // Drop write lock before calling update_stats
327
328        info!(
329            "Node {} transitioned from {:?} to {:?}: {}",
330            node_id, old_state, new_state, reason
331        );
332
333        self.update_stats().await;
334
335        Ok(())
336    }
337
338    /// Check if a state transition is valid
339    fn is_valid_transition(&self, from: NodeState, to: NodeState) -> bool {
340        if from == to {
341            return true;
342        }
343
344        self.valid_transitions
345            .get(&from)
346            .map(|valid| valid.contains(&to))
347            .unwrap_or(false)
348    }
349
350    /// Get node status
351    pub async fn get_node_status(&self, node_id: &OxirsNodeId) -> Option<NodeStatus> {
352        let statuses = self.node_statuses.read().await;
353        statuses.get(node_id).cloned()
354    }
355
356    /// Get all node statuses
357    pub async fn get_all_statuses(&self) -> BTreeMap<OxirsNodeId, NodeStatus> {
358        self.node_statuses.read().await.clone()
359    }
360
361    /// Get nodes in a specific state
362    pub async fn get_nodes_in_state(&self, state: NodeState) -> Vec<OxirsNodeId> {
363        let statuses = self.node_statuses.read().await;
364        statuses
365            .iter()
366            .filter(|(_, status)| status.current_state == state)
367            .map(|(id, _)| *id)
368            .collect()
369    }
370
371    /// Get transition history
372    pub async fn get_transition_history(&self) -> Vec<StateTransition> {
373        self.transition_history
374            .read()
375            .await
376            .iter()
377            .cloned()
378            .collect()
379    }
380
381    /// Get transition history for a specific node
382    pub async fn get_node_transition_history(&self, node_id: &OxirsNodeId) -> Vec<StateTransition> {
383        let history = self.transition_history.read().await;
384        history
385            .iter()
386            .filter(|t| &t.node_id == node_id)
387            .cloned()
388            .collect()
389    }
390
391    /// Update node metadata
392    pub async fn update_metadata(
393        &self,
394        node_id: &OxirsNodeId,
395        key: String,
396        value: String,
397    ) -> Result<(), String> {
398        let mut statuses = self.node_statuses.write().await;
399
400        let status = statuses
401            .get_mut(node_id)
402            .ok_or_else(|| format!("Node {} not found", node_id))?;
403
404        status.metadata.insert(key, value);
405
406        Ok(())
407    }
408
409    /// Get statistics
410    pub async fn get_stats(&self) -> StateMachineStats {
411        self.stats.read().await.clone()
412    }
413
414    /// Update statistics
415    async fn update_stats(&self) {
416        let mut stats = StateMachineStats {
417            total_nodes: 0,
418            nodes_by_state: BTreeMap::new(),
419            total_transitions: 0,
420            invalid_transitions: 0,
421            avg_time_in_state: BTreeMap::new(),
422        };
423
424        // Collect data from statuses (scope read lock)
425        {
426            let statuses = self.node_statuses.read().await;
427            stats.total_nodes = statuses.len();
428
429            // Count nodes by state
430            for status in statuses.values() {
431                let state_name = format!("{:?}", status.current_state);
432                *stats.nodes_by_state.entry(state_name).or_insert(0) += 1;
433                stats.total_transitions += status.transition_count;
434            }
435        } // Drop statuses read lock
436
437        // Calculate average time in each state (scope read lock)
438        {
439            let history = self.transition_history.read().await;
440            let mut state_durations: BTreeMap<String, Vec<u64>> = BTreeMap::new();
441
442            for transition in history.iter() {
443                if let Some(duration) = transition.duration {
444                    let state_name = format!("{:?}", transition.from_state);
445                    state_durations
446                        .entry(state_name)
447                        .or_default()
448                        .push(duration.as_secs());
449                }
450            }
451
452            for (state, durations) in state_durations.iter() {
453                if !durations.is_empty() {
454                    let avg = durations.iter().sum::<u64>() as f64 / durations.len() as f64;
455                    stats.avg_time_in_state.insert(state.clone(), avg);
456                }
457            }
458        } // Drop history read lock
459
460        // Preserve invalid transitions count and update (scope locks separately)
461        {
462            let old_stats = self.stats.read().await;
463            stats.invalid_transitions = old_stats.invalid_transitions;
464        } // Drop stats read lock before acquiring write lock
465
466        *self.stats.write().await = stats;
467    }
468
469    /// Perform automatic state checks
470    pub async fn perform_auto_checks(&self) {
471        if !self.config.enable_auto_transitions {
472            return;
473        }
474
475        let statuses = self.node_statuses.read().await;
476        let now = SystemTime::now();
477        let mut transitions = Vec::new();
478
479        for (node_id, status) in statuses.iter() {
480            let time_in_state = now
481                .duration_since(status.last_state_change)
482                .unwrap_or(Duration::from_secs(0));
483
484            // Check for suspect timeout
485            if status.current_state == NodeState::Suspect
486                && time_in_state.as_secs() > self.config.suspect_timeout_secs
487            {
488                transitions.push((
489                    *node_id,
490                    NodeState::Failed,
491                    "Suspect timeout exceeded".to_string(),
492                ));
493            }
494
495            // Check for failed timeout
496            if status.current_state == NodeState::Failed
497                && time_in_state.as_secs() > self.config.failed_timeout_secs
498            {
499                transitions.push((
500                    *node_id,
501                    NodeState::Left,
502                    "Failed timeout exceeded".to_string(),
503                ));
504            }
505        }
506
507        drop(statuses);
508
509        // Apply transitions
510        for (node_id, new_state, reason) in transitions {
511            if let Err(e) = self.transition_state(node_id, new_state, reason).await {
512                warn!("Auto-transition failed for node {}: {}", node_id, e);
513            }
514        }
515    }
516
517    /// Clear all data
518    pub async fn clear(&self) {
519        self.node_statuses.write().await.clear();
520        self.transition_history.write().await.clear();
521        *self.stats.write().await = StateMachineStats::default();
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[tokio::test]
530    async fn test_node_status_tracker_creation() {
531        let config = StateMachineConfig::default();
532        let tracker = NodeStatusTracker::new(config);
533
534        let stats = tracker.get_stats().await;
535        assert_eq!(stats.total_nodes, 0);
536    }
537
538    #[tokio::test]
539    async fn test_register_node() {
540        let config = StateMachineConfig::default();
541        let tracker = NodeStatusTracker::new(config);
542
543        tracker.register_node(1).await;
544
545        let status = tracker.get_node_status(&1).await;
546        assert!(status.is_some());
547
548        let status = status.unwrap();
549        assert_eq!(status.current_state, NodeState::Initializing);
550        assert_eq!(status.transition_count, 0);
551    }
552
553    #[tokio::test]
554    async fn test_valid_transition() {
555        let config = StateMachineConfig::default();
556        let tracker = NodeStatusTracker::new(config);
557
558        tracker.register_node(1).await;
559
560        let result = tracker
561            .transition_state(1, NodeState::Joining, "Starting join process".to_string())
562            .await;
563
564        assert!(result.is_ok());
565
566        let status = tracker.get_node_status(&1).await.unwrap();
567        assert_eq!(status.current_state, NodeState::Joining);
568        assert_eq!(status.previous_state, Some(NodeState::Initializing));
569        assert_eq!(status.transition_count, 1);
570    }
571
572    #[tokio::test]
573    async fn test_invalid_transition() {
574        let config = StateMachineConfig::default();
575        let tracker = NodeStatusTracker::new(config);
576
577        tracker.register_node(1).await;
578
579        let result = tracker
580            .transition_state(1, NodeState::Active, "Invalid transition".to_string())
581            .await;
582
583        assert!(result.is_err());
584
585        let stats = tracker.get_stats().await;
586        assert_eq!(stats.invalid_transitions, 1);
587    }
588
589    #[tokio::test]
590    async fn test_state_machine_flow() {
591        let config = StateMachineConfig::default();
592        let tracker = NodeStatusTracker::new(config);
593
594        tracker.register_node(1).await;
595
596        // Initializing -> Joining
597        tracker
598            .transition_state(1, NodeState::Joining, "Joining cluster".to_string())
599            .await
600            .unwrap();
601
602        // Joining -> Active
603        tracker
604            .transition_state(1, NodeState::Active, "Joined successfully".to_string())
605            .await
606            .unwrap();
607
608        // Active -> Degraded
609        tracker
610            .transition_state(1, NodeState::Degraded, "Performance degraded".to_string())
611            .await
612            .unwrap();
613
614        let status = tracker.get_node_status(&1).await.unwrap();
615        assert_eq!(status.current_state, NodeState::Degraded);
616        assert_eq!(status.transition_count, 3);
617    }
618
619    #[tokio::test]
620    async fn test_get_nodes_in_state() {
621        let config = StateMachineConfig::default();
622        let tracker = NodeStatusTracker::new(config);
623
624        tracker.register_node(1).await;
625        tracker.register_node(2).await;
626        tracker.register_node(3).await;
627
628        tracker
629            .transition_state(1, NodeState::Joining, "test".to_string())
630            .await
631            .unwrap();
632        tracker
633            .transition_state(2, NodeState::Joining, "test".to_string())
634            .await
635            .unwrap();
636
637        let joining_nodes = tracker.get_nodes_in_state(NodeState::Joining).await;
638        assert_eq!(joining_nodes.len(), 2);
639        assert!(joining_nodes.contains(&1));
640        assert!(joining_nodes.contains(&2));
641    }
642
643    #[tokio::test]
644    async fn test_transition_history() {
645        let config = StateMachineConfig::default();
646        let tracker = NodeStatusTracker::new(config);
647
648        tracker.register_node(1).await;
649
650        tracker
651            .transition_state(1, NodeState::Joining, "test1".to_string())
652            .await
653            .unwrap();
654        tracker
655            .transition_state(1, NodeState::Active, "test2".to_string())
656            .await
657            .unwrap();
658
659        let history = tracker.get_node_transition_history(&1).await;
660        assert_eq!(history.len(), 2);
661        assert_eq!(history[0].from_state, NodeState::Initializing);
662        assert_eq!(history[0].to_state, NodeState::Joining);
663        assert_eq!(history[1].from_state, NodeState::Joining);
664        assert_eq!(history[1].to_state, NodeState::Active);
665    }
666
667    #[tokio::test]
668    async fn test_metadata() {
669        let config = StateMachineConfig::default();
670        let tracker = NodeStatusTracker::new(config);
671
672        tracker.register_node(1).await;
673
674        tracker
675            .update_metadata(&1, "version".to_string(), "1.0.0".to_string())
676            .await
677            .unwrap();
678        tracker
679            .update_metadata(&1, "region".to_string(), "us-west".to_string())
680            .await
681            .unwrap();
682
683        let status = tracker.get_node_status(&1).await.unwrap();
684        assert_eq!(status.metadata.get("version"), Some(&"1.0.0".to_string()));
685        assert_eq!(status.metadata.get("region"), Some(&"us-west".to_string()));
686    }
687
688    #[tokio::test]
689    async fn test_stats() {
690        let config = StateMachineConfig::default();
691        let tracker = NodeStatusTracker::new(config);
692
693        tracker.register_node(1).await;
694        tracker.register_node(2).await;
695        tracker.register_node(3).await;
696
697        tracker
698            .transition_state(1, NodeState::Joining, "test".to_string())
699            .await
700            .unwrap();
701        tracker
702            .transition_state(2, NodeState::Joining, "test".to_string())
703            .await
704            .unwrap();
705        tracker
706            .transition_state(1, NodeState::Active, "test".to_string())
707            .await
708            .unwrap();
709
710        let stats = tracker.get_stats().await;
711        assert_eq!(stats.total_nodes, 3);
712        assert_eq!(stats.total_transitions, 3);
713    }
714
715    #[tokio::test]
716    async fn test_unregister_node() {
717        let config = StateMachineConfig::default();
718        let tracker = NodeStatusTracker::new(config);
719
720        tracker.register_node(1).await;
721        assert!(tracker.get_node_status(&1).await.is_some());
722
723        tracker.unregister_node(&1).await;
724        assert!(tracker.get_node_status(&1).await.is_none());
725    }
726
727    #[tokio::test]
728    async fn test_node_state_helpers() {
729        assert!(NodeState::Active.is_operational());
730        assert!(NodeState::Degraded.is_operational());
731        assert!(!NodeState::Failed.is_operational());
732
733        assert!(NodeState::Suspect.is_problematic());
734        assert!(NodeState::Failed.is_problematic());
735        assert!(!NodeState::Active.is_problematic());
736
737        assert!(NodeState::Initializing.is_transitional());
738        assert!(NodeState::Joining.is_transitional());
739        assert!(!NodeState::Active.is_transitional());
740    }
741
742    #[tokio::test]
743    async fn test_clear() {
744        let config = StateMachineConfig::default();
745        let tracker = NodeStatusTracker::new(config);
746
747        tracker.register_node(1).await;
748        tracker.register_node(2).await;
749
750        tracker.clear().await;
751
752        let stats = tracker.get_stats().await;
753        assert_eq!(stats.total_nodes, 0);
754    }
755}