use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, RequestBuilder, Response, StatusCode};
#[cfg(any(test, feature = "modrinth", feature = "bmclapi", feature = "java"))]
use serde::Serialize;
#[cfg(any(
test,
feature = "curseforge",
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
use serde::de::DeserializeOwned;
use crate::error::{Error, Result};
use crate::mirror::Mirror;
const MAX_ERROR_BODY_BYTES: usize = 64 * 1024;
#[cfg(any(feature = "mojang", feature = "yggdrasil", feature = "blessing"))]
pub(crate) fn bearer_header(token: &str) -> Result<HeaderValue> {
let mut val = HeaderValue::from_str(&format!("Bearer {token}"))?;
val.set_sensitive(true);
Ok(val)
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResiliencePolicy {
pub auto_retry_rate_limit: bool,
pub max_retries: u32,
pub retry_5xx: bool,
pub retry_transport: 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,
retry_transport: false,
fallback_to_official: false,
max_retry_wait: Duration::from_secs(30),
}
}
}
impl ResiliencePolicy {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn auto_retry_rate_limit(mut self, enabled: bool) -> Self {
self.auto_retry_rate_limit = enabled;
self
}
#[must_use]
pub const fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = max_retries;
self
}
#[must_use]
pub const fn retry_5xx(mut self, enabled: bool) -> Self {
self.retry_5xx = enabled;
self
}
#[must_use]
pub const fn retry_transport(mut self, enabled: bool) -> Self {
self.retry_transport = enabled;
self
}
#[must_use]
pub const fn fallback_to_official(mut self, enabled: bool) -> Self {
self.fallback_to_official = enabled;
self
}
#[must_use]
pub const fn max_retry_wait(mut self, wait: Duration) -> Self {
self.max_retry_wait = wait;
self
}
}
#[derive(Clone, Debug)]
pub struct HttpClientBuilder {
user_agent: String,
mirror: Mirror,
resilience: ResiliencePolicy,
timeout: Duration,
client: Option<Client>,
default_headers: HeaderMap,
}
impl Default for HttpClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl HttpClientBuilder {
#[must_use]
pub fn new() -> Self {
Self {
user_agent: concat!("mcapi/", env!("CARGO_PKG_VERSION")).to_string(),
mirror: Mirror::Official,
resilience: ResiliencePolicy::default(),
timeout: Duration::from_secs(30),
client: None,
default_headers: HeaderMap::new(),
}
}
#[must_use]
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.user_agent = user_agent.into();
self
}
#[must_use]
pub fn mirror(mut self, mirror: Mirror) -> Self {
self.mirror = mirror;
self
}
#[must_use]
pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
self.resilience = resilience;
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.default_headers.insert(name, value);
self
}
#[must_use]
pub fn reqwest_client(mut self, client: Client) -> Self {
self.client = Some(client);
self
}
pub fn build(self) -> Result<HttpClient> {
let client = match self.client {
Some(client) => client,
None => Client::builder()
.user_agent(self.user_agent.clone())
.timeout(self.timeout)
.default_headers(self.default_headers)
.redirect(safe_redirect_policy())
.build()?,
};
Ok(HttpClient {
inner: Arc::new(HttpClientInner {
client,
mirror: self.mirror,
resilience: self.resilience,
user_agent: self.user_agent,
}),
})
}
}
#[derive(Debug)]
struct HttpClientInner {
client: Client,
mirror: Mirror,
resilience: ResiliencePolicy,
user_agent: String,
}
#[derive(Clone, Debug)]
pub struct HttpClient {
inner: Arc<HttpClientInner>,
}
impl HttpClient {
pub fn new() -> Result<Self> {
HttpClientBuilder::new().build()
}
#[must_use]
pub fn builder() -> HttpClientBuilder {
HttpClientBuilder::new()
}
#[must_use]
pub fn reqwest_client(&self) -> &Client {
&self.inner.client
}
#[must_use]
pub fn mirror(&self) -> &Mirror {
&self.inner.mirror
}
#[must_use]
pub fn resilience(&self) -> &ResiliencePolicy {
&self.inner.resilience
}
#[must_use]
pub fn user_agent(&self) -> &str {
&self.inner.user_agent
}
#[must_use]
pub fn resolve_url(&self, official_url: &str) -> String {
self.inner.mirror.rewrite_url(official_url)
}
pub(crate) 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
}
#[cfg(any(
test,
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil",
feature = "blessing"
))]
pub(crate) 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, false).await
}
#[cfg(any(
test,
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil",
feature = "blessing"
))]
pub(crate) async fn send_direct_idempotent<F>(
&self,
url: &str,
mut build_req: F,
) -> Result<Response>
where
F: FnMut(&Client, &str) -> RequestBuilder,
{
self.execute_with_retries(url, &mut build_req, true).await
}
#[cfg(any(
feature = "mojang",
feature = "modrinth-write",
feature = "yggdrasil",
feature = "blessing"
))]
pub(crate) 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
}
#[cfg(any(
test,
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil-authlib",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
pub(crate) 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_json_with_fallback_policy(official_url, true, build_req)
.await
}
#[cfg(any(
test,
feature = "curseforge",
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil-authlib",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
pub(crate) async fn send_json_with_fallback_policy<F, T>(
&self,
official_url: &str,
allow_official_fallback: bool,
build_req: F,
) -> Result<T>
where
F: FnMut(&Client, &str) -> RequestBuilder,
T: DeserializeOwned,
{
self.send_and_map_inner(
official_url,
allow_official_fallback,
build_req,
|resp| async move { Ok(resp.json::<T>().await?) },
)
.await
}
#[cfg(any(
test,
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil-authlib",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
pub(crate) async fn get_json<T: DeserializeOwned>(&self, official_url: &str) -> Result<T> {
self.send_json_with(official_url, |client, url| client.get(url))
.await
}
#[cfg(any(feature = "modrinth", feature = "bmclapi", feature = "java"))]
pub(crate) 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
}
#[cfg(any(test, feature = "modrinth"))]
pub(crate) 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
}
#[cfg(any(test, feature = "mojang"))]
pub(crate) 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
}
#[cfg(feature = "loaders")]
pub(crate) 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 stream(&self, official_url: &str) -> Result<Response> {
self.send_with(official_url, |client, target| client.get(target))
.await
}
#[cfg(any(test, feature = "mojang", feature = "yggdrasil", feature = "blessing"))]
pub(crate) 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(ref err)) if err.status == 404 => Ok(None),
Err(err) => Err(err),
}
}
pub(crate) async fn send_and_map<F, M, Fut, T>(
&self,
official_url: &str,
build_req: F,
map_resp: M,
) -> Result<T>
where
F: FnMut(&Client, &str) -> RequestBuilder,
M: FnMut(Response) -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
self.send_and_map_inner(official_url, true, build_req, map_resp)
.await
}
async fn send_and_map_inner<F, M, Fut, T>(
&self,
official_url: &str,
allow_official_fallback: bool,
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 mut candidates = self.inner.mirror.candidate_urls(official_url);
if (!self.inner.resilience.fallback_to_official || !allow_official_fallback)
&& candidates.len() > 1
{
candidates.pop();
}
let total = candidates.len();
for (idx, target_url) in candidates.into_iter().enumerate() {
#[cfg(feature = "tracing")]
tracing::debug!(target_url = %target_url, official_url = %official_url, "sending mirror-aware request");
let res = match self
.execute_with_retries(&target_url, &mut build_req, true)
.await
{
Ok(resp) => map_resp(resp).await,
Err(err) => Err(err),
};
match res {
Ok(val) => return Ok(val),
Err(err) if idx + 1 < total && should_fallback(&err) => {
#[cfg(feature = "tracing")]
tracing::warn!(
target_url = %target_url,
official_url = %official_url,
error = %err,
"mirror candidate failed, falling back to next candidate"
);
}
Err(err) => return Err(err),
}
}
unreachable!("candidate_urls always yields at least official_url")
}
async fn execute_with_retries<F>(
&self,
target_url: &str,
build_req: &mut F,
idempotent: bool,
) -> Result<Response>
where
F: FnMut(&Client, &str) -> RequestBuilder,
{
let mut attempt: u32 = 0;
let resilience = self.inner.resilience;
loop {
let response = match build_req(&self.inner.client, target_url).send().await {
Ok(resp) => resp,
Err(err)
if idempotent
&& resilience.retry_transport
&& is_retryable_transport_error(&err)
&& attempt < resilience.max_retries =>
{
let backoff = backoff_with_jitter(attempt);
#[cfg(feature = "tracing")]
tracing::warn!(
url = %target_url,
attempt,
backoff_ms = backoff.as_millis() as u64,
error = %err,
"transient transport failure, retrying"
);
tokio::time::sleep(backoff).await;
attempt += 1;
continue;
}
Err(err) => return Err(Error::Http(err)),
};
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 = match retry_after_secs {
Some(secs) => {
Duration::from_secs(secs.max(1)).min(resilience.max_retry_wait)
}
None => backoff_with_jitter(attempt).min(resilience.max_retry_wait),
};
#[cfg(feature = "tracing")]
tracing::warn!(
url = %target_url,
attempt,
wait_ms = wait.as_millis() as u64,
"rate limited (429), sleeping before retry"
);
tokio::time::sleep(wait).await;
attempt += 1;
continue;
}
return Err(Error::RateLimitExceeded {
retry_after_secs,
limit,
remaining,
});
}
Err(Error::ApiStatus(ref err))
if idempotent
&& resilience.retry_5xx
&& (500..600).contains(&err.status)
&& attempt < resilience.max_retries =>
{
let backoff = backoff_with_jitter(attempt);
#[cfg(feature = "tracing")]
tracing::warn!(
url = %target_url,
status = err.status,
attempt,
backoff_ms = backoff.as_millis() as u64,
"upstream 5xx error, retrying"
);
tokio::time::sleep(backoff).await;
attempt += 1;
}
Err(err) => return Err(err),
}
}
}
}
static JITTER_SEQ: AtomicU64 = AtomicU64::new(0);
fn backoff_with_jitter(attempt: u32) -> Duration {
let base_ms = 200_u64.saturating_mul(1_u64 << attempt.min(5));
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| u64::from(d.subsec_nanos()))
.unwrap_or(0);
let seq = JITTER_SEQ.fetch_add(1, Ordering::Relaxed);
let mut x = nanos ^ seq.wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 30;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 27;
x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
let factor_pct = 75 + (x % 51);
Duration::from_millis((base_ms * factor_pct) / 100)
}
fn is_retryable_transport_error(err: &reqwest::Error) -> bool {
(err.is_timeout() || err.is_connect() || err.is_request())
&& !err.is_builder()
&& !err.is_redirect()
&& !err.is_decode()
}
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 (retry_after_secs, limit, remaining) = parse_rate_limit_headers(response.headers());
return Err(Error::RateLimitExceeded {
retry_after_secs,
limit,
remaining,
});
}
let body = read_bounded_error_body(response, MAX_ERROR_BODY_BYTES).await;
let message = extract_api_error_message(&body, status);
Err(Error::api_status(status.as_u16(), url, message, body))
}
async fn read_bounded_error_body(mut response: Response, max_bytes: usize) -> String {
let mut buf = Vec::new();
let mut truncated = false;
while let Ok(Some(chunk)) = response.chunk().await {
let remaining = max_bytes.saturating_sub(buf.len());
if chunk.len() > remaining {
buf.extend_from_slice(&chunk[..remaining]);
truncated = true;
break;
}
buf.extend_from_slice(&chunk);
}
if truncated
&& let Err(err) = std::str::from_utf8(&buf)
&& err.error_len().is_none()
{
buf.truncate(err.valid_up_to());
}
String::from_utf8_lossy(&buf).into_owned()
}
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 parse_header<T: std::str::FromStr>(headers: &HeaderMap, name: &str) -> Option<T> {
headers.get(name)?.to_str().ok()?.trim().parse::<T>().ok()
}
fn parse_rate_limit_headers(headers: &HeaderMap) -> (Option<u64>, Option<u32>, Option<u32>) {
let retry_after_secs = parse_header::<u64>(headers, "retry-after").or_else(|| {
parse_header::<u64>(headers, "x-ratelimit-reset").map(|val| {
if val >= 1_000_000_000 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
val.saturating_sub(now)
} else {
val
}
})
});
let limit = parse_header::<u32>(headers, "x-ratelimit-limit");
let remaining = parse_header::<u32>(headers, "x-ratelimit-remaining");
(retry_after_secs, limit, remaining)
}
fn extract_api_error_message(body: &str, status: StatusCode) -> String {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
for key in [
"errorMessage",
"description",
"message",
"error_description",
"error",
] {
if let Some(msg) = value.get(key).and_then(|v| v.as_str())
&& !msg.trim().is_empty()
{
return msg.to_string();
}
}
}
let trimmed = body.trim();
if trimmed.is_empty() {
status
.canonical_reason()
.unwrap_or("unexpected status")
.to_string()
} else if trimmed.len() > 240 {
let end = (0..=240)
.rev()
.find(|&i| trimmed.is_char_boundary(i))
.unwrap_or(0);
format!("{}...", &trimmed[..end])
} else {
trimmed.to_string()
}
}
fn should_fallback(err: &Error) -> bool {
match err {
Error::Http(_) | Error::Json(_) => true,
#[cfg(feature = "loaders")]
Error::Xml(_) => true,
Error::ApiStatus(err) => err.status == 404 || err.status >= 500,
_ => false,
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde_json::json;
use super::{HttpClient, ResiliencePolicy};
use crate::Error;
use crate::mirror::{Mirror, RewriteRule};
use crate::test_common::{MockResponse, MockServer};
#[tokio::test]
async fn rate_limit_fast_fail_and_auto_retry() {
let server = MockServer::start().await;
server.enqueue(
MockResponse::text(429, "slow down")
.with_header("Retry-After", "0")
.with_header("X-Ratelimit-Limit", "300")
.with_header("X-Ratelimit-Remaining", "0"),
);
let http = HttpClient::new().unwrap();
let url = format!("{}/test", server.base_url());
let err = http.get_text(&url).await.unwrap_err();
match err {
Error::RateLimitExceeded {
retry_after_secs,
limit,
remaining,
} => {
assert_eq!(retry_after_secs, Some(0));
assert_eq!(limit, Some(300));
assert_eq!(remaining, Some(0));
}
other => panic!("expected RateLimitExceeded, got {other:?}"),
}
server.enqueue(MockResponse::text(429, "no headers"));
let err_none = http.get_text(&url).await.unwrap_err();
assert!(matches!(
err_none,
Error::RateLimitExceeded {
retry_after_secs: None,
..
}
));
server.enqueue(MockResponse::text(429, "slow down").with_header("Retry-After", "0"));
server.enqueue(MockResponse::text(429, "no headers"));
server.enqueue(MockResponse::json(200, &json!({ "ok": true })));
let retrying = HttpClient::builder()
.resilience(
ResiliencePolicy::new()
.auto_retry_rate_limit(true)
.max_retries(2)
.max_retry_wait(Duration::from_secs(1)),
)
.build()
.unwrap();
let val: serde_json::Value = retrying.get_json(&url).await.unwrap();
assert_eq!(val["ok"], true);
}
#[tokio::test]
async fn mirror_fallback_to_official_when_enabled() {
let mirror_srv = MockServer::start().await;
let official_srv = MockServer::start().await;
mirror_srv.on_get("/data.json", |_| MockResponse::text(502, "bad gateway"));
official_srv.on_get("/data.json", |_| {
MockResponse::json(200, &json!({ "source": "official" }))
});
let http = HttpClient::builder()
.mirror(Mirror::Custom(vec![RewriteRule::new(
official_srv.base_url(),
mirror_srv.base_url(),
)]))
.resilience(ResiliencePolicy::new().fallback_to_official(true))
.build()
.unwrap();
let val: serde_json::Value = http
.get_json(&format!("{}/data.json", official_srv.base_url()))
.await
.unwrap();
assert_eq!(val["source"], "official");
assert_eq!(mirror_srv.recorded_requests().len(), 1);
assert_eq!(official_srv.recorded_requests().len(), 1);
}
#[tokio::test]
async fn optional_json_404_falls_back_to_official_and_direct_bypasses_mirror() {
let mirror_srv = MockServer::start().await;
let official_srv = MockServer::start().await;
mirror_srv.on_get("/item.json", |_| MockResponse::empty(404));
official_srv.on_get("/item.json", |_| {
MockResponse::json(200, &json!({ "from": "official" }))
});
official_srv.on_post("/secret", |req| {
MockResponse::json(200, &json!({ "body": req.body_text() }))
});
let http = HttpClient::builder()
.mirror(Mirror::Custom(vec![RewriteRule::new(
official_srv.base_url(),
mirror_srv.base_url(),
)]))
.resilience(ResiliencePolicy::new().fallback_to_official(true))
.build()
.unwrap();
let url = format!("{}/item.json", official_srv.base_url());
let val: Option<serde_json::Value> = http
.send_optional_json(&url, |c, target| c.get(target))
.await
.unwrap();
assert_eq!(val.unwrap()["from"], "official");
let direct_url = format!("{}/secret", official_srv.base_url());
let payload = json!({ "tok": "abc" });
let raw_resp = http
.send_direct(&direct_url, |c, target| c.post(target).json(&payload))
.await
.unwrap();
let resp: serde_json::Value = raw_resp.json().await.unwrap();
assert!(resp["body"].as_str().unwrap().contains("abc"));
assert_eq!(mirror_srv.recorded_requests().len(), 1);
}
#[tokio::test]
async fn utf8_error_truncation() {
let server = MockServer::start().await;
let chinese_err = "错误".repeat(100); server.enqueue(MockResponse::text(500, chinese_err));
let http = HttpClient::new().unwrap();
let err = http
.get_text(&format!("{}/utf8", server.base_url()))
.await
.unwrap_err();
match err {
Error::ApiStatus(err) => assert!(err.message.ends_with("...")),
other => panic!("expected ApiStatus, got {other:?}"),
}
}
#[tokio::test]
async fn mirror_json_parse_failure_falls_back_to_official() {
let mirror_srv = MockServer::start().await;
let official_srv = MockServer::start().await;
mirror_srv.on_get("/data.json", |_| {
MockResponse::text(200, "<html><body>Mirror WAF challenge</body></html>")
});
official_srv.on_get("/data.json", |_| {
MockResponse::json(200, &json!({ "source": "official-get" }))
});
mirror_srv.on_post("/batch", |_| MockResponse::text(200, "{\"truncated\":"));
official_srv.on_post("/batch", |_| {
MockResponse::json(200, &json!({ "source": "official-post" }))
});
mirror_srv.on_get("/optional.json", |_| {
MockResponse::text(200, "<html>not json</html>")
});
official_srv.on_get("/optional.json", |_| {
MockResponse::json(200, &json!({ "source": "official-opt" }))
});
let http = HttpClient::builder()
.mirror(Mirror::Custom(vec![RewriteRule::new(
official_srv.base_url(),
mirror_srv.base_url(),
)]))
.resilience(ResiliencePolicy::new().fallback_to_official(true))
.build()
.unwrap();
let v_get: serde_json::Value = http
.get_json(&format!("{}/data.json", official_srv.base_url()))
.await
.unwrap();
assert_eq!(v_get["source"], "official-get");
let v_post: serde_json::Value = http
.post_json(
&format!("{}/batch", official_srv.base_url()),
&json!({ "ids": [1] }),
)
.await
.unwrap();
assert_eq!(v_post["source"], "official-post");
let v_opt: Option<serde_json::Value> = http
.send_optional_json(
&format!("{}/optional.json", official_srv.base_url()),
|c, u| c.get(u),
)
.await
.unwrap();
assert_eq!(v_opt.unwrap()["source"], "official-opt");
let no_fallback = HttpClient::builder()
.mirror(Mirror::Custom(vec![RewriteRule::new(
official_srv.base_url(),
mirror_srv.base_url(),
)]))
.build()
.unwrap();
assert!(
no_fallback
.get_json::<serde_json::Value>(&format!("{}/data.json", official_srv.base_url()))
.await
.is_err()
);
}
#[tokio::test]
async fn error_status_body_is_bounded_and_utf8_safe() {
let server = MockServer::start().await;
server.enqueue(MockResponse::text(502, "X".repeat(256 * 1024)));
server.enqueue(MockResponse::text(500, "错误".repeat(20_000)));
let http = HttpClient::new().unwrap();
let ascii_err = http
.get_text(&format!("{}/big-ascii", server.base_url()))
.await
.unwrap_err();
match ascii_err {
Error::ApiStatus(err) if err.status == 502 => {
assert_eq!(err.body.len(), 64 * 1024);
assert!(err.message.ends_with("..."));
}
other => panic!("expected ApiStatus 502, got {other:?}"),
}
let utf8_err = http
.get_text(&format!("{}/big-utf8", server.base_url()))
.await
.unwrap_err();
match utf8_err {
Error::ApiStatus(err) if err.status == 500 => {
assert!(err.body.len() <= 64 * 1024);
assert!(!err.body.contains('\u{FFFD}'));
assert!(err.message.ends_with("..."));
}
other => panic!("expected ApiStatus 500, got {other:?}"),
}
}
#[tokio::test]
async fn multi_mirror_candidate_fallback_and_transport_retry() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let mirror_a = MockServer::start().await;
let mirror_b = MockServer::start().await;
let official = MockServer::start().await;
mirror_a.on_get("/item.json", |_| MockResponse::empty(502));
mirror_b.on_get("/item.json", |_| {
MockResponse::json(200, &json!({ "from": "mirror_b" }))
});
official.on_get("/item.json", |_| {
MockResponse::json(200, &json!({ "from": "official" }))
});
let no_official_http = HttpClient::builder()
.mirror(Mirror::Combined(vec![
Mirror::Custom(vec![RewriteRule::new(
official.base_url(),
mirror_a.base_url(),
)]),
Mirror::Custom(vec![RewriteRule::new(
official.base_url(),
mirror_b.base_url(),
)]),
]))
.resilience(ResiliencePolicy::new().fallback_to_official(false))
.build()
.unwrap();
let url = format!("{}/item.json", official.base_url());
let val: serde_json::Value = no_official_http.get_json(&url).await.unwrap();
assert_eq!(val["from"], "mirror_b");
assert_eq!(mirror_a.recorded_requests().len(), 1);
assert_eq!(mirror_b.recorded_requests().len(), 1);
assert!(official.recorded_requests().is_empty());
mirror_b.on_get("/item.json", |_| MockResponse::empty(503));
let with_official_http = HttpClient::builder()
.mirror(no_official_http.mirror().clone())
.resilience(ResiliencePolicy::new().fallback_to_official(true))
.build()
.unwrap();
let val2: serde_json::Value = with_official_http.get_json(&url).await.unwrap();
assert_eq!(val2["from"], "official");
assert_eq!(official.recorded_requests().len(), 1);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let srv = tokio::spawn(async move {
let (first, _) = listener.accept().await.unwrap();
drop(first);
let (mut second, _) = listener.accept().await.unwrap();
let mut buf = [0_u8; 1024];
let _ = second.read(&mut buf).await.unwrap();
let body = r#"{"ok":true}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
second.write_all(resp.as_bytes()).await.unwrap();
second.flush().await.unwrap();
});
let transport_http = HttpClient::builder()
.resilience(ResiliencePolicy::new().retry_transport(true).max_retries(1))
.build()
.unwrap();
let ok_val: serde_json::Value = transport_http
.get_json(&format!("http://127.0.0.1:{port}/retry"))
.await
.unwrap();
assert_eq!(ok_val["ok"], true);
srv.await.unwrap();
}
#[tokio::test]
async fn direct_non_idempotent_skips_5xx_while_idempotent_retries_and_both_allow_429() {
let mirror_srv = MockServer::start().await;
let official_srv = MockServer::start().await;
let http = HttpClient::builder()
.mirror(Mirror::Custom(vec![RewriteRule::new(
official_srv.base_url(),
mirror_srv.base_url(),
)]))
.resilience(
ResiliencePolicy::new()
.retry_5xx(true)
.auto_retry_rate_limit(true)
.max_retries(2)
.max_retry_wait(Duration::from_secs(1)),
)
.build()
.unwrap();
official_srv.enqueue(MockResponse::text(503, "unavailable"));
let err = http
.send_direct(&format!("{}/mutate", official_srv.base_url()), |c, u| {
c.post(u)
})
.await
.unwrap_err();
assert!(matches!(err, Error::ApiStatus(ref e) if e.status == 503));
assert_eq!(official_srv.recorded_requests().len(), 1);
assert!(mirror_srv.recorded_requests().is_empty());
official_srv.enqueue(MockResponse::text(429, "slow down").with_header("Retry-After", "0"));
official_srv.enqueue(MockResponse::json(200, &json!({ "mutated": true })));
let resp = http
.send_direct(&format!("{}/mutate", official_srv.base_url()), |c, u| {
c.post(u)
})
.await
.unwrap();
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(body["mutated"], true);
assert_eq!(official_srv.recorded_requests().len(), 3);
official_srv.enqueue(MockResponse::text(503, "transient"));
official_srv.enqueue(MockResponse::json(200, &json!({ "ok": true })));
let read_resp = http
.send_direct_idempotent(&format!("{}/read", official_srv.base_url()), |c, u| {
c.get(u)
})
.await
.unwrap();
let read_body: serde_json::Value = read_resp.json().await.unwrap();
assert_eq!(read_body["ok"], true);
assert_eq!(official_srv.recorded_requests().len(), 5);
assert!(mirror_srv.recorded_requests().is_empty());
}
#[test]
fn parse_rate_limit_headers_handles_relative_epoch_and_precedence() {
use std::time::{SystemTime, UNIX_EPOCH};
use reqwest::header::{HeaderMap, HeaderValue};
use super::parse_rate_limit_headers;
let mut h_rel = HeaderMap::new();
h_rel.insert("x-ratelimit-reset", HeaderValue::from_static("12"));
h_rel.insert("x-ratelimit-limit", HeaderValue::from_static("300"));
h_rel.insert("x-ratelimit-remaining", HeaderValue::from_static("0"));
assert_eq!(
parse_rate_limit_headers(&h_rel),
(Some(12), Some(300), Some(0))
);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let future = (now + 30).to_string();
let mut h_future = HeaderMap::new();
h_future.insert("x-ratelimit-reset", HeaderValue::from_str(&future).unwrap());
let (retry, _, _) = parse_rate_limit_headers(&h_future);
assert!(matches!(retry, Some(s) if (1..=30).contains(&s)));
let mut h_past = HeaderMap::new();
h_past.insert("x-ratelimit-reset", HeaderValue::from_static("1500000000"));
assert_eq!(parse_rate_limit_headers(&h_past).0, Some(0));
let mut h_prec = HeaderMap::new();
h_prec.insert("retry-after", HeaderValue::from_static("5"));
h_prec.insert("x-ratelimit-reset", HeaderValue::from_static("99"));
assert_eq!(parse_rate_limit_headers(&h_prec).0, Some(5));
}
}