Skip to main content

gemini_genai_rs/client/
http.rs

1//! HTTP client for Gemini REST APIs.
2//!
3//! Wraps `reqwest` with retry logic, telemetry, and typed errors.
4//! Feature-gated behind `http`.
5
6use std::time::Duration;
7
8use crate::telemetry;
9
10/// Configuration for the HTTP client.
11#[derive(Debug, Clone)]
12pub struct HttpConfig {
13    /// Request timeout.
14    pub timeout: Duration,
15    /// Maximum number of retries on transient errors (5xx, network).
16    pub max_retries: u32,
17    /// Base delay for exponential backoff between retries.
18    pub retry_base_delay: Duration,
19    /// Maximum delay between retries.
20    pub retry_max_delay: Duration,
21    /// User-Agent header value.
22    pub user_agent: String,
23}
24
25impl Default for HttpConfig {
26    fn default() -> Self {
27        Self {
28            timeout: Duration::from_secs(60),
29            max_retries: 3,
30            retry_base_delay: Duration::from_millis(500),
31            retry_max_delay: Duration::from_secs(30),
32            user_agent: format!("gemini-live/{}", env!("CARGO_PKG_VERSION")),
33        }
34    }
35}
36
37/// Errors from HTTP client operations.
38#[derive(Debug, thiserror::Error)]
39pub enum HttpError {
40    /// HTTP request failed.
41    #[error("HTTP request failed: {0}")]
42    Request(#[from] reqwest::Error),
43
44    /// Server returned an error status.
45    #[error("API error {status}: {message}")]
46    ApiError {
47        /// HTTP status code.
48        status: u16,
49        /// Error message from the API.
50        message: String,
51        /// Optional response body.
52        body: Option<serde_json::Value>,
53    },
54
55    /// Authentication error.
56    #[error("Auth error: {0}")]
57    Auth(#[from] crate::session::AuthError),
58
59    /// JSON deserialization error.
60    #[error("JSON parse error: {0}")]
61    Json(#[from] serde_json::Error),
62
63    /// The HTTP method string is not a valid method token.
64    #[error("invalid HTTP method {method:?}")]
65    InvalidMethod {
66        /// The rejected method string.
67        method: String,
68    },
69
70    /// All retries exhausted.
71    #[error("All {attempts} retries exhausted: {last_error}")]
72    RetriesExhausted {
73        /// Number of retry attempts made.
74        attempts: u32,
75        /// Error message from the last attempt.
76        last_error: String,
77    },
78}
79
80/// HTTP client wrapping reqwest with retry and telemetry.
81pub struct HttpClient {
82    inner: reqwest::Client,
83    config: HttpConfig,
84}
85
86impl HttpClient {
87    /// Create a new HTTP client with the given configuration.
88    pub fn new(config: HttpConfig) -> Self {
89        let inner = reqwest::Client::builder()
90            .timeout(config.timeout)
91            .user_agent(&config.user_agent)
92            .build()
93            .expect("Failed to build reqwest client");
94        Self { inner, config }
95    }
96
97    /// POST JSON to a URL and return the parsed response.
98    pub async fn post_json(
99        &self,
100        url: &str,
101        auth_headers: Vec<(String, String)>,
102        body: &impl serde::Serialize,
103    ) -> Result<serde_json::Value, HttpError> {
104        self.request_with_retry("POST", url, auth_headers, Some(body))
105            .await
106    }
107
108    /// PATCH JSON to a URL and return the parsed response.
109    pub async fn patch_json(
110        &self,
111        url: &str,
112        auth_headers: Vec<(String, String)>,
113        body: &impl serde::Serialize,
114    ) -> Result<serde_json::Value, HttpError> {
115        self.request_with_retry("PATCH", url, auth_headers, Some(body))
116            .await
117    }
118
119    /// PUT JSON to a URL and return the parsed response.
120    pub async fn put_json(
121        &self,
122        url: &str,
123        auth_headers: Vec<(String, String)>,
124        body: &impl serde::Serialize,
125    ) -> Result<serde_json::Value, HttpError> {
126        self.request_with_retry("PUT", url, auth_headers, Some(body))
127            .await
128    }
129
130    /// GET a URL and return the parsed response.
131    pub async fn get_json(
132        &self,
133        url: &str,
134        auth_headers: Vec<(String, String)>,
135    ) -> Result<serde_json::Value, HttpError> {
136        self.request_with_retry::<()>("GET", url, auth_headers, None)
137            .await
138    }
139
140    /// DELETE a URL and return the parsed response.
141    pub async fn delete(
142        &self,
143        url: &str,
144        auth_headers: Vec<(String, String)>,
145    ) -> Result<serde_json::Value, HttpError> {
146        self.request_with_retry::<()>("DELETE", url, auth_headers, None)
147            .await
148    }
149
150    /// POST JSON to a URL and stream the Server-Sent Events it answers with,
151    /// each event's `data` parsed as JSON.
152    ///
153    /// Transient failures are retried until the response starts, as for
154    /// [`post_json`](Self::post_json); after that the stream is not retried.
155    /// The client's timeout covers the whole stream.
156    pub async fn post_sse(
157        &self,
158        url: &str,
159        auth_headers: Vec<(String, String)>,
160        body: &impl serde::Serialize,
161    ) -> Result<
162        futures_util::stream::BoxStream<'static, Result<serde_json::Value, HttpError>>,
163        HttpError,
164    > {
165        use futures_util::StreamExt;
166
167        let response = self
168            .send_with_retry("POST", url, auth_headers, Some(body))
169            .await?;
170        let state = (
171            response,
172            SseDecoder::default(),
173            std::collections::VecDeque::<String>::new(),
174        );
175        let events = futures_util::stream::unfold(
176            state,
177            |(mut response, mut decoder, mut ready)| async move {
178                loop {
179                    if let Some(data) = ready.pop_front() {
180                        let parsed = serde_json::from_str::<serde_json::Value>(&data)
181                            .map_err(HttpError::from);
182                        return Some((parsed, (response, decoder, ready)));
183                    }
184                    match response.chunk().await {
185                        Ok(Some(bytes)) => ready.extend(decoder.push(&bytes)),
186                        Ok(None) => {
187                            ready.extend(decoder.finish());
188                            if ready.is_empty() {
189                                return None;
190                            }
191                        }
192                        Err(e) => {
193                            return Some((Err(HttpError::Request(e)), (response, decoder, ready)));
194                        }
195                    }
196                }
197            },
198        );
199        Ok(events.boxed())
200    }
201
202    /// Execute an HTTP request with exponential backoff retry on transient errors.
203    async fn request_with_retry<B: serde::Serialize>(
204        &self,
205        method: &str,
206        url: &str,
207        auth_headers: Vec<(String, String)>,
208        body: Option<&B>,
209    ) -> Result<serde_json::Value, HttpError> {
210        let response = self
211            .send_with_retry(method, url, auth_headers, body)
212            .await?;
213        let body = response.text().await?;
214        if body.is_empty() {
215            return Ok(serde_json::Value::Null);
216        }
217        Ok(serde_json::from_str(&body)?)
218    }
219
220    /// Send a request, retrying transient failures (5xx, 429, network) with
221    /// exponential backoff, and return the first successful response.
222    async fn send_with_retry<B: serde::Serialize>(
223        &self,
224        method: &str,
225        url: &str,
226        auth_headers: Vec<(String, String)>,
227        body: Option<&B>,
228    ) -> Result<reqwest::Response, HttpError> {
229        // Parse once, before any attempt: an invalid method can never succeed
230        // on retry, and it is not a transport failure.
231        let http_method = reqwest::Method::from_bytes(method.as_bytes()).map_err(|_| {
232            HttpError::InvalidMethod {
233                method: method.to_string(),
234            }
235        })?;
236        let mut last_error = String::new();
237
238        for attempt in 0..=self.config.max_retries {
239            if attempt > 0 {
240                let delay = self.backoff_delay(attempt);
241                telemetry::logging::log_http_retry(url, attempt, delay.as_millis() as u64);
242                tokio::time::sleep(delay).await;
243            }
244
245            telemetry::logging::log_http_request(method, url);
246            let _span = telemetry::spans::http_request_span(method, url);
247            let start = std::time::Instant::now();
248
249            match self
250                .execute_request(&http_method, url, &auth_headers, body)
251                .await
252            {
253                Ok(response) => {
254                    let status = response.status();
255                    let duration_ms = start.elapsed().as_millis() as f64;
256                    telemetry::metrics::record_http_request(method, status.as_u16(), duration_ms);
257                    telemetry::logging::log_http_response(status.as_u16(), duration_ms);
258
259                    if status.is_success() {
260                        return Ok(response);
261                    }
262
263                    let status_code = status.as_u16();
264                    let body_text = response.text().await.unwrap_or_default();
265                    let body_json: Option<serde_json::Value> =
266                        serde_json::from_str(&body_text).ok();
267
268                    // Extract error message
269                    let message = body_json
270                        .as_ref()
271                        .and_then(|v| v.get("error"))
272                        .and_then(|v| v.get("message"))
273                        .and_then(|v| v.as_str())
274                        .unwrap_or(&body_text)
275                        .to_string();
276
277                    // Retry on 5xx and 429 (rate limit)
278                    if is_retryable_status(status_code) && attempt < self.config.max_retries {
279                        last_error = format!("HTTP {status_code}: {message}");
280                        continue;
281                    }
282
283                    return Err(HttpError::ApiError {
284                        status: status_code,
285                        message,
286                        body: body_json,
287                    });
288                }
289                Err(e) => {
290                    let duration_ms = start.elapsed().as_millis() as f64;
291                    telemetry::metrics::record_http_request(method, 0, duration_ms);
292
293                    if is_retryable_error(&e) && attempt < self.config.max_retries {
294                        last_error = e.to_string();
295                        continue;
296                    }
297                    return Err(HttpError::Request(e));
298                }
299            }
300        }
301
302        Err(HttpError::RetriesExhausted {
303            attempts: self.config.max_retries + 1,
304            last_error,
305        })
306    }
307
308    /// Execute a single HTTP request (no retry).
309    async fn execute_request<B: serde::Serialize>(
310        &self,
311        method: &reqwest::Method,
312        url: &str,
313        auth_headers: &[(String, String)],
314        body: Option<&B>,
315    ) -> Result<reqwest::Response, reqwest::Error> {
316        let mut builder = self.inner.request(method.clone(), url);
317
318        for (key, value) in auth_headers {
319            builder = builder.header(key, value);
320        }
321
322        if let Some(body) = body {
323            builder = builder.json(body);
324        }
325
326        builder.send().await
327    }
328
329    /// Calculate exponential backoff delay.
330    fn backoff_delay(&self, attempt: u32) -> Duration {
331        let delay = self.config.retry_base_delay * 2u32.saturating_pow(attempt.saturating_sub(1));
332        std::cmp::min(delay, self.config.retry_max_delay)
333    }
334}
335
336/// Whether an HTTP status code is retryable.
337/// Splits a Server-Sent Events byte stream into the `data` of each event.
338///
339/// Bytes are buffered until an event is complete (a blank line), so an event
340/// or a UTF-8 character split across network chunks is decoded whole. Lines
341/// other than `data:` (`event:`, `id:`, comments) are ignored; the lines of a
342/// multi-line `data` field are joined with `\n`.
343#[derive(Debug, Default)]
344pub struct SseDecoder {
345    buffer: Vec<u8>,
346}
347
348impl SseDecoder {
349    /// Feed received bytes; returns the `data` of every event they complete.
350    pub fn push(&mut self, bytes: &[u8]) -> Vec<String> {
351        self.buffer.extend_from_slice(bytes);
352        let mut events = Vec::new();
353        while let Some((end, separator)) = find_event_end(&self.buffer) {
354            let event: Vec<u8> = self.buffer.drain(..end + separator).collect();
355            if let Some(data) = event_data(&event[..end]) {
356                events.push(data);
357            }
358        }
359        events
360    }
361
362    /// The stream ended: return the last event if it was not terminated.
363    pub fn finish(&mut self) -> Vec<String> {
364        let rest = std::mem::take(&mut self.buffer);
365        event_data(&rest).into_iter().collect()
366    }
367}
368
369/// Where the first complete event ends, and the length of its separator.
370fn find_event_end(buffer: &[u8]) -> Option<(usize, usize)> {
371    (0..buffer.len()).find_map(|i| {
372        if buffer[i..].starts_with(b"\r\n\r\n") {
373            Some((i, 4))
374        } else if buffer[i..].starts_with(b"\n\n") {
375            Some((i, 2))
376        } else {
377            None
378        }
379    })
380}
381
382/// The joined `data:` lines of one event, if it has any.
383fn event_data(event: &[u8]) -> Option<String> {
384    let text = String::from_utf8_lossy(event);
385    let data: Vec<&str> = text
386        .lines()
387        .filter_map(|line| line.strip_prefix("data:"))
388        .map(|value| value.strip_prefix(' ').unwrap_or(value))
389        .collect();
390    (!data.is_empty()).then(|| data.join("\n"))
391}
392
393fn is_retryable_status(status: u16) -> bool {
394    status == 429 || (500..600).contains(&status)
395}
396
397/// Whether a reqwest error is retryable (network, timeout).
398fn is_retryable_error(e: &reqwest::Error) -> bool {
399    e.is_timeout() || e.is_connect() || e.is_request()
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn sse_events_survive_arbitrary_chunk_boundaries() {
408        let wire = "data: {\"a\":1}\n\n: comment\nevent: x\ndata: {\"b\":\"é\"}\r\n\r\ndata: [1,\ndata: 2]\n\n";
409        let bytes = wire.as_bytes();
410        // Every split point, including one inside the two-byte `é`.
411        for split in 0..=bytes.len() {
412            let mut decoder = SseDecoder::default();
413            let mut events = decoder.push(&bytes[..split]);
414            events.extend(decoder.push(&bytes[split..]));
415            events.extend(decoder.finish());
416            assert_eq!(
417                events,
418                ["{\"a\":1}", "{\"b\":\"é\"}", "[1,\n2]"],
419                "split at {split}"
420            );
421        }
422    }
423
424    /// Serve one canned HTTP response, written in the given pieces.
425    async fn serve_once(pieces: Vec<&'static str>) -> String {
426        use tokio::io::{AsyncReadExt, AsyncWriteExt};
427        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
428        let url = format!("http://{}/stream", listener.local_addr().unwrap());
429        tokio::spawn(async move {
430            let (mut socket, _) = listener.accept().await.unwrap();
431            let mut request = vec![0u8; 4096];
432            let _ = socket.read(&mut request).await;
433            for piece in pieces {
434                socket.write_all(piece.as_bytes()).await.unwrap();
435                socket.flush().await.unwrap();
436                tokio::time::sleep(Duration::from_millis(5)).await;
437            }
438        });
439        url
440    }
441
442    fn client() -> HttpClient {
443        HttpClient::new(HttpConfig {
444            max_retries: 0,
445            ..HttpConfig::default()
446        })
447    }
448
449    #[tokio::test]
450    async fn post_sse_yields_each_event_as_it_arrives() {
451        use futures_util::StreamExt;
452        let url = serve_once(vec![
453            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
454            "data: {\"n\":1}\n",
455            "\ndata: {\"n\"",
456            ":2}\n\n",
457        ])
458        .await;
459        let events: Vec<_> = client()
460            .post_sse(&url, vec![], &serde_json::json!({}))
461            .await
462            .unwrap()
463            .collect()
464            .await;
465        let values: Vec<serde_json::Value> = events.into_iter().map(Result::unwrap).collect();
466        assert_eq!(
467            values,
468            [serde_json::json!({"n": 1}), serde_json::json!({"n": 2})]
469        );
470    }
471
472    #[tokio::test]
473    async fn post_sse_reports_an_error_status_before_streaming() {
474        let url = serve_once(vec![
475            "HTTP/1.1 400 Bad Request\r\ncontent-type: application/json\r\nconnection: close\r\n\r\n",
476            "{\"error\":{\"message\":\"bad schema\"}}",
477        ])
478        .await;
479        match client()
480            .post_sse(&url, vec![], &serde_json::json!({}))
481            .await
482        {
483            Err(HttpError::ApiError {
484                status, message, ..
485            }) => {
486                assert_eq!(status, 400);
487                assert_eq!(message, "bad schema");
488            }
489            Err(other) => panic!("expected ApiError, got {other}"),
490            Ok(_) => panic!("expected ApiError, got a stream"),
491        }
492    }
493
494    #[test]
495    fn an_unterminated_last_event_is_kept() {
496        let mut decoder = SseDecoder::default();
497        assert!(decoder.push(b"data: {}").is_empty());
498        assert_eq!(decoder.finish(), ["{}"]);
499    }
500
501    #[test]
502    fn default_config() {
503        let config = HttpConfig::default();
504        assert_eq!(config.timeout, Duration::from_secs(60));
505        assert_eq!(config.max_retries, 3);
506        assert!(config.user_agent.starts_with("gemini-live/"));
507    }
508
509    #[test]
510    fn backoff_delay_calculation() {
511        let client = HttpClient::new(HttpConfig {
512            retry_base_delay: Duration::from_millis(100),
513            retry_max_delay: Duration::from_secs(5),
514            ..HttpConfig::default()
515        });
516        assert_eq!(client.backoff_delay(1), Duration::from_millis(100));
517        assert_eq!(client.backoff_delay(2), Duration::from_millis(200));
518        assert_eq!(client.backoff_delay(3), Duration::from_millis(400));
519    }
520
521    #[test]
522    fn backoff_delay_capped() {
523        let client = HttpClient::new(HttpConfig {
524            retry_base_delay: Duration::from_secs(1),
525            retry_max_delay: Duration::from_secs(5),
526            ..HttpConfig::default()
527        });
528        // 2^9 = 512 seconds, should be capped at 5 seconds
529        assert_eq!(client.backoff_delay(10), Duration::from_secs(5));
530    }
531
532    #[test]
533    fn retryable_status_codes() {
534        assert!(is_retryable_status(429));
535        assert!(is_retryable_status(500));
536        assert!(is_retryable_status(503));
537        assert!(is_retryable_status(599));
538        assert!(!is_retryable_status(400));
539        assert!(!is_retryable_status(404));
540        assert!(!is_retryable_status(200));
541    }
542}