Skip to main content

aws_smithy_http_client/client/pool/
builder.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Construction and validation for [`ConnectionPool`].
7
8use super::establish::{self, TransportFactory};
9use super::events::{ConnectionEventListener, ConnectionEvents, SharedConnectionEventListener};
10use super::maintenance::MaintenanceConfig;
11use super::registry::{AdmissionPolicy, PartitionRegistry, PartitionRegistryError};
12use super::{ConnectionPool, ConnectionReuseScope, Partition, PoolConfig, PoolInner};
13use crate::client::connect::HttpProxyConnector;
14use crate::client::dns::HyperUtilResolver;
15use crate::client::{TlsProviderSelected, TlsUnset};
16use crate::proxy::ProxyConfig;
17use crate::sync::Arc;
18use crate::tls::{self, TlsContext};
19use aws_smithy_async::rt::sleep::{default_async_sleep, AsyncSleep, SharedAsyncSleep};
20use aws_smithy_async::time::{SharedTimeSource, TimeSource};
21#[cfg(any(
22    all(test, feature = "rt-tokio"),
23    all(feature = "test-util", aws_sdk_unstable)
24))]
25use aws_smithy_runtime_api::box_error::BoxError;
26use aws_smithy_runtime_api::client::dns::{ResolveDns, ResolveDnsError, SharedDnsResolver};
27use aws_smithy_runtime_api::shared::IntoShared;
28#[cfg(any(
29    all(test, feature = "rt-tokio"),
30    all(feature = "test-util", aws_sdk_unstable)
31))]
32use http_1x::Uri;
33use hyper_util::client::legacy::connect::dns::GaiResolver;
34use hyper_util::client::legacy::connect::dns::Name;
35use hyper_util::client::legacy::connect::HttpConnector;
36use std::error::Error;
37use std::fmt;
38use std::future::Future;
39use std::net::SocketAddr;
40use std::num::NonZeroUsize;
41use std::pin::Pin;
42use std::sync::atomic::AtomicU64;
43use std::task::{Context, Poll};
44use std::time::Duration;
45use tower::Service;
46
47/// Default duration for retaining an idle reusable connection.
48const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
49
50/// Default TCP keepalive probe interval for newly created sockets.
51///
52/// 30 seconds keeps connections alive well within the idle timeout of
53/// NAT gateways and firewalls without adding meaningful overhead.
54const DEFAULT_TCP_KEEPALIVE: Duration = Duration::from_secs(30);
55
56#[derive(Clone, Debug, Default, Eq, PartialEq)]
57enum TriStateOption<T> {
58    /// No option was set by the user, so construction applies its default.
59    #[default]
60    NotSet,
61    /// The option was explicitly unset, so construction does not apply a default.
62    ExplicitlyUnset,
63    /// The caller supplied this value.
64    Set(T),
65}
66
67impl<T> TriStateOption<T> {
68    /// Preserves the public nested-option setter contract internally.
69    fn from_nested(value: Option<Option<T>>) -> Self {
70        match value {
71            None => Self::NotSet,
72            Some(None) => Self::ExplicitlyUnset,
73            Some(Some(value)) => Self::Set(value),
74        }
75    }
76
77    /// Resolves the setting, applying `default` only when it was never set.
78    fn resolve(self, default: Option<T>) -> Option<T> {
79        match self {
80            Self::NotSet => default,
81            Self::ExplicitlyUnset => None,
82            Self::Set(value) => Some(value),
83        }
84    }
85}
86
87/// Builds a partition-aware connection pool.
88#[derive(Clone)]
89pub struct Builder<Tls = TlsUnset> {
90    /// Idle retention setting, including explicit disablement.
91    idle_timeout: TriStateOption<Duration>,
92    /// Clock used to assign and evaluate idle deadlines.
93    time_source: Option<SharedTimeSource>,
94    /// Runtime timer used by idle maintenance.
95    sleep_impl: Option<SharedAsyncSleep>,
96    /// Whether newly created TCP sockets disable Nagle's algorithm.
97    tcp_nodelay: bool,
98    /// TCP keepalive setting, including explicit disablement.
99    tcp_keepalive: TriStateOption<Duration>,
100    /// Optional live-connection limit per scheme, host, and port.
101    max_connections_per_host: Option<usize>,
102    /// Partitions allowed to reuse each other's connections.
103    reuse_scope: ConnectionReuseScope,
104    /// Complete explicit partition set, or `None` for anonymous topology.
105    partitions: Option<Vec<Partition>>,
106    /// Pool-wide proxy selection, authentication, and bypass policy.
107    proxy_config: ProxyConfig,
108    /// Caller-supplied DNS resolver, or `None` for the client default.
109    dns_resolver: Option<SharedDnsResolver>,
110    /// Optional listener for every connection lifecycle event from this pool.
111    event_listener: Option<SharedConnectionEventListener>,
112    /// TLS typestate carried into protocol-specific terminal builders.
113    tls: Tls,
114}
115
116/// Connection-pool builder with a TLS provider selected.
117///
118/// Created by [`Builder::tls_provider`]. HTTPS construction requires an enabled
119/// TLS provider feature.
120pub type HttpsBuilder = Builder<TlsProviderSelected>;
121
122impl Default for Builder<TlsUnset> {
123    fn default() -> Self {
124        Self {
125            idle_timeout: TriStateOption::NotSet,
126            time_source: None,
127            sleep_impl: None,
128            tcp_nodelay: true,
129            tcp_keepalive: TriStateOption::Set(DEFAULT_TCP_KEEPALIVE),
130            max_connections_per_host: None,
131            reuse_scope: ConnectionReuseScope::default(),
132            partitions: None,
133            proxy_config: ProxyConfig::disabled(),
134            dns_resolver: None,
135            event_listener: None,
136            tls: TlsUnset {},
137        }
138    }
139}
140
141impl<Tls: fmt::Debug> fmt::Debug for Builder<Tls> {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct("Builder")
144            .field("idle_timeout", &self.idle_timeout)
145            .field("time_source", &self.time_source)
146            .field("sleep_impl", &self.sleep_impl)
147            .field("tcp_nodelay", &self.tcp_nodelay)
148            .field("tcp_keepalive", &self.tcp_keepalive)
149            .field("max_connections_per_host", &self.max_connections_per_host)
150            .field("reuse_scope", &self.reuse_scope)
151            .field("partitions", &self.partitions.as_ref().map(Vec::len))
152            .field(
153                "proxy_config",
154                &if self.proxy_config.is_disabled() {
155                    "disabled"
156                } else if self.proxy_config.is_from_env() {
157                    "environment"
158                } else {
159                    "configured"
160                },
161            )
162            .field(
163                "dns_resolver",
164                &if self.dns_resolver.is_some() {
165                    "custom"
166                } else {
167                    "default"
168                },
169            )
170            .field(
171                "event_listener",
172                &if self.event_listener.is_some() {
173                    "configured"
174                } else {
175                    "disabled"
176                },
177            )
178            .field("tls", &self.tls)
179            .finish()
180    }
181}
182
183impl<Tls> Builder<Tls> {
184    /// Sets how long a reusable idle connection remains in the pool.
185    ///
186    /// Passing `None` disables idle expiration. When unset, the pool uses a
187    /// 90-second timeout.
188    pub fn idle_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
189        self.idle_timeout = match timeout.into() {
190            Some(timeout) => TriStateOption::Set(timeout),
191            None => TriStateOption::ExplicitlyUnset,
192        };
193        self
194    }
195
196    /// Mutably sets the idle timeout.
197    ///
198    /// The outer `None` restores the default; `Some(None)` disables expiry.
199    pub fn set_idle_timeout(&mut self, timeout: Option<Option<Duration>>) -> &mut Self {
200        self.idle_timeout = TriStateOption::from_nested(timeout);
201        self
202    }
203
204    /// Sets the clock used by pool maintenance and connection timing.
205    pub fn time_source(mut self, source: impl TimeSource + 'static) -> Self {
206        self.time_source = Some(SharedTimeSource::new(source));
207        self
208    }
209
210    /// Mutably sets the clock used by pool maintenance and connection timing.
211    pub fn set_time_source(&mut self, source: Option<SharedTimeSource>) -> &mut Self {
212        self.time_source = source;
213        self
214    }
215
216    /// Sets the sleep implementation used by pool maintenance.
217    pub fn sleep_impl(mut self, sleep: impl AsyncSleep + 'static) -> Self {
218        self.sleep_impl = Some(SharedAsyncSleep::new(sleep));
219        self
220    }
221
222    /// Mutably sets the sleep implementation used by pool maintenance.
223    pub fn set_sleep_impl(&mut self, sleep: Option<SharedAsyncSleep>) -> &mut Self {
224        self.sleep_impl = sleep;
225        self
226    }
227
228    /// Configures `TCP_NODELAY` for newly created sockets.
229    pub fn tcp_nodelay(mut self, enabled: bool) -> Self {
230        self.tcp_nodelay = enabled;
231        self
232    }
233
234    /// Mutably configures `TCP_NODELAY`.
235    pub fn set_tcp_nodelay(&mut self, enabled: bool) -> &mut Self {
236        self.tcp_nodelay = enabled;
237        self
238    }
239
240    /// Configures TCP keepalive for newly created sockets.
241    pub fn tcp_keepalive(mut self, time: impl Into<Option<Duration>>) -> Self {
242        self.tcp_keepalive = match time.into() {
243            Some(time) => TriStateOption::Set(time),
244            None => TriStateOption::ExplicitlyUnset,
245        };
246        self
247    }
248
249    /// Mutably configures TCP keepalive.
250    pub fn set_tcp_keepalive(&mut self, time: Option<Option<Duration>>) -> &mut Self {
251        self.tcp_keepalive = TriStateOption::from_nested(time);
252        self
253    }
254
255    /// Bounds connection capacity for one origin across every pool partition.
256    ///
257    /// An origin is a scheme, host, and port, so `https://example.com` and
258    /// `http://example.com` are bounded separately, as is each non-default
259    /// port. Establishing, idle, and active connections occupy capacity.
260    /// Logical close normally returns capacity while accepted work drains.
261    /// An HTTP/1 upgrade retains capacity until the caller releases upgraded
262    /// I/O. This is not an idle-connection limit.
263    pub fn max_connections_per_host(mut self, limit: usize) -> Self {
264        self.max_connections_per_host = Some(limit);
265        self
266    }
267
268    /// Mutably sets the connection-capacity bound described by
269    /// [`Builder::max_connections_per_host`].
270    pub fn set_max_connections_per_host(&mut self, limit: Option<usize>) -> &mut Self {
271        self.max_connections_per_host = limit;
272        self
273    }
274
275    /// Selects which partitions may reuse each other's connections.
276    pub fn connection_reuse_scope(mut self, scope: ConnectionReuseScope) -> Self {
277        self.reuse_scope = scope;
278        self
279    }
280
281    /// Mutably selects the connection reuse scope.
282    pub fn set_connection_reuse_scope(&mut self, scope: ConnectionReuseScope) -> &mut Self {
283        self.reuse_scope = scope;
284        self
285    }
286
287    /// Returns whether an explicit partition set is configured.
288    ///
289    /// An explicitly supplied empty set also returns `true`. Clearing the set
290    /// with [`Self::set_partitions`] and `None` restores anonymous partition
291    /// construction.
292    pub fn has_explicit_partitions(&self) -> bool {
293        self.partitions.is_some()
294    }
295
296    /// Declares the complete explicit partition set.
297    pub fn partitions(mut self, partitions: impl IntoIterator<Item = Partition>) -> Self {
298        self.partitions = Some(partitions.into_iter().collect());
299        self
300    }
301
302    /// Mutably declares or clears the explicit partition set.
303    pub fn set_partitions(&mut self, partitions: Option<Vec<Partition>>) -> &mut Self {
304        self.partitions = partitions;
305        self
306    }
307
308    /// Configures proxy selection for every connection established by this pool.
309    ///
310    /// The configuration applies across every partition. Proxying is disabled
311    /// unless this method is called.
312    pub fn proxy_config(mut self, config: ProxyConfig) -> Self {
313        self.proxy_config = config;
314        self
315    }
316
317    /// Mutably configures pool-wide proxy selection.
318    ///
319    /// Passing `None` disables proxying.
320    pub fn set_proxy_config(&mut self, config: Option<ProxyConfig>) -> &mut Self {
321        self.proxy_config = config.unwrap_or_else(ProxyConfig::disabled);
322        self
323    }
324
325    /// Configures the DNS resolver used by connections established by this pool.
326    ///
327    /// The resolver applies across every partition. When unset, the client uses
328    /// its default resolver, which currently delegates to the operating system.
329    pub fn dns_resolver(mut self, resolver: impl ResolveDns + 'static) -> Self {
330        self.dns_resolver = Some(resolver.into_shared());
331        self
332    }
333
334    /// Mutably configures the pool-wide DNS resolver.
335    ///
336    /// Passing `None` restores the client default.
337    pub fn set_dns_resolver(&mut self, resolver: Option<SharedDnsResolver>) -> &mut Self {
338        self.dns_resolver = resolver;
339        self
340    }
341
342    /// Observes connection establishment and installed-lifetime transitions.
343    ///
344    /// The listener applies to every partition. Each callback runs
345    /// synchronously on the task that completed the transition and after pool
346    /// locks are released. A listener must not block on work that requires
347    /// progress from that same task.
348    ///
349    /// Observation is disabled unless a listener is configured.
350    pub fn event_listener(mut self, listener: impl ConnectionEventListener) -> Self {
351        self.event_listener = Some(SharedConnectionEventListener::new(listener));
352        self
353    }
354
355    /// Mutably configures pool-wide connection lifecycle observation.
356    ///
357    /// Passing `None` disables observation. The callback contract is the same
358    /// as [`Builder::event_listener`].
359    pub fn set_event_listener(
360        &mut self,
361        listener: Option<SharedConnectionEventListener>,
362    ) -> &mut Self {
363        self.event_listener = listener;
364        self
365    }
366}
367
368impl Builder<TlsUnset> {
369    /// Selects the TLS provider used by HTTPS pool connections.
370    pub fn tls_provider(self, provider: tls::Provider) -> Builder<TlsProviderSelected> {
371        Builder {
372            idle_timeout: self.idle_timeout,
373            time_source: self.time_source,
374            sleep_impl: self.sleep_impl,
375            tcp_nodelay: self.tcp_nodelay,
376            tcp_keepalive: self.tcp_keepalive,
377            max_connections_per_host: self.max_connections_per_host,
378            reuse_scope: self.reuse_scope,
379            partitions: self.partitions,
380            proxy_config: self.proxy_config,
381            dns_resolver: self.dns_resolver,
382            event_listener: self.event_listener,
383            tls: TlsProviderSelected {
384                provider,
385                context: TlsContext::default(),
386            },
387        }
388    }
389}
390
391impl Builder<TlsProviderSelected> {
392    /// Builds a pool whose connector performs TLS and ALPN negotiation.
393    pub fn build_https(self) -> Result<ConnectionPool, BuildError> {
394        #[cfg(any(feature = "__rustls", feature = "s2n-tls"))]
395        {
396            self.build_https_enabled()
397        }
398        #[cfg(not(any(feature = "__rustls", feature = "s2n-tls")))]
399        {
400            // Provider has no variants here; exhaustiveness is compiler-checked.
401            match self.tls.provider {}
402        }
403    }
404}
405
406crate::cfg::cfg_tls! {
407    impl Builder<TlsProviderSelected> {
408        /// Sets provider-specific TLS configuration for HTTPS connections.
409        pub fn tls_context(mut self, context: TlsContext) -> Self {
410            self.tls.context = context;
411            self
412        }
413
414        /// Mutably sets provider-specific TLS configuration.
415        pub fn set_tls_context(&mut self, context: TlsContext) -> &mut Self {
416            self.tls.context = context;
417            self
418        }
419
420        /// Selects the resolver for the HTTPS transport.
421        fn build_https_enabled(self) -> Result<ConnectionPool, BuildError> {
422            let resolver = self.dns_resolver.clone();
423            match resolver {
424                Some(resolver) => {
425                    self.build_https_with_resolver(HyperUtilResolver { resolver })
426                }
427                None => self.build_https_with_resolver(DefaultResolver(GaiResolver::new())),
428            }
429        }
430
431        /// Builds an HTTPS transport around one concrete Hyper resolver.
432        fn build_https_with_resolver<R>(self, resolver: R) -> Result<ConnectionPool, BuildError>
433        where
434            R: tower::Service<Name> + Clone + Send + Sync + 'static,
435            R::Response: Iterator<Item = SocketAddr>,
436            R::Future: Send,
437            R::Error: Into<Box<dyn Error + Send + Sync>>,
438        {
439            validate_default_connector_interfaces(self.partitions.as_deref())?;
440            let provider = self.tls.provider.clone();
441            let context = self.tls.context.clone();
442            let proxy_config = self.proxy_config.clone();
443            match provider {
444                #[cfg(feature = "__rustls")]
445                tls::Provider::Rustls(crypto_mode) => {
446                    let tcp_nodelay = self.tcp_nodelay;
447                    let tcp_keepalive = self.tcp_keepalive.clone().resolve(Some(DEFAULT_TCP_KEEPALIVE));
448                    let transport = establish::from_cached_interface_connector(
449                        move |interface, alpn_protocols| {
450                            let mut connector =
451                                HttpConnector::new_with_resolver(resolver.clone());
452                            connector.set_nodelay(tcp_nodelay);
453                            connector.set_keepalive(tcp_keepalive);
454                            set_default_connector_interface(&mut connector, interface);
455                            tls::rustls_provider::build_connector::wrap_connector_with_alpn(
456                                connector,
457                                crypto_mode.clone(),
458                                &context,
459                                proxy_config.clone(),
460                                alpn_protocols,
461                            )
462                        },
463                        true,
464                    );
465                    self.build_with_transport(transport)
466                }
467                #[cfg(feature = "s2n-tls")]
468                tls::Provider::S2nTls => {
469                    let tcp_nodelay = self.tcp_nodelay;
470                    let tcp_keepalive = self.tcp_keepalive.clone().resolve(Some(DEFAULT_TCP_KEEPALIVE));
471                    let transport = establish::from_cached_interface_connector(
472                        move |interface, _alpn_protocols| {
473                            let mut connector =
474                                HttpConnector::new_with_resolver(resolver.clone());
475                            connector.set_nodelay(tcp_nodelay);
476                            connector.set_keepalive(tcp_keepalive);
477                            set_default_connector_interface(&mut connector, interface);
478                            tls::s2n_tls_provider::build_connector::wrap_connector(
479                                connector,
480                                &context,
481                                proxy_config.clone(),
482                            )
483                        },
484                        false,
485                    );
486                    self.build_with_transport(transport)
487                }
488            }
489        }
490    }
491}
492
493/// Reports a hyper-util resolver's failures as `ResolveDnsError`, so they are classified like
494/// a custom resolver's, as I/O.
495///
496/// The pool wraps its default resolver, `GaiResolver`, in this. getaddrinfo's error does not say
497/// which failures are permanent, so every DNS failure is retried.
498#[derive(Clone)]
499struct DefaultResolver<R>(R);
500
501impl<R> Service<Name> for DefaultResolver<R>
502where
503    R: Service<Name>,
504    R::Error: Into<Box<dyn Error + Send + Sync>>,
505    R::Future: Send + 'static,
506{
507    type Response = R::Response;
508    type Error = ResolveDnsError;
509    type Future = Pin<Box<dyn Future<Output = Result<R::Response, ResolveDnsError>> + Send>>;
510
511    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
512        self.0.poll_ready(cx).map_err(ResolveDnsError::new)
513    }
514
515    fn call(&mut self, name: Name) -> Self::Future {
516        let resolving = self.0.call(name);
517        Box::pin(async move { resolving.await.map_err(ResolveDnsError::new) })
518    }
519}
520
521impl Builder<TlsUnset> {
522    /// Builds a pool for cleartext HTTP connections.
523    ///
524    /// This method remains public for explicit cleartext endpoints and tests,
525    /// but is hidden from generated documentation because HTTPS with automatic
526    /// ALPN negotiation is the intended production entry point.
527    #[doc(hidden)]
528    pub fn build_http(self) -> Result<ConnectionPool, BuildError> {
529        let resolver = self.dns_resolver.clone();
530        match resolver {
531            Some(resolver) => self.build_http_with_resolver(HyperUtilResolver { resolver }),
532            None => self.build_http_with_resolver(DefaultResolver(GaiResolver::new())),
533        }
534    }
535
536    /// Builds a cleartext transport around one concrete Hyper resolver.
537    fn build_http_with_resolver<R>(self, resolver: R) -> Result<ConnectionPool, BuildError>
538    where
539        R: tower::Service<Name> + Clone + Send + Sync + 'static,
540        R::Response: Iterator<Item = SocketAddr>,
541        R::Future: Send,
542        R::Error: Into<Box<dyn Error + Send + Sync>>,
543    {
544        validate_default_connector_interfaces(self.partitions.as_deref())?;
545        let tcp_nodelay = self.tcp_nodelay;
546        let tcp_keepalive = self
547            .tcp_keepalive
548            .clone()
549            .resolve(Some(DEFAULT_TCP_KEEPALIVE));
550        let proxy_config = self.proxy_config.clone();
551        let transport = if proxy_config.is_disabled() {
552            establish::from_interface_connector(move |interface| {
553                let mut connector = HttpConnector::new_with_resolver(resolver.clone());
554                connector.set_nodelay(tcp_nodelay);
555                connector.set_keepalive(tcp_keepalive);
556                set_default_connector_interface(&mut connector, interface);
557                connector
558            })
559        } else {
560            establish::from_interface_connector(move |interface| {
561                let mut connector = HttpConnector::new_with_resolver(resolver.clone());
562                connector.set_nodelay(tcp_nodelay);
563                connector.set_keepalive(tcp_keepalive);
564                set_default_connector_interface(&mut connector, interface);
565                HttpProxyConnector::new(connector, proxy_config.clone())
566            })
567        };
568        self.build_with_transport(transport)
569    }
570
571    /// Builds a pool around a test transport connector.
572    #[cfg(all(feature = "test-util", aws_sdk_unstable))]
573    #[doc(hidden)]
574    pub fn build_http_with_tcp_connector<C, IO>(
575        self,
576        connector: C,
577    ) -> Result<ConnectionPool, BuildError>
578    where
579        C: Service<Uri, Response = IO> + Clone + Send + Sync + 'static,
580        C::Error: Into<BoxError>,
581        C::Future: Send + 'static,
582        IO: hyper::rt::Read
583            + hyper::rt::Write
584            + hyper_util::client::legacy::connect::Connection
585            + Send
586            + Sync
587            + Unpin
588            + 'static,
589    {
590        self.build_with_transport(establish::from_connector(connector))
591    }
592
593    #[cfg(all(test, feature = "rt-tokio"))]
594    pub(super) fn build_with_connector<C, IO>(
595        self,
596        connector: C,
597    ) -> Result<ConnectionPool, BuildError>
598    where
599        C: Service<Uri, Response = IO> + Clone + Send + Sync + 'static,
600        C::Error: Into<BoxError>,
601        C::Future: Send + 'static,
602        IO: hyper::rt::Read
603            + hyper::rt::Write
604            + hyper_util::client::legacy::connect::Connection
605            + Send
606            + Sync
607            + Unpin
608            + 'static,
609    {
610        self.build_with_transport(establish::from_connector(connector))
611    }
612}
613
614impl<Tls> Builder<Tls> {
615    /// Builds a pool with a transport supplied by a pool-internal test.
616    #[cfg(test)]
617    pub(super) fn build_with_transport_for_test(
618        self,
619        transport: std::sync::Arc<dyn TransportFactory>,
620    ) -> Result<ConnectionPool, BuildError> {
621        self.build_with_transport(transport)
622    }
623
624    /// Validates pool policy and installs the type-erased transport factory.
625    fn build_with_transport(
626        self,
627        transport: std::sync::Arc<dyn TransportFactory>,
628    ) -> Result<ConnectionPool, BuildError> {
629        let max_connections_per_host = match self.max_connections_per_host {
630            Some(0) => {
631                return Err(BuildError::new(
632                    "max_connections_per_host must be greater than zero",
633                ))
634            }
635            Some(limit) => NonZeroUsize::new(limit),
636            None => None,
637        };
638        let idle_timeout = self.idle_timeout.resolve(Some(DEFAULT_IDLE_TIMEOUT));
639        let time_source = self.time_source.unwrap_or_default();
640        let sleep_impl = self.sleep_impl.or_else(default_async_sleep);
641        if idle_timeout.is_some() && sleep_impl.is_none() {
642            return Err(BuildError::new(
643                "idle_timeout requires an async sleep implementation",
644            ));
645        }
646        let maintenance = MaintenanceConfig {
647            idle_timeout,
648            time_source: time_source.clone(),
649            sleep: sleep_impl.clone(),
650        };
651        let admission_policy = max_connections_per_host
652            .map(|limit| AdmissionPolicy::new(limit, transport.can_guarantee_http1()));
653        let registry = PartitionRegistry::new(
654            self.partitions,
655            self.reuse_scope,
656            admission_policy,
657            maintenance,
658        )
659        .map_err(BuildError::from)?;
660        let config = PoolConfig {
661            idle_timeout,
662            max_connections_per_host,
663            reuse_scope: self.reuse_scope,
664        };
665        Ok(ConnectionPool {
666            inner: Arc::new(PoolInner {
667                config,
668                registry,
669                transport,
670                connection_events: ConnectionEvents::new(self.event_listener, time_source),
671                next_connection_id: AtomicU64::new(0),
672            }),
673        })
674    }
675}
676
677/// Error returned when a pool configuration is internally inconsistent.
678#[derive(Debug)]
679pub struct BuildError {
680    /// Stable configuration diagnostic.
681    message: String,
682}
683
684impl BuildError {
685    fn new(message: impl Into<String>) -> Self {
686        Self {
687            message: message.into(),
688        }
689    }
690}
691
692impl fmt::Display for BuildError {
693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
694        self.message.fmt(f)
695    }
696}
697
698impl Error for BuildError {}
699
700impl From<PartitionRegistryError> for BuildError {
701    fn from(error: PartitionRegistryError) -> Self {
702        Self::new(error.to_string())
703    }
704}
705
706/// Rejects interface values the default connector cannot convert to its
707/// platform socket representation.
708#[cfg(any(
709    target_os = "android",
710    target_os = "fuchsia",
711    target_os = "illumos",
712    target_os = "ios",
713    target_os = "linux",
714    target_os = "macos",
715    target_os = "solaris",
716    target_os = "tvos",
717    target_os = "visionos",
718    target_os = "watchos",
719))]
720fn validate_default_connector_interfaces(
721    partitions: Option<&[Partition]>,
722) -> Result<(), BuildError> {
723    if let Some(partition) = partitions.into_iter().flatten().find(|partition| {
724        partition
725            .interface_name()
726            .is_some_and(|interface| interface.as_bytes().contains(&0))
727    }) {
728        return Err(BuildError::new(format!(
729            "partition {:?} has an invalid network-interface name",
730            partition.id()
731        )));
732    }
733    Ok(())
734}
735
736/// Performs no interface validation on targets without connector support.
737#[cfg(not(any(
738    target_os = "android",
739    target_os = "fuchsia",
740    target_os = "illumos",
741    target_os = "ios",
742    target_os = "linux",
743    target_os = "macos",
744    target_os = "solaris",
745    target_os = "tvos",
746    target_os = "visionos",
747    target_os = "watchos",
748)))]
749fn validate_default_connector_interfaces(
750    _partitions: Option<&[Partition]>,
751) -> Result<(), BuildError> {
752    Ok(())
753}
754
755/// Applies this partition's interface to the default connector.
756#[cfg(any(
757    target_os = "android",
758    target_os = "fuchsia",
759    target_os = "illumos",
760    target_os = "ios",
761    target_os = "linux",
762    target_os = "macos",
763    target_os = "solaris",
764    target_os = "tvos",
765    target_os = "visionos",
766    target_os = "watchos",
767))]
768fn set_default_connector_interface<R>(connector: &mut HttpConnector<R>, interface: Option<&str>) {
769    if let Some(interface) = interface {
770        connector.set_interface(interface);
771    }
772}
773
774/// Leaves the default connector unchanged on unsupported targets.
775#[cfg(not(any(
776    target_os = "android",
777    target_os = "fuchsia",
778    target_os = "illumos",
779    target_os = "ios",
780    target_os = "linux",
781    target_os = "macos",
782    target_os = "solaris",
783    target_os = "tvos",
784    target_os = "visionos",
785    target_os = "watchos",
786)))]
787fn set_default_connector_interface<R>(_connector: &mut HttpConnector<R>, _interface: Option<&str>) {
788}
789
790#[cfg(all(test, not(smithy_http_client_loom)))]
791mod tests {
792    use super::*;
793    use crate::client::pool::partition::Spawn;
794    use crate::client::pool::{DriverSpawner, PartitionId};
795    use std::future::Future;
796    use std::net::IpAddr;
797    use std::pin::Pin;
798
799    #[derive(Debug)]
800    struct PendingSleep;
801
802    impl AsyncSleep for PendingSleep {
803        fn sleep(&self, _duration: Duration) -> aws_smithy_async::rt::sleep::Sleep {
804            aws_smithy_async::rt::sleep::Sleep::new(std::future::pending())
805        }
806    }
807
808    #[derive(Debug)]
809    struct TestSpawner;
810
811    impl Spawn for TestSpawner {
812        fn spawn(&self, driver: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
813            drop(driver);
814        }
815    }
816
817    #[derive(Debug)]
818    struct EmptyDnsResolver;
819
820    impl ResolveDns for EmptyDnsResolver {
821        fn resolve_dns<'a>(
822            &'a self,
823            _name: &'a str,
824        ) -> aws_smithy_runtime_api::client::dns::DnsFuture<'a> {
825            aws_smithy_runtime_api::client::dns::DnsFuture::ready(Ok(Vec::<IpAddr>::new()))
826        }
827    }
828
829    fn partition(index: usize) -> Partition {
830        Partition::new(
831            PartitionId::from_index(index),
832            DriverSpawner::new(TestSpawner),
833        )
834    }
835
836    #[test]
837    fn builder_preserves_unset_disabled_and_configured_settings() {
838        let mut builder = Builder::default();
839        assert_eq!(TriStateOption::NotSet, builder.idle_timeout);
840        assert_eq!(
841            TriStateOption::Set(DEFAULT_TCP_KEEPALIVE),
842            builder.tcp_keepalive
843        );
844        assert!(builder.tcp_nodelay);
845        assert_eq!(None, builder.max_connections_per_host);
846        assert!(builder.partitions.is_none());
847        assert!(builder.proxy_config.is_disabled());
848        assert!(builder.dns_resolver.is_none());
849        assert!(builder.event_listener.is_none());
850
851        builder.set_idle_timeout(Some(None));
852        builder.set_tcp_keepalive(Some(None));
853        assert_eq!(TriStateOption::ExplicitlyUnset, builder.idle_timeout);
854        assert_eq!(TriStateOption::ExplicitlyUnset, builder.tcp_keepalive);
855
856        builder.set_idle_timeout(Some(Some(Duration::from_secs(5))));
857        builder.set_tcp_keepalive(Some(Some(Duration::from_secs(10))));
858        builder.set_tcp_nodelay(false);
859        builder.set_max_connections_per_host(Some(3));
860        builder.set_partitions(Some(vec![partition(7)]));
861        assert_eq!(
862            TriStateOption::Set(Duration::from_secs(5)),
863            builder.idle_timeout
864        );
865        assert_eq!(
866            TriStateOption::Set(Duration::from_secs(10)),
867            builder.tcp_keepalive
868        );
869        assert!(!builder.tcp_nodelay);
870        assert_eq!(Some(3), builder.max_connections_per_host);
871        assert_eq!(1, builder.partitions.as_ref().unwrap().len());
872
873        builder.set_idle_timeout(None);
874        builder.set_tcp_keepalive(None);
875        builder.set_max_connections_per_host(None);
876        builder.set_partitions(None);
877        assert_eq!(TriStateOption::NotSet, builder.idle_timeout);
878        assert_eq!(TriStateOption::NotSet, builder.tcp_keepalive);
879        assert_eq!(None, builder.max_connections_per_host);
880        assert!(builder.partitions.is_none());
881    }
882
883    #[test]
884    fn proxy_and_dns_settings_set_reset_and_redact() {
885        let mut builder = Builder::default();
886        builder.set_proxy_config(Some(
887            ProxyConfig::http("http://proxy.test:8080")
888                .unwrap()
889                .with_basic_auth("secret-user", "secret-password"),
890        ));
891        builder.set_dns_resolver(Some(SharedDnsResolver::new(EmptyDnsResolver)));
892
893        assert!(!builder.proxy_config.is_disabled());
894        assert!(builder.dns_resolver.is_some());
895        let debug = format!("{builder:?}");
896        assert!(debug.contains("configured"));
897        assert!(debug.contains("custom"));
898        assert!(!debug.contains("secret-user"));
899        assert!(!debug.contains("secret-password"));
900
901        builder.set_proxy_config(None);
902        builder.set_dns_resolver(None);
903        assert!(builder.proxy_config.is_disabled());
904        assert!(builder.dns_resolver.is_none());
905    }
906
907    #[test]
908    fn event_listener_sets_resets_and_survives_tls_selection() {
909        let observed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
910        let mut builder = Builder::default().event_listener({
911            let observed = observed.clone();
912            move |_: &super::super::ConnectionEvent<'_>| {
913                observed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
914            }
915        });
916        assert!(builder.event_listener.is_some());
917
918        let shared = builder.event_listener.clone();
919        builder.set_event_listener(None);
920        assert!(builder.event_listener.is_none());
921        builder.set_event_listener(shared);
922        assert!(builder.event_listener.is_some());
923
924        #[cfg(feature = "rustls-ring")]
925        let builder = builder.tls_provider(tls::Provider::rustls(
926            tls::rustls_provider::CryptoMode::Ring,
927        ));
928        assert!(builder.event_listener.is_some());
929        assert_eq!(0, observed.load(std::sync::atomic::Ordering::Relaxed));
930    }
931
932    #[cfg(feature = "rustls-ring")]
933    #[test]
934    fn tls_selection_preserves_proxy_and_dns_settings() {
935        let builder = Builder::default()
936            .proxy_config(
937                ProxyConfig::http("http://proxy.test:8080")
938                    .unwrap()
939                    .with_basic_auth("secret-user", "secret-password"),
940            )
941            .dns_resolver(EmptyDnsResolver)
942            .tls_provider(tls::Provider::rustls(
943                tls::rustls_provider::CryptoMode::Ring,
944            ));
945
946        assert!(!builder.proxy_config.is_disabled());
947        assert!(builder.dns_resolver.is_some());
948        let debug = format!("{builder:?}");
949        assert!(debug.contains("configured"));
950        assert!(debug.contains("custom"));
951        assert!(!debug.contains("secret-user"));
952        assert!(!debug.contains("secret-password"));
953    }
954
955    #[test]
956    fn terminal_build_resolves_the_default_idle_timeout() {
957        let pool = Builder::default()
958            .sleep_impl(PendingSleep)
959            .build_http()
960            .unwrap();
961
962        assert_eq!(
963            Some(Duration::from_secs(90)),
964            pool.inner.config.idle_timeout
965        );
966    }
967
968    #[test]
969    fn terminal_build_preserves_explicitly_disabled_idle_timeout() {
970        let pool = Builder::default().idle_timeout(None).build_http().unwrap();
971
972        assert_eq!(None, pool.inner.config.idle_timeout);
973    }
974
975    #[test]
976    #[cfg(any(
977        target_os = "android",
978        target_os = "fuchsia",
979        target_os = "illumos",
980        target_os = "ios",
981        target_os = "linux",
982        target_os = "macos",
983        target_os = "solaris",
984        target_os = "tvos",
985        target_os = "visionos",
986        target_os = "watchos",
987    ))]
988    fn terminal_build_rejects_interface_names_with_nul_bytes() {
989        let error = Builder::default()
990            .partitions([partition(7).interface("eth\0invalid")])
991            .build_http()
992            .unwrap_err();
993        assert_eq!(
994            "partition PartitionId(7) has an invalid network-interface name",
995            error.to_string()
996        );
997    }
998
999    #[test]
1000    fn terminal_build_rejects_zero_connection_limit() {
1001        let error = Builder::default()
1002            .max_connections_per_host(0)
1003            .build_http()
1004            .unwrap_err();
1005        assert_eq!(
1006            "max_connections_per_host must be greater than zero",
1007            error.to_string()
1008        );
1009    }
1010
1011    #[test]
1012    fn terminal_build_rejects_empty_explicit_partition_set() {
1013        let error = Builder::default().partitions([]).build_http().unwrap_err();
1014        assert_eq!(
1015            "explicit partition set must not be empty",
1016            error.to_string()
1017        );
1018    }
1019
1020    #[test]
1021    fn terminal_build_rejects_duplicate_partition_ids() {
1022        let error = Builder::default()
1023            .partitions([partition(7), partition(7)])
1024            .build_http()
1025            .unwrap_err();
1026        assert_eq!(
1027            "duplicate partition identifier: PartitionId(7)",
1028            error.to_string()
1029        );
1030    }
1031
1032    #[test]
1033    fn terminal_build_rejects_reserved_anonymous_partition_id() {
1034        let error = Builder::default()
1035            .partitions([Partition::new(
1036                PartitionId::ANONYMOUS,
1037                DriverSpawner::new(TestSpawner),
1038            )])
1039            .build_http()
1040            .unwrap_err();
1041        assert_eq!(
1042            "the anonymous partition identifier is reserved",
1043            error.to_string()
1044        );
1045    }
1046
1047    /// A resolver that fails every lookup with an `io::Error`.
1048    #[derive(Clone)]
1049    struct FailingResolver;
1050
1051    impl Service<Name> for FailingResolver {
1052        type Response = std::vec::IntoIter<SocketAddr>;
1053        type Error = std::io::Error;
1054        type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
1055
1056        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1057            Poll::Ready(Ok(()))
1058        }
1059
1060        fn call(&mut self, name: Name) -> Self::Future {
1061            std::future::ready(Err(std::io::Error::other(format!(
1062                "no addresses for {name}"
1063            ))))
1064        }
1065    }
1066
1067    #[tokio::test]
1068    async fn default_resolver_failure_through_http_connector_is_io() {
1069        let mut connector = HttpConnector::new_with_resolver(DefaultResolver(FailingResolver));
1070
1071        let error = connector
1072            .call(http_1x::Uri::from_static("http://example.com/"))
1073            .await
1074            .expect_err("DNS resolution fails");
1075
1076        let error = crate::client::downcast_error(error.into());
1077        assert!(error.is_io(), "expected an I/O error, got {error:?}");
1078    }
1079}