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
//! Network stream types for connection metadata and upgraded connections.
//!
//! This module provides:
//!
//! - [`ConnectionMetadata`]: read-only metadata about an established
//!   connection (addresses, TLS info, transport kind).
//! - [`UpgradedStream`]: an owned post-HTTP IO handle for 101/CONNECT
//!   upgrade handoff.
//! - [`NetworkStream`]: a compatibility object exposed on responses for
//!   metadata access and, where safe, low-level IO.

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

use bytes::Bytes;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

use crate::error::{Error, Result};

/// The kind of transport used for a connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportKind {
    /// Plain TCP.
    Tcp,
    /// Unix domain socket (no IP addresses; local/peer remain `None`).
    Unix,
    /// TLS-wrapped TCP (rustls).
    Tls,
    /// TLS-wrapped Unix domain socket.
    TlsUnix,
    /// QUIC (HTTP/3) via Quinn.
    ///
    /// Reserved for H3 endpoint information where Quinn exposes it
    /// (remote address). Per-response H3 metadata is currently
    /// explicitly unavailable (`Response::network_stream()` is `None`
    /// for ordinary H3 responses); this variant documents the transport
    /// kind for future connector-derived metadata without inventing
    /// values today.
    Quic,
}

/// Read-only TLS session metadata captured after handshake.
///
/// This is an EggFetch-specific type; it does **not** masquerade as
/// `ssl.SSLObject` or any Python SSL type.
#[derive(Debug, Clone)]
pub struct TlsInfo {
    /// Negotiated ALPN protocol (e.g. `"http/1.1"`, `"h2"`).
    pub alpn_protocol: Option<String>,
    /// TLS version string (e.g. `"TLSv1.3"`).
    pub tls_version: Option<String>,
    /// Cipher suite identifier.
    pub cipher_suite: Option<String>,
    /// Server name used for SNI.
    pub server_name: Option<String>,
}

/// Read-only metadata about an established connection.
///
/// All fields are captured at connection time and never mutated.
/// Shared through `Arc` so multiple responses (H2) can reference the
/// same connection metadata.
#[derive(Debug, Clone)]
pub struct ConnectionMetadata {
    /// Local (client) socket address, if available.
    pub local_addr: Option<SocketAddr>,
    /// Remote (peer/server) socket address, if available.
    pub peer_addr: Option<SocketAddr>,
    /// Transport kind.
    pub transport_kind: TransportKind,
    /// TLS session info, if the connection is TLS.
    pub tls_info: Option<TlsInfo>,
}

impl Default for ConnectionMetadata {
    fn default() -> Self {
        Self {
            local_addr: None,
            peer_addr: None,
            transport_kind: TransportKind::Tcp,
            tls_info: None,
        }
    }
}

/// Build [`TlsInfo`] from a rustls client connection.
///
/// Extracts ALPN, TLS version, and cipher suite where rustls exposes them
/// safely. `server_name` is the SNI hostname when known (direct-connector
/// TLS host); `None` explicitly marks unavailable rather than inventing a
/// value. No secret-bearing material is included.
#[cfg(feature = "tls-rustls")]
pub(crate) fn tls_info_from_rustls(
    conn: &rustls::ClientConnection,
    server_name: Option<String>,
) -> TlsInfo {
    TlsInfo {
        alpn_protocol: conn
            .alpn_protocol()
            .map(|p| String::from_utf8_lossy(p).into_owned()),
        tls_version: conn.protocol_version().map(|v| format!("{v:?}")),
        cipher_suite: conn.negotiated_cipher_suite().map(|c| format!("{c:?}")),
        server_name,
    }
}

