Skip to main content

bitfold_peer/
peer_state.rs

1/// Peer connection state machine.
2///
3/// Tracks the lifecycle of a peer connection from initial contact through
4/// active communication to graceful shutdown.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum PeerState {
7    /// Peer has been created but no packets exchanged yet
8    #[default]
9    Idle,
10
11    /// Client: Sent CONNECT, waiting for VERIFY_CONNECT
12    Connecting,
13
14    /// Server: Received CONNECT, sent VERIFY_CONNECT, waiting for ACK
15    AcknowledgingConnect,
16
17    /// Client: Received VERIFY_CONNECT, sent ACK, waiting for confirmation
18    ConnectionSucceeded,
19
20    /// Both sides have completed handshake - connection is active
21    Connected,
22
23    /// Disconnect command sent, waiting for acknowledgment
24    Disconnecting,
25
26    /// Peer is being cleaned up (zombie state before removal)
27    Zombie,
28}
29
30impl PeerState {
31    /// Returns true if the peer is in an active state where data can be sent
32    pub fn is_active(&self) -> bool {
33        matches!(
34            self,
35            PeerState::Connected
36                | PeerState::ConnectionSucceeded
37                | PeerState::AcknowledgingConnect
38                | PeerState::Connecting
39        )
40    }
41
42    /// Returns true if the connection is fully established
43    pub fn is_established(&self) -> bool {
44        matches!(self, PeerState::Connected | PeerState::ConnectionSucceeded)
45    }
46
47    /// Returns true if the peer is disconnecting or already disconnected
48    pub fn is_disconnecting(&self) -> bool {
49        matches!(self, PeerState::Disconnecting | PeerState::Zombie)
50    }
51
52    /// Returns true if the peer is in the middle of connection handshake
53    pub fn is_connecting(&self) -> bool {
54        matches!(
55            self,
56            PeerState::Connecting
57                | PeerState::AcknowledgingConnect
58                | PeerState::ConnectionSucceeded
59        )
60    }
61}