use std::fmt;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NganoError {
#[error("http transport error: {0}")]
Http(#[from] reqwest::Error),
#[error("could not decode json: {0}")]
Json(#[from] serde_json::Error),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("dataset {repo} is gated: accept its terms at {url}, then pass an HF token")]
Gated {
repo: String,
url: String,
},
#[error("{source_name} returned {status}: {message}")]
Api {
source_name: String,
status: u16,
message: String,
},
#[error("not found: {0}")]
NotFound(String),
#[error("gave up after {attempts} attempts against {url}{}", .status.map(|s| format!(" (last status {s})")).unwrap_or_default())]
RetryLimit {
url: String,
attempts: u32,
status: Option<u16>,
},
#[error("unexpected response from {url}: {detail}")]
InvalidResponse {
url: String,
detail: String,
},
#[error("no streamable datasets matched the filter: {0}")]
NoDatasets(String),
#[error("audio reference for {0} has neither bytes nor a url")]
AudioUnavailable(String),
#[error("could not start a tokio runtime: {0}")]
Runtime(String),
}
impl NganoError {
pub fn is_retryable(&self) -> bool {
match self {
NganoError::Http(e) => !e.is_builder() && !e.is_decode(),
NganoError::Api { status, .. } => is_retryable_status(*status),
NganoError::RetryLimit { .. } => false,
_ => false,
}
}
pub fn status(&self) -> Option<u16> {
match self {
NganoError::Api { status, .. } => Some(*status),
NganoError::RetryLimit { status, .. } => *status,
NganoError::Gated { .. } => Some(401),
NganoError::NotFound(_) => Some(404),
NganoError::Http(e) => e.status().map(|s| s.as_u16()),
_ => None,
}
}
}
pub(crate) fn is_retryable_status(status: u16) -> bool {
status == 429 || (500..600).contains(&status)
}
pub type Result<T, E = NganoError> = std::result::Result<T, E>;
#[derive(Debug, serde::Deserialize)]
pub(crate) struct ApiErrorBody {
pub error: ApiErrorDetail,
}
#[derive(Debug, serde::Deserialize)]
pub(crate) struct ApiErrorDetail {
#[serde(default)]
pub code: String,
#[serde(default)]
pub message: String,
}
impl fmt::Display for ApiErrorDetail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.code.is_empty() {
write!(f, "{}", self.message)
} else {
write!(f, "{} ({})", self.message, self.code)
}
}
}