Skip to main content

rtc/peer_connection/state/
ice_connection_state.rs

1use crate::peer_connection::configuration::UNSPECIFIED_STR;
2use ice::state::ConnectionState;
3use std::fmt;
4
5/// Indicates the state of the ICE connection.
6///
7/// `RTCIceConnectionState` describes the current state of the ICE (Interactive
8/// Connectivity Establishment) transport layer, which is responsible for establishing
9/// network connectivity between peers through NAT traversal.
10///
11/// # State Transitions
12///
13/// The ICE connection typically progresses through these states:
14///
15/// 1. **New** - Initial state, no connectivity checks yet
16/// 2. **Checking** - ICE agent is checking candidate pairs
17/// 3. **Connected** - At least one working candidate pair found
18/// 4. **Completed** - ICE has finished checking all candidates
19///
20/// The connection may also enter error states:
21///
22/// - **Disconnected** - Connectivity lost but recovery possible
23/// - **Failed** - All candidate pairs failed, connection cannot be established
24/// - **Closed** - Connection has been closed
25///
26/// # Examples
27///
28/// ## Monitoring ICE State Changes
29///
30/// ```no_run
31/// use rtc::peer_connection::state::RTCIceConnectionState;
32/// use rtc::peer_connection::event::RTCPeerConnectionEvent;
33///
34/// # fn handle_event(event: RTCPeerConnectionEvent) {
35/// match event {
36///     RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(state) => {
37///         match state {
38///             RTCIceConnectionState::New => {
39///                 println!("ICE connectivity checking not started");
40///             }
41///             RTCIceConnectionState::Checking => {
42///                 println!("ICE agent is checking connectivity...");
43///             }
44///             RTCIceConnectionState::Connected => {
45///                 println!("ICE connected! Media can flow.");
46///             }
47///             RTCIceConnectionState::Completed => {
48///                 println!("ICE finished checking all candidates");
49///             }
50///             RTCIceConnectionState::Disconnected => {
51///                 println!("ICE connection lost - may reconnect");
52///             }
53///             RTCIceConnectionState::Failed => {
54///                 println!("ICE failed - cannot establish connection");
55///             }
56///             RTCIceConnectionState::Closed => {
57///                 println!("ICE connection closed");
58///             }
59///             _ => {}
60///         }
61///     }
62///     _ => {}
63/// }
64/// # }
65/// ```
66///
67/// ## String Conversion
68///
69/// ```
70/// use rtc::peer_connection::state::RTCIceConnectionState;
71///
72/// // Convert state to string
73/// let state = RTCIceConnectionState::Connected;
74/// assert_eq!(state.to_string(), "connected");
75///
76/// // Parse from string
77/// let parsed: RTCIceConnectionState = "checking".into();
78/// assert_eq!(parsed, RTCIceConnectionState::Checking);
79/// ```
80///
81/// ## Checking for Active Connection
82///
83/// ```
84/// use rtc::peer_connection::state::RTCIceConnectionState;
85///
86/// fn is_ice_active(state: RTCIceConnectionState) -> bool {
87///     matches!(
88///         state,
89///         RTCIceConnectionState::Connected | RTCIceConnectionState::Completed
90///     )
91/// }
92///
93/// assert!(is_ice_active(RTCIceConnectionState::Connected));
94/// assert!(is_ice_active(RTCIceConnectionState::Completed));
95/// assert!(!is_ice_active(RTCIceConnectionState::Disconnected));
96/// ```
97///
98/// # Specifications
99///
100/// - [W3C RTCPeerConnection.iceConnectionState]
101/// - [MDN RTCPeerConnection.iceConnectionState]
102/// - [RFC 8445] - ICE Protocol
103///
104/// [W3C RTCPeerConnection.iceConnectionState]: https://w3c.github.io/webrtc-pc/#dom-peerconnection-ice-connection-state
105/// [MDN RTCPeerConnection.iceConnectionState]: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
106/// [RFC 8445]: https://datatracker.ietf.org/doc/html/rfc8445
107#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
108pub enum RTCIceConnectionState {
109    /// State not specified. This should not occur in normal operation.
110    #[default]
111    Unspecified,
112
113    /// ICE agent is gathering addresses or waiting to be given remote candidates.
114    ///
115    /// This is the initial state before connectivity checks begin. Any of the
116    /// ICE transports are in the "new" state and none are in "checking",
117    /// "disconnected", or "failed" state, or all ICE transports are in the
118    /// "closed" state, or there are no transports.
119    New,
120
121    /// ICE agent has been given remote candidates and is checking pairs.
122    ///
123    /// The ICE agent is actively checking candidate pairs to find a working
124    /// connection. At least one ICE transport is in the "checking" state and
125    /// none are in "disconnected" or "failed" state.
126    Checking,
127
128    /// ICE agent has found a usable connection for all components.
129    ///
130    /// A working candidate pair has been found and is being used for
131    /// communication. All ICE transports are in "connected", "completed",
132    /// or "closed" state, and at least one is in the "connected" state.
133    ///
134    /// Media can flow in this state.
135    Connected,
136
137    /// ICE agent has finished gathering and checking candidates.
138    ///
139    /// The ICE agent has finished checking all candidate pairs and found
140    /// working connections. All ICE transports are in "completed" or "closed"
141    /// state, and at least one is in "completed" state.
142    ///
143    /// This is a more stable state than Connected.
144    Completed,
145
146    /// ICE connection has been lost, but recovery may be possible.
147    ///
148    /// The connection was working but has been lost. The ICE agent may be
149    /// able to re-establish connectivity through ICE restart. At least one
150    /// ICE transport is in "disconnected" state and none are in "failed" state.
151    ///
152    /// Consider triggering ICE restart if this state persists.
153    Disconnected,
154
155    /// ICE agent has determined that connection is not possible.
156    ///
157    /// All candidate pairs have failed connectivity checks. At least one ICE
158    /// transport is in the "failed" state. Connection cannot be established
159    /// without ICE restart.
160    ///
161    /// This typically indicates NAT/firewall issues or network problems.
162    Failed,
163
164    /// ICE agent has shut down and is no longer processing candidates.
165    ///
166    /// The peer connection's `isClosed` is true. No further ICE processing
167    /// will occur.
168    Closed,
169}
170
171const ICE_CONNECTION_STATE_NEW_STR: &str = "new";
172const ICE_CONNECTION_STATE_CHECKING_STR: &str = "checking";
173const ICE_CONNECTION_STATE_CONNECTED_STR: &str = "connected";
174const ICE_CONNECTION_STATE_COMPLETED_STR: &str = "completed";
175const ICE_CONNECTION_STATE_DISCONNECTED_STR: &str = "disconnected";
176const ICE_CONNECTION_STATE_FAILED_STR: &str = "failed";
177const ICE_CONNECTION_STATE_CLOSED_STR: &str = "closed";
178
179/// takes a string and converts it to iceconnection_state
180impl From<&str> for RTCIceConnectionState {
181    fn from(raw: &str) -> Self {
182        match raw {
183            ICE_CONNECTION_STATE_NEW_STR => RTCIceConnectionState::New,
184            ICE_CONNECTION_STATE_CHECKING_STR => RTCIceConnectionState::Checking,
185            ICE_CONNECTION_STATE_CONNECTED_STR => RTCIceConnectionState::Connected,
186            ICE_CONNECTION_STATE_COMPLETED_STR => RTCIceConnectionState::Completed,
187            ICE_CONNECTION_STATE_DISCONNECTED_STR => RTCIceConnectionState::Disconnected,
188            ICE_CONNECTION_STATE_FAILED_STR => RTCIceConnectionState::Failed,
189            ICE_CONNECTION_STATE_CLOSED_STR => RTCIceConnectionState::Closed,
190            _ => RTCIceConnectionState::Unspecified,
191        }
192    }
193}
194
195impl From<u8> for RTCIceConnectionState {
196    fn from(v: u8) -> Self {
197        match v {
198            1 => RTCIceConnectionState::New,
199            2 => RTCIceConnectionState::Checking,
200            3 => RTCIceConnectionState::Connected,
201            4 => RTCIceConnectionState::Completed,
202            5 => RTCIceConnectionState::Disconnected,
203            6 => RTCIceConnectionState::Failed,
204            7 => RTCIceConnectionState::Closed,
205            _ => RTCIceConnectionState::Unspecified,
206        }
207    }
208}
209
210impl fmt::Display for RTCIceConnectionState {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        let s = match *self {
213            RTCIceConnectionState::New => ICE_CONNECTION_STATE_NEW_STR,
214            RTCIceConnectionState::Checking => ICE_CONNECTION_STATE_CHECKING_STR,
215            RTCIceConnectionState::Connected => ICE_CONNECTION_STATE_CONNECTED_STR,
216            RTCIceConnectionState::Completed => ICE_CONNECTION_STATE_COMPLETED_STR,
217            RTCIceConnectionState::Disconnected => ICE_CONNECTION_STATE_DISCONNECTED_STR,
218            RTCIceConnectionState::Failed => ICE_CONNECTION_STATE_FAILED_STR,
219            RTCIceConnectionState::Closed => ICE_CONNECTION_STATE_CLOSED_STR,
220            RTCIceConnectionState::Unspecified => UNSPECIFIED_STR,
221        };
222        write!(f, "{s}")
223    }
224}
225
226impl From<ConnectionState> for RTCIceConnectionState {
227    fn from(raw: ConnectionState) -> Self {
228        match raw {
229            ConnectionState::New => RTCIceConnectionState::New,
230            ConnectionState::Checking => RTCIceConnectionState::Checking,
231            ConnectionState::Connected => RTCIceConnectionState::Connected,
232            ConnectionState::Completed => RTCIceConnectionState::Completed,
233            ConnectionState::Failed => RTCIceConnectionState::Failed,
234            ConnectionState::Disconnected => RTCIceConnectionState::Disconnected,
235            ConnectionState::Closed => RTCIceConnectionState::Closed,
236            _ => RTCIceConnectionState::Unspecified,
237        }
238    }
239}
240
241impl RTCIceConnectionState {
242    pub(crate) fn to_ice(self) -> ConnectionState {
243        match self {
244            RTCIceConnectionState::New => ConnectionState::New,
245            RTCIceConnectionState::Checking => ConnectionState::Checking,
246            RTCIceConnectionState::Connected => ConnectionState::Connected,
247            RTCIceConnectionState::Completed => ConnectionState::Completed,
248            RTCIceConnectionState::Failed => ConnectionState::Failed,
249            RTCIceConnectionState::Disconnected => ConnectionState::Disconnected,
250            RTCIceConnectionState::Closed => ConnectionState::Closed,
251            _ => ConnectionState::Unspecified,
252        }
253    }
254}
255
256#[cfg(test)]
257mod test {
258    use super::*;
259
260    #[test]
261    fn test_new_ice_connection_state() {
262        let tests = vec![
263            (UNSPECIFIED_STR, RTCIceConnectionState::Unspecified),
264            ("new", RTCIceConnectionState::New),
265            ("checking", RTCIceConnectionState::Checking),
266            ("connected", RTCIceConnectionState::Connected),
267            ("completed", RTCIceConnectionState::Completed),
268            ("disconnected", RTCIceConnectionState::Disconnected),
269            ("failed", RTCIceConnectionState::Failed),
270            ("closed", RTCIceConnectionState::Closed),
271        ];
272
273        for (state_string, expected_state) in tests {
274            assert_eq!(
275                RTCIceConnectionState::from(state_string),
276                expected_state,
277                "testCase: {expected_state}",
278            );
279        }
280    }
281
282    #[test]
283    fn test_ice_connection_state_string() {
284        let tests = vec![
285            (RTCIceConnectionState::Unspecified, UNSPECIFIED_STR),
286            (RTCIceConnectionState::New, "new"),
287            (RTCIceConnectionState::Checking, "checking"),
288            (RTCIceConnectionState::Connected, "connected"),
289            (RTCIceConnectionState::Completed, "completed"),
290            (RTCIceConnectionState::Disconnected, "disconnected"),
291            (RTCIceConnectionState::Failed, "failed"),
292            (RTCIceConnectionState::Closed, "closed"),
293        ];
294
295        for (state, expected_string) in tests {
296            assert_eq!(state.to_string(), expected_string)
297        }
298    }
299}