Skip to main content

adk_realtime/
error.rs

1//! Error types for the realtime module.
2
3use thiserror::Error;
4
5/// Result type for realtime operations.
6pub type Result<T> = std::result::Result<T, RealtimeError>;
7
8/// Errors that can occur during realtime operations.
9#[derive(Error, Debug)]
10pub enum RealtimeError {
11    /// WebSocket connection error.
12    #[error("WebSocket connection error: {0}")]
13    ConnectionError(String),
14
15    /// WebSocket message error.
16    #[error("WebSocket message error: {0}")]
17    MessageError(String),
18
19    /// Authentication error.
20    #[error("Authentication error: {0}")]
21    AuthError(String),
22
23    /// Session not connected.
24    #[error("Session not connected")]
25    NotConnected,
26
27    /// Session already closed.
28    #[error("Session already closed")]
29    SessionClosed,
30
31    /// Invalid configuration.
32    #[error("Invalid configuration: {0}")]
33    ConfigError(String),
34
35    /// Audio format error.
36    #[error("Audio format error: {0}")]
37    AudioFormatError(String),
38
39    /// Tool execution error.
40    #[error("Tool execution error: {0}")]
41    ToolError(String),
42
43    /// An output guardrail blocked the model's text or transcript; the response was
44    /// interrupted and the text was not persisted.
45    #[error("output blocked by guardrail {guardrail}: {reason}")]
46    OutputBlocked {
47        /// The guardrail that blocked the text.
48        guardrail: String,
49        /// Why it blocked, as the guardrail reported.
50        reason: String,
51    },
52
53    /// The run's spend ledger refused to reserve the next response, so the session ended.
54    #[error("spend ledger refused the response: {0}")]
55    SpendRefused(String),
56
57    /// Server returned an error.
58    #[error("Server error: {code} - {message}")]
59    ServerError {
60        /// Error code from the server.
61        code: String,
62        /// Error message from the server.
63        message: String,
64    },
65
66    /// Timeout waiting for response.
67    #[error("Timeout: {0}")]
68    Timeout(String),
69
70    /// Serialization/deserialization error.
71    #[error("Serialization error: {0}")]
72    SerializationError(#[from] serde_json::Error),
73
74    /// Provider-specific error.
75    #[error("Provider error: {0}")]
76    ProviderError(String),
77
78    /// Generic IO error.
79    #[error("IO error: {0}")]
80    IoError(#[from] std::io::Error),
81
82    /// Opus codec error.
83    #[error("Opus codec error: {0}")]
84    OpusCodecError(String),
85
86    /// WebRTC error.
87    #[error("WebRTC error: {0}")]
88    WebRTCError(String),
89
90    /// LiveKit bridge error (legacy string format).
91    #[error("LiveKit error: {0}")]
92    LiveKitError(String),
93
94    /// Native LiveKit component error.
95    #[cfg(feature = "livekit")]
96    #[error(transparent)]
97    LiveKitNativeError(Box<crate::livekit::LiveKitError>),
98}
99
100#[cfg(feature = "livekit")]
101/// Manually implemented to box the inner error, keeping `Result` small on the happy path.
102impl From<crate::livekit::LiveKitError> for RealtimeError {
103    fn from(err: crate::livekit::LiveKitError) -> Self {
104        RealtimeError::LiveKitNativeError(Box::new(err))
105    }
106}
107
108impl RealtimeError {
109    /// The error's variant as a fixed name, which carries none of its message and so may be
110    /// logged whatever the payload rule.
111    pub(crate) fn kind(&self) -> &'static str {
112        match self {
113            Self::ConnectionError(_) => "connection",
114            Self::MessageError(_) => "message",
115            Self::AuthError(_) => "auth",
116            Self::NotConnected => "not_connected",
117            Self::SessionClosed => "session_closed",
118            Self::ConfigError(_) => "config",
119            Self::AudioFormatError(_) => "audio_format",
120            Self::ToolError(_) => "tool",
121            Self::OutputBlocked { .. } => "output_blocked",
122            Self::SpendRefused(_) => "spend_refused",
123            Self::ServerError { .. } => "server",
124            Self::Timeout(_) => "timeout",
125            Self::SerializationError(_) => "serialization",
126            Self::ProviderError(_) => "provider",
127            Self::IoError(_) => "io",
128            Self::OpusCodecError(_) => "opus_codec",
129            Self::WebRTCError(_) => "webrtc",
130            Self::LiveKitError(_) => "livekit",
131            #[cfg(feature = "livekit")]
132            Self::LiveKitNativeError(_) => "livekit_native",
133        }
134    }
135
136    /// Create a new connection error.
137    pub fn connection<S: Into<String>>(msg: S) -> Self {
138        Self::ConnectionError(msg.into())
139    }
140
141    /// Create a new server error.
142    pub fn server<S: Into<String>>(code: S, message: S) -> Self {
143        Self::ServerError { code: code.into(), message: message.into() }
144    }
145
146    /// Create a new provider error.
147    pub fn provider<S: Into<String>>(msg: S) -> Self {
148        Self::ProviderError(msg.into())
149    }
150
151    /// Create a new avatar provider error.
152    ///
153    /// Convenience constructor that prefixes the message with "avatar:"
154    /// for clear identification in logs.
155    #[cfg(feature = "video-avatar")]
156    pub fn avatar<S: Into<String>>(msg: S) -> Self {
157        Self::ProviderError(format!("avatar: {}", msg.into()))
158    }
159
160    /// Create a new configuration error.
161    pub fn config<S: Into<String>>(msg: S) -> Self {
162        Self::ConfigError(msg.into())
163    }
164
165    /// Create a new protocol error.
166    pub fn protocol<S: Into<String>>(msg: S) -> Self {
167        Self::MessageError(msg.into())
168    }
169
170    /// Create a new audio format error.
171    pub fn audio<S: Into<String>>(msg: S) -> Self {
172        Self::AudioFormatError(msg.into())
173    }
174
175    /// Create a new Opus codec error.
176    pub fn opus(msg: impl Into<String>) -> Self {
177        Self::OpusCodecError(msg.into())
178    }
179
180    /// Create a new WebRTC error.
181    pub fn webrtc(msg: impl Into<String>) -> Self {
182        Self::WebRTCError(msg.into())
183    }
184
185    /// Create a new LiveKit error.
186    pub fn livekit(msg: impl Into<String>) -> Self {
187        Self::LiveKitError(msg.into())
188    }
189}
190
191#[cfg(test)]
192mod tests {
193
194    #[cfg(feature = "livekit")]
195    #[test]
196    fn test_livekit_native_error_conversion() {
197        // Construct a simple LiveKitError variant
198        let inner = crate::livekit::LiveKitError::ConfigError("test config error".to_string());
199
200        // Convert into RealtimeError
201        let realtime_err: crate::error::RealtimeError = inner.into();
202
203        // Verify it matches the Boxed variant and formats correctly
204        match realtime_err {
205            crate::error::RealtimeError::LiveKitNativeError(boxed_err) => {
206                assert!(matches!(*boxed_err, crate::livekit::LiveKitError::ConfigError(_)));
207                assert_eq!(
208                    format!("{}", boxed_err),
209                    "LiveKit configuration error: test config error"
210                );
211            }
212            _ => panic!("Expected LiveKitNativeError variant"),
213        }
214    }
215}