eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
//! Policy-driven retry subsystem.
//!
//! Retries are opt-in and idempotency-aware. The retry engine wraps the
//! entire logical request attempt (including redirects) under a single
//! total deadline. Each retry restarts the complete logical request,
//! including redirects, under the original total deadline.
//!
//! # Safety
//!
//! POST and PATCH requests are never retried by default unless explicitly
//! allowed by the policy or protected by an idempotency key. Stream
//! bodies are never retried unless a replay factory is provided.
//!
//! # Backoff
//!
//! Uses bounded exponential backoff with jitter. Tests can use
//! deterministic policies by injecting a fixed random source.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
use std::time::Duration;

use http::Method;

use crate::body::RequestBody;
use crate::error::Error;

/// Default retryable status codes: 408, 429, 502, 503, 504.
const DEFAULT_RETRYABLE_STATUSES: &[u16] = &[408, 429, 502, 503, 504];

/// Returns `true` when a hyper-util legacy client error wraps a canceled
/// hyper connection (stale pooled connection closed before any byte was
/// sent). Delegates to the centralized bounded classifier evidence in
/// `crate::error` so cancellation facts cannot diverge; retry policy
/// semantics are unchanged (only this typed fact is consulted, never the
/// broader `TransportFailureKind` category).
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
fn is_hyper_canceled(inner: &hyper_util::client::legacy::Error) -> bool {
    crate::error::hyper_legacy_is_canceled(inner)
}

/// Default retryable methods: GET, HEAD, OPTIONS.
const DEFAULT_RETRYABLE_METHODS: &[Method] = &[Method::GET, Method::HEAD, Method::OPTIONS];

/// Policy-driven retry configuration.
///
/// Controls which requests are retried, how many times, and with what
/// backoff strategy. Retries are opt-in: the default policy disables
/// retries.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use eggfetch_core::RetryPolicy;
///
/// let policy = RetryPolicy::builder()
///     .max_attempts(3)
///     .backoff_factor(0.2)
///     .retry_status(429)
///     .retry_status(503)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    /// Maximum number of total attempts (1 = no retries).
    max_attempts: usize,
    /// Maximum total elapsed time across all attempts including backoff sleeps.
    max_elapsed: Option<Duration>,
    /// Backoff configuration.
    backoff: BackoffPolicy,
    /// Which HTTP methods are eligible for retry.
    method_policy: MethodPolicy,
    /// Which status codes trigger a retry.
    status_policy: StatusPolicy,
    /// Whether to respect `Retry-After` headers.
    respect_retry_after: bool,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 1,
            max_elapsed: None,
            backoff: BackoffPolicy::default(),
            method_policy: MethodPolicy::default(),
            status_policy: StatusPolicy::default(),
            respect_retry_after: false,
        }
    }
}

impl RetryPolicy {
    /// Create a new retry policy builder.
    #[must_use]
    pub fn builder() -> RetryPolicyBuilder {
        RetryPolicyBuilder::new()
    }

    /// Returns the maximum number of total attempts.
    #[must_use]
    pub fn max_attempts(&self) -> usize {
        self.max_attempts
    }

    /// Returns the maximum total elapsed time.
    #[must_use]
    pub fn max_elapsed(&self) -> Option<Duration> {
        self.max_elapsed
    }

    /// Returns a reference to the backoff policy.
    #[must_use]
    pub fn backoff(&self) -> &BackoffPolicy {
        &self.backoff
    }

    /// Returns a reference to the method policy.
    #[must_use]
    pub fn method_policy(&self) -> &MethodPolicy {
        &self.method_policy
    }

    /// Returns a reference to the status policy.
    #[must_use]
    pub fn status_policy(&self) -> &StatusPolicy {
        &self.status_policy
    }

    /// Returns whether `Retry-After` headers are respected.
    #[must_use]
    pub fn respect_retry_after(&self) -> bool {
        self.respect_retry_after
    }

