nautilus_network/
net.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Network abstractions for dependency injection and testing.
17//!
18//! This module provides traits and types that allow our networking components
19//! to work with both real networking (`tokio::net`) and simulated networking (`turmoil::net`)
20//! through dependency injection.
21//!
22//! ## Conditional Compilation
23//!
24//! The module re-exports TCP types that are swapped at compile time:
25//! - Default builds: `tokio::net::{TcpStream, TcpListener}`
26//! - Builds with `--features turmoil`: `turmoil::net::{TcpStream, TcpListener}`
27//!
28//! This allows production code to be tested with turmoil's network simulation
29//! without runtime overhead or code changes when the feature flag is enabled.
30
31use std::{future::Future, io::Result};
32
33use tokio::io::{AsyncRead, AsyncWrite};
34// Re-export TCP types based on build configuration
35// Production: use tokio networking
36#[cfg(not(feature = "turmoil"))]
37pub use tokio::net::{TcpListener, TcpStream};
38// Testing with turmoil: use turmoil's simulated networking
39#[cfg(feature = "turmoil")]
40pub use turmoil::net::{TcpListener, TcpStream};
41
42/// Trait for network types that can establish TCP connections.
43pub trait TcpConnector: Send + Sync {
44    type Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static;
45
46    /// Connect to the specified address.
47    fn connect(&self, addr: &str) -> impl Future<Output = Result<Self::Stream>> + Send;
48}
49
50/// Production TCP connector.
51///
52/// Uses `tokio::net::TcpStream` in production, `turmoil::net::TcpStream` in turmoil tests.
53#[derive(Default, Clone, Debug)]
54pub struct RealTcpConnector;
55
56impl TcpConnector for RealTcpConnector {
57    type Stream = TcpStream;
58
59    fn connect(&self, addr: &str) -> impl Future<Output = Result<Self::Stream>> + Send {
60        TcpStream::connect(addr.to_string())
61    }
62}