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