mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
//! Shared HTTP client, resilience/retry policies, and mirror-aware request helpers.

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)
}

/// Default resilience policy controlling rate-limit retries, transient 5xx/transport
/// retries, and multi-mirror fallback behavior.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResiliencePolicy {
    /// Whether HTTP 429 responses should automatically sleep and retry.
    /// Applies to replayable requests and idempotent reads (never one-shot multipart uploads).
    /// Defaults to `false` (fast-fail with `Error::RateLimitExceeded`).
    pub auto_retry_rate_limit: bool,
    /// Maximum number of retry attempts on rate limits or transient 5xx/transport errors.
    pub max_retries: u32,
    /// Whether HTTP 5xx responses should automatically retry with jittered exponential backoff.
    /// Applies only to idempotent/replayable requests (mirror-aware helpers and
    /// idempotent direct reads); never applied to non-idempotent mutations or one-shot uploads.
    pub retry_5xx: bool,
    /// Whether transient transport/connect/timeout errors on idempotent/replayable requests
    /// (mirror-aware helpers and idempotent direct reads) should automatically retry
    /// with jittered exponential backoff. Never applied to non-idempotent mutations or one-shot
    /// uploads.
    pub retry_transport: bool,
    /// Whether mirror failures (transport error, 404, 5xx, or parse error) may fall back to the
    /// original official URL after exhausting mirror candidates.
    ///
    /// Note: when disabled (`false`) and a custom mirror rewrites an optional lookup endpoint,
    /// mirror `404` responses on optional JSON lookups map directly to `Ok(None)`.
    pub fallback_to_official: bool,
    /// Maximum backoff wait for automatic rate-limit retries.
    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 {
    /// Creates a new [`ResiliencePolicy`] with default settings (retries and fallback disabled).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enables or disables automatic sleep-and-retry on HTTP `429` responses.
    #[must_use]
    pub const fn auto_retry_rate_limit(mut self, enabled: bool) -> Self {
        self.auto_retry_rate_limit = enabled;
        self
    }

    /// Sets the maximum number of retry attempts on rate limits or transient 5xx/transport errors.
    #[must_use]
    pub const fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Enables or disables automatic retries on HTTP `5xx` responses for idempotent requests.
    #[must_use]
    pub const fn retry_5xx(mut self, enabled: bool) -> Self {
        self.retry_5xx = enabled;
        self
    }

    /// Enables or disables automatic retries on transient transport errors for idempotent requests.
    #[must_use]
    pub const fn retry_transport(mut self, enabled: bool) -> Self {
        self.retry_transport = enabled;
        self
    }

    /// Enables or disables falling back to official origins after mirror failures.
    #[must_use]
    pub const fn fallback_to_official(mut self, enabled: bool) -> Self {
        self.fallback_to_official = enabled;
        self
    }

    /// Sets the maximum backoff wait duration for automatic rate-limit retries.
    #[must_use]
    pub const fn max_retry_wait(mut self, wait: Duration) -> Self {
        self.max_retry_wait = wait;
        self
    }
}

/// Builder for [`HttpClient`].
#[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 {
    /// Creates a new [`HttpClientBuilder`] with default `User-Agent`, timeout, mirror, and resilience policy.
    #[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(),
        }
    }

    /// Sets the `User-Agent` header used when building an internal `reqwest::Client`.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    /// Configures the [`Mirror`] routing strategy applied to public read requests.
    #[must_use]
    pub fn mirror(mut self, mirror: Mirror) -> Self {
        self.mirror = mirror;
        self
    }

    /// Configures the [`ResiliencePolicy`] (retries, backoff, and official fallback).
    #[must_use]
    pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
        self.resilience = resilience;
        self
    }

    /// Sets the request timeout when building an internal `reqwest::Client`.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Adds a default header when building an internal `reqwest::Client`.
    #[must_use]
    pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.default_headers.insert(name, value);
        self
    }

    /// Injects a pre-configured `reqwest::Client` (for connection pool sharing or custom TLS).
    ///
    /// Note: `user_agent`, `timeout`, and `default_header` configure the internally constructed
    /// `reqwest::Client` and are bypassed when an external `reqwest::Client` is provided.
    #[must_use]
    pub fn reqwest_client(mut self, client: Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Builds an [`HttpClient`] using the configured options.
    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,
}

/// Shared, cheaply cloneable (`Arc`-backed) HTTP client wrapper adding mirror routing,
/// rate-limit inspection, optional retries, and official-origin fallback on top of `reqwest::Client`.
#[derive(Clone, Debug)]
pub struct HttpClient {
    inner: Arc<HttpClientInner>,
}

