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
//! Request pipeline: retry, redirect, preparation, dispatch, finalization.
//!
//! Short orchestration entry points. Each phase has an explicit private
//! owner: `retry` (retry loop, backoff, discard drain), `redirect`
//! (redirect state, hop transformation, first-hop assembly), `prepare`
//! (request normalization, pool acquisition), `route` (precedence),
//! `hyper_dispatch` (ordinary H1/H2 routes), `proxy_dispatch` (proxy
//! routes), `h3_dispatch` (experimental H3 discovery/fallback), and
//! `finalize` (common post-transport policy). This module wires those phases
//! together and keeps the narrower native frame-execution semantics explicit.

#[cfg(feature = "advanced-routing")]
mod custom_dialing;
#[cfg(feature = "high-level-url")]
mod finalize;
#[cfg(feature = "http3")]
mod h3_dispatch;
#[cfg(feature = "high-level-url")]
mod hop;
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
mod hyper_dispatch;
#[cfg(all(feature = "high-level-url", not(feature = "redirects")))]
mod lean;
mod prepare;
#[cfg(feature = "proxy")]
mod proxy_dispatch;
#[cfg(all(feature = "high-level-url", feature = "redirects"))]
mod redirect;
#[cfg(all(feature = "high-level-url", feature = "logical-retry"))]
mod retry;
mod route;

// Preserve the pre-decomposition `crate::pipeline::X` paths used outside
// this module tree. `validate_target` is consumed by the proxy transport
// modules, so its re-export follows the same feature gate.
#[cfg(feature = "proxy")]
pub(crate) use prepare::validate_target;
#[cfg(all(feature = "high-level-url", feature = "logical-retry"))]
pub(crate) use retry::send_with_retry;
// Re-exported for `Client::{send, send_detailed}` only when the retry loop
// is absent; the retry loop itself reaches the redirect/lean modules via
// `super::` paths.
#[cfg(all(
    feature = "high-level-url",
    not(feature = "redirects"),
    not(feature = "logical-retry")
))]
pub(crate) use lean::send_lean;
#[cfg(all(
    feature = "high-level-url",
    feature = "redirects",
    not(feature = "logical-retry")
))]
pub(crate) use redirect::send_with_redirects;
// `apply_content_length` is exercised directly by `client.rs` unit tests
// through the pre-decomposition path; preparation itself uses it in-file.
#[cfg(test)]
pub(crate) use prepare::apply_content_length;

use std::time::Duration;

#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
use bytes::Bytes;

use crate::body::{NativeRequestBody, NativeResponseBody};
use crate::client::ClientInner;
use crate::error::{Error, Result};
#[cfg(feature = "high-level-url")]
use crate::request::Request;
#[cfg(feature = "high-level-url")]
use crate::response::Response;
use crate::timeout::Timeout;
use crate::transport_hints::NativeRequestOptions;

/// Bound a complete transport future only by an explicitly configured native
/// total deadline. Direct Hyper/UDS/H3 transports do not expose a clean
/// response-header boundary here, so their read budget is applied by the
/// response-body stream after transport setup has completed.
///
/// Shared by every dispatch route; the current request's shrinking total
/// budget remains authoritative here and is never stored in the reusable
/// route caches.
async fn send_with_total_timeout<F, T>(
    send_future: F,
    remaining_total: Option<Duration>,
) -> Result<T>
where
    F: std::future::Future<Output = Result<T>>,
{
    use crate::timeout::TimeoutPhase;

    match remaining_total {
        Some(duration) => {
            let started = std::time::Instant::now();
            tokio::time::timeout(duration, send_future)
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::Total,
                    elapsed: started.elapsed(),
                })?
        }
        None => send_future.await,
    }
}

/// Upper bound on how much of a discarded response body is drained so
/// the underlying connection can be returned to the pool. Bodies larger
/// than this are abandoned (the connection closes instead), matching
/// common client practice (e.g. Go's `net/http` 256 KiB drain cap) and
/// guaranteeing retry/redirect processing cannot be stalled indefinitely
/// by a slow-dripping server when no read timeout is configured.
#[cfg(all(
    feature = "high-level-url",
    any(feature = "logical-retry", feature = "redirects")
))]
const DRAIN_MAX_BYTES: usize = 256 * 1024;