/// An owned post-HTTP IO handle for upgraded connections (101, CONNECT).
///
/// After Hyper transfers ownership of the underlying IO through its
/// upgrade mechanism, this type owns the raw stream and provides
/// async read/write, TLS upgrade, and metadata access.
///
/// # Ownership rules
///
/// - Once created, the connection is removed from the HTTP pool and
///   must never be reused.
/// - `close()` is idempotent.
/// - Cancellation during `start_tls()` closes or leaves the stream
///   in a deterministic state.
pub struct UpgradedStream {
    inner: UpgradedStreamInner,
    metadata: Arc<ConnectionMetadata>,
    /// Keeps connector-lifecycle resources alive after Hyper hands off a 101
    /// stream. The concrete resource is intentionally private to transport.
    connection_guard: Option<Box<dyn Send>>,
    /// Leading bytes already read from the connection before the
    /// upgrade completed (e.g. data sent by the server in the same
    /// write as the 101/CONNECT response headers).
    leading_data: Bytes,
}

/// Classification of the concrete IO inside an [`UpgradedStream`].
///
/// Used by the Python bindings to refuse `start_tls` on streams where
/// the underlying socket cannot be recovered (Hyper's opaque adapter).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpgradedStreamVariant {
    /// Plain TCP.
    Tcp,
    /// Already TLS-wrapped.
    Tls,
    /// Opaque adapter (Hyper's `Upgraded` wrapper).
    Adapter,
}

/// The concrete IO inside an upgraded stream.
enum UpgradedStreamInner {
    /// Plain TCP stream.
    Tcp(tokio::net::TcpStream),
    /// TLS stream already established before upgrade.
    #[cfg(feature = "tls-rustls")]
    Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
    /// Opaque adapter (e.g. Hyper's Upgraded wrapper).
    Adapter(Pin<Box<dyn TokioIoBox>>),
}

/// Trait alias for `AsyncRead + AsyncWrite + Send` objects that can
/// be stored in a trait object.
pub(crate) trait TokioIoBox:
    tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin
{
}
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> TokioIoBox for T {}

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

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

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

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

impl UpgradedStream {
    /// Wrap a tokio TCP stream into an upgraded stream.
    ///
    /// Leading data is bytes already read from the connection before
    /// the upgrade handshake completed (preserved by Hyper in its
    /// `Upgraded::read_buf`).
    pub fn from_tcp(stream: tokio::net::TcpStream, leading_data: Bytes) -> Self {
        let metadata = Arc::new(ConnectionMetadata {
            local_addr: stream.local_addr().ok(),
            peer_addr: stream.peer_addr().ok(),
            transport_kind: TransportKind::Tcp,
            tls_info: None,
        });
        Self {
            inner: UpgradedStreamInner::Tcp(stream),
            metadata,
            leading_data,
            connection_guard: None,
        }
    }

    /// Wrap an adapter implementing `AsyncRead + AsyncWrite` into an
    /// upgraded stream.
    ///
    /// Used when the underlying IO type is opaque (e.g. Hyper's
    /// `Upgraded` wrapper) and cannot be downcast to a concrete type.
    /// The metadata must be provided by the caller.
    pub(crate) fn from_adapter(
        adapter: impl TokioIoBox + 'static,
        leading_data: Bytes,
        metadata: Arc<ConnectionMetadata>,
    ) -> Self {
        let pinned: Pin<Box<dyn TokioIoBox>> = Box::pin(adapter);
        Self {
            inner: UpgradedStreamInner::Adapter(pinned),
            metadata,
            leading_data,
            connection_guard: None,
        }
    }

    /// Retain a connector-owned resource until this upgraded stream closes.
    pub(crate) fn hold_connection_guard(&mut self, guard: Box<dyn Send>) {
        self.connection_guard = Some(guard);
    }

    /// Wrap a TLS stream into an upgraded stream.
    #[cfg(feature = "tls-rustls")]
    pub fn from_tls(
        stream: tokio_rustls::client::TlsStream<tokio::net::TcpStream>,
        leading_data: Bytes,
        tls_info: TlsInfo,
    ) -> Self {
        // Extract peer/local addr from the underlying TcpStream through
        // the TLS stream's `get_ref()` which returns (&TcpStream, &ClientConnection).
        let (inner_tcp, _) = stream.get_ref();
        let local_addr = inner_tcp.local_addr().ok();
        let peer_addr = inner_tcp.peer_addr().ok();
        let metadata = Arc::new(ConnectionMetadata {
            local_addr,
            peer_addr,
            transport_kind: TransportKind::Tls,
            tls_info: Some(tls_info),
        });
        Self {
            inner: UpgradedStreamInner::Tls(Box::new(stream)),
            metadata,
            leading_data,
            connection_guard: None,
        }
    }

