Skip to main content

nautilus_network/
net.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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//! The traits and type aliases let network clients use either real `tokio` networking or simulated
19//! `turmoil` networking through dependency injection. `apply_socket_options` is the single place
20//! every connect path configures its TCP socket.
21//!
22//! ## Conditional compilation
23//!
24//! The module selects TCP types at compile time:
25//! - Default builds: `tokio::net::{TcpStream, TcpListener}`
26//! - Builds with `--features turmoil`: `turmoil::net::{TcpStream, TcpListener}`
27//!
28//! Production code therefore runs against the simulator without source changes, while default
29//! builds incur no runtime dispatch or simulation overhead.
30
31#[cfg(not(feature = "turmoil"))]
32use std::time::Duration;
33use std::{future::Future, io::Result};
34
35#[cfg(not(feature = "turmoil"))]
36use socket2::{SockRef, TcpKeepalive};
37use tokio::io::{AsyncRead, AsyncWrite};
38// Re-export TCP types based on build configuration
39// Production: use tokio networking
40#[cfg(not(feature = "turmoil"))]
41pub use tokio::net::{TcpListener, TcpStream};
42// Testing with turmoil: use turmoil's simulated networking
43#[cfg(feature = "turmoil")]
44pub use turmoil::net::{TcpListener, TcpStream};
45
46/// Trait for network types that can establish TCP connections.
47pub trait TcpConnector: Send + Sync {
48    type Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static;
49
50    /// Connects to the specified address.
51    fn connect(&self, addr: &str) -> impl Future<Output = Result<Self::Stream>> + Send;
52}
53
54/// Production TCP connector.
55///
56/// Uses `tokio::net::TcpStream` in production, `turmoil::net::TcpStream` in turmoil tests.
57#[derive(Default, Clone, Debug)]
58pub struct RealTcpConnector;
59
60impl TcpConnector for RealTcpConnector {
61    type Stream = TcpStream;
62
63    fn connect(&self, addr: &str) -> impl Future<Output = Result<Self::Stream>> + Send {
64        TcpStream::connect(addr)
65    }
66}
67
68/// Applies the standard socket options for a long-lived venue connection.
69///
70/// Disables Nagle so small frames leave immediately, enables TCP keepalive so a half-open peer is
71/// detected in roughly a minute instead of the multi-hour platform default, and on Linux bounds
72/// unacknowledged outbound data. Without keepalive, writes to a connection dropped by a NAT or load
73/// balancer without a FIN or RST keep succeeding into the send buffer for as long as it takes that
74/// buffer to fill.
75///
76/// These are a kernel-level backstop operating in tens of seconds. The application-level heartbeat
77/// timeouts remain the primary detector, and are the only thing that sees a peer whose transport is
78/// healthy but which has stopped sending.
79///
80/// A socket that rejects an option is still usable, so failures are logged and execution continues.
81pub(crate) fn apply_socket_options(stream: &TcpStream) {
82    if let Err(e) = stream.set_nodelay(true) {
83        log::warn!("Failed to enable TCP_NODELAY: {e}");
84    }
85
86    apply_keepalive(stream);
87}
88
89/// Idle period before the kernel sends the first TCP keepalive probe.
90#[cfg(not(feature = "turmoil"))]
91const KEEPALIVE_TIME: Duration = Duration::from_secs(20);
92
93/// Interval between successive TCP keepalive probes.
94#[cfg(not(feature = "turmoil"))]
95const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
96
97/// Unanswered TCP keepalive probes tolerated before the peer is declared gone.
98#[cfg(not(feature = "turmoil"))]
99const KEEPALIVE_RETRIES: u32 = 3;
100
101/// Ceiling on how long transmitted data may stay unacknowledged before the kernel drops the
102/// connection.
103///
104/// Must not be shorter than the full keepalive probe budget
105/// (`KEEPALIVE_TIME + KEEPALIVE_INTERVAL * KEEPALIVE_RETRIES`), because Linux applies this timeout
106/// to the probe sequence as well and would otherwise cut it short.
107///
108/// Linux additionally lets this value override `TCP_KEEPCNT`, dropping the connection once a probe
109/// has been outstanding this long. Detection there is therefore governed by this timeout rather
110/// than by `KEEPALIVE_RETRIES`, which only bounds the probe count on macOS and Windows.
111#[cfg(all(not(feature = "turmoil"), target_os = "linux"))]
112const UNACKED_DATA_TIMEOUT: Duration = Duration::from_mins(1);
113
114#[cfg(not(feature = "turmoil"))]
115fn apply_keepalive(stream: &TcpStream) {
116    let socket = SockRef::from(stream);
117    let keepalive = TcpKeepalive::new()
118        .with_time(KEEPALIVE_TIME)
119        .with_interval(KEEPALIVE_INTERVAL)
120        .with_retries(KEEPALIVE_RETRIES);
121
122    if let Err(e) = socket.set_tcp_keepalive(&keepalive) {
123        log::warn!("Failed to enable TCP keepalive: {e}");
124    }
125
126    #[cfg(target_os = "linux")]
127    if let Err(e) = socket.set_tcp_user_timeout(Some(UNACKED_DATA_TIMEOUT)) {
128        log::warn!("Failed to set TCP_USER_TIMEOUT: {e}");
129    }
130}
131
132/// The turmoil simulator models TCP without a file descriptor, so there is nothing for the
133/// keepalive options to apply to.
134#[cfg(feature = "turmoil")]
135const fn apply_keepalive(_stream: &TcpStream) {}
136
137#[cfg(all(test, not(feature = "turmoil")))]
138mod tests {
139    use rstest::rstest;
140    use tokio::net::TcpListener;
141
142    use super::*;
143
144    #[rstest]
145    #[tokio::test]
146    async fn test_apply_socket_options_sets_nodelay_and_keepalive() {
147        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
148        let addr = listener.local_addr().unwrap();
149        let accept = tokio::spawn(async move { listener.accept().await.unwrap() });
150        let stream = TcpStream::connect(addr).await.unwrap();
151        let _accepted = accept.await.unwrap();
152
153        apply_socket_options(&stream);
154
155        let socket = SockRef::from(&stream);
156
157        assert!(stream.nodelay().unwrap());
158        assert!(socket.keepalive().unwrap());
159        assert_eq!(socket.tcp_keepalive_time().unwrap(), KEEPALIVE_TIME);
160
161        #[cfg(target_os = "linux")]
162        assert_eq!(
163            socket.tcp_user_timeout().unwrap(),
164            Some(UNACKED_DATA_TIMEOUT)
165        );
166    }
167
168    /// The kernel applies `TCP_USER_TIMEOUT` to the keepalive probe sequence, so a value below the
169    /// full probe budget would cut detection short and silently defeat the retry count.
170    #[cfg(target_os = "linux")]
171    #[rstest]
172    fn test_unacked_timeout_covers_keepalive_probe_budget() {
173        let probe_budget = KEEPALIVE_TIME + KEEPALIVE_INTERVAL * KEEPALIVE_RETRIES;
174
175        assert!(UNACKED_DATA_TIMEOUT >= probe_budget);
176    }
177}