Skip to main content

eggfetch_core/
network_stream.rs

1//! Network stream types for connection metadata and upgraded connections.
2//!
3//! This module provides:
4//!
5//! - [`ConnectionMetadata`]: read-only metadata about an established
6//!   connection (addresses, TLS info, transport kind).
7//! - [`UpgradedStream`]: an owned post-HTTP IO handle for 101/CONNECT
8//!   upgrade handoff.
9//! - [`NetworkStream`]: a compatibility object exposed on responses for
10//!   metadata access and, where safe, low-level IO.
11
12use std::net::SocketAddr;
13use std::pin::Pin;
14use std::sync::Arc;
15use std::task::{Context, Poll};
16
17use bytes::Bytes;
18use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
19
20use crate::error::{Error, Result};
21
22/// The kind of transport used for a connection.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum TransportKind {
25    /// Plain TCP.
26    Tcp,
27    /// Unix domain socket (no IP addresses; local/peer remain `None`).
28    Unix,
29    /// TLS-wrapped TCP (rustls).
30    Tls,
31    /// TLS-wrapped Unix domain socket.
32    TlsUnix,
33    /// QUIC (HTTP/3) via Quinn.
34    ///
35    /// Reserved for H3 endpoint information where Quinn exposes it
36    /// (remote address). Per-response H3 metadata is currently
37    /// explicitly unavailable (`Response::network_stream()` is `None`
38    /// for ordinary H3 responses); this variant documents the transport
39    /// kind for future connector-derived metadata without inventing
40    /// values today.
41    Quic,
42}
43
44/// Read-only TLS session metadata captured after handshake.
45///
46/// This is an EggFetch-specific type; it does **not** masquerade as
47/// `ssl.SSLObject` or any Python SSL type.
48#[derive(Debug, Clone)]
49pub struct TlsInfo {
50    /// Negotiated ALPN protocol (e.g. `"http/1.1"`, `"h2"`).
51    pub alpn_protocol: Option<String>,
52    /// TLS version string (e.g. `"TLSv1.3"`).
53    pub tls_version: Option<String>,
54    /// Cipher suite identifier.
55    pub cipher_suite: Option<String>,
56    /// Server name used for SNI.
57    pub server_name: Option<String>,
58}
59
60/// Read-only metadata about an established connection.
61///
62/// All fields are captured at connection time and never mutated.
63/// Shared through `Arc` so multiple responses (H2) can reference the
64/// same connection metadata.
65#[derive(Debug, Clone)]
66pub struct ConnectionMetadata {
67    /// Local (client) socket address, if available.
68    pub local_addr: Option<SocketAddr>,
69    /// Remote (peer/server) socket address, if available.
70    pub peer_addr: Option<SocketAddr>,
71    /// Transport kind.
72    pub transport_kind: TransportKind,
73    /// TLS session info, if the connection is TLS.
74    pub tls_info: Option<TlsInfo>,
75}
76
77impl Default for ConnectionMetadata {
78    fn default() -> Self {
79        Self {
80            local_addr: None,
81            peer_addr: None,
82            transport_kind: TransportKind::Tcp,
83            tls_info: None,
84        }
85    }
86}
87
88/// Build [`TlsInfo`] from a rustls client connection.
89///
90/// Extracts ALPN, TLS version, and cipher suite where rustls exposes them
91/// safely. `server_name` is the SNI hostname when known (direct-connector
92/// TLS host); `None` explicitly marks unavailable rather than inventing a
93/// value. No secret-bearing material is included.
94#[cfg(feature = "tls-rustls")]
95pub(crate) fn tls_info_from_rustls(
96    conn: &rustls::ClientConnection,
97    server_name: Option<String>,
98) -> TlsInfo {
99    TlsInfo {
100        alpn_protocol: conn
101            .alpn_protocol()
102            .map(|p| String::from_utf8_lossy(p).into_owned()),
103        tls_version: conn.protocol_version().map(|v| format!("{v:?}")),
104        cipher_suite: conn.negotiated_cipher_suite().map(|c| format!("{c:?}")),
105        server_name,
106    }
107}
108
109/// An owned post-HTTP IO handle for upgraded connections (101, CONNECT).
110///
111/// After Hyper transfers ownership of the underlying IO through its
112/// upgrade mechanism, this type owns the raw stream and provides
113/// async read/write, TLS upgrade, and metadata access.
114///
115/// # Ownership rules
116///
117/// - Once created, the connection is removed from the HTTP pool and
118///   must never be reused.
119/// - `close()` is idempotent.
120/// - Cancellation during `start_tls()` closes or leaves the stream
121///   in a deterministic state.
122pub struct UpgradedStream {
123    inner: UpgradedStreamInner,
124    metadata: Arc<ConnectionMetadata>,
125    /// Keeps connector-lifecycle resources alive after Hyper hands off a 101
126    /// stream. The concrete resource is intentionally private to transport.
127    connection_guard: Option<Box<dyn Send>>,
128    /// Leading bytes already read from the connection before the
129    /// upgrade completed (e.g. data sent by the server in the same
130    /// write as the 101/CONNECT response headers).
131    leading_data: Bytes,
132}
133
134/// Classification of the concrete IO inside an [`UpgradedStream`].
135///
136/// Used by the Python bindings to refuse `start_tls` on streams where
137/// the underlying socket cannot be recovered (Hyper's opaque adapter).
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum UpgradedStreamVariant {
140    /// Plain TCP.
141    Tcp,
142    /// Already TLS-wrapped.
143    Tls,
144    /// Opaque adapter (Hyper's `Upgraded` wrapper).
145    Adapter,
146}
147
148/// The concrete IO inside an upgraded stream.
149enum UpgradedStreamInner {
150    /// Plain TCP stream.
151    Tcp(tokio::net::TcpStream),
152    /// TLS stream already established before upgrade.
153    #[cfg(feature = "tls-rustls")]
154    Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
155    /// Opaque adapter (e.g. Hyper's Upgraded wrapper).
156    Adapter(Pin<Box<dyn TokioIoBox>>),
157}
158
159/// Trait alias for `AsyncRead + AsyncWrite + Send` objects that can
160/// be stored in a trait object.
161pub(crate) trait TokioIoBox:
162    tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin
163{
164}
165impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> TokioIoBox for T {}
166
167impl AsyncRead for UpgradedStreamInner {
168    fn poll_read(
169        mut self: Pin<&mut Self>,
170        cx: &mut Context<'_>,
171        buf: &mut ReadBuf<'_>,
172    ) -> Poll<std::io::Result<()>> {
173        match &mut *self {
174            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_read(cx, buf),
175            #[cfg(feature = "tls-rustls")]
176            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_read(cx, buf),
177            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_read(cx, buf),
178        }
179    }
180}
181
182impl AsyncWrite for UpgradedStreamInner {
183    fn poll_write(
184        mut self: Pin<&mut Self>,
185        cx: &mut Context<'_>,
186        buf: &[u8],
187    ) -> Poll<std::io::Result<usize>> {
188        match &mut *self {
189            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_write(cx, buf),
190            #[cfg(feature = "tls-rustls")]
191            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_write(cx, buf),
192            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_write(cx, buf),
193        }
194    }
195
196    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
197        match &mut *self {
198            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_flush(cx),
199            #[cfg(feature = "tls-rustls")]
200            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_flush(cx),
201            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_flush(cx),
202        }
203    }
204
205    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
206        match &mut *self {
207            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_shutdown(cx),
208            #[cfg(feature = "tls-rustls")]
209            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_shutdown(cx),
210            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_shutdown(cx),
211        }
212    }
213}
214
215impl UpgradedStream {
216    /// Wrap a tokio TCP stream into an upgraded stream.
217    ///
218    /// Leading data is bytes already read from the connection before
219    /// the upgrade handshake completed (preserved by Hyper in its
220    /// `Upgraded::read_buf`).
221    pub fn from_tcp(stream: tokio::net::TcpStream, leading_data: Bytes) -> Self {
222        let metadata = Arc::new(ConnectionMetadata {
223            local_addr: stream.local_addr().ok(),
224            peer_addr: stream.peer_addr().ok(),
225            transport_kind: TransportKind::Tcp,
226            tls_info: None,
227        });
228        Self {
229            inner: UpgradedStreamInner::Tcp(stream),
230            metadata,
231            leading_data,
232            connection_guard: None,
233        }
234    }
235
236    /// Wrap an adapter implementing `AsyncRead + AsyncWrite` into an
237    /// upgraded stream.
238    ///
239    /// Used when the underlying IO type is opaque (e.g. Hyper's
240    /// `Upgraded` wrapper) and cannot be downcast to a concrete type.
241    /// The metadata must be provided by the caller.
242    pub(crate) fn from_adapter(
243        adapter: impl TokioIoBox + 'static,
244        leading_data: Bytes,
245        metadata: Arc<ConnectionMetadata>,
246    ) -> Self {
247        let pinned: Pin<Box<dyn TokioIoBox>> = Box::pin(adapter);
248        Self {
249            inner: UpgradedStreamInner::Adapter(pinned),
250            metadata,
251            leading_data,
252            connection_guard: None,
253        }
254    }
255
256    /// Retain a connector-owned resource until this upgraded stream closes.
257    pub(crate) fn hold_connection_guard(&mut self, guard: Box<dyn Send>) {
258        self.connection_guard = Some(guard);
259    }
260
261    /// Wrap a TLS stream into an upgraded stream.
262    #[cfg(feature = "tls-rustls")]
263    pub fn from_tls(
264        stream: tokio_rustls::client::TlsStream<tokio::net::TcpStream>,
265        leading_data: Bytes,
266        tls_info: TlsInfo,
267    ) -> Self {
268        // Extract peer/local addr from the underlying TcpStream through
269        // the TLS stream's `get_ref()` which returns (&TcpStream, &ClientConnection).
270        let (inner_tcp, _) = stream.get_ref();
271        let local_addr = inner_tcp.local_addr().ok();
272        let peer_addr = inner_tcp.peer_addr().ok();
273        let metadata = Arc::new(ConnectionMetadata {
274            local_addr,
275            peer_addr,
276            transport_kind: TransportKind::Tls,
277            tls_info: Some(tls_info),
278        });
279        Self {
280            inner: UpgradedStreamInner::Tls(Box::new(stream)),
281            metadata,
282            leading_data,
283            connection_guard: None,
284        }
285    }
286
287    /// Returns a reference to the connection metadata.
288    #[must_use]
289    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
290        &self.metadata
291    }
292
293    /// Returns the concrete variant of the inner stream.
294    ///
295    /// The Python bindings use this to refuse `start_tls` on streams
296    /// backed by Hyper's opaque adapter (where the underlying TCP socket
297    /// is not recoverable).
298    #[must_use]
299    pub fn variant(&self) -> UpgradedStreamVariant {
300        match &self.inner {
301            UpgradedStreamInner::Tcp(_) => UpgradedStreamVariant::Tcp,
302            #[cfg(feature = "tls-rustls")]
303            UpgradedStreamInner::Tls(_) => UpgradedStreamVariant::Tls,
304            UpgradedStreamInner::Adapter(_) => UpgradedStreamVariant::Adapter,
305        }
306    }
307
308    /// Returns the leading data that was buffered before the upgrade.
309    ///
310    /// These are bytes already read from the connection after the
311    /// HTTP response headers but before the caller consumed the
312    /// upgrade. They must be returned before any new socket reads.
313    #[must_use]
314    pub fn leading_data(&self) -> &Bytes {
315        &self.leading_data
316    }
317
318    /// Consume leading data, returning it.
319    pub fn take_leading_data(&mut self) -> Bytes {
320        std::mem::take(&mut self.leading_data)
321    }
322
323    /// Read up to `max_bytes` from the stream.
324    ///
325    /// Returns the bytes read. Returns empty bytes on EOF.
326    ///
327    /// # Errors
328    ///
329    /// Returns `Error::Io` if the underlying read fails.
330    pub async fn read(&mut self, max_bytes: usize) -> Result<Bytes> {
331        // First drain leading data.
332        if !self.leading_data.is_empty() {
333            let available = self.leading_data.len().min(max_bytes);
334            return Ok(self.leading_data.split_to(available));
335        }
336        let mut buf = vec![0u8; max_bytes];
337        let n = tokio::io::AsyncReadExt::read(self, &mut buf)
338            .await
339            .map_err(|e| Error::Io(std::sync::Arc::new(e)))?;
340        if n == 0 {
341            Ok(Bytes::new())
342        } else {
343            Ok(Bytes::copy_from_slice(&buf[..n]))
344        }
345    }
346
347    /// Write all supplied bytes to the stream.
348    ///
349    /// # Errors
350    ///
351    /// Returns `Error::Io` if the underlying write fails.
352    pub async fn write_all(&mut self, buf: &[u8]) -> Result<()> {
353        tokio::io::AsyncWriteExt::write_all(self, buf)
354            .await
355            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
356    }
357
358    /// Flush the stream.
359    ///
360    /// # Errors
361    ///
362    /// Returns `Error::Io` if the underlying flush fails.
363    pub async fn flush(&mut self) -> Result<()> {
364        tokio::io::AsyncWriteExt::flush(self)
365            .await
366            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
367    }
368
369    /// Shut down the stream (idempotent).
370    ///
371    /// # Errors
372    ///
373    /// This method currently always succeeds; shutdown errors are
374    /// best-effort and counted via `tracing::debug` (when enabled) to
375    /// keep close idempotent without hiding them entirely.
376    pub async fn close(&mut self) -> Result<()> {
377        if let Err(e) = tokio::io::AsyncWriteExt::shutdown(self).await {
378            #[cfg(feature = "tracing")]
379            tracing::debug!("eggfetch: network stream shutdown error: {e}");
380            #[cfg(not(feature = "tracing"))]
381            let _ = &e;
382        }
383        Ok(())
384    }
385
386    /// Upgrade this TCP stream to TLS.
387    ///
388    /// Wraps the inner TCP stream with a new TLS layer using the
389    /// provided connector and server name. On success, returns a new
390    /// `UpgradedStream` with TLS metadata. The stream is consumed whether
391    /// the handshake succeeds or fails; callers that need a fallback must
392    /// retain their own connection before calling this method.
393    ///
394    /// Only works for streams backed by a concrete `TcpStream`.
395    /// Adapter-based streams (from Hyper's Upgraded) return an error
396    /// because the concrete type cannot be recovered.
397    ///
398    /// # Errors
399    ///
400    /// Returns `Error::Tls` if the handshake fails or the stream type
401    /// does not support TLS upgrade.
402    #[cfg(feature = "tls-rustls")]
403    pub async fn start_tls(
404        mut self,
405        tls_connector: &tokio_rustls::TlsConnector,
406        server_name: &str,
407    ) -> Result<Self> {
408        let tcp = match std::mem::replace(
409            &mut self.inner,
410            // Placeholder that we'll immediately replace.
411            // A zero-capacity in-memory stream avoids allocating a real
412            // socket solely to move the enum value out.
413            UpgradedStreamInner::Adapter(Box::pin(tokio::io::duplex(0).0)),
414        ) {
415            UpgradedStreamInner::Tcp(s) => s,
416            UpgradedStreamInner::Tls(_) => {
417                return Err(Error::Tls("stream is already TLS-wrapped".into()));
418            }
419            UpgradedStreamInner::Adapter(_) => {
420                return Err(Error::Tls(
421                    "cannot start TLS on an opaque adapter stream; \
422                     use a concrete TcpStream-backed UpgradedStream"
423                        .into(),
424                ));
425            }
426        };
427
428        let sn = crate::transport::direct_connector::tls_server_name(server_name)
429            .map_err(|e| Error::Tls(format!("invalid server name '{server_name}': {e}")))?;
430
431        let tls_stream = tls_connector
432            .connect(sn, tcp)
433            .await
434            .map_err(|e| Error::Tls(format!("TLS handshake failed: {e}")))?;
435
436        // Extract TLS info from the negotiated parameters.
437        let (inner_tcp, connection_info) = tls_stream.get_ref();
438        let tls_info = tls_info_from_rustls(connection_info, Some(server_name.to_owned()));
439
440        let local_addr = inner_tcp.local_addr().ok();
441        let peer_addr = inner_tcp.peer_addr().ok();
442
443        let metadata = Arc::new(ConnectionMetadata {
444            local_addr,
445            peer_addr,
446            transport_kind: TransportKind::Tls,
447            tls_info: Some(tls_info),
448        });
449
450        Ok(UpgradedStream {
451            inner: UpgradedStreamInner::Tls(Box::new(tls_stream)),
452            metadata,
453            // Carry any leading data buffered before the TLS handshake so
454            // pipelined bytes from the 101 upgrade are not dropped.
455            leading_data: std::mem::take(&mut self.leading_data),
456            connection_guard: self.connection_guard.take(),
457        })
458    }
459}
460
461impl AsyncRead for UpgradedStream {
462    fn poll_read(
463        mut self: Pin<&mut Self>,
464        cx: &mut Context<'_>,
465        buf: &mut ReadBuf<'_>,
466    ) -> Poll<std::io::Result<()>> {
467        // Drain leading data first.
468        if !self.leading_data.is_empty() {
469            let available = self.leading_data.len().min(buf.remaining());
470            let chunk = self.leading_data.split_to(available);
471            buf.put_slice(&chunk);
472            return Poll::Ready(Ok(()));
473        }
474        Pin::new(&mut self.inner).poll_read(cx, buf)
475    }
476}
477
478impl AsyncWrite for UpgradedStream {
479    fn poll_write(
480        mut self: Pin<&mut Self>,
481        cx: &mut Context<'_>,
482        buf: &[u8],
483    ) -> Poll<std::io::Result<usize>> {
484        Pin::new(&mut self.inner).poll_write(cx, buf)
485    }
486
487    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
488        Pin::new(&mut self.inner).poll_flush(cx)
489    }
490
491    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
492        Pin::new(&mut self.inner).poll_shutdown(cx)
493    }
494}
495
496/// A network stream handle exposed on responses for metadata access.
497///
498/// For upgraded connections (101/CONNECT), this provides full
499/// read/write/close/TLS access. For ordinary pooled connections,
500/// this provides read-only metadata — raw IO operations are not
501/// exposed while Hyper still owns the connection.
502///
503/// # Ordinal response limitation
504///
505/// Hyper's legacy client pool retains ownership of socket connections
506/// for ordinary HTTP/1.1 and HTTP/2 responses. The pool does not expose
507/// per-response socket metadata, and raw IO operations would corrupt
508/// pool state. Therefore, `NetworkStream::Metadata` is currently only
509/// constructed for responses where socket metadata can be safely
510/// captured without interfering with the pool. For ordinary responses,
511/// `network_stream` on `Response` is `None`.
512///
513/// This is a documented bounded difference from httpcore, which owns
514/// its connections directly and can expose metadata on every response.
515pub enum NetworkStream {
516    /// An upgraded stream with full IO access.
517    Upgraded(UpgradedStream),
518    /// Read-only metadata for an ordinary pooled connection.
519    ///
520    /// Currently reserved for future use when socket metadata can be
521    /// safely captured from Hyper's connection pool. For ordinary
522    /// responses, `Response::network_stream()` returns `None`.
523    Metadata(Arc<ConnectionMetadata>),
524}
525
526impl NetworkStream {
527    /// Returns the connection metadata.
528    #[must_use]
529    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
530        match self {
531            NetworkStream::Upgraded(s) => s.metadata(),
532            NetworkStream::Metadata(m) => m,
533        }
534    }
535
536    /// Returns `true` if this is an upgraded stream with IO access.
537    #[must_use]
538    pub fn is_upgraded(&self) -> bool {
539        matches!(self, NetworkStream::Upgraded(_))
540    }
541
542    /// If this is an upgraded stream, returns a reference to it.
543    #[must_use]
544    pub fn as_upgraded(&self) -> Option<&UpgradedStream> {
545        match self {
546            NetworkStream::Upgraded(s) => Some(s),
547            NetworkStream::Metadata(_) => None,
548        }
549    }
550
551    /// If this is an upgraded stream, returns a mutable reference.
552    pub fn as_upgraded_mut(&mut self) -> Option<&mut UpgradedStream> {
553        match self {
554            NetworkStream::Upgraded(s) => Some(s),
555            NetworkStream::Metadata(_) => None,
556        }
557    }
558
559    /// If this is an upgraded stream, consume and return it.
560    pub fn into_upgraded(self) -> Option<UpgradedStream> {
561        match self {
562            NetworkStream::Upgraded(s) => Some(s),
563            NetworkStream::Metadata(_) => None,
564        }
565    }
566}
567
568/// Read-only metadata accessible through `get_extra_info()`.
569#[derive(Debug, Clone)]
570pub struct ExtraInfo {
571    /// Local address (`client_addr`).
572    pub client_addr: Option<SocketAddr>,
573    /// Remote address (`server_addr`).
574    pub server_addr: Option<SocketAddr>,
575    /// TLS info, if available.
576    pub tls_info: Option<TlsInfo>,
577}
578
579impl ExtraInfo {
580    /// Create from connection metadata.
581    #[must_use]
582    pub fn from_metadata(meta: &ConnectionMetadata) -> Self {
583        Self {
584            client_addr: meta.local_addr,
585            server_addr: meta.peer_addr,
586            tls_info: meta.tls_info.clone(),
587        }
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    #[test]
596    fn connection_metadata_default() {
597        let meta = ConnectionMetadata::default();
598        assert!(meta.local_addr.is_none());
599        assert!(meta.peer_addr.is_none());
600        assert_eq!(meta.transport_kind, TransportKind::Tcp);
601        assert!(meta.tls_info.is_none());
602    }
603
604    #[test]
605    fn network_stream_metadata_only() {
606        let meta = Arc::new(ConnectionMetadata {
607            local_addr: Some("127.0.0.1:12345".parse().unwrap()),
608            peer_addr: Some("93.184.216.34:443".parse().unwrap()),
609            transport_kind: TransportKind::Tls,
610            tls_info: Some(TlsInfo {
611                alpn_protocol: Some("h2".into()),
612                tls_version: Some("TLSv1.3".into()),
613                cipher_suite: Some("TLS_AES_256_GCM_SHA384".into()),
614                server_name: Some("example.com".into()),
615            }),
616        });
617        let ns = NetworkStream::Metadata(meta.clone());
618        assert!(!ns.is_upgraded());
619        assert!(ns.as_upgraded().is_none());
620        let info = ns.metadata();
621        assert_eq!(info.local_addr.unwrap().port(), 12345);
622        assert_eq!(info.peer_addr.unwrap().port(), 443);
623    }
624
625    #[test]
626    fn extra_info_from_metadata() {
627        let meta = ConnectionMetadata {
628            local_addr: Some("127.0.0.1:1000".parse().unwrap()),
629            peer_addr: Some("10.0.0.1:443".parse().unwrap()),
630            transport_kind: TransportKind::Tcp,
631            tls_info: None,
632        };
633        let info = ExtraInfo::from_metadata(&meta);
634        assert_eq!(info.client_addr.unwrap().port(), 1000);
635        assert_eq!(info.server_addr.unwrap().port(), 443);
636        assert!(info.tls_info.is_none());
637    }
638}