1use std::error::Error;
20use std::fmt;
21
22use async_trait::async_trait;
23use gadk_genai::{Blob, Content};
24
25use crate::LlmResponse;
26
27#[derive(Debug, Clone, PartialEq)]
30pub enum RealtimeInput {
31 Blob(Blob),
33 ActivityStart,
35 ActivityEnd,
37 AudioStreamEnd,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[non_exhaustive]
44pub enum LiveConnErrorKind {
45 ConnectionLost,
48 Closed {
50 code: u16,
52 },
53 Other,
55}
56
57#[derive(Debug)]
59pub struct LiveConnError {
60 pub kind: LiveConnErrorKind,
62 pub message: String,
64 pub source: Option<Box<dyn Error + Send + Sync>>,
66}
67
68const RESUMABLE_TEXT: [&str; 4] = ["broken pipe", "connection reset", "EOF", "GoAway"];
70
71const CLOSE_POLICY_VIOLATION: u16 = 1008;
73
74impl LiveConnError {
75 pub fn new(kind: LiveConnErrorKind, message: impl Into<String>) -> Self {
77 Self {
78 kind,
79 message: message.into(),
80 source: None,
81 }
82 }
83
84 pub fn with_source(mut self, source: impl Into<Box<dyn Error + Send + Sync>>) -> Self {
86 self.source = Some(source.into());
87 self
88 }
89
90 pub fn eof() -> Self {
92 Self::new(LiveConnErrorKind::ConnectionLost, "EOF")
93 }
94
95 pub fn is_resumable(&self) -> bool {
99 match self.kind {
100 LiveConnErrorKind::ConnectionLost => true,
101 LiveConnErrorKind::Closed { code } if code == CLOSE_POLICY_VIOLATION => true,
102 _ => RESUMABLE_TEXT.iter().any(|t| self.message.contains(t)),
103 }
104 }
105}
106
107impl fmt::Display for LiveConnError {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.write_str(&self.message)
110 }
111}
112
113impl Error for LiveConnError {
114 fn source(&self) -> Option<&(dyn Error + 'static)> {
115 self.source.as_deref().map(|e| e as &(dyn Error + 'static))
116 }
117}
118
119#[async_trait]
122pub trait LiveConnection: Send + Sync {
123 async fn send_history(&self, history: &[Content]) -> Result<(), LiveConnError>;
125 async fn send_content(&self, content: Content) -> Result<(), LiveConnError>;
127 async fn send_realtime(&self, input: RealtimeInput) -> Result<(), LiveConnError>;
129 async fn recv(&self) -> Result<Option<LlmResponse>, LiveConnError>;
133 async fn close(&self) -> Result<(), LiveConnError>;
135}
136
137#[cfg(test)]
138#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
139mod tests {
140 use std::any::Any;
141 use std::error::Error;
142
143 use futures::stream::BoxStream;
144 use gadk_genai::LiveConnectConfig;
145
146 use super::{LiveConnError, LiveConnErrorKind};
147 use crate::{Llm, LlmRequest, LlmResponse, ModelError};
148
149 struct NoLive;
150
151 impl Llm for NoLive {
152 fn name(&self) -> &str {
153 "no-live"
154 }
155 fn generate_content(
156 &self,
157 _req: LlmRequest,
158 _stream: bool,
159 ) -> BoxStream<'static, Result<LlmResponse, ModelError>> {
160 Box::pin(futures::stream::empty())
161 }
162 fn as_any(&self) -> &dyn Any {
163 self
164 }
165 }
166
167 #[tokio::test]
168 async fn live_default_connect_live_is_unsupported() {
169 let m: &dyn Llm = &NoLive;
170 let Err(err) = m.connect_live(LiveConnectConfig::default()).await else {
171 panic!("the default connect_live must fail");
172 };
173 assert!(matches!(err, ModelError::Other(_)), "{err:?}");
174 assert_eq!(err.to_string(), "model does not support live connection");
175 }
176
177 fn other(msg: &str) -> LiveConnError {
178 LiveConnError::new(LiveConnErrorKind::Other, msg)
179 }
180
181 #[test]
182 fn live_is_resumable_follows_go_is_resumable() {
183 let cases: Vec<(&str, LiveConnError, bool)> = vec![
184 ("eof", LiveConnError::eof(), true),
185 (
186 "connection lost",
187 LiveConnError::new(
188 LiveConnErrorKind::ConnectionLost,
189 "failed to send message: IO error: x",
190 ),
191 true,
192 ),
193 (
194 "close 1008",
195 LiveConnError::new(
196 LiveConnErrorKind::Closed { code: 1008 },
197 "websocket: close 1008 (policy violation)",
198 ),
199 true,
200 ),
201 (
202 "close 1002",
203 LiveConnError::new(
204 LiveConnErrorKind::Closed { code: 1002 },
205 "websocket: close 1002 (protocol error): fatal",
206 ),
207 false,
208 ),
209 (
211 "close 1002 with EOF in reason",
212 LiveConnError::new(
213 LiveConnErrorKind::Closed { code: 1002 },
214 "websocket: close 1002 (protocol error): unexpected EOF",
215 ),
216 true,
217 ),
218 (
219 "close 1002 with 1008 in reason",
220 LiveConnError::new(
221 LiveConnErrorKind::Closed { code: 1002 },
222 "websocket: close 1002 (protocol error): error 1008",
223 ),
224 false,
225 ),
226 ("broken pipe text", other("write: broken pipe"), true),
227 (
228 "connection reset text",
229 other("read: connection reset by peer"),
230 true,
231 ),
232 (
233 "EOF text",
234 other(
235 "failed to receive message: websocket: close 1006 (abnormal closure): unexpected EOF",
236 ),
237 true,
238 ),
239 ("GoAway text", other("GoAway received"), true),
240 (
241 "1008 in a port is not a code",
242 other(
243 "failed to receive message: read tcp 127.0.0.1:41008->127.0.0.1:42207: i/o timeout",
244 ),
245 false,
246 ),
247 (
248 "application error",
249 other("model refused the request"),
250 false,
251 ),
252 ];
253 for (name, err, want) in cases {
254 assert_eq!(err.is_resumable(), want, "{name}: {err}");
255 }
256 }
257
258 #[test]
259 fn live_display_is_message_and_source_is_kept() {
260 let src = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe");
261 let err = LiveConnError::new(
262 LiveConnErrorKind::ConnectionLost,
263 "failed to send message: pipe",
264 )
265 .with_source(src);
266 assert_eq!(err.to_string(), "failed to send message: pipe");
267 assert_eq!(err.kind, LiveConnErrorKind::ConnectionLost);
268 let source = err.source().expect("source kept");
269 assert!(source.downcast_ref::<std::io::Error>().is_some());
270 let eof = LiveConnError::eof();
271 assert_eq!(
272 (eof.kind, eof.message.as_str()),
273 (LiveConnErrorKind::ConnectionLost, "EOF")
274 );
275 assert!(eof.source.is_none());
276 }
277}