/// Upper bound on how long a best-effort drain may run when no explicit
/// total deadline governs it. Without this, a slow-drip server could
/// stall retry/redirect processing indefinitely even though only a
/// bounded number of bytes would ever be drained.
#[cfg(all(
    feature = "high-level-url",
    any(feature = "logical-retry", feature = "redirects")
))]
const DRAIN_MAX_TIME: Duration = Duration::from_secs(30);

/// Best-effort drain of a discarded response body.
///
/// Uses the raw (encoded) byte stream so a zip-bomb response does not
/// abort the drain via `DecompressionRatioExceeded` and abandon the
/// connection. Drain errors are ignored; draining stops after
/// [`DRAIN_MAX_BYTES`] or [`DRAIN_MAX_TIME`].
///
/// Shared by the retry loop and the redirect loop; both discard a response
/// body before the next attempt/hop.
#[cfg(all(
    feature = "high-level-url",
    any(feature = "logical-retry", feature = "redirects")
))]
pub(super) async fn drain_response_body(response: &mut Response, read_timeout: Option<Duration>) {
    let Ok(stream) = response.raw_bytes_stream() else {
        return; // body already consumed; nothing to drain
    };
    let mut remaining = DRAIN_MAX_BYTES;
    let mut stream = std::pin::pin!(stream);
    // Cap the best-effort drain by the read budget when one is set so a
    // slow-drip body cannot stall retry/redirect for the full
    // `DRAIN_MAX_TIME` when the caller only tolerates a shorter read.
    let cap = read_timeout.map_or(DRAIN_MAX_TIME, |read| read.min(DRAIN_MAX_TIME));
    let drain = async {
        while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
            match chunk {
                Ok(bytes) => {
                    if bytes.len() >= remaining {
                        break;
                    }
                    remaining -= bytes.len();
                }
                Err(_) => break,
            }
        }
    };
    let _ = tokio::time::timeout(cap, drain).await;
}

