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
//! Retry policy: retry loop, backoff delay, and bounded discard drain.
//!
//! Retries restart the complete logical request (including redirects) under
//! the original total deadline. Stream bodies are never retried. Backoff,
//! `Retry-After`, replayability, retryable status/error classification, and
//! total-deadline behavior live here and must not change in a pure
//! decomposition.

use std::time::Duration;

use crate::client::Client;
use crate::error::{Error, Result};
use crate::request::Request;
use crate::response::Response;
use crate::retry::{should_retry, RetryCause, RetryPolicy};
use crate::timeout::TimeoutPhase;

use super::drain_response_body;

/// Sleep for the backoff delay if the total budget allows it.
///
/// Returns `Err(RetryBudgetExhausted)` if sleeping would exceed the
/// remaining total budget.
async fn sleep_if_budget_allows(
    policy: &RetryPolicy,
    delay: Duration,
    attempt: usize,
    start_time: std::time::Instant,
    total: Option<Duration>,
) -> Result<()> {
    if let Some(max_elapsed) = policy.max_elapsed() {
        let elapsed = start_time.elapsed();
        // `Duration::add` panics on overflow; fail closed instead.
        match elapsed.checked_add(delay) {
            Some(t) if t <= max_elapsed => {}
            _ => return Err(Error::RetryBudgetExhausted { attempts: attempt }),
        }
    }
    // Gate backoff sleep on the remaining native total so a long backoff
    // cannot overshoot the outer deadline; the next-attempt check is too late.
    if let Some(total) = total {
        let elapsed = start_time.elapsed();
        match elapsed.checked_add(delay) {
            Some(t) if t <= total => {}
            _ => {
                return Err(Error::Timeout {
                    phase: TimeoutPhase::Total,
                    elapsed: start_time.elapsed(),
                });
            }
        }
    }
    tokio::time::sleep(delay).await;
    Ok(())
}

/// Check if there is budget remaining for another retry attempt.
fn has_budget(policy: &RetryPolicy, attempt: usize, start_time: std::time::Instant) -> bool {
    if attempt >= policy.max_attempts() {
        return false;
    }
    if let Some(max_elapsed) = policy.max_elapsed() {
        if start_time.elapsed() >= max_elapsed {
            return false;
        }
    }
    true
}

/// Send a request with optional retry policy.
///
/// This is the top-level entry point called by [`Client::send`]. It
/// resolves the effective retry policy from the request override and
/// client default, then wraps the redirect loop in a retry loop with
/// exponential backoff.
///
/// Retries restart the complete logical request (including redirects)
/// under the original total deadline. Stream bodies are never retried.
///
/// Retry eligibility is intentionally original-method-scoped: `should_retry`
/// is evaluated with the logical (pre-redirect) method and replayable body,
/// not the post-redirect wire method. A `POST → 301 → GET → 503` therefore
/// does not retry under a `GET`-only policy, because retrying would replay
/// the original non-idempotent `POST`.
/// Send one logical attempt through the inner policy layer.
///
/// When the `redirects` feature is enabled this is the redirect loop;
/// otherwise it is the lean single-hop dispatch. The retry loop itself is
/// unchanged: it restarts the complete logical request under the original
/// total deadline.
async fn dispatch_attempt(client: &Client, request: Request) -> Result<Response> {
    #[cfg(feature = "redirects")]
    {
        Box::pin(super::redirect::send_with_redirects(client, request)).await
    }
    #[cfg(not(feature = "redirects"))]
    {
        Box::pin(super::lean::send_lean(client, request)).await
    }
}

