1use std::sync::Arc;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
8use reqwest::{Client, RequestBuilder, Response, StatusCode};
9#[cfg(any(test, feature = "modrinth", feature = "bmclapi", feature = "java"))]
10use serde::Serialize;
11#[cfg(any(
12 test,
13 feature = "curseforge",
14 feature = "mojang",
15 feature = "modrinth",
16 feature = "yggdrasil",
17 feature = "blessing",
18 feature = "loaders",
19 feature = "bmclapi",
20 feature = "java"
21))]
22use serde::de::DeserializeOwned;
23
24use crate::error::{Error, Result};
25use crate::mirror::Mirror;
26
27const MAX_ERROR_BODY_BYTES: usize = 64 * 1024;
28
29#[cfg(any(feature = "mojang", feature = "yggdrasil", feature = "blessing"))]
30pub(crate) fn bearer_header(token: &str) -> Result<HeaderValue> {
31 let mut val = HeaderValue::from_str(&format!("Bearer {token}"))?;
32 val.set_sensitive(true);
33 Ok(val)
34}
35
36#[non_exhaustive]
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub struct ResiliencePolicy {
41 pub auto_retry_rate_limit: bool,
45 pub max_retries: u32,
47 pub retry_5xx: bool,
51 pub retry_transport: bool,
56 pub fallback_to_official: bool,
62 pub max_retry_wait: Duration,
64}
65
66impl Default for ResiliencePolicy {
67 fn default() -> Self {
68 Self {
69 auto_retry_rate_limit: false,
70 max_retries: 2,
71 retry_5xx: false,
72 retry_transport: false,
73 fallback_to_official: false,
74 max_retry_wait: Duration::from_secs(30),
75 }
76 }
77}
78
79impl ResiliencePolicy {
80 #[must_use]
82 pub fn new() -> Self {
83 Self::default()
84 }
85
86 #[must_use]
88 pub const fn auto_retry_rate_limit(mut self, enabled: bool) -> Self {
89 self.auto_retry_rate_limit = enabled;
90 self
91 }
92
93 #[must_use]
95 pub const fn max_retries(mut self, max_retries: u32) -> Self {
96 self.max_retries = max_retries;
97 self
98 }
99
100 #[must_use]
102 pub const fn retry_5xx(mut self, enabled: bool) -> Self {
103 self.retry_5xx = enabled;
104 self
105 }
106
107 #[must_use]
109 pub const fn retry_transport(mut self, enabled: bool) -> Self {
110 self.retry_transport = enabled;
111 self
112 }
113
114 #[must_use]
116 pub const fn fallback_to_official(mut self, enabled: bool) -> Self {
117 self.fallback_to_official = enabled;
118 self
119 }
120
121 #[must_use]
123 pub const fn max_retry_wait(mut self, wait: Duration) -> Self {
124 self.max_retry_wait = wait;
125 self
126 }
127}
128
129#[derive(Clone, Debug)]
131pub struct HttpClientBuilder {
132 user_agent: String,
133 mirror: Mirror,
134 resilience: ResiliencePolicy,
135 timeout: Duration,
136 client: Option<Client>,
137 default_headers: HeaderMap,
138}
139
140impl Default for HttpClientBuilder {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl HttpClientBuilder {
147 #[must_use]
149 pub fn new() -> Self {
150 Self {
151 user_agent: concat!("mcapi/", env!("CARGO_PKG_VERSION")).to_string(),
152 mirror: Mirror::Official,
153 resilience: ResiliencePolicy::default(),
154 timeout: Duration::from_secs(30),
155 client: None,
156 default_headers: HeaderMap::new(),
157 }
158 }
159
160 #[must_use]
162 pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
163 self.user_agent = user_agent.into();
164 self
165 }
166
167 #[must_use]
169 pub fn mirror(mut self, mirror: Mirror) -> Self {
170 self.mirror = mirror;
171 self
172 }
173
174 #[must_use]
176 pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
177 self.resilience = resilience;
178 self
179 }
180
181 #[must_use]
183 pub fn timeout(mut self, timeout: Duration) -> Self {
184 self.timeout = timeout;
185 self
186 }
187
188 #[must_use]
190 pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
191 self.default_headers.insert(name, value);
192 self
193 }
194
195 #[must_use]
200 pub fn reqwest_client(mut self, client: Client) -> Self {
201 self.client = Some(client);
202 self
203 }
204
205 pub fn build(self) -> Result<HttpClient> {
207 let client = match self.client {
208 Some(client) => client,
209 None => Client::builder()
210 .user_agent(self.user_agent.clone())
211 .timeout(self.timeout)
212 .default_headers(self.default_headers)
213 .redirect(safe_redirect_policy())
214 .build()?,
215 };
216
217 Ok(HttpClient {
218 inner: Arc::new(HttpClientInner {
219 client,
220 mirror: self.mirror,
221 resilience: self.resilience,
222 user_agent: self.user_agent,
223 }),
224 })
225 }
226}
227
228#[derive(Debug)]
229struct HttpClientInner {
230 client: Client,
231 mirror: Mirror,
232 resilience: ResiliencePolicy,
233 user_agent: String,
234}
235
236#[derive(Clone, Debug)]
239pub struct HttpClient {
240 inner: Arc<HttpClientInner>,
241}
242
243impl HttpClient {
244 pub fn new() -> Result<Self> {
246 HttpClientBuilder::new().build()
247 }
248
249 #[must_use]
251 pub fn builder() -> HttpClientBuilder {
252 HttpClientBuilder::new()
253 }
254
255 #[must_use]
257 pub fn reqwest_client(&self) -> &Client {
258 &self.inner.client
259 }
260
261 #[must_use]
263 pub fn mirror(&self) -> &Mirror {
264 &self.inner.mirror
265 }
266
267 #[must_use]
269 pub fn resilience(&self) -> &ResiliencePolicy {
270 &self.inner.resilience
271 }
272
273 #[must_use]
275 pub fn user_agent(&self) -> &str {
276 &self.inner.user_agent
277 }
278
279 #[must_use]
281 pub fn resolve_url(&self, official_url: &str) -> String {
282 self.inner.mirror.rewrite_url(official_url)
283 }
284
285 #[must_use]
292 pub fn candidate_urls(&self, official_url: &str) -> Vec<String> {
293 self.candidate_urls_inner(official_url, true)
294 }
295
296 fn candidate_urls_inner(
297 &self,
298 official_url: &str,
299 allow_official_fallback: bool,
300 ) -> Vec<String> {
301 let mut candidates = self.inner.mirror.candidate_urls(official_url);
302 if (!self.inner.resilience.fallback_to_official || !allow_official_fallback)
303 && candidates.len() > 1
304 {
305 candidates.pop();
306 }
307 candidates
308 }
309
310 pub(crate) async fn send_with<F>(&self, official_url: &str, build_req: F) -> Result<Response>
312 where
313 F: FnMut(&Client, &str) -> RequestBuilder,
314 {
315 self.send_and_map(official_url, build_req, |resp| std::future::ready(Ok(resp)))
316 .await
317 }
318
319 #[cfg(any(
325 test,
326 feature = "mojang",
327 feature = "modrinth",
328 feature = "yggdrasil",
329 feature = "blessing"
330 ))]
331 pub(crate) async fn send_direct<F>(&self, url: &str, mut build_req: F) -> Result<Response>
332 where
333 F: FnMut(&Client, &str) -> RequestBuilder,
334 {
335 self.execute_with_retries(url, &mut build_req, false).await
336 }
337
338 #[cfg(any(
342 test,
343 feature = "mojang",
344 feature = "modrinth",
345 feature = "yggdrasil",
346 feature = "blessing"
347 ))]
348 pub(crate) async fn send_direct_idempotent<F>(
349 &self,
350 url: &str,
351 mut build_req: F,
352 ) -> Result<Response>
353 where
354 F: FnMut(&Client, &str) -> RequestBuilder,
355 {
356 self.execute_with_retries(url, &mut build_req, true).await
357 }
358
359 #[cfg(any(
362 feature = "mojang",
363 feature = "modrinth-write",
364 feature = "yggdrasil",
365 feature = "blessing"
366 ))]
367 pub(crate) async fn send_direct_oneshot<F>(&self, url: &str, build_req: F) -> Result<Response>
368 where
369 F: FnOnce(&Client, &str) -> RequestBuilder,
370 {
371 let response = build_req(&self.inner.client, url).send().await?;
372 check_response_status(response, url).await
373 }
374
375 #[cfg(any(
378 test,
379 feature = "mojang",
380 feature = "modrinth",
381 feature = "yggdrasil-authlib",
382 feature = "loaders",
383 feature = "bmclapi",
384 feature = "java"
385 ))]
386 pub(crate) async fn send_json_with<F, T>(&self, official_url: &str, build_req: F) -> Result<T>
387 where
388 F: FnMut(&Client, &str) -> RequestBuilder,
389 T: DeserializeOwned,
390 {
391 self.send_json_with_fallback_policy(official_url, true, build_req)
392 .await
393 }
394
395 #[cfg(any(
396 test,
397 feature = "curseforge",
398 feature = "mojang",
399 feature = "modrinth",
400 feature = "yggdrasil-authlib",
401 feature = "loaders",
402 feature = "bmclapi",
403 feature = "java"
404 ))]
405 pub(crate) async fn send_json_with_fallback_policy<F, T>(
406 &self,
407 official_url: &str,
408 allow_official_fallback: bool,
409 build_req: F,
410 ) -> Result<T>
411 where
412 F: FnMut(&Client, &str) -> RequestBuilder,
413 T: DeserializeOwned,
414 {
415 self.send_and_map_inner(
416 official_url,
417 allow_official_fallback,
418 build_req,
419 |resp| async move { Ok(resp.json::<T>().await?) },
420 )
421 .await
422 }
423
424 #[cfg(any(
426 test,
427 feature = "mojang",
428 feature = "modrinth",
429 feature = "yggdrasil-authlib",
430 feature = "loaders",
431 feature = "bmclapi",
432 feature = "java"
433 ))]
434 pub(crate) async fn get_json<T: DeserializeOwned>(&self, official_url: &str) -> Result<T> {
435 self.send_json_with(official_url, |client, url| client.get(url))
436 .await
437 }
438
439 #[cfg(any(feature = "modrinth", feature = "bmclapi", feature = "java"))]
441 pub(crate) async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
442 &self,
443 official_url: &str,
444 query: &Q,
445 ) -> Result<T> {
446 self.send_json_with(official_url, |client, url| client.get(url).query(query))
447 .await
448 }
449
450 #[cfg(any(test, feature = "modrinth"))]
452 pub(crate) async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
453 &self,
454 official_url: &str,
455 body: &B,
456 ) -> Result<T> {
457 self.send_json_with(official_url, |client, url| client.post(url).json(body))
458 .await
459 }
460
461 #[cfg(any(test, feature = "mojang"))]
463 pub(crate) async fn get_text(&self, official_url: &str) -> Result<String> {
464 self.send_and_map(
465 official_url,
466 |client, url| client.get(url),
467 |resp| async move { Ok(resp.text().await?) },
468 )
469 .await
470 }
471
472 #[cfg(feature = "loaders")]
478 pub(crate) async fn get_text_parsed<P, T>(&self, official_url: &str, parse: P) -> Result<T>
479 where
480 P: Fn(&str) -> Result<T>,
481 {
482 self.send_and_map(
483 official_url,
484 |client, url| client.get(url),
485 |resp| {
486 let parse = &parse;
487 async move { parse(&resp.text().await?) }
488 },
489 )
490 .await
491 }
492
493 pub async fn stream(&self, official_url: &str) -> Result<Response> {
500 self.send_with(official_url, |client, target| client.get(target))
501 .await
502 }
503
504 #[cfg(any(test, feature = "mojang", feature = "yggdrasil", feature = "blessing"))]
510 pub(crate) async fn send_optional_json<F, T>(
511 &self,
512 official_url: &str,
513 build_req: F,
514 ) -> Result<Option<T>>
515 where
516 F: FnMut(&Client, &str) -> RequestBuilder,
517 T: DeserializeOwned,
518 {
519 let res = self
520 .send_and_map(official_url, build_req, |resp| async move {
521 if resp.status() == StatusCode::NO_CONTENT {
522 return Ok(None);
523 }
524 let text = resp.text().await?;
525 if text.trim().is_empty() {
526 return Ok(None);
527 }
528 Ok(Some(serde_json::from_str(&text)?))
529 })
530 .await;
531
532 match res {
533 Ok(val) => Ok(val),
534 Err(Error::ApiStatus(ref err)) if err.status == 404 => Ok(None),
535 Err(err) => Err(err),
536 }
537 }
538
539 pub(crate) async fn send_and_map<F, M, Fut, T>(
540 &self,
541 official_url: &str,
542 build_req: F,
543 map_resp: M,
544 ) -> Result<T>
545 where
546 F: FnMut(&Client, &str) -> RequestBuilder,
547 M: FnMut(Response) -> Fut,
548 Fut: std::future::Future<Output = Result<T>>,
549 {
550 self.send_and_map_inner(official_url, true, build_req, map_resp)
551 .await
552 }
553
554 async fn send_and_map_inner<F, M, Fut, T>(
555 &self,
556 official_url: &str,
557 allow_official_fallback: bool,
558 mut build_req: F,
559 mut map_resp: M,
560 ) -> Result<T>
561 where
562 F: FnMut(&Client, &str) -> RequestBuilder,
563 M: FnMut(Response) -> Fut,
564 Fut: std::future::Future<Output = Result<T>>,
565 {
566 let candidates = self.candidate_urls_inner(official_url, allow_official_fallback);
567 let total = candidates.len();
568
569 for (idx, target_url) in candidates.into_iter().enumerate() {
570 #[cfg(feature = "tracing")]
571 tracing::debug!(target_url = %target_url, official_url = %official_url, "sending mirror-aware request");
572
573 let res = match self
574 .execute_with_retries(&target_url, &mut build_req, true)
575 .await
576 {
577 Ok(resp) => map_resp(resp).await,
578 Err(err) => Err(err),
579 };
580
581 match res {
582 Ok(val) => return Ok(val),
583 Err(err) if idx + 1 < total && should_fallback(&err) => {
584 #[cfg(feature = "tracing")]
585 tracing::warn!(
586 target_url = %target_url,
587 official_url = %official_url,
588 error = %err,
589 "mirror candidate failed, falling back to next candidate"
590 );
591 }
592 Err(err) => return Err(err),
593 }
594 }
595
596 unreachable!("candidate_urls always yields at least official_url")
597 }
598
599 async fn execute_with_retries<F>(
600 &self,
601 target_url: &str,
602 build_req: &mut F,
603 idempotent: bool,
604 ) -> Result<Response>
605 where
606 F: FnMut(&Client, &str) -> RequestBuilder,
607 {
608 let mut attempt: u32 = 0;
609 let resilience = self.inner.resilience;
610 loop {
611 let response = match build_req(&self.inner.client, target_url).send().await {
612 Ok(resp) => resp,
613 Err(err)
614 if idempotent
615 && resilience.retry_transport
616 && is_retryable_transport_error(&err)
617 && attempt < resilience.max_retries =>
618 {
619 let backoff = backoff_with_jitter(attempt);
620 #[cfg(feature = "tracing")]
621 tracing::warn!(
622 url = %target_url,
623 attempt,
624 backoff_ms = backoff.as_millis() as u64,
625 error = %err,
626 "transient transport failure, retrying"
627 );
628 tokio::time::sleep(backoff).await;
629 attempt += 1;
630 continue;
631 }
632 Err(err) => return Err(Error::Http(err)),
633 };
634 match check_response_status(response, target_url).await {
635 Ok(resp) => return Ok(resp),
636 Err(Error::RateLimitExceeded {
637 retry_after_secs,
638 limit,
639 remaining,
640 }) => {
641 if resilience.auto_retry_rate_limit && attempt < resilience.max_retries {
642 let wait = match retry_after_secs {
643 Some(secs) => {
644 Duration::from_secs(secs.max(1)).min(resilience.max_retry_wait)
645 }
646 None => backoff_with_jitter(attempt).min(resilience.max_retry_wait),
647 };
648 #[cfg(feature = "tracing")]
649 tracing::warn!(
650 url = %target_url,
651 attempt,
652 wait_ms = wait.as_millis() as u64,
653 "rate limited (429), sleeping before retry"
654 );
655 tokio::time::sleep(wait).await;
656 attempt += 1;
657 continue;
658 }
659 return Err(Error::RateLimitExceeded {
660 retry_after_secs,
661 limit,
662 remaining,
663 });
664 }
665 Err(Error::ApiStatus(ref err))
666 if idempotent
667 && resilience.retry_5xx
668 && (500..600).contains(&err.status)
669 && attempt < resilience.max_retries =>
670 {
671 let backoff = backoff_with_jitter(attempt);
672 #[cfg(feature = "tracing")]
673 tracing::warn!(
674 url = %target_url,
675 status = err.status,
676 attempt,
677 backoff_ms = backoff.as_millis() as u64,
678 "upstream 5xx error, retrying"
679 );
680 tokio::time::sleep(backoff).await;
681 attempt += 1;
682 }
683 Err(err) => return Err(err),
684 }
685 }
686 }
687}
688
689static JITTER_SEQ: AtomicU64 = AtomicU64::new(0);
690
691fn backoff_with_jitter(attempt: u32) -> Duration {
692 let base_ms = 200_u64.saturating_mul(1_u64 << attempt.min(5));
693 let nanos = SystemTime::now()
694 .duration_since(UNIX_EPOCH)
695 .map(|d| u64::from(d.subsec_nanos()))
696 .unwrap_or(0);
697 let seq = JITTER_SEQ.fetch_add(1, Ordering::Relaxed);
698 let mut x = nanos ^ seq.wrapping_mul(0x9E37_79B9_7F4A_7C15);
699 x ^= x >> 30;
700 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
701 x ^= x >> 27;
702 x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
703 x ^= x >> 31;
704 let factor_pct = 75 + (x % 51);
705 Duration::from_millis((base_ms * factor_pct) / 100)
706}
707
708fn is_retryable_transport_error(err: &reqwest::Error) -> bool {
709 (err.is_timeout() || err.is_connect() || err.is_request())
710 && !err.is_builder()
711 && !err.is_redirect()
712 && !err.is_decode()
713}
714
715async fn check_response_status(response: Response, url: &str) -> Result<Response> {
716 let status = response.status();
717 if status.is_success() {
718 return Ok(response);
719 }
720
721 if status == StatusCode::TOO_MANY_REQUESTS {
722 let (retry_after_secs, limit, remaining) = parse_rate_limit_headers(response.headers());
723 return Err(Error::RateLimitExceeded {
724 retry_after_secs,
725 limit,
726 remaining,
727 });
728 }
729
730 let body = read_bounded_error_body(response, MAX_ERROR_BODY_BYTES).await;
731 let message = extract_api_error_message(&body, status);
732 Err(Error::api_status(status.as_u16(), url, message, body))
733}
734
735async fn read_bounded_error_body(mut response: Response, max_bytes: usize) -> String {
736 let mut buf = Vec::new();
737 let mut truncated = false;
738
739 while let Ok(Some(chunk)) = response.chunk().await {
740 let remaining = max_bytes.saturating_sub(buf.len());
741 if chunk.len() > remaining {
742 buf.extend_from_slice(&chunk[..remaining]);
743 truncated = true;
744 break;
745 }
746 buf.extend_from_slice(&chunk);
747 }
748
749 if truncated
750 && let Err(err) = std::str::from_utf8(&buf)
751 && err.error_len().is_none()
752 {
753 buf.truncate(err.valid_up_to());
754 }
755
756 String::from_utf8_lossy(&buf).into_owned()
757}
758
759fn safe_redirect_policy() -> reqwest::redirect::Policy {
760 reqwest::redirect::Policy::custom(|attempt| {
761 if attempt.previous().len() >= 10 {
762 attempt.error("too many redirects")
763 } else if attempt
764 .previous()
765 .last()
766 .is_some_and(|prev| prev.scheme() == "https")
767 && attempt.url().scheme() == "http"
768 {
769 attempt.error("refusing HTTPS to HTTP redirect downgrade")
770 } else {
771 attempt.follow()
772 }
773 })
774}
775
776fn parse_header<T: std::str::FromStr>(headers: &HeaderMap, name: &str) -> Option<T> {
777 headers.get(name)?.to_str().ok()?.trim().parse::<T>().ok()
778}
779
780fn parse_rate_limit_headers(headers: &HeaderMap) -> (Option<u64>, Option<u32>, Option<u32>) {
781 let retry_after_secs = parse_header::<u64>(headers, "retry-after").or_else(|| {
782 parse_header::<u64>(headers, "x-ratelimit-reset").map(|val| {
784 if val >= 1_000_000_000 {
785 let now = SystemTime::now()
786 .duration_since(UNIX_EPOCH)
787 .map(|d| d.as_secs())
788 .unwrap_or(0);
789 val.saturating_sub(now)
790 } else {
791 val
792 }
793 })
794 });
795 let limit = parse_header::<u32>(headers, "x-ratelimit-limit");
796 let remaining = parse_header::<u32>(headers, "x-ratelimit-remaining");
797 (retry_after_secs, limit, remaining)
798}
799
800fn extract_api_error_message(body: &str, status: StatusCode) -> String {
801 if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
802 for key in [
803 "errorMessage",
804 "description",
805 "message",
806 "error_description",
807 "error",
808 ] {
809 if let Some(msg) = value.get(key).and_then(|v| v.as_str())
810 && !msg.trim().is_empty()
811 {
812 return msg.to_string();
813 }
814 }
815 }
816 let trimmed = body.trim();
817 if trimmed.is_empty() {
818 status
819 .canonical_reason()
820 .unwrap_or("unexpected status")
821 .to_string()
822 } else if trimmed.len() > 240 {
823 let end = (0..=240)
824 .rev()
825 .find(|&i| trimmed.is_char_boundary(i))
826 .unwrap_or(0);
827 format!("{}...", &trimmed[..end])
828 } else {
829 trimmed.to_string()
830 }
831}
832
833fn should_fallback(err: &Error) -> bool {
834 match err {
835 Error::Http(_) | Error::Json(_) => true,
836 #[cfg(feature = "loaders")]
837 Error::Xml(_) => true,
838 Error::ApiStatus(err) => err.status == 404 || err.status >= 500,
839 _ => false,
840 }
841}
842
843#[cfg(test)]
844mod tests {
845 use std::time::Duration;
846
847 use serde_json::json;
848
849 use super::{HttpClient, ResiliencePolicy};
850 use crate::Error;
851 use crate::mirror::{Mirror, RewriteRule};
852 use crate::test_common::{MockResponse, MockServer};
853
854 #[tokio::test]
855 async fn rate_limit_fast_fail_and_auto_retry() {
856 let server = MockServer::start().await;
857 server.enqueue(
858 MockResponse::text(429, "slow down")
859 .with_header("Retry-After", "0")
860 .with_header("X-Ratelimit-Limit", "300")
861 .with_header("X-Ratelimit-Remaining", "0"),
862 );
863
864 let http = HttpClient::new().unwrap();
865 let url = format!("{}/test", server.base_url());
866 let err = http.get_text(&url).await.unwrap_err();
867 match err {
868 Error::RateLimitExceeded {
869 retry_after_secs,
870 limit,
871 remaining,
872 } => {
873 assert_eq!(retry_after_secs, Some(0));
874 assert_eq!(limit, Some(300));
875 assert_eq!(remaining, Some(0));
876 }
877 other => panic!("expected RateLimitExceeded, got {other:?}"),
878 }
879
880 server.enqueue(MockResponse::text(429, "no headers"));
882 let err_none = http.get_text(&url).await.unwrap_err();
883 assert!(matches!(
884 err_none,
885 Error::RateLimitExceeded {
886 retry_after_secs: None,
887 ..
888 }
889 ));
890
891 server.enqueue(MockResponse::text(429, "slow down").with_header("Retry-After", "0"));
893 server.enqueue(MockResponse::text(429, "no headers"));
894 server.enqueue(MockResponse::json(200, &json!({ "ok": true })));
895
896 let retrying = HttpClient::builder()
897 .resilience(
898 ResiliencePolicy::new()
899 .auto_retry_rate_limit(true)
900 .max_retries(2)
901 .max_retry_wait(Duration::from_secs(1)),
902 )
903 .build()
904 .unwrap();
905
906 let val: serde_json::Value = retrying.get_json(&url).await.unwrap();
907 assert_eq!(val["ok"], true);
908 }
909
910 #[tokio::test]
911 async fn mirror_fallback_to_official_when_enabled() {
912 let mirror_srv = MockServer::start().await;
913 let official_srv = MockServer::start().await;
914
915 mirror_srv.on_get("/data.json", |_| MockResponse::text(502, "bad gateway"));
916 official_srv.on_get("/data.json", |_| {
917 MockResponse::json(200, &json!({ "source": "official" }))
918 });
919
920 let http = HttpClient::builder()
921 .mirror(Mirror::Custom(vec![RewriteRule::new(
922 official_srv.base_url(),
923 mirror_srv.base_url(),
924 )]))
925 .resilience(ResiliencePolicy::new().fallback_to_official(true))
926 .build()
927 .unwrap();
928
929 let val: serde_json::Value = http
930 .get_json(&format!("{}/data.json", official_srv.base_url()))
931 .await
932 .unwrap();
933 assert_eq!(val["source"], "official");
934 assert_eq!(mirror_srv.recorded_requests().len(), 1);
935 assert_eq!(official_srv.recorded_requests().len(), 1);
936 }
937
938 #[tokio::test]
939 async fn optional_json_404_falls_back_to_official_and_direct_bypasses_mirror() {
940 let mirror_srv = MockServer::start().await;
941 let official_srv = MockServer::start().await;
942
943 mirror_srv.on_get("/item.json", |_| MockResponse::empty(404));
944 official_srv.on_get("/item.json", |_| {
945 MockResponse::json(200, &json!({ "from": "official" }))
946 });
947 official_srv.on_post("/secret", |req| {
948 MockResponse::json(200, &json!({ "body": req.body_text() }))
949 });
950
951 let http = HttpClient::builder()
952 .mirror(Mirror::Custom(vec![RewriteRule::new(
953 official_srv.base_url(),
954 mirror_srv.base_url(),
955 )]))
956 .resilience(ResiliencePolicy::new().fallback_to_official(true))
957 .build()
958 .unwrap();
959
960 let url = format!("{}/item.json", official_srv.base_url());
961 let val: Option<serde_json::Value> = http
962 .send_optional_json(&url, |c, target| c.get(target))
963 .await
964 .unwrap();
965 assert_eq!(val.unwrap()["from"], "official");
966
967 let direct_url = format!("{}/secret", official_srv.base_url());
968 let payload = json!({ "tok": "abc" });
969 let raw_resp = http
970 .send_direct(&direct_url, |c, target| c.post(target).json(&payload))
971 .await
972 .unwrap();
973 let resp: serde_json::Value = raw_resp.json().await.unwrap();
974 assert!(resp["body"].as_str().unwrap().contains("abc"));
975 assert_eq!(mirror_srv.recorded_requests().len(), 1);
976 }
977
978 #[tokio::test]
979 async fn utf8_error_truncation() {
980 let server = MockServer::start().await;
981 let chinese_err = "错误".repeat(100); server.enqueue(MockResponse::text(500, chinese_err));
983
984 let http = HttpClient::new().unwrap();
985 let err = http
986 .get_text(&format!("{}/utf8", server.base_url()))
987 .await
988 .unwrap_err();
989 match err {
990 Error::ApiStatus(err) => assert!(err.message.ends_with("...")),
991 other => panic!("expected ApiStatus, got {other:?}"),
992 }
993 }
994
995 #[tokio::test]
996 async fn mirror_json_parse_failure_falls_back_to_official() {
997 let mirror_srv = MockServer::start().await;
998 let official_srv = MockServer::start().await;
999
1000 mirror_srv.on_get("/data.json", |_| {
1001 MockResponse::text(200, "<html><body>Mirror WAF challenge</body></html>")
1002 });
1003 official_srv.on_get("/data.json", |_| {
1004 MockResponse::json(200, &json!({ "source": "official-get" }))
1005 });
1006 mirror_srv.on_post("/batch", |_| MockResponse::text(200, "{\"truncated\":"));
1007 official_srv.on_post("/batch", |_| {
1008 MockResponse::json(200, &json!({ "source": "official-post" }))
1009 });
1010 mirror_srv.on_get("/optional.json", |_| {
1011 MockResponse::text(200, "<html>not json</html>")
1012 });
1013 official_srv.on_get("/optional.json", |_| {
1014 MockResponse::json(200, &json!({ "source": "official-opt" }))
1015 });
1016
1017 let http = HttpClient::builder()
1018 .mirror(Mirror::Custom(vec![RewriteRule::new(
1019 official_srv.base_url(),
1020 mirror_srv.base_url(),
1021 )]))
1022 .resilience(ResiliencePolicy::new().fallback_to_official(true))
1023 .build()
1024 .unwrap();
1025
1026 let v_get: serde_json::Value = http
1027 .get_json(&format!("{}/data.json", official_srv.base_url()))
1028 .await
1029 .unwrap();
1030 assert_eq!(v_get["source"], "official-get");
1031
1032 let v_post: serde_json::Value = http
1033 .post_json(
1034 &format!("{}/batch", official_srv.base_url()),
1035 &json!({ "ids": [1] }),
1036 )
1037 .await
1038 .unwrap();
1039 assert_eq!(v_post["source"], "official-post");
1040
1041 let v_opt: Option<serde_json::Value> = http
1042 .send_optional_json(
1043 &format!("{}/optional.json", official_srv.base_url()),
1044 |c, u| c.get(u),
1045 )
1046 .await
1047 .unwrap();
1048 assert_eq!(v_opt.unwrap()["source"], "official-opt");
1049
1050 let no_fallback = HttpClient::builder()
1052 .mirror(Mirror::Custom(vec![RewriteRule::new(
1053 official_srv.base_url(),
1054 mirror_srv.base_url(),
1055 )]))
1056 .build()
1057 .unwrap();
1058 assert!(
1059 no_fallback
1060 .get_json::<serde_json::Value>(&format!("{}/data.json", official_srv.base_url()))
1061 .await
1062 .is_err()
1063 );
1064 }
1065
1066 #[tokio::test]
1067 async fn error_status_body_is_bounded_and_utf8_safe() {
1068 let server = MockServer::start().await;
1069 server.enqueue(MockResponse::text(502, "X".repeat(256 * 1024)));
1070 server.enqueue(MockResponse::text(500, "错误".repeat(20_000)));
1071
1072 let http = HttpClient::new().unwrap();
1073
1074 let ascii_err = http
1075 .get_text(&format!("{}/big-ascii", server.base_url()))
1076 .await
1077 .unwrap_err();
1078 match ascii_err {
1079 Error::ApiStatus(err) if err.status == 502 => {
1080 assert_eq!(err.body.len(), 64 * 1024);
1081 assert!(err.message.ends_with("..."));
1082 }
1083 other => panic!("expected ApiStatus 502, got {other:?}"),
1084 }
1085
1086 let utf8_err = http
1087 .get_text(&format!("{}/big-utf8", server.base_url()))
1088 .await
1089 .unwrap_err();
1090 match utf8_err {
1091 Error::ApiStatus(err) if err.status == 500 => {
1092 assert!(err.body.len() <= 64 * 1024);
1093 assert!(!err.body.contains('\u{FFFD}'));
1094 assert!(err.message.ends_with("..."));
1095 }
1096 other => panic!("expected ApiStatus 500, got {other:?}"),
1097 }
1098 }
1099
1100 #[tokio::test]
1101 async fn multi_mirror_candidate_fallback_and_transport_retry() {
1102 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1103 use tokio::net::TcpListener;
1104
1105 let mirror_a = MockServer::start().await;
1106 let mirror_b = MockServer::start().await;
1107 let official = MockServer::start().await;
1108
1109 mirror_a.on_get("/item.json", |_| MockResponse::empty(502));
1110 mirror_b.on_get("/item.json", |_| {
1111 MockResponse::json(200, &json!({ "from": "mirror_b" }))
1112 });
1113 official.on_get("/item.json", |_| {
1114 MockResponse::json(200, &json!({ "from": "official" }))
1115 });
1116
1117 let no_proxy_client = || reqwest::Client::builder().no_proxy().build().unwrap();
1118
1119 let no_official_http = HttpClient::builder()
1120 .reqwest_client(no_proxy_client())
1121 .mirror(Mirror::Combined(vec![
1122 Mirror::Custom(vec![RewriteRule::new(
1123 official.base_url(),
1124 mirror_a.base_url(),
1125 )]),
1126 Mirror::Custom(vec![RewriteRule::new(
1127 official.base_url(),
1128 mirror_b.base_url(),
1129 )]),
1130 ]))
1131 .resilience(ResiliencePolicy::new().fallback_to_official(false))
1132 .build()
1133 .unwrap();
1134
1135 let url = format!("{}/item.json", official.base_url());
1136 let val: serde_json::Value = no_official_http.get_json(&url).await.unwrap();
1137 assert_eq!(val["from"], "mirror_b");
1138 assert_eq!(mirror_a.recorded_requests().len(), 1);
1139 assert_eq!(mirror_b.recorded_requests().len(), 1);
1140 assert!(official.recorded_requests().is_empty());
1141
1142 mirror_b.on_get("/item.json", |_| MockResponse::empty(503));
1143 let with_official_http = HttpClient::builder()
1144 .reqwest_client(no_proxy_client())
1145 .mirror(no_official_http.mirror().clone())
1146 .resilience(ResiliencePolicy::new().fallback_to_official(true))
1147 .build()
1148 .unwrap();
1149 let val2: serde_json::Value = with_official_http.get_json(&url).await.unwrap();
1150 assert_eq!(val2["from"], "official");
1151 assert_eq!(official.recorded_requests().len(), 1);
1152
1153 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1155 let port = listener.local_addr().unwrap().port();
1156 let srv = tokio::spawn(async move {
1157 let (first, _) = listener.accept().await.unwrap();
1158 drop(first);
1159
1160 let (mut second, _) = listener.accept().await.unwrap();
1161 let mut buf = [0_u8; 1024];
1162 let _ = second.read(&mut buf).await.unwrap();
1163 let body = r#"{"ok":true}"#;
1164 let resp = format!(
1165 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1166 body.len()
1167 );
1168 second.write_all(resp.as_bytes()).await.unwrap();
1169 second.flush().await.unwrap();
1170 });
1171
1172 let transport_http = HttpClient::builder()
1175 .reqwest_client(no_proxy_client())
1176 .resilience(ResiliencePolicy::new().retry_transport(true).max_retries(1))
1177 .build()
1178 .unwrap();
1179 let ok_val: serde_json::Value = transport_http
1180 .get_json(&format!("http://127.0.0.1:{port}/retry"))
1181 .await
1182 .unwrap();
1183 assert_eq!(ok_val["ok"], true);
1184 srv.await.unwrap();
1185 }
1186
1187 #[tokio::test]
1188 async fn direct_non_idempotent_skips_5xx_while_idempotent_retries_and_both_allow_429() {
1189 let mirror_srv = MockServer::start().await;
1190 let official_srv = MockServer::start().await;
1191
1192 let http = HttpClient::builder()
1193 .mirror(Mirror::Custom(vec![RewriteRule::new(
1194 official_srv.base_url(),
1195 mirror_srv.base_url(),
1196 )]))
1197 .resilience(
1198 ResiliencePolicy::new()
1199 .retry_5xx(true)
1200 .auto_retry_rate_limit(true)
1201 .max_retries(2)
1202 .max_retry_wait(Duration::from_secs(1)),
1203 )
1204 .build()
1205 .unwrap();
1206
1207 official_srv.enqueue(MockResponse::text(503, "unavailable"));
1209 let err = http
1210 .send_direct(&format!("{}/mutate", official_srv.base_url()), |c, u| {
1211 c.post(u)
1212 })
1213 .await
1214 .unwrap_err();
1215 assert!(matches!(err, Error::ApiStatus(ref e) if e.status == 503));
1216 assert_eq!(official_srv.recorded_requests().len(), 1);
1217 assert!(mirror_srv.recorded_requests().is_empty());
1218
1219 official_srv.enqueue(MockResponse::text(429, "slow down").with_header("Retry-After", "0"));
1221 official_srv.enqueue(MockResponse::json(200, &json!({ "mutated": true })));
1222 let resp = http
1223 .send_direct(&format!("{}/mutate", official_srv.base_url()), |c, u| {
1224 c.post(u)
1225 })
1226 .await
1227 .unwrap();
1228 let body: serde_json::Value = resp.json().await.unwrap();
1229 assert_eq!(body["mutated"], true);
1230 assert_eq!(official_srv.recorded_requests().len(), 3);
1231
1232 official_srv.enqueue(MockResponse::text(503, "transient"));
1234 official_srv.enqueue(MockResponse::json(200, &json!({ "ok": true })));
1235 let read_resp = http
1236 .send_direct_idempotent(&format!("{}/read", official_srv.base_url()), |c, u| {
1237 c.get(u)
1238 })
1239 .await
1240 .unwrap();
1241 let read_body: serde_json::Value = read_resp.json().await.unwrap();
1242 assert_eq!(read_body["ok"], true);
1243 assert_eq!(official_srv.recorded_requests().len(), 5);
1244 assert!(mirror_srv.recorded_requests().is_empty());
1245 }
1246
1247 #[test]
1248 fn parse_rate_limit_headers_handles_relative_epoch_and_precedence() {
1249 use std::time::{SystemTime, UNIX_EPOCH};
1250
1251 use reqwest::header::{HeaderMap, HeaderValue};
1252
1253 use super::parse_rate_limit_headers;
1254
1255 let mut h_rel = HeaderMap::new();
1257 h_rel.insert("x-ratelimit-reset", HeaderValue::from_static("12"));
1258 h_rel.insert("x-ratelimit-limit", HeaderValue::from_static("300"));
1259 h_rel.insert("x-ratelimit-remaining", HeaderValue::from_static("0"));
1260 assert_eq!(
1261 parse_rate_limit_headers(&h_rel),
1262 (Some(12), Some(300), Some(0))
1263 );
1264
1265 let now = SystemTime::now()
1267 .duration_since(UNIX_EPOCH)
1268 .unwrap()
1269 .as_secs();
1270 let future = (now + 30).to_string();
1271 let mut h_future = HeaderMap::new();
1272 h_future.insert("x-ratelimit-reset", HeaderValue::from_str(&future).unwrap());
1273 let (retry, _, _) = parse_rate_limit_headers(&h_future);
1274 assert!(matches!(retry, Some(s) if (1..=30).contains(&s)));
1275
1276 let mut h_past = HeaderMap::new();
1278 h_past.insert("x-ratelimit-reset", HeaderValue::from_static("1500000000"));
1279 assert_eq!(parse_rate_limit_headers(&h_past).0, Some(0));
1280
1281 let mut h_prec = HeaderMap::new();
1283 h_prec.insert("retry-after", HeaderValue::from_static("5"));
1284 h_prec.insert("x-ratelimit-reset", HeaderValue::from_static("99"));
1285 assert_eq!(parse_rate_limit_headers(&h_prec).0, Some(5));
1286 }
1287}