eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Direct TCP connector with socket-level configuration.
//!
//! This connector provides the same DNS resolution + TCP connect flow as
//! `hyper_util::client::legacy::connect::HttpConnector`, but adds support
//! for:
//!
//! - **Socket options**: common TCP options (`TCP_NODELAY`, `SO_KEEPALIVE`,
//!   `SO_RCVBUF`, `SO_SNDBUF`) applied to the socket before connecting via
//!   `tokio::net::TcpSocket`.
//! - **Local address binding**: bind the outbound socket to a specific local
//!   address before connecting to the remote.
//!
//! When no advanced options are configured, callers should use the standard
//! `hyper_rustls::HttpsConnector` path for maximum compatibility and
//! performance.
//!
//! # Socket option representation
//!
//! Socket options are represented as `(level, option, value)` triples,
//! matching HTTPX's tuple-list format. The connector interprets common
//! TCP options by their integer constants:
//!
//! - `IPPROTO_TCP (6)` + `TCP_NODELAY (1)` → `set_nodelay`
//! - `SOL_SOCKET (1)` + `SO_KEEPALIVE (5)` → `set_keepalive`
//! - `SOL_SOCKET (1)` + `SO_RCVBUF (8)` → `set_recv_buffer_size`
//! - `SOL_SOCKET (1)` + `SO_SNDBUF (7)` → `set_send_buffer_size`
//!
//! Unrecognized option triples produce an error. This satisfies the plan
//! requirement that unsupported options are never silently ignored. Callers
//! that need platform-specific socket options beyond the recognized set
//! should use a custom transport.

use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use http::Uri;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tower_service::Service;

use crate::error::Error;

/// Build a rustls server name from a DNS name or IP literal.
#[cfg(feature = "tls-rustls")]
pub(crate) fn tls_server_name(
    host: &str,
) -> std::result::Result<tokio_rustls::rustls::pki_types::ServerName<'static>, String> {
    let ip_host = host
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
        .unwrap_or(host);
    if let Ok(ip) = ip_host.parse::<std::net::IpAddr>() {
        return Ok(tokio_rustls::rustls::pki_types::ServerName::IpAddress(
            ip.into(),
        ));
    }

    tokio_rustls::rustls::pki_types::ServerName::try_from(host.to_owned())
        .map_err(|error| error.to_string())
}

/// Socket options that the safe connector can apply portably.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SocketOptionKind {
    /// Disable Nagle's algorithm.
    TcpNoDelay,
    /// Enable or disable TCP keepalive.
    KeepAlive,
    /// Set the receive buffer size.
    ReceiveBuffer,
    /// Set the send buffer size.
    SendBuffer,
}

/// Private structured error emitted before Hyper collapses connector errors
/// into its legacy client error. The message remains the existing public
/// `Error::Connect` text; the category is consumed only by detailed sends.
pub(crate) struct DirectConnectError {
    kind: crate::transport::ConnectFailureKind,
    message: String,
    source: Option<std::io::Error>,
}

impl DirectConnectError {
    pub(crate) fn new(
        kind: crate::transport::ConnectFailureKind,
        message: String,
        source: Option<std::io::Error>,
    ) -> Self {
        Self {
            kind,
            message,
            source,
        }
    }

    pub(crate) const fn kind(&self) -> crate::transport::ConnectFailureKind {
        self.kind
    }

    pub(crate) fn message(&self) -> &str {
        &self.message
    }
}

fn classify_tcp_failures(attempted: usize, refused: usize) -> crate::transport::ConnectFailureKind {
    if attempted > 0 && attempted == refused {
        crate::transport::ConnectFailureKind::ConnectionRefused
    } else {
        crate::transport::ConnectFailureKind::Connect
    }
}

impl fmt::Debug for DirectConnectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DirectConnectError")
            .field("kind", &self.kind)
            .field("message", &self.message)
            .field("source", &self.source.as_ref().map(|_| "<redacted>"))
            .finish()
    }
}

impl fmt::Display for DirectConnectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for DirectConnectError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|source| source as &(dyn std::error::Error + 'static))
    }
}