#[allow(
    clippy::too_many_lines,
    reason = "the retry loop keeps the attempt budget checks, the backoff computation and the replayable-body guard in one linear flow"
)]
pub(crate) async fn send_with_retry(client: &Client, request: Request) -> Result<Response> {
    let body_replayable = request.body().is_replayable();

    // Resolve the effective retry policy. Request-level takes precedence.
    let effective_policy = request
        .retry()
        .cloned()
        .or_else(|| client.config().retry.clone());
    let policy = match effective_policy {
        Some(p) if p.is_enabled() => p,
        _ => {
            return dispatch_attempt(client, request).await;
        }
    };

    // If the body is not replayable, we can only attempt once.
    if !body_replayable {
        return dispatch_attempt(client, request).await;
    }

    // Save the complete logical-request state for replay. The typed
    // `retry_request` transformation below reconstructs each attempt from
    // this saved state, so every field (including future additions) is
    // preserved or explicitly transformed rather than copied through a
    // long parameter list.
    let saved = request.into_parts();
    let saved_timeout = saved.timeout;
    let start_time = std::time::Instant::now();
    let mut attempt = 0usize;

    loop {
        attempt += 1;
        if let Some(context) = saved.failure_context.as_deref() {
            context.clear();
        }

        // Check max attempts budget first so the `attempts` field in the
        // error reports the same count regardless of which constraint
        // (max_attempts or max_elapsed) ends the loop. Without this order,
        // a tight `max_elapsed` can return `attempts: 0` for the same
        // logical situation that `max_attempts` would report as
        // `attempts: attempt - 1`.
        if attempt > policy.max_attempts() {
            return Err(Error::RetryBudgetExhausted {
                attempts: attempt - 1,
            });
        }

        // Check total budget before attempting.
        // Snapshot elapsed once so the total-deadline remainder below cannot
        // go to zero between two samples and waste a connection on an
        // attempt that fails immediately on the total deadline.
        let elapsed = start_time.elapsed();
        if let Some(max_elapsed) = policy.max_elapsed() {
            if elapsed >= max_elapsed {
                return Err(Error::RetryBudgetExhausted {
                    attempts: attempt - 1,
                });
            }
        }

        // Enforce the original total deadline across attempts: each attempt
        // receives only the remaining wall-clock budget, mirroring how the
        // redirect loop shrinks per-hop deadlines. Without this, an attempt
        // would restart with the full original `total` and the aggregate
        // elapsed time could reach `max_attempts * total`.
        if let Some(total) = saved_timeout.as_ref().and_then(|t| t.total) {
            if elapsed >= total {
                return Err(Error::Timeout {
                    phase: TimeoutPhase::Total,
                    elapsed,
                });
            }
        }
        let attempt_timeout =
            saved_timeout.map(|t| crate::request::RequestParts::shrink_total_deadline(&t, elapsed));
        // Skip an attempt with no remaining total budget instead of spending
        // a pool slot and TCP connect only to fail on the deadline.
        if attempt_timeout
            .as_ref()
            .and_then(|t| t.total)
            .is_some_and(|remaining| remaining.is_zero())
        {
            return Err(Error::Timeout {
                phase: TimeoutPhase::Total,
                elapsed,
            });
        }

        // Reconstruct the attempt through the single typed transformation.
        let attempt_request = saved.retry_request(attempt_timeout)?;

        let result = dispatch_attempt(client, attempt_request).await;

        match result {
            Ok(response) => {
                if response.status().is_success() {
                    return Ok(response);
                }
                let status = response.status().as_u16();

                if let Some(cause) =
                    should_retry(&policy, &saved.method, &saved.body, None, Some(status))
                {
                    if !has_budget(&policy, attempt, start_time) {
                        return Ok(response);
                    }

                    let mut resp = response;
                    // Capture the header before the body drain consumes it.
                    let retry_after = resp
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .map(str::to_owned);
                    // Bound the drain by the remaining total deadline so a
                    // stalled body cannot block the retry loop past `total`.
                    // Drain errors are intentionally ignored: the body is
                    // being discarded and the request retried regardless.
                    if let Some(total) = saved_timeout.as_ref().and_then(|t| t.total) {
                        let dur = total.saturating_sub(start_time.elapsed());
                        let read = saved_timeout.as_ref().and_then(|t| t.read);
                        let _ =
                            tokio::time::timeout(dur, drain_response_body(&mut resp, read)).await;
                    } else {
                        let read = saved_timeout.as_ref().and_then(|t| t.read);
                        drain_response_body(&mut resp, read).await;
                    }

                    if let Some(dur) =
                        compute_retry_delay(&policy, &cause, attempt, retry_after.as_deref())
                    {
                        let total = saved_timeout.as_ref().and_then(|t| t.total);
                        sleep_if_budget_allows(&policy, dur, attempt, start_time, total).await?;
                    }
                    continue;
                }
                return Ok(response);
            }
            Err(err) => {
                if let Some(cause) =
                    should_retry(&policy, &saved.method, &saved.body, Some(&err), None)
                {
                    if !has_budget(&policy, attempt, start_time) {
                        return Err(err);
                    }

                    // No response is available on the error path; only the
                    // configured backoff applies.
                    if let Some(dur) = compute_retry_delay(&policy, &cause, attempt, None) {
                        let total = saved_timeout.as_ref().and_then(|t| t.total);
                        sleep_if_budget_allows(&policy, dur, attempt, start_time, total).await?;
                    }
                    continue;
                }
                return Err(err);
            }
        }
    }
}