    /// Returns `true` if retries are effectively enabled (`max_attempts` > 1).
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.max_attempts > 1
    }

    /// Returns `true` if the given method is eligible for retry.
    #[must_use]
    pub fn is_method_retryable(&self, method: &Method) -> bool {
        self.method_policy.is_retryable(method)
    }

    /// Returns `true` if the given status code is eligible for retry.
    #[must_use]
    pub fn is_status_retryable(&self, status: u16) -> bool {
        self.status_policy.is_retryable(status)
    }

    /// Returns `true` if the given error is eligible for retry.
    #[must_use]
    pub fn is_error_retryable(error: &Error) -> bool {
        #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
        if let Error::HyperClient(inner) = error {
            // Only retry failures that can succeed on replay:
            // connect-level errors (`is_connect`, including DNS/TCP and
            // connector handshake failures) and stale-pooled-connection
            // cancellations (`hyper::Error::is_canceled`, "connection
            // closed" before any byte was sent). User/config errors
            // (unsupported method/version/absolute-uri) and mid-request
            // send failures are never retried, so cert/config problems
            // cannot be masked by a retry loop.
            return inner.is_connect() || is_hyper_canceled(inner.as_ref());
        }
        match error {
            Error::Connect(_)
            | Error::Io(_)
            | Error::Hyper(_)
            | Error::Timeout {
                phase: crate::timeout::TimeoutPhase::Connect,
                ..
            }
            | Error::Timeout {
                phase: crate::timeout::TimeoutPhase::Pool,
                ..
            }
            | Error::Timeout {
                phase:
                    crate::timeout::TimeoutPhase::ProxyConnect | crate::timeout::TimeoutPhase::ProxyTls,
                ..
            }
            | Error::H3Connect(_) => true,
            Error::CustomTransport(error) => matches!(
                error.kind(),
                crate::transport::dialer::DialErrorKind::Connection
                    | crate::transport::dialer::DialErrorKind::Timeout
            ),
            Error::Http2StreamReset { reason } if reason.starts_with("REFUSED_STREAM") => true,
            _ => false,
        }
    }

    /// Compute the backoff delay for the given attempt number (1-indexed).
    ///
    /// Returns `None` if no delay is needed (attempt 1).
    #[must_use]
    pub fn backoff_delay(&self, attempt: usize) -> Option<Duration> {
        self.backoff.delay(attempt)
    }

    /// Compute the delay after receiving a `Retry-After` header value.
    ///
    /// Parses `Retry-After` as either a number of seconds or an HTTP-date.
    /// Returns `None` if parsing fails, if a past HTTP-date is supplied
    /// (the header carries no useful information), or if the value
    /// exceeds the backoff cap.
    #[must_use]
    pub fn retry_after_delay(&self, retry_after: &str) -> Option<Duration> {
        if !self.respect_retry_after {
            return None;
        }
        let delay = if let Ok(secs) = retry_after.trim().parse::<u64>() {
            Duration::from_secs(secs)
        } else if let Ok(date) = httpdate::parse_http_date(retry_after.trim()) {
            match date.duration_since(std::time::SystemTime::now()) {
                Ok(duration) => duration,
                Err(_) => return None,
            }
        } else {
            return None;
        };
        let cap = self.backoff.max_delay;
        Some(if delay > cap { cap } else { delay })
    }

    /// Check if a request body is replayable for retry.
    ///
    /// Returns `ReplayCheck::Replayable` if the body can be replayed,
    /// or `ReplayCheck::NotReplayable` if the body is a live stream.
    #[must_use]
    pub fn check_body_replayable(body: &RequestBody) -> ReplayCheck {
        if body.is_replayable() {
            ReplayCheck::Replayable
        } else {
            ReplayCheck::NotReplayable
        }
    }
}

/// Builder for constructing a [`RetryPolicy`].
pub struct RetryPolicyBuilder {
    max_attempts: usize,
    max_elapsed: Option<Duration>,
    backoff: BackoffPolicyBuilder,
    method_policy: MethodPolicy,
    status_policy: StatusPolicy,
    respect_retry_after: bool,
    custom_statuses_used: bool,
}