/// A socket option triple `(level, option, value)`.
///
/// Mirrors the Python `socket` module's tuple representation used by HTTPX.
/// `level` and `option` are integers matching OS socket option constants.
/// `value` is the raw bytes to set, interpreted in native endianness
/// (`from_ne_bytes`); values must be produced and consumed in-process and
/// never persisted or passed across differing-endian boundaries.
#[derive(Debug, Clone)]
pub struct SocketOption {
    /// Socket level (e.g., `IPPROTO_TCP`).
    pub level: i32,
    /// Option name within the level (e.g., `TCP_NODELAY`).
    pub option: i32,
    /// Raw option value bytes.
    pub value: Vec<u8>,
    /// Semantic classification performed by the compatibility boundary.
    /// `None` deliberately represents an unsupported tuple and is rejected
    /// before the socket is connected.
    pub kind: Option<SocketOptionKind>,
}

/// Configuration for a direct TCP connection with advanced socket options.
///
/// This is stored in `ClientInner` when the caller requests local-address
/// binding, socket options, or both. The connector is only used for requests
/// that need these options; ordinary requests continue through the standard
/// hyper connector path.
#[derive(Debug, Clone)]
pub struct DirectConnectorConfig {
    /// Optional local address to bind before connecting.
    pub(crate) local_address: Option<SocketAddr>,
    /// Socket options to apply before connecting.
    pub(crate) socket_options: Vec<SocketOption>,
}

impl DirectConnectorConfig {}

/// Apply a socket option to a `tokio::net::TcpSocket`.
///
/// Recognized options are applied via the socket's typed setters.
/// Unrecognized options return an error (the plan requires that
/// unsupported options are never silently ignored).
fn apply_socket_option(
    socket: &tokio::net::TcpSocket,
    opt: &SocketOption,
) -> std::result::Result<(), Error> {
    if opt.value.len() < 4 {
        return Err(Error::Connect(format!(
            "socket option value too short: expected at least 4 bytes, got {}",
            opt.value.len()
        )));
    }
    match opt.kind {
        // TCP_NODELAY: value is a 4-byte int (non-zero = enabled).
        Some(SocketOptionKind::TcpNoDelay) => {
            let val = i32::from_ne_bytes([opt.value[0], opt.value[1], opt.value[2], opt.value[3]]);
            socket
                .set_nodelay(val != 0)
                .map_err(|e| Error::Connect(format!("failed to set TCP_NODELAY: {e}")))?;
        }
        // SO_KEEPALIVE: value is a 4-byte int (non-zero = enabled).
        Some(SocketOptionKind::KeepAlive) => {
            let val = i32::from_ne_bytes([opt.value[0], opt.value[1], opt.value[2], opt.value[3]]);
            socket
                .set_keepalive(val != 0)
                .map_err(|e| Error::Connect(format!("failed to set SO_KEEPALIVE: {e}")))?;
        }
        // SO_RCVBUF: value is a 4-byte int (buffer size in bytes).
        Some(SocketOptionKind::ReceiveBuffer) => {
            let val = u32::from_ne_bytes([opt.value[0], opt.value[1], opt.value[2], opt.value[3]]);
            socket
                .set_recv_buffer_size(val)
                .map_err(|e| Error::Connect(format!("failed to set SO_RCVBUF: {e}")))?;
        }
        // SO_SNDBUF: value is a 4-byte int (buffer size in bytes).
        Some(SocketOptionKind::SendBuffer) => {
            let val = u32::from_ne_bytes([opt.value[0], opt.value[1], opt.value[2], opt.value[3]]);
            socket
                .set_send_buffer_size(val)
                .map_err(|e| Error::Connect(format!("failed to set SO_SNDBUF: {e}")))?;
        }
        // Unrecognized: return error (plan Track 2.4: never silently ignore).
        _ => {
            return Err(Error::Connect(format!(
                "unsupported socket option: level={}, option={}",
                opt.level, opt.option
            )));
        }
    }
    Ok(())
}

/// A connected stream that can be either a raw TCP stream or a TLS stream.
///
/// This enum allows the direct connector to return a single type that
/// implements both `AsyncRead` and `AsyncWrite`, satisfying hyper-util's
/// connector requirements.
pub(crate) enum DirectStream {
    /// A plain TCP stream (for HTTP).
    Tcp(tokio::net::TcpStream),
    /// A TLS-wrapped stream (for HTTPS), boxed to reduce enum size.
    #[cfg(feature = "tls-rustls")]
    Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
}

impl AsyncRead for DirectStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        match &mut *self {
            DirectStream::Tcp(s) => Pin::new(s).poll_read(cx, buf),
            #[cfg(feature = "tls-rustls")]
            DirectStream::Tls(s) => Pin::new(s).poll_read(cx, buf),
        }
    }
}

