Skip to main content

nautilus_network/socket/
config.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//! Static transport, framing, heartbeat, and reconnect configuration for TCP sockets.
17//!
18//! # Reconnection strategy
19//!
20//! The default configuration uses unlimited reconnection attempts (`reconnect_max_attempts: None`).
21//! This suits long-lived trading connections because:
22//!
23//! - Venues may remain unavailable for an extended period and later recover.
24//! - Exponential backoff bounds retry frequency during the outage.
25//! - Automatic recovery avoids requiring manual intervention for a transient failure.
26//!
27//! A connection active for at least 10 seconds resets the attempt count and backoff delay.
28//! Shorter-lived connections remain part of the same reconnect cycle. Use `Some(n)` primarily for
29//! tests, development, or connections that should stop retrying without intervention.
30
31use std::fmt::Debug;
32
33use nautilus_core::string::secret::REDACTED;
34use tokio_tungstenite::tungstenite::stream::Mode;
35
36use super::types::TcpMessageHandler;
37use crate::error::{NetworkConfigError, NetworkConfigResult};
38
39/// Application keepalive for a raw TCP socket.
40///
41/// A raw socket has no control frames, so [`Self::payload`] is required. WebSocket keepalives stay
42/// on [`crate::websocket::WebSocketConfig`] and may omit a payload to send a protocol Ping.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct SocketHeartbeat {
45    /// Interval between keepalives, in seconds.
46    ///
47    /// Must be positive.
48    pub interval_secs: u64,
49    /// Bytes sent as each heartbeat, framed with [`SocketConfig::suffix`].
50    pub payload: Vec<u8>,
51}
52
53/// Configuration for a TCP socket connection.
54#[derive(Clone, bon::Builder)]
55#[builder(finish_fn(name = build_inner, vis = ""))]
56pub struct SocketConfig {
57    /// The server address as `host:port` or a URL.
58    pub url: String,
59    /// The plain or TLS connection mode.
60    pub mode: Mode,
61    /// The byte sequence that frames messages in both directions.
62    pub suffix: Vec<u8>,
63    /// The function called for each complete incoming message.
64    pub message_handler: Option<TcpMessageHandler>,
65    /// Optional application keepalive.
66    ///
67    /// When set, the client sends [`SocketHeartbeat::payload`] every
68    /// [`SocketHeartbeat::interval_secs`] seconds. A raw socket has no Ping frames, so this type
69    /// requires a payload; the WebSocket Ping-frame case stays on
70    /// [`crate::websocket::WebSocketConfig::heartbeat_payload`].
71    ///
72    /// Each timing field carries the coarsest unit that expresses every legitimate value, and
73    /// quantities compared against each other share a unit: the interval and
74    /// [`Self::heartbeat_timeout_secs`] are bounded below by whole-second cadences, while reconnect
75    /// delays and jitter have real sub-second values and stay in milliseconds.
76    pub heartbeat: Option<SocketHeartbeat>,
77    /// The timeout (milliseconds) for establishing a usable connection. Defaults to 10 seconds.
78    ///
79    /// Bounds the initial connection attempt, each reconnect attempt, and how long a send waits for
80    /// the client to become active again. Keep it above the reconnect backoff so a send does not
81    /// give up part-way through a normal reconnect. The client has no separate send-wait timeout.
82    pub connect_timeout_ms: Option<u64>,
83    /// The initial reconnection delay (milliseconds) for reconnects.
84    pub reconnect_delay_initial_ms: Option<u64>,
85    /// The maximum reconnect delay (milliseconds) for exponential backoff.
86    pub reconnect_delay_max_ms: Option<u64>,
87    /// The exponential backoff factor for reconnection delays.
88    pub reconnect_backoff_factor: Option<f64>,
89    /// The maximum jitter (milliseconds) added to reconnection delays.
90    pub reconnect_jitter_ms: Option<u64>,
91    /// The maximum number of initial connection attempts, including the first. Defaults to 5.
92    ///
93    /// The field name is retained for compatibility: this bounds total attempts, not retries after
94    /// the first. `Some(0)` and `Some(1)` both make one attempt.
95    pub connection_max_retries: Option<u32>,
96    /// The maximum number of reconnection attempts before closing the client.
97    ///
98    /// - `None`: Unlimited reconnection attempts (default, recommended for production).
99    /// - `Some(0)`: Disables reconnection; any reconnect trigger closes the client.
100    /// - `Some(n)` for `n > 0`: Transitions to CLOSED once `n` consecutive reconnect attempts have
101    ///   either failed or established connections active for less than 10 seconds.
102    pub reconnect_max_attempts: Option<u32>,
103    /// The dead-peer timeout (seconds) for the read task.
104    ///
105    /// Seconds rather than milliseconds because this is a multiple of the heartbeat interval: it
106    /// can never sensibly sit below one heartbeat cycle.
107    ///
108    /// When set, the read task stops and triggers reconnection if no bytes at all arrive within
109    /// this duration. A raw socket has no control frames, so any inbound byte refreshes it,
110    /// including the venue's reply to a heartbeat. That makes this the byte-level equivalent of
111    /// the WebSocket client's `heartbeat_timeout_secs`, not of its `idle_timeout_ms`: there is
112    /// no transport-level way to tell keepalive traffic from data here.
113    ///
114    /// `None` derives three heartbeat intervals when [`Self::heartbeat`] is set, and disables
115    /// detection otherwise. `Some(0)` is rejected. Set an explicit value above the heartbeat
116    /// interval so a healthy connection cannot trip it.
117    pub heartbeat_timeout_secs: Option<u64>,
118    /// The maximum number of outstanding messages, including queued, in-flight, and replay messages.
119    ///
120    /// Defaults to 1,024. Sends fail immediately when full. Must be positive and no greater
121    /// than [`tokio::sync::Semaphore::MAX_PERMITS`]. This bounds message count, not payload bytes.
122    pub writer_capacity: Option<usize>,
123    /// The path to the certificates directory.
124    ///
125    /// Every certificate that parses from any file directly inside the directory, regardless of
126    /// file name, becomes a trust anchor for the connection alongside the bundled `webpki-roots`
127    /// set. No CA or self-signature checks are performed. A certificate chain matched to a
128    /// private key in the directory is used as the client certificate instead. Write access to
129    /// the directory is therefore equivalent to control over which servers the connection
130    /// trusts. Restrict its contents to intended trust anchors. Each anchor loaded from it is
131    /// logged at INFO with its SHA-256 fingerprint.
132    pub certs_dir: Option<String>,
133}
134
135impl<S: socket_config_builder::IsComplete> SocketConfigBuilder<S> {
136    /// Validates and builds the [`SocketConfig`].
137    ///
138    /// # Errors
139    ///
140    /// Returns an error if any field fails validation (see [`SocketConfig::validate`]).
141    pub fn build(self) -> NetworkConfigResult<SocketConfig> {
142        let config = self.build_inner();
143        config.validate()?;
144        Ok(config)
145    }
146}
147
148impl SocketConfig {
149    /// Checks whether all socket settings are valid.
150    ///
151    /// # Errors
152    ///
153    /// Returns an error if `url` is empty, the heartbeat interval or a reconnection timing field is
154    /// not positive, `reconnect_backoff_factor` is outside `[1.0, 100.0]`,
155    /// `reconnect_delay_initial_ms` exceeds `reconnect_delay_max_ms`, or `writer_capacity` is
156    /// outside `[1, Semaphore::MAX_PERMITS]`.
157    pub fn validate(&self) -> NetworkConfigResult<()> {
158        let mut errors = Vec::new();
159        if let Err(e) = crate::writer::validate_capacity(self.writer_capacity) {
160            errors.push(e);
161        }
162
163        if self.url.trim().is_empty() {
164            errors.push(NetworkConfigError::invalid("url", "must not be empty"));
165        }
166
167        if let Some(heartbeat) = &self.heartbeat
168            && heartbeat.interval_secs == 0
169        {
170            errors.push(NetworkConfigError::invalid(
171                "heartbeat",
172                "interval must be positive",
173            ));
174        }
175
176        // A timeout at or below the send cadence tears every connection down before its first
177        // reply is due, so a healthy socket would reconnect forever.
178        if let (Some(heartbeat), Some(timeout_secs)) =
179            (&self.heartbeat, self.heartbeat_timeout_secs)
180            && timeout_secs <= heartbeat.interval_secs
181        {
182            errors.push(NetworkConfigError::invalid(
183                "heartbeat_timeout_secs",
184                format!(
185                    "must exceed heartbeat interval ({}s), was {timeout_secs}s",
186                    heartbeat.interval_secs
187                ),
188            ));
189        }
190
191        // `reconnect_jitter_ms` is intentionally unchecked: zero disables jitter and
192        // `ExponentialBackoff::new` accepts it.
193        for (field, value) in [
194            ("connect_timeout_ms", self.connect_timeout_ms),
195            (
196                "reconnect_delay_initial_ms",
197                self.reconnect_delay_initial_ms,
198            ),
199            ("reconnect_delay_max_ms", self.reconnect_delay_max_ms),
200            ("heartbeat_timeout_secs", self.heartbeat_timeout_secs),
201        ] {
202            if let Some(value) = value
203                && value == 0
204            {
205                errors.push(NetworkConfigError::invalid(
206                    field,
207                    format!("must be positive, was {value}"),
208                ));
209            }
210        }
211
212        if let Some(factor) = self.reconnect_backoff_factor
213            && !(1.0..=100.0).contains(&factor)
214        {
215            errors.push(NetworkConfigError::invalid(
216                "reconnect_backoff_factor",
217                format!("must be in range [1.0, 100.0], was {factor}"),
218            ));
219        }
220
221        if let (Some(initial), Some(max)) =
222            (self.reconnect_delay_initial_ms, self.reconnect_delay_max_ms)
223            && initial > max
224        {
225            errors.push(NetworkConfigError::invalid(
226                "reconnect_delay_initial_ms",
227                format!("must not exceed reconnect_delay_max_ms ({max}), was {initial}"),
228            ));
229        }
230
231        NetworkConfigError::collect(errors)
232    }
233
234    pub(crate) fn resolved_heartbeat_timeout(&self) -> Option<u64> {
235        crate::heartbeat::resolve_heartbeat_timeout(
236            self.heartbeat_timeout_secs,
237            self.heartbeat
238                .as_ref()
239                .map(|heartbeat| heartbeat.interval_secs),
240        )
241    }
242}
243
244impl Debug for SocketConfig {
245    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        f.debug_struct(stringify!(SocketConfig))
247            .field("url", &REDACTED)
248            .field("mode", &self.mode)
249            .field("suffix", &self.suffix)
250            .field(
251                "message_handler",
252                &self.message_handler.as_ref().map(|_| "<function>"),
253            )
254            .field("heartbeat", &self.heartbeat)
255            .field("writer_capacity", &self.writer_capacity)
256            .field("connect_timeout_ms", &self.connect_timeout_ms)
257            .field(
258                "reconnect_delay_initial_ms",
259                &self.reconnect_delay_initial_ms,
260            )
261            .field("reconnect_delay_max_ms", &self.reconnect_delay_max_ms)
262            .field("reconnect_backoff_factor", &self.reconnect_backoff_factor)
263            .field("reconnect_jitter_ms", &self.reconnect_jitter_ms)
264            .field("connection_max_retries", &self.connection_max_retries)
265            .field("reconnect_max_attempts", &self.reconnect_max_attempts)
266            .field("heartbeat_timeout_secs", &self.heartbeat_timeout_secs)
267            .field("certs_dir", &self.certs_dir)
268            .finish()
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use rstest::rstest;
275    use tokio_tungstenite::tungstenite::stream::Mode;
276
277    use super::{SocketConfig, SocketHeartbeat};
278    use crate::error::NetworkConfigError;
279
280    fn valid_config() -> SocketConfig {
281        SocketConfig::builder()
282            .url("tcp://127.0.0.1:8080".to_string())
283            .mode(Mode::Plain)
284            .suffix(vec![b'\n'])
285            .build()
286            .expect("baseline socket config should be valid")
287    }
288
289    #[rstest]
290    fn test_builder_accepts_valid_config() {
291        let result = SocketConfig::builder()
292            .url("tcp://127.0.0.1:8080".to_string())
293            .mode(Mode::Plain)
294            .suffix(vec![b'\n'])
295            .build();
296
297        assert!(result.is_ok());
298    }
299
300    #[rstest]
301    fn test_validate_accepts_zero_jitter() {
302        let mut config = valid_config();
303        config.reconnect_jitter_ms = Some(0);
304
305        assert!(config.validate().is_ok());
306    }
307
308    #[rstest]
309    fn test_validate_accepts_heartbeat_with_payload() {
310        let mut config = valid_config();
311        config.heartbeat = Some(SocketHeartbeat {
312            interval_secs: 5,
313            payload: b"ping".to_vec(),
314        });
315
316        assert!(config.validate().is_ok());
317    }
318
319    #[rstest]
320    #[case::derived(None, Some(15))]
321    #[case::explicit_wins(Some(20), Some(20))]
322    fn test_resolve_timeout_from_socket_heartbeat(
323        #[case] timeout_secs: Option<u64>,
324        #[case] expected: Option<u64>,
325    ) {
326        let mut config = valid_config();
327        config.heartbeat = Some(SocketHeartbeat {
328            interval_secs: 5,
329            payload: b"ping".to_vec(),
330        });
331
332        config.heartbeat_timeout_secs = timeout_secs;
333
334        assert_eq!(config.resolved_heartbeat_timeout(), expected);
335    }
336
337    #[rstest]
338    #[case::writer_capacity_zero(|c: &mut SocketConfig| c.writer_capacity = Some(0), "writer_capacity")]
339    #[case::writer_capacity_excess(|c: &mut SocketConfig| c.writer_capacity = Some(usize::MAX), "writer_capacity")]
340    #[case::empty_url(|c: &mut SocketConfig| c.url = String::new(), "url")]
341    #[case::heartbeat_interval(|c: &mut SocketConfig| { c.heartbeat = Some(SocketHeartbeat { interval_secs: 0, payload: vec![] }); }, "heartbeat")]
342    #[case::heartbeat_timeout_below_interval(|c: &mut SocketConfig| { c.heartbeat = Some(SocketHeartbeat { interval_secs: 5, payload: vec![b'p'] }); c.heartbeat_timeout_secs = Some(5); }, "heartbeat_timeout_secs")]
343    #[case::connect_timeout(|c: &mut SocketConfig| c.connect_timeout_ms = Some(0), "connect_timeout_ms")]
344    #[case::reconnect_delay_initial(|c: &mut SocketConfig| c.reconnect_delay_initial_ms = Some(0), "reconnect_delay_initial_ms")]
345    #[case::reconnect_delay_max(|c: &mut SocketConfig| c.reconnect_delay_max_ms = Some(0), "reconnect_delay_max_ms")]
346    #[case::heartbeat_timeout_zero(|c: &mut SocketConfig| c.heartbeat_timeout_secs = Some(0), "heartbeat_timeout_secs")]
347    fn test_validate_rejects_invalid_field(
348        #[case] mutate: fn(&mut SocketConfig),
349        #[case] expected_field: &str,
350    ) {
351        let mut config = valid_config();
352        mutate(&mut config);
353
354        let err = config
355            .validate()
356            .expect_err("invalid value should be rejected");
357
358        assert!(
359            matches!(err, NetworkConfigError::Invalid { field, .. } if field == expected_field)
360        );
361    }
362
363    #[rstest]
364    #[case::too_small(0.5)]
365    #[case::too_large(100.1)]
366    #[case::nan(f64::NAN)]
367    #[case::infinite(f64::INFINITY)]
368    fn test_validate_rejects_invalid_backoff_factor(#[case] factor: f64) {
369        let mut config = valid_config();
370        config.reconnect_backoff_factor = Some(factor);
371
372        let err = config
373            .validate()
374            .expect_err("invalid backoff factor should be rejected");
375
376        assert!(
377            matches!(err, NetworkConfigError::Invalid { field, .. } if field == "reconnect_backoff_factor")
378        );
379    }
380
381    #[rstest]
382    fn test_validate_rejects_delay_initial_exceeding_max() {
383        let mut config = valid_config();
384        config.reconnect_delay_initial_ms = Some(5_000);
385        config.reconnect_delay_max_ms = Some(1_000);
386
387        let err = config
388            .validate()
389            .expect_err("initial delay above max should be rejected");
390
391        assert!(
392            matches!(err, NetworkConfigError::Invalid { field, .. } if field == "reconnect_delay_initial_ms")
393        );
394    }
395
396    #[rstest]
397    fn test_validate_collects_multiple_errors() {
398        let mut config = valid_config();
399        config.url = String::new();
400        config.connect_timeout_ms = Some(0);
401
402        let err = config.validate().expect_err("multiple invalid fields");
403
404        match err {
405            NetworkConfigError::Multiple { errors } => assert_eq!(errors.len(), 2),
406            other @ NetworkConfigError::Invalid { .. } => {
407                panic!("expected Multiple, was {other:?}")
408            }
409        }
410    }
411
412    #[rstest]
413    fn test_debug_redacts_endpoint_credentials() {
414        const ENDPOINT_PATH_SECRET: &str = "unique-endpoint-path-secret";
415        const ENDPOINT_QUERY_SECRET: &str = "unique-endpoint-query-secret";
416        let mut config = valid_config();
417        config.url =
418            format!("wss://rpc.example.com/{ENDPOINT_PATH_SECRET}?api_key={ENDPOINT_QUERY_SECRET}");
419
420        let debug = format!("{config:?}");
421
422        assert!(debug.contains("url: \"<redacted>\""));
423        assert!(!debug.contains(ENDPOINT_PATH_SECRET));
424        assert!(!debug.contains(ENDPOINT_QUERY_SECRET));
425    }
426}