Audiphi/src/core/http.rs
2026-10-24 17:58:16 -05:00

195 lines
6.6 KiB
Rust

//! One shared ureq agent with sane timeouts and retries, plus the helpers the resolvers use.
use serde_json::Value;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use ureq::ResponseExt;
pub const BROWSER_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
pub const TIMEOUT: Duration = Duration::from_secs(20);
pub fn app_ua() -> String {
format!("{}/{} ( {} )", crate::APP_NAME, crate::VERSION, crate::HOMEPAGE)
}
#[derive(Debug, Clone)]
pub struct HttpError {
/// 0 for transport errors (DNS, TLS, timeout).
pub status: u16,
pub msg: String,
}
impl std::fmt::Display for HttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.status > 0 {
write!(f, "HTTP {}: {}", self.status, self.msg)
} else {
write!(f, "{}", self.msg)
}
}
}
impl From<HttpError> for String {
fn from(e: HttpError) -> String {
e.to_string()
}
}
fn agent() -> &'static ureq::Agent {
static A: OnceLock<ureq::Agent> = OnceLock::new();
A.get_or_init(|| {
let cfg = ureq::Agent::config_builder().timeout_global(Some(TIMEOUT)).http_status_as_error(false).build();
ureq::Agent::new_with_config(cfg)
})
}
pub struct Reply {
pub status: u16,
pub url: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
}
impl Reply {
pub fn text(&self, force_utf8: bool) -> String {
let _ = force_utf8;
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json(&self) -> Result<Value, HttpError> {
serde_json::from_slice(&self.body).map_err(|e| HttpError { status: self.status, msg: format!("bad JSON: {e}") })
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
fn check(self) -> Result<Reply, HttpError> {
if self.ok() {
Ok(self)
} else {
let snippet: String = String::from_utf8_lossy(&self.body).chars().take(200).collect();
Err(HttpError { status: self.status, msg: snippet })
}
}
}
pub fn query_string(params: &[(&str, String)]) -> String {
params.iter().map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v))).collect::<Vec<_>>().join("&")
}
pub fn with_params(url: &str, params: &[(&str, String)]) -> String {
if params.is_empty() {
return url.to_string();
}
format!("{}{}{}", url, if url.contains('?') { "&" } else { "?" }, query_string(params))
}
fn finish(mut resp: ureq::http::Response<ureq::Body>) -> Result<Reply, HttpError> {
let status = resp.status().as_u16();
let url = resp.get_uri().to_string();
let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
let body = resp.body_mut().with_config().limit(64 * 1024 * 1024).read_to_vec().map_err(|e| HttpError { status: 0, msg: e.to_string() })?;
Ok(Reply { status, url, body, headers })
}
fn terr(e: ureq::Error) -> HttpError {
HttpError { status: 0, msg: e.to_string() }
}
/// GET with up to three tries on transport errors and 429/5xx.
pub fn get(url: &str, headers: &[(&str, &str)]) -> Result<Reply, HttpError> {
let mut last = HttpError { status: 0, msg: "no attempt".into() };
for attempt in 0..3u32 {
if attempt > 0 {
std::thread::sleep(Duration::from_millis(600 * (1 << (attempt - 1))));
}
let mut req = agent().get(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
match req.call().map_err(terr).and_then(finish) {
Ok(r) if r.status == 429 || (500..600).contains(&r.status) => {
last = HttpError { status: r.status, msg: String::from_utf8_lossy(&r.body).chars().take(200).collect() };
if r.status == 429 {
if let Some(s) = r.header("retry-after").and_then(|s| s.parse::<u64>().ok()) {
std::thread::sleep(Duration::from_secs(s.min(5)));
}
}
}
Ok(r) => return Ok(r),
Err(e) => last = e,
}
}
Err(last)
}
pub fn get_json(url: &str, params: &[(&str, String)], browser: bool, extra: &[(&str, &str)]) -> Result<Value, HttpError> {
let ua = if browser { BROWSER_UA.to_string() } else { app_ua() };
let mut h: Vec<(&str, &str)> = vec![("User-Agent", ua.as_str()), ("Accept", "application/json")];
h.extend_from_slice(extra);
get(&with_params(url, params), &h)?.check()?.json()
}
/// (final_url, body)
pub fn get_text(url: &str) -> Result<(String, String), HttpError> {
let r = get(url, &[("User-Agent", BROWSER_UA), ("Accept-Language", "en-US,en;q=0.8")])?.check()?;
let text = r.text(true);
Ok((r.url, text))
}
pub fn get_bytes(url: &str) -> Result<Vec<u8>, HttpError> {
Ok(get(url, &[("User-Agent", BROWSER_UA)])?.check()?.body)
}
/// Follow redirects and return the final URL (short links).
pub fn final_url(url: &str) -> Result<String, HttpError> {
Ok(get(url, &[("User-Agent", BROWSER_UA)])?.url)
}
pub fn post_json(url: &str, body: &Value, headers: &[(&str, &str)]) -> Result<Value, HttpError> {
let mut req = agent().post(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send_json(body).map_err(terr)?;
finish(resp)?.check()?.json()
}
/// Form POST; returns the raw reply so callers can read the status.
pub fn post_form(url: &str, form: &[(&str, &str)], headers: &[(&str, &str)]) -> Result<Reply, HttpError> {
let mut req = agent().post(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send_form(form.iter().map(|(k, v)| (*k, *v))).map_err(terr)?;
finish(resp)
}
/// At most one call per `interval` across threads (MusicBrainz asks for 1/s).
pub struct RateLimiter {
interval: Duration,
last: Mutex<Option<Instant>>,
}
impl RateLimiter {
pub const fn new(ms: u64) -> Self {
RateLimiter { interval: Duration::from_millis(ms), last: Mutex::new(None) }
}
pub fn wait(&self) {
let mut g = self.last.lock().unwrap();
if let Some(t) = *g {
let due = t + self.interval;
let now = Instant::now();
if due > now {
std::thread::sleep(due - now);
}
}
*g = Some(Instant::now());
}
}
pub fn b64(s: &str) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(s)
}