Skip to main content

open_net/api/ws/
connect_options.rs

1use super::{
2    EventOptions, HandshakeDiagnosticOptions, HandshakeProvider, ReceiveOptions, ReceiveOverflow,
3    ReconnectPolicy, ResponseRouting,
4};
5use crate::{HeaderMap, Metadata, NetError, Result};
6use std::time::Duration;
7
8/// URL, handshake, reconnect, and receive settings for a WebSocket session.
9#[derive(Clone)]
10pub struct ConnectOptions {
11    /// Target WebSocket URL with a host and `ws` or `wss` scheme.
12    pub url: String,
13    /// Static HTTP headers added to each handshake; provider values may override duplicates.
14    pub headers: HeaderMap,
15    /// Provider for dynamic handshake headers and context; `None` uses static settings only.
16    pub handshake_provider: Option<HandshakeProvider>,
17    /// Application metadata for local observation and correlation; never sent automatically.
18    pub metadata: Metadata,
19    /// Retry policy after connection failure or termination; bounded exponential backoff by default.
20    pub reconnect: ReconnectPolicy,
21    /// Per-attempt handshake deadline, including context preparation and network setup (10 s default).
22    pub handshake_timeout: Duration,
23    /// Overall deadline from session start to the first successful connection (30 s default).
24    /// Retries and waits count toward it; `None` removes this additional limit.
25    pub connect_timeout: Option<Duration>,
26    /// Whether to create a buffered initial message inbox when the session starts.
27    pub initial_messages: InitialMessages,
28    /// Count and byte capacity of connection-event history for later replay.
29    pub event_history: EventOptions,
30    /// Strategy for recognizing and completing pending requests from business messages.
31    pub routing: ResponseRouting,
32    /// Handshake diagnostic collection and redaction; `None` disables optional diagnostics.
33    pub diagnostics: Option<HandshakeDiagnosticOptions>,
34}
35
36impl ConnectOptions {
37    /// Creates options for a URL with safe defaults.
38    pub fn new(url: impl Into<String>) -> Self {
39        Self {
40            url: url.into(),
41            headers: HeaderMap::new(),
42            handshake_provider: None,
43            metadata: Metadata::new(),
44            reconnect: ReconnectPolicy::default(),
45            handshake_timeout: Duration::from_secs(10),
46            connect_timeout: Some(Duration::from_secs(30)),
47            initial_messages: InitialMessages::default(),
48            event_history: EventOptions::default(),
49            routing: ResponseRouting::default(),
50            diagnostics: None,
51        }
52    }
53    /// Validates URL, limits, routing, and nested option values.
54    pub fn validate(&self) -> Result<()> {
55        let uri = self
56            .url
57            .parse::<http::Uri>()
58            .map_err(|_| NetError::config("url", "must be a valid WebSocket URL"))?;
59        if !matches!(uri.scheme_str(), Some("ws" | "wss")) || uri.host().is_none() {
60            return Err(NetError::config("url", "must use ws or wss with a host"));
61        }
62        super::validate_headers(&self.headers)?;
63        super::validate_metadata(&self.metadata)?;
64        self.reconnect.validate()?;
65        super::config::deadline(self.handshake_timeout, "handshake_timeout", false)?;
66        if let Some(timeout) = self.connect_timeout {
67            super::config::deadline(timeout, "connect_timeout", false)?;
68        }
69        self.event_history.validate()?;
70        if let InitialMessages::Buffer(options) = &self.initial_messages {
71            options.validate()?;
72            if matches!(self.routing, ResponseRouting::Manual)
73                && options.overflow == ReceiveOverflow::DropOldest
74            {
75                return Err(NetError::config(
76                    "initial_messages.overflow",
77                    "Manual routing requires a lossless initial inbox",
78                ));
79            }
80        }
81        if let Some(options) = &self.diagnostics {
82            options.validate()?;
83        }
84        Ok(())
85    }
86}
87impl From<String> for ConnectOptions {
88    fn from(url: String) -> Self {
89        Self::new(url)
90    }
91}
92impl From<&str> for ConnectOptions {
93    fn from(url: &str) -> Self {
94        Self::new(url)
95    }
96}
97impl std::fmt::Debug for ConnectOptions {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("ConnectOptions")
100            .field("url", &"[redacted]")
101            .field("header_count", &self.headers.len())
102            .field("has_handshake_provider", &self.handshake_provider.is_some())
103            .field("metadata_entries", &self.metadata.len())
104            .field("reconnect", &self.reconnect)
105            .field("handshake_timeout", &self.handshake_timeout)
106            .field("connect_timeout", &self.connect_timeout)
107            .field("initial_messages", &self.initial_messages)
108            .field("event_history", &self.event_history)
109            .field("routing", &self.routing)
110            .field("diagnostics", &self.diagnostics)
111            .finish()
112    }
113}
114/// Initial inbox policy between session startup and application takeover.
115#[derive(Clone, Debug)]
116pub enum InitialMessages {
117    /// Create a bounded inbox that the application can take or convert to a callback subscription.
118    Buffer(
119        /// Inbox limits, overflow policy, and control-frame settings.
120        ReceiveOptions,
121    ),
122    /// Do not create an inbox; unmatched messages without subscribers are discarded.
123    DiscardUnmatched,
124}
125impl Default for InitialMessages {
126    fn default() -> Self {
127        Self::Buffer(ReceiveOptions::default())
128    }
129}