use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Tool(Box<crate::tool_framework::ToolError>),
#[error("Application error: {0}")]
Application(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("Invalid request: {0}")]
InvalidRequest(String),
#[error("Authentication failed: {0}")]
Authentication(String),
#[error("Rate limit exceeded: {0}")]
RateLimit(String),
#[error("HTTP error: {0}")]
Http(#[from] timvw_rust_runtime::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("`OpenAI` API error (status {status}): {message}")]
Api {
status: u16,
message: String,
error_type: Option<String>,
error_code: Option<String>,
},
#[error("Stream connection error: {message}")]
StreamConnection {
message: String,
},
#[error("Stream parsing error: {message}, chunk: {chunk}")]
StreamParsing {
message: String,
chunk: String,
},
#[error("Stream buffer error: {message}")]
StreamBuffer {
message: String,
},
#[error("Stream error: {0}")]
Stream(String),
#[error("File error: {0}")]
File(#[from] std::io::Error),
#[error("Configuration error: {0}")]
Config(String),
#[error("Builder validation error: {0}")]
Builder(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("Fatal error: {0}")]
Fatal(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("Response failed ({}): {message}", code.as_deref().unwrap_or("no code"))]
#[non_exhaustive]
ResponseFailed {
code: Option<String>,
message: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RetryClass {
Never,
ServerDirected {
after: std::time::Duration,
},
Backoff,
}
impl RetryClass {
#[must_use]
pub fn is_retryable(self) -> bool {
!matches!(self, Self::Never)
}
}
impl From<crate::tool_framework::ToolError> for Error {
fn from(error: crate::tool_framework::ToolError) -> Self {
Self::Tool(Box::new(error))
}
}
impl Error {
pub fn application(error: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::Application(Box::new(error))
}
pub fn api(status: u16, message: impl Into<String>) -> Self {
Self::Api {
status,
message: message.into(),
error_type: None,
error_code: None,
}
}
pub fn api_detailed(
status: u16,
message: impl Into<String>,
error_type: Option<String>,
error_code: Option<String>,
) -> Self {
Self::Api {
status,
message: message.into(),
error_type,
error_code,
}
}
pub fn is_rate_limit(&self) -> bool {
matches!(self, Error::RateLimit(_)) || matches!(self, Error::Api { status: 429, .. })
}
pub fn is_auth_error(&self) -> bool {
matches!(self, Error::Authentication(_)) || matches!(self, Error::Api { status: 401, .. })
}
pub fn is_client_error(&self) -> bool {
match self {
Error::Api { status, .. } => (400..500).contains(status),
Error::Authentication(_) | Error::RateLimit(_) | Error::InvalidRequest(_) => true,
_ => false,
}
}
pub fn is_server_error(&self) -> bool {
match self {
Error::Api { status, .. } => (500..600).contains(status),
_ => false,
}
}
pub fn is_retryable(&self) -> bool {
self.is_rate_limit() || self.is_server_error()
}
pub fn fatal(error: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::Fatal(Box::new(error))
}
pub fn is_fatal(&self) -> bool {
matches!(self, Self::Fatal(_))
}
pub fn response_failed(code: Option<String>, message: impl Into<String>) -> Self {
Self::ResponseFailed {
code,
message: message.into(),
}
}
pub fn is_context_length_exceeded(&self) -> bool {
self.code() == Some("context_length_exceeded")
}
fn code(&self) -> Option<&str> {
match self {
Self::Api { error_code, .. } => error_code.as_deref(),
Self::ResponseFailed { code, .. } => code.as_deref(),
_ => None,
}
}
pub fn retry_class(&self) -> RetryClass {
let directed = |message: &str| {
retry_after_in_message(message).map_or(RetryClass::Backoff, |after| {
RetryClass::ServerDirected { after }
})
};
match self {
Self::Api {
status,
message,
error_type,
error_code,
} => {
let quota = [error_type, error_code]
.iter()
.any(|value| value.as_deref() == Some("insufficient_quota"));
match status {
429 if quota => RetryClass::Never,
408 | 429 | 500..=599 => directed(message),
_ => RetryClass::Never,
}
}
Self::RateLimit(message) => directed(message),
Self::ResponseFailed { code, message } => match code.as_deref() {
Some(
"insufficient_quota"
| "context_length_exceeded"
| "invalid_prompt"
| "data_residency_mismatch"
| "bio_policy"
| "misalignment_policy_violation",
) => RetryClass::Never,
Some(code) if code.contains("image") => RetryClass::Never,
_ => directed(message),
},
Self::StreamConnection { .. } => RetryClass::Backoff,
Self::Http(error) if error.is_timeout() || error.is_connect() || error.is_body() => {
RetryClass::Backoff
}
_ => RetryClass::Never,
}
}
pub fn is_io(&self) -> bool {
match self {
Error::File(_) => true,
Error::Http(error) => error.is_io(),
_ => false,
}
}
pub fn io_error(&self) -> Option<&std::io::Error> {
match self {
Error::File(error) => Some(error),
Error::Http(error) if error.is_io() => {
let mut source = std::error::Error::source(error);
while let Some(current) = source {
if let Some(io) = current.downcast_ref::<std::io::Error>() {
return Some(io);
}
source = current.source();
}
None
}
_ => None,
}
}
}
fn retry_after_in_message(message: &str) -> Option<std::time::Duration> {
let lower = message.to_ascii_lowercase();
let start = lower.find("try again in ")? + "try again in ".len();
let rest = &message[start..];
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '.'))
.unwrap_or(rest.len());
parse_duration(rest[..end].trim_end_matches('.'))
}
pub(crate) fn parse_duration(text: &str) -> Option<std::time::Duration> {
let text = text.trim();
if text.is_empty() {
return None;
}
if let Ok(seconds) = text.parse::<f64>() {
return std::time::Duration::try_from_secs_f64(seconds).ok();
}
let mut total = 0.0_f64;
let mut rest = text;
while !rest.is_empty() {
let number_end = rest
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
.filter(|end| *end > 0)?;
let value: f64 = rest[..number_end].parse().ok()?;
rest = &rest[number_end..];
let unit_end = rest
.find(|c: char| c.is_ascii_digit() || c == '.')
.unwrap_or(rest.len());
let scale = match &rest[..unit_end] {
"h" => 3600.0,
"m" => 60.0,
"s" => 1.0,
"ms" => 1e-3,
"us" | "µs" => 1e-6,
"ns" => 1e-9,
_ => return None,
};
total = value.mul_add(scale, total);
rest = &rest[unit_end..];
}
std::time::Duration::try_from_secs_f64(total).ok()
}
pub mod chat {
use super::Error;
pub fn invalid_messages(msg: impl Into<String>) -> Error {
Error::InvalidRequest(format!("Invalid chat messages: {}", msg.into()))
}
pub fn unsupported_model(model: impl Into<String>) -> Error {
Error::InvalidRequest(format!("Unsupported model: {}", model.into()))
}
}
pub mod responses {
use super::Error;
pub fn invalid_tool(msg: impl Into<String>) -> Error {
Error::InvalidRequest(format!("Invalid tool definition: {}", msg.into()))
}
pub fn missing_response_format() -> Error {
Error::InvalidRequest("Response format is required for structured outputs".to_string())
}
}
pub mod files {
use super::Error;
pub fn upload_failed(msg: impl Into<String>) -> Error {
Error::File(std::io::Error::new(
std::io::ErrorKind::Other,
format!("File upload failed: {}", msg.into()),
))
}
pub fn unsupported_type(file_type: impl Into<String>) -> Error {
Error::InvalidRequest(format!("Unsupported file type: {}", file_type.into()))
}
}
pub mod streaming {
use super::Error;
pub fn connection_failed(msg: impl Into<String>) -> Error {
Error::Stream(format!("Stream connection failed: {}", msg.into()))
}
pub fn parse_failed(msg: impl Into<String>) -> Error {
Error::Stream(format!("Stream parsing failed: {}", msg.into()))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::io;
#[tokio::test]
async fn test_io_errors() {
let missing = timvw_rust_runtime::Upload::path("/no/such/dir/data.jsonl")
.resolve()
.await
.unwrap_err();
let error = Error::Http(missing);
assert!(error.is_io());
assert_eq!(error.io_error().unwrap().kind(), io::ErrorKind::NotFound);
assert!(error.to_string().contains("data.jsonl"));
let error = Error::File(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
assert!(error.is_io());
assert_eq!(
error.io_error().unwrap().kind(),
io::ErrorKind::PermissionDenied
);
let error = Error::InvalidRequest("x".to_string());
assert!(!error.is_io());
assert!(error.io_error().is_none());
}
#[test]
fn test_retry_class() {
use std::time::Duration;
let quota = Error::api_detailed(429, "quota", None, Some("insufficient_quota".into()));
assert_eq!(quota.retry_class(), RetryClass::Never);
assert_eq!(
Error::api(429, "Rate limit reached. Please try again in 1.5s.").retry_class(),
RetryClass::ServerDirected {
after: Duration::from_millis(1500)
}
);
assert_eq!(
Error::api(429, "slow down").retry_class(),
RetryClass::Backoff
);
assert_eq!(
Error::api(503, "overloaded").retry_class(),
RetryClass::Backoff
);
assert_eq!(Error::api(400, "bad").retry_class(), RetryClass::Never);
assert_eq!(
Error::response_failed(Some("context_length_exceeded".into()), "too long")
.retry_class(),
RetryClass::Never
);
assert!(
Error::response_failed(Some("context_length_exceeded".into()), "too long")
.is_context_length_exceeded()
);
assert_eq!(
Error::response_failed(Some("rate_limit_exceeded".into()), "try again in 20ms")
.retry_class(),
RetryClass::ServerDirected {
after: Duration::from_millis(20)
}
);
assert_eq!(
Error::response_failed(Some("server_error".into()), "boom").retry_class(),
RetryClass::Backoff
);
assert_eq!(
Error::response_failed(Some("invalid_image_url".into()), "bad").retry_class(),
RetryClass::Never
);
let cut = Error::StreamConnection {
message: "cut".into(),
};
assert_eq!(cut.retry_class(), RetryClass::Backoff);
assert!(cut.retry_class().is_retryable());
assert_eq!(
Error::fatal(io::Error::other("x")).retry_class(),
RetryClass::Never
);
assert!(Error::fatal(io::Error::other("x")).is_fatal());
}
#[test]
fn test_parse_duration() {
use std::time::Duration;
assert_eq!(parse_duration("1s"), Some(Duration::from_secs(1)));
assert_eq!(parse_duration("6m0s"), Some(Duration::from_secs(360)));
assert_eq!(parse_duration("20ms"), Some(Duration::from_millis(20)));
assert_eq!(
parse_duration("1h2m3.5s"),
Some(Duration::from_millis(3_723_500))
);
assert_eq!(parse_duration("2"), Some(Duration::from_secs(2)));
assert_eq!(parse_duration("soon"), None);
assert_eq!(parse_duration(""), None);
}
#[test]
fn test_error_display() {
let error = Error::InvalidRequest("test message".to_string());
assert_eq!(error.to_string(), "Invalid request: test message");
let error = Error::Authentication("invalid API key".to_string());
assert_eq!(error.to_string(), "Authentication failed: invalid API key");
let error = Error::RateLimit("rate limit exceeded".to_string());
assert_eq!(
error.to_string(),
"Rate limit exceeded: rate limit exceeded"
);
}
#[test]
fn test_api_error_constructors() {
let error = Error::api(400, "Bad request");
match error {
Error::Api {
status,
message,
error_type,
error_code,
} => {
assert_eq!(status, 400);
assert_eq!(message, "Bad request");
assert!(error_type.is_none());
assert!(error_code.is_none());
}
_ => panic!("Expected API error"),
}
let error = Error::api_detailed(
429,
"Rate limit exceeded",
Some("rate_limit_exceeded".to_string()),
Some("RL001".to_string()),
);
match error {
Error::Api {
status,
message,
error_type,
error_code,
} => {
assert_eq!(status, 429);
assert_eq!(message, "Rate limit exceeded");
assert_eq!(error_type, Some("rate_limit_exceeded".to_string()));
assert_eq!(error_code, Some("RL001".to_string()));
}
_ => panic!("Expected API error"),
}
}
#[test]
fn test_is_rate_limit() {
let error = Error::RateLimit("exceeded".to_string());
assert!(error.is_rate_limit());
let error = Error::api(429, "Too Many Requests");
assert!(error.is_rate_limit());
let error = Error::api(400, "Bad Request");
assert!(!error.is_rate_limit());
let error = Error::InvalidRequest("invalid".to_string());
assert!(!error.is_rate_limit());
}
#[test]
fn test_is_auth_error() {
let error = Error::Authentication("invalid key".to_string());
assert!(error.is_auth_error());
let error = Error::api(401, "Unauthorized");
assert!(error.is_auth_error());
let error = Error::api(403, "Forbidden");
assert!(!error.is_auth_error());
let error = Error::InvalidRequest("invalid".to_string());
assert!(!error.is_auth_error());
}
#[test]
fn test_is_client_error() {
let error = Error::api(400, "Bad Request");
assert!(error.is_client_error());
let error = Error::api(404, "Not Found");
assert!(error.is_client_error());
let error = Error::api(499, "Client Error");
assert!(error.is_client_error());
let error = Error::Authentication("invalid".to_string());
assert!(error.is_client_error());
let error = Error::RateLimit("exceeded".to_string());
assert!(error.is_client_error());
let error = Error::InvalidRequest("invalid".to_string());
assert!(error.is_client_error());
let error = Error::api(500, "Server Error");
assert!(!error.is_client_error());
let error = Error::Internal("internal".to_string());
assert!(!error.is_client_error());
}
#[test]
fn test_is_server_error() {
let error = Error::api(500, "Internal Server Error");
assert!(error.is_server_error());
let error = Error::api(502, "Bad Gateway");
assert!(error.is_server_error());
let error = Error::api(599, "Server Error");
assert!(error.is_server_error());
let error = Error::api(400, "Client Error");
assert!(!error.is_server_error());
let error = Error::Internal("internal".to_string());
assert!(!error.is_server_error());
}
#[test]
fn test_is_retryable() {
let error = Error::RateLimit("exceeded".to_string());
assert!(error.is_retryable());
let error = Error::api(429, "Too Many Requests");
assert!(error.is_retryable());
let error = Error::api(500, "Internal Server Error");
assert!(error.is_retryable());
let error = Error::api(502, "Bad Gateway");
assert!(error.is_retryable());
let error = Error::api(400, "Bad Request");
assert!(!error.is_retryable());
let error = Error::Authentication("invalid".to_string());
assert!(!error.is_retryable());
let error = Error::InvalidRequest("invalid".to_string());
assert!(!error.is_retryable());
}
#[test]
fn test_from_http_error() {
#[allow(clippy::items_after_statements)]
fn _test_http_error_conversion(http_error: timvw_rust_runtime::Error) -> Error {
http_error.into()
}
}
#[test]
fn test_from_serde_json_error() {
let json_error = serde_json::from_str::<serde_json::Value>("invalid json").unwrap_err();
let error: Error = json_error.into();
assert!(matches!(error, Error::Json(_)));
}
#[test]
fn test_from_io_error() {
let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
let error: Error = io_error.into();
assert!(matches!(error, Error::File(_)));
}
#[test]
fn test_stream_errors() {
let error = Error::StreamConnection {
message: "connection lost".to_string(),
};
assert_eq!(
error.to_string(),
"Stream connection error: connection lost"
);
let error = Error::StreamParsing {
message: "invalid data".to_string(),
chunk: "bad chunk".to_string(),
};
assert_eq!(
error.to_string(),
"Stream parsing error: invalid data, chunk: bad chunk"
);
let error = Error::StreamBuffer {
message: "buffer overflow".to_string(),
};
assert_eq!(error.to_string(), "Stream buffer error: buffer overflow");
let error = Error::Stream("generic stream error".to_string());
assert_eq!(error.to_string(), "Stream error: generic stream error");
}
#[test]
fn test_specialized_error_modules() {
let error = chat::invalid_messages("empty messages");
assert!(matches!(error, Error::InvalidRequest(_)));
assert!(error.to_string().contains("Invalid chat messages"));
let error = chat::unsupported_model("gpt-5");
assert!(matches!(error, Error::InvalidRequest(_)));
assert!(error.to_string().contains("Unsupported model"));
let error = responses::invalid_tool("missing name");
assert!(matches!(error, Error::InvalidRequest(_)));
assert!(error.to_string().contains("Invalid tool definition"));
let error = responses::missing_response_format();
assert!(matches!(error, Error::InvalidRequest(_)));
assert!(error.to_string().contains("Response format is required"));
let error = files::upload_failed("network error");
assert!(matches!(error, Error::File(_)));
let error = files::unsupported_type("txt");
assert!(matches!(error, Error::InvalidRequest(_)));
assert!(error.to_string().contains("Unsupported file type"));
let error = streaming::connection_failed("timeout");
assert!(matches!(error, Error::Stream(_)));
assert!(error.to_string().contains("Stream connection failed"));
let error = streaming::parse_failed("invalid JSON");
assert!(matches!(error, Error::Stream(_)));
assert!(error.to_string().contains("Stream parsing failed"));
}
#[test]
fn test_error_debug_format() {
let error = Error::InvalidRequest("test".to_string());
let debug_str = format!("{error:?}");
assert!(debug_str.contains("InvalidRequest"));
assert!(debug_str.contains("test"));
}
#[test]
fn test_error_chains() {
let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");
let wrapped_error: Error = io_error.into();
match wrapped_error {
Error::File(ref err) => {
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
}
_ => panic!("Expected File error"),
}
}
#[test]
fn test_config_error() {
let error = Error::Config("missing API key".to_string());
assert_eq!(error.to_string(), "Configuration error: missing API key");
}
#[test]
fn test_builder_error() {
let error = Error::Builder("validation failed".to_string());
assert_eq!(
error.to_string(),
"Builder validation error: validation failed"
);
}
#[test]
fn test_internal_error() {
let error = Error::Internal("unexpected state".to_string());
assert_eq!(error.to_string(), "Internal error: unexpected state");
}
#[test]
fn test_error_status_boundaries() {
let error = Error::api(399, "Client Error");
assert!(!error.is_client_error());
let error = Error::api(400, "Client Error");
assert!(error.is_client_error());
let error = Error::api(499, "Client Error");
assert!(error.is_client_error());
let error = Error::api(500, "Server Error");
assert!(!error.is_client_error());
assert!(error.is_server_error());
let error = Error::api(599, "Server Error");
assert!(error.is_server_error());
let error = Error::api(600, "Unknown");
assert!(!error.is_server_error());
}
}