/// Send a single HTTP request and return the streaming response.
///
/// This handles pool acquisition, timeout application, and body
/// processing for one request/response cycle. It does NOT handle
/// redirects—that is the responsibility of the redirect loop.
///
/// The implementation separates a preparation phase
/// (`prepare::prepare_single_request`) from declarative transport selection
/// (`route::select_route`); one common post-transport policy
/// (`finalize::finalize_response`: decompression, decoded-size limiting,
/// read-timeout and pool-lease attachment) applies to every route.
#[allow(
    clippy::too_many_lines,
    reason = "the body is the prepare, route-select and finalize sequence for one request, and the order of those three phases is the behaviour"
)]
#[cfg(all(
    any(feature = "transport-http1", feature = "transport-http2"),
    feature = "high-level-url"
))]
pub(crate) async fn send_single_request(
    inner: &ClientInner,
    request: Request,
    timeout: &Timeout,
) -> Result<Response> {
    let (prepared, guard) = prepare::prepare_single_request(inner, request, timeout).await?;
    let prepare::PreparedRequest {
        method,
        url,
        uri,
        headers,
        body,
        version,
        transport_hints,
        proxied_target,
        #[cfg(feature = "proxy")]
        effective_proxy,
        decompression_enabled,
        max_decoded_body_size,
        max_decompression_ratio,
        timeout: hop_timeout,
        remaining_total,
        deadline,
        failure_context,
    } = prepared;

    // `deadline` feeds the proxy multi-phase context; without the `proxy`
    // feature no route consumes it.
    #[cfg(not(feature = "proxy"))]
    let _ = &deadline;
    #[cfg(not(feature = "proxy"))]
    let _ = &proxied_target;

    #[cfg(all(unix, feature = "advanced-routing"))]
    let has_uds = inner.uds_client.is_some();
    #[cfg(all(unix, not(feature = "advanced-routing")))]
    let has_uds = false;
    #[cfg(not(unix))]
    let has_uds = false;
    #[cfg(feature = "proxy")]
    let has_proxy = effective_proxy.is_some();
    #[cfg(not(feature = "proxy"))]
    let has_proxy = false;
    // Advanced-route availability: in lean standard-route profiles the
    // corresponding client state does not exist; advanced hints fail closed
    // below instead of selecting an absent route.
    #[cfg(all(feature = "proxy", feature = "advanced-routing"))]
    let has_direct_no_proxy = !has_proxy
        && (transport_hints.resolved_target.is_some() || inner.direct_client.is_some())
        && !has_uds;
    #[cfg(all(feature = "proxy", not(feature = "advanced-routing")))]
    let has_direct_no_proxy = false;
    #[cfg(all(not(feature = "proxy"), feature = "advanced-routing"))]
    let has_direct_no_proxy =
        !has_uds && (transport_hints.resolved_target.is_some() || inner.direct_client.is_some());
    #[cfg(all(not(feature = "proxy"), not(feature = "advanced-routing")))]
    let has_direct_no_proxy = false;
    #[cfg(feature = "advanced-routing")]
    let has_sni = transport_hints.sni_hostname.is_some();
    #[cfg(not(feature = "advanced-routing"))]
    let has_sni = false;
    #[cfg(feature = "advanced-routing")]
    let has_custom = inner.config.dialer.is_some();
    #[cfg(not(feature = "advanced-routing"))]
    let has_custom = false;
    #[cfg(not(feature = "advanced-routing"))]
    {
        if transport_hints.resolved_target.is_some() {
            return Err(Error::Unsupported(
                "caller-supplied resolved destinations require the advanced-routing feature".into(),
            ));
        }
        if transport_hints.sni_hostname.is_some() {
            return Err(Error::Unsupported(
                "SNI override requires the advanced-routing feature".into(),
            ));
        }
    }
    #[cfg(all(feature = "advanced-routing", feature = "proxy"))]
    if has_custom {
        let arms = custom_dialing::CustomDialingState {
            has_resolved_target: transport_hints.resolved_target.is_some(),
            has_local_address_or_socket_options: inner.direct_connector_config.is_some(),
            has_uds: inner.config.uds_configured,
            #[cfg(feature = "http3")]
            is_http3_only: matches!(
                inner.config.http_version_policy,
                crate::HttpVersionPolicy::Http3Only
            ),
            #[cfg(not(feature = "http3"))]
            is_http3_only: false,
            // The built-in-proxy arm is evaluated here, at the dispatch
            // boundary, so it stays last in the ladder: the preparation phase
            // already rejected the other arms before the pool was acquired.
            has_built_in_proxy: Some(has_proxy),
        };
        if let Some(conflict) = custom_dialing::custom_dialing_conflict(arms) {
            return Err(conflict.error());
        }
    }
    #[cfg(feature = "http3")]
    let (use_h3, h3_alt) =
        h3_dispatch::decide_h3_use(inner, &url, has_uds, has_proxy, has_sni, has_custom);
    #[cfg(not(feature = "http3"))]
    let use_h3 = false;
    let route = route::select_route(
        has_uds,
        has_custom,
        has_direct_no_proxy,
        has_proxy,
        has_sni,
        use_h3,
    );
    #[cfg(feature = "http3")]
    if transport_hints.resolved_target.is_some() && use_h3 {
        return Err(Error::Unsupported(
            "caller-supplied resolved destinations are incompatible with HTTP/3".into(),
        ));
    }
    #[cfg(feature = "http3")]
    if use_h3 {
        inner.transport_metrics.record_h3_attempted();
    }

    // Declarative transport dispatch. Precedence is encoded in
    // `route::select_route` and covered by direct unit tests; H3 never bypasses
    // proxy rules because proxy routes are selected first.
    let response = match route {
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Uds => {
            hyper_dispatch::send_uds_route(
                inner,
                method,
                uri,
                headers,
                body,
                version,
                url,
                &transport_hints,
                remaining_total,
                hop_timeout.read,
            )
            .await?
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Custom => {
            hyper_dispatch::send_custom_route(
                inner,
                method,
                uri,
                headers,
                body,
                version,
                url,
                &transport_hints,
                failure_context.as_deref(),
                remaining_total,
                hop_timeout.read,
            )
            .await?
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Direct => {
            hyper_dispatch::send_direct_route(
                inner,
                method,
                uri,
                headers,
                body,
                version,
                url,
                &transport_hints,
                failure_context.as_deref(),
                remaining_total,
                hop_timeout.read,
            )
            .await?
        }
        route::TransportRoute::Proxy => {
            #[cfg(feature = "proxy")]
            {
                proxy_dispatch::send_proxy_route(
                    inner,
                    &method,
                    &url,
                    headers,
                    body,
                    version,
                    effective_proxy.as_ref(),
                    &transport_hints,
                    proxied_target.as_ref(),
                    hop_timeout,
                    remaining_total,
                    deadline,
                    failure_context.as_deref(),
                )
                .await?
            }
            #[cfg(not(feature = "proxy"))]
            {
                let _ = (method, uri, headers, body, version);
                return Err(Error::Unsupported("proxy support is not enabled".into()));
            }
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::SniDirect => {
            hyper_dispatch::send_sni_route(
                inner,
                method,
                uri,
                headers,
                body,
                version,
                url,
                &transport_hints,
                failure_context.as_deref(),
                remaining_total,
                hop_timeout.read,
            )
            .await?
        }
        route::TransportRoute::H3 => {
            #[cfg(feature = "http3")]
            {
                h3_dispatch::send_h3_route(
                    inner,
                    &method,
                    &url,
                    &headers,
                    body,
                    version,
                    uri,
                    h3_alt,
                    hop_timeout,
                    remaining_total,
                    &transport_hints,
                    failure_context.as_deref(),
                )
                .await?
            }
            #[cfg(not(feature = "http3"))]
            {
                let _ = (method, uri, headers, body, version);
                return Err(Error::Unsupported("HTTP/3 support is not enabled".into()));
            }
        }
        route::TransportRoute::Standard => {
            hyper_dispatch::send_hyper_request(
                inner,
                method,
                url,
                headers,
                body,
                version,
                remaining_total,
                &transport_hints,
                failure_context.as_deref(),
                hop_timeout.read,
            )
            .await?
        }
    };

    #[cfg(feature = "proxy")]
    let via_proxy = effective_proxy.is_some();
    #[cfg(not(feature = "proxy"))]
    let via_proxy = false;

    // Carry the final hop/attempt's absolute deadline into the returned
    // body rather than assigning a fresh total after headers: retry and
    // redirect loops already shrank `hop_timeout.total`, so this deadline
    // is the remaining original logical budget.
    let total_deadline = match (deadline, hop_timeout.total) {
        (Some(deadline), Some(total)) => {
            Some(crate::timeout::ResponseDeadline::new(deadline, total))
        }
        _ => None,
    };
    finalize::finalize_response(
        inner,
        response,
        route,
        via_proxy,
        decompression_enabled,
        max_decoded_body_size,
        max_decompression_ratio,
        guard,
        hop_timeout.read,
        total_deadline,
    )
}

/// Execute a caller-owned `http_body::Body` through eggfetch's transport
/// engine without applying high-level request policy.
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[allow(
    clippy::too_many_lines,
    reason = "native dispatch keeps route validation, pool admission, and the shared route matrix together"
)]
pub(crate) async fn send_native_http_body<B>(
    inner: &ClientInner,
    request: http::Request<B>,
    options: NativeRequestOptions,
) -> Result<http::Response<NativeResponseBody>>
where
    B: http_body::Body<Data = Bytes> + Send + 'static,
    B::Error: std::error::Error + Send + Sync + 'static,
{
    use http_body_util::BodyExt;

    use crate::headers::Headers;
    use crate::http_origin::HttpOrigin;
    use crate::pool::OriginKey;
    use crate::timeout::TimeoutPhase;

    // Native transport facts come directly from `http::Uri`; never reparse
    // through `url::Url`.
    let http_origin = HttpOrigin::from_uri(request.uri())?;
    #[cfg(feature = "proxy")]
    let explicit_port = request.uri().port_u16();

    let NativeRequestOptions {
        timeout: request_timeout,
        transport_hints,
    } = options;
    let timeout = match inner.config.timeout {
        Some(client_timeout) => client_timeout.merge(request_timeout),
        None => request_timeout.unwrap_or_default(),
    };

    if let Some(target) = &transport_hints.resolved_target {
        crate::http_origin::validate_effective_port(
            crate::http_origin::EffectivePortSubject::ResolvedDestination,
            target.addresses(),
            http_origin.port_ref(),
        )?;
    }

    #[cfg(feature = "proxy")]
    if prepare::native_would_use_proxy(inner, &http_origin, explicit_port) {
        return Err(Error::Unsupported(
            "native frame bodies are not supported through the built-in proxy routes".into(),
        ));
    }

    #[cfg(feature = "advanced-routing")]
    if inner.config.dialer.is_some() {
        let arms = custom_dialing::CustomDialingState {
            has_resolved_target: transport_hints.resolved_target.is_some(),
            has_local_address_or_socket_options: inner.direct_connector_config.is_some(),
            has_uds: inner.config.uds_configured,
            #[cfg(feature = "http3")]
            is_http3_only: matches!(
                inner.config.http_version_policy,
                crate::HttpVersionPolicy::Http3Only
            ),
            #[cfg(not(feature = "http3"))]
            is_http3_only: false,
            // The native dispatch path has no built-in-proxy arm: native
            // proxy frames are rejected above with their own diagnostic.
            has_built_in_proxy: None,
        };
        if let Some(conflict) = custom_dialing::custom_dialing_conflict(arms) {
            return Err(conflict.error());
        }
    }
    #[cfg(not(feature = "advanced-routing"))]
    {
        if transport_hints.resolved_target.is_some() {
            return Err(Error::Unsupported(
                "caller-supplied resolved destinations require the advanced-routing feature".into(),
            ));
        }
        if transport_hints.sni_hostname.is_some() {
            return Err(Error::Unsupported(
                "SNI override requires the advanced-routing feature".into(),
            ));
        }
    }

    #[cfg(feature = "http3")]
    if matches!(
        inner.config.http_version_policy,
        crate::HttpVersionPolicy::Http3Only
    ) {
        return Err(Error::Unsupported(
            "native frame bodies are not supported by the experimental HTTP/3 route".into(),
        ));
    }

    #[cfg(feature = "tls-rustls")]
    if http_origin.is_https() {
        if let Some(error) = &inner.tls_config_error {
            return Err(Error::Tls(error.clone()));
        }
    }

    // Every validation above only borrowed request metadata. Once those
    // checks have completed, decompose the caller-owned request so the
    // method, URI, version, and HeaderMap move into the selected transport
    // route together with the body.
    let (request_parts, request_body) = request.into_parts();
    let uri = prepare::resolve_native_request_uri(request_parts.uri, &transport_hints)?;
    let method = request_parts.method;
    let version = request_parts.version;
    let headers = Headers::from(request_parts.headers);
    let body = BodyExt::map_err(request_body, |error| {
        Box::new(error) as Box<dyn std::error::Error + Send + Sync>
    })
    .boxed_unsync();
    let body = NativeRequestBody::new(Box::pin(body), timeout.write).boxed_unsync();

    let origin_key = inner
        .pool
        .needs_origin_key()
        .then(|| OriginKey::from_origin(&http_origin));
    let started = std::time::Instant::now();
    // Total wins ties (matching the body-deadline boundary).
    let pool_deadline = match (timeout.pool, timeout.total) {
        (Some(pool), Some(total)) if total <= pool => Some((total, TimeoutPhase::Total)),
        (Some(pool), _) => Some((pool, TimeoutPhase::Pool)),
        (None, Some(total)) => Some((total, TimeoutPhase::Total)),
        (None, None) => None,
    };
    let guard = match pool_deadline {
        Some((duration, phase)) => {
            match tokio::time::timeout(duration, inner.pool.acquire(origin_key.as_ref())).await {
                Ok(guard) => guard?,
                Err(_) => {
                    return Err(Error::Timeout {
                        phase,
                        elapsed: started.elapsed(),
                    })
                }
            }
        }
        None => inner.pool.acquire(origin_key.as_ref()).await?,
    };

    let remaining_total = timeout
        .total
        .map(|total| total.saturating_sub(started.elapsed()));
    // Skip dispatch with no remaining total budget instead of spending a pool
    // slot and TCP connect only to fail on the deadline.
    if remaining_total.is_some_and(|remaining| remaining.is_zero()) {
        return Err(Error::Timeout {
            phase: crate::timeout::TimeoutPhase::Total,
            elapsed: started.elapsed(),
        });
    }
    // Absolute native total deadline starts with the request lifecycle
    // (pool admission), not the first frame poll, and never resets on DATA
    // or trailer frames.
    let total_deadline = timeout.total.map(|total| {
        crate::timeout::ResponseDeadline::new(
            crate::timeout::saturating_add_instant(started, total),
            total,
        )
    });
    let trace = transport_hints.trace.as_deref();
    #[cfg(all(unix, feature = "advanced-routing"))]
    let has_uds = inner.uds_client.is_some();
    #[cfg(any(not(unix), not(feature = "advanced-routing")))]
    let has_uds = false;
    #[cfg(feature = "advanced-routing")]
    let (has_dialer, has_direct) = (
        inner.config.dialer.is_some(),
        transport_hints.resolved_target.is_some() || inner.direct_client.is_some(),
    );
    #[cfg(not(feature = "advanced-routing"))]
    let (has_dialer, has_direct) = (false, false);
    #[cfg(feature = "advanced-routing")]
    let has_sni = transport_hints.sni_hostname.is_some();
    #[cfg(not(feature = "advanced-routing"))]
    let has_sni = false;
    let route = route::select_route(has_uds, has_dialer, has_direct, false, has_sni, false);

    let raw_response = match route {
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Uds => {
            #[cfg(unix)]
            {
                let uds_client = inner
                    .uds_client
                    .as_ref()
                    .ok_or_else(|| Error::Unsupported("UDS client not available".into()))?;
                let hyper_request = hyper_dispatch::build_http_request_owned(
                    method,
                    uri,
                    version,
                    headers,
                    crate::transport::HyperRequestBody::new(body),
                )?;
                send_with_total_timeout(
                    crate::transport::direct::send_raw_request(
                        uds_client,
                        hyper_request,
                        trace,
                        timeout.read,
                        remaining_total,
                    ),
                    remaining_total,
                )
                .await?
            }
            #[cfg(not(unix))]
            {
                let _ = (method, uri, headers, body, version);
                return Err(Error::Unsupported(
                    "Unix domain sockets are not supported on this platform".into(),
                ));
            }
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Custom => {
            let custom_client = if let Some(sni_hostname) = transport_hints.sni_hostname.as_deref()
            {
                inner.sni_custom_client(sni_hostname).await?
            } else {
                inner
                    .custom_client
                    .as_ref()
                    .ok_or_else(|| Error::Unsupported("custom dialer client not available".into()))?
                    .clone()
            };
            let hyper_request = hyper_dispatch::build_http_request_owned(
                method,
                uri,
                version,
                headers,
                crate::transport::HyperRequestBody::new(body),
            )?;
            send_with_total_timeout(
                crate::transport::direct::send_raw_request(
                    &custom_client,
                    hyper_request,
                    trace,
                    timeout.read,
                    remaining_total,
                ),
                remaining_total,
            )
            .await?
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::Direct => {
            let resolved_client;
            let direct_client = if let Some(target) = transport_hints.resolved_target.as_ref() {
                resolved_client = inner
                    .resolved_client(
                        &http_origin,
                        target,
                        transport_hints.sni_hostname.as_deref(),
                    )
                    .await?;
                &resolved_client
            } else {
                inner
                    .direct_client
                    .as_ref()
                    .ok_or_else(|| Error::Unsupported("direct client not available".into()))?
            };
            let hyper_request = hyper_dispatch::build_http_request_owned(
                method,
                uri,
                version,
                headers,
                crate::transport::HyperRequestBody::new(body),
            )?;
            send_with_total_timeout(
                crate::transport::direct::send_raw_request(
                    direct_client,
                    hyper_request,
                    trace,
                    timeout.read,
                    remaining_total,
                ),
                remaining_total,
            )
            .await?
        }
        #[cfg(feature = "advanced-routing")]
        route::TransportRoute::SniDirect => {
            let sni_hostname = transport_hints.sni_hostname.as_deref().ok_or_else(|| {
                Error::RequestBuild("SNI route selected without sni_hostname".into())
            })?;
            let sni_client = inner.sni_client(sni_hostname).await?;
            let hyper_request = hyper_dispatch::build_http_request_owned(
                method,
                uri,
                version,
                headers,
                crate::transport::HyperRequestBody::new(body),
            )?;
            send_with_total_timeout(
                crate::transport::direct::send_raw_request(
                    &sni_client,
                    hyper_request,
                    trace,
                    timeout.read,
                    remaining_total,
                ),
                remaining_total,
            )
            .await?
        }
        route::TransportRoute::Standard => {
            let hyper_client = inner.hyper_client.as_ref().ok_or_else(|| {
                crate::http_version::missing_client_error(inner.config.http_version_policy)
            })?;
            let hyper_request = hyper_dispatch::build_http_request_owned(
                method,
                uri,
                version,
                headers,
                crate::transport::HyperRequestBody::new(body),
            )?;
            send_with_total_timeout(
                crate::transport::direct::send_raw_request(
                    hyper_client,
                    hyper_request,
                    trace,
                    timeout.read,
                    remaining_total,
                ),
                remaining_total,
            )
            .await?
        }
        route::TransportRoute::Proxy | route::TransportRoute::H3 => {
            return Err(Error::Unsupported(
                "native frame body route is not available".into(),
            ));
        }
    };

    if raw_response.status() == http::StatusCode::SWITCHING_PROTOCOLS {
        return Err(Error::Unsupported(
            "native frame bodies do not expose protocol upgrades; use the high-level upgrade API"
                .into(),
        ));
    }

    let (parts, incoming) = raw_response.into_parts();
    let lease = guard
        .has_response_state()
        .then(|| std::sync::Arc::new(guard));
    let native_body =
        NativeResponseBody::from_incoming(incoming, lease, timeout.read, total_deadline);
    Ok(http::Response::from_parts(parts, native_body))
}

/// Report that no HTTP protocol feature was selected for native bodies.
#[cfg(not(any(feature = "transport-http1", feature = "transport-http2")))]
pub(crate) async fn send_native_http_body<B>(
    _inner: &ClientInner,
    _request: http::Request<B>,
    _options: NativeRequestOptions,
) -> Result<http::Response<NativeResponseBody>> {
    Err(Error::Unsupported(
        "no HTTP protocol feature is enabled; enable http1 or http2".into(),
    ))
}

/// Report that no HTTP protocol feature was selected.
#[cfg(all(
    not(any(feature = "transport-http1", feature = "transport-http2")),
    feature = "high-level-url"
))]
pub(crate) async fn send_single_request(
    _inner: &ClientInner,
    _request: Request,
    _timeout: &Timeout,
) -> Result<Response> {
    Err(Error::Unsupported(
        "no HTTP protocol feature is enabled; enable http1 or http2".into(),
    ))
}

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

    #[tokio::test]
    async fn total_timeout_wraps_transport_future() {
        // No budget: the inner future passes through unchanged.
        let ok = send_with_total_timeout(async { Ok::<u32, Error>(7) }, None)
            .await
            .expect("passthrough");
        assert_eq!(ok, 7);

        // Expired budget: the outer Total deadline wins without running long.
        let err = send_with_total_timeout(
            async {
                tokio::time::sleep(Duration::from_secs(5)).await;
                Ok::<u32, Error>(7)
            },
            Some(Duration::from_millis(20)),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, Error::Timeout { .. }),
            "expected total timeout, got {err:?}"
        );
    }
}