    /// Returns a reference to the connection metadata.
    #[must_use]
    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
        &self.metadata
    }

    /// Returns the concrete variant of the inner stream.
    ///
    /// The Python bindings use this to refuse `start_tls` on streams
    /// backed by Hyper's opaque adapter (where the underlying TCP socket
    /// is not recoverable).
    #[must_use]
    pub fn variant(&self) -> UpgradedStreamVariant {
        match &self.inner {
            UpgradedStreamInner::Tcp(_) => UpgradedStreamVariant::Tcp,
            #[cfg(feature = "tls-rustls")]
            UpgradedStreamInner::Tls(_) => UpgradedStreamVariant::Tls,
            UpgradedStreamInner::Adapter(_) => UpgradedStreamVariant::Adapter,
        }
    }

    /// Returns the leading data that was buffered before the upgrade.
    ///
    /// These are bytes already read from the connection after the
    /// HTTP response headers but before the caller consumed the
    /// upgrade. They must be returned before any new socket reads.
    #[must_use]
    pub fn leading_data(&self) -> &Bytes {
        &self.leading_data
    }

    /// Consume leading data, returning it.
    pub fn take_leading_data(&mut self) -> Bytes {
        std::mem::take(&mut self.leading_data)
    }

    /// Read up to `max_bytes` from the stream.
    ///
    /// Returns the bytes read. Returns empty bytes on EOF.
    ///
    /// # Errors
    ///
    /// Returns `Error::Io` if the underlying read fails.
    pub async fn read(&mut self, max_bytes: usize) -> Result<Bytes> {
        // First drain leading data.
        if !self.leading_data.is_empty() {
            let available = self.leading_data.len().min(max_bytes);
            return Ok(self.leading_data.split_to(available));
        }
        let mut buf = vec![0u8; max_bytes];
        let n = tokio::io::AsyncReadExt::read(self, &mut buf)
            .await
            .map_err(|e| Error::Io(std::sync::Arc::new(e)))?;
        if n == 0 {
            Ok(Bytes::new())
        } else {
            Ok(Bytes::copy_from_slice(&buf[..n]))
        }
    }

    /// Write all supplied bytes to the stream.
    ///
    /// # Errors
    ///
    /// Returns `Error::Io` if the underlying write fails.
    pub async fn write_all(&mut self, buf: &[u8]) -> Result<()> {
        tokio::io::AsyncWriteExt::write_all(self, buf)
            .await
            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
    }

    /// Flush the stream.
    ///
    /// # Errors
    ///
    /// Returns `Error::Io` if the underlying flush fails.
    pub async fn flush(&mut self) -> Result<()> {
        tokio::io::AsyncWriteExt::flush(self)
            .await
            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
    }

    /// Shut down the stream (idempotent).
    ///
    /// # Errors
    ///
    /// This method currently always succeeds; shutdown errors are
    /// best-effort and counted via `tracing::debug` (when enabled) to
    /// keep close idempotent without hiding them entirely.
    pub async fn close(&mut self) -> Result<()> {
        if let Err(e) = tokio::io::AsyncWriteExt::shutdown(self).await {
            #[cfg(feature = "tracing")]
            tracing::debug!("eggfetch: network stream shutdown error: {e}");
            #[cfg(not(feature = "tracing"))]
            let _ = &e;
        }
        Ok(())
    }

    /// Upgrade this TCP stream to TLS.
    ///
    /// Wraps the inner TCP stream with a new TLS layer using the
    /// provided connector and server name. On success, returns a new
    /// `UpgradedStream` with TLS metadata. The stream is consumed whether
    /// the handshake succeeds or fails; callers that need a fallback must
    /// retain their own connection before calling this method.
    ///
    /// Only works for streams backed by a concrete `TcpStream`.
    /// Adapter-based streams (from Hyper's Upgraded) return an error
    /// because the concrete type cannot be recovered.
    ///
    /// # Errors
    ///
    /// Returns `Error::Tls` if the handshake fails or the stream type
    /// does not support TLS upgrade.
    #[cfg(feature = "tls-rustls")]
    pub async fn start_tls(
        mut self,
        tls_connector: &tokio_rustls::TlsConnector,
        server_name: &str,
    ) -> Result<Self> {
        let tcp = match std::mem::replace(
            &mut self.inner,
            // Placeholder that we'll immediately replace.
            // A zero-capacity in-memory stream avoids allocating a real
            // socket solely to move the enum value out.
            UpgradedStreamInner::Adapter(Box::pin(tokio::io::duplex(0).0)),
        ) {
            UpgradedStreamInner::Tcp(s) => s,
            UpgradedStreamInner::Tls(_) => {
                return Err(Error::Tls("stream is already TLS-wrapped".into()));
            }
            UpgradedStreamInner::Adapter(_) => {
                return Err(Error::Tls(
                    "cannot start TLS on an opaque adapter stream; \
                     use a concrete TcpStream-backed UpgradedStream"
                        .into(),
                ));
            }
        };

        let sn = crate::transport::direct_connector::tls_server_name(server_name)
            .map_err(|e| Error::Tls(format!("invalid server name '{server_name}': {e}")))?;

        let tls_stream = tls_connector
            .connect(sn, tcp)
            .await
            .map_err(|e| Error::Tls(format!("TLS handshake failed: {e}")))?;

        // Extract TLS info from the negotiated parameters.
        let (inner_tcp, connection_info) = tls_stream.get_ref();
        let tls_info = tls_info_from_rustls(connection_info, Some(server_name.to_owned()));

        let local_addr = inner_tcp.local_addr().ok();
        let peer_addr = inner_tcp.peer_addr().ok();

        let metadata = Arc::new(ConnectionMetadata {
            local_addr,
            peer_addr,
            transport_kind: TransportKind::Tls,
            tls_info: Some(tls_info),
        });

        Ok(UpgradedStream {
            inner: UpgradedStreamInner::Tls(Box::new(tls_stream)),
            metadata,
            // Carry any leading data buffered before the TLS handshake so
            // pipelined bytes from the 101 upgrade are not dropped.
            leading_data: std::mem::take(&mut self.leading_data),
            connection_guard: self.connection_guard.take(),
        })
    }
}