impl RetryPolicyBuilder {
    /// Create a new builder with defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_attempts: 1,
            max_elapsed: None,
            backoff: BackoffPolicyBuilder::new(),
            method_policy: MethodPolicy::default(),
            status_policy: StatusPolicy::default(),
            respect_retry_after: false,
            custom_statuses_used: false,
        }
    }

    /// Set the maximum number of total attempts (including the first request).
    ///
    /// A value of 1 means no retries. A value of 3 means up to 2 retries.
    #[must_use]
    pub fn max_attempts(mut self, max: usize) -> Self {
        self.max_attempts = max;
        self
    }

    /// Set the maximum total elapsed time across all attempts.
    ///
    /// Includes backoff sleeps. If `None`, no total time limit is applied.
    #[must_use]
    pub fn max_elapsed(mut self, elapsed: Duration) -> Self {
        self.max_elapsed = Some(elapsed);
        self
    }

    /// Set the backoff factor for exponential backoff.
    ///
    /// The delay before retry attempt `n` (`n >= 2`) is
    /// `initial_delay * factor^(n - 2)`, capped at `max_delay` and
    /// reduced by full jitter. The default factor is `2.0`.
    #[must_use]
    pub fn backoff_factor(mut self, factor: f64) -> Self {
        self.backoff = self.backoff.factor(factor);
        self
    }

    /// Set the maximum delay between retries.
    #[must_use]
    pub fn max_delay(mut self, delay: Duration) -> Self {
        self.backoff = self.backoff.max_delay(delay);
        self
    }

    /// Set the initial delay for the first retry.
    #[must_use]
    pub fn initial_delay(mut self, delay: Duration) -> Self {
        self.backoff = self.backoff.initial_delay(delay);
        self
    }

    /// Add a retryable status code.
    ///
    /// The first call to `retry_status` replaces the default set
    /// (408, 429, 502, 503, 504). Subsequent calls add to the set.
    #[must_use]
    pub fn retry_status(mut self, status: u16) -> Self {
        if !self.custom_statuses_used {
            self.status_policy = StatusPolicy::default_empty();
            self.custom_statuses_used = true;
        }
        self.status_policy.add_status(status);
        self
    }

    /// Set the retryable status codes, replacing any existing ones.
    #[must_use]
    pub fn retry_statuses(mut self, statuses: impl IntoIterator<Item = u16>) -> Self {
        self.status_policy = StatusPolicy::new(statuses);
        self.custom_statuses_used = true;
        self
    }

    /// Add a retryable method.
    #[must_use]
    pub fn retry_method(mut self, method: Method) -> Self {
        self.method_policy.add_method(method);
        self
    }

    /// Allow POST requests to be retried.
    #[must_use]
    pub fn allow_post_retry(mut self) -> Self {
        self.method_policy.add_method(Method::POST);
        self
    }

    /// Allow PUT requests to be retried.
    #[must_use]
    pub fn allow_put_retry(mut self) -> Self {
        self.method_policy.add_method(Method::PUT);
        self
    }

    /// Allow DELETE requests to be retried.
    #[must_use]
    pub fn allow_delete_retry(mut self) -> Self {
        self.method_policy.add_method(Method::DELETE);
        self
    }

    /// Allow PATCH requests to be retried.
    #[must_use]
    pub fn allow_patch_retry(mut self) -> Self {
        self.method_policy.add_method(Method::PATCH);
        self
    }

    /// Enable or disable `Retry-After` header support.
    #[must_use]
    pub fn respect_retry_after(mut self, respect: bool) -> Self {
        self.respect_retry_after = respect;
        self
    }

    /// Build the retry policy.
    #[must_use]
    pub fn build(self) -> RetryPolicy {
        RetryPolicy {
            max_attempts: self.max_attempts,
            max_elapsed: self.max_elapsed,
            backoff: self.backoff.build(),
            method_policy: self.method_policy,
            status_policy: self.status_policy,
            respect_retry_after: self.respect_retry_after,
        }
    }
}

impl Default for RetryPolicyBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Backoff strategy for retries.
#[derive(Debug, Clone)]
pub struct BackoffPolicy {
    /// Base factor for exponential backoff.
    factor: f64,
    /// Maximum delay cap.
    max_delay: Duration,
    /// Initial delay for the first retry.
    initial_delay: Duration,
}

impl Default for BackoffPolicy {
    fn default() -> Self {
        Self {
            factor: 2.0,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(500),
        }
    }
}

impl BackoffPolicy {
    /// Compute the delay for the given attempt number (1-indexed).
    ///
    /// Attempt 1 returns `None` (no delay before the first attempt).
    /// Later attempts use exponential backoff with full jitter: the
    /// delay is drawn uniformly from `[0, capped)`, where `capped` is
    /// `initial_delay * factor^(attempt - 2)` clamped to `max_delay`.
    #[must_use]
    #[allow(
        clippy::cast_precision_loss,
        reason = "the attempt counter is only used as an f64 exponent, so rounding beyond 2^53 attempts cannot change the delay"
    )]
    pub fn delay(&self, attempt: usize) -> Option<Duration> {
        if attempt <= 1 {
            return None;
        }

        // Exponential backoff: initial_delay * factor^(attempt-2)
        let exp = (attempt - 2) as f64;
        let raw = self.initial_delay.as_secs_f64() * self.factor.powf(exp);
        // `Duration::MAX.as_secs_f64()` rounds up to 2^64 (oversize for
        // `from_secs_f64`), so treat a non-convertible max as unbounded
        // here; the saturating conversion below clamps to `max_delay` anyway.
        let max_float = self.max_delay.as_secs_f64();
        let max_secs = if Duration::try_from_secs_f64(max_float).is_ok() {
            max_float
        } else {
            f64::MAX
        };

        // Guard against NaN, inf, negative, and values exceeding max_delay
        // before converting to Duration. `Duration::from_secs_f64` panics on
        // non-finite, negative, or oversized floats, and `max_delay` itself
        // may be `Duration::MAX` whose `as_secs_f64()` rounds up to 2^64
        // (oversize), so saturate instead of converting directly.
        let capped = if !raw.is_finite() || raw < 0.0 || raw > max_secs {
            self.max_delay
        } else {
            Duration::try_from_secs_f64(raw).unwrap_or(self.max_delay)
        };

        // Full jitter: uniform value in [0, capped) so retries in the
        // saturated regime do not all collapse onto the cap (which would
        // re-create the thundering-herd pattern jitter exists to prevent).
        // If the system RNG fails, degrade to the deterministic capped
        // delay instead of panicking.
        let jittered_secs = match get_random_f64() {
            Some(jitter) => capped.as_secs_f64() * jitter,
            None => capped.as_secs_f64(),
        };

        let final_delay = if !jittered_secs.is_finite() || jittered_secs < 0.0 {
            capped
        } else {
            // `capped` may be `Duration::MAX` (whose float form rounds to
            // oversize 2^64); saturate instead of panicking.
            Duration::try_from_secs_f64(jittered_secs).unwrap_or(capped)
        };

        // Avoid a zero-length retry loop when jitter rounds a positive
        // budget down to zero. Preserve an explicitly zero cap as an
        // intentional immediate retry.
        Some(final_delay.max(Duration::from_millis(1).min(capped)))
    }

    /// Returns the maximum delay.
    #[must_use]
    pub fn max_delay(&self) -> Duration {
        self.max_delay
    }

    /// Returns the factor.
    #[must_use]
    pub fn factor(&self) -> f64 {
        self.factor
    }

    /// Returns the initial delay.
    #[must_use]
    pub fn initial_delay(&self) -> Duration {
        self.initial_delay
    }
}

