Skip to main content

samod_core/network/
connection_event.rs

1use crate::ConnectionId;
2
3use super::{ConnectionOwner, PeerInfo, connection_info::ConnectionInfo};
4
5/// Events related to connection lifecycle and handshake process.
6///
7/// These events are emitted during connection establishment, handshake
8/// completion, and connection failures. They allow applications to track
9/// the state of network connections and respond to connectivity changes.
10///
11/// Each event includes a `ConnectionOwner` that identifies the dialer
12/// or listener that owns the connection.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ConnectionEvent {
15    /// Handshake completed successfully with a peer.
16    ///
17    /// This event is emitted when the connection handshake process
18    /// finishes successfully and the connection transitions to the
19    /// established state. After this event, the connection is ready
20    /// for document synchronization.
21    HandshakeCompleted {
22        connection_id: ConnectionId,
23        owner: ConnectionOwner,
24        peer_info: PeerInfo,
25    },
26    /// Connection failed or was disconnected.
27    ///
28    /// This event is emitted when a connection fails or when a connection is
29    /// explicitly disconnected. This can happen due to network errors, protocol
30    /// violations, or explicit disconnection.
31    ConnectionFailed {
32        connection_id: ConnectionId,
33        owner: ConnectionOwner,
34        error: String,
35    },
36
37    /// This event is emitted whenever some part of the connection state changes
38    StateChanged {
39        connection_id: ConnectionId,
40        owner: ConnectionOwner,
41        // The new state
42        new_state: ConnectionInfo,
43    },
44}
45
46impl ConnectionEvent {
47    /// Get the connection ID associated with this event.
48    pub fn connection_id(&self) -> ConnectionId {
49        match self {
50            ConnectionEvent::HandshakeCompleted { connection_id, .. } => *connection_id,
51            ConnectionEvent::ConnectionFailed { connection_id, .. } => *connection_id,
52            ConnectionEvent::StateChanged { connection_id, .. } => *connection_id,
53        }
54    }
55
56    /// Get the owner of the connection associated with this event.
57    pub fn owner(&self) -> ConnectionOwner {
58        match self {
59            ConnectionEvent::HandshakeCompleted { owner, .. } => *owner,
60            ConnectionEvent::ConnectionFailed { owner, .. } => *owner,
61            ConnectionEvent::StateChanged { owner, .. } => *owner,
62        }
63    }
64}