Skip to main content

titan_rust_client/
state.rs

1//! Connection state observable.
2
3use std::fmt;
4
5/// Connection state for observing connection health.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ConnectionState {
8    /// Connected to the server and ready for requests.
9    Connected,
10
11    /// Attempting to reconnect after disconnection.
12    Reconnecting {
13        /// Current reconnection attempt number.
14        attempt: u32,
15    },
16
17    /// Disconnected from the server.
18    Disconnected {
19        /// Reason for disconnection.
20        reason: String,
21    },
22}
23
24impl ConnectionState {
25    /// Returns true if currently connected.
26    pub fn is_connected(&self) -> bool {
27        matches!(self, Self::Connected)
28    }
29
30    /// Returns true if currently reconnecting.
31    pub fn is_reconnecting(&self) -> bool {
32        matches!(self, Self::Reconnecting { .. })
33    }
34
35    /// Returns true if disconnected (not reconnecting).
36    pub fn is_disconnected(&self) -> bool {
37        matches!(self, Self::Disconnected { .. })
38    }
39
40    /// Returns the reconnection attempt number if reconnecting.
41    pub fn reconnect_attempt(&self) -> Option<u32> {
42        match self {
43            Self::Reconnecting { attempt } => Some(*attempt),
44            _ => None,
45        }
46    }
47
48    /// Returns the disconnection reason if disconnected.
49    pub fn disconnect_reason(&self) -> Option<&str> {
50        match self {
51            Self::Disconnected { reason } => Some(reason),
52            _ => None,
53        }
54    }
55}
56
57impl Default for ConnectionState {
58    fn default() -> Self {
59        Self::Disconnected {
60            reason: "Not connected".to_string(),
61        }
62    }
63}
64
65impl fmt::Display for ConnectionState {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::Connected => write!(f, "Connected"),
69            Self::Reconnecting { attempt } => write!(f, "Reconnecting (attempt {})", attempt),
70            Self::Disconnected { reason } => write!(f, "Disconnected: {}", reason),
71        }
72    }
73}