stream-tungstenite 0.6.1

A streaming implementation of the Tungstenite WebSocket protocol
Documentation
//! Transport layer abstraction for establishing underlying connections.

use async_trait::async_trait;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};

use crate::error::ConnectError;

/// Transport layer abstraction - responsible for establishing raw byte stream connections.
///
/// This trait allows for different transport implementations (TCP, TLS, Unix sockets, etc.)
/// and enables testing with mock transports.
#[async_trait]
pub trait Transport: Send + Sync + 'static {
    /// The underlying stream type produced by this transport
    type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static;

    /// Establish a connection to the given host and port
    async fn connect(&self, host: &str, port: u16) -> Result<Self::Stream, ConnectError>;

    /// Get the transport name (for logging/debugging)
    fn name(&self) -> &'static str;

    /// Get the default port for this transport
    fn default_port(&self) -> u16 {
        80
    }
}

/// Transport configuration options
#[derive(Debug, Clone)]
pub struct TransportConfig {
    /// Connection timeout
    pub connect_timeout: Duration,
    /// Whether to disable Nagle's algorithm (`TCP_NODELAY`)
    pub disable_nagle: bool,
    /// Keep-alive settings
    pub keep_alive: Option<Duration>,
}

impl Default for TransportConfig {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_secs(30),
            disable_nagle: false,
            keep_alive: Some(Duration::from_secs(60)),
        }
    }
}

impl TransportConfig {
    /// Create a new transport config with default values
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set connection timeout
    #[must_use]
    pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Enable or disable Nagle's algorithm
    #[must_use]
    pub const fn with_nagle(mut self, enable: bool) -> Self {
        self.disable_nagle = !enable;
        self
    }

    /// Set keep-alive duration (None to disable)
    #[must_use]
    pub const fn with_keep_alive(mut self, duration: Option<Duration>) -> Self {
        self.keep_alive = duration;
        self
    }

    /// Preset for low-latency connections
    #[must_use]
    pub const fn low_latency() -> Self {
        Self {
            connect_timeout: Duration::from_secs(10),
            disable_nagle: true,
            keep_alive: Some(Duration::from_secs(30)),
        }
    }
}