diff --git a/src/client.rs b/src/client.rs index 7d48c7a..216c4ca 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,3 +1,4 @@ +use std::time::Duration; use std::vec; use tracing::error; @@ -59,12 +60,17 @@ impl GeminiClient { async fn error_for_status(response: reqwest::Response) -> Result { if !response.status().is_success() { let status = response.status(); + let retry_after = parse_retry_after(response.headers()); let body = response.text().await?; if let Ok(error_response) = serde_json::from_str::(&body) { return Err(error_response.error.into()); } - return Err(Error::HttpStatus { status, body }); + return Err(Error::HttpStatus { + status, + body, + retry_after, + }); } Ok(response) } @@ -241,6 +247,14 @@ impl GeminiClient { } } +/// Parses a `Retry-After` header in its delay-seconds form (e.g. `Retry-After: 30`). +/// +/// The HTTP-date form is not supported and yields `None`. +fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option { + let value = headers.get(reqwest::header::RETRY_AFTER)?.to_str().ok()?; + value.trim().parse().ok().map(Duration::from_secs) +} + #[cfg(test)] #[path = "client_tests.rs"] mod tests; diff --git a/src/client_tests.rs b/src/client_tests.rs index ab058be..6749b20 100644 --- a/src/client_tests.rs +++ b/src/client_tests.rs @@ -87,7 +87,7 @@ async fn stream_generate_content_returns_http_status_on_non_json_error() -> Resu .await; match result { - Err(Error::HttpStatus { status, body }) => { + Err(Error::HttpStatus { status, body, .. }) => { assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(body, "Internal Server Error"); } @@ -234,7 +234,7 @@ async fn generate_content_returns_http_status_on_non_json_503() -> Result<()> { let result = client.generate_content(&request, "gemini-test").await; match result { - Err(Error::HttpStatus { status, body }) => { + Err(Error::HttpStatus { status, body, .. }) => { assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(body, "Service Unavailable"); } @@ -314,7 +314,7 @@ async fn count_tokens_returns_http_status_on_non_json_error() -> Result<()> { let result = client.count_tokens(&request, "gemini-test").await; match result { - Err(Error::HttpStatus { status, body }) => { + Err(Error::HttpStatus { status, body, .. }) => { assert_eq!(status, reqwest::StatusCode::BAD_GATEWAY); assert_eq!(body, "Bad Gateway"); } @@ -353,7 +353,7 @@ async fn text_embeddings_returns_http_status_on_non_json_error() -> Result<()> { let result = client.text_embeddings(&request, "gemini-test").await; match result { - Err(Error::HttpStatus { status, body }) => { + Err(Error::HttpStatus { status, body, .. }) => { assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(body, "Internal Server Error"); } @@ -395,7 +395,7 @@ async fn predict_image_returns_http_status_on_non_json_error() -> Result<()> { let result = client.predict_image(&request, "imagen-test").await; match result { - Err(Error::HttpStatus { status, body }) => { + Err(Error::HttpStatus { status, body, .. }) => { assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(body, "Service Unavailable"); } @@ -404,3 +404,82 @@ async fn predict_image_returns_http_status_on_non_json_error() -> Result<()> { } Ok(()) } + +#[tokio::test] +async fn generate_content_captures_retry_after_on_non_json_429() -> Result<()> { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let addr = listener.local_addr()?; + + tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 4096]; + let _ = socket.read(&mut buf).await; + let body = "Too Many Requests"; + let response = format!( + "HTTP/1.1 429 Too Many Requests\r\nContent-Type: text/plain\r\nRetry-After: 30\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + socket.write_all(response.as_bytes()).await.unwrap(); + }); + + let client = GeminiClient::new( + MockTokenProvider, + format!("http://{addr}"), + "test-project".to_string(), + "test-location".to_string(), + ); + let request = GenerateContentRequest::default(); + + let err = match client.generate_content(&request, "gemini-test").await { + Err(err) => err, + Ok(_) => panic!("Expected error response, got Ok"), + }; + match &err { + Error::HttpStatus { + status, + retry_after, + .. + } => { + assert_eq!(*status, reqwest::StatusCode::TOO_MANY_REQUESTS); + assert_eq!(*retry_after, Some(Duration::from_secs(30))); + } + other => panic!("Expected Error::HttpStatus, got: {other:?}"), + } + assert_eq!(err.retry_delay(), Some(Duration::from_secs(30))); + Ok(()) +} + +#[test] +fn parse_retry_after_reads_delay_seconds() -> Result<()> { + let mut headers = reqwest::header::HeaderMap::new(); + assert_eq!(parse_retry_after(&headers), None); + + headers.insert(reqwest::header::RETRY_AFTER, "30".parse()?); + assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(30))); + + headers.insert(reqwest::header::RETRY_AFTER, " 0 ".parse()?); + assert_eq!(parse_retry_after(&headers), Some(Duration::ZERO)); + Ok(()) +} + +#[test] +fn parse_retry_after_rejects_invalid_values() -> Result<()> { + let cases = [ + "Wed, 21 Oct 2015 07:28:00 GMT", // HTTP-date form is not supported + "soon", + "-1", + "1.5", + "", + ]; + for case in cases { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert(reqwest::header::RETRY_AFTER, case.parse()?); + assert_eq!( + parse_retry_after(&headers), + None, + "expected None for: {case:?}" + ); + } + Ok(()) +} diff --git a/src/error.rs b/src/error.rs index 52922d1..42a3169 100644 --- a/src/error.rs +++ b/src/error.rs @@ -21,6 +21,9 @@ pub enum Error { HttpStatus { status: reqwest::StatusCode, body: String, + /// The delay from the response's `Retry-After` header, if present and in + /// delay-seconds form. + retry_after: Option, }, } @@ -34,7 +37,7 @@ impl Display for Error { Error::VertexError(e) => write!(f, "Vertex error: {e}"), Error::NoCandidatesError => write!(f, "No candidates returned for the prompt"), Error::EventSourceError(e) => write!(f, "EventSource error: {e}"), - Error::HttpStatus { status, body } => write!(f, "HTTP status {status}: {body}"), + Error::HttpStatus { status, body, .. } => write!(f, "HTTP status {status}: {body}"), } } } @@ -102,11 +105,14 @@ impl Error { } } - /// Returns the server-recommended retry delay if this error is a - /// [`Error::VertexError`] containing a `google.rpc.RetryInfo` detail entry. + /// Returns the server-recommended retry delay, if any. + /// + /// - `VertexError`: the delay from a `google.rpc.RetryInfo` detail entry. + /// - `HttpStatus`: the delay from the response's `Retry-After` header. pub fn retry_delay(&self) -> Option { match self { Error::VertexError(e) => e.retry_delay(), + Error::HttpStatus { retry_after, .. } => *retry_after, _ => None, } } @@ -125,6 +131,14 @@ mod tests { }) } + fn http_status_error(status: reqwest::StatusCode, retry_after: Option) -> Error { + Error::HttpStatus { + status, + body: "error".to_string(), + retry_after, + } + } + #[test] fn vertex_error_retryable_classification() { let make_err = |code: i32, status: &str| vertex_error(code, status, None); @@ -150,10 +164,7 @@ mod tests { #[test] fn http_status_retryable_classification() { - let make_err = |status: reqwest::StatusCode| Error::HttpStatus { - status, - body: "error".to_string(), - }; + let make_err = |status: reqwest::StatusCode| http_status_error(status, None); assert!(make_err(reqwest::StatusCode::TOO_MANY_REQUESTS).is_retryable()); assert!(make_err(reqwest::StatusCode::INTERNAL_SERVER_ERROR).is_retryable()); @@ -180,11 +191,18 @@ mod tests { assert_eq!(err.retry_delay(), Some(Duration::from_secs(15))); assert_eq!(Error::NoCandidatesError.retry_delay(), None); - let http_err = Error::HttpStatus { - status: reqwest::StatusCode::TOO_MANY_REQUESTS, - body: "error".to_string(), - }; - assert_eq!(http_err.retry_delay(), None); + } + + #[test] + fn retry_delay_returns_http_status_retry_after() { + let err = http_status_error( + reqwest::StatusCode::TOO_MANY_REQUESTS, + Some(Duration::from_secs(30)), + ); + assert_eq!(err.retry_delay(), Some(Duration::from_secs(30))); + + let err = http_status_error(reqwest::StatusCode::TOO_MANY_REQUESTS, None); + assert_eq!(err.retry_delay(), None); } #[test]