/// Builder for [`BackoffPolicy`].
pub struct BackoffPolicyBuilder {
    factor: f64,
    max_delay: Duration,
    initial_delay: Duration,
}

impl BackoffPolicyBuilder {
    #[must_use]
    fn new() -> Self {
        Self {
            factor: 2.0,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(500),
        }
    }

    #[must_use]
    fn factor(mut self, factor: f64) -> Self {
        // `BackoffPolicy::delay` caps non-finite or non-positive factors to
        // `max_delay` (see fuzz regression for NaN), so the builder accepts
        // any f64 and defers validation to the delay computation.
        self.factor = factor;
        self
    }

    #[must_use]
    fn max_delay(mut self, delay: Duration) -> Self {
        self.max_delay = delay;
        self
    }

    #[must_use]
    fn initial_delay(mut self, delay: Duration) -> Self {
        self.initial_delay = delay;
        self
    }

    #[must_use]
    fn build(self) -> BackoffPolicy {
        BackoffPolicy {
            factor: self.factor,
            max_delay: self.max_delay,
            initial_delay: self.initial_delay,
        }
    }
}

/// Policy controlling which HTTP methods are eligible for retry.
#[derive(Debug, Clone)]
pub struct MethodPolicy {
    /// Set of methods eligible for retry.
    methods: Vec<Method>,
}

impl Default for MethodPolicy {
    fn default() -> Self {
        Self {
            methods: DEFAULT_RETRYABLE_METHODS.to_vec(),
        }
    }
}

impl MethodPolicy {
    /// Create a method policy with the given methods.
    #[must_use]
    pub fn new(methods: Vec<Method>) -> Self {
        Self { methods }
    }

    /// Add a method to the retryable set.
    pub fn add_method(&mut self, method: Method) {
        if !self.methods.contains(&method) {
            self.methods.push(method);
        }
    }

    /// Returns `true` if the method is retryable.
    #[must_use]
    pub fn is_retryable(&self, method: &Method) -> bool {
        self.methods.contains(method)
    }

    /// Returns the list of retryable methods.
    #[must_use]
    pub fn methods(&self) -> &[Method] {
        &self.methods
    }
}

/// Policy controlling which status codes trigger a retry.
#[derive(Debug, Clone)]
pub struct StatusPolicy {
    /// Set of status codes eligible for retry.
    statuses: Vec<u16>,
}

impl Default for StatusPolicy {
    fn default() -> Self {
        Self {
            statuses: DEFAULT_RETRYABLE_STATUSES.to_vec(),
        }
    }
}

impl StatusPolicy {
    /// Create a status policy with the given codes.
    #[must_use]
    pub fn new(statuses: impl IntoIterator<Item = u16>) -> Self {
        Self {
            statuses: statuses.into_iter().collect(),
        }
    }

    /// Create an empty status policy (no retryable statuses).
    #[must_use]
    pub fn default_empty() -> Self {
        Self {
            statuses: Vec::new(),
        }
    }

    /// Add a status code to the retryable set.
    pub fn add_status(&mut self, status: u16) {
        if !self.statuses.contains(&status) {
            self.statuses.push(status);
        }
    }

    /// Returns `true` if the status code is retryable.
    #[must_use]
    pub fn is_retryable(&self, status: u16) -> bool {
        self.statuses.contains(&status)
    }

    /// Returns the list of retryable status codes.
    #[must_use]
    pub fn statuses(&self) -> &[u16] {
        &self.statuses
    }
}

/// Result of a body replayability check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplayCheck {
    /// The body can be replayed.
    Replayable,
    /// The body cannot be replayed.
    NotReplayable,
}

