Skip to main content

rama/http/client/
builder.rs

1use rama_core::{error::extra::OpaqueError, graceful::WeakScope, layer::MapInput};
2
3use super::{
4    HttpConnectRequestAdapter, HttpConnector, HttpPooledConnector, HttpPooledConnectorConfig,
5};
6use crate::{
7    Layer, Service,
8    dns::client::{
9        DnsConnector, DnsConnectorLayer, GlobalDnsResolver,
10        resolver::{DnsAddressResolver, DnsResolver},
11    },
12    error::{BoxError, BoxErrorExt as _},
13    extensions::ExtensionsRef,
14    http::{
15        Body as ResponseBody, Request, Response, StreamingBody,
16        client::proxy::HttpTunnelRoute,
17        client::proxy_connector::{
18            DefaultProxyConnectMethod, DefaultProxyConnectUdpMethod, DefaultProxyForwardMethod,
19            DefaultProxySocksMethod, MaybeForwardedConnection, MaybeForwardedConnector,
20            NoProxyConnection, ProxyConnector, ProxyConnectorParts, ProxyMethodNotEnabled,
21            ProxyStreamConnector,
22        },
23        layer::version_adapter::RequestVersionAdapter,
24    },
25    net::client::{
26        ConnectRequest, ConnectionError, ConnectionErrorKind, ConnectorService,
27        DirectOnlyConnector, EstablishedClientConnection, MapEstablishedConnection, MaybeProxied,
28        MaybeProxiedConnector, ProxyRouteFailureCache, ProxyRouteFailureCacheConnector,
29        ProxyRoutesConnector, pool::PooledConnector,
30    },
31    service::BoxService,
32    tcp::client::service::TcpConnector,
33};
34use rama_http::layer::{
35    alt_svc::{AltSvc, AltSvcCache, AltSvcLayer},
36    http_service::HttpServiceConnector,
37    retry::{
38        ManagedPolicy, Retry, RetryBody, RetryError,
39        early_data::{is_early_data_rejected, permit_attempt, with_recovery},
40        managed::{PrepareBody, RetryRule},
41    },
42};
43use rama_net::http::{TargetHttpVersion, Version};
44use rama_utils::macros::generate_set_and_with;
45#[cfg(any(feature = "boring", all(feature = "quic", feature = "rustls")))]
46use std::sync::Arc;
47use std::time::Duration;
48
49#[cfg(feature = "boring")]
50use crate::tls::boring::client as boring_client;
51
52#[cfg(all(feature = "boring", feature = "quic"))]
53use crate::quic::tls::BoringTlsProvider;
54#[cfg(all(feature = "rustls", feature = "quic"))]
55use crate::quic::tls::default_tls_provider;
56#[cfg(feature = "rustls")]
57use crate::tls::rustls::client as rustls_client;
58#[cfg(any(feature = "rustls", feature = "boring"))]
59use {
60    crate::http::conn::FallbackHttpVersion, rama_core::layer::AddInputExtension,
61    rama_tls::client::TlsClientConfig,
62};
63#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
64use {
65    crate::{
66        extensions::Extensions,
67        futures::future::{self, BoxFuture},
68        net::{client::pool::ReuseKey, tls::ServerName},
69        quic::{
70            ClientConfig,
71            tls::{ClientConfigRequest, QuicClientConfigProvider, TlsConfigError, TlsOptions},
72        },
73    },
74    rama_crypto::pki_types::CertificateDer,
75    rama_tls::client::{TlsClientConfigProvider, TlsPoolId},
76};
77
78#[cfg(feature = "quic")]
79use crate::{
80    dns::client::resolver::BoxDnsResolver,
81    http::layer::https_service::{HttpsService, HttpsServiceLayer},
82};
83
84#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
85use crate::{
86    http::core::h3::connection::Config as Http3Config,
87    quic::{
88        TransportConfig,
89        client::{ClientEndpoint, SharedQuicEndpoint},
90    },
91};
92#[cfg(all(
93    feature = "masque",
94    feature = "quic",
95    any(feature = "boring", feature = "rustls")
96))]
97use crate::{net::client::ProxiedRoute, quic::client::QuicEndpointConnector};
98
99/// Builder that is designed to easily create a connector for [`super::EasyHttpWebClient`] from most basic use cases
100pub struct EasyHttpConnectorBuilder<C = (), S = (), D = (), F = ProxyMethodNotEnabled> {
101    connector: C,
102    stage: S,
103    dns: D,
104    discovery: HttpsDiscovery,
105    forward: F,
106    scope: WeakScope,
107    target_version: Option<Version>,
108}
109
110#[derive(Debug, Clone)]
111pub(super) struct HttpsDiscovery {
112    #[cfg(feature = "quic")]
113    pub(super) layer: HttpsServiceLayer<BoxDnsResolver>,
114}
115
116impl Default for HttpsDiscovery {
117    fn default() -> Self {
118        Self {
119            #[cfg(feature = "quic")]
120            layer: HttpsServiceLayer::new()
121                .with_resolver(BoxDnsResolver::new(GlobalDnsResolver::new())),
122        }
123    }
124}
125
126#[cfg(any(feature = "boring", feature = "rustls"))]
127impl HttpsDiscovery {
128    pub(super) fn with_tls(self, config: &TlsClientConfig, capable: bool) -> Self {
129        #[cfg(feature = "quic")]
130        {
131            Self {
132                layer: self
133                    .layer
134                    .with_tls(config.clone())
135                    .with_ech_capable(capable),
136            }
137        }
138        #[cfg(not(feature = "quic"))]
139        {
140            let _ = (config, capable);
141            self
142        }
143    }
144}
145
146/// The QUIC leg of a builder stage: the endpoints HTTP/3 runs on, and the HTTP/3
147/// configuration of the built-in connector over them. `()` is no QUIC leg, and so no
148/// HTTP/3.
149#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
150#[derive(Debug, Clone)]
151pub struct QuicLeg<E> {
152    pub(super) endpoints: E,
153    config: Option<Http3Config>,
154    pub(super) transport: Option<TransportConfig>,
155}
156
157#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
158impl<E> QuicLeg<E> {
159    pub(super) fn new(endpoints: E) -> Self {
160        Self {
161            endpoints,
162            config: None,
163            transport: None,
164        }
165    }
166}
167
168#[non_exhaustive]
169#[derive(Debug, Default)]
170pub struct TransportStage<Q = ()> {
171    pub(super) quic: Q,
172}
173
174#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
175impl<T, E, F> EasyHttpConnectorBuilder<T, TransportStage<QuicLeg<E>>, (), F> {
176    /// Configure the QUIC transport of the connections the QUIC leg dials, such as a
177    /// larger initial MTU; HTTP/3 limits are applied on top. A request's `QuicProfile`
178    /// replaces it.
179    #[must_use]
180    pub fn with_quic_transport_config(mut self, transport: TransportConfig) -> Self {
181        self.stage.quic.transport = Some(transport);
182        self
183    }
184}
185
186#[non_exhaustive]
187#[derive(Debug, Default)]
188pub struct DnsStage<Q = ()> {
189    pub(super) quic: Q,
190}
191
192#[non_exhaustive]
193#[derive(Debug, Default)]
194pub struct ProxyStage<const PROXY: bool = true, Q = ()> {
195    quic: Q,
196}
197
198#[non_exhaustive]
199#[derive(Debug, Default)]
200pub struct TlsStage<const PROXY: bool = true, Tls = (), Q = ()> {
201    #[cfg_attr(
202        not(any(feature = "boring", feature = "rustls")),
203        expect(
204            dead_code,
205            reason = "only a TLS backend reads it, for HTTPS discovery and HTTP/3"
206        )
207    )]
208    pub(super) tls: Tls,
209    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
210    pub(super) quic_tls: Option<Arc<dyn QuicClientConfigProvider>>,
211    #[cfg_attr(
212        not(all(feature = "quic", any(feature = "boring", feature = "rustls"))),
213        expect(
214            dead_code,
215            reason = "only a build with a QUIC TLS backend hands the QUIC leg on to HTTP/3"
216        )
217    )]
218    pub(super) quic: Q,
219}
220
221#[cfg(any(feature = "boring", feature = "rustls"))]
222impl<const PROXY: bool, Q> TlsStage<PROXY, TlsClientConfig, Q> {
223    #[cfg(feature = "boring")]
224    pub(super) fn using_boring(tls: TlsClientConfig, quic: Q) -> Self {
225        Self {
226            tls,
227            #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
228            quic_tls: Some(Arc::new(BoringTlsProvider::new())),
229            quic,
230        }
231    }
232
233    #[cfg(feature = "rustls")]
234    pub(super) fn using_rustls(tls: TlsClientConfig, quic: Q) -> Self {
235        Self {
236            tls,
237            #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
238            quic_tls: default_tls_provider().ok(),
239            quic,
240        }
241    }
242}
243
244impl<const PROXY: bool, Q> TlsStage<PROXY, (), Q> {
245    pub(super) fn without_tls(quic: Q) -> Self {
246        Self {
247            tls: (),
248            #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
249            quic_tls: None,
250            quic,
251        }
252    }
253}
254
255/// The QUIC TLS provider of a TLS stage which has none: every HTTP/3 dial fails with
256/// [`TlsConfigError::BackendUnavailable`].
257#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
258pub(crate) fn quic_tls_provider_or_unavailable(
259    provider: Option<Arc<dyn QuicClientConfigProvider>>,
260) -> Arc<dyn QuicClientConfigProvider> {
261    provider.unwrap_or_else(|| Arc::new(UnavailableQuicTls))
262}
263
264#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
265#[derive(Debug)]
266struct UnavailableQuicTls;
267
268#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
269impl TlsClientConfigProvider for UnavailableQuicTls {
270    fn pool_id(&self, _: &Extensions) -> Option<TlsPoolId> {
271        None
272    }
273
274    fn pool_classifier(&self) -> ReuseKey {
275        ReuseKey::of::<Self>()
276    }
277
278    fn authenticates_server(&self, _: &Extensions) -> bool {
279        false
280    }
281}
282
283#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
284impl QuicClientConfigProvider for UnavailableQuicTls {
285    fn client_config(
286        &self,
287        _: &TlsClientConfig,
288        _: TlsOptions,
289    ) -> Result<ClientConfig, TlsConfigError> {
290        Err(TlsConfigError::BackendUnavailable)
291    }
292
293    fn acquire_client_config(
294        &self,
295        _: ClientConfigRequest<'_>,
296    ) -> Result<Option<ClientConfig>, TlsConfigError> {
297        Err(TlsConfigError::BackendUnavailable)
298    }
299
300    fn acquire_client_config_async<'a>(
301        &'a self,
302        request: ClientConfigRequest<'a>,
303    ) -> BoxFuture<'a, Result<Option<ClientConfig>, TlsConfigError>> {
304        Box::pin(future::ready(self.acquire_client_config(request)))
305    }
306
307    fn allows_early_data(&self, _: &Extensions) -> bool {
308        false
309    }
310
311    fn peer_matches_name(&self, _: &Extensions, _: &CertificateDer<'_>, _: &ServerName) -> bool {
312        false
313    }
314}
315
316#[non_exhaustive]
317#[derive(Debug, Default)]
318pub struct HttpStage<const PROXY: bool = true>;
319
320#[non_exhaustive]
321#[derive(Debug, Default)]
322pub struct ProxyRouteFailureCacheStage;
323
324#[non_exhaustive]
325#[derive(Debug, Default)]
326pub struct PoolStage;
327
328impl Default for EasyHttpConnectorBuilder {
329    fn default() -> Self {
330        Self::new(WeakScope::default())
331    }
332}
333
334impl EasyHttpConnectorBuilder {
335    /// Start a connector whose connections and tunnels run in `scope`.
336    #[must_use]
337    pub fn new(scope: impl Into<WeakScope>) -> Self {
338        Self {
339            connector: (),
340            stage: (),
341            dns: (),
342            discovery: HttpsDiscovery::default(),
343            forward: ProxyMethodNotEnabled::HTTP_FORWARD,
344            scope: scope.into(),
345            target_version: None,
346        }
347    }
348
349    /// Dial origins over TCP, and over QUIC for HTTP/3 where this build has a QUIC
350    /// TLS backend.
351    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
352    #[must_use]
353    pub fn with_default_transport_connector(
354        self,
355    ) -> EasyHttpConnectorBuilder<TcpConnector, TransportStage<QuicLeg<SharedQuicEndpoint>>> {
356        let quic = QuicLeg::new(SharedQuicEndpoint::managed(self.scope.clone()));
357        self.with_transport(TcpConnector::default(), quic)
358    }
359
360    /// Dial origins over TCP.
361    #[cfg(not(all(feature = "quic", any(feature = "boring", feature = "rustls"))))]
362    #[must_use]
363    pub fn with_default_transport_connector(
364        self,
365    ) -> EasyHttpConnectorBuilder<TcpConnector, TransportStage> {
366        self.with_default_tcp_connector()
367    }
368
369    /// Dial origins over QUIC only: every request is sent over HTTP/3, whichever version
370    /// it was built with. Only a request which explicitly targets another version, with a
371    /// [`TargetHttpVersion`] of its own, fails: this client has no byte stream to carry it.
372    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
373    #[must_use]
374    pub fn with_default_quic_connector(
375        self,
376    ) -> EasyHttpConnectorBuilder<NoTcpConnector, TransportStage<QuicLeg<SharedQuicEndpoint>>> {
377        let quic = QuicLeg::new(SharedQuicEndpoint::managed(self.scope.clone()));
378        self.with_quic_transport(quic)
379    }
380
381    /// Dial origins over TCP only: no HTTP/3.
382    #[must_use]
383    pub fn with_default_tcp_connector(
384        self,
385    ) -> EasyHttpConnectorBuilder<TcpConnector, TransportStage> {
386        self.with_transport(TcpConnector::default(), ())
387    }
388
389    /// Dial origins over `connector` only: this first call is the only transport leg, so
390    /// there is no HTTP/3 unless a QUIC leg is added with
391    /// [`EasyHttpConnectorBuilder::with_custom_quic_connector`].
392    pub fn with_custom_tcp_connector<C>(
393        self,
394        connector: C,
395    ) -> EasyHttpConnectorBuilder<C, TransportStage> {
396        self.with_transport(connector, ())
397    }
398
399    /// Dial origins over the QUIC endpoints `endpoints` hands out only, like
400    /// [`EasyHttpConnectorBuilder::with_default_quic_connector`]: this first call is the
401    /// only transport leg, so every request is sent over HTTP/3. A TCP leg can be added
402    /// with [`EasyHttpConnectorBuilder::with_custom_tcp_connector`], which then serves the
403    /// requests that explicitly target another version.
404    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
405    pub fn with_custom_quic_connector<E>(
406        self,
407        endpoints: E,
408    ) -> EasyHttpConnectorBuilder<NoTcpConnector, TransportStage<QuicLeg<E>>>
409    where
410        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint>,
411    {
412        self.with_quic_transport(QuicLeg::new(endpoints))
413    }
414
415    /// Dial over `quic` only: every request without a [`TargetHttpVersion`] of its own is
416    /// sent over HTTP/3, as there is no TCP leg.
417    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
418    fn with_quic_transport<Q>(
419        mut self,
420        quic: Q,
421    ) -> EasyHttpConnectorBuilder<NoTcpConnector, TransportStage<Q>> {
422        self.target_version = Some(Version::HTTP_3);
423        self.with_transport(NoTcpConnector, quic)
424    }
425
426    fn with_transport<C, Q>(
427        self,
428        connector: C,
429        quic: Q,
430    ) -> EasyHttpConnectorBuilder<C, TransportStage<Q>> {
431        EasyHttpConnectorBuilder {
432            dns: self.dns,
433            discovery: self.discovery,
434            target_version: self.target_version,
435            forward: self.forward,
436            scope: self.scope,
437            connector,
438            stage: TransportStage { quic },
439        }
440    }
441}
442
443#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
444impl<T, Q, F> EasyHttpConnectorBuilder<T, TransportStage<Q>, (), F> {
445    /// Run HTTP/3 over the QUIC endpoints `endpoints` hands out, instead of the built-in
446    /// ones or none: on a builder which already has a transport this swaps the QUIC leg
447    /// and keeps the TCP leg.
448    pub fn with_custom_quic_connector<E>(
449        self,
450        endpoints: E,
451    ) -> EasyHttpConnectorBuilder<T, TransportStage<QuicLeg<E>>, (), F>
452    where
453        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint>,
454    {
455        EasyHttpConnectorBuilder {
456            dns: self.dns,
457            discovery: self.discovery,
458            target_version: self.target_version,
459            forward: self.forward,
460            scope: self.scope,
461            connector: self.connector,
462            stage: TransportStage {
463                quic: QuicLeg::new(endpoints),
464            },
465        }
466    }
467
468    /// Run HTTP/3 over the built-in QUIC endpoints, keeping the TCP leg chosen before,
469    /// such as a custom one.
470    #[must_use]
471    pub fn with_default_quic_connector(
472        self,
473    ) -> EasyHttpConnectorBuilder<T, TransportStage<QuicLeg<SharedQuicEndpoint>>, (), F> {
474        let endpoints = SharedQuicEndpoint::managed(self.scope.clone());
475        self.with_custom_quic_connector(endpoints)
476    }
477}
478
479impl<T, Q, F> EasyHttpConnectorBuilder<T, TransportStage<Q>, (), F> {
480    /// Dial origins over `connector` instead of the TCP leg chosen before, keeping the
481    /// QUIC leg: `with_default_transport_connector().with_custom_tcp_connector(c)` dials
482    /// HTTP/1.1 and HTTP/2 over `c` and HTTP/3 over rama's default QUIC endpoints.
483    pub fn with_custom_tcp_connector<C>(
484        self,
485        connector: C,
486    ) -> EasyHttpConnectorBuilder<C, TransportStage<Q>, (), F> {
487        EasyHttpConnectorBuilder {
488            dns: self.dns,
489            discovery: self.discovery,
490            target_version: self.target_version,
491            forward: self.forward,
492            scope: self.scope,
493            connector,
494            stage: self.stage,
495        }
496    }
497}
498
499impl<T, Stage, D, F> EasyHttpConnectorBuilder<T, Stage, D, F> {
500    /// Add a custom connector to this Stage.
501    ///
502    /// Adding a custom connector to a stage will not change the state
503    /// so this can be used to modify behaviour at a specific stage.
504    pub fn with_custom_connector<L>(
505        self,
506        connector_layer: L,
507    ) -> EasyHttpConnectorBuilder<L::Service, Stage, D, F>
508    where
509        L: Layer<T>,
510    {
511        self.map_connector(|c| connector_layer.into_layer(c))
512    }
513
514    /// Map the current connector using the given fn.
515    ///
516    /// Mapping a connector to a stage will not change the state
517    /// so this can be used to modify behaviour at a specific stage.
518    pub fn map_connector<T2>(
519        self,
520        map_fn: impl FnOnce(T) -> T2,
521    ) -> EasyHttpConnectorBuilder<T2, Stage, D, F> {
522        let connector = map_fn(self.connector);
523        EasyHttpConnectorBuilder {
524            dns: self.dns,
525            discovery: self.discovery,
526            target_version: self.target_version,
527            forward: self.forward,
528            scope: self.scope,
529            connector,
530            stage: self.stage,
531        }
532    }
533}
534
535impl<T, Q, F> EasyHttpConnectorBuilder<T, TransportStage<Q>, (), F> {
536    /// Add the global DNS policy to both the stream and built-in QUIC transports.
537    pub fn with_default_dns_connector(
538        self,
539    ) -> EasyHttpConnectorBuilder<DnsConnector<T>, DnsStage<Q>, DnsConnectorLayer, F> {
540        self.with_dns_resolver(GlobalDnsResolver::new())
541    }
542
543    /// Share one resolver between transport address resolution and HTTPS discovery.
544    pub fn with_dns_resolver<R: DnsResolver + Clone>(
545        self,
546        resolver: R,
547    ) -> EasyHttpConnectorBuilder<DnsConnector<T, R>, DnsStage<Q>, DnsConnectorLayer<R>, F> {
548        let builder = self.with_dns_address_resolver(resolver.clone());
549        #[cfg(feature = "quic")]
550        let builder = {
551            let mut builder = builder;
552            builder.discovery.layer = builder
553                .discovery
554                .layer
555                .with_resolver(BoxDnsResolver::new(resolver))
556                .with_enabled(true);
557            builder
558        };
559        builder
560    }
561
562    /// Add a custom address resolver to both the stream and built-in QUIC transports.
563    /// Automatic HTTPS discovery is disabled because this resolver need not support
564    /// HTTPS records. Use `with_dns_resolver` to share an aggregate resolver, or
565    /// explicitly opt in with `with_https_resolver` after configuring the pool.
566    pub fn with_dns_address_resolver<R: DnsAddressResolver + Clone>(
567        self,
568        resolver: R,
569    ) -> EasyHttpConnectorBuilder<DnsConnector<T, R>, DnsStage<Q>, DnsConnectorLayer<R>, F> {
570        self.with_dns_connector(DnsConnectorLayer::with_resolver(resolver))
571    }
572
573    /// Omit DNS resolution and automatic HTTPS discovery.
574    /// Transports require IP targets or their own resolution.
575    pub fn without_dns_connector(self) -> EasyHttpConnectorBuilder<T, DnsStage<Q>, (), F> {
576        self.with_dns_connector(())
577    }
578
579    /// Retain a custom DNS layer for both transport stacks.
580    ///
581    /// The layer is applied to the TCP leg here and to the HTTP/3 connector over the QUIC leg
582    /// the HTTP step builds. Automatic HTTPS discovery is disabled: an opaque layer cannot
583    /// authorize global DNS queries.
584    pub fn with_dns_connector<L: Layer<T>>(
585        self,
586        layer: L,
587    ) -> EasyHttpConnectorBuilder<L::Service, DnsStage<Q>, L, F> {
588        let connector = layer.layer(self.connector);
589        let discovery = self.discovery;
590        #[cfg(feature = "quic")]
591        let discovery = HttpsDiscovery {
592            layer: discovery.layer.with_enabled(false),
593        };
594        EasyHttpConnectorBuilder {
595            connector,
596            stage: DnsStage {
597                quic: self.stage.quic,
598            },
599            dns: layer,
600            discovery,
601            target_version: self.target_version,
602            forward: self.forward,
603            scope: self.scope,
604        }
605    }
606}
607
608/// The TCP leg of a client that dials QUIC only: it refuses every connection.
609#[derive(Debug, Clone, Copy, Default)]
610#[non_exhaustive]
611pub struct NoTcpConnector;
612
613impl<Input: Send + 'static> Service<Input> for NoTcpConnector {
614    type Output = EstablishedClientConnection<NoProxyConnection, Input>;
615    type Error = ConnectionError;
616
617    async fn serve(&self, _: Input) -> Result<Self::Output, Self::Error> {
618        Err(ConnectionError::local(
619            BoxError::from_static_str("this client dials over QUIC only"),
620            ConnectionErrorKind::Unavailable,
621        ))
622    }
623}
624
625/// A QUIC leg the proxy stage can put CONNECT-UDP ([RFC 9298]) next to, the way it puts
626/// SOCKS5 and CONNECT next to the TCP leg: `()`, no QUIC leg, stays without one.
627///
628/// [RFC 9298]: https://datatracker.ietf.org/doc/html/rfc9298
629pub trait ProxiedQuicLeg<U> {
630    type Proxied;
631
632    fn with_connect_udp(self, connect_udp: U, scope: &WeakScope) -> Self::Proxied;
633}
634
635impl<U> ProxiedQuicLeg<U> for () {
636    type Proxied = ();
637
638    fn with_connect_udp(self, _: U, _: &WeakScope) -> Self::Proxied {}
639}
640
641#[cfg(all(
642    feature = "masque",
643    feature = "quic",
644    any(feature = "boring", feature = "rustls")
645))]
646impl<E, U> ProxiedQuicLeg<U> for QuicLeg<E> {
647    type Proxied = QuicLeg<
648        MapEstablishedConnection<
649            MaybeProxiedConnector<E, QuicEndpointConnector<U>, ProxiedRoute>,
650            FlattenMaybeProxied,
651        >,
652    >;
653
654    fn with_connect_udp(self, connect_udp: U, scope: &WeakScope) -> Self::Proxied {
655        QuicLeg {
656            endpoints: MapEstablishedConnection::new(
657                MaybeProxiedConnector::new(
658                    self.endpoints,
659                    QuicEndpointConnector::new(connect_udp, scope.clone()),
660                    ProxiedRoute::new(),
661                ),
662                FlattenMaybeProxied,
663            ),
664            config: self.config,
665            transport: self.transport,
666        }
667    }
668}
669
670#[cfg(all(
671    feature = "quic",
672    not(feature = "masque"),
673    any(feature = "boring", feature = "rustls")
674))]
675impl<E, U> ProxiedQuicLeg<U> for QuicLeg<E> {
676    type Proxied = Self;
677
678    fn with_connect_udp(self, _: U, _: &WeakScope) -> Self::Proxied {
679        self
680    }
681}
682
683/// Turn a [`MaybeProxied`] connection whose two sides are of one type into that type.
684#[derive(Debug, Clone, Copy, Default)]
685#[non_exhaustive]
686pub struct FlattenMaybeProxied;
687
688impl<A> Layer<MaybeProxied<A, A>> for FlattenMaybeProxied {
689    type Service = A;
690
691    fn layer(&self, conn: MaybeProxied<A, A>) -> Self::Service {
692        match conn {
693            MaybeProxied::Direct { conn } | MaybeProxied::Proxied { conn } => conn,
694        }
695    }
696}
697
698impl<T, Q, D, F> EasyHttpConnectorBuilder<T, DnsStage<Q>, D, F> {
699    /// Reach the origin of a request with a proxied [`ProxyRoute`] through `proxies`, and
700    /// every other origin over the connector built so far.
701    ///
702    /// Every proxy method lands next to the leg it belongs to: SOCKS5 and CONNECT next to
703    /// the TCP leg, as they answer with a byte stream to the origin; CONNECT-UDP next to
704    /// the QUIC leg, as it answers with the datagrams HTTP/3 runs on; forwarding above the
705    /// HTTP connections, where the proxy plays origin for the request.
706    ///
707    /// The connections to proxies are client connections of their own, with their own
708    /// transport, DNS, TLS and connection pool: nothing of this client's transport, DNS, TLS
709    /// or HTTP configuration applies to them. To dial proxies over a transport of your own,
710    /// build the connector with
711    /// [`ProxyConnector::builder(scope).with_custom_tcp_connector(..)`](ProxyConnector::builder).
712    ///
713    /// [`ProxyRoute`]: rama_net::client::ProxyRoute
714    pub fn with_proxy_support<S, C, U, F2>(
715        self,
716        proxies: ProxyConnector<S, C, U, F2>,
717    ) -> EasyHttpConnectorBuilder<
718        MaybeProxiedConnector<
719            T,
720            ProxyStreamConnector<ErasedConnector<S::Connection>, ErasedConnector<C::Connection>>,
721            HttpTunnelRoute,
722        >,
723        ProxyStage<true, Q::Proxied>,
724        D,
725        ErasedConnector<F2::Connection>,
726    >
727    where
728        S: ConnectorService<ConnectRequest>,
729        C: ConnectorService<ConnectRequest>,
730        U: ConnectorService<ConnectRequest>,
731        F2: ConnectorService<ConnectRequest>,
732        Q: ProxiedQuicLeg<ErasedConnector<U::Connection>>,
733    {
734        let ProxyConnectorParts {
735            socks,
736            connect,
737            connect_udp,
738            forward,
739            ..
740        } = proxies.into_parts();
741        // Each method is a client stack of its own; erased so this client's types and
742        // futures do not nest them.
743        let quic = self
744            .stage
745            .quic
746            .with_connect_udp(erase_connector(connect_udp), &self.scope);
747        EasyHttpConnectorBuilder {
748            dns: self.dns,
749            discovery: self.discovery,
750            target_version: self.target_version,
751            forward: erase_connector(forward),
752            scope: self.scope,
753            connector: MaybeProxiedConnector::new(
754                self.connector,
755                ProxyStreamConnector::new(erase_connector(socks), erase_connector(connect)),
756                HttpTunnelRoute::new(),
757            ),
758            stage: ProxyStage { quic },
759        }
760    }
761
762    /// [`Self::with_proxy_support`] with rama's default connections towards proxies, which
763    /// run in the scope of this builder; see [`ProxyConnector::default_with_scope`].
764    ///
765    /// `Body` is the body type sent to a proxy, the one this client serves origins with.
766    /// These connections are clients of their own, as in [`Self::with_proxy_support`]: they
767    /// have their own transport, DNS, TLS and pool, and none of this client's. Isolating the
768    /// `407` of an upstream proxy, as an intermediary needs, is a setting of the
769    /// [`ProxyConnector`]: pass one to [`Self::with_proxy_support`] instead.
770    pub fn with_default_proxy_support<Body>(
771        self,
772    ) -> EasyHttpConnectorBuilder<
773        MaybeProxiedConnector<
774            T,
775            ProxyStreamConnector<
776                ErasedMethod<DefaultProxySocksMethod>,
777                ErasedMethod<DefaultProxyConnectMethod<TcpConnector, Body>>,
778            >,
779            HttpTunnelRoute,
780        >,
781        ProxyStage<true, Q::Proxied>,
782        D,
783        ErasedMethod<DefaultProxyForwardMethod<TcpConnector, Body>>,
784    >
785    where
786        Q: ProxiedQuicLeg<ErasedMethod<DefaultProxyConnectUdpMethod<TcpConnector, Body>>>,
787        Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
788    {
789        let proxies = ProxyConnector::default_with_scope(self.scope.clone());
790        self.with_proxy_support(proxies)
791    }
792
793    /// Make a client without proxy support: a request with a proxied [`ProxyRoute`] is
794    /// refused rather than connected around its proxy.
795    ///
796    /// [`ProxyRoute`]: rama_net::client::ProxyRoute
797    pub fn without_proxy_support(
798        self,
799    ) -> EasyHttpConnectorBuilder<DirectOnlyConnector<T>, ProxyStage<false, Q>, D, F> {
800        EasyHttpConnectorBuilder {
801            dns: self.dns,
802            discovery: self.discovery,
803            target_version: self.target_version,
804            forward: self.forward,
805            scope: self.scope,
806            connector: DirectOnlyConnector::new(self.connector),
807            stage: ProxyStage {
808                quic: self.stage.quic,
809            },
810        }
811    }
812}
813impl<T, Q, D, F, const PROXY: bool> EasyHttpConnectorBuilder<T, ProxyStage<PROXY, Q>, D, F> {
814    /// Add a custom tls connector that will be used by the client.
815    ///
816    /// The QUIC leg gets no TLS from a custom connector, so this client has no built-in
817    /// HTTP/3.
818    ///
819    /// TLS connectors publish connection reuse policies on their established
820    /// transports. Custom secure connectors without this metadata are not pooled;
821    /// implement the generic connection reuse policy to support safe pooling.
822    ///
823    /// The final HTTP transition applies a [`RequestVersionAdapter`] outside
824    /// the complete connection attempt so it can apply the negotiated version
825    /// to the original HTTP request.
826    pub fn with_custom_tls_connector<L>(
827        self,
828        connector_layer: L,
829    ) -> EasyHttpConnectorBuilder<L::Service, TlsStage<PROXY, (), Q>, D, F>
830    where
831        L: Layer<T>,
832    {
833        let connector = connector_layer.into_layer(self.connector);
834
835        EasyHttpConnectorBuilder {
836            dns: self.dns,
837            discovery: self.discovery,
838            target_version: self.target_version,
839            forward: self.forward,
840            scope: self.scope,
841            connector,
842            stage: TlsStage::without_tls(self.stage.quic),
843        }
844    }
845
846    #[cfg(feature = "boring")]
847    #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
848    /// Support https connections by using boringssl for tls
849    ///
850    /// The final HTTP transition automatically applies the HTTP version
851    /// negotiated through TLS to the original request.
852    ///
853    /// `config` secures both legs, but its ALPN only applies to TCP: the QUIC leg always
854    /// offers `h3`.
855    pub fn with_tls_support_using_boringssl(
856        self,
857        config: TlsClientConfig,
858    ) -> EasyHttpConnectorBuilder<
859        boring_client::TlsConnector<T>,
860        TlsStage<PROXY, TlsClientConfig, Q>,
861        D,
862        F,
863    > {
864        let discovery = self.discovery.with_tls(&config, true);
865        let connector =
866            boring_client::TlsConnector::auto(self.connector).with_base_config(config.clone());
867
868        EasyHttpConnectorBuilder {
869            dns: self.dns,
870            discovery,
871            target_version: self.target_version,
872            forward: self.forward,
873            scope: self.scope,
874            connector,
875            stage: TlsStage::using_boring(config, self.stage.quic),
876        }
877    }
878
879    #[cfg(feature = "boring")]
880    #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
881    /// Same as [`Self::with_tls_support_using_boringssl`] but also
882    /// setting a fallback HTTP version in case no ALPN is negotiated.
883    /// The fallback does not constrain the ALPN protocols offered by TLS.
884    ///
885    /// This is a fairly important detail for proxy purposes given otherwise
886    /// you might come in situations where the ingress traffic is negotiated to `h2`,
887    /// but the egress traffic has no negotiation which would without a default
888    /// http version remain on h2... In such a case you can get failed
889    /// requests if the egress server does not handle multiple http versions.
890    pub fn with_tls_support_using_boringssl_and_default_http_version(
891        self,
892        config: TlsClientConfig,
893        default_http_version: rama_http::Version,
894    ) -> EasyHttpConnectorBuilder<
895        AddInputExtension<boring_client::TlsConnector<T>, FallbackHttpVersion>,
896        TlsStage<PROXY, TlsClientConfig, Q>,
897        D,
898        F,
899    > {
900        let discovery = self.discovery.with_tls(&config, true);
901        let connector =
902            boring_client::TlsConnector::auto(self.connector).with_base_config(config.clone());
903        let connector =
904            AddInputExtension::new(connector, FallbackHttpVersion(default_http_version))
905                .with_overwrite(false);
906
907        EasyHttpConnectorBuilder {
908            dns: self.dns,
909            discovery,
910            target_version: self.target_version,
911            forward: self.forward,
912            scope: self.scope,
913            connector,
914            stage: TlsStage::using_boring(config, self.stage.quic),
915        }
916    }
917
918    #[cfg(feature = "rustls")]
919    #[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
920    /// Support https connections by using ruslts for tls
921    ///
922    /// The final HTTP transition automatically applies the HTTP version
923    /// negotiated through TLS to the original request.
924    ///
925    /// `config` secures both legs, but its ALPN only applies to TCP: the QUIC leg always
926    /// offers `h3`.
927    pub fn with_tls_support_using_rustls(
928        self,
929        config: TlsClientConfig,
930    ) -> EasyHttpConnectorBuilder<
931        rustls_client::TlsConnector<T>,
932        TlsStage<PROXY, TlsClientConfig, Q>,
933        D,
934        F,
935    > {
936        let discovery = self.discovery.with_tls(&config, false);
937        let connector =
938            rustls_client::TlsConnector::auto(self.connector).with_base_config(config.clone());
939
940        EasyHttpConnectorBuilder {
941            dns: self.dns,
942            discovery,
943            target_version: self.target_version,
944            forward: self.forward,
945            scope: self.scope,
946            connector,
947            stage: TlsStage::using_rustls(config, self.stage.quic),
948        }
949    }
950
951    #[cfg(feature = "rustls")]
952    #[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
953    /// Same as [`Self::with_tls_support_using_rustls`] but also
954    /// setting a fallback HTTP version in case no ALPN is negotiated.
955    /// The fallback does not constrain the ALPN protocols offered by TLS.
956    ///
957    /// This is a fairly important detail for proxy purposes given otherwise
958    /// you might come in situations where the ingress traffic is negotiated to `h2`,
959    /// but the egress traffic has no negotiation which would without a default
960    /// http version remain on h2... In such a case you can get failed
961    /// requests if the egress server does not handle multiple http versions.
962    pub fn with_tls_support_using_rustls_and_default_http_version(
963        self,
964        config: TlsClientConfig,
965        default_http_version: rama_http::Version,
966    ) -> EasyHttpConnectorBuilder<
967        AddInputExtension<rustls_client::TlsConnector<T>, FallbackHttpVersion>,
968        TlsStage<PROXY, TlsClientConfig, Q>,
969        D,
970        F,
971    > {
972        let discovery = self.discovery.with_tls(&config, false);
973        let connector =
974            rustls_client::TlsConnector::auto(self.connector).with_base_config(config.clone());
975        let connector =
976            AddInputExtension::new(connector, FallbackHttpVersion(default_http_version))
977                .with_overwrite(false);
978
979        EasyHttpConnectorBuilder {
980            dns: self.dns,
981            discovery,
982            target_version: self.target_version,
983            forward: self.forward,
984            scope: self.scope,
985            connector,
986            stage: TlsStage::using_rustls(config, self.stage.quic),
987        }
988    }
989
990    core::cfg_select! {
991        feature = "boring" => {
992            /// Support https connections with the TLS implementation this build of rama
993            /// prefers; see [`Self::with_tls_support_using_boringssl`].
994            pub fn with_default_tls_support(
995                self,
996                config: TlsClientConfig,
997            ) -> EasyHttpConnectorBuilder<
998                boring_client::TlsConnector<T>,
999                TlsStage<PROXY, TlsClientConfig, Q>,
1000                D,
1001                F,
1002            > {
1003                self.with_tls_support_using_boringssl(config)
1004            }
1005        }
1006        feature = "rustls" => {
1007            /// Support https connections with the TLS implementation this build of rama
1008            /// prefers; see [`Self::with_tls_support_using_rustls`].
1009            pub fn with_default_tls_support(
1010                self,
1011                config: TlsClientConfig,
1012            ) -> EasyHttpConnectorBuilder<
1013                rustls_client::TlsConnector<T>,
1014                TlsStage<PROXY, TlsClientConfig, Q>,
1015                D,
1016                F,
1017            > {
1018                self.with_tls_support_using_rustls(config)
1019            }
1020        }
1021        _ => {}
1022    }
1023
1024    /// Don't support https on this connector, nor HTTP/3, which is always secure.
1025    pub fn without_tls_support(self) -> EasyHttpConnectorBuilder<T, TlsStage<PROXY, (), Q>, D, F> {
1026        EasyHttpConnectorBuilder {
1027            dns: self.dns,
1028            discovery: self.discovery,
1029            target_version: self.target_version,
1030            forward: self.forward,
1031            scope: self.scope,
1032            connector: self.connector,
1033            stage: TlsStage::without_tls(self.stage.quic),
1034        }
1035    }
1036}
1037
1038#[cfg(feature = "boring")]
1039impl<T, D, F, Tls, Q, const PROXY: bool>
1040    EasyHttpConnectorBuilder<boring_client::TlsConnector<T>, TlsStage<PROXY, Tls, Q>, D, F>
1041{
1042    #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
1043    /// Resume TLS sessions with servers connected to before, keeping them in `store`;
1044    /// see [`boring_client::TlsConnector::with_session_store`].
1045    ///
1046    /// Servers can link the connections that resume each other's sessions, so a
1047    /// client acting for several users should keep a store per user.
1048    #[must_use]
1049    pub fn with_tls_session_store(
1050        mut self,
1051        store: Arc<dyn boring_client::TlsClientSessionStore>,
1052    ) -> Self {
1053        self.connector.set_session_store(store);
1054        self
1055    }
1056}
1057
1058impl<T, D, F, Tls, Q, const PROXY: bool>
1059    EasyHttpConnectorBuilder<T, TlsStage<PROXY, Tls, Q>, D, F>
1060{
1061    fn http_connector<Body>(
1062        self,
1063    ) -> EasyHttpConnectorBuilder<HttpConnector<T, Body>, HttpStage<PROXY>, D, F> {
1064        let connector = HttpConnector::new(self.connector, self.scope.clone());
1065
1066        EasyHttpConnectorBuilder {
1067            dns: self.dns,
1068            discovery: self.discovery,
1069            target_version: self.target_version,
1070            forward: self.forward,
1071            scope: self.scope,
1072            connector,
1073            stage: HttpStage,
1074        }
1075    }
1076
1077    /// Add a custom http connector that will be run just after tls, instead of the one
1078    /// [`Self::with_default_http_connector`] builds; the QUIC leg is left out.
1079    pub fn with_custom_http_connector<L>(
1080        self,
1081        connector_layer: L,
1082    ) -> EasyHttpConnectorBuilder<L::Service, HttpStage<PROXY>, D, F>
1083    where
1084        L: Layer<T>,
1085    {
1086        let connector = connector_layer.into_layer(self.connector);
1087
1088        EasyHttpConnectorBuilder {
1089            dns: self.dns,
1090            discovery: self.discovery,
1091            target_version: self.target_version,
1092            forward: self.forward,
1093            scope: self.scope,
1094            connector,
1095            stage: HttpStage,
1096        }
1097    }
1098}
1099
1100impl<T, D, F, Q, const PROXY: bool> EasyHttpConnectorBuilder<T, TlsStage<PROXY, (), Q>, D, F> {
1101    /// Speak HTTP/1.1 and HTTP/2 over the TCP leg. Without TLS there is no HTTP/3: that
1102    /// runs over QUIC, which is always secure.
1103    pub fn with_default_http_connector<Body>(
1104        self,
1105    ) -> EasyHttpConnectorBuilder<HttpConnector<T, Body>, HttpStage<PROXY>, D, F> {
1106        self.http_connector()
1107    }
1108}
1109
1110#[cfg(any(feature = "boring", feature = "rustls"))]
1111impl<T, D, F, const PROXY: bool>
1112    EasyHttpConnectorBuilder<T, TlsStage<PROXY, TlsClientConfig, ()>, D, F>
1113{
1114    /// Speak HTTP/1.1 and HTTP/2 over the TCP leg; there is no QUIC leg for HTTP/3.
1115    pub fn with_default_http_connector<Body>(
1116        self,
1117    ) -> EasyHttpConnectorBuilder<HttpConnector<T, Body>, HttpStage<PROXY>, D, F> {
1118        self.http_connector()
1119    }
1120}
1121
1122#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
1123#[cfg_attr(docsrs, doc(cfg(feature = "quic")))]
1124impl<T, D, F, E, const PROXY: bool>
1125    EasyHttpConnectorBuilder<T, TlsStage<PROXY, TlsClientConfig, QuicLeg<E>>, D, F>
1126{
1127    /// Configure the HTTP/3 connector [`Self::with_default_http_connector`] builds over
1128    /// the QUIC leg, such as `Config { early_requests: true, ..Default::default() }`.
1129    ///
1130    /// A client which brings its own HTTP/3 connector configures it itself and adds it
1131    /// with [`Self::with_custom_http_connector`].
1132    #[must_use]
1133    pub fn with_http3_config(mut self, config: Http3Config) -> Self {
1134        self.stage.quic.config = Some(config);
1135        self
1136    }
1137
1138    /// Build the QUIC TLS configurations through `provider` instead of the backend the
1139    /// TLS stage selected, so the QUIC leg can use another backend than the TCP leg.
1140    #[must_use]
1141    pub fn with_quic_tls_provider(mut self, provider: Arc<dyn QuicClientConfigProvider>) -> Self {
1142        self.stage.quic_tls = Some(provider);
1143        self
1144    }
1145
1146    /// Speak HTTP/1.1 and HTTP/2 over the TCP leg and HTTP/3 over the QUIC leg, on the TLS
1147    /// of the stage before this one and the same DNS policy for both. HTTP/3 is reached
1148    /// through alternative-service discovery or an explicit HTTP/3 request.
1149    pub fn with_default_http_connector<Body>(
1150        self,
1151    ) -> EasyHttpConnectorBuilder<
1152        HttpConnector<super::HttpTransportConnector<T, D::Service>, Body>,
1153        HttpStage<PROXY>,
1154        D,
1155        F,
1156    >
1157    where
1158        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint> + Clone,
1159        D: Layer<super::Http3Connector<E>>,
1160        D::Service: Service<
1161                ConnectRequest,
1162                Output = EstablishedClientConnection<super::Http3Transport, ConnectRequest>,
1163                Error = ConnectionError,
1164            > + Clone
1165            + Send
1166            + Sync
1167            + 'static,
1168    {
1169        let Self {
1170            connector,
1171            stage,
1172            dns,
1173            mut discovery,
1174            target_version,
1175            forward,
1176            scope,
1177        } = self;
1178        let provider = quic_tls_provider_or_unavailable(stage.quic_tls);
1179        let http3 = super::default_http3_builder(scope.clone(), stage.tls, provider)
1180            .with_endpoints(stage.quic.endpoints)
1181            .maybe_with_transport(stage.quic.transport);
1182        let http3 = match stage.quic.config {
1183            Some(config) => http3.with_config(config),
1184            None => http3,
1185        };
1186        #[expect(
1187            clippy::expect_used,
1188            reason = "the built-in HTTP/3 configuration is always valid"
1189        )]
1190        let http3 = http3.build_lazy().expect("built-in HTTP/3 configuration");
1191        let capable = discovery.layer.is_ech_capable() || http3.tls_provider().supports_ech();
1192        discovery.layer.set_ech_capable(capable);
1193        let quic = dns.layer(http3);
1194        EasyHttpConnectorBuilder {
1195            connector: HttpConnector::new(connector, scope.clone()).with_http3_connector(quic),
1196            stage: HttpStage,
1197            dns,
1198            discovery,
1199            target_version,
1200            forward,
1201            scope,
1202        }
1203    }
1204}
1205
1206#[cfg(feature = "quic")]
1207type SelectedConnector<T> =
1208    HttpsService<HttpServiceConnector<ProxyRoutesConnector<T>>, BoxDnsResolver>;
1209#[cfg(not(feature = "quic"))]
1210type SelectedConnector<T> = HttpServiceConnector<ProxyRoutesConnector<T>>;
1211
1212type DefaultHttpConnector<T> = TargetVersionConnector<
1213    RequestVersionAdapter<
1214        HttpConnectRequestAdapter<
1215            MapEstablishedConnection<SelectedConnector<T>, AltSvcConnectionLayer>,
1216        >,
1217    >,
1218>;
1219
1220/// The HTTP version a client dials with unless the request names one of its own, as a
1221/// client which dials over QUIC only targets HTTP/3.
1222#[doc(hidden)]
1223#[derive(Clone, Debug)]
1224pub struct TargetVersionConnector<S> {
1225    inner: S,
1226    version: Option<Version>,
1227}
1228
1229impl<S> TargetVersionConnector<S> {
1230    fn get_mut(&mut self) -> &mut S {
1231        &mut self.inner
1232    }
1233}
1234
1235impl<S, Input> Service<Input> for TargetVersionConnector<S>
1236where
1237    S: Service<Input>,
1238    Input: ExtensionsRef + Send + 'static,
1239{
1240    type Output = S::Output;
1241    type Error = S::Error;
1242
1243    async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
1244        if let Some(version) = self.version
1245            && !input.extensions().contains::<TargetHttpVersion>()
1246        {
1247            input.extensions().insert(TargetHttpVersion(version));
1248        }
1249        self.inner.serve(input).await
1250    }
1251}
1252
1253/// HTTP response observation configured by the easy-client builder.
1254///
1255/// Protocol selection and response observation share the configured cache but
1256/// remain independently composable services.
1257#[doc(hidden)]
1258#[derive(Clone, Debug)]
1259pub struct AltSvcConnectionLayer {
1260    pub(super) cache: Option<AltSvcCache>,
1261}
1262
1263impl<S> Layer<S> for AltSvcConnectionLayer {
1264    type Service = AltSvc<S>;
1265
1266    fn layer(&self, inner: S) -> Self::Service {
1267        match &self.cache {
1268            Some(cache) => AltSvcLayer::new(cache.clone()).layer(inner),
1269            None => AltSvc::passthrough(inner),
1270        }
1271    }
1272}
1273
1274type ConfiguredConnectionBuilder<T> = EasyHttpConnectorBuilder<DefaultHttpConnector<T>, PoolStage>;
1275
1276type ConfiguredConnectionPoolBuilder<T> =
1277    EasyHttpConnectorBuilder<DefaultHttpConnector<HttpPooledConnector<T>>, PoolStage>;
1278
1279type ErasedConnector<C> =
1280    BoxService<ConnectRequest, EstablishedClientConnection<C, ConnectRequest>, ConnectionError>;
1281
1282type ErasedMethod<M> = ErasedConnector<<M as ConnectorService<ConnectRequest>>::Connection>;
1283
1284type DefaultConnectionBuilder<C, F> = ConfiguredConnectionBuilder<
1285    ProxyRouteFailureCacheConnector<ErasedConnector<MaybeForwardedConnection<C, F>>>,
1286>;
1287
1288type DefaultConnectionPoolBuilder<C, F> = ConfiguredConnectionPoolBuilder<
1289    ProxyRouteFailureCacheConnector<ErasedConnector<MaybeForwardedConnection<C, F>>>,
1290>;
1291
1292// Keep the configured connector and its future behind one dynamic boundary
1293// before adding route caching and fallback. This prevents deeply nested TLS
1294// connector futures from overflowing ordinary thread stacks while dispatching
1295// only once per new connection (and behind the pool when pooling is enabled).
1296#[derive(ExtensionsRef)]
1297struct ConnectorServiceAdapter<T>(T);
1298
1299impl<T> Service<ConnectRequest> for ConnectorServiceAdapter<T>
1300where
1301    T: ConnectorService<ConnectRequest>,
1302{
1303    type Output = EstablishedClientConnection<T::Connection, ConnectRequest>;
1304    type Error = ConnectionError;
1305
1306    fn serve(
1307        &self,
1308        input: ConnectRequest,
1309    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send + '_ {
1310        self.0.connect(input)
1311    }
1312}
1313
1314fn erase_connector<T>(connector: T) -> ErasedConnector<T::Connection>
1315where
1316    T: ConnectorService<ConnectRequest>,
1317{
1318    ConnectorServiceAdapter(connector).boxed()
1319}
1320
1321fn finalize_http_connector<T>(
1322    connector: T,
1323    discovery: HttpsDiscovery,
1324    target_version: Option<Version>,
1325) -> DefaultHttpConnector<T> {
1326    let connector = ProxyRoutesConnector::new(connector);
1327    let cache = AltSvcCache::default();
1328    let connector = HttpServiceConnector::new(connector).with_cache(cache.clone());
1329    #[cfg(feature = "quic")]
1330    let connector = discovery.layer.with_cache(cache.clone()).layer(connector);
1331    #[cfg(not(feature = "quic"))]
1332    let _ = discovery;
1333    adapt_http_service_connector(connector, Some(cache), target_version)
1334}
1335
1336fn adapt_http_service_connector<T>(
1337    connector: SelectedConnector<T>,
1338    cache: Option<AltSvcCache>,
1339    target_version: Option<Version>,
1340) -> DefaultHttpConnector<T> {
1341    let connector = MapEstablishedConnection::new(connector, AltSvcConnectionLayer { cache });
1342    TargetVersionConnector {
1343        inner: RequestVersionAdapter::new(HttpConnectRequestAdapter::new(connector)),
1344        version: target_version,
1345    }
1346}
1347
1348impl<T> EasyHttpConnectorBuilder<DefaultHttpConnector<T>, PoolStage> {
1349    fn selected_connector_mut(&mut self) -> &mut SelectedConnector<T> {
1350        self.connector.get_mut().get_mut().get_mut().get_mut()
1351    }
1352
1353    fn service_selector_mut(&mut self) -> &mut HttpServiceConnector<ProxyRoutesConnector<T>> {
1354        let connector = self.selected_connector_mut();
1355        #[cfg(feature = "quic")]
1356        let connector = connector.get_mut();
1357        connector
1358    }
1359
1360    /// Configure HTTP service selection, including attempt timeouts and budgets.
1361    #[must_use]
1362    pub fn configure_http_service(
1363        mut self,
1364        configure: impl FnOnce(&mut HttpServiceConnector<ProxyRoutesConnector<T>>),
1365    ) -> Self {
1366        configure(self.service_selector_mut());
1367        self
1368    }
1369
1370    #[cfg(feature = "quic")]
1371    /// Disable HTTPS discovery while retaining independently configured Alt-Svc.
1372    #[must_use]
1373    pub fn without_https_discovery(mut self) -> Self {
1374        self.selected_connector_mut()
1375            .config_mut()
1376            .set_enabled(false);
1377        self
1378    }
1379
1380    #[cfg(feature = "quic")]
1381    /// Enable HTTPS discovery with this resolver for HTTPS and A/AAAA records.
1382    /// Its lazy address source takes precedence over the transport resolver for
1383    /// matching HTTPS endpoints. Use `with_dns_resolver` to share one DNS policy.
1384    #[must_use]
1385    pub fn with_https_resolver<R: DnsResolver>(mut self, resolver: R) -> Self {
1386        let config = self.selected_connector_mut().config_mut();
1387        *config = config
1388            .clone()
1389            .with_resolver(BoxDnsResolver::new(resolver))
1390            .with_enabled(true);
1391        self
1392    }
1393
1394    #[cfg(feature = "quic")]
1395    /// Configure the reusable discovery layer, including proxy permission and limits.
1396    #[must_use]
1397    pub fn configure_https_discovery(
1398        mut self,
1399        configure: impl FnOnce(&mut HttpsServiceLayer<BoxDnsResolver>),
1400    ) -> Self {
1401        configure(self.selected_connector_mut().config_mut());
1402        self
1403    }
1404
1405    /// Disable advertised alternatives and response learning for every HTTP version.
1406    #[must_use]
1407    pub fn without_alt_svc(self) -> Self {
1408        self.maybe_with_alt_svc_cache(None)
1409    }
1410
1411    generate_set_and_with! {
1412        /// Share an Alt-Svc cache across HTTP clients; `None` disables Alt-Svc only.
1413        /// HTTPS-record discovery is configured separately.
1414        pub fn alt_svc_cache(mut self, cache: Option<AltSvcCache>) -> Self {
1415            self.service_selector_mut().maybe_set_cache(cache.clone());
1416            #[cfg(feature = "quic")]
1417            self.selected_connector_mut().config_mut().maybe_set_cache(cache.clone());
1418            self.connector.get_mut().get_mut().get_mut().layer_mut().cache = cache;
1419            self
1420        }
1421    }
1422}
1423
1424fn finish_without_connection_pool<T, Stage, D, F>(
1425    builder: EasyHttpConnectorBuilder<T, Stage, D, F>,
1426) -> ConfiguredConnectionBuilder<T>
1427where
1428    T: ConnectorService<ConnectRequest>,
1429{
1430    EasyHttpConnectorBuilder {
1431        dns: (),
1432        discovery: HttpsDiscovery::default(),
1433        forward: ProxyMethodNotEnabled::HTTP_FORWARD,
1434        scope: builder.scope,
1435        connector: finalize_http_connector(
1436            builder.connector,
1437            builder.discovery,
1438            builder.target_version,
1439        ),
1440        stage: Default::default(),
1441        target_version: builder.target_version,
1442    }
1443}
1444
1445fn finish_with_connection_pool<T, Stage, D, F>(
1446    builder: EasyHttpConnectorBuilder<T, Stage, D, F>,
1447    config: HttpPooledConnectorConfig,
1448) -> ConfiguredConnectionPoolBuilder<T>
1449where
1450    T: ConnectorService<ConnectRequest>,
1451{
1452    let connector = config.build_connector(builder.connector);
1453    EasyHttpConnectorBuilder {
1454        dns: (),
1455        discovery: HttpsDiscovery::default(),
1456        forward: ProxyMethodNotEnabled::HTTP_FORWARD,
1457        scope: builder.scope,
1458        connector: finalize_http_connector(connector, builder.discovery, builder.target_version),
1459        stage: Default::default(),
1460        target_version: builder.target_version,
1461    }
1462}
1463
1464fn finish_with_custom_connection_pool<T, Stage, D, F, P, R>(
1465    builder: EasyHttpConnectorBuilder<T, Stage, D, F>,
1466    pool: P,
1467    req_to_conn_id: R,
1468    wait_for_pool_timeout: Option<Duration>,
1469) -> EasyHttpConnectorBuilder<TargetVersionConnector<PooledConnector<T, P, R>>, PoolStage> {
1470    let connector = PooledConnector::new(builder.connector, pool, req_to_conn_id)
1471        .maybe_with_wait_for_pool_timeout(wait_for_pool_timeout);
1472    EasyHttpConnectorBuilder {
1473        dns: (),
1474        discovery: HttpsDiscovery::default(),
1475        forward: ProxyMethodNotEnabled::HTTP_FORWARD,
1476        scope: builder.scope,
1477        connector: TargetVersionConnector {
1478            inner: connector,
1479            version: builder.target_version,
1480        },
1481        stage: Default::default(),
1482        target_version: builder.target_version,
1483    }
1484}
1485
1486#[cfg(feature = "quic")]
1487impl<T, Q, Body, D, F, const PROXY: bool>
1488    EasyHttpConnectorBuilder<
1489        HttpConnector<super::HttpTransportConnector<T, Q>, Body>,
1490        HttpStage<PROXY>,
1491        D,
1492        F,
1493    >
1494{
1495    /// Wrap the HTTP/3 transport connector [`Self::with_default_http_connector`] built,
1496    /// as [`Self::map_connector`] wraps the stream transport at an earlier stage.
1497    pub fn map_http3_connector<Q2>(
1498        self,
1499        map: impl FnOnce(Q) -> Q2,
1500    ) -> EasyHttpConnectorBuilder<
1501        HttpConnector<super::HttpTransportConnector<T, Q2>, Body>,
1502        HttpStage<PROXY>,
1503        D,
1504        F,
1505    > {
1506        self.map_connector(|connector| connector.map_http3_connector(map))
1507    }
1508
1509    /// Wrap the stream transport connector [`Self::with_default_http_connector`] built,
1510    /// keeping the HTTP/3 one.
1511    pub fn map_stream_connector<T2>(
1512        self,
1513        map: impl FnOnce(T) -> T2,
1514    ) -> EasyHttpConnectorBuilder<
1515        HttpConnector<super::HttpTransportConnector<T2, Q>, Body>,
1516        HttpStage<PROXY>,
1517        D,
1518        F,
1519    > {
1520        self.map_connector(|connector| connector.map_stream_connector(map))
1521    }
1522}
1523
1524impl<T, D, F, const PROXY: bool> EasyHttpConnectorBuilder<T, HttpStage<PROXY>, D, F> {
1525    /// Explicitly use the given shared proxy route failure cache.
1526    ///
1527    /// This selects the failure-cache policy for the final connection stage.
1528    /// The configured connector is type-erased at this boundary to keep the
1529    /// combined connector future stack-safe.
1530    #[must_use]
1531    pub fn with_proxy_route_failure_cache(
1532        self,
1533        cache: ProxyRouteFailureCache,
1534    ) -> EasyHttpConnectorBuilder<
1535        ProxyRouteFailureCacheConnector<
1536            ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1537        >,
1538        ProxyRouteFailureCacheStage,
1539        D,
1540    >
1541    where
1542        T: ConnectorService<ConnectRequest>,
1543        F: ConnectorService<ConnectRequest>,
1544    {
1545        let Self {
1546            connector,
1547            dns,
1548            discovery,
1549            target_version,
1550            forward,
1551            ..
1552        } = self;
1553        let connector = MaybeForwardedConnector::new(connector, forward);
1554        EasyHttpConnectorBuilder {
1555            dns,
1556            discovery,
1557            target_version,
1558            forward: ProxyMethodNotEnabled::HTTP_FORWARD,
1559            scope: self.scope,
1560            connector: ProxyRouteFailureCacheConnector::new(erase_connector(connector), cache),
1561            stage: ProxyRouteFailureCacheStage,
1562        }
1563    }
1564
1565    /// Disable negative caching of temporarily failing proxy routes.
1566    #[must_use]
1567    pub fn without_proxy_route_failure_cache(
1568        self,
1569    ) -> EasyHttpConnectorBuilder<
1570        ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1571        ProxyRouteFailureCacheStage,
1572        D,
1573    >
1574    where
1575        T: ConnectorService<ConnectRequest>,
1576        F: ConnectorService<ConnectRequest>,
1577    {
1578        let Self {
1579            connector,
1580            dns,
1581            discovery,
1582            target_version,
1583            forward,
1584            ..
1585        } = self;
1586        EasyHttpConnectorBuilder {
1587            connector: erase_connector(MaybeForwardedConnector::new(connector, forward)),
1588            dns,
1589            discovery,
1590            target_version,
1591            forward: ProxyMethodNotEnabled::HTTP_FORWARD,
1592            scope: self.scope,
1593            stage: ProxyRouteFailureCacheStage,
1594        }
1595    }
1596}
1597
1598impl<T, D, F> EasyHttpConnectorBuilder<T, HttpStage<true>, D, F> {
1599    /// Finish the default HTTP connector stack without adding a connection pool.
1600    ///
1601    /// This still installs HTTP request adaptation and ordered proxy-route
1602    /// fallback. It also installs the default proxy-route failure cache. The
1603    /// only omitted component is the pool itself.
1604    pub fn without_connection_pool(self) -> DefaultConnectionBuilder<T::Connection, F::Connection>
1605    where
1606        T: ConnectorService<ConnectRequest>,
1607        F: ConnectorService<ConnectRequest>,
1608    {
1609        finish_without_connection_pool(
1610            self.with_proxy_route_failure_cache(ProxyRouteFailureCache::default()),
1611        )
1612    }
1613
1614    /// Use the default connection pool for this [`super::EasyHttpWebClient`]
1615    ///
1616    /// This will create a [`MultiplexPool`](crate::net::client::pool::MultiplexPool)
1617    /// using the provided limits and will use
1618    /// [`super::HttpConnIdentifier`] to group connections on
1619    /// protocol, authority, selected route, physical transport, any HTTP
1620    /// version requirement, and the selected plaintext HTTP proxy mode. This
1621    /// keeps forward-proxy connections separate from CONNECT tunnels to the
1622    /// same proxy. The default proxy-route failure cache is installed behind
1623    /// the pool, so reusable connections bypass negative-cache checks.
1624    ///
1625    /// Use `wait_for_pool_timeout` to limit how long we wait for the pool to give us a connection
1626    ///
1627    /// If you need a different pool or custom way to group connection you can
1628    /// use [`EasyHttpConnectorBuilder::with_custom_connection_pool()`] to provide
1629    /// you own.
1630    ///
1631    /// This also applies a [`RequestVersionAdapter`] layer to make sure that request versions
1632    /// are adapted when pooled connections are used, which you almost always need, but in case
1633    /// that is unwanted, you can use [`Self::with_custom_connection_pool`] instead.
1634    pub fn with_connection_pool(
1635        self,
1636        config: HttpPooledConnectorConfig,
1637    ) -> DefaultConnectionPoolBuilder<T::Connection, F::Connection>
1638    where
1639        T: ConnectorService<ConnectRequest>,
1640        F: ConnectorService<ConnectRequest>,
1641    {
1642        finish_with_connection_pool(
1643            self.with_proxy_route_failure_cache(ProxyRouteFailureCache::default()),
1644            config,
1645        )
1646    }
1647
1648    /// Use Rama's default connection pool and default proxy-route failure
1649    /// cache.
1650    pub fn with_default_connection_pool(
1651        self,
1652    ) -> DefaultConnectionPoolBuilder<T::Connection, F::Connection>
1653    where
1654        T: ConnectorService<ConnectRequest>,
1655        F: ConnectorService<ConnectRequest>,
1656    {
1657        self.with_connection_pool(HttpPooledConnectorConfig::default())
1658    }
1659
1660    /// Configure this client to use the provided [`Pool`] and [`ReqToConnId`]
1661    ///
1662    /// Use `wait_for_pool_timeout` to limit how long we wait for the pool to give us a connection
1663    ///
1664    /// Warning: this does not apply a [`RequestVersionAdapter`] layer to make sure that request versions
1665    /// are adapted when pooled connections are used, which you almost always. This should be manually added
1666    /// by using [`Self::with_custom_connector`] after configuring this pool and providing a [`RequestVersionAdapter`] there.
1667    /// Unlike [`Self::with_connection_pool`], this fully generic method also does not install the HTTP
1668    /// connect-request adapter or proxy-route connector. It installs the default proxy-route failure cache behind
1669    /// the custom pool. Callers that want route-aware fallback around a custom pool can compose those layers
1670    /// explicitly around their [`PooledConnector`].
1671    ///
1672    /// When the connector supports plaintext HTTP through an HTTP proxy, the
1673    /// custom [`ReqToConnId`] must keep ordinary forward-proxy connections
1674    /// separate from CONNECT tunnels to the same proxy. Rama's
1675    /// [`super::HttpConnIdentifier`] includes this
1676    /// distinction automatically.
1677    ///
1678    /// [`Pool`]: rama_net::client::pool::Pool
1679    /// [`ReqToConnId`]: rama_net::client::pool::ReqToConnID
1680    ///
1681    /// The supplied `ReqToConnID` partitions routes and application protocols.
1682    /// The pool must also honor connection-owned reuse policies published by
1683    /// transport connectors. Return a non-reusable `ConnID` to require a fresh
1684    /// connection that must not return to the pool.
1685    pub fn with_custom_connection_pool<P, R>(
1686        self,
1687        pool: P,
1688        req_to_conn_id: R,
1689        wait_for_pool_timeout: Option<Duration>,
1690    ) -> EasyHttpConnectorBuilder<
1691        TargetVersionConnector<
1692            PooledConnector<
1693                ProxyRouteFailureCacheConnector<
1694                    ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1695                >,
1696                P,
1697                R,
1698            >,
1699        >,
1700        PoolStage,
1701    >
1702    where
1703        T: ConnectorService<ConnectRequest>,
1704        F: ConnectorService<ConnectRequest>,
1705    {
1706        finish_with_custom_connection_pool(
1707            self.with_proxy_route_failure_cache(ProxyRouteFailureCache::default()),
1708            pool,
1709            req_to_conn_id,
1710            wait_for_pool_timeout,
1711        )
1712    }
1713}
1714
1715impl<T, D, F> EasyHttpConnectorBuilder<T, HttpStage<false>, D, F> {
1716    /// Finish the proxy-free HTTP connector stack without a connection pool.
1717    ///
1718    /// No proxy-route failure cache is installed. Call
1719    /// [`Self::with_proxy_route_failure_cache`] before this method to
1720    /// explicitly add one for a custom transport.
1721    pub fn without_connection_pool(
1722        self,
1723    ) -> ConfiguredConnectionBuilder<
1724        ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1725    >
1726    where
1727        T: ConnectorService<ConnectRequest>,
1728        F: ConnectorService<ConnectRequest>,
1729    {
1730        finish_without_connection_pool(self.without_proxy_route_failure_cache())
1731    }
1732
1733    /// Use a connection pool of `config` without a proxy-route failure cache.
1734    pub fn with_connection_pool(
1735        self,
1736        config: HttpPooledConnectorConfig,
1737    ) -> ConfiguredConnectionPoolBuilder<
1738        ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1739    >
1740    where
1741        T: ConnectorService<ConnectRequest>,
1742        F: ConnectorService<ConnectRequest>,
1743    {
1744        finish_with_connection_pool(self.without_proxy_route_failure_cache(), config)
1745    }
1746
1747    /// Use Rama's default connection pool without a
1748    /// proxy-route failure cache.
1749    pub fn with_default_connection_pool(
1750        self,
1751    ) -> ConfiguredConnectionPoolBuilder<
1752        ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1753    >
1754    where
1755        T: ConnectorService<ConnectRequest>,
1756        F: ConnectorService<ConnectRequest>,
1757    {
1758        self.with_connection_pool(HttpPooledConnectorConfig::default())
1759    }
1760
1761    /// Use a custom connection pool without a proxy-route failure cache.
1762    ///
1763    /// The supplied `ReqToConnID` partitions routes and application protocols.
1764    /// The pool must also honor connection-owned reuse policies published by
1765    /// transport connectors. Return a non-reusable `ConnID` to require a fresh
1766    /// connection that must not return to the pool.
1767    pub fn with_custom_connection_pool<P, R>(
1768        self,
1769        pool: P,
1770        req_to_conn_id: R,
1771        wait_for_pool_timeout: Option<Duration>,
1772    ) -> EasyHttpConnectorBuilder<
1773        TargetVersionConnector<
1774            PooledConnector<
1775                ErasedConnector<MaybeForwardedConnection<T::Connection, F::Connection>>,
1776                P,
1777                R,
1778            >,
1779        >,
1780        PoolStage,
1781    >
1782    where
1783        T: ConnectorService<ConnectRequest>,
1784        F: ConnectorService<ConnectRequest>,
1785    {
1786        finish_with_custom_connection_pool(
1787            self.without_proxy_route_failure_cache(),
1788            pool,
1789            req_to_conn_id,
1790            wait_for_pool_timeout,
1791        )
1792    }
1793}
1794
1795impl<T, D, F> EasyHttpConnectorBuilder<T, ProxyRouteFailureCacheStage, D, F> {
1796    /// Finish the default HTTP connector stack without a connection pool.
1797    pub fn without_connection_pool(self) -> ConfiguredConnectionBuilder<T>
1798    where
1799        T: ConnectorService<ConnectRequest>,
1800    {
1801        finish_without_connection_pool(self)
1802    }
1803
1804    /// Use a connection pool of `config` with the selected failure-cache policy.
1805    pub fn with_connection_pool(
1806        self,
1807        config: HttpPooledConnectorConfig,
1808    ) -> ConfiguredConnectionPoolBuilder<T>
1809    where
1810        T: ConnectorService<ConnectRequest>,
1811    {
1812        finish_with_connection_pool(self, config)
1813    }
1814
1815    /// Use Rama's default connection pool with the
1816    /// selected failure-cache policy.
1817    pub fn with_default_connection_pool(self) -> ConfiguredConnectionPoolBuilder<T>
1818    where
1819        T: ConnectorService<ConnectRequest>,
1820    {
1821        finish_with_connection_pool(self, HttpPooledConnectorConfig::default())
1822    }
1823
1824    /// Use a custom connection pool with the selected failure-cache policy.
1825    ///
1826    /// For a proxy-capable connector, the custom
1827    /// [`ReqToConnID`](rama_net::client::pool::ReqToConnID) must partition
1828    /// plaintext HTTP forward-proxy connections from CONNECT tunnels to the
1829    /// same proxy. [`super::HttpConnIdentifier`] does so by
1830    /// default.
1831    ///
1832    /// The supplied `ReqToConnID` partitions routes and application protocols.
1833    /// The pool must also honor connection-owned reuse policies published by
1834    /// transport connectors. Return a non-reusable `ConnID` to require a fresh
1835    /// connection that must not return to the pool.
1836    pub fn with_custom_connection_pool<P, R>(
1837        self,
1838        pool: P,
1839        req_to_conn_id: R,
1840        wait_for_pool_timeout: Option<Duration>,
1841    ) -> EasyHttpConnectorBuilder<TargetVersionConnector<PooledConnector<T, P, R>>, PoolStage> {
1842        finish_with_custom_connection_pool(self, pool, req_to_conn_id, wait_for_pool_timeout)
1843    }
1844}
1845
1846impl<T> EasyHttpConnectorBuilder<T, PoolStage> {
1847    /// Build a client with one owner for HTTP early-data recovery.
1848    ///
1849    /// This composes the existing Retry and MapInput services around the client,
1850    /// above pool selection. Configure HTTP/3 `Config::early_requests` to make
1851    /// early transport available; ordinary clients remain handshake-first.
1852    /// That explicit HTTP/3 setting can add an early-data offer to a resumed
1853    /// ClientHello even for requests that wait. Leave it off for exact TLS
1854    /// fingerprint emulation; compiled captured profiles disable early data.
1855    ///
1856    /// This helper is optional. Custom recovery middleware can wrap
1857    /// [`Self::build_client`] and use [`rama_net::tls::EarlyDataPermit`],
1858    /// [`rama_net::tls::ForbidEarlyData`] and the transport facts in
1859    /// [`rama_http::proto::ext::early_data`] directly, without Retry or RetryBody.
1860    /// The custom owner must isolate each attempt's extensions, retain its
1861    /// replayable request, and bound recovery itself.
1862    ///
1863    /// `prepare_body` selects which uploads to capture for replay and can tighten
1864    /// the default memory store's 64 KiB byte limit and 30-second deadline.
1865    /// Use [`rama_http::layer::retry::early_data::prepare_bodyless`] to stream
1866    /// payloads once, or provide a bounded preparation policy for ordinary payload
1867    /// retries. Only safe, truly empty requests may send early, regardless of that
1868    /// policy. A 425 with actual original-client early-send evidence, or a
1869    /// per-request TLS early rejection, receives one confirmed retry. Forwarded
1870    /// 425 responses pass through. Other results use `application_rule`, with
1871    /// its normal limits; no additional outer retry loop should own recovery.
1872    pub fn build_client_with_early_data<Body, ModifiedBody, ConnResponse, IncomingBody, R, P>(
1873        self,
1874        application_rule: R,
1875        prepare_body: P,
1876    ) -> impl Service<Request<Body>, Output = Response, Error = RetryError>
1877    where
1878        Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Send + 'static,
1879        ModifiedBody:
1880            StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
1881        T: Service<
1882                Request<RetryBody>,
1883                Output = EstablishedClientConnection<ConnResponse, Request<ModifiedBody>>,
1884                Error: Into<BoxError>,
1885            >,
1886        ConnResponse: Service<Request<ModifiedBody>, Output = Response<IncomingBody>, Error = BoxError>
1887            + ExtensionsRef,
1888        IncomingBody: Send + Sync + 'static,
1889        ResponseBody: From<IncomingBody>,
1890        R: RetryRule<Request<RetryBody>, Response, OpaqueError>,
1891        P: PrepareBody,
1892    {
1893        let client = self.build_client::<RetryBody, ModifiedBody, ConnResponse>();
1894        let rule = with_recovery(application_rule, |error: &OpaqueError| {
1895            is_early_data_rejected(error)
1896        });
1897        Retry::new(
1898            ManagedPolicy::new(rule).with_prepare_body(prepare_body),
1899            MapInput::new(client, permit_attempt),
1900        )
1901    }
1902
1903    /// Build a [`super::EasyHttpWebClient`] using the currently configured connector
1904    pub fn build_client<Body, ModifiedBody, ConnResponse>(
1905        self,
1906    ) -> super::EasyHttpWebClient<Body, T::Output, ()>
1907    where
1908        Body: StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
1909        ModifiedBody:
1910            StreamingBody<Data: Send + 'static, Error: Into<BoxError>> + Unpin + Send + 'static,
1911        T: Service<
1912                Request<Body>,
1913                Output = EstablishedClientConnection<ConnResponse, Request<ModifiedBody>>,
1914                Error: Into<BoxError>,
1915            >,
1916        ConnResponse: ExtensionsRef,
1917    {
1918        super::EasyHttpWebClient::new(self.connector)
1919    }
1920}
1921
1922impl<T, S, D, F> EasyHttpConnectorBuilder<T, S, D, F> {
1923    /// Build a connector from the currently configured setup
1924    pub fn build_connector(self) -> T {
1925        self.connector
1926    }
1927}
1928
1929#[cfg(test)]
1930mod tests {
1931    use super::*;
1932    use crate::http::{Body, client::ProxyConnectorBuilder};
1933    use rama_utils::octets::kib;
1934
1935    use rama_core::layer::layer_fn;
1936    #[cfg(feature = "quic")]
1937    use rama_dns::{
1938        client::resolver::*,
1939        wire::{Name, ServiceBinding, Txt},
1940    };
1941    #[cfg(all(
1942        feature = "quic",
1943        any(
1944            feature = "boring",
1945            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
1946        )
1947    ))]
1948    use {
1949        crate::http::client::Http3Connector,
1950        crate::quic::Endpoint,
1951        rama_core::futures::{Stream, stream},
1952        rama_http::layer::http_service::HttpServiceAttempt,
1953        rama_net::{
1954            address::{Domain, SocketAddress},
1955            client::ConnectionErrorKind,
1956            http::TargetHttpVersion as RequestedVersion,
1957        },
1958        std::{
1959            net::{Ipv4Addr, Ipv6Addr, SocketAddr},
1960            sync::{
1961                Arc,
1962                atomic::{AtomicUsize, Ordering},
1963            },
1964        },
1965    };
1966    #[cfg(feature = "tls")]
1967    use {
1968        crate::http::client::HttpConnIdentifier,
1969        crate::http::{
1970            HeaderMap, Version,
1971            conn::{HttpOrigin, SelectedHttpService},
1972            header::ALT_SVC,
1973        },
1974        rama_core::{ServiceInput, service::service_fn},
1975        rama_net::{
1976            Protocol,
1977            address::HostWithPort,
1978            client::{
1979                ConnectRequest,
1980                pool::{ConnID as _, ReqToConnID},
1981            },
1982        },
1983        rama_net::{
1984            http::TargetHttpVersion,
1985            tls::{ApplicationProtocol, ServerName},
1986        },
1987        rama_tls::client::{ServerVerifyMode, TlsPoolId, TlsServerVerify},
1988        rama_tls::{
1989            ProtocolVersion,
1990            client::{NegotiatedTlsParameters, TlsServerAuthentication},
1991        },
1992        std::convert::Infallible,
1993    };
1994
1995    fn assert_future_budget(connector: &impl Service<Request>, name: &str) {
1996        let request = Request::builder()
1997            .uri("https://example.com/")
1998            .body(Body::empty())
1999            .unwrap();
2000        let future = connector.serve(request);
2001        let size = std::mem::size_of_val(&future);
2002        assert!(
2003            size <= kib(64),
2004            "{name} connector future is {size} bytes; connector error adapters must not duplicate nested future storage"
2005        );
2006    }
2007
2008    #[tokio::test]
2009    async fn default_connector_futures_stay_within_stack_budget() {
2010        let builder = || {
2011            EasyHttpConnectorBuilder::new(WeakScope::detached())
2012                .with_default_transport_connector()
2013                .without_dns_connector()
2014                .without_proxy_support()
2015        };
2016        let plain = builder()
2017            .without_tls_support()
2018            .with_default_http_connector::<Body>()
2019            .with_default_connection_pool()
2020            .build_connector();
2021        assert_future_budget(&plain, "plain pooled");
2022        #[cfg(feature = "rustls")]
2023        {
2024            let pooled = builder()
2025                .with_tls_support_using_rustls(TlsClientConfig::new())
2026                .with_default_http_connector::<Body>()
2027                .with_default_connection_pool()
2028                .build_connector();
2029            assert_future_budget(&pooled, "rustls pooled");
2030            let unpooled = builder()
2031                .with_tls_support_using_rustls(TlsClientConfig::new())
2032                .with_default_http_connector::<Body>()
2033                .without_connection_pool()
2034                .build_connector();
2035            assert_future_budget(&unpooled, "rustls unpooled");
2036        }
2037    }
2038
2039    #[cfg(feature = "tls")]
2040    #[tokio::test]
2041    async fn custom_http_connector_discovers_h3_without_capability_configuration() {
2042        let cache = AltSvcCache::default();
2043        let origin =
2044            HttpOrigin::new(Protocol::HTTPS, HostWithPort::example_domain_https()).unwrap();
2045        let mut headers = HeaderMap::new();
2046        headers.insert(ALT_SVC, "h3=\":8443\"".parse().unwrap());
2047        cache.record(&origin, &headers, Duration::ZERO);
2048
2049        let builder = EasyHttpConnectorBuilder::new(WeakScope::detached())
2050            .with_custom_tcp_connector(())
2051            .without_dns_connector()
2052            .without_proxy_support()
2053            .without_tls_support()
2054            .with_custom_http_connector(layer_fn(|_| {
2055                service_fn(|input: ConnectRequest| async move {
2056                    let version = input
2057                        .extensions()
2058                        .get_ref::<TargetHttpVersion>()
2059                        .map_or(Version::HTTP_2, |version| version.0);
2060                    let conn = ServiceInput::new(());
2061                    conn.extensions.insert(TargetHttpVersion(version));
2062                    conn.extensions.insert(TlsServerAuthentication(Some(
2063                        ServerName::try_from(&input.authority.host).unwrap(),
2064                    )));
2065                    conn.extensions.insert(NegotiatedTlsParameters {
2066                        protocol_version: ProtocolVersion::TLSv1_3,
2067                        application_layer_protocol: Some(if version == Version::HTTP_3 {
2068                            ApplicationProtocol::HTTP_3
2069                        } else {
2070                            ApplicationProtocol::HTTP_2
2071                        }),
2072                        peer_certificate_chain: None,
2073                        server_name: None,
2074                        resumed: None,
2075                        algorithms: Default::default(),
2076                        server_hello: None,
2077                    });
2078                    Ok::<_, Infallible>(EstablishedClientConnection { input, conn })
2079                })
2080            }))
2081            .without_connection_pool()
2082            .with_alt_svc_cache(cache.clone());
2083        let connector = builder.build_connector();
2084        for _ in 0..2 {
2085            let established = connector
2086                .serve(
2087                    Request::builder()
2088                        .uri("https://example.com/")
2089                        .body(Body::empty())
2090                        .unwrap(),
2091                )
2092                .await
2093                .unwrap();
2094            assert!(
2095                established
2096                    .input
2097                    .extensions()
2098                    .contains::<SelectedHttpService>()
2099            );
2100            assert_eq!(established.input.version(), Version::HTTP_3);
2101            assert_eq!(
2102                established
2103                    .input
2104                    .extensions()
2105                    .get_ref::<SelectedHttpService>()
2106                    .unwrap()
2107                    .candidate
2108                    .target
2109                    .port,
2110                8443
2111            );
2112        }
2113    }
2114
2115    #[tokio::test]
2116    async fn https_proxy_without_available_tls_support_is_rejected_before_dial() {
2117        use rama_core::{ServiceInput, service::service_fn};
2118        use rama_net::{
2119            Protocol,
2120            address::HostWithPort,
2121            client::{ConnectionErrorDomain, ConnectorService as _, ProxyRoute},
2122        };
2123        use std::sync::{
2124            Arc,
2125            atomic::{AtomicUsize, Ordering},
2126        };
2127
2128        let dials = Arc::new(AtomicUsize::new(0));
2129        let transport = service_fn({
2130            let dials = dials.clone();
2131            move |_: ConnectRequest| {
2132                dials.fetch_add(1, Ordering::Relaxed);
2133                async {
2134                    Err::<
2135                        EstablishedClientConnection<
2136                            ServiceInput<tokio::io::DuplexStream>,
2137                            ConnectRequest,
2138                        >,
2139                        _,
2140                    >(ConnectionError::local(
2141                        BoxError::from_static_str("the proxy must not be dialed"),
2142                        ConnectionErrorKind::Unavailable,
2143                    ))
2144                }
2145            }
2146        });
2147        let ProxyConnectorParts { connect, .. } = ProxyConnectorBuilder::new(WeakScope::detached())
2148            .with_custom_tcp_connector(transport)
2149            .without_dns_connector()
2150            .without_tls_support()
2151            .with_default_http_connector::<Body>()
2152            .without_connection_pool()
2153            .with_http_connect()
2154            .build()
2155            .into_parts();
2156
2157        let input = ConnectRequest::new(HostWithPort::example_domain_http())
2158            .with_application_protocol(Protocol::HTTP);
2159        input.extensions.insert(ProxyRoute::Proxy(
2160            "https://proxy.example:8443".parse().unwrap(),
2161        ));
2162
2163        let error = connect.connect(input).await.unwrap_err();
2164
2165        assert_eq!(error.domain(), ConnectionErrorDomain::Transport);
2166        assert_eq!(error.kind(), ConnectionErrorKind::Protocol);
2167        assert_eq!(dials.load(Ordering::Relaxed), 0);
2168    }
2169
2170    #[test]
2171    fn custom_tls_proxy_layer_requires_no_builtin_provider() {
2172        ProxyConnectorBuilder::new(WeakScope::detached())
2173            .with_custom_tcp_connector(())
2174            .without_dns_connector()
2175            .with_custom_tls_connector(layer_fn(|inner| inner))
2176            .with_default_http_connector::<Body>();
2177    }
2178
2179    #[cfg(feature = "tls")]
2180    #[tokio::test]
2181    async fn a_refused_http3_alternative_is_served_over_the_stream_and_not_retried() {
2182        use std::sync::Arc;
2183
2184        let cache = AltSvcCache::default();
2185        let origin =
2186            HttpOrigin::new(Protocol::HTTPS, HostWithPort::example_domain_https()).unwrap();
2187        let mut headers = HeaderMap::new();
2188        headers.insert(ALT_SVC, "h3=\":8443\"".parse().unwrap());
2189        cache.record(&origin, &headers, Duration::ZERO);
2190
2191        let attempts = Arc::new(parking_lot::Mutex::new(Vec::new()));
2192        let connector = EasyHttpConnectorBuilder::new(WeakScope::detached())
2193            .with_custom_tcp_connector(())
2194            .without_dns_connector()
2195            .without_proxy_support()
2196            .without_tls_support()
2197            .with_custom_http_connector(layer_fn({
2198                let attempts = attempts.clone();
2199                move |_| {
2200                    let attempts = attempts.clone();
2201                    service_fn(move |input: ConnectRequest| {
2202                        let version = input
2203                            .extensions()
2204                            .get_ref::<TargetHttpVersion>()
2205                            .map_or(Version::HTTP_11, |version| version.0);
2206                        attempts.lock().push(version);
2207                        async move {
2208                            if version == Version::HTTP_3 {
2209                                // What a proxy refusing CONNECT-UDP answers with.
2210                                return Err(ConnectionError::transport(
2211                                    BoxError::from_static_str("connect-udp is not available"),
2212                                    ConnectionErrorKind::Unavailable,
2213                                ));
2214                            }
2215                            let conn = ServiceInput::new(());
2216                            conn.extensions.insert(TargetHttpVersion(version));
2217                            Ok(EstablishedClientConnection { input, conn })
2218                        }
2219                    })
2220                }
2221            }))
2222            .without_connection_pool()
2223            .with_alt_svc_cache(cache)
2224            .build_connector();
2225
2226        for _ in 0..2 {
2227            let request = Request::builder()
2228                .uri("https://example.com/")
2229                .body(Body::empty())
2230                .unwrap();
2231            let established = connector.serve(request).await.unwrap();
2232            assert_eq!(established.input.version(), Version::HTTP_11);
2233        }
2234
2235        let attempts = attempts.lock();
2236        assert_eq!(
2237            attempts
2238                .iter()
2239                .filter(|version| **version == Version::HTTP_3)
2240                .count(),
2241            1,
2242            "a refused alternative is not tried again: {attempts:?}"
2243        );
2244    }
2245
2246    #[cfg(feature = "tls")]
2247    #[test]
2248    fn custom_fixed_policy_pool_respects_explicit_override_identity() {
2249        let identifier = HttpConnIdentifier::default();
2250        let input = ConnectRequest::new(HostWithPort::example_domain_https());
2251        let fixed = identifier.id(&input).unwrap();
2252        assert!(fixed.is_reusable());
2253        let policy = TlsPoolId::builder()
2254            .with_verify(&TlsServerVerify(ServerVerifyMode::Disable))
2255            .build()
2256            .unwrap();
2257        input.extensions.insert(policy);
2258        let overridden = identifier.id(&input).unwrap();
2259        assert!(overridden.is_reusable());
2260        assert_ne!(fixed, overridden);
2261        assert_eq!(overridden, identifier.id(&input).unwrap());
2262        input.extensions.insert(TlsPoolId::non_reusable());
2263        assert!(!identifier.id(&input).unwrap().is_reusable());
2264    }
2265
2266    #[cfg(all(
2267        feature = "quic",
2268        any(
2269            feature = "boring",
2270            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2271        )
2272    ))]
2273    #[derive(Clone)]
2274    struct RecordingResolver {
2275        calls: Arc<AtomicUsize>,
2276    }
2277
2278    #[cfg(all(
2279        feature = "quic",
2280        any(
2281            feature = "boring",
2282            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2283        )
2284    ))]
2285    impl DnsAddressResolver for RecordingResolver {
2286        type Error = Infallible;
2287
2288        fn lookup_ipv4(
2289            &self,
2290            domain: Domain,
2291        ) -> impl Stream<Item = Result<Ipv4Addr, Self::Error>> + Send + '_ {
2292            assert_eq!(domain.as_str(), "private.invalid");
2293            self.calls.fetch_add(1, Ordering::Relaxed);
2294            stream::empty()
2295        }
2296
2297        fn lookup_ipv6(
2298            &self,
2299            domain: Domain,
2300        ) -> impl Stream<Item = Result<Ipv6Addr, Self::Error>> + Send + '_ {
2301            assert_eq!(domain.as_str(), "private.invalid");
2302            self.calls.fetch_add(1, Ordering::Relaxed);
2303            stream::empty()
2304        }
2305    }
2306
2307    #[cfg(all(
2308        feature = "quic",
2309        any(
2310            feature = "boring",
2311            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2312        )
2313    ))]
2314    struct RecordingDnsLayer {
2315        resolver: RecordingResolver,
2316        applied: Arc<AtomicUsize>,
2317    }
2318
2319    #[cfg(all(
2320        feature = "quic",
2321        any(
2322            feature = "boring",
2323            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2324        )
2325    ))]
2326    impl<S> Layer<S> for RecordingDnsLayer {
2327        type Service = DnsConnector<S, RecordingResolver>;
2328
2329        fn layer(&self, inner: S) -> Self::Service {
2330            self.applied.fetch_add(1, Ordering::Relaxed);
2331            DnsConnector::with_resolver(inner, self.resolver.clone())
2332        }
2333    }
2334
2335    #[cfg(all(
2336        feature = "quic",
2337        any(
2338            feature = "boring",
2339            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2340        )
2341    ))]
2342    #[tokio::test]
2343    async fn a_quic_only_client_dials_a_plain_request_over_quic() {
2344        async fn assert_quic_is_dialed(
2345            connector: impl Service<Request, Error: Send>,
2346            dials: &AtomicUsize,
2347        ) {
2348            // An address target keeps this test clear of DNS; a QUIC domain needs a resolver.
2349            let request = Request::builder()
2350                .uri("https://127.0.0.1:8443/")
2351                .body(Body::empty())
2352                .unwrap();
2353            let Err(_) = connector.serve(request).await else {
2354                panic!("a client with only a QUIC leg has no origin to reach here")
2355            };
2356            assert_eq!(
2357                dials.load(Ordering::Relaxed),
2358                1,
2359                "a request without a version of its own is dialed over the QUIC leg"
2360            );
2361        }
2362
2363        let quic_only = |dials: Arc<AtomicUsize>| {
2364            let endpoints = service_fn(move |_: ConnectRequest| {
2365                dials.fetch_add(1, Ordering::Relaxed);
2366                async {
2367                    Err::<
2368                        EstablishedClientConnection<
2369                            crate::quic::client::ClientEndpoint,
2370                            ConnectRequest,
2371                        >,
2372                        _,
2373                    >(ConnectionError::local(
2374                        BoxError::from_static_str("no endpoint in this test"),
2375                        ConnectionErrorKind::Unavailable,
2376                    ))
2377                }
2378            });
2379            let builder = EasyHttpConnectorBuilder::new(WeakScope::detached())
2380                .with_custom_quic_connector(endpoints)
2381                .without_dns_connector()
2382                .without_proxy_support();
2383            #[cfg(feature = "boring")]
2384            let builder = builder.with_tls_support_using_boringssl(TlsClientConfig::new());
2385            #[cfg(not(feature = "boring"))]
2386            let builder = builder.with_tls_support_using_rustls(TlsClientConfig::new());
2387            builder.with_default_http_connector::<Body>()
2388        };
2389
2390        let dials = Arc::new(AtomicUsize::new(0));
2391        let connector = quic_only(dials.clone())
2392            .without_connection_pool()
2393            .build_connector();
2394        assert_quic_is_dialed(connector, &dials).await;
2395
2396        // A custom pool serves connect requests of its own, without the request adapters.
2397        let dials = Arc::new(AtomicUsize::new(0));
2398        let config = HttpPooledConnectorConfig::default();
2399        let connector = quic_only(dials.clone())
2400            .with_custom_connection_pool(
2401                config.build_pool(),
2402                HttpConnIdentifier::default(),
2403                config.wait_for_pool_timeout,
2404            )
2405            .build_connector();
2406        let input = ConnectRequest::new("127.0.0.1:8443".parse().unwrap())
2407            .with_application_protocol(Protocol::HTTPS);
2408        let Err(_) = connector.serve(input).await else {
2409            panic!("a client with only a QUIC leg has no origin to reach here")
2410        };
2411        assert_eq!(
2412            dials.load(Ordering::Relaxed),
2413            1,
2414            "a client with a custom pool dials over the QUIC leg too"
2415        );
2416    }
2417
2418    #[cfg(all(
2419        feature = "quic",
2420        any(
2421            feature = "boring",
2422            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2423        )
2424    ))]
2425    #[tokio::test]
2426    async fn built_in_quic_uses_the_configured_dns_resolver() {
2427        let calls = Arc::new(AtomicUsize::new(0));
2428        let applied = Arc::new(AtomicUsize::new(0));
2429        let builder = EasyHttpConnectorBuilder::new(WeakScope::detached())
2430            .with_default_transport_connector()
2431            .with_dns_connector(RecordingDnsLayer {
2432                resolver: RecordingResolver {
2433                    calls: calls.clone(),
2434                },
2435                applied: applied.clone(),
2436            })
2437            .without_proxy_support();
2438        #[cfg(feature = "boring")]
2439        let builder = builder.with_tls_support_using_boringssl(TlsClientConfig::new());
2440        #[cfg(not(feature = "boring"))]
2441        let builder = builder.with_tls_support_using_rustls(TlsClientConfig::new());
2442        let connector = builder
2443            .with_default_http_connector::<Body>()
2444            .build_connector();
2445        let input = ConnectRequest::new("private.invalid:443".parse().unwrap())
2446            .with_application_protocol(Protocol::HTTPS);
2447        input.extensions.insert(RequestedVersion(Version::HTTP_3));
2448        let error = connector.serve(input).await.err().unwrap();
2449        assert_eq!(error.kind(), ConnectionErrorKind::Unavailable);
2450        assert!(calls.load(Ordering::Relaxed) > 0);
2451        assert_eq!(
2452            applied.load(Ordering::Relaxed),
2453            2,
2454            "the same DNS layer must wrap both transports"
2455        );
2456    }
2457
2458    #[cfg(all(
2459        feature = "quic",
2460        any(
2461            feature = "boring",
2462            all(feature = "rustls", any(feature = "ring", feature = "aws-lc"))
2463        )
2464    ))]
2465    #[tokio::test]
2466    async fn ipv4_quic_endpoint_skips_ipv6_candidates_without_terminal_failure() {
2467        let scope = WeakScope::detached();
2468        let endpoint = Endpoint::bind_client(scope.clone(), SocketAddress::local_ipv4(0))
2469            .await
2470            .unwrap();
2471        let blackhole = tokio::net::UdpSocket::bind(SocketAddr::from(SocketAddress::local_ipv4(0)))
2472            .await
2473            .unwrap();
2474        let connector = Http3Connector::builder(scope)
2475            .with_endpoint(endpoint.clone())
2476            .build()
2477            .await
2478            .unwrap();
2479        // Supply the incompatible candidate first, independent of DNS scheduling.
2480        struct LoopbackCandidates(Domain);
2481
2482        impl rama_net::client::AddressCandidates for LoopbackCandidates {
2483            fn domain(&self) -> &Domain {
2484                &self.0
2485            }
2486
2487            fn stream<'a>(
2488                &'a self,
2489                _: &'a rama_core::extensions::Extensions,
2490            ) -> stream::BoxStream<'a, Result<std::net::IpAddr, BoxError>> {
2491                Box::pin(stream::iter([
2492                    Ok(Ipv6Addr::LOCALHOST.into()),
2493                    Ok(Ipv4Addr::LOCALHOST.into()),
2494                ]))
2495            }
2496        }
2497
2498        let domain = Domain::from_static("private.invalid");
2499        let target = HostWithPort::new(
2500            domain.clone().into(),
2501            blackhole.local_addr().unwrap().port(),
2502        );
2503        let input = ConnectRequest::new(target.clone()).with_application_protocol(Protocol::HTTPS);
2504        input
2505            .extensions
2506            .insert(rama_net::client::ConnectorTargetStream::new(
2507                target,
2508                LoopbackCandidates(domain),
2509            ));
2510        let attempt = Arc::new(HttpServiceAttempt::default());
2511        input.extensions.insert_arc(attempt.clone());
2512        let mut packet = [0; 1500];
2513        tokio::select! {
2514            _ = connector.serve(input) => panic!("QUIC connection finished before the IPv4 dial"),
2515            result = tokio::time::timeout(Duration::from_secs(10), blackhole.recv(&mut packet)) => {
2516                assert!(result.expect("no IPv4 QUIC packet").unwrap() > 0);
2517            }
2518        }
2519        assert!(
2520            !attempt.failed(),
2521            "a mismatched candidate family must not turn the IPv4 timeout into an authentication failure"
2522        );
2523        endpoint.close(0u32, b"test complete");
2524    }
2525    #[cfg(feature = "quic")]
2526    #[tokio::test]
2527    async fn default_https_discovery_accepts_a_custom_resolver_and_can_be_disabled() {
2528        use rama_core::futures::{Stream, stream};
2529        use rama_net::address::Domain;
2530        use std::{
2531            net::{Ipv4Addr, Ipv6Addr},
2532            sync::{
2533                Arc,
2534                atomic::{AtomicUsize, Ordering},
2535            },
2536        };
2537
2538        #[derive(Clone, Default)]
2539        struct Resolver(Arc<AtomicUsize>, Arc<AtomicUsize>);
2540        impl DnsAddressResolver for Resolver {
2541            type Error = BoxError;
2542            fn lookup_ipv4(
2543                &self,
2544                _: Domain,
2545            ) -> impl Stream<Item = Result<Ipv4Addr, BoxError>> + Send + '_ {
2546                self.1.fetch_add(1, Ordering::SeqCst);
2547                stream::empty()
2548            }
2549            fn lookup_ipv6(
2550                &self,
2551                _: Domain,
2552            ) -> impl Stream<Item = Result<Ipv6Addr, BoxError>> + Send + '_ {
2553                stream::empty()
2554            }
2555        }
2556        impl DnsCnameResolver for Resolver {
2557            type Error = BoxError;
2558            fn lookup_cname(
2559                &self,
2560                _: Domain,
2561            ) -> impl Stream<Item = Result<Name, BoxError>> + Send + '_ {
2562                stream::empty()
2563            }
2564        }
2565        impl DnsTxtResolver for Resolver {
2566            type Error = BoxError;
2567            fn lookup_txt(
2568                &self,
2569                _: Domain,
2570            ) -> impl Stream<Item = Result<Txt, BoxError>> + Send + '_ {
2571                stream::empty()
2572            }
2573        }
2574        impl DnsServiceBindingResolver for Resolver {
2575            type Error = BoxError;
2576            fn lookup_svcb(
2577                &self,
2578                _: Domain,
2579            ) -> impl Stream<Item = Result<ServiceBindingRecord, BoxError>> + Send + '_
2580            {
2581                stream::empty()
2582            }
2583            fn lookup_https(
2584                &self,
2585                _: Domain,
2586            ) -> impl Stream<Item = Result<ServiceBindingRecord, BoxError>> + Send + '_
2587            {
2588                self.0.fetch_add(1, Ordering::SeqCst);
2589                stream::once(async {
2590                    Ok(ServiceBindingRecord {
2591                        owner: Name::from_presentation("origin.example").unwrap(),
2592                        binding: ServiceBinding::parse_rdata(&[0, 1, 0, 0, 1, 0, 3, 2, b'h', b'2'])
2593                            .unwrap(),
2594                    })
2595                })
2596            }
2597        }
2598        impl DnsResolver for Resolver {}
2599        for (shared, override_https, disabled) in [
2600            (true, false, false),
2601            (true, false, true),
2602            (false, false, false),
2603            (false, true, false),
2604        ] {
2605            let enabled = (shared || override_https) && !disabled;
2606            let resolver = Resolver::default();
2607            let selected = Arc::new(std::sync::atomic::AtomicBool::new(false));
2608            let builder =
2609                EasyHttpConnectorBuilder::new(WeakScope::detached()).with_custom_tcp_connector(());
2610            let builder = if shared {
2611                builder.with_dns_resolver(resolver.clone())
2612            } else {
2613                builder.with_dns_address_resolver(resolver.clone())
2614            };
2615            let builder = builder
2616                .without_proxy_support()
2617                .without_tls_support()
2618                .with_custom_http_connector(layer_fn({
2619                    let selected = selected.clone();
2620                    move |_inner| {
2621                        let selected = selected.clone();
2622                        service_fn(move |input: ConnectRequest| {
2623                            if input
2624                                .extensions()
2625                                .get_ref::<SelectedHttpService>()
2626                                .is_some_and(|service| {
2627                                    service.candidate.source
2628                                        == rama_http::conn::HttpServiceSource::Https
2629                                })
2630                            {
2631                                selected.store(true, Ordering::SeqCst);
2632                            }
2633                            async {
2634                                Err::<
2635                                    EstablishedClientConnection<ServiceInput<()>, ConnectRequest>,
2636                                    _,
2637                                >(ConnectionError::local(
2638                                    BoxError::from_static_str("test stopped before transport"),
2639                                    ConnectionErrorKind::Unavailable,
2640                                ))
2641                            }
2642                        })
2643                    }
2644                }))
2645                .without_connection_pool();
2646            let builder = if override_https {
2647                builder.with_https_resolver(resolver.clone())
2648            } else {
2649                builder
2650            };
2651            let builder = if disabled {
2652                builder.without_https_discovery()
2653            } else {
2654                builder
2655            };
2656            let error = builder
2657                .build_connector()
2658                .serve(
2659                    Request::builder()
2660                        .uri("https://origin.example/")
2661                        .body(Body::empty())
2662                        .unwrap(),
2663                )
2664                .await
2665                .unwrap_err();
2666            assert!(!error.to_string().is_empty());
2667            assert_eq!(resolver.0.load(Ordering::SeqCst), usize::from(enabled));
2668            assert_eq!(selected.load(Ordering::SeqCst), enabled);
2669            // This connector stops before transport: discovery must not start A/AAAA.
2670            assert_eq!(resolver.1.load(Ordering::SeqCst), 0);
2671        }
2672    }
2673
2674    #[cfg(all(feature = "boring", feature = "quic"))]
2675    #[tokio::test]
2676    async fn every_combination_of_legs_builds_a_connector() {
2677        let scope = WeakScope::detached();
2678        let tls = || TlsClientConfig::default_http();
2679
2680        drop(
2681            EasyHttpConnectorBuilder::new(scope.clone())
2682                .with_default_transport_connector()
2683                .with_default_dns_connector()
2684                .without_proxy_support()
2685                .with_tls_support_using_boringssl(tls())
2686                .with_default_http_connector::<Body>()
2687                .with_default_connection_pool()
2688                .build_connector(),
2689        );
2690
2691        drop(
2692            EasyHttpConnectorBuilder::new(scope.clone())
2693                .with_default_tcp_connector()
2694                .with_default_dns_connector()
2695                .without_proxy_support()
2696                .with_tls_support_using_boringssl(tls())
2697                .with_default_http_connector::<Body>()
2698                .with_default_connection_pool()
2699                .build_connector(),
2700        );
2701
2702        drop(
2703            EasyHttpConnectorBuilder::new(scope.clone())
2704                .with_default_transport_connector()
2705                .with_default_dns_connector()
2706                .with_proxy_support(ProxyConnector::default_with_scope::<Body>(scope.clone()))
2707                .with_tls_support_using_boringssl(tls())
2708                .with_default_http_connector::<Body>()
2709                .with_default_connection_pool()
2710                .build_connector(),
2711        );
2712
2713        drop(
2714            EasyHttpConnectorBuilder::new(scope.clone())
2715                .with_default_tcp_connector()
2716                .with_custom_quic_connector(SharedQuicEndpoint::managed(scope.clone()))
2717                .with_default_dns_connector()
2718                .without_proxy_support()
2719                .with_tls_support_using_boringssl(tls())
2720                .with_default_http_connector::<Body>()
2721                .without_connection_pool()
2722                .build_connector(),
2723        );
2724
2725        drop(
2726            EasyHttpConnectorBuilder::new(scope.clone())
2727                .with_custom_tcp_connector(TcpConnector::new())
2728                .with_default_quic_connector()
2729                .with_default_dns_connector()
2730                .without_proxy_support()
2731                .with_tls_support_using_boringssl(tls())
2732                .with_default_http_connector::<Body>()
2733                .without_connection_pool()
2734                .build_connector(),
2735        );
2736
2737        drop(
2738            EasyHttpConnectorBuilder::new(scope.clone())
2739                .with_default_quic_connector()
2740                .with_default_dns_connector()
2741                .without_proxy_support()
2742                .with_tls_support_using_boringssl(tls())
2743                .with_default_http_connector::<Body>()
2744                .with_default_connection_pool()
2745                .build_connector(),
2746        );
2747
2748        drop(
2749            EasyHttpConnectorBuilder::new(scope)
2750                .with_default_transport_connector()
2751                .without_dns_connector()
2752                .without_proxy_support()
2753                .without_tls_support()
2754                .with_default_http_connector::<Body>()
2755                .without_connection_pool()
2756                .build_connector(),
2757        );
2758    }
2759
2760    #[cfg(all(feature = "quic", feature = "boring"))]
2761    #[tokio::test]
2762    async fn a_tls_stage_without_quic_tls_provider_refuses_http3_explicitly() {
2763        use crate::quic::{client::ClientEndpoint, tls::TlsConfigError};
2764        use rama_core::{
2765            error::{BoxError, error_chain},
2766            service::service_fn,
2767        };
2768        use rama_net::client::ConnectionErrorKind;
2769        use std::sync::{
2770            Arc,
2771            atomic::{AtomicUsize, Ordering},
2772        };
2773
2774        let dials = Arc::new(AtomicUsize::new(0));
2775        let mut builder = EasyHttpConnectorBuilder::new(WeakScope::detached())
2776            .with_custom_quic_connector(service_fn({
2777                let dials = dials.clone();
2778                move |_: ConnectRequest| {
2779                    dials.fetch_add(1, Ordering::Relaxed);
2780                    async {
2781                        Err::<EstablishedClientConnection<ClientEndpoint, ConnectRequest>, _>(
2782                            ConnectionError::local(
2783                                BoxError::from_static_str("the QUIC leg must not be dialed"),
2784                                ConnectionErrorKind::Unavailable,
2785                            ),
2786                        )
2787                    }
2788                }
2789            }))
2790            .without_dns_connector()
2791            .without_proxy_support()
2792            .with_tls_support_using_boringssl(TlsClientConfig::new());
2793        builder.stage.quic_tls = None;
2794
2795        let Err(error) = builder
2796            .with_default_http_connector::<Body>()
2797            .without_connection_pool()
2798            .build_connector()
2799            .serve(
2800                Request::builder()
2801                    .uri("https://127.0.0.1:4433/")
2802                    .body(Body::empty())
2803                    .unwrap(),
2804            )
2805            .await
2806        else {
2807            panic!("an HTTP/3 dial without a QUIC TLS provider must fail");
2808        };
2809
2810        let unavailable = error_chain(&error).any(|error| {
2811            matches!(
2812                error.downcast_ref::<TlsConfigError>(),
2813                Some(TlsConfigError::BackendUnavailable)
2814            )
2815        });
2816        assert!(unavailable, "{error:?}");
2817        assert_eq!(dials.load(Ordering::Relaxed), 0);
2818    }
2819}