/// Compute the backoff delay for a retry attempt.
///
/// When the failed attempt carried a `Retry-After` response header and
/// the policy respects it, the server-directed delay takes precedence
/// over the configured exponential backoff.
fn compute_retry_delay(
    policy: &RetryPolicy,
    cause: &RetryCause,
    attempt: usize,
    retry_after: Option<&str>,
) -> Option<Duration> {
    if let Some(value) = retry_after {
        if let Some(delay) = policy.retry_after_delay(value) {
            return Some(delay);
        }
    }
    let base = policy.backoff_delay(attempt)?;
    // 429 (Too Many Requests) without a server-directed Retry-After should
    // back off longer than other retryable statuses per conventional policy.
    // Route through the validated cap: the float multiply can otherwise yield
    // a non-finite/oversize value that panics in `from_secs_f64`.
    if matches!(cause, RetryCause::Status(429)) {
        let max = policy.backoff().max_delay();
        let increased = base.as_secs_f64() * 1.5;
        if !increased.is_finite() || increased < 0.0 {
            return Some(max);
        }
        let max_secs = max.as_secs_f64();
        // `max` may be `Duration::MAX`, whose float form rounds up to 2^64
        // (oversize for `from_secs_f64`); saturate instead of panicking.
        // (`BackoffPolicyBuilder` accepts any `Duration`, so `max` was not
        // necessarily validated at construction.)
        let capped = increased.min(max_secs);
        return Some(Duration::try_from_secs_f64(capped.max(0.0)).unwrap_or(max));
    }
    Some(base)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::body::RequestBody;
    use crate::request::{RequestParts, ResolvedTarget, TransportHints};
    use crate::timeout::Timeout;
    use bytes::Bytes;
    use std::sync::Arc;

    fn test_url() -> url::Url {
        url::Url::parse("https://example.com/path").expect("valid test URL")
    }

    fn full_request() -> Request {
        #[cfg(not(feature = "basic-auth"))]
        use crate::auth::AuthScheme;
        #[cfg(feature = "basic-auth")]
        use crate::auth::{AuthScheme, BasicAuth};
        #[cfg(feature = "redirects")]
        use crate::redirect::RedirectPolicy;
        use crate::retry::RetryPolicy;

        let mut req = Request::new(http::Method::POST, test_url());
        req.headers_mut().insert("x-custom", "keep").unwrap();
        req.headers_mut()
            .insert("content-type", "text/plain")
            .unwrap();
        req.set_body(RequestBody::Bytes(Bytes::from("payload")));
        req.set_version(http::Version::HTTP_11);
        req.set_timeout(Some(
            Timeout::builder()
                .pool(Duration::from_secs(1))
                .connect(Duration::from_secs(2))
                .write(Duration::from_secs(3))
                .read(Duration::from_secs(4))
                .total(Duration::from_secs(30))
                .build(),
        ));
        #[cfg(feature = "redirects")]
        req.set_redirect(Some(RedirectPolicy::new(true, 7)));
        #[cfg(feature = "basic-auth")]
        req.set_auth(Some(AuthScheme::Basic(
            BasicAuth::new("user", "pass").expect("valid auth"),
        )));
        #[cfg(not(feature = "basic-auth"))]
        req.set_auth(Some(AuthScheme::bearer("tok").expect("valid auth")));
        req.set_auth_disabled(false);
        req.set_decompress(Some(false));
        req.set_max_decoded_body_size(Some(1024));
        req.set_max_decompression_ratio(Some(12.5));
        #[cfg(feature = "proxy")]
        req.set_proxy_override(crate::request::ProxyOverride::Direct);
        req.set_retry(Some(RetryPolicy::default()));
        req.set_transport_hints(TransportHints {
            target: Some(Bytes::from("/override-target")),
            sni_hostname: Some("sni.example".to_owned()),
            resolved_target: None,
            trace: Some(Arc::new(crate::trace::NoopTraceObserver)),
        });
        req.set_proxied_target(Some(
            ResolvedTarget::new(["192.0.2.10:443".parse().expect("valid address")])
                .expect("non-empty target"),
        ));
        req
    }

    #[test]
    fn into_request_round_trip_preserves_every_field() {
        // Exhaustive round-trip: if a field is added to `RequestParts` but
        // omitted from `into_request`, this test (and compilation) fails.
        let req = full_request();
        let expected_method = req.method().clone();
        let expected_url = req.url().clone();
        let expected_headers = req.headers().clone();
        let expected_version = req.version();
        let expected_timeout = req.timeout().copied();
        #[cfg(feature = "redirects")]
        let expected_redirect = req.redirect().cloned();
        let expected_auth = req.auth().cloned();
        let expected_auth_disabled = req.is_auth_disabled();
        let expected_decompress = req.decompress();
        let expected_max_decoded_body_size = req.max_decoded_body_size();
        let expected_max_decompression_ratio = req.max_decompression_ratio();
        let expected_retry = req.retry().cloned();
        let expected_target = req.transport_hints().target.clone();
        let expected_sni = req.transport_hints().sni_hostname.clone();
        let expected_has_trace = req.transport_hints().trace.is_some();
        let expected_proxied_target = req.proxied_target().cloned();

        let parts = req.into_parts();
        // Touch every field so wildcard destructuring cannot silently pass.
        let RequestParts {
            method: _,
            url: _,
            headers: _,
            body: _,
            version: _,
            timeout: _,
            #[cfg(feature = "redirects")]
                redirect: _,
            auth: _,
            auth_disabled: _,
            decompress: _,
            max_decoded_body_size: _,
            max_decompression_ratio: _,
            proxy_override: _,
            retry: _,
            transport_hints: _,
            proxied_target: _,
            failure_context: _,
        } = &parts;
        let rebuilt = parts.into_request();

        assert_eq!(rebuilt.method(), &expected_method);
        assert_eq!(rebuilt.url(), &expected_url);
        assert_eq!(
            rebuilt.headers().get("x-custom").unwrap().to_str().unwrap(),
            "keep"
        );
        let _ = expected_headers;
        assert_eq!(rebuilt.version(), expected_version);
        match (rebuilt.timeout(), expected_timeout.as_ref()) {
            (None, None) => {}
            (Some(a), Some(b)) => {
                assert_eq!(a.pool, b.pool);
                assert_eq!(a.connect, b.connect);
                assert_eq!(a.write, b.write);
                assert_eq!(a.read, b.read);
                assert_eq!(a.total, b.total);
            }
            (a, b) => panic!("timeout mismatch: {a:?} vs {b:?}"),
        }
        #[cfg(feature = "redirects")]
        assert_eq!(
            rebuilt.redirect().map(|r| (r.follow, r.max_redirects)),
            expected_redirect.map(|r| (r.follow, r.max_redirects))
        );
        assert_eq!(
            rebuilt.auth().map(|a| format!("{a:?}")),
            expected_auth.map(|a| format!("{a:?}"))
        );
        assert_eq!(rebuilt.is_auth_disabled(), expected_auth_disabled);
        assert_eq!(rebuilt.decompress(), expected_decompress);
        assert_eq!(
            rebuilt.max_decoded_body_size(),
            expected_max_decoded_body_size
        );
        assert_eq!(
            rebuilt.max_decompression_ratio(),
            expected_max_decompression_ratio
        );
        #[cfg(feature = "proxy")]
        assert!(matches!(
            rebuilt.proxy_override(),
            crate::request::ProxyOverride::Direct
        ));
        assert_eq!(rebuilt.retry().is_some(), expected_retry.is_some());
        assert_eq!(rebuilt.transport_hints().target, expected_target);
        assert_eq!(rebuilt.transport_hints().sni_hostname, expected_sni);
        assert_eq!(
            rebuilt.transport_hints().trace.is_some(),
            expected_has_trace
        );
        assert_eq!(rebuilt.proxied_target(), expected_proxied_target.as_ref());
        match rebuilt.body() {
            RequestBody::Bytes(b) => assert_eq!(b, "payload"),
            other => panic!("expected bytes body, got {other:?}"),
        }
    }

    #[test]
    fn retry_request_preserves_every_override_and_shrinks_total() {
        let req = full_request();
        let parts = req.into_parts();
        let attempt_timeout = Some(
            Timeout::builder()
                .pool(Duration::from_secs(1))
                .total(Duration::from_secs(25))
                .build(),
        );
        let attempt = parts.retry_request(attempt_timeout).expect("replayable");

        // All request-local configuration survives the retry transformation.
        assert_eq!(attempt.method(), &http::Method::POST);
        assert_eq!(attempt.url().as_str(), "https://example.com/path");
        assert_eq!(
            attempt.headers().get("x-custom").unwrap().to_str().unwrap(),
            "keep"
        );
        assert_eq!(attempt.version(), http::Version::HTTP_11);
        assert_eq!(
            attempt.timeout().and_then(|t| t.total),
            Some(Duration::from_secs(25)),
            "total deadline is replaced by the shrunk attempt budget"
        );
        #[cfg(feature = "redirects")]
        assert!(attempt.redirect().is_some());
        assert!(attempt.auth().is_some());
        assert!(!attempt.is_auth_disabled());
        assert_eq!(attempt.decompress(), Some(false));
        assert_eq!(attempt.max_decoded_body_size(), Some(1024));
        assert_eq!(attempt.max_decompression_ratio(), Some(12.5));
        #[cfg(feature = "proxy")]
        assert!(matches!(
            attempt.proxy_override(),
            crate::request::ProxyOverride::Direct
        ));
        assert!(attempt.retry().is_some());
        assert_eq!(
            attempt.transport_hints().target.as_deref(),
            Some(b"/override-target".as_slice())
        );
        assert_eq!(
            attempt.transport_hints().sni_hostname.as_deref(),
            Some("sni.example")
        );
        assert!(attempt.transport_hints().trace.is_some());
        let expected_proxied_target =
            ResolvedTarget::new(["192.0.2.10:443".parse().expect("valid address")])
                .expect("non-empty target");
        assert_eq!(attempt.proxied_target(), Some(&expected_proxied_target));
        match attempt.body() {
            RequestBody::Bytes(b) => assert_eq!(b, "payload"),
            other => panic!("expected replayed bytes, got {other:?}"),
        }
    }

    #[test]
    fn retry_request_rejects_one_shot_stream() {
        let mut req = Request::new(http::Method::POST, test_url());
        req.set_body(RequestBody::from_stream(
            futures_util::stream::empty::<crate::error::Result<Bytes>>(),
            None,
        ));
        let parts = req.into_parts();
        let err = parts.retry_request(None).unwrap_err();
        assert!(
            matches!(err, Error::BodyNotReplayableForRetry),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn retry_preserves_auth_disabled_state() {
        let mut req = Request::new(http::Method::GET, test_url());
        req.set_auth_disabled(true);
        let parts = req.into_parts();
        let attempt = parts.retry_request(None).expect("empty body replays");
        assert!(attempt.is_auth_disabled());
        assert!(attempt.auth().is_none());
    }

    #[test]
    fn shrink_total_deadline_subtracts_elapsed() {
        let t = Timeout::builder()
            .pool(Duration::from_secs(1))
            .total(Duration::from_secs(10))
            .build();
        let shrunk = RequestParts::shrink_total_deadline(&t, Duration::from_secs(3));
        assert_eq!(shrunk.total, Some(Duration::from_secs(7)));
        assert_eq!(shrunk.pool, Some(Duration::from_secs(1)));

        let saturated = RequestParts::shrink_total_deadline(&t, Duration::from_secs(20));
        assert_eq!(saturated.total, Some(Duration::ZERO));
    }

    #[test]
    fn compute_retry_delay_429_with_max_duration_does_not_panic() {
        use crate::retry::RetryPolicy;
        let policy = RetryPolicy::builder()
            .max_attempts(5)
            .max_delay(Duration::MAX)
            .initial_delay(Duration::from_millis(500))
            .build();
        let d = compute_retry_delay(&policy, &RetryCause::Status(429), 5, None).unwrap();
        assert!(d <= Duration::MAX);
    }
}