use std::io::{self, BufRead, BufReader, Read};
use std::time::Duration;
use crate::jobs::CancelToken;
#[derive(Clone, Debug, PartialEq)]
pub enum AiError {
Cancelled,
Network(String),
Status {
code: u16,
message: String,
retry_after: Option<u64>,
},
Protocol(String),
Setup(String),
}
impl AiError {
pub fn retryable(&self) -> bool {
match self {
AiError::Status { code, .. } => matches!(code, 408 | 429 | 500 | 502 | 503 | 504 | 529),
AiError::Network(_) => true,
_ => false,
}
}
pub fn user_text(&self) -> String {
match self {
AiError::Cancelled => "Stopped.".into(),
AiError::Network(e) => format!("Could not reach the provider: {e}"),
AiError::Status { code, message, .. } => {
let what = match code {
400 => "The provider did not accept the request",
401 => "The provider did not accept the key",
403 => "The provider refused access",
404 => "The provider does not know this address or model",
408 | 504 => "The provider took too long to answer",
413 => "The request is too large for the provider",
429 => "Too many requests or no credit left",
500 | 502 | 503 => "The provider has a problem",
529 => "The provider is overloaded",
_ => "The provider answered with an error",
};
if message.is_empty() {
format!("{what} (HTTP {code}).")
} else {
format!("{what} (HTTP {code}): {message}")
}
}
AiError::Protocol(e) => format!("Unexpected answer from the provider: {e}"),
AiError::Setup(e) => e.clone(),
}
}
}
impl std::fmt::Display for AiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.user_text())
}
}
pub fn is_local(url: &str) -> bool {
let rest = url
.split_once("://")
.map(|(_, r)| r)
.unwrap_or(url)
.trim_start_matches(|c: char| c.is_whitespace());
let host_port = rest.split(['/', '?', '#']).next().unwrap_or("");
let host_port = host_port.rsplit_once('@').map(|x| x.1).unwrap_or(host_port);
let host = if let Some(v6) = host_port.strip_prefix('[') {
v6.split(']').next().unwrap_or("")
} else {
host_port.split(':').next().unwrap_or("")
};
let host = host.to_ascii_lowercase();
host == "localhost"
|| host.ends_with(".localhost")
|| host == "::1"
|| host.strip_prefix("127.").is_some_and(|r| {
r.split('.').count() == 3 && r.split('.').all(|p| p.parse::<u8>().is_ok())
})
}
pub(crate) fn agent(local: bool) -> ureq::Agent {
ureq::Agent::config_builder()
.user_agent(format!("BigText/{}", env!("CARGO_PKG_VERSION")))
.timeout_connect(Some(Duration::from_secs(15)))
.timeout_per_read(Some(Duration::from_secs(if local { 600 } else { 180 })))
.http_status_as_error(false)
.proxy(if local {
None
} else {
crate::net_proxy::proxy()
})
.build()
.new_agent()
}
pub(crate) fn scrub(text: &str, secret: Option<&str>) -> String {
match secret.filter(|s| s.len() >= 6) {
Some(s) => text.replace(s, "…"),
None => text.to_string(),
}
}
pub(crate) fn error_message(body: &str) -> String {
let msg = serde_json::from_str::<serde_json::Value>(body)
.ok()
.and_then(|v| {
let e = v.get("error")?;
e.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
.map(str::to_string)
})
.or_else(|| {
serde_json::from_str::<serde_json::Value>(body)
.ok()?
.get("message")?
.as_str()
.map(str::to_string)
});
let msg = msg.unwrap_or_else(|| body.trim().to_string());
let mut m: String = msg.chars().take(400).collect();
if m.len() < msg.len() {
m.push('…');
}
m
}
fn network(e: ureq::Error) -> AiError {
match e {
ureq::Error::StatusCode(code) => AiError::Status {
code,
message: String::new(),
retry_after: None,
},
ureq::Error::Timeout(_) => AiError::Network("the connection timed out".into()),
ureq::Error::Io(e) => AiError::Network(e.to_string()),
e => AiError::Network(e.to_string()),
}
}
pub(crate) enum Body {
Stream(Sse<BufReader<ureq::BodyReader<'static>>>),
Whole(String),
}
pub(crate) fn post(
url: &str,
headers: &[(&str, String)],
body: &[u8],
secret: Option<&str>,
cancel: &CancelToken,
) -> Result<Body, AiError> {
if cancel.is_cancelled() {
return Err(AiError::Cancelled);
}
let local = is_local(url);
let mut req = agent(local)
.post(url)
.header("content-type", "application/json")
.header("accept", "text/event-stream, application/json");
for (k, v) in headers {
req = req.header(*k, v.as_str());
}
let resp = req.send(body).map_err(network)?;
let status = resp.status().as_u16();
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok());
let stream = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|t| t.contains("event-stream"));
let (_, b) = resp.into_parts();
if !(200..300).contains(&status) {
let text = read_limited(b.into_reader(), 64 * 1024);
return Err(AiError::Status {
code: status,
message: scrub(&error_message(&text), secret),
retry_after,
});
}
if stream {
Ok(Body::Stream(Sse::new(BufReader::new(b.into_reader()))))
} else {
Ok(Body::Whole(read_limited(b.into_reader(), 16 << 20)))
}
}
pub(crate) fn get(
url: &str,
headers: &[(&str, String)],
secret: Option<&str>,
) -> Result<String, AiError> {
let mut req = agent(is_local(url)).get(url);
for (k, v) in headers {
req = req.header(*k, v.as_str());
}
let resp = req.call().map_err(network)?;
let status = resp.status().as_u16();
let (_, b) = resp.into_parts();
let text = read_limited(b.into_reader(), 16 << 20);
if !(200..300).contains(&status) {
return Err(AiError::Status {
code: status,
message: scrub(&error_message(&text), secret),
retry_after: None,
});
}
Ok(text)
}
fn read_limited(r: impl Read, max: u64) -> String {
let mut out = Vec::new();
let _ = r.take(max).read_to_end(&mut out);
String::from_utf8_lossy(&out).into_owned()
}
pub(crate) fn with_retries<T>(
cancel: &CancelToken,
mut f: impl FnMut() -> Result<T, AiError>,
) -> Result<T, AiError> {
let mut tries = 0;
loop {
match f() {
Err(e) if e.retryable() && tries < 2 && !cancel.is_cancelled() => {
let wait = match &e {
AiError::Status {
retry_after: Some(s),
..
} if *s <= 30 => *s,
AiError::Status {
retry_after: Some(_),
..
} => return Err(e),
_ => [2, 6][tries],
};
tries += 1;
let until = std::time::Instant::now() + Duration::from_secs(wait);
while std::time::Instant::now() < until {
if cancel.is_cancelled() {
return Err(AiError::Cancelled);
}
std::thread::sleep(Duration::from_millis(100));
}
}
r => return r,
}
}
}
const SSE_LINE_MAX: usize = 8 << 20;
pub struct Sse<R> {
r: R,
line: Vec<u8>,
}
impl<R: BufRead> Sse<R> {
pub fn new(r: R) -> Sse<R> {
Sse {
r,
line: Vec::new(),
}
}
pub fn next_event(&mut self) -> io::Result<Option<(String, String)>> {
let mut event = String::new();
let mut data = String::new();
let mut any = false;
loop {
self.line.clear();
let n = (&mut self.r)
.take(SSE_LINE_MAX as u64 + 1)
.read_until(b'\n', &mut self.line)?;
if n > SSE_LINE_MAX {
return Err(io::Error::other("an event is too long"));
}
if n == 0 {
return Ok(any.then_some((event, data)));
}
let mut l: &[u8] = &self.line;
while let Some(x) = l.strip_suffix(b"\n").or_else(|| l.strip_suffix(b"\r")) {
l = x;
}
if l.is_empty() {
if any {
return Ok(Some((event, data)));
}
continue;
}
if l.starts_with(b":") {
continue;
}
let l = String::from_utf8_lossy(l);
let (field, value) = match l.split_once(':') {
Some((f, v)) => (f, v.strip_prefix(' ').unwrap_or(v)),
None => (l.as_ref(), ""),
};
match field {
"event" => {
event = value.to_string();
any = true;
}
"data" => {
if !data.is_empty() {
data.push('\n');
}
data.push_str(value);
any = true;
}
_ => {}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn local_addresses() {
for u in [
"http://localhost:11434/v1",
"http://127.0.0.1:1234/v1",
"http://[::1]:8080/v1",
"localhost:8000",
"http://LOCALHOST/v1",
"http://user:pw@127.0.0.1:9/v1",
] {
assert!(is_local(u), "{u}");
}
for u in [
"https://api.anthropic.com/v1",
"http://192.168.1.5:11434/v1",
"http://localhost.example.com/v1",
"http://127.0.0.1.example.com/",
"http://10.0.0.1/v1",
] {
assert!(!is_local(u), "{u}");
}
}
#[test]
fn events_are_split_and_joined() {
let text = ": keep-alive\r\nevent: a\r\ndata: one\r\ndata: two\r\n\r\ndata: {\"x\":1}\n\n\nevent: end\ndata:\n";
let mut s = Sse::new(text.as_bytes());
assert_eq!(
s.next_event().unwrap(),
Some(("a".into(), "one\ntwo".into()))
);
assert_eq!(
s.next_event().unwrap(),
Some((String::new(), "{\"x\":1}".into()))
);
assert_eq!(s.next_event().unwrap(), Some(("end".into(), String::new())));
assert_eq!(s.next_event().unwrap(), None);
}
#[test]
fn error_messages() {
assert_eq!(
error_message(
r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#
),
"invalid x-api-key"
);
assert_eq!(
error_message(r#"{"error":"model 'x' not found"}"#),
"model 'x' not found"
);
assert_eq!(error_message(" Bad Gateway \n"), "Bad Gateway");
assert_eq!(
scrub(
"Incorrect API key provided: sk-abcdef123",
Some("sk-abcdef123")
),
"Incorrect API key provided: …"
);
let e = AiError::Status {
code: 401,
message: "invalid x-api-key".into(),
retry_after: None,
};
assert!(e.user_text().contains("did not accept the key"));
assert!(!e.retryable());
assert!(AiError::Status {
code: 529,
message: String::new(),
retry_after: None
}
.retryable());
}
#[test]
fn retries_stop_at_two_and_on_cancel() {
let cancel = CancelToken::new();
let mut n = 0;
let r: Result<(), AiError> = with_retries(&cancel, || {
n += 1;
Err(AiError::Status {
code: 429,
message: String::new(),
retry_after: Some(0),
})
});
assert!(r.is_err());
assert_eq!(n, 3);
let mut n = 0;
let r: Result<(), AiError> = with_retries(&cancel, || {
n += 1;
Err(AiError::Status {
code: 400,
message: String::new(),
retry_after: None,
})
});
assert!(r.is_err());
assert_eq!(n, 1);
cancel.cancel();
let r: Result<(), AiError> = with_retries(&cancel, || Err(AiError::Network("x".into())));
assert!(matches!(r, Err(AiError::Network(_))));
}
}