impl AsyncRead for UpgradedStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        // Drain leading data first.
        if !self.leading_data.is_empty() {
            let available = self.leading_data.len().min(buf.remaining());
            let chunk = self.leading_data.split_to(available);
            buf.put_slice(&chunk);
            return Poll::Ready(Ok(()));
        }
        Pin::new(&mut self.inner).poll_read(cx, buf)
    }
}

impl AsyncWrite for UpgradedStream {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(cx)
    }
}

/// A network stream handle exposed on responses for metadata access.
///
/// For upgraded connections (101/CONNECT), this provides full
/// read/write/close/TLS access. For ordinary pooled connections,
/// this provides read-only metadata — raw IO operations are not
/// exposed while Hyper still owns the connection.
///
/// # Ordinal response limitation
///
/// Hyper's legacy client pool retains ownership of socket connections
/// for ordinary HTTP/1.1 and HTTP/2 responses. The pool does not expose
/// per-response socket metadata, and raw IO operations would corrupt
/// pool state. Therefore, `NetworkStream::Metadata` is currently only
/// constructed for responses where socket metadata can be safely
/// captured without interfering with the pool. For ordinary responses,
/// `network_stream` on `Response` is `None`.
///
/// This is a documented bounded difference from httpcore, which owns
/// its connections directly and can expose metadata on every response.
pub enum NetworkStream {
    /// An upgraded stream with full IO access.
    Upgraded(UpgradedStream),
    /// Read-only metadata for an ordinary pooled connection.
    ///
    /// Currently reserved for future use when socket metadata can be
    /// safely captured from Hyper's connection pool. For ordinary
    /// responses, `Response::network_stream()` returns `None`.
    Metadata(Arc<ConnectionMetadata>),
}

