Skip to main content

nautilus_network/websocket/
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 and lifecycle configuration for WebSocket connections.
17//!
18//! [`WebSocketConfig`] selects the endpoint, upgrade headers, heartbeat and idle detection,
19//! reconnect policy, inbound size limits, transport backend, and optional proxy. Runtime handlers
20//! and rate limiting are supplied through the client builders instead.
21//!
22//! # Reconnection strategy
23//!
24//! Reconnect settings apply only in handler mode; stream mode ignores them.
25//! `reconnect_max_attempts: None` permits unlimited attempts with exponential backoff, while
26//! `Some(n)` closes the client once `n` consecutive reconnect attempts have either failed or
27//! established connections active for less than 10 seconds. A reconnect active for at least 10
28//! seconds resets its attempt count and backoff delay; shorter-lived connections continue the
29//! current cycle.
30
31use std::{fmt::Debug, num::NonZeroU32, time::Duration};
32
33use nautilus_core::string::secret::REDACTED;
34use serde::{Deserialize, Serialize};
35
36use crate::error::{NetworkConfigError, NetworkConfigResult};
37
38/// WebSocket transport backend selection.
39///
40/// Selection is runtime so multiple backends can compile side-by-side without
41/// a `compile_error!` collision under `--all-features`.
42///
43/// `Sockudo` is the default backend and is enabled by the `transport-sockudo`
44/// Cargo feature (on by default); it uses a local HTTP/1.1 handshake path to
45/// pass custom upgrade headers through. When the feature is disabled the
46/// default falls back to `Tungstenite`, which is always compiled and supports
47/// custom HTTP upgrade headers on the WebSocket handshake (see
48/// [`WebSocketConfig::headers`]).
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51#[cfg_attr(
52    feature = "python",
53    pyo3::pyclass(
54        module = "nautilus_trader.network",
55        eq,
56        from_py_object,
57        rename_all = "SCREAMING_SNAKE_CASE"
58    )
59)]
60#[cfg_attr(
61    feature = "python",
62    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.network")
63)]
64#[allow(
65    clippy::unsafe_derive_deserialize,
66    reason = "network configuration requires strict serde decoding"
67)]
68pub enum TransportBackend {
69    /// `tokio-tungstenite` backed transport (default when `transport-sockudo` is disabled).
70    #[cfg_attr(not(feature = "transport-sockudo"), default)]
71    Tungstenite,
72    /// `sockudo-ws` backed transport (default; gated on `transport-sockudo` feature).
73    #[cfg_attr(feature = "transport-sockudo", default)]
74    Sockudo,
75}
76
77/// Static configuration for WebSocket client connections.
78///
79/// Runtime handlers and rate limiters are passed separately through the client builders.
80///
81/// # Connection modes
82///
83/// ## Handler mode
84///
85/// - Uses [`WebSocketClient::builder`](crate::websocket::WebSocketClient::builder).
86/// - Delivers messages through the supplied callback.
87/// - Runs the reader in an internal task.
88/// - Supports automatic reconnection with exponential backoff.
89/// - Applies `reconnect_*`, `heartbeat_timeout_secs`, and `idle_timeout_ms` settings.
90/// - Suits long-lived connections and callback-based APIs.
91///
92/// ## Stream mode
93///
94/// - Uses [`WebSocketClient::stream_builder`](crate::websocket::WebSocketClient::stream_builder).
95/// - Returns a [`MessageReader`](super::types::MessageReader) owned by the caller.
96/// - Does not support automatic reconnection because the client cannot replace the caller's reader.
97/// - Ignores `reconnect_*`, `heartbeat_timeout_secs`, and `idle_timeout_ms` settings.
98/// - Enters the closed state after disconnection, requiring the caller to create a new connection.
99#[allow(
100    clippy::unsafe_derive_deserialize,
101    reason = "network configuration requires strict serde decoding"
102)]
103#[derive(Clone, Serialize, Deserialize, bon::Builder)]
104#[builder(finish_fn(name = build_inner, vis = ""))]
105#[serde(deny_unknown_fields)]
106pub struct WebSocketConfig {
107    /// The URL to connect to.
108    pub url: String,
109    /// The default headers.
110    #[serde(default)]
111    #[builder(default)]
112    pub headers: Vec<(String, String)>,
113    /// The optional heartbeat interval (seconds).
114    ///
115    /// Each timing field carries the coarsest unit that expresses every legitimate value, and
116    /// quantities compared against each other share a unit: this and [`Self::heartbeat_timeout_secs`]
117    /// are bounded below by whole-second cadences, while reconnect delays and jitter have real
118    /// sub-second values and stay in milliseconds.
119    #[serde(default)]
120    pub heartbeat_interval_secs: Option<u64>,
121    /// The optional heartbeat payload sent as a text frame.
122    ///
123    /// When `None`, the heartbeat is an empty Ping control frame instead. A venue that counts only
124    /// an application-level keepalive needs the text form; the two are not interchangeable.
125    #[serde(default)]
126    pub heartbeat_payload: Option<String>,
127    /// The timeout (milliseconds) for establishing a usable connection. Defaults to 10 seconds.
128    ///
129    /// Bounds three things: the initial connection attempt, each reconnect attempt, and how long a
130    /// send waits for the client to become active again. A short value therefore makes sends give
131    /// up early during a reconnect as well as failing a connection attempt faster; keep it above
132    /// the reconnect backoff. The client has no separate send-wait timeout.
133    ///
134    /// Only applies to handler mode and must be non-zero when set. Stream mode ignores this field
135    /// and bounds its connection attempt at 10 seconds.
136    #[serde(default)]
137    pub connect_timeout_ms: Option<u64>,
138    /// The initial reconnection delay (milliseconds) for reconnects.
139    ///
140    /// Only applies to handler mode. Stream mode ignores this field.
141    #[serde(default)]
142    pub reconnect_delay_initial_ms: Option<u64>,
143    /// The maximum reconnect delay (milliseconds) for exponential backoff.
144    ///
145    /// Only applies to handler mode. Stream mode ignores this field.
146    #[serde(default)]
147    pub reconnect_delay_max_ms: Option<u64>,
148    /// The exponential backoff factor for reconnection delays.
149    ///
150    /// Only applies to handler mode. Stream mode ignores this field.
151    #[serde(default)]
152    pub reconnect_backoff_factor: Option<f64>,
153    /// The maximum jitter (milliseconds) added to reconnection delays.
154    ///
155    /// Only applies to handler mode. Stream mode ignores this field.
156    #[serde(default)]
157    pub reconnect_jitter_ms: Option<u64>,
158    /// The maximum number of reconnection attempts before giving up.
159    ///
160    /// Only applies to handler mode. Stream mode ignores this field.
161    ///
162    /// - `None`: Unlimited reconnection attempts (default, recommended for production).
163    /// - `Some(0)`: Disables reconnection; any reconnect trigger closes the client.
164    /// - `Some(n)` for `n > 0`: Transitions to CLOSED once `n` consecutive reconnect attempts have
165    ///   either failed or established connections active for less than 10 seconds.
166    #[serde(default)]
167    pub reconnect_max_attempts: Option<u32>,
168    /// The dead-peer timeout (seconds) for the read task.
169    ///
170    /// Seconds rather than milliseconds because this is a multiple of
171    /// [`Self::heartbeat_interval_secs`]: it can never sensibly sit below one heartbeat cycle.
172    ///
173    /// When set, the read task stops and triggers reconnection if no inbound frame of any kind
174    /// arrives within this duration. Ping and Pong both refresh it, so this detects a peer that has
175    /// gone silent rather than one whose feed is merely quiet. Continuation frames refresh it
176    /// before their message is complete. Set it above
177    /// [`Self::heartbeat_interval_secs`] so a healthy connection cannot trip it; three intervals is
178    /// the usual choice, tolerating two lost replies.
179    ///
180    /// `None` derives three heartbeat intervals when a heartbeat is configured, and disables
181    /// detection otherwise. `Some(0)` is rejected.
182    ///
183    /// Only applies to handler mode; stream mode ignores this field.
184    #[serde(default)]
185    pub heartbeat_timeout_secs: Option<u64>,
186    /// The idle timeout (milliseconds) for the read task.
187    ///
188    /// When set, the read task stops and triggers reconnection if no Text or Binary frame arrives
189    /// within this duration. Ping and Pong deliberately do not refresh it, so this detects a feed
190    /// that has stopped flowing even while the transport is provably alive. Contrast
191    /// [`Self::heartbeat_timeout_secs`], which any inbound frame refreshes.
192    ///
193    /// `None` disables this timeout. `Some(0)` is rejected. Adapters that expose a required integer
194    /// map `0` to `None` rather than passing it through.
195    ///
196    /// The raw-socket client has no equivalent: TCP carries no control frames, so there is no
197    /// transport-level way to tell keepalive traffic from data.
198    ///
199    /// A venue answering the keepalive with a text payload refreshes this timer exactly like real
200    /// data does, so on those venues the window must sit below
201    /// [`Self::heartbeat_interval_secs`] to mean anything. Prefer
202    /// [`Self::heartbeat_timeout_secs`] unless the venue guarantees periodic inbound data.
203    ///
204    /// Only applies to handler mode; stream mode ignores this field.
205    #[serde(default)]
206    pub idle_timeout_ms: Option<u64>,
207    /// The maximum number of outstanding ordinary messages, including queued, in-flight, and replay messages.
208    ///
209    /// Ownership-bound sends, keepalives, and control frames share a separate allowance of the same size,
210    /// so authentication can proceed when replay fills the ordinary allowance.
211    ///
212    /// Defaults to 1,024. Sends fail immediately when full. Must be positive and no greater
213    /// than [`tokio::sync::Semaphore::MAX_PERMITS`]. This bounds message count, not payload bytes.
214    #[serde(default)]
215    pub writer_capacity: Option<usize>,
216    /// The transport backend to use for the WebSocket connection.
217    ///
218    /// Defaults to [`TransportBackend::Sockudo`] when the `transport-sockudo`
219    /// Cargo feature is enabled (the default), otherwise [`TransportBackend::Tungstenite`].
220    /// When the feature is disabled, `connect_with_server` returns an error if
221    /// `Sockudo` is selected. Both backends pass `headers` into the HTTP
222    /// upgrade request and both honor [`Self::proxy_url`].
223    #[serde(default)]
224    #[builder(default)]
225    pub backend: TransportBackend,
226    /// Optional forward proxy URL for the WebSocket connection.
227    ///
228    /// Routes the connection through an HTTP `CONNECT` tunnel. Accepts
229    /// `http://` and `https://` schemes; SOCKS schemes are not yet supported.
230    #[serde(default)]
231    pub proxy_url: Option<String>,
232    /// Maximum size in bytes of one inbound WebSocket message.
233    ///
234    /// `None` passes the selected backend's default message cap of 64 MiB. The cap applies to
235    /// single-frame and fragmented messages. `Some(0)` is rejected. A message that exceeds this cap
236    /// and fits in the frame cap fails the read with `MessageTooLarge`. This cap does not bound
237    /// per-frame memory: both backends apply it after the frame payload is read. Set
238    /// `max_frame_size_bytes` for that bound.
239    #[serde(default)]
240    pub max_message_size_bytes: Option<usize>,
241    /// Maximum size in bytes of one inbound WebSocket frame payload, excluding the frame header.
242    ///
243    /// `None` keeps the selected backend's default of 16 MiB. `Some(0)` is rejected. Sockudo reports
244    /// a frame that exceeds the cap as `FrameTooLarge`, including a fully buffered small frame.
245    /// Tungstenite uses one capacity error for both limits, so every frame breach is
246    /// `MessageTooLarge`. On Sockudo, a frame that exceeds this cap fails before the message cap.
247    #[serde(default)]
248    pub max_frame_size_bytes: Option<usize>,
249}
250
251impl Debug for WebSocketConfig {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct(stringify!(WebSocketConfig))
254            .field("url", &REDACTED)
255            .field(
256                "headers",
257                &format_args!("<{} header(s)>", self.headers.len()),
258            )
259            .field("heartbeat_interval_secs", &self.heartbeat_interval_secs)
260            .field("heartbeat_payload", &self.heartbeat_payload)
261            .field("writer_capacity", &self.writer_capacity)
262            .field("connect_timeout_ms", &self.connect_timeout_ms)
263            .field(
264                "reconnect_delay_initial_ms",
265                &self.reconnect_delay_initial_ms,
266            )
267            .field("reconnect_delay_max_ms", &self.reconnect_delay_max_ms)
268            .field("reconnect_backoff_factor", &self.reconnect_backoff_factor)
269            .field("reconnect_jitter_ms", &self.reconnect_jitter_ms)
270            .field("reconnect_max_attempts", &self.reconnect_max_attempts)
271            .field("heartbeat_timeout_secs", &self.heartbeat_timeout_secs)
272            .field("idle_timeout_ms", &self.idle_timeout_ms)
273            .field("backend", &self.backend)
274            .field("proxy_url", &self.proxy_url.as_ref().map(|_| REDACTED))
275            .field("max_message_size_bytes", &self.max_message_size_bytes)
276            .field("max_frame_size_bytes", &self.max_frame_size_bytes)
277            .finish()
278    }
279}
280
281impl<S: web_socket_config_builder::IsComplete> WebSocketConfigBuilder<S> {
282    /// Validates and builds the [`WebSocketConfig`].
283    ///
284    /// # Errors
285    ///
286    /// Returns an error if any field fails validation (see [`WebSocketConfig::validate`]).
287    pub fn build(self) -> NetworkConfigResult<WebSocketConfig> {
288        let config = self.build_inner();
289        config.validate()?;
290        Ok(config)
291    }
292}
293
294impl WebSocketConfig {
295    /// Checks whether all WebSocket settings are valid.
296    ///
297    /// # Errors
298    ///
299    /// Returns an error if `url` is empty, the heartbeat interval, a reconnection timing field, or
300    /// an inbound size limit is not positive, `reconnect_backoff_factor` is outside `[1.0, 100.0]`,
301    /// `reconnect_delay_initial_ms` exceeds `reconnect_delay_max_ms`, or `writer_capacity` is
302    /// outside `[1, Semaphore::MAX_PERMITS]`.
303    pub fn validate(&self) -> NetworkConfigResult<()> {
304        let mut errors = Vec::new();
305        if let Err(e) = crate::writer::validate_capacity(self.writer_capacity) {
306            errors.push(e);
307        }
308
309        if self.url.trim().is_empty() {
310            errors.push(NetworkConfigError::invalid("url", "must not be empty"));
311        }
312
313        if let Some(interval) = self.heartbeat_interval_secs
314            && interval == 0
315        {
316            errors.push(NetworkConfigError::invalid(
317                "heartbeat_interval_secs",
318                "interval must be positive",
319            ));
320        }
321
322        // A timeout at or below the send cadence tears every connection down before its first
323        // reply is due, so a healthy socket would reconnect forever.
324        if let (Some(interval_secs), Some(timeout_secs)) =
325            (self.heartbeat_interval_secs, self.heartbeat_timeout_secs)
326            && timeout_secs <= interval_secs
327        {
328            errors.push(NetworkConfigError::invalid(
329                "heartbeat_timeout_secs",
330                format!(
331                    "must exceed heartbeat_interval_secs ({interval_secs}s), was {timeout_secs}s"
332                ),
333            ));
334        }
335
336        // `reconnect_jitter_ms` is intentionally unchecked: zero disables jitter and
337        // `ExponentialBackoff::new` accepts it.
338        for (field, value) in [
339            ("connect_timeout_ms", self.connect_timeout_ms),
340            (
341                "reconnect_delay_initial_ms",
342                self.reconnect_delay_initial_ms,
343            ),
344            ("reconnect_delay_max_ms", self.reconnect_delay_max_ms),
345            ("heartbeat_timeout_secs", self.heartbeat_timeout_secs),
346            ("idle_timeout_ms", self.idle_timeout_ms),
347        ] {
348            if let Some(value) = value
349                && value == 0
350            {
351                errors.push(NetworkConfigError::invalid(
352                    field,
353                    format!("must be positive, was {value}"),
354                ));
355            }
356        }
357
358        for (field, value) in [
359            ("max_message_size_bytes", self.max_message_size_bytes),
360            ("max_frame_size_bytes", self.max_frame_size_bytes),
361        ] {
362            if let Some(value) = value
363                && value == 0
364            {
365                errors.push(NetworkConfigError::invalid(
366                    field,
367                    format!("must be positive, was {value}"),
368                ));
369            }
370        }
371
372        if let Some(factor) = self.reconnect_backoff_factor
373            && !(1.0..=100.0).contains(&factor)
374        {
375            errors.push(NetworkConfigError::invalid(
376                "reconnect_backoff_factor",
377                format!("must be in range [1.0, 100.0], was {factor}"),
378            ));
379        }
380
381        if let (Some(initial), Some(max)) =
382            (self.reconnect_delay_initial_ms, self.reconnect_delay_max_ms)
383            && initial > max
384        {
385            errors.push(NetworkConfigError::invalid(
386                "reconnect_delay_initial_ms",
387                format!("must not exceed reconnect_delay_max_ms ({max}), was {initial}"),
388            ));
389        }
390
391        NetworkConfigError::collect(errors)
392    }
393
394    pub(crate) fn resolved_heartbeat_timeout(&self) -> Option<u64> {
395        crate::heartbeat::resolve_heartbeat_timeout(
396            self.heartbeat_timeout_secs,
397            self.heartbeat_interval_secs,
398        )
399    }
400}
401
402/// Retry policy for establishing the initial handler-mode connection.
403///
404/// Supplied to the client builder rather than held in [`WebSocketConfig`], because it governs a
405/// single invocation of `connect` and has no meaning once a client exists. Without a policy the
406/// builder makes exactly one attempt.
407///
408/// This does not affect automatic reconnection after a connection has been established; that is
409/// configured by the `reconnect_*` fields of [`WebSocketConfig`].
410///
411/// An attempt is retried only after `ConnectionClosed`, `ConnectionReset`, or `ClosedByPeer`; an
412/// I/O error of any kind except `InvalidInput`, `InvalidData`, `Unsupported`, and
413/// `PermissionDenied`; or an HTTP upgrade or proxy `CONNECT` rejection carrying status 408, 425,
414/// 429, or 500 through 599. Every other transport error and rejection status returns immediately
415/// without waiting for a backoff delay, however many attempts remain.
416///
417/// The classification is by error variant, not by cause, and the backends do not map causes to
418/// variants uniformly - a TLS failure is permanent as `Tls` but follows the I/O rule where a
419/// backend reports it as `Io`. A permanent failure on the first attempt is indistinguishable from
420/// an exhausted ladder by the returned error alone.
421#[derive(Clone, Debug)]
422pub struct InitialConnectRetryPolicy {
423    /// Maximum number of connection attempts, including the first attempt.
424    ///
425    /// A value of 1 disables retries. This is an upper bound rather than a promise: a failure
426    /// classified as permanent returns before the bound is reached.
427    pub max_attempts: NonZeroU32,
428    /// Delay before the second connection attempt.
429    pub delay_initial: Duration,
430    /// Maximum delay between connection attempts.
431    pub delay_max: Duration,
432    /// Multiplier applied to the delay after each failed attempt.
433    pub backoff_factor: f64,
434    /// Maximum random jitter added to each delay, in milliseconds.
435    pub jitter_ms: u64,
436}
437
438#[cfg(test)]
439mod tests {
440    use rstest::rstest;
441    use serde_json::json;
442
443    use super::WebSocketConfig;
444    use crate::error::NetworkConfigError;
445
446    #[rstest]
447    fn test_deserialize_websocket_config_rejects_unknown_field() {
448        let config = json!({
449            "url": "wss://example.com/ws",
450            "unexpected": true,
451        });
452
453        let error = serde_json::from_value::<WebSocketConfig>(config).unwrap_err();
454
455        assert!(error.to_string().contains("unknown field `unexpected`"));
456    }
457
458    fn valid_config() -> WebSocketConfig {
459        WebSocketConfig::builder()
460            .url("wss://example.com/ws".to_string())
461            .build()
462            .expect("baseline websocket config should be valid")
463    }
464
465    #[rstest]
466    fn test_builder_accepts_valid_config() {
467        let result = WebSocketConfig::builder()
468            .url("wss://example.com/ws".to_string())
469            .build();
470
471        assert!(result.is_ok());
472    }
473
474    #[rstest]
475    fn test_deserialize_websocket_config_defaults_inbound_size_limits() {
476        let config = serde_json::from_value::<WebSocketConfig>(json!({
477            "url": "wss://example.com/ws",
478        }))
479        .unwrap();
480
481        assert_eq!(config.max_message_size_bytes, None);
482        assert_eq!(config.max_frame_size_bytes, None);
483    }
484
485    #[rstest]
486    fn test_validate_accepts_positive_inbound_size_limits() {
487        let mut config = valid_config();
488        config.max_message_size_bytes = Some(1);
489        config.max_frame_size_bytes = Some(1);
490
491        assert!(config.validate().is_ok());
492    }
493
494    #[rstest]
495    fn test_validate_accepts_zero_jitter() {
496        let mut config = valid_config();
497        config.reconnect_jitter_ms = Some(0);
498
499        assert!(config.validate().is_ok());
500    }
501
502    #[rstest]
503    #[case::writer_capacity_zero(|c: &mut WebSocketConfig| c.writer_capacity = Some(0), "writer_capacity")]
504    #[case::writer_capacity_excess(|c: &mut WebSocketConfig| c.writer_capacity = Some(usize::MAX), "writer_capacity")]
505    #[case::empty_url(|c: &mut WebSocketConfig| c.url = String::new(), "url")]
506    #[case::heartbeat_interval(|c: &mut WebSocketConfig| c.heartbeat_interval_secs = Some(0), "heartbeat_interval_secs")]
507    #[case::heartbeat_timeout_below_interval(|c: &mut WebSocketConfig| { c.heartbeat_interval_secs = Some(30); c.heartbeat_timeout_secs = Some(30); }, "heartbeat_timeout_secs")]
508    #[case::connect_timeout(|c: &mut WebSocketConfig| c.connect_timeout_ms = Some(0), "connect_timeout_ms")]
509    #[case::reconnect_delay_initial(|c: &mut WebSocketConfig| c.reconnect_delay_initial_ms = Some(0), "reconnect_delay_initial_ms")]
510    #[case::reconnect_delay_max(|c: &mut WebSocketConfig| c.reconnect_delay_max_ms = Some(0), "reconnect_delay_max_ms")]
511    #[case::heartbeat_timeout_zero(|c: &mut WebSocketConfig| c.heartbeat_timeout_secs = Some(0), "heartbeat_timeout_secs")]
512    #[case::idle_timeout(|c: &mut WebSocketConfig| c.idle_timeout_ms = Some(0), "idle_timeout_ms")]
513    #[case::message_size(|c: &mut WebSocketConfig| c.max_message_size_bytes = Some(0), "max_message_size_bytes")]
514    #[case::frame_size(|c: &mut WebSocketConfig| c.max_frame_size_bytes = Some(0), "max_frame_size_bytes")]
515    fn test_validate_rejects_invalid_field(
516        #[case] mutate: fn(&mut WebSocketConfig),
517        #[case] expected_field: &str,
518    ) {
519        let mut config = valid_config();
520        mutate(&mut config);
521
522        let err = config
523            .validate()
524            .expect_err("invalid value should be rejected");
525
526        assert!(
527            matches!(err, NetworkConfigError::Invalid { field, .. } if field == expected_field)
528        );
529    }
530
531    #[rstest]
532    #[case::too_small(0.5)]
533    #[case::too_large(100.1)]
534    #[case::nan(f64::NAN)]
535    #[case::infinite(f64::INFINITY)]
536    fn test_validate_rejects_invalid_backoff_factor(#[case] factor: f64) {
537        let mut config = valid_config();
538        config.reconnect_backoff_factor = Some(factor);
539
540        let err = config
541            .validate()
542            .expect_err("invalid backoff factor should be rejected");
543
544        assert!(
545            matches!(err, NetworkConfigError::Invalid { field, .. } if field == "reconnect_backoff_factor")
546        );
547    }
548
549    #[rstest]
550    fn test_validate_rejects_delay_initial_exceeding_max() {
551        let mut config = valid_config();
552        config.reconnect_delay_initial_ms = Some(5_000);
553        config.reconnect_delay_max_ms = Some(1_000);
554
555        let err = config
556            .validate()
557            .expect_err("initial delay above max should be rejected");
558
559        assert!(
560            matches!(err, NetworkConfigError::Invalid { field, .. } if field == "reconnect_delay_initial_ms")
561        );
562    }
563
564    #[rstest]
565    fn test_validate_collects_multiple_errors() {
566        let mut config = valid_config();
567        config.url = String::new();
568        config.connect_timeout_ms = Some(0);
569
570        let err = config.validate().expect_err("multiple invalid fields");
571
572        match err {
573            NetworkConfigError::Multiple { errors } => assert_eq!(errors.len(), 2),
574            other @ NetworkConfigError::Invalid { .. } => {
575                panic!("expected Multiple, was {other:?}")
576            }
577        }
578    }
579
580    #[rstest]
581    #[case::derived(Some(30), None, Some(90))]
582    #[case::explicit_wins(Some(30), Some(45), Some(45))]
583    fn test_resolve_timeout_from_websocket_heartbeat(
584        #[case] interval_secs: Option<u64>,
585        #[case] timeout_secs: Option<u64>,
586        #[case] expected: Option<u64>,
587    ) {
588        let mut config = valid_config();
589        config.heartbeat_interval_secs = interval_secs;
590        config.heartbeat_timeout_secs = timeout_secs;
591
592        assert_eq!(config.resolved_heartbeat_timeout(), expected);
593    }
594
595    #[rstest]
596    fn test_debug_redacts_endpoint_and_proxy_credentials() {
597        const ENDPOINT_PATH_SECRET: &str = "unique-endpoint-path-secret";
598        const ENDPOINT_QUERY_SECRET: &str = "unique-endpoint-query-secret";
599        const PROXY_SECRET: &str = "unique-proxy-secret";
600        let mut config = valid_config();
601        config.url =
602            format!("wss://rpc.example.com/{ENDPOINT_PATH_SECRET}?api_key={ENDPOINT_QUERY_SECRET}");
603        config.proxy_url = Some(format!(
604            "http://proxytest:{PROXY_SECRET}@proxy.example.com:8080"
605        ));
606
607        let debug = format!("{config:?}");
608
609        assert!(debug.contains("url: \"<redacted>\""));
610        assert!(debug.contains("proxy_url: Some(\"<redacted>\")"));
611        assert!(!debug.contains(ENDPOINT_PATH_SECRET));
612        assert!(!debug.contains(ENDPOINT_QUERY_SECRET));
613        assert!(!debug.contains(PROXY_SECRET));
614    }
615}