Compare commits
4 Commits
feat/conte
...
f7cc9977aa
| Author | SHA1 | Date | |
|---|---|---|---|
| f7cc9977aa | |||
| a8961b12e3 | |||
| 2f15b5298d | |||
| 01a4300bb3 |
31
src/error.rs
31
src/error.rs
@@ -1,4 +1,5 @@
|
||||
use std::fmt::Display;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio_util::codec::LinesCodecError;
|
||||
|
||||
@@ -100,6 +101,15 @@ impl Error {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the server-recommended retry delay if this error is a
|
||||
/// [`Error::VertexError`] containing a `google.rpc.RetryInfo` detail entry.
|
||||
pub fn retry_delay(&self) -> Option<Duration> {
|
||||
match self {
|
||||
Error::VertexError(e) => e.retry_delay(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -155,6 +165,27 @@ mod tests {
|
||||
assert!(!make_err(reqwest::StatusCode::GATEWAY_TIMEOUT).is_retryable());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_delegates_to_vertex_error() {
|
||||
let err = Error::VertexError(types::VertexApiError {
|
||||
code: 429,
|
||||
message: "Quota exceeded".to_string(),
|
||||
status: "RESOURCE_EXHAUSTED".to_string(),
|
||||
details: Some(vec![serde_json::json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "15s"
|
||||
})]),
|
||||
});
|
||||
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 other_errors_not_retryable() {
|
||||
assert!(!Error::NoCandidatesError.is_retryable());
|
||||
|
||||
@@ -151,6 +151,8 @@ impl Part {
|
||||
id: None,
|
||||
name: name.into(),
|
||||
args,
|
||||
partial_args: None,
|
||||
will_continue: None,
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -166,6 +168,8 @@ impl Part {
|
||||
id: Some(id.into()),
|
||||
name: name.into(),
|
||||
args,
|
||||
partial_args: None,
|
||||
will_continue: None,
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -229,14 +233,35 @@ impl Part {
|
||||
) -> Self {
|
||||
self.add_function_response_part(FunctionResponsePart::inline_data(mime_type, data))
|
||||
}
|
||||
|
||||
pub fn with_will_continue(mut self, will_continue: bool) -> Self {
|
||||
if let Some(ref mut call) = self.function_call {
|
||||
call.will_continue = Some(will_continue);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub fn with_partial_args(mut self, partial_args: Vec<Value>) -> Self {
|
||||
if let Some(ref mut call) = self.function_call {
|
||||
call.partial_args = Some(partial_args);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FunctionCallData {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Value::is_null")]
|
||||
pub args: Value,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub partial_args: Option<Vec<Value>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub will_continue: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -345,6 +370,57 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_call_omits_unset_name_and_args_and_parses_missing_fields() {
|
||||
// Deserializing without args (e.g. zero-argument function call)
|
||||
let without_args: Part =
|
||||
serde_json::from_value(json!({"functionCall": {"name": "f"}})).unwrap();
|
||||
let fc = without_args.function_call.unwrap();
|
||||
assert_eq!(fc.name, "f");
|
||||
assert!(fc.args.is_null());
|
||||
assert!(fc.partial_args.is_none());
|
||||
assert!(fc.will_continue.is_none());
|
||||
|
||||
// Serializing when args is null omits args
|
||||
assert_eq!(
|
||||
serde_json::to_value(&Part {
|
||||
function_call: Some(fc),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
json!({"functionCall": {"name": "f"}})
|
||||
);
|
||||
|
||||
// Deserializing partial chunk without name and args
|
||||
let partial_chunk: Part = serde_json::from_value(json!({
|
||||
"functionCall": {
|
||||
"partialArgs": [{"key": "val"}],
|
||||
"willContinue": true
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let fc_partial = partial_chunk.function_call.unwrap();
|
||||
assert_eq!(fc_partial.name, "");
|
||||
assert!(fc_partial.args.is_null());
|
||||
assert_eq!(fc_partial.partial_args, Some(vec![json!({"key": "val"})]));
|
||||
assert_eq!(fc_partial.will_continue, Some(true));
|
||||
|
||||
// Serializing partial chunk omits empty name and null args
|
||||
assert_eq!(
|
||||
serde_json::to_value(&Part {
|
||||
function_call: Some(fc_partial),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
json!({
|
||||
"functionCall": {
|
||||
"partialArgs": [{"key": "val"}],
|
||||
"willContinue": true
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_response_id_handling() {
|
||||
let without_id = Part::function_response("lookup", json!({"output": "ok"}));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::fmt::Formatter;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -7,7 +8,9 @@ pub struct VertexApiError {
|
||||
pub code: i32,
|
||||
pub message: String,
|
||||
pub status: String,
|
||||
pub details: Option<Vec<ErrorType>>,
|
||||
/// Raw `google.rpc.*` detail entries, each tagged with an `@type` field. Kept as
|
||||
/// untyped JSON so that unknown detail types never break deserialization.
|
||||
pub details: Option<Vec<serde_json::Value>>,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for VertexApiError {
|
||||
@@ -19,36 +22,240 @@ impl core::fmt::Display for VertexApiError {
|
||||
|
||||
impl std::error::Error for VertexApiError {}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Link {
|
||||
pub description: String,
|
||||
pub url: String,
|
||||
impl VertexApiError {
|
||||
/// Returns the recommended retry delay if provided in the error details.
|
||||
///
|
||||
/// When Gemini rejects a request due to quota limits (`429 RESOURCE_EXHAUSTED`),
|
||||
/// its error details usually include a `google.rpc.RetryInfo` entry specifying
|
||||
/// how long the client should wait before retrying (e.g. `"37s"` or `"1.5s"`).
|
||||
///
|
||||
/// Returns `None` if there are no error details, no `RetryInfo` entry is found,
|
||||
/// or the `retryDelay` value is missing or cannot be parsed.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use std::time::Duration;
|
||||
/// use gemini_rs::prelude::VertexApiError;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let err = VertexApiError {
|
||||
/// code: 429,
|
||||
/// message: "Resource exhausted".into(),
|
||||
/// status: "RESOURCE_EXHAUSTED".into(),
|
||||
/// details: Some(vec![json!({
|
||||
/// "@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
/// "retryDelay": "37s"
|
||||
/// })]),
|
||||
/// };
|
||||
///
|
||||
/// assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
/// ```
|
||||
pub fn retry_delay(&self) -> Option<Duration> {
|
||||
self.details.as_deref()?.iter().find_map(|detail| {
|
||||
let is_retry_info = detail
|
||||
.get("@type")
|
||||
.and_then(|t| t.as_str())
|
||||
.is_some_and(is_retry_info_type);
|
||||
if !is_retry_info {
|
||||
return None;
|
||||
}
|
||||
detail
|
||||
.get("retryDelay")
|
||||
.or_else(|| detail.get("retry_delay"))
|
||||
.and_then(|d| d.as_str())
|
||||
.and_then(parse_duration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "@type")]
|
||||
pub enum ErrorType {
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.ErrorInfo")]
|
||||
ErrorInfo { metadata: ErrorInfoMetadata },
|
||||
fn is_retry_info_type(type_url: &str) -> bool {
|
||||
type_url == "google.rpc.RetryInfo" || type_url.ends_with("/google.rpc.RetryInfo")
|
||||
}
|
||||
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.Help")]
|
||||
Help { links: Vec<Link> },
|
||||
/// Parses a protobuf JSON `Duration` string (`"<secs>s"` or `"<secs>.<frac>s"`).
|
||||
fn parse_duration(s: &str) -> Option<Duration> {
|
||||
let s = s.strip_suffix('s')?;
|
||||
let (secs_str, frac_str) = match s.split_once('.') {
|
||||
Some((secs, frac)) => (secs, Some(frac)),
|
||||
None => (s, None),
|
||||
};
|
||||
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.BadRequest")]
|
||||
BadRequest {
|
||||
#[serde(rename = "fieldViolations")]
|
||||
field_violations: Vec<FieldViolation>,
|
||||
if secs_str.is_empty() || !secs_str.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let secs: u64 = secs_str.parse().ok()?;
|
||||
|
||||
let nanos = match frac_str {
|
||||
Some(frac) => {
|
||||
if frac.is_empty() || frac.len() > 9 || !frac.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let parsed: u32 = frac.parse().ok()?;
|
||||
parsed.checked_mul(10u32.pow(9 - frac.len() as u32))?
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
|
||||
Some(Duration::new(secs, nanos))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn retry_info_error(details: Vec<serde_json::Value>) -> VertexApiError {
|
||||
VertexApiError {
|
||||
code: 429,
|
||||
message: "Quota exceeded".into(),
|
||||
status: "RESOURCE_EXHAUSTED".into(),
|
||||
details: Some(details),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_unknown_detail_types() -> Result<(), serde_json::Error> {
|
||||
let body = r#"{
|
||||
"code": 429,
|
||||
"message": "Resource exhausted",
|
||||
"status": "RESOURCE_EXHAUSTED",
|
||||
"details": [
|
||||
{
|
||||
"@type": "type.googleapis.com/google.rpc.QuotaFailure",
|
||||
"violations": [{ "quotaMetric": "generate_content_requests" }]
|
||||
},
|
||||
{
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "37s"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let err: VertexApiError = serde_json::from_str(body)?;
|
||||
assert_eq!(err.details.as_ref().map(Vec::len), Some(2));
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ErrorInfoMetadata {
|
||||
pub service: String,
|
||||
pub consumer: String,
|
||||
#[test]
|
||||
fn retry_delay_whole_seconds() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "37s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FieldViolation {
|
||||
pub field: String,
|
||||
pub description: String,
|
||||
#[test]
|
||||
fn retry_delay_fractional_seconds() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "1.5s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_millis(1500)));
|
||||
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "0.005s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_millis(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_without_details() {
|
||||
let err = VertexApiError {
|
||||
details: None,
|
||||
..retry_info_error(vec![])
|
||||
};
|
||||
assert_eq!(err.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_without_retry_info() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.BadRequest"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), None);
|
||||
|
||||
assert_eq!(retry_info_error(vec![]).retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_unparsable_or_missing_retry_delay() {
|
||||
let cases = [
|
||||
"invalid",
|
||||
"37", // missing 's' suffix
|
||||
"-1s", // negative
|
||||
"-1.5s", // negative fractional
|
||||
"1.5.0s", // multiple decimals
|
||||
".5s", // missing leading digits
|
||||
"1.s", // missing fractional digits
|
||||
"", // empty
|
||||
"s", // only suffix
|
||||
" 37s", // leading space
|
||||
"37s ", // trailing space
|
||||
"NaNs", // non-digit
|
||||
"1e3s", // scientific notation
|
||||
"1.1234567890s", // more than 9 fractional digits
|
||||
];
|
||||
|
||||
for case in cases {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": case
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), None, "expected None for: {case:?}");
|
||||
}
|
||||
|
||||
let missing = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo"
|
||||
})]);
|
||||
assert_eq!(missing.retry_delay(), None);
|
||||
|
||||
let non_string = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": 37
|
||||
})]);
|
||||
assert_eq!(non_string.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_multiple_details_entries() {
|
||||
let err = retry_info_error(vec![
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": "RATE_LIMIT_EXCEEDED"
|
||||
}),
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "42s"
|
||||
}),
|
||||
]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(42)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_multiple_retry_info_entries_skips_malformed() {
|
||||
let err = retry_info_error(vec![
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "malformed"
|
||||
}),
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "20s"
|
||||
}),
|
||||
]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(20)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_snake_case_and_short_type() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "google.rpc.RetryInfo",
|
||||
"retry_delay": "10s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(10)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user