/// The cause of a retry decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RetryCause {
    /// A transport error occurred (connection refused, reset, etc.).
    TransportError(String),
    /// A retryable HTTP status code was received.
    Status(u16),
    /// A timeout occurred during a retryable phase.
    Timeout(String),
}

impl std::fmt::Display for RetryCause {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TransportError(msg) => write!(f, "transport error: {msg}"),
            Self::Status(status) => write!(f, "retryable status: {status}"),
            Self::Timeout(phase) => write!(f, "timeout: {phase}"),
        }
    }
}

/// Context for a retry attempt.
#[derive(Debug, Clone)]
pub struct RetryContext {
    /// The current attempt number (1-indexed).
    pub attempt: usize,
    /// The HTTP method.
    pub method: Method,
    /// Whether the request body is replayable.
    pub body_replayable: bool,
    /// The cause that triggered this retry.
    pub cause: RetryCause,
    /// Remaining total budget.
    pub remaining_total: Option<Duration>,
}

/// Determine if an error/status should trigger a retry.
///
/// Returns `Some(RetryCause)` if the error is retryable under the given
/// policy, `None` otherwise.
#[must_use]
pub fn should_retry(
    policy: &RetryPolicy,
    method: &Method,
    body: &RequestBody,
    error: Option<&Error>,
    status: Option<u16>,
) -> Option<RetryCause> {
    // Check method eligibility
    if !policy.is_method_retryable(method) {
        return None;
    }

    // Check body replayability
    if !body.is_replayable() {
        return None;
    }

    // Check error-based retry
    if let Some(err) = error {
        if RetryPolicy::is_error_retryable(err) {
            return Some(RetryCause::TransportError(err.to_string()));
        }
        return None;
    }

    // Check status-based retry
    if let Some(status) = status {
        if policy.is_status_retryable(status) {
            return Some(RetryCause::Status(status));
        }
    }

    None
}