impl AsyncWrite for DirectStream {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        match &mut *self {
            DirectStream::Tcp(s) => Pin::new(s).poll_write(cx, buf),
            #[cfg(feature = "tls-rustls")]
            DirectStream::Tls(s) => Pin::new(s).poll_write(cx, buf),
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match &mut *self {
            DirectStream::Tcp(s) => Pin::new(s).poll_flush(cx),
            #[cfg(feature = "tls-rustls")]
            DirectStream::Tls(s) => Pin::new(s).poll_flush(cx),
        }
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match &mut *self {
            DirectStream::Tcp(s) => Pin::new(s).poll_shutdown(cx),
            #[cfg(feature = "tls-rustls")]
            DirectStream::Tls(s) => Pin::new(s).poll_shutdown(cx),
        }
    }
}

impl hyper_util::client::legacy::connect::Connection for DirectStream {
    fn connected(&self) -> hyper_util::client::legacy::connect::Connected {
        // Inspect the negotiated ALPN protocol on TLS streams so hyper-util
        // knows whether the connection negotiated HTTP/2. Without this
        // signal, an HTTP/2-only legacy client could silently downgrade to
        // HTTP/1.1 even when ALPN selected `h2`.
        #[cfg(feature = "tls-rustls")]
        let mut connected = hyper_util::client::legacy::connect::Connected::new();
        #[cfg(not(feature = "tls-rustls"))]
        let connected = hyper_util::client::legacy::connect::Connected::new();
        #[cfg(feature = "tls-rustls")]
        if let Self::Tls(tls) = self {
            if super::negotiated_http2(tls.get_ref().1.alpn_protocol()) {
                connected = connected.negotiated_h2();
            }
        }
        connected
    }
}

#[cfg(feature = "tls-rustls")]
type TlsConnector = tokio_rustls::TlsConnector;

#[cfg(not(feature = "tls-rustls"))]
type TlsConnector = ();

#[allow(
    dead_code,
    reason = "connector metadata helpers are exercised by integration tests; upgrade path uses from_tcp/from_tls directly"
)]
impl DirectStream {
    /// Local socket address, if observable (TCP/TLS over TCP).
    pub(crate) fn local_addr(&self) -> Option<SocketAddr> {
        match self {
            Self::Tcp(s) => s.local_addr().ok(),
            #[cfg(feature = "tls-rustls")]
            Self::Tls(s) => s.get_ref().0.local_addr().ok(),
        }
    }

    /// Remote socket address, if observable.
    pub(crate) fn peer_addr(&self) -> Option<SocketAddr> {
        match self {
            Self::Tcp(s) => s.peer_addr().ok(),
            #[cfg(feature = "tls-rustls")]
            Self::Tls(s) => s.get_ref().0.peer_addr().ok(),
        }
    }

    /// TLS session info when this is a TLS stream.
    ///
    /// `server_name` is the SNI hostname when known; `None` explicitly
    /// marks unavailable. Returns `None` for plain TCP.
    pub(crate) fn tls_info(
        &self,
        server_name: Option<String>,
    ) -> Option<crate::network_stream::TlsInfo> {
        #[cfg(not(feature = "tls-rustls"))]
        let _ = server_name;
        match self {
            Self::Tcp(_) => None,
            #[cfg(feature = "tls-rustls")]
            Self::Tls(s) => Some(crate::network_stream::tls_info_from_rustls(
                s.get_ref().1,
                server_name,
            )),
        }
    }

    /// Connection metadata captured at the connector where socket
    /// information is directly observable.
    ///
    /// Uses `Option`/unknown for unavailable fields; never fabricates
    /// zero/default addresses and never includes secrets.
    pub(crate) fn connection_metadata(
        &self,
        server_name: Option<String>,
    ) -> crate::network_stream::ConnectionMetadata {
        let tls_info = self.tls_info(server_name);
        let kind = if tls_info.is_some() {
            crate::network_stream::TransportKind::Tls
        } else {
            crate::network_stream::TransportKind::Tcp
        };
        crate::network_stream::ConnectionMetadata {
            local_addr: self.local_addr(),
            peer_addr: self.peer_addr(),
            transport_kind: kind,
            tls_info,
        }
    }
}

