Skip to main content

rtflow_core/
error.rs

1//! Stable error classification for retry, protocol mapping and telemetry.
2use std::io;
3use thiserror::Error;
4
5#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
6#[non_exhaustive]
7pub enum ErrorCode {
8    InvalidProtocol,
9    InvalidMedia,
10    InvalidState,
11    Timeout,
12    ResourceExhausted,
13    Unauthorized,
14    Forbidden,
15    Unsupported,
16    UpstreamUnavailable,
17    Io,
18    Closed,
19    Internal,
20    SrtpAuthenticationFailed,
21    SrtpReplayDetected,
22}
23
24#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
25pub enum RetryClass {
26    Never,
27    Immediate,
28    Backoff,
29}
30
31#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
32#[non_exhaustive]
33pub enum Operation {
34    Unknown,
35    Accept,
36    Connect,
37    ReadControl,
38    WriteControl,
39    ParseControl,
40    SetupTransport,
41    ReadMedia,
42    WriteMedia,
43    Authenticate,
44    Authorize,
45    RegisterMount,
46    ProxyConnect,
47    PipelineProcess,
48    Shutdown,
49    SrtpProtect,
50    SrtpUnprotect,
51}
52
53#[derive(Debug, Error)]
54#[non_exhaustive]
55pub enum Error {
56    #[error("invalid RTSP message: {0}")]
57    Rtsp(String),
58    #[error("invalid media payload: {0}")]
59    Media(String),
60    #[error("HTTP/WebSocket error: {0}")]
61    Http(String),
62    #[error("invalid configuration: {0}")]
63    InvalidConfig(String),
64    #[error("unsupported: {0}")]
65    Unsupported(String),
66    #[error("I/O error: {0}")]
67    Io(#[from] io::Error),
68    #[error("TLS error: {0}")]
69    Tls(String),
70    #[error("RTSP redirect to {0}")]
71    Redirect(String),
72    #[error("{method} returned 551 (unsupported: {unsupported:?})")]
73    RtspUnsupported {
74        method: String,
75        unsupported: Vec<String>,
76    },
77    #[error("session closed")]
78    Closed,
79    #[error("resource limit exceeded: {0}")]
80    Limit(&'static str),
81    #[error("not found: {0}")]
82    NotFound(String),
83    #[error("conflict: {0}")]
84    Conflict(String),
85    #[error("authentication failed")]
86    Unauthorized,
87    /// Non-2xx response to an RTSP control request.
88    #[error("{method} returned {status}")]
89    RtspStatus { method: &'static str, status: u16 },
90    #[error("SRTP error: {0}")]
91    Srtp(String),
92    #[error("RTMP error: {0}")]
93    Rtmp(String),
94    #[error("SRT error: {0}")]
95    Srt(String),
96    #[error("WebRTC error: {0}")]
97    Webrtc(String),
98}
99
100impl Error {
101    pub fn code(&self) -> ErrorCode {
102        match self {
103            Self::Rtsp(_) => ErrorCode::InvalidProtocol,
104            Self::Media(_) => ErrorCode::InvalidMedia,
105            Self::Http(_) => ErrorCode::InvalidProtocol,
106            Self::InvalidConfig(_) => ErrorCode::InvalidState,
107            Self::Unsupported(_) => ErrorCode::Unsupported,
108            Self::Io(error) if error.kind() == io::ErrorKind::TimedOut => ErrorCode::Timeout,
109            Self::Io(_) | Self::Tls(_) => ErrorCode::Io,
110            Self::Redirect(_) => ErrorCode::InvalidState,
111            Self::RtspUnsupported { .. } => ErrorCode::Unsupported,
112            Self::Closed => ErrorCode::Closed,
113            Self::Limit(_) => ErrorCode::ResourceExhausted,
114            Self::NotFound(_) | Self::Conflict(_) => ErrorCode::InvalidState,
115            Self::Unauthorized => ErrorCode::Unauthorized,
116            Self::RtspStatus { status: 401, .. } => ErrorCode::Unauthorized,
117            Self::RtspStatus { status: 403, .. } => ErrorCode::Forbidden,
118            Self::RtspStatus { status: 404, .. } => ErrorCode::InvalidState,
119            Self::RtspStatus { status: 453, .. } => ErrorCode::ResourceExhausted,
120            Self::RtspStatus { status: 461, .. } => ErrorCode::Unsupported,
121            Self::RtspStatus {
122                status: 500..=599, ..
123            } => ErrorCode::UpstreamUnavailable,
124            Self::RtspStatus { .. } => ErrorCode::InvalidProtocol,
125            Self::Srtp(_) => ErrorCode::InvalidMedia,
126            Self::Rtmp(_) => ErrorCode::InvalidProtocol,
127            Self::Srt(_) => ErrorCode::InvalidProtocol,
128            Self::Webrtc(_) => ErrorCode::InvalidProtocol,
129        }
130    }
131
132    pub fn retry_class(&self) -> RetryClass {
133        match self {
134            Self::Io(error)
135                if matches!(
136                    error.kind(),
137                    io::ErrorKind::ConnectionRefused
138                        | io::ErrorKind::ConnectionReset
139                        | io::ErrorKind::ConnectionAborted
140                        | io::ErrorKind::BrokenPipe
141                        | io::ErrorKind::TimedOut
142                ) =>
143            {
144                RetryClass::Backoff
145            }
146            Self::Redirect(_) | Self::RtspUnsupported { .. } => RetryClass::Never,
147            Self::Closed => RetryClass::Immediate,
148            Self::RtspStatus {
149                status: 500..=599 | 408 | 453 | 461,
150                ..
151            } => RetryClass::Backoff,
152            Self::RtspStatus { .. } => RetryClass::Never,
153            Self::Srtp(_) => RetryClass::Never,
154            _ => RetryClass::Never,
155        }
156    }
157
158    pub fn rtsp_status(&self) -> u16 {
159        match self {
160            Self::Unauthorized => 401,
161            Self::RtspStatus { status, .. } => *status,
162            Self::NotFound(_) => 404,
163            Self::Conflict(_) => 455,
164            Self::Limit(_) => 453,
165            Self::Redirect(_) => 503,
166            Self::RtspUnsupported { .. } => 551,
167            Self::Rtsp(_) | Self::Media(_) => 400,
168            Self::Http(_) | Self::InvalidConfig(_) => 500,
169            Self::Unsupported(_) => 501,
170            Self::Srtp(_) => 400,
171            Self::Rtmp(_) => 400,
172            Self::Srt(_) => 400,
173            Self::Webrtc(_) => 400,
174            Self::Closed | Self::Io(_) | Self::Tls(_) => 500,
175        }
176    }
177}
178
179pub type Result<T, E = Error> = std::result::Result<T, E>;
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    #[test]
185    fn errors_have_stable_operational_metadata() {
186        let limit = Error::Limit("sessions");
187        assert_eq!(limit.code(), ErrorCode::ResourceExhausted);
188        assert_eq!(limit.retry_class(), RetryClass::Never);
189        assert_eq!(limit.rtsp_status(), 453);
190        let reset = Error::Io(io::Error::new(io::ErrorKind::ConnectionReset, "reset"));
191        assert_eq!(reset.code(), ErrorCode::Io);
192        assert_eq!(reset.retry_class(), RetryClass::Backoff);
193        // Domain-specific variants map to their own codes/statuses.
194        assert_eq!(
195            Error::Http("bad request".into()).code(),
196            ErrorCode::InvalidProtocol
197        );
198        assert_eq!(Error::Http("bad request".into()).rtsp_status(), 500);
199        assert_eq!(
200            Error::InvalidConfig("bad CIDR".into()).code(),
201            ErrorCode::InvalidState
202        );
203        assert_eq!(
204            Error::Unsupported("ipv6 multicast".into()).code(),
205            ErrorCode::Unsupported
206        );
207        assert_eq!(
208            Error::Unsupported("ipv6 multicast".into()).rtsp_status(),
209            501
210        );
211        // Typed RTSP status errors carry stable operational metadata.
212        let unauthorized = Error::RtspStatus {
213            method: "OPTIONS",
214            status: 401,
215        };
216        assert_eq!(unauthorized.code(), ErrorCode::Unauthorized);
217        assert_eq!(unauthorized.retry_class(), RetryClass::Never);
218        assert_eq!(unauthorized.rtsp_status(), 401);
219        let unsupported_transport = Error::RtspStatus {
220            method: "SETUP",
221            status: 461,
222        };
223        assert_eq!(unsupported_transport.code(), ErrorCode::Unsupported);
224        assert_eq!(unsupported_transport.retry_class(), RetryClass::Backoff);
225        assert_eq!(unsupported_transport.rtsp_status(), 461);
226        let server_error = Error::RtspStatus {
227            method: "SETUP",
228            status: 500,
229        };
230        assert_eq!(server_error.code(), ErrorCode::UpstreamUnavailable);
231        assert_eq!(server_error.retry_class(), RetryClass::Backoff);
232        assert_eq!(server_error.rtsp_status(), 500);
233        let bandwidth = Error::RtspStatus {
234            method: "PLAY",
235            status: 453,
236        };
237        assert_eq!(bandwidth.code(), ErrorCode::ResourceExhausted);
238        assert_eq!(bandwidth.retry_class(), RetryClass::Backoff);
239        let permanent = Error::RtspStatus {
240            method: "PLAY",
241            status: 455,
242        };
243        assert_eq!(permanent.retry_class(), RetryClass::Never);
244    }
245}