Skip to main content

open_net/api/ws/
config.rs

1use crate::error::NetError;
2use crate::Result;
3use std::time::{Duration, Instant};
4use tokio::sync::Semaphore;
5
6// These executors create a fixed set of workers. The data executor instead
7// grows lazily and is bounded by its existing semaphore budget.
8const MAX_FIXED_CALLBACK_WORKERS: usize = 256;
9
10/// Shared resource limits, transport parameters, and heartbeat configuration for WebSocket clients.
11#[derive(Clone, Debug)]
12pub struct WebSocketClientConfig {
13    /// Capacity of command, I/O event, and normal and emergency send queues.
14    pub queues: QueueLimits,
15    /// Resource caps for receiving messages, subscribing to distribution, callback execution, and blocking handshake tasks.
16    pub dispatch: DispatchLimits,
17    /// Number of pending requests and manual response handling grace configuration.
18    pub requests: RequestLimits,
19    /// WebSocket frame fragmentation, read and write buffers and sizes, timeout limits.
20    pub frames: FrameConfig,
21    /// Low-level TCP socket options.
22    pub tcp: TcpConfig,
23    /// Active Ping/Pong heartbeat configuration; `None` means disabling active heartbeat.
24    pub heartbeat: Option<HeartbeatConfig>,
25    /// Maximum time to wait for the closing handshake and I/O task to finish
26    /// during shutdown; the default is 2 seconds.
27    pub close_timeout: Duration,
28}
29
30impl Default for WebSocketClientConfig {
31    fn default() -> Self {
32        Self {
33            queues: QueueLimits::default(),
34            dispatch: DispatchLimits::default(),
35            requests: RequestLimits::default(),
36            frames: FrameConfig::default(),
37            tcp: TcpConfig::default(),
38            heartbeat: Some(HeartbeatConfig::default()),
39            close_timeout: Duration::from_secs(2),
40        }
41    }
42}
43
44impl WebSocketClientConfig {
45    /// Validates all nested limits and transport settings before client creation.
46    pub fn validate(&self) -> Result<()> {
47        self.queues.validate()?;
48        self.dispatch.validate()?;
49        self.requests.validate()?;
50        self.frames.validate()?;
51        self.tcp.validate()?;
52        if let Some(heartbeat) = &self.heartbeat {
53            heartbeat.validate()?;
54        }
55        deadline(self.close_timeout, "close_timeout", false)?;
56        if self.frames.data_frame_payload_size.is_none() {
57            let payload = self
58                .queues
59                .normal
60                .max_bytes
61                .max(self.queues.urgent.max_bytes);
62            self.frames.validate_outgoing_payload(payload)?;
63        }
64        Ok(())
65    }
66}
67
68/// Double caps on the number of entries and bytes in a queue or resource pool.
69#[derive(Clone, Debug)]
70pub struct QueueLimit {
71    /// The maximum number of entries that can be occupied simultaneously must be greater than zero.
72    pub max_items: usize,
73    /// The upper limit of the total number of payload bytes that can be occupied simultaneously must be greater than zero.
74    pub max_bytes: usize,
75}
76
77impl Default for QueueLimit {
78    fn default() -> Self {
79        Self {
80            max_items: 128,
81            max_bytes: 1024 * 1024,
82        }
83    }
84}
85
86impl QueueLimit {
87    /// Validates that both entry and byte limits are representable and non-zero.
88    pub fn validate(&self) -> Result<()> {
89        self.validate_fields("max_items", "max_bytes")
90    }
91
92    pub(super) fn validate_fields(&self, items_field: &str, bytes_field: &str) -> Result<()> {
93        permits(self.max_items, items_field)?;
94        permits(self.max_bytes, bytes_field)?;
95        if self.max_bytes > u32::MAX as usize {
96            return Err(NetError::config(
97                bytes_field,
98                "must fit a u32 byte allowance",
99            ));
100        }
101        Ok(())
102    }
103}
104
105/// Queue capacity for client internal commands, I/O events, and two send channels.
106#[derive(Clone, Debug)]
107pub struct QueueLimits {
108    /// The maximum number of commands that the client command queue can accommodate, default 128.
109    pub commands: usize,
110    /// The maximum number of events that the I/O event queue can accommodate, default 128.
111    pub io_events: usize,
112    /// The upper limit of entries and payload bytes for ordinary send channels, default is 1024 entries, 16 MiB.
113    pub normal: QueueLimit,
114    /// Independent capacity of emergency sending channels, default 64, 1 MiB.
115    pub urgent: QueueLimit,
116}
117
118impl Default for QueueLimits {
119    fn default() -> Self {
120        Self {
121            commands: 128,
122            io_events: 128,
123            normal: QueueLimit {
124                max_items: 1024,
125                max_bytes: 16 * 1024 * 1024,
126            },
127            urgent: QueueLimit {
128                max_items: 64,
129                max_bytes: 1024 * 1024,
130            },
131        }
132    }
133}
134
135impl QueueLimits {
136    /// Validates command, event, and send-queue capacities.
137    pub fn validate(&self) -> Result<()> {
138        permits(self.commands, "queues.commands")?;
139        permits(self.io_events, "queues.io_events")?;
140        self.normal
141            .validate_fields("queues.normal.max_items", "queues.normal.max_bytes")?;
142        self.urgent
143            .validate_fields("queues.urgent.max_items", "queues.urgent.max_bytes")
144    }
145}
146
147/// Upper limit on client-shared message distribution, subscription, and callback execution resources.
148#[derive(Clone, Debug)]
149pub struct DispatchLimits {
150    /// Entry and payload byte limits shared by all sessions receiving messages; unread messages from old sessions still occupy the quota.
151    pub incoming: QueueLimit,
152    /// The maximum number of message subscriptions that a client can hold at the same time.
153    pub message_subscriptions: usize,
154    /// The maximum number of deliveries that can be held simultaneously when a message is distributed to subscribers; multiple recipients of the same message are counted separately.
155    pub message_deliveries: usize,
156    /// The upper limit on the number of tasks that message callbacks can perform concurrently; worker threads are created on demand.
157    pub message_callback_workers: usize,
158    /// The maximum number of connection state subscriptions a client can hold simultaneously.
159    pub state_subscriptions: usize,
160    /// Number of worker threads to execute connection status callbacks, allowed range is 1 to 256.
161    pub state_callback_workers: usize,
162    /// The maximum number of connection event subscriptions that a client can hold simultaneously.
163    pub event_subscriptions: usize,
164    /// Number of worker threads to execute connection event callbacks, allowed range is 1 to 256.
165    pub event_callback_workers: usize,
166    /// The upper limit of the number of task final event subscriptions that the client can hold at the same time.
167    pub task_subscriptions: usize,
168    /// The number of worker threads that execute task final event callbacks. The allowed range is 1 to 256.
169    pub task_callback_workers: usize,
170    /// Shared limits for final-state notifications from all session tasks;
171    /// quotas are reserved when a task is admitted and count both deliveries
172    /// and payload bytes.
173    pub task_events: QueueLimit,
174    /// The maximum number of tasks that can be executed simultaneously on a blocking handshake context provider.
175    pub blocking_handshake_jobs: usize,
176}
177
178impl Default for DispatchLimits {
179    fn default() -> Self {
180        Self {
181            incoming: QueueLimit {
182                max_items: 256,
183                max_bytes: 64 * 1024 * 1024,
184            },
185            message_subscriptions: 64,
186            message_deliveries: 1024,
187            message_callback_workers: 1,
188            state_subscriptions: 64,
189            state_callback_workers: 2,
190            event_subscriptions: 64,
191            event_callback_workers: 2,
192            task_subscriptions: 64,
193            task_callback_workers: 2,
194            task_events: QueueLimit {
195                max_items: 1024,
196                max_bytes: 16 * 1024 * 1024,
197            },
198            blocking_handshake_jobs: 8,
199        }
200    }
201}
202
203impl DispatchLimits {
204    /// Validates distribution quotas and callback worker counts.
205    pub fn validate(&self) -> Result<()> {
206        self.incoming
207            .validate_fields("dispatch.incoming.max_items", "dispatch.incoming.max_bytes")?;
208        for (value, field) in [
209            (self.message_subscriptions, "dispatch.message_subscriptions"),
210            (self.message_deliveries, "dispatch.message_deliveries"),
211            (
212                self.message_callback_workers,
213                "dispatch.message_callback_workers",
214            ),
215            (self.state_subscriptions, "dispatch.state_subscriptions"),
216            (self.event_subscriptions, "dispatch.event_subscriptions"),
217            (self.task_subscriptions, "dispatch.task_subscriptions"),
218            (
219                self.blocking_handshake_jobs,
220                "dispatch.blocking_handshake_jobs",
221            ),
222        ] {
223            permits(value, field)?;
224        }
225        for (value, field) in [
226            (
227                self.state_callback_workers,
228                "dispatch.state_callback_workers",
229            ),
230            (
231                self.event_callback_workers,
232                "dispatch.event_callback_workers",
233            ),
234            (self.task_callback_workers, "dispatch.task_callback_workers"),
235        ] {
236            if value == 0 || value > MAX_FIXED_CALLBACK_WORKERS {
237                return Err(NetError::config(field, "must be between 1 and 256"));
238            }
239        }
240        self.task_events.validate_fields(
241            "dispatch.task_events.max_items",
242            "dispatch.task_events.max_bytes",
243        )
244    }
245}
246
247/// Request registration capacity and manual processing grace configuration of received responses.
248#[derive(Clone, Debug)]
249pub struct RequestLimits {
250    /// Maximum number of requests that may be registered and unfinished at one
251    /// time; the default is 4,096.
252    pub max_pending: usize,
253    /// Processing grace reserved for responses received in time but not yet manually parsed, default 2 seconds; zero means no wait.
254    ///
255    /// Grace does not extend the absolute deadline of the request and is also used to wait for the response callback to drain when the connection is terminated.
256    pub manual_response_grace: Duration,
257}
258
259impl Default for RequestLimits {
260    fn default() -> Self {
261        Self {
262            max_pending: 4096,
263            manual_response_grace: Duration::from_secs(2),
264        }
265    }
266}
267
268impl RequestLimits {
269    /// Validates pending-request capacity and manual response grace.
270    pub fn validate(&self) -> Result<()> {
271        permits(self.max_pending, "requests.max_pending")?;
272        deadline(
273            self.manual_response_grace,
274            "requests.manual_response_grace",
275            true,
276        )
277    }
278}
279
280/// WebSocket data frame fragmentation, read and write buffers, and receive size limits.
281#[derive(Clone, Debug)]
282pub struct FrameConfig {
283    /// Payload size, in bytes, for outgoing data-frame fragments; the default is
284    /// 32 KiB and `None` disables active fragmentation.
285    /// Set to at least 1024 bytes, and the write buffer limit must also accommodate the payload and frame header.
286    pub data_frame_payload_size: Option<usize>,
287    /// Maximum time for a single Ping, Pong, or Close write and for closing the
288    /// underlying sender; the default is 1,500 milliseconds.
289    pub control_write_timeout: Duration,
290    /// The time limit for writing a single data frame, the default is 1500 milliseconds; it is still subject to the overall message writing deadline.
291    pub data_frame_write_timeout: Duration,
292    /// The underlying WebSocket read buffer size in bytes, default 128 KiB.
293    pub read_buffer_size: usize,
294    /// Target size of the underlying WebSocket write buffer, in bytes, defaults to 128 KiB; zero is allowed.
295    pub write_buffer_size: usize,
296    /// Maximum number of bytes for the underlying WebSocket write buffer, defaults to 4 MiB; must be larger than the target write buffer size.
297    pub max_write_buffer_size: usize,
298    /// The maximum number of bytes to receive a complete message, default 64 MiB; `None` means not to set this size limit.
299    pub max_message_size: Option<usize>,
300    /// Maximum bytes in one received frame; the default is 16 MiB and `None`
301    /// disables this limit.
302    pub max_frame_size: Option<usize>,
303}
304
305impl Default for FrameConfig {
306    fn default() -> Self {
307        Self {
308            data_frame_payload_size: Some(Self::DEFAULT_DATA_FRAME_PAYLOAD_SIZE),
309            control_write_timeout: Duration::from_millis(1500),
310            data_frame_write_timeout: Duration::from_millis(1500),
311            read_buffer_size: 128 * 1024,
312            write_buffer_size: 128 * 1024,
313            max_write_buffer_size: 4 * 1024 * 1024,
314            max_message_size: Some(64 * 1024 * 1024),
315            max_frame_size: Some(16 * 1024 * 1024),
316        }
317    }
318}
319
320impl FrameConfig {
321    /// Smallest supported outgoing data-frame payload fragment.
322    pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
323    /// Default outgoing data-frame payload fragment size.
324    pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
325    pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
326
327    /// Validates frame sizes, buffer capacities, and write deadlines.
328    pub fn validate(&self) -> Result<()> {
329        deadline(
330            self.control_write_timeout,
331            "frames.control_write_timeout",
332            false,
333        )?;
334        deadline(
335            self.data_frame_write_timeout,
336            "frames.data_frame_write_timeout",
337            false,
338        )?;
339        allocation_size(self.read_buffer_size, "frames.read_buffer_size", false)?;
340        allocation_size(self.write_buffer_size, "frames.write_buffer_size", true)?;
341        allocation_size(
342            self.max_write_buffer_size,
343            "frames.max_write_buffer_size",
344            false,
345        )?;
346        if self.max_write_buffer_size <= self.write_buffer_size {
347            return Err(NetError::config(
348                "frames.max_write_buffer_size",
349                "must exceed frames.write_buffer_size",
350            ));
351        }
352        for (limit, field) in [
353            (self.max_message_size, "frames.max_message_size"),
354            (self.max_frame_size, "frames.max_frame_size"),
355        ] {
356            if let Some(size) = limit {
357                allocation_size(size, field, false)?;
358            }
359        }
360        if let Some(size) = self.data_frame_payload_size {
361            if size < Self::MIN_DATA_FRAME_PAYLOAD_SIZE
362                || size
363                    .checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD)
364                    .is_none_or(|size| size > isize::MAX as usize)
365            {
366                return Err(NetError::config("frames.data_frame_payload_size", "must be at least 1024 bytes and leave room for the frame header within isize::MAX"));
367            }
368            self.validate_outgoing_payload(size)?;
369        }
370        Ok(())
371    }
372
373    fn validate_outgoing_payload(&self, payload: usize) -> Result<()> {
374        match payload.checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD) {
375            Some(required) if required <= self.max_write_buffer_size => Ok(()),
376            _ => Err(NetError::config(
377                "frames.max_write_buffer_size",
378                "must hold one outgoing frame payload and its 14-byte header",
379            )),
380        }
381    }
382}
383
384/// Socket configuration for the underlying WebSocket TCP connection.
385#[derive(Clone, Debug)]
386pub struct TcpConfig {
387    /// Whether to enable `TCP_NODELAY` to disable Nagle algorithm, default `true`.
388    pub nodelay: bool,
389    /// Request to set the TCP send buffer size in bytes; `None` means to keep the system default value.
390    pub send_buffer_size: Option<usize>,
391    /// TCP keepalive detection parameters; `None` means no additional configuration of TCP keepalive.
392    pub keepalive: Option<TcpKeepaliveConfig>,
393}
394
395impl Default for TcpConfig {
396    fn default() -> Self {
397        Self {
398            nodelay: true,
399            send_buffer_size: None,
400            keepalive: None,
401        }
402    }
403}
404
405impl TcpConfig {
406    /// Validates native socket buffer and keepalive settings.
407    pub fn validate(&self) -> Result<()> {
408        if let Some(size) = self.send_buffer_size {
409            if size == 0 || size > i32::MAX as usize {
410                return Err(NetError::config(
411                    "tcp.send_buffer_size",
412                    "must be between 1 and i32::MAX for the native socket option",
413                ));
414            }
415        }
416        if let Some(keepalive) = &self.keepalive {
417            keepalive.validate()?;
418        }
419        Ok(())
420    }
421}
422
423/// Idle wait time and probe interval for TCP keepalive probes; specific support depends on the running platform.
424#[derive(Clone, Debug)]
425pub struct TcpKeepaliveConfig {
426    /// How long after the connection is idle before sending keepalive probes, the default is 5 seconds.
427    pub idle: Duration,
428    /// The time interval between consecutive keepalive probes, default 2 seconds.
429    pub interval: Duration,
430}
431
432impl Default for TcpKeepaliveConfig {
433    fn default() -> Self {
434        Self {
435            idle: Duration::from_secs(5),
436            interval: Duration::from_secs(2),
437        }
438    }
439}
440
441impl TcpKeepaliveConfig {
442    /// Validates non-zero keepalive durations and platform-native ranges.
443    pub fn validate(&self) -> Result<()> {
444        nonzero_duration(self.idle, "tcp.keepalive.idle")?;
445        nonzero_duration(self.interval, "tcp.keepalive.interval")?;
446        // Match socket2's actual option conversion on each target. Unsupported
447        // options must not acquire artificial native range restrictions.
448        #[cfg(windows)]
449        {
450            native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
451            native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
452        }
453        #[cfg(all(
454            unix,
455            not(any(
456                target_os = "haiku",
457                target_os = "openbsd",
458                target_os = "nto",
459                target_os = "vita"
460            ))
461        ))]
462        native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
463        #[cfg(any(
464            target_os = "aix",
465            target_os = "android",
466            target_os = "dragonfly",
467            target_os = "emscripten",
468            target_os = "freebsd",
469            target_os = "fuchsia",
470            target_os = "hurd",
471            target_os = "illumos",
472            target_os = "ios",
473            target_os = "visionos",
474            target_os = "linux",
475            target_os = "macos",
476            target_os = "netbsd",
477            target_os = "tvos",
478            target_os = "watchos",
479            target_os = "cygwin",
480            target_os = "nuttx",
481            all(target_os = "wasi", not(target_env = "p1"))
482        ))]
483        native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
484        Ok(())
485    }
486}
487
488/// Active Ping/Pong heartbeat parameters on each physical connection.
489#[derive(Clone, Debug)]
490pub struct HeartbeatConfig {
491    /// Interval for checking whether to send a heartbeat Ping; the default is
492    /// 20 seconds. No new probe is created while another Ping is pending.
493    pub interval: Duration,
494    /// The time limit for waiting for matching payload Pong after Ping is successfully written. The default is 45 seconds.
495    pub pong_timeout: Duration,
496}
497
498impl Default for HeartbeatConfig {
499    fn default() -> Self {
500        Self {
501            interval: Duration::from_secs(20),
502            pong_timeout: Duration::from_secs(45),
503        }
504    }
505}
506
507impl HeartbeatConfig {
508    /// Validates heartbeat intervals and Pong deadlines.
509    pub fn validate(&self) -> Result<()> {
510        deadline(self.interval, "heartbeat.interval", false)?;
511        deadline(self.pong_timeout, "heartbeat.pong_timeout", false)
512    }
513}
514
515fn positive(value: usize, field: &str) -> Result<()> {
516    if value == 0 {
517        Err(NetError::config(field, "must be greater than zero"))
518    } else {
519        Ok(())
520    }
521}
522
523fn permits(value: usize, field: &str) -> Result<()> {
524    positive(value, field)?;
525    if value > Semaphore::MAX_PERMITS {
526        Err(NetError::config(
527            field,
528            "must not exceed Tokio Semaphore::MAX_PERMITS",
529        ))
530    } else {
531        Ok(())
532    }
533}
534
535fn allocation_size(value: usize, field: &str, allow_zero: bool) -> Result<()> {
536    if !allow_zero {
537        positive(value, field)?;
538    }
539    if value > isize::MAX as usize {
540        Err(NetError::config(
541            field,
542            "must not exceed isize::MAX for a byte allocation",
543        ))
544    } else {
545        Ok(())
546    }
547}
548
549fn nonzero_duration(value: Duration, field: &str) -> Result<()> {
550    if value.is_zero() {
551        Err(NetError::config(field, "must be greater than zero"))
552    } else {
553        Ok(())
554    }
555}
556
557pub(super) fn deadline(value: Duration, field: &str, allow_zero: bool) -> Result<()> {
558    if !allow_zero {
559        nonzero_duration(value, field)?;
560    }
561    if Instant::now().checked_add(value).is_none() {
562        Err(NetError::config(
563            field,
564            "must fit a monotonic Instant deadline",
565        ))
566    } else {
567        Ok(())
568    }
569}
570
571#[cfg(windows)]
572fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
573    if value.as_millis() == 0 || value.as_millis() >= u32::MAX as u128 {
574        Err(NetError::config(
575            field,
576            "must be at least one millisecond and below u32::MAX milliseconds",
577        ))
578    } else {
579        Ok(())
580    }
581}
582
583#[cfg(not(windows))]
584fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
585    if value.as_secs() == 0 || value.as_secs() > i32::MAX as u64 {
586        Err(NetError::config(
587            field,
588            "must be at least one second and fit i32 seconds",
589        ))
590    } else {
591        Ok(())
592    }
593}
594
595#[cfg(test)]
596#[path = "config_tests.rs"]
597mod tests;