impl NetworkStream {
    /// Returns the connection metadata.
    #[must_use]
    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
        match self {
            NetworkStream::Upgraded(s) => s.metadata(),
            NetworkStream::Metadata(m) => m,
        }
    }

    /// Returns `true` if this is an upgraded stream with IO access.
    #[must_use]
    pub fn is_upgraded(&self) -> bool {
        matches!(self, NetworkStream::Upgraded(_))
    }

    /// If this is an upgraded stream, returns a reference to it.
    #[must_use]
    pub fn as_upgraded(&self) -> Option<&UpgradedStream> {
        match self {
            NetworkStream::Upgraded(s) => Some(s),
            NetworkStream::Metadata(_) => None,
        }
    }

    /// If this is an upgraded stream, returns a mutable reference.
    pub fn as_upgraded_mut(&mut self) -> Option<&mut UpgradedStream> {
        match self {
            NetworkStream::Upgraded(s) => Some(s),
            NetworkStream::Metadata(_) => None,
        }
    }

    /// If this is an upgraded stream, consume and return it.
    pub fn into_upgraded(self) -> Option<UpgradedStream> {
        match self {
            NetworkStream::Upgraded(s) => Some(s),
            NetworkStream::Metadata(_) => None,
        }
    }
}

/// Read-only metadata accessible through `get_extra_info()`.
#[derive(Debug, Clone)]
pub struct ExtraInfo {
    /// Local address (`client_addr`).
    pub client_addr: Option<SocketAddr>,
    /// Remote address (`server_addr`).
    pub server_addr: Option<SocketAddr>,
    /// TLS info, if available.
    pub tls_info: Option<TlsInfo>,
}

impl ExtraInfo {
    /// Create from connection metadata.
    #[must_use]
    pub fn from_metadata(meta: &ConnectionMetadata) -> Self {
        Self {
            client_addr: meta.local_addr,
            server_addr: meta.peer_addr,
            tls_info: meta.tls_info.clone(),
        }
    }
}

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

    #[test]
    fn connection_metadata_default() {
        let meta = ConnectionMetadata::default();
        assert!(meta.local_addr.is_none());
        assert!(meta.peer_addr.is_none());
        assert_eq!(meta.transport_kind, TransportKind::Tcp);
        assert!(meta.tls_info.is_none());
    }

    #[test]
    fn network_stream_metadata_only() {
        let meta = Arc::new(ConnectionMetadata {
            local_addr: Some("127.0.0.1:12345".parse().unwrap()),
            peer_addr: Some("93.184.216.34:443".parse().unwrap()),
            transport_kind: TransportKind::Tls,
            tls_info: Some(TlsInfo {
                alpn_protocol: Some("h2".into()),
                tls_version: Some("TLSv1.3".into()),
                cipher_suite: Some("TLS_AES_256_GCM_SHA384".into()),
                server_name: Some("example.com".into()),
            }),
        });
        let ns = NetworkStream::Metadata(meta.clone());
        assert!(!ns.is_upgraded());
        assert!(ns.as_upgraded().is_none());
        let info = ns.metadata();
        assert_eq!(info.local_addr.unwrap().port(), 12345);
        assert_eq!(info.peer_addr.unwrap().port(), 443);
    }

    #[test]
    fn extra_info_from_metadata() {
        let meta = ConnectionMetadata {
            local_addr: Some("127.0.0.1:1000".parse().unwrap()),
            peer_addr: Some("10.0.0.1:443".parse().unwrap()),
            transport_kind: TransportKind::Tcp,
            tls_info: None,
        };
        let info = ExtraInfo::from_metadata(&meta);
        assert_eq!(info.client_addr.unwrap().port(), 1000);
        assert_eq!(info.server_addr.unwrap().port(), 443);
        assert!(info.tls_info.is_none());
    }
}