/// A tower service connector that establishes TCP connections with optional
/// socket-level pre-configuration and per-request TLS SNI override.
///
/// This is used by the hyper client for requests that require advanced
/// socket options, local-address binding, or TLS SNI override. It performs:
///
/// 1. DNS resolution (via `tokio::net::lookup_host`)
/// 2. Socket creation with `tokio::net::TcpSocket`
/// 3. Application of recognized socket options
/// 4. Optional local-address binding
/// 5. TCP connect
/// 6. Optional TLS handshake (for HTTPS), using `sni_hostname` for SNI
///    when set, while TCP connects to the original URL host.
///
/// The connector is `Clone`-able and can be shared across requests.
#[derive(Clone)]
pub(crate) struct DirectConnector {
    config: DirectConnectorConfig,
    tls: Option<Arc<TlsConnector>>,
    /// Per-request TLS SNI hostname override. When set, TLS uses this
    /// hostname for `ServerName` Indication and certificate verification,
    /// while TCP still connects to the URL host.
    sni_hostname: Option<String>,
    /// Request-scoped static destinations. When present, DNS is never used.
    resolved_addresses: Option<Arc<[SocketAddr]>>,
    /// Shared transport observability counters. `None` disables metering
    /// (unit tests, one-off connectors); client-owned connectors always
    /// carry the client's shared metrics.
    metrics: Option<Arc<crate::transport::metrics::TransportMetrics>>,
}

impl DirectConnector {
    /// Create a new direct connector with the given configuration.
    #[allow(
        dead_code,
        reason = "kept for unit tests and one-off connectors without metrics; client paths use with_metrics"
    )]
    pub(crate) fn new(config: DirectConnectorConfig, tls: Option<TlsConnector>) -> Self {
        Self {
            config,
            tls: tls.map(Arc::new),
            sni_hostname: None,
            resolved_addresses: None,
            metrics: None,
        }
    }

    /// Create a new direct connector with shared transport metrics.
    pub(crate) fn with_metrics(
        config: DirectConnectorConfig,
        tls: Option<TlsConnector>,
        metrics: Arc<crate::transport::metrics::TransportMetrics>,
    ) -> Self {
        Self {
            config,
            tls: tls.map(Arc::new),
            sni_hostname: None,
            resolved_addresses: None,
            metrics: Some(metrics),
        }
    }

    /// Create a clone of this connector with a TLS SNI hostname override.
    ///
    /// When `sni_hostname` is set, TLS uses the specified hostname for
    /// `ServerName` Indication and certificate verification, while TCP
    /// still connects to the URL host from the request URI.
    pub(crate) fn with_sni(&self, sni_hostname: String) -> Self {
        Self {
            config: self.config.clone(),
            tls: self.tls.clone(),
            sni_hostname: Some(sni_hostname),
            resolved_addresses: self.resolved_addresses.clone(),
            metrics: self.metrics.clone(),
        }
    }

    /// Create a connector clone pinned to the supplied destination snapshot.
    pub(crate) fn with_resolved_target(
        &self,
        target: &crate::transport_hints::ResolvedTarget,
    ) -> Self {
        Self {
            config: self.config.clone(),
            tls: self.tls.clone(),
            sni_hostname: self.sni_hostname.clone(),
            resolved_addresses: Some(target.addresses_shared()),
            metrics: self.metrics.clone(),
        }
    }
}

