Skip to main content

ws_reconnect_client/
config.rs

1use futures_util::stream::{SplitSink, SplitStream};
2use tokio::net::TcpStream;
3use tokio_tungstenite::{
4    tungstenite::Message,
5    MaybeTlsStream, WebSocketStream,
6};
7
8pub type WsWriter = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>;
9pub type WsReader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
10
11/// Configuration for websocket connection with retry logic
12#[derive(Clone, Debug)]
13pub struct WsConnectionConfig {
14    /// Base URL for the websocket connection
15    pub url: String,
16    /// Maximum retry attempts for initial connection and reconnections (default: 20)
17    pub max_retries: usize,
18    /// Initial backoff delay in milliseconds (default: 100ms)
19    pub initial_backoff_ms: u64,
20    /// Maximum backoff delay in milliseconds (default: 10s)
21    pub max_backoff_ms: u64,
22    /// Ping interval in seconds (default: 5s). Set to 0 to disable automatic pings.
23    pub ping_interval_secs: u64,
24    /// Auto-reconnect on connection loss (default: true)
25    pub auto_reconnect: bool,
26}
27
28impl WsConnectionConfig {
29    pub fn new(url: impl Into<String>) -> Self {
30        Self {
31            url: url.into(),
32            max_retries: 20,
33            initial_backoff_ms: 100,
34            max_backoff_ms: 10_000,
35            ping_interval_secs: 5,
36            auto_reconnect: true,
37        }
38    }
39
40    pub fn with_retries(mut self, max_retries: usize) -> Self {
41        self.max_retries = max_retries;
42        self
43    }
44
45    pub fn with_backoff(mut self, initial_ms: u64, max_ms: u64) -> Self {
46        self.initial_backoff_ms = initial_ms;
47        self.max_backoff_ms = max_ms;
48        self
49    }
50
51    pub fn with_ping_interval(mut self, ping_interval_secs: u64) -> Self {
52        self.ping_interval_secs = ping_interval_secs;
53        self
54    }
55
56    pub fn with_auto_reconnect(mut self, auto_reconnect: bool) -> Self {
57        self.auto_reconnect = auto_reconnect;
58        self
59    }
60}