use std::sync::Arc;
use std::time::Duration;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, RequestBuilder, Response, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::error::{Error, Result, extract_api_error_message, parse_rate_limit_headers};
use crate::mirror::Mirror;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResiliencePolicy {
pub auto_retry_rate_limit: bool,
pub max_retries: u32,
pub retry_5xx: bool,
pub fallback_to_official: bool,
pub max_retry_wait: Duration,
}
impl Default for ResiliencePolicy {
fn default() -> Self {
Self {
auto_retry_rate_limit: false,
max_retries: 2,
retry_5xx: false,
fallback_to_official: false,
max_retry_wait: Duration::from_secs(30),
}
}
}
#[derive(Clone, Debug)]
pub struct HttpConfig {
pub user_agent: String,
pub mirror: Mirror,
pub resilience: ResiliencePolicy,
pub timeout: Duration,
}
impl Default for HttpConfig {
fn default() -> Self {
Self {
user_agent: concat!("mcapi/", env!("CARGO_PKG_VERSION")).to_string(),
mirror: Mirror::Official,
resilience: ResiliencePolicy::default(),
timeout: Duration::from_secs(30),
}
}
}
#[derive(Clone, Debug)]
pub struct HttpCoreBuilder {
config: HttpConfig,
client: Option<Client>,
default_headers: HeaderMap,
}
impl Default for HttpCoreBuilder {
fn default() -> Self {
Self::new()
}
}
impl HttpCoreBuilder {
pub fn new() -> Self {
Self {
config: HttpConfig::default(),
client: None,
default_headers: HeaderMap::new(),
}
}
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.config.user_agent = user_agent.into();
self
}
pub fn mirror(mut self, mirror: Mirror) -> Self {
self.config.mirror = mirror;
self
}
pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
self.config.resilience = resilience;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.config.timeout = timeout;
self
}
pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.default_headers.insert(name, value);
self
}
pub fn with_client(mut self, client: Client) -> Self {
self.client = Some(client);
self
}
pub fn build(self) -> Result<HttpCore> {
let client = match self.client {
Some(client) => client,
None => Client::builder()
.user_agent(self.config.user_agent.clone())
.timeout(self.config.timeout)
.default_headers(self.default_headers)
.redirect(safe_redirect_policy())
.build()?,
};
Ok(HttpCore {
inner: Arc::new(HttpCoreInner {
client,
mirror: self.config.mirror,
resilience: self.config.resilience,
user_agent: self.config.user_agent,
}),
})
}
}
#[derive(Debug)]
struct HttpCoreInner {
client: Client,
mirror: Mirror,
resilience: ResiliencePolicy,
user_agent: String,
}
#[derive(Clone, Debug)]
pub struct HttpCore {
inner: Arc<HttpCoreInner>,
}
impl HttpCore {
pub fn new() -> Result<Self> {
HttpCoreBuilder::new().build()
}
pub fn builder() -> HttpCoreBuilder {
HttpCoreBuilder::new()
}
pub fn client(&self) -> &Client {
&self.inner.client
}
pub fn mirror(&self) -> &Mirror {
&self.inner.mirror
}
pub fn resilience(&self) -> &ResiliencePolicy {
&self.inner.resilience
}
pub fn user_agent(&self) -> &str {
&self.inner.user_agent
}
pub fn resolve_url(&self, official_url: &str) -> String {
self.inner.mirror.rewrite_url(official_url)
}
pub async fn send_with<F>(&self, official_url: &str, build_req: F) -> Result<Response>
where
F: FnMut(&Client, &str) -> RequestBuilder,
{
self.send_and_map(official_url, build_req, |resp| std::future::ready(Ok(resp)))
.await
}
pub async fn send_oneshot<F>(&self, official_url: &str, build_req: F) -> Result<Response>
where
F: FnOnce(&Client, &str) -> RequestBuilder,
{
let target_url = self.inner.mirror.rewrite_url(official_url);
let response = build_req(&self.inner.client, &target_url).send().await?;
check_response_status(response, &target_url).await
}
pub async fn send_direct<F>(&self, url: &str, mut build_req: F) -> Result<Response>
where
F: FnMut(&Client, &str) -> RequestBuilder,
{
self.execute_with_retries(url, &mut build_req).await
}
pub async fn send_direct_oneshot<F>(&self, url: &str, build_req: F) -> Result<Response>
where
F: FnOnce(&Client, &str) -> RequestBuilder,
{
let response = build_req(&self.inner.client, url).send().await?;
check_response_status(response, url).await
}
pub async fn post_direct_json<B: Serialize + ?Sized, T: DeserializeOwned>(
&self,
url: &str,
body: &B,
) -> Result<T> {
let resp = self
.send_direct(url, |client, target| client.post(target).json(body))
.await?;
Ok(resp.json::<T>().await?)
}
pub async fn send_json_with<F, T>(&self, official_url: &str, build_req: F) -> Result<T>
where
F: FnMut(&Client, &str) -> RequestBuilder,
T: DeserializeOwned,
{
self.send_and_map(official_url, build_req, |resp| async move {
Ok(resp.json::<T>().await?)
})
.await
}
pub async fn get_json<T: DeserializeOwned>(&self, official_url: &str) -> Result<T> {
self.send_json_with(official_url, |client, url| client.get(url))
.await
}
pub async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
&self,
official_url: &str,
query: &Q,
) -> Result<T> {
self.send_json_with(official_url, |client, url| client.get(url).query(query))
.await
}
pub async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
&self,
official_url: &str,
body: &B,
) -> Result<T> {
self.send_json_with(official_url, |client, url| client.post(url).json(body))
.await
}
pub async fn get_text(&self, official_url: &str) -> Result<String> {
self.send_and_map(
official_url,
|client, url| client.get(url),
|resp| async move { Ok(resp.text().await?) },
)
.await
}
pub async fn get_text_parsed<P, T>(&self, official_url: &str, parse: P) -> Result<T>
where
P: Fn(&str) -> Result<T>,
{
self.send_and_map(
official_url,
|client, url| client.get(url),
|resp| {
let parse = &parse;
async move { parse(&resp.text().await?) }
},
)
.await
}
pub async fn get_stream(&self, official_url: &str) -> Result<Response> {
self.send_with(official_url, |client, target| client.get(target))
.await
}
pub async fn send_optional_json<F, T>(
&self,
official_url: &str,
build_req: F,
) -> Result<Option<T>>
where
F: FnMut(&Client, &str) -> RequestBuilder,
T: DeserializeOwned,
{
let res = self
.send_and_map(official_url, build_req, |resp| async move {
if resp.status() == StatusCode::NO_CONTENT {
return Ok(None);
}
let text = resp.text().await?;
if text.trim().is_empty() {
return Ok(None);
}
Ok(Some(serde_json::from_str(&text)?))
})
.await;
match res {
Ok(val) => Ok(val),
Err(Error::ApiStatus { status: 404, .. }) => Ok(None),
Err(err) => Err(err),
}
}
async fn send_and_map<F, M, Fut, T>(
&self,
official_url: &str,
mut build_req: F,
mut map_resp: M,
) -> Result<T>
where
F: FnMut(&Client, &str) -> RequestBuilder,
M: FnMut(Response) -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let primary_url = self.inner.mirror.rewrite_url(official_url);
let rewritten = primary_url != official_url;
let primary_res = match self
.execute_with_retries(&primary_url, &mut build_req)
.await
{
Ok(resp) => map_resp(resp).await,
Err(err) => Err(err),
};
match primary_res {
Ok(val) => Ok(val),
Err(err)
if rewritten
&& self.inner.resilience.fallback_to_official
&& should_fallback(&err) =>
{
let resp = self
.execute_with_retries(official_url, &mut build_req)
.await?;
map_resp(resp).await
}
Err(err) => Err(err),
}
}
async fn execute_with_retries<F>(&self, target_url: &str, build_req: &mut F) -> Result<Response>
where
F: FnMut(&Client, &str) -> RequestBuilder,
{
let mut attempt: u32 = 0;
let resilience = self.inner.resilience;
loop {
let response = build_req(&self.inner.client, target_url).send().await?;
match check_response_status(response, target_url).await {
Ok(resp) => return Ok(resp),
Err(Error::RateLimitExceeded {
retry_after_secs,
limit,
remaining,
}) => {
if resilience.auto_retry_rate_limit && attempt < resilience.max_retries {
let wait = Duration::from_secs(retry_after_secs.max(1))
.min(resilience.max_retry_wait);
tokio::time::sleep(wait).await;
attempt += 1;
continue;
}
return Err(Error::RateLimitExceeded {
retry_after_secs,
limit,
remaining,
});
}
Err(Error::ApiStatus { status, .. })
if resilience.retry_5xx
&& (500..600).contains(&status)
&& attempt < resilience.max_retries =>
{
let backoff = Duration::from_millis(200 * (1_u64 << attempt.min(5)));
tokio::time::sleep(backoff).await;
attempt += 1;
}
Err(err) => return Err(err),
}
}
}
}
pub async fn check_response_status(response: Response, url: &str) -> Result<Response> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
if status == StatusCode::TOO_MANY_REQUESTS {
let info = parse_rate_limit_headers(response.headers());
return Err(Error::RateLimitExceeded {
retry_after_secs: info.retry_after_secs.unwrap_or(60),
limit: info.limit,
remaining: info.remaining,
});
}
let body = response.text().await.unwrap_or_default();
let message = extract_api_error_message(&body, status);
Err(Error::ApiStatus {
status: status.as_u16(),
url: url.to_string(),
message,
body,
})
}
fn safe_redirect_policy() -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(|attempt| {
if attempt.previous().len() >= 10 {
attempt.error("too many redirects")
} else if attempt
.previous()
.last()
.is_some_and(|prev| prev.scheme() == "https")
&& attempt.url().scheme() == "http"
{
attempt.error("refusing HTTPS to HTTP redirect downgrade")
} else {
attempt.follow()
}
})
}
fn should_fallback(err: &Error) -> bool {
match err {
Error::Http(_) | Error::Json(_) => true,
#[cfg(feature = "loaders")]
Error::Xml(_) => true,
Error::ApiStatus { status, .. } => *status == 404 || *status >= 500,
_ => false,
}
}