impl Service<Uri> for DirectConnector {
    type Response = hyper_util::rt::TokioIo<DirectStream>;
    type Error = Box<dyn std::error::Error + Send + Sync>;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    #[allow(
        clippy::too_many_lines,
        reason = "the address resolution, the per-address socket setup, the connect retry, the failure classification and the TLS handshake are one ordered dial sequence"
    )]
    fn call(&mut self, dst: Uri) -> Self::Future {
        let config = self.config.clone();
        #[cfg(feature = "tls-rustls")]
        let tls = self.tls.clone();
        #[cfg(feature = "tls-rustls")]
        let sni_hostname = self.sni_hostname.clone();
        let resolved_addresses = self.resolved_addresses.clone();
        let metrics = self.metrics.clone();

        Box::pin(async move {
            if let Some(ref m) = metrics {
                m.record_direct_attempt();
                if resolved_addresses.is_none() {
                    m.record_direct_dns_attempt();
                }
            }
            let host = dst
                .host()
                .ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
                    Error::Connect("no hostname in URI".into()).into()
                })?
                .to_owned();

            // Determine port: use explicit port or default for scheme.
            let port = dst.port_u16().unwrap_or_else(|| {
                if dst.scheme_str() == Some("https") {
                    443
                } else {
                    80
                }
            });

            let is_https = dst.scheme_str() == Some("https");

            let addresses = if let Some(addresses) = resolved_addresses {
                addresses.to_vec()
            } else {
                match tokio::net::lookup_host((host.as_str(), port)).await {
                    Ok(addrs) => addrs.collect(),
                    Err(e) => {
                        if let Some(ref m) = metrics {
                            m.record_direct_dns_failure();
                            m.record_direct_failure();
                        }
                        return Err(Box::new(DirectConnectError::new(
                            crate::transport::ConnectFailureKind::Dns,
                            format!("DNS resolution failed for {host}: {e}"),
                            Some(e),
                        ))
                            as Box<dyn std::error::Error + Send + Sync>);
                    }
                }
            };
            let mut attempted = 0usize;
            let mut refused = 0;
            let mut last_error: Option<(String, std::io::Error)> = None;
            let mut tokio_stream = None;
            for addr in addresses {
                if let Some(local_addr) = config.local_address {
                    if local_addr.is_ipv4() != addr.is_ipv4() {
                        continue;
                    }
                }
                let socket = if addr.is_ipv4() {
                    tokio::net::TcpSocket::new_v4()
                } else {
                    tokio::net::TcpSocket::new_v6()
                }
                .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> {
                    Error::Connect(format!("failed to create socket: {e}")).into()
                })?;
                for opt in &config.socket_options {
                    if let Err(error) = apply_socket_option(&socket, opt) {
                        return Err(error.into());
                    }
                }
                if let Some(local_addr) = config.local_address {
                    if let Err(error) = socket.bind(local_addr) {
                        attempted += 1;
                        last_error = Some((error.to_string(), error));
                        continue;
                    }
                }
                attempted += 1;
                match socket.connect(addr).await {
                    Ok(stream) => {
                        tokio_stream = Some(stream);
                        break;
                    }
                    Err(error) => {
                        if error.kind() == std::io::ErrorKind::ConnectionRefused {
                            refused += 1;
                        }
                        last_error = Some((format!("{addr}: {error}"), error));
                    }
                }
            }
            let Some(tokio_stream) = tokio_stream else {
                if let Some(ref m) = metrics {
                    m.record_direct_failure();
                }
                let (last_message, source) = last_error.map_or_else(
                    || ("no compatible addresses".into(), None),
                    |(message, error)| (message, Some(error)),
                );
                let kind = classify_tcp_failures(attempted, refused);
                return Err(Box::new(DirectConnectError::new(
                    kind,
                    format!("TCP connect to {host}:{port} failed: {last_message}"),
                    source,
                ))
                    as Box<dyn std::error::Error + Send + Sync>);
            };
            if let Some(ref m) = metrics {
                m.record_direct_success();
            }

            // Set TCP_NODELAY after connect only if the caller did not
            // explicitly configure it via socket_options. An explicit
            // `TcpNoDelay=0` disables Nagle and must be respected.
            let has_nodelay = config
                .socket_options
                .iter()
                .any(|opt| opt.kind == Some(SocketOptionKind::TcpNoDelay));
            if !has_nodelay {
                tokio_stream.set_nodelay(true).map_err(
                    |e| -> Box<dyn std::error::Error + Send + Sync> {
                        Error::Connect(format!("failed to set TCP_NODELAY: {e}")).into()
                    },
                )?;
            }

            #[cfg(feature = "tls-rustls")]
            let direct_stream = if is_https {
                let tls_connector =
                    tls.ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
                        Error::Connect("HTTPS requested but TLS connector not configured".into())
                            .into()
                    })?;

                // Use sni_hostname override for TLS SNI when set; otherwise
                // use the URL host for both TCP and TLS.
                let tls_host = sni_hostname.as_deref().unwrap_or(&host);
                let server_name = tls_server_name(tls_host).map_err(
                    |e| -> Box<dyn std::error::Error + Send + Sync> {
                        Error::Tls(format!("invalid server name '{tls_host}': {e}")).into()
                    },
                )?;

                if let Some(ref m) = metrics {
                    m.record_direct_tls_attempt();
                }
                let stream = match tls_connector.connect(server_name, tokio_stream).await {
                    Ok(s) => s,
                    Err(e) => {
                        if let Some(ref m) = metrics {
                            m.record_direct_tls_failure();
                        }
                        return Err(Box::new(Error::Tls(format!("TLS handshake failed: {e}")))
                            as Box<dyn std::error::Error + Send + Sync>);
                    }
                };

                DirectStream::Tls(Box::new(stream))
            } else {
                DirectStream::Tcp(tokio_stream)
            };
            #[cfg(not(feature = "tls-rustls"))]
            let direct_stream = if is_https {
                return Err(Box::new(Error::Tls(
                    "HTTPS requested but the tls-rustls feature is disabled".into(),
                ))
                    as Box<dyn std::error::Error + Send + Sync>);
            } else {
                DirectStream::Tcp(tokio_stream)
            };
            Ok(hyper_util::rt::TokioIo::new(direct_stream))
        })
    }
}

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

    #[test]
    fn connector_config_is_clone() {
        let config = DirectConnectorConfig {
            local_address: None,
            socket_options: vec![SocketOption {
                level: 0,
                option: 0,
                value: 1i32.to_ne_bytes().to_vec(),
                kind: Some(SocketOptionKind::TcpNoDelay),
            }],
        };
        let _cloned = config.clone();
    }

    #[test]
    fn socket_option_stores_raw_value() {
        let opt = SocketOption {
            level: 0,
            option: 0,
            value: 1i32.to_ne_bytes().to_vec(),
            kind: Some(SocketOptionKind::TcpNoDelay),
        };
        assert_eq!(opt.value.len(), 4);
    }

    #[test]
    fn tls_server_name_accepts_ip_literals() {
        assert!(tls_server_name("127.0.0.1").is_ok());
        assert!(tls_server_name("::1").is_ok());
        assert!(tls_server_name("[::1]").is_ok());
    }

    #[test]
    fn apply_socket_option_nodelay() {
        let socket = tokio::net::TcpSocket::new_v4().unwrap();
        let opt = SocketOption {
            level: 0,
            option: 0,
            value: 1i32.to_ne_bytes().to_vec(),
            kind: Some(SocketOptionKind::TcpNoDelay),
        };
        apply_socket_option(&socket, &opt).unwrap();
    }

    #[test]
    fn apply_socket_option_keepalive() {
        let socket = tokio::net::TcpSocket::new_v4().unwrap();
        let opt = SocketOption {
            level: 0,
            option: 0,
            value: 1i32.to_ne_bytes().to_vec(),
            kind: Some(SocketOptionKind::KeepAlive),
        };
        apply_socket_option(&socket, &opt).unwrap();
    }

    #[test]
    fn apply_socket_option_unrecognized_returns_error() {
        let socket = tokio::net::TcpSocket::new_v4().unwrap();
        let opt = SocketOption {
            level: 999,
            option: 999,
            value: vec![0, 1, 2, 3],
            kind: None,
        };
        let err = apply_socket_option(&socket, &opt).unwrap_err();
        assert_eq!(err.kind(), "connect");
        assert!(err.to_string().contains("unsupported socket option"));
    }

    #[test]
    fn apply_socket_option_short_value_returns_error() {
        let socket = tokio::net::TcpSocket::new_v4().unwrap();
        let opt = SocketOption {
            level: 0,
            option: 0,
            value: vec![1],
            kind: Some(SocketOptionKind::TcpNoDelay),
        };
        let err = apply_socket_option(&socket, &opt).unwrap_err();
        assert_eq!(err.kind(), "connect");
        assert!(err.to_string().contains("too short"));
    }

    #[test]
    fn tcp_failure_classification_requires_all_attempts_to_be_refused() {
        assert_eq!(
            classify_tcp_failures(2, 2),
            crate::transport::ConnectFailureKind::ConnectionRefused
        );
        assert_eq!(
            classify_tcp_failures(2, 1),
            crate::transport::ConnectFailureKind::Connect
        );
        assert_eq!(
            classify_tcp_failures(0, 0),
            crate::transport::ConnectFailureKind::Connect
        );
    }

    #[test]
    fn direct_dns_error_keeps_private_structured_category() {
        let error = DirectConnectError::new(
            crate::transport::ConnectFailureKind::Dns,
            "DNS resolution failed".into(),
            Some(std::io::Error::new(
                std::io::ErrorKind::AddrNotAvailable,
                "synthetic resolver failure",
            )),
        );
        assert_eq!(error.kind(), crate::transport::ConnectFailureKind::Dns);
        assert_eq!(error.to_string(), "DNS resolution failed");
        assert!(std::error::Error::source(&error).is_some());
    }
}