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