use std::fmt;
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::large_enum_variant)] pub enum NRouterError {
Request(Box<ErrorBody>),
GuardrailBlocked(Box<ErrorBody>),
Authentication(Box<ErrorBody>),
Credit(Box<ErrorBody>),
BudgetExceeded(Box<ErrorBody>),
NotFound(Box<ErrorBody>),
RateLimit(Box<ErrorBody>),
Service(Box<ErrorBody>),
Other(Box<ErrorBody>),
Transport(String),
Configuration(String),
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ErrorBody {
pub message: String,
pub code: Option<String>,
pub param: Option<String>,
pub error_type: Option<String>,
pub status: Option<u16>,
pub request_id: Option<String>,
pub limit_source: Option<String>,
pub auth_reason: Option<String>,
pub retry_after: Option<u64>,
pub guardrails: Option<String>,
pub meta: Option<crate::meta::ResponseMeta>,
}
impl NRouterError {
pub fn from_code(mut body: ErrorBody) -> Self {
body.message = redact_keys(&body.message);
let boxed = Box::new(body);
let body = boxed;
match body.code.as_deref() {
Some("invalid_request")
| Some("input_too_large")
| Some("max_output_tokens_too_large")
| Some("fallback_not_allowed")
| Some("guardrail_not_found")
| Some("image_input_unsupported")
| Some("pot_route_feature_unsupported")
| Some("cost_band_unsatisfiable") => Self::Request(body),
Some("guardrail_blocked") => Self::GuardrailBlocked(body),
Some("invalid_api_key") => Self::Authentication(body),
Some("insufficient_credits")
| Some("plan_allowance_exhausted")
| Some("plan_required")
| Some("insufficient_promo_credit")
| Some("insufficient_hack_credit") => Self::Credit(body),
Some("model_not_found") => Self::NotFound(body),
Some("rate_limit_exceeded")
| Some("tpm_limit_exceeded")
| Some("pot_spend_limit_exceeded") => Self::RateLimit(body),
Some("credit_check_failed") | Some("service_unavailable") => Self::Service(body),
Some("model_denied_by_org")
| Some("model_denied_by_team")
| Some("model_denied_by_key") => Self::Other(body),
Some(_) => Self::Other(body),
None => match body.status {
Some(400) => {
if body.guardrails.as_deref() == Some("blocked")
|| body.error_type.as_deref() == Some("guardrail_blocked")
|| body.message.to_lowercase().contains("guardrail")
{
Self::GuardrailBlocked(body)
} else {
Self::Request(body)
}
}
Some(401) => Self::Authentication(body),
Some(403) => Self::Other(body),
Some(402) => {
if body
.message
.trim_start()
.to_lowercase()
.starts_with("budget")
{
Self::BudgetExceeded(body)
} else {
Self::Credit(body)
}
}
Some(404) => {
if body.message.to_lowercase().contains("model") {
Self::NotFound(body)
} else {
Self::Other(body)
}
}
Some(429) => Self::RateLimit(body),
Some(502) | Some(504) => {
if body.message.to_lowercase().contains("too large") {
Self::Other(body)
} else {
Self::Service(body)
}
}
Some(503) => Self::Service(body),
_ => Self::Other(body),
},
}
}
pub fn body(&self) -> Option<&ErrorBody> {
match self {
Self::Request(b)
| Self::GuardrailBlocked(b)
| Self::Authentication(b)
| Self::Credit(b)
| Self::BudgetExceeded(b)
| Self::NotFound(b)
| Self::RateLimit(b)
| Self::Service(b)
| Self::Other(b) => Some(b),
Self::Transport(_) | Self::Configuration(_) => None,
}
}
pub fn param(&self) -> Option<&str> {
self.body().and_then(|b| b.param.as_deref())
}
pub fn error_type(&self) -> Option<&str> {
self.body().and_then(|b| b.error_type.as_deref())
}
pub fn request_id(&self) -> Option<&str> {
self.body().and_then(|b| b.request_id.as_deref())
}
pub fn limit_source(&self) -> Option<&str> {
self.body().and_then(|b| b.limit_source.as_deref())
}
pub fn auth_reason(&self) -> Option<&str> {
self.body().and_then(|b| b.auth_reason.as_deref())
}
pub fn guardrails(&self) -> Option<&str> {
self.body().and_then(|b| b.guardrails.as_deref())
}
pub fn meta(&self) -> Option<&crate::meta::ResponseMeta> {
self.body().and_then(|b| b.meta.as_ref())
}
pub fn is_retryable(&self) -> bool {
if let Some(body) = self.body() {
if matches!(body.status, Some(408) | Some(425)) {
return true;
}
}
matches!(
self,
Self::RateLimit(_) | Self::Service(_) | Self::Transport(_)
)
}
}
pub fn redact_keys(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut remaining = s;
while let Some(pos) = remaining.find("sk-") {
out.push_str(&remaining[..pos]);
let slice = &remaining[pos..];
if let Some(stripped) = slice.strip_prefix("sk-nrouter-***") {
out.push_str("sk-nrouter-***");
remaining = stripped;
} else if let Some(rest) = slice.strip_prefix("sk-nrouter-") {
out.push_str("sk-nrouter-***");
let skip = rest
.find(|c: char| !c.is_alphanumeric() && c != '_' && c != '-' && c != '.')
.unwrap_or(rest.len());
remaining = &rest[skip..];
} else if let Some(stripped) = slice.strip_prefix("sk-***") {
out.push_str("sk-***");
remaining = stripped;
} else {
let rest = &slice["sk-".len()..];
let key_len = rest
.find(|c: char| !c.is_alphanumeric() && c != '_' && c != '-' && c != '.')
.unwrap_or(rest.len());
if key_len >= 4 {
out.push_str("sk-***");
remaining = &rest[key_len..];
} else {
out.push_str("sk-");
remaining = rest;
}
}
}
out.push_str(remaining);
out
}
pub fn format_error(err: &NRouterError) -> String {
let mut parts = vec![match err {
NRouterError::Request(_) => "[request]".to_string(),
NRouterError::GuardrailBlocked(_) => "[guardrail_blocked]".to_string(),
NRouterError::Authentication(_) => "[authentication]".to_string(),
NRouterError::Credit(_) => "[credit]".to_string(),
NRouterError::BudgetExceeded(_) => "[budget_exceeded]".to_string(),
NRouterError::NotFound(_) => "[not_found]".to_string(),
NRouterError::RateLimit(_) => "[rate_limit]".to_string(),
NRouterError::Service(_) => "[service]".to_string(),
NRouterError::Other(_) => "[other]".to_string(),
NRouterError::Transport(_) => "[transport]".to_string(),
NRouterError::Configuration(_) => "[configuration]".to_string(),
}];
if let Some(b) = err.body() {
if let Some(status) = b.status {
parts.push(format!("HTTP {status}"));
}
if let Some(code) = &b.code {
parts.push(format!("code={code}"));
}
if let Some(param) = &b.param {
parts.push(format!("param={param}"));
}
if let Some(req_id) = &b.request_id {
parts.push(format!("requestId={req_id}"));
}
if let Some(src) = &b.limit_source {
parts.push(format!("limitSource={src}"));
}
if let Some(ra) = b.retry_after {
parts.push(format!("retryAfter={ra}s"));
}
parts.push(format!(": {}", redact_keys(&b.message)));
} else {
parts.push(format!(": {}", redact_keys(&err.to_string())));
}
parts.join(" ")
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ErrorEnvelope {
pub code: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
pub error_type: Option<String>,
}
pub fn parse_gateway_error_envelope(body: &serde_json::Value) -> ErrorEnvelope {
let node = body.get("error").unwrap_or(body);
ErrorEnvelope {
code: node
.get("code")
.and_then(serde_json::Value::as_str)
.map(str::to_owned),
message: node
.get("message")
.and_then(serde_json::Value::as_str)
.map(redact_keys),
param: node
.get("param")
.and_then(serde_json::Value::as_str)
.map(str::to_owned),
error_type: node
.get("type")
.and_then(serde_json::Value::as_str)
.map(str::to_owned),
}
}
impl fmt::Display for NRouterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Transport(m) => write!(f, "nRouter transport error: {}", redact_keys(m)),
Self::Configuration(m) => write!(f, "nRouter configuration error: {}", redact_keys(m)),
other => {
let b = other.body().expect("non-transport variants carry a body");
let msg = redact_keys(&b.message);
match &b.code {
Some(code) => write!(f, "{} ({code})", msg),
None => write!(f, "{}", msg),
}
}
}
}
}
impl std::error::Error for NRouterError {}
pub const MAX_RETRY_AFTER_SECONDS: u64 = 86400;
pub fn parse_retry_after(raw: Option<&str>) -> Option<u64> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
parse_retry_after_at(raw, now)
}
pub fn parse_retry_after_at(raw: Option<&str>, now_epoch: u64) -> Option<u64> {
let raw = raw?.trim();
if raw.is_empty() {
return None;
}
if let Ok(seconds) = raw.parse::<u64>() {
return Some(seconds.min(MAX_RETRY_AFTER_SECONDS));
}
parse_http_date(raw).map(|epoch| {
if epoch <= now_epoch {
0
} else {
(epoch - now_epoch).min(MAX_RETRY_AFTER_SECONDS)
}
})
}
pub fn compute_jittered_backoff(
attempt: u32,
base_delay: std::time::Duration,
max_delay: std::time::Duration,
retry_after_seconds: Option<u64>,
) -> std::time::Duration {
let attempt = attempt.min(30);
if let Some(ra) = retry_after_seconds {
if ra > 0 {
let retry_dur = std::time::Duration::from_secs(ra).min(max_delay);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let factor = 0.5 + 0.5 * ((nanos % 1000) as f64 / 1000.0);
return std::time::Duration::from_secs_f64(retry_dur.as_secs_f64() * factor);
}
}
let mult = 1u64 << attempt;
let raw = base_delay.saturating_mul(mult as u32);
let capped = raw.min(max_delay);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let factor = 0.5 + 0.5 * ((nanos % 1000) as f64 / 1000.0);
std::time::Duration::from_secs_f64(capped.as_secs_f64() * factor)
}
fn parse_http_date(s: &str) -> Option<u64> {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.len() != 6 {
return None;
}
if !parts[0].ends_with(',') {
return None;
}
let day: u32 = parts[1].parse().ok()?;
let month: u32 = match parts[2].to_ascii_lowercase().as_str() {
"jan" => 1,
"feb" => 2,
"mar" => 3,
"apr" => 4,
"may" => 5,
"jun" => 6,
"jul" => 7,
"aug" => 8,
"sep" => 9,
"oct" => 10,
"nov" => 11,
"dec" => 12,
_ => return None,
};
let year: i64 = parts[3].parse().ok()?;
if year < 1970 {
return None;
}
let time_parts: Vec<&str> = parts[4].split(':').collect();
if time_parts.len() != 3 {
return None;
}
let hour: u32 = time_parts[0].parse().ok()?;
let min: u32 = time_parts[1].parse().ok()?;
let sec: u32 = time_parts[2].parse().ok()?;
if hour > 23 || min > 59 || sec > 60 || day == 0 || day > 31 {
return None;
}
let days = days_from_civil(year, month, day)?;
let total_secs = days as u64 * 86400 + hour as u64 * 3600 + min as u64 * 60 + sec as u64;
Some(total_secs)
}
fn days_from_civil(y: i64, m: u32, d: u32) -> Option<i64> {
let mut y = y;
if m <= 2 {
y -= 1;
}
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = (y - era * 400) as u32;
let m_adj = if m > 2 { m - 3 } else { m + 9 };
let doy = (153 * m_adj + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146097 + doe as i64 - 719468;
if days >= 0 {
Some(days)
} else {
None
}
}