impl HttpClient {
    /// Creates a new [`HttpClient`] with default configuration.
    pub fn new() -> Result<Self> {
        HttpClientBuilder::new().build()
    }

    /// Returns an [`HttpClientBuilder`] for customizing headers, mirror routing, and retries.
    #[must_use]
    pub fn builder() -> HttpClientBuilder {
        HttpClientBuilder::new()
    }

    /// Returns the underlying `reqwest::Client`.
    #[must_use]
    pub fn reqwest_client(&self) -> &Client {
        &self.inner.client
    }

    /// Returns the active [`Mirror`] routing strategy.
    #[must_use]
    pub fn mirror(&self) -> &Mirror {
        &self.inner.mirror
    }

    /// Returns the active [`ResiliencePolicy`].
    #[must_use]
    pub fn resilience(&self) -> &ResiliencePolicy {
        &self.inner.resilience
    }

    /// Returns the configured `User-Agent` string.
    #[must_use]
    pub fn user_agent(&self) -> &str {
        &self.inner.user_agent
    }

    /// Resolves `official_url` through the active [`Mirror`].
    #[must_use]
    pub fn resolve_url(&self, official_url: &str) -> String {
        self.inner.mirror.rewrite_url(official_url)
    }

    /// Sends a replayable request built by `build_req` and returns the raw successful [`Response`].
    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
    }

    /// Sends a non-idempotent/mutating request directly to `url`, bypassing [`Mirror`] URL
    /// rewriting and mirror fallback. Use this for authenticated mutations so credentials are
    /// never sent to third-party mirrors and requests are never replayed on transport or 5xx
    /// errors (only explicit `429` rate-limit retries apply when `auto_retry_rate_limit` is
    /// enabled).
    #[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
    }

    /// Sends an idempotent request directly to `url`, bypassing [`Mirror`] URL rewriting and
    /// mirror fallback. Use this for authenticated reads or read-only lookups that may safely
    /// retry on transient transport, `5xx`, and `429` errors according to [`ResiliencePolicy`].
    #[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
    }

    /// Sends a one-shot request directly to `url`, bypassing [`Mirror`] URL rewriting and all
    /// retries (transport, `429`, and `5xx`).
    #[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
    }

    /// Sends a replayable request built by `build_req` and deserializes the JSON body,
    /// falling back to `official_url` if mirror transport, status, or JSON parsing fails.
    #[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
    }

    /// Sends a `GET` request and deserializes the JSON body.
    #[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
    }

    /// Sends a `GET` request with query parameters and deserializes the JSON body.
    #[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
    }

    /// Sends a `POST` JSON request and deserializes the JSON body.
    #[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
    }

    /// Sends a `GET` request and returns plain text.
    #[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
    }

    /// Sends a `GET` request, reads the body as text, and parses it with `parse`.
    ///
    /// If reading or parsing the mirror response fails with a fallback-eligible error
    /// (such as malformed JSON/XML from a mirror HTML page), retries against `official_url`
    /// when `fallback_to_official` is enabled.
    #[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
    }

    /// Issues a mirror-aware `GET` request and returns the raw [`reqwest::Response`] stream.
    pub async fn stream(&self, official_url: &str) -> Result<Response> {
        self.send_with(official_url, |client, target| client.get(target))
            .await
    }

    /// Reads a JSON response or returns `Ok(None)` when the status is `204 No Content` or `404 Not Found`.
    ///
    /// Note: when a custom [`Mirror`] rewrites the endpoint and
    /// [`ResiliencePolicy::fallback_to_official`] is `false`, a mirror `404` is returned as
    /// `Ok(None)` without querying the official origin.
    #[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(|| {
        // Modrinth sends relative seconds while Laravel/some proxies send Unix epoch seconds.
        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:?}"),
        }

        // 429 without Retry-After / X-Ratelimit-Reset yields retry_after_secs: None
        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,
                ..
            }
        ));

        // Auto-retry works both with explicit Retry-After and without headers (jittered backoff)
        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); // 600 UTF-8 bytes, 240th byte is inside a 3-byte char
        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");

        // Disabled fallback surfaces the decode error directly
        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);

        // Transient transport error retry on replayable mirror-aware requests
        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();

        // 1. send_direct MUST NOT retry 5xx (non-idempotent mutations)
        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());

        // 2. send_direct DOES retry 429 when auto_retry_rate_limit is enabled
        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);

        // 3. send_direct_idempotent DOES retry 5xx while still bypassing Mirror
        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;

        // Relative x-ratelimit-reset
        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))
        );

        // Future Unix epoch in x-ratelimit-reset
        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)));

        // Past Unix epoch saturates to 0
        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));

        // Retry-After takes precedence over X-Ratelimit-Reset
        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));
    }
}