use serde_json::Value;
use crate::store::error::Error;
#[derive(Debug, PartialEq, Eq)]
pub struct Refusal {
pub status: u16,
pub retry_after: Option<u64>,
pub code: Option<String>,
pub message: String,
pub details: Value,
}
#[cfg_attr(not(test), allow(dead_code))]
const CONFLICT: &str = "agent_conversation_conflict";
#[derive(Debug)]
pub enum Failure {
Unsupported,
Refused(Box<Refusal>),
Transport(Error),
Unreadable(String),
Client(Error),
}
impl Failure {
pub(super) fn refused(status: u16, retry_after: Option<&str>, body: &[u8]) -> Self {
let envelope = serde_json::from_slice::<Value>(body)
.ok()
.and_then(|mut data| data.get_mut("error").map(Value::take))
.filter(Value::is_object);
let text = |value: Option<&Value>| value.and_then(Value::as_str).map(str::to_string);
let (code, message, details) = match envelope {
Some(mut error) => (
text(error.get("code")),
text(error.get("message")).unwrap_or_default(),
error
.get_mut("details")
.map(Value::take)
.unwrap_or_default(),
),
None => {
let shown = String::from_utf8_lossy(body);
(None, shown.chars().take(256).collect(), Value::Null)
}
};
Self::Refused(Box::new(Refusal {
status,
retry_after: retry_after.and_then(seconds),
code,
message,
details,
}))
}
#[cfg_attr(not(test), allow(dead_code))]
pub fn reason(&self) -> Option<&str> {
match self {
Self::Refused(refusal) if refusal.code.as_deref() == Some(CONFLICT) => {
refusal.details.get("reason").and_then(Value::as_str)
}
_ => None,
}
}
}
fn seconds(header: &str) -> Option<u64> {
let header = header.trim();
let digits = !header.is_empty() && header.bytes().all(|byte| byte.is_ascii_digit());
digits.then(|| header.parse().ok()).flatten()
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unsupported => f.write_str("the server does not declare turn records version 1"),
Self::Refused(refusal) => {
let code = refusal.code.as_deref().unwrap_or("no envelope");
let (status, message) = (refusal.status, &refusal.message);
write!(f, "refused with {status} ({code}): {message}")
}
Self::Transport(error) => write!(f, "no answer: {error:?}"),
Self::Unreadable(what) => write!(f, "malformed wire response: {what}"),
Self::Client(error) => write!(f, "{error:?}"),
}
}
}