/// Get a random f64 in [0, 1) from a process-local PRNG.
///
/// Returns `None` if the system RNG fails so callers can degrade
/// gracefully (e.g. to a deterministic delay) instead of panicking.
#[allow(
    clippy::cast_precision_loss,
    reason = "the 53 high bits of the PRNG state are exactly representable in f64, so the conversion is lossless"
)]
fn get_random_f64() -> Option<f64> {
    // Only successful seeds are cached: a transient `getrandom` failure is
    // retried on the next call instead of pinning the process to
    // deterministic backoff for its whole lifetime.
    static STATE: OnceLock<AtomicU64> = OnceLock::new();

    let state = if let Some(state) = STATE.get() {
        state
    } else {
        let mut buf = [0u8; 8];
        let seed = u64::from_le_bytes({
            getrandom::getrandom(&mut buf).ok()?;
            buf
        })
        .max(1);
        let _ = STATE.set(AtomicU64::new(seed));
        STATE.get()?
    };
    // `fetch_update` is deprecated in favor of `try_update` on recent
    // toolchains, but `try_update` is still unstable on MSRV 1.89, so the
    // rename cannot be adopted until MSRV moves forward.
    #[allow(
        deprecated,
        reason = "fetch_update is deprecated in favour of try_update, which is still unstable on the MSRV toolchain"
    )]
    let val = state
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |mut value| {
            value ^= value << 13;
            value ^= value >> 7;
            value ^= value << 17;
            Some(value.max(1))
        })
        .ok()?;
    // Use the top 53 bits so the value is exactly representable and the
    // result stays strictly below 1.0 (dividing a rounded u64 by
    // `u64::MAX as f64` could round up to exactly 1.0).
    Some(((val >> 11) as f64) / ((1u64 << 53) as f64))
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn retry_policy_default_disables_retries() {
        let policy = RetryPolicy::default();
        assert!(!policy.is_enabled());
        assert_eq!(policy.max_attempts(), 1);
    }

    #[test]
    fn proxy_timeout_phases_are_retryable() {
        for phase in [
            crate::timeout::TimeoutPhase::ProxyConnect,
            crate::timeout::TimeoutPhase::ProxyTls,
        ] {
            let error = Error::Timeout {
                phase,
                elapsed: Duration::from_secs(1),
            };
            assert!(RetryPolicy::is_error_retryable(&error));
        }
    }

    #[test]
    fn custom_dialer_connection_and_timeout_failures_are_retryable() {
        for kind in [
            crate::transport::dialer::DialErrorKind::Connection,
            crate::transport::dialer::DialErrorKind::Timeout,
        ] {
            let error = Error::CustomTransport(std::sync::Arc::new(
                crate::transport::dialer::DialError::new(kind, "route failed"),
            ));
            assert!(RetryPolicy::is_error_retryable(&error));
        }
        for kind in [
            crate::transport::dialer::DialErrorKind::Authentication,
            crate::transport::dialer::DialErrorKind::Rejected,
            crate::transport::dialer::DialErrorKind::Other,
        ] {
            let error = Error::CustomTransport(std::sync::Arc::new(
                crate::transport::dialer::DialError::new(kind, "route failed"),
            ));
            assert!(!RetryPolicy::is_error_retryable(&error));
        }
    }

    #[test]
    fn jitter_is_strictly_below_one() {
        // The documented contract is [0, 1); a sample that rounds up to
        // exactly 1.0 would let the backoff delay reach the capped max.
        for _ in 0..10_000 {
            let Some(jitter) = get_random_f64() else {
                // RNG unavailable in this environment: the production
                // path degrades to a deterministic delay, so there is
                // nothing to assert here.
                return;
            };
            assert!((0.0..1.0).contains(&jitter));
        }
    }

    #[test]
    fn retry_policy_builder_basic() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .backoff_factor(0.2)
            .build();
        assert!(policy.is_enabled());
        assert_eq!(policy.max_attempts(), 3);
    }

    #[test]
    fn retry_policy_method_default_safe() {
        let policy = RetryPolicy::default();
        assert!(policy.is_method_retryable(&Method::GET));
        assert!(policy.is_method_retryable(&Method::HEAD));
        assert!(policy.is_method_retryable(&Method::OPTIONS));
        assert!(!policy.is_method_retryable(&Method::POST));
        assert!(!policy.is_method_retryable(&Method::PUT));
        assert!(!policy.is_method_retryable(&Method::DELETE));
        assert!(!policy.is_method_retryable(&Method::PATCH));
    }

    #[test]
    fn retry_policy_method_allow_post() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .allow_post_retry()
            .build();
        assert!(policy.is_method_retryable(&Method::POST));
    }

    #[test]
    fn retry_policy_status_default() {
        let policy = RetryPolicy::default();
        assert!(policy.is_status_retryable(408));
        assert!(policy.is_status_retryable(429));
        assert!(policy.is_status_retryable(502));
        assert!(policy.is_status_retryable(503));
        assert!(policy.is_status_retryable(504));
        assert!(!policy.is_status_retryable(200));
        assert!(!policy.is_status_retryable(404));
    }

    #[test]
    fn retry_policy_status_custom() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .retry_status(429)
            .retry_status(503)
            .build();
        assert!(policy.is_status_retryable(429));
        assert!(policy.is_status_retryable(503));
        assert!(!policy.is_status_retryable(408));
        assert!(!policy.is_status_retryable(504));
    }

    #[test]
    fn backoff_delay_none_for_first_attempt() {
        let backoff = BackoffPolicy::default();
        assert!(backoff.delay(1).is_none());
    }

    #[test]
    fn backoff_delay_bounded_for_later_attempts() {
        let backoff = BackoffPolicy {
            factor: 0.5,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(100),
        };
        // Full jitter: the delay is drawn from [0, capped).
        let d2 = backoff.delay(2).unwrap();
        assert!(d2 <= Duration::from_millis(100));

        let d3 = backoff.delay(3).unwrap();
        assert!(d3 <= Duration::from_millis(50));
    }

    #[test]
    fn backoff_delay_has_minimum_when_cap_is_positive() {
        let backoff = BackoffPolicy {
            factor: 1.0,
            max_delay: Duration::from_millis(1),
            initial_delay: Duration::from_millis(1),
        };
        assert_eq!(backoff.delay(2), Some(Duration::from_millis(1)));
    }

    #[test]
    fn default_backoff_grows_exponentially() {
        // The default policy must back off, not speed up: the cap for
        // attempt n is `initial_delay * 2^(n - 2)`. Jitter draws below
        // the cap, so only upper bounds are asserted.
        let backoff = BackoffPolicy::default();
        assert!((backoff.factor() - 2.0).abs() < f64::EPSILON);
        assert!(backoff.delay(2).unwrap() <= Duration::from_millis(500));
        assert!(backoff.delay(3).unwrap() <= Duration::from_secs(1));
        assert!(backoff.delay(4).unwrap() <= Duration::from_secs(2));
    }

    #[test]
    fn backoff_delay_capped_at_max() {
        let backoff = BackoffPolicy {
            factor: 2.0,
            max_delay: Duration::from_secs(5),
            initial_delay: Duration::from_secs(1),
        };
        let d = backoff.delay(10).unwrap();
        assert!(d < Duration::from_secs(5)); // full jitter stays below cap
    }

    #[test]
    fn retry_after_disabled_by_default() {
        let policy = RetryPolicy::default();
        assert!(policy.retry_after_delay("5").is_none());
    }

    #[test]
    fn retry_after_respected_when_enabled() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .respect_retry_after(true)
            .build();
        let delay = policy.retry_after_delay("5").unwrap();
        assert_eq!(delay, Duration::from_secs(5));
    }

    #[test]
    fn retry_after_capped_at_max_delay() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .respect_retry_after(true)
            .max_delay(Duration::from_secs(10))
            .build();
        let delay = policy.retry_after_delay("60").unwrap();
        assert_eq!(delay, Duration::from_secs(10));
    }

    #[test]
    fn retry_after_invalid_ignored() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .respect_retry_after(true)
            .build();
        assert!(policy.retry_after_delay("not-a-number").is_none());
    }

    #[test]
    fn retry_after_http_date_parses() {
        use std::time::UNIX_EPOCH;

        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .respect_retry_after(true)
            .build();
        // Build a future SystemTime and format it with httpdate, then parse it back
        // to guarantee the day-of-week matches
        let future_time = UNIX_EPOCH
            + Duration::from_secs(
                std::time::SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    + 3600,
            ); // 1 hour from now
        let formatted = httpdate::fmt_http_date(future_time);
        let parsed = httpdate::parse_http_date(&formatted);
        assert!(parsed.is_ok(), "round-trip parse failed: {formatted}");
        let delay = policy.retry_after_delay(&formatted);
        assert!(
            delay.is_some(),
            "retry_after_delay returned None for HTTP-date: {formatted}"
        );
        let d = delay.unwrap();
        assert!(d.as_secs() > 0, "delay should be positive");
    }

    #[test]
    fn retry_after_past_http_date_is_ignored() {
        use std::time::UNIX_EPOCH;

        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .respect_retry_after(true)
            .build();
        // One hour in the past: the header carries no useful information,
        // so it must be ignored (None) rather than mapped to zero.
        let past_time = UNIX_EPOCH
            + Duration::from_secs(
                std::time::SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    .saturating_sub(3600),
            );
        let formatted = httpdate::fmt_http_date(past_time);
        assert!(policy.retry_after_delay(&formatted).is_none());
    }

    #[test]
    fn body_replayable_empty() {
        let body = RequestBody::Empty;
        assert_eq!(
            RetryPolicy::check_body_replayable(&body),
            ReplayCheck::Replayable
        );
    }

    #[test]
    fn body_replayable_bytes() {
        let body = RequestBody::from(bytes::Bytes::from("hello"));
        assert_eq!(
            RetryPolicy::check_body_replayable(&body),
            ReplayCheck::Replayable
        );
    }

    #[test]
    fn body_not_replayable_stream() {
        let body = RequestBody::from_stream(
            futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
            None,
        );
        assert_eq!(
            RetryPolicy::check_body_replayable(&body),
            ReplayCheck::NotReplayable
        );
    }

    #[test]
    fn should_retry_get_with_retryable_status() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
        assert_eq!(cause, Some(RetryCause::Status(503)));
    }

    #[test]
    fn should_not_retry_post_by_default() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
        assert_eq!(cause, None);
    }

    #[test]
    fn should_retry_post_when_allowed() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .allow_post_retry()
            .build();
        let body = RequestBody::Empty;
        let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
        assert_eq!(cause, Some(RetryCause::Status(503)));
    }

    #[test]
    fn should_not_retry_non_retryable_status() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let cause = should_retry(&policy, &Method::GET, &body, None, Some(200));
        assert_eq!(cause, None);
    }

    #[test]
    fn should_not_retry_stream_body() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::from_stream(
            futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
            None,
        );
        let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
        assert_eq!(cause, None);
    }

    #[test]
    fn should_retry_connect_error() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::Connect("connection refused".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert!(matches!(cause, Some(RetryCause::TransportError(_))));
    }

    #[test]
    fn should_not_retry_invalid_url() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::InvalidUrl("bad url".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert_eq!(cause, None);
    }

    #[test]
    #[cfg(feature = "http3")]
    fn should_retry_h3_connect_error() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::H3Connect("QUIC handshake failed".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert!(matches!(cause, Some(RetryCause::TransportError(_))));
    }

    #[test]
    #[cfg(feature = "http3")]
    fn should_not_retry_h3_connection_closed() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::H3ConnectionClosed("peer sent GOAWAY".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert_eq!(cause, None);
    }

    #[test]
    #[cfg(feature = "http3")]
    fn should_not_retry_h3_protocol_error() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::H3Protocol("unexpected frame".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert_eq!(cause, None);
    }

    #[test]
    #[cfg(feature = "http3")]
    fn should_not_retry_h3_stream_error() {
        let policy = RetryPolicy::builder().max_attempts(3).build();
        let body = RequestBody::Empty;
        let err = Error::H3Stream("stream reset".into());
        let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
        assert_eq!(cause, None);
    }

    #[test]
    fn retry_cause_display() {
        assert_eq!(
            RetryCause::TransportError("refused".into()).to_string(),
            "transport error: refused"
        );
        assert_eq!(RetryCause::Status(503).to_string(), "retryable status: 503");
        assert_eq!(
            RetryCause::Timeout("total".into()).to_string(),
            "timeout: total"
        );
    }

    #[test]
    fn method_policy_add_method() {
        let mut policy = MethodPolicy::default();
        assert!(!policy.is_retryable(&Method::POST));
        policy.add_method(Method::POST);
        assert!(policy.is_retryable(&Method::POST));
    }

    #[test]
    fn status_policy_add_status() {
        let mut policy = StatusPolicy::default();
        assert!(!policy.is_retryable(418));
        policy.add_status(418);
        assert!(policy.is_retryable(418));
    }

    #[test]
    fn retry_policy_max_elapsed() {
        let policy = RetryPolicy::builder()
            .max_attempts(3)
            .max_elapsed(Duration::from_secs(10))
            .build();
        assert_eq!(policy.max_elapsed(), Some(Duration::from_secs(10)));
    }

    #[test]
    fn retry_policy_display_cause() {
        let cause = RetryCause::Status(429);
        assert_eq!(format!("{cause}"), "retryable status: 429");
    }

    #[test]
    fn prop_backoff_delay_some_for_attempt_gt_1() {
        proptest::proptest!(|(attempt in 2usize..100usize)| {
            let backoff = BackoffPolicy::default();
            prop_assert!(backoff.delay(attempt).is_some());
        });
    }

    #[test]
    fn prop_backoff_delay_bounded_by_max_delay() {
        proptest::proptest!(|(
            factor in 0.1f64..2.0f64,
            initial_ms in 1u64..1000u64,
            max_secs in 1u64..60u64,
            attempt in 2usize..20usize,
        )| {
            let backoff = BackoffPolicy {
                factor,
                max_delay: Duration::from_secs(max_secs),
                initial_delay: Duration::from_millis(initial_ms),
            };
            if let Some(delay) = backoff.delay(attempt) {
                prop_assert!(delay <= Duration::from_secs(max_secs * 2));
            }
        });
    }

    #[test]
    fn prop_method_policy_default_contains_get_head_options() {
        let policy = MethodPolicy::default();
        assert!(policy.is_retryable(&Method::GET));
        assert!(policy.is_retryable(&Method::HEAD));
        assert!(policy.is_retryable(&Method::OPTIONS));
    }

    #[test]
    fn prop_status_policy_default_contains_expected() {
        let policy = StatusPolicy::default();
        assert!(policy.is_retryable(408));
        assert!(policy.is_retryable(429));
        assert!(policy.is_retryable(502));
        assert!(policy.is_retryable(503));
        assert!(policy.is_retryable(504));
    }

    #[test]
    fn prop_retry_after_delay_returns_none_for_garbage() {
        proptest::proptest!(|(input in ".{0,100}")| {
            let policy = RetryPolicy::builder()
                .max_attempts(3)
                .respect_retry_after(true)
                .build();
            let _ = policy.retry_after_delay(&input);
        });
    }

    #[test]
    fn regression_fuzz_retry_crash_extreme_backoff_factor() {
        let backoff = BackoffPolicy {
            factor: 22.0,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(500),
        };
        for attempt in 2..=20 {
            let delay = backoff.delay(attempt);
            assert!(delay.is_some());
            assert!(delay.unwrap() <= backoff.max_delay);
        }
    }

    #[test]
    fn backoff_delay_nan_factor_returns_bounded_delay() {
        let backoff = BackoffPolicy {
            factor: f64::NAN,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(500),
        };
        let d = backoff.delay(5).unwrap();
        assert!(d <= Duration::from_secs(30));
    }

    #[test]
    fn backoff_delay_infinite_factor_returns_bounded_delay() {
        let backoff = BackoffPolicy {
            factor: f64::INFINITY,
            max_delay: Duration::from_secs(30),
            initial_delay: Duration::from_millis(500),
        };
        let d = backoff.delay(5).unwrap();
        assert!(d <= Duration::from_secs(30));
    }

    #[test]
    fn backoff_delay_max_duration_does_not_panic() {
        // `Duration::MAX.as_secs_f64()` rounds up to 2^64, which
        // `Duration::from_secs_f64` rejects: the delay must saturate.
        let backoff = BackoffPolicy {
            factor: 2.0,
            max_delay: Duration::MAX,
            initial_delay: Duration::from_millis(500),
        };
        for attempt in [2, 5, 100] {
            let d = backoff.delay(attempt).unwrap();
            assert!(d <= Duration::MAX);
        }
    }

    #[test]
    fn prop_is_error_retryable_never_panics() {
        proptest::proptest!(|(msg in ".{0,200}")| {
            let errors = vec![
                Error::Connect(msg.clone()),
                Error::Io(std::sync::Arc::new(std::io::Error::other(msg.clone()))),
                Error::InvalidUrl(msg.clone()),
                Error::Tls(msg.clone()),
                Error::Protocol(msg.clone()),
                Error::Body(msg.clone()),
            ];
            for err in &errors {
                let _ = RetryPolicy::is_error_retryable(err);
            }
        });
    }
}