Skip to main content

rtc/peer_connection/state/
peer_connection_state.rs

1use crate::peer_connection::configuration::UNSPECIFIED_STR;
2use std::fmt;
3
4/// Indicates the overall state of the peer connection.
5///
6/// `RTCPeerConnectionState` is an aggregate state that combines the states of
7/// both the ICE transport layer and the DTLS transport layer. It provides a
8/// high-level view of whether the connection is ready for media to flow.
9///
10/// # State Determination
11///
12/// This state is derived from the combination of:
13///
14/// - **ICE transport states** - Network connectivity
15/// - **DTLS transport states** - Encryption handshake
16///
17/// The peer connection is only fully "connected" when both ICE and DTLS are
18/// successfully established.
19///
20/// # State Transitions
21///
22/// Typical progression for a successful connection:
23///
24/// ```text
25/// New → Connecting → Connected
26/// ```
27///
28/// If problems occur:
29///
30/// ```text
31/// Connected → Disconnected → (may recover to Connected)
32/// Connected → Failed (permanent failure)
33/// Any state → Closed (connection closed)
34/// ```
35///
36/// # Examples
37///
38/// ## Monitoring Overall Connection State
39///
40/// ```no_run
41/// use rtc::peer_connection::state::RTCPeerConnectionState;
42/// use rtc::peer_connection::event::RTCPeerConnectionEvent;
43///
44/// # fn handle_event(event: RTCPeerConnectionEvent) {
45/// match event {
46///     RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
47///         match state {
48///             RTCPeerConnectionState::New => {
49///                 println!("Connection initialized");
50///             }
51///             RTCPeerConnectionState::Connecting => {
52///                 println!("Establishing connection (ICE + DTLS)...");
53///             }
54///             RTCPeerConnectionState::Connected => {
55///                 println!("✓ Connection established - media can flow!");
56///             }
57///             RTCPeerConnectionState::Disconnected => {
58///                 println!("⚠ Connection lost - may reconnect automatically");
59///             }
60///             RTCPeerConnectionState::Failed => {
61///                 println!("✗ Connection failed - requires ICE restart");
62///             }
63///             RTCPeerConnectionState::Closed => {
64///                 println!("Connection closed");
65///             }
66///             _ => {}
67///         }
68///     }
69///     _ => {}
70/// }
71/// # }
72/// ```
73///
74/// ## Checking if Connection is Active
75///
76/// ```
77/// use rtc::peer_connection::state::RTCPeerConnectionState;
78///
79/// fn is_connected(state: RTCPeerConnectionState) -> bool {
80///     matches!(state, RTCPeerConnectionState::Connected)
81/// }
82///
83/// fn can_send_media(state: RTCPeerConnectionState) -> bool {
84///     matches!(state, RTCPeerConnectionState::Connected)
85/// }
86///
87/// assert!(is_connected(RTCPeerConnectionState::Connected));
88/// assert!(!is_connected(RTCPeerConnectionState::Connecting));
89/// assert!(can_send_media(RTCPeerConnectionState::Connected));
90/// ```
91///
92/// ## String Conversion
93///
94/// ```
95/// use rtc::peer_connection::state::RTCPeerConnectionState;
96///
97/// // Convert to string
98/// let state = RTCPeerConnectionState::Connected;
99/// assert_eq!(state.to_string(), "connected");
100///
101/// // Parse from string
102/// let parsed: RTCPeerConnectionState = "connecting".into();
103/// assert_eq!(parsed, RTCPeerConnectionState::Connecting);
104/// ```
105///
106/// ## Handling Disconnections
107///
108/// ```no_run
109/// use rtc::peer_connection::state::RTCPeerConnectionState;
110/// use rtc::peer_connection::event::RTCPeerConnectionEvent;
111///
112/// # fn handle_disconnection(event: RTCPeerConnectionEvent) {
113/// match event {
114///     RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
115///         match state {
116///             RTCPeerConnectionState::Disconnected => {
117///                 println!("Connection lost - ICE will try to reconnect");
118///                 // Optionally: Show reconnecting UI
119///                 // Wait for automatic recovery or timeout
120///             }
121///             RTCPeerConnectionState::Failed => {
122///                 println!("Connection failed permanently");
123///                 // Typically: Trigger ICE restart
124///                 // Or: Close and recreate connection
125///             }
126///             RTCPeerConnectionState::Connected => {
127///                 println!("Connection restored!");
128///             }
129///             _ => {}
130///         }
131///     }
132///     _ => {}
133/// }
134/// # }
135/// ```
136///
137/// # Specifications
138///
139/// - [W3C RTCPeerConnection.connectionState]
140/// - [MDN RTCPeerConnection.connectionState]
141///
142/// [W3C RTCPeerConnection.connectionState]: https://w3c.github.io/webrtc-pc/#dom-peerconnection-connection-state
143/// [MDN RTCPeerConnection.connectionState]: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
144#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
145pub enum RTCPeerConnectionState {
146    /// State not specified. This should not occur in normal operation.
147    #[default]
148    Unspecified,
149
150    /// Connection is in initial state.
151    ///
152    /// Any of the ICE or DTLS transports are in the "new" state and none are
153    /// in "connecting", "checking", "failed", or "disconnected" state, or all
154    /// transports are in "closed" state, or there are no transports.
155    New,
156
157    /// Connection establishment is in progress.
158    ///
159    /// At least one ICE or DTLS transport is in the "connecting" or "checking"
160    /// state and none are in "failed" state. This indicates that ICE connectivity
161    /// checks are running and/or DTLS handshake is in progress.
162    ///
163    /// Media cannot flow yet in this state.
164    Connecting,
165
166    /// Connection is established and media can flow.
167    ///
168    /// All ICE and DTLS transports are in "connected", "completed", or "closed"
169    /// state, and at least one is in "connected" or "completed" state. Both
170    /// ICE connectivity and DTLS encryption are successfully established.
171    ///
172    /// This is the desired state for active media communication.
173    Connected,
174
175    /// Connection was established but has been lost.
176    ///
177    /// At least one ICE or DTLS transport is in "disconnected" state and none
178    /// are in "failed", "connecting", or "checking" state. This may be a
179    /// temporary condition due to network changes.
180    ///
181    /// ICE will attempt to restore connectivity automatically. If it succeeds,
182    /// the state will return to Connected. If it fails, the state will move to
183    /// Failed.
184    Disconnected,
185
186    /// Connection has permanently failed.
187    ///
188    /// At least one ICE or DTLS transport is in "failed" state. The connection
189    /// cannot be established or restored without intervention, typically
190    /// requiring an ICE restart.
191    ///
192    /// Common causes: NAT/firewall blocking, network unreachable, DTLS
193    /// handshake failure.
194    Failed,
195
196    /// Connection has been closed.
197    ///
198    /// The peer connection's `isClosed` member is true. All transports have
199    /// been shut down. No further communication is possible.
200    Closed,
201}
202
203const PEER_CONNECTION_STATE_NEW_STR: &str = "new";
204const PEER_CONNECTION_STATE_CONNECTING_STR: &str = "connecting";
205const PEER_CONNECTION_STATE_CONNECTED_STR: &str = "connected";
206const PEER_CONNECTION_STATE_DISCONNECTED_STR: &str = "disconnected";
207const PEER_CONNECTION_STATE_FAILED_STR: &str = "failed";
208const PEER_CONNECTION_STATE_CLOSED_STR: &str = "closed";
209
210impl From<&str> for RTCPeerConnectionState {
211    fn from(raw: &str) -> Self {
212        match raw {
213            PEER_CONNECTION_STATE_NEW_STR => RTCPeerConnectionState::New,
214            PEER_CONNECTION_STATE_CONNECTING_STR => RTCPeerConnectionState::Connecting,
215            PEER_CONNECTION_STATE_CONNECTED_STR => RTCPeerConnectionState::Connected,
216            PEER_CONNECTION_STATE_DISCONNECTED_STR => RTCPeerConnectionState::Disconnected,
217            PEER_CONNECTION_STATE_FAILED_STR => RTCPeerConnectionState::Failed,
218            PEER_CONNECTION_STATE_CLOSED_STR => RTCPeerConnectionState::Closed,
219            _ => RTCPeerConnectionState::Unspecified,
220        }
221    }
222}
223
224impl From<u8> for RTCPeerConnectionState {
225    fn from(v: u8) -> Self {
226        match v {
227            1 => RTCPeerConnectionState::New,
228            2 => RTCPeerConnectionState::Connecting,
229            3 => RTCPeerConnectionState::Connected,
230            4 => RTCPeerConnectionState::Disconnected,
231            5 => RTCPeerConnectionState::Failed,
232            6 => RTCPeerConnectionState::Closed,
233            _ => RTCPeerConnectionState::Unspecified,
234        }
235    }
236}
237
238impl fmt::Display for RTCPeerConnectionState {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        let s = match *self {
241            RTCPeerConnectionState::New => PEER_CONNECTION_STATE_NEW_STR,
242            RTCPeerConnectionState::Connecting => PEER_CONNECTION_STATE_CONNECTING_STR,
243            RTCPeerConnectionState::Connected => PEER_CONNECTION_STATE_CONNECTED_STR,
244            RTCPeerConnectionState::Disconnected => PEER_CONNECTION_STATE_DISCONNECTED_STR,
245            RTCPeerConnectionState::Failed => PEER_CONNECTION_STATE_FAILED_STR,
246            RTCPeerConnectionState::Closed => PEER_CONNECTION_STATE_CLOSED_STR,
247            RTCPeerConnectionState::Unspecified => UNSPECIFIED_STR,
248        };
249        write!(f, "{s}")
250    }
251}
252
253#[derive(Default, Debug, Copy, Clone, PartialEq)]
254pub(crate) enum NegotiationNeededState {
255    /// NegotiationNeededStateEmpty not running and queue is empty
256    #[default]
257    Empty,
258    /// NegotiationNeededStateEmpty running and queue is empty
259    Run,
260    /// NegotiationNeededStateEmpty running and queue
261    Queue,
262}
263
264impl From<u8> for NegotiationNeededState {
265    fn from(v: u8) -> Self {
266        match v {
267            1 => NegotiationNeededState::Run,
268            2 => NegotiationNeededState::Queue,
269            _ => NegotiationNeededState::Empty,
270        }
271    }
272}
273
274#[cfg(test)]
275mod test {
276    use super::*;
277
278    #[test]
279    fn test_new_peer_connection_state() {
280        let tests = vec![
281            (UNSPECIFIED_STR, RTCPeerConnectionState::Unspecified),
282            ("new", RTCPeerConnectionState::New),
283            ("connecting", RTCPeerConnectionState::Connecting),
284            ("connected", RTCPeerConnectionState::Connected),
285            ("disconnected", RTCPeerConnectionState::Disconnected),
286            ("failed", RTCPeerConnectionState::Failed),
287            ("closed", RTCPeerConnectionState::Closed),
288        ];
289
290        for (state_string, expected_state) in tests {
291            assert_eq!(
292                RTCPeerConnectionState::from(state_string),
293                expected_state,
294                "testCase: {expected_state}",
295            );
296        }
297    }
298
299    #[test]
300    fn test_peer_connection_state_string() {
301        let tests = vec![
302            (RTCPeerConnectionState::Unspecified, UNSPECIFIED_STR),
303            (RTCPeerConnectionState::New, "new"),
304            (RTCPeerConnectionState::Connecting, "connecting"),
305            (RTCPeerConnectionState::Connected, "connected"),
306            (RTCPeerConnectionState::Disconnected, "disconnected"),
307            (RTCPeerConnectionState::Failed, "failed"),
308            (RTCPeerConnectionState::Closed, "closed"),
309        ];
310
311        for (state, expected_string) in tests {
312            assert_eq!(state.to_string(), expected_string)
313        }
314    }
315}