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    /// Control frames can be scheduled between fragments, but cannot pre-empt an
306    /// in-progress frame or overtake bytes already buffered by the transport.
307    /// This setting does not split one logical message into multiple messages,
308    /// and does not control the peer's outgoing frame sizes.
309    pub data_frame_payload_size: Option<usize>,
310    /// Maximum time for a single Ping, Pong, or Close write and for closing the
311    /// underlying sender; the default is 1,500 milliseconds.
312    /// This bounds the local write operation, including any preceding buffered
313    /// data it must drain; it is not an end-to-end peer response deadline.
314    pub control_write_timeout: Duration,
315    /// The time limit for writing a single data frame, the default is 1500 milliseconds; it is still subject to the overall message writing deadline.
316    /// Deferred data batches retain the earliest pending frame's deadline.
317    /// Expiry after a write has started retires the connection because delivery
318    /// may be partial; it does not imply a missing heartbeat Pong.
319    pub data_frame_write_timeout: Duration,
320    /// The underlying WebSocket read buffer size in bytes, default 128 KiB.
321    pub read_buffer_size: usize,
322    /// Target size of the underlying WebSocket write buffer, in bytes, defaults to 128 KiB; zero is allowed.
323    pub write_buffer_size: usize,
324    /// Maximum number of bytes for the underlying WebSocket write buffer, defaults to 4 MiB; must be larger than the target write buffer size.
325    pub max_write_buffer_size: usize,
326    /// The maximum number of bytes to receive a complete message, default 64 MiB; `None` means not to set this size limit.
327    pub max_message_size: Option<usize>,
328    /// Maximum bytes in one received frame; the default is 16 MiB and `None`
329    /// disables this limit.
330    pub max_frame_size: Option<usize>,
331}
332
333impl Default for FrameConfig {
334    fn default() -> Self {
335        Self {
336            data_frame_payload_size: Some(Self::DEFAULT_DATA_FRAME_PAYLOAD_SIZE),
337            control_write_timeout: Duration::from_millis(1500),
338            data_frame_write_timeout: Duration::from_millis(1500),
339            read_buffer_size: 128 * 1024,
340            write_buffer_size: 128 * 1024,
341            max_write_buffer_size: 4 * 1024 * 1024,
342            max_message_size: Some(64 * 1024 * 1024),
343            max_frame_size: Some(16 * 1024 * 1024),
344        }
345    }
346}
347
348impl FrameConfig {
349    /// Smallest supported outgoing data-frame payload fragment.
350    pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
351    /// Default outgoing data-frame payload fragment size.
352    pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
353    pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
354
355    /// Validates frame sizes, buffer capacities, and write deadlines.
356    pub fn validate(&self) -> Result<()> {
357        deadline(
358            self.control_write_timeout,
359            "frames.control_write_timeout",
360            false,
361        )?;
362        deadline(
363            self.data_frame_write_timeout,
364            "frames.data_frame_write_timeout",
365            false,
366        )?;
367        allocation_size(self.read_buffer_size, "frames.read_buffer_size", false)?;
368        allocation_size(self.write_buffer_size, "frames.write_buffer_size", true)?;
369        allocation_size(
370            self.max_write_buffer_size,
371            "frames.max_write_buffer_size",
372            false,
373        )?;
374        if self.max_write_buffer_size <= self.write_buffer_size {
375            return Err(NetError::config(
376                "frames.max_write_buffer_size",
377                "must exceed frames.write_buffer_size",
378            ));
379        }
380        for (limit, field) in [
381            (self.max_message_size, "frames.max_message_size"),
382            (self.max_frame_size, "frames.max_frame_size"),
383        ] {
384            if let Some(size) = limit {
385                allocation_size(size, field, false)?;
386            }
387        }
388        if let Some(size) = self.data_frame_payload_size {
389            if size < Self::MIN_DATA_FRAME_PAYLOAD_SIZE
390                || size
391                    .checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD)
392                    .is_none_or(|size| size > isize::MAX as usize)
393            {
394                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"));
395            }
396            self.validate_outgoing_payload(size)?;
397        }
398        Ok(())
399    }
400
401    fn validate_outgoing_payload(&self, payload: usize) -> Result<()> {
402        match payload.checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD) {
403            Some(required) if required <= self.max_write_buffer_size => Ok(()),
404            _ => Err(NetError::config(
405                "frames.max_write_buffer_size",
406                "must hold one outgoing frame payload and its 14-byte header",
407            )),
408        }
409    }
410}
411
412/// Socket configuration for the underlying WebSocket TCP connection.
413#[derive(Clone, Debug)]
414pub struct TcpConfig {
415    /// Whether to enable `TCP_NODELAY` to disable Nagle algorithm, default `true`.
416    pub nodelay: bool,
417    /// Request to set the TCP send buffer size in bytes; `None` means to keep the system default value.
418    pub send_buffer_size: Option<usize>,
419    /// TCP keepalive detection parameters; `None` means no additional configuration of TCP keepalive.
420    pub keepalive: Option<TcpKeepaliveConfig>,
421}
422
423impl Default for TcpConfig {
424    fn default() -> Self {
425        Self {
426            nodelay: true,
427            send_buffer_size: None,
428            keepalive: None,
429        }
430    }
431}
432
433impl TcpConfig {
434    /// Validates native socket buffer and keepalive settings.
435    pub fn validate(&self) -> Result<()> {
436        if let Some(size) = self.send_buffer_size {
437            if size == 0 || size > i32::MAX as usize {
438                return Err(NetError::config(
439                    "tcp.send_buffer_size",
440                    "must be between 1 and i32::MAX for the native socket option",
441                ));
442            }
443        }
444        if let Some(keepalive) = &self.keepalive {
445            keepalive.validate()?;
446        }
447        Ok(())
448    }
449}
450
451/// Idle wait time and probe interval for TCP keepalive probes; specific support depends on the running platform.
452#[derive(Clone, Debug)]
453pub struct TcpKeepaliveConfig {
454    /// How long after the connection is idle before sending keepalive probes, the default is 5 seconds.
455    pub idle: Duration,
456    /// The time interval between consecutive keepalive probes, default 2 seconds.
457    pub interval: Duration,
458}
459
460impl Default for TcpKeepaliveConfig {
461    fn default() -> Self {
462        Self {
463            idle: Duration::from_secs(5),
464            interval: Duration::from_secs(2),
465        }
466    }
467}
468
469impl TcpKeepaliveConfig {
470    /// Validates non-zero keepalive durations and platform-native ranges.
471    pub fn validate(&self) -> Result<()> {
472        nonzero_duration(self.idle, "tcp.keepalive.idle")?;
473        nonzero_duration(self.interval, "tcp.keepalive.interval")?;
474        // Match socket2's actual option conversion on each target. Unsupported
475        // options must not acquire artificial native range restrictions.
476        #[cfg(windows)]
477        {
478            native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
479            native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
480        }
481        #[cfg(all(
482            unix,
483            not(any(
484                target_os = "haiku",
485                target_os = "openbsd",
486                target_os = "nto",
487                target_os = "vita"
488            ))
489        ))]
490        native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
491        #[cfg(any(
492            target_os = "aix",
493            target_os = "android",
494            target_os = "dragonfly",
495            target_os = "emscripten",
496            target_os = "freebsd",
497            target_os = "fuchsia",
498            target_os = "hurd",
499            target_os = "illumos",
500            target_os = "ios",
501            target_os = "visionos",
502            target_os = "linux",
503            target_os = "macos",
504            target_os = "netbsd",
505            target_os = "tvos",
506            target_os = "watchos",
507            target_os = "cygwin",
508            target_os = "nuttx",
509            all(target_os = "wasi", not(target_env = "p1"))
510        ))]
511        native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
512        Ok(())
513    }
514}
515
516/// Active Ping/Pong heartbeat parameters on each physical connection.
517#[derive(Clone, Debug)]
518pub struct HeartbeatConfig {
519    /// Interval for checking whether to send a heartbeat Ping; the default is
520    /// 20 seconds. No new probe is created while another Ping is pending.
521    pub interval: Duration,
522    /// The time limit for waiting for a matching Pong after the local Ping write
523    /// succeeds. The default is 45 seconds.
524    ///
525    /// Local write completion does not mean the peer has received the Ping:
526    /// TCP/TLS buffering, network delay, peer processing, and local receive
527    /// scheduling can consume this budget. A responsive peer can still exceed
528    /// a short deadline under load. The deadline is not extended by unrelated
529    /// traffic or by a late matching Pong.
530    pub pong_timeout: Duration,
531    /// Bounded recovery and safe Ping-write retry policy. The default keeps the
532    /// existing fail-fast behavior by disabling both retry paths.
533    pub retry: HeartbeatRetryConfig,
534}
535
536impl Default for HeartbeatConfig {
537    fn default() -> Self {
538        Self {
539            interval: Duration::from_secs(20),
540            pong_timeout: Duration::from_secs(45),
541            retry: HeartbeatRetryConfig::default(),
542        }
543    }
544}
545
546impl HeartbeatConfig {
547    /// Validates heartbeat intervals and Pong deadlines.
548    pub fn validate(&self) -> Result<()> {
549        deadline(self.interval, "heartbeat.interval", false)?;
550        deadline(self.pong_timeout, "heartbeat.pong_timeout", false)?;
551        self.retry.validate()
552    }
553}
554
555/// Bounded recovery policy for WebSocket control-layer heartbeats.
556///
557/// `pong_recovery_attempts` counts the additional Ping probes after the
558/// normal probe's Pong deadline expires and is limited to ten. `ping_write_retries`
559/// counts only additional safe write attempts after the initial normal-heartbeat write.
560/// A write timeout or an error with unknown delivery is never retried on the
561/// same sink; the physical connection is retired instead.
562#[derive(Clone, Debug)]
563pub struct HeartbeatRetryConfig {
564    /// Number of additional fast Ping probes after a Pong timeout.
565    pub pong_recovery_attempts: usize,
566    /// Maximum wait for a matching Pong for each recovery probe and the delay
567    /// before the next probe.
568    pub pong_retry_interval: Duration,
569    /// Number of additional normal-heartbeat Ping write attempts.
570    pub ping_write_retries: usize,
571    /// Delay between safe normal-heartbeat Ping write attempts.
572    pub ping_write_retry_interval: Duration,
573}
574
575impl Default for HeartbeatRetryConfig {
576    fn default() -> Self {
577        Self {
578            pong_recovery_attempts: 0,
579            pong_retry_interval: Duration::from_millis(1500),
580            ping_write_retries: 0,
581            ping_write_retry_interval: Duration::from_millis(1500),
582        }
583    }
584}
585
586impl HeartbeatRetryConfig {
587    /// Validates retry counts and enabled retry delays without permitting a
588    /// busy loop or an unrepresentable monotonic deadline.
589    pub fn validate(&self) -> Result<()> {
590        self.validate_attempts(
591            self.pong_recovery_attempts,
592            self.pong_retry_interval,
593            "heartbeat.retry.pong_recovery_attempts",
594            "heartbeat.retry.pong_retry_interval",
595            MAX_HEARTBEAT_PONG_RECOVERY_ATTEMPTS,
596        )?;
597        self.validate_attempts(
598            self.ping_write_retries,
599            self.ping_write_retry_interval,
600            "heartbeat.retry.ping_write_retries",
601            "heartbeat.retry.ping_write_retry_interval",
602            MAX_HEARTBEAT_PING_WRITE_RETRIES,
603        )
604    }
605
606    fn validate_attempts(
607        &self,
608        attempts: usize,
609        interval: Duration,
610        attempts_field: &str,
611        interval_field: &str,
612        maximum: usize,
613    ) -> Result<()> {
614        if attempts == 0 {
615            return Ok(());
616        }
617        if attempts > maximum {
618            return Err(NetError::config(
619                attempts_field,
620                format!("must not exceed {maximum}"),
621            ));
622        }
623        deadline(interval, interval_field, false)
624    }
625}
626
627fn positive(value: usize, field: &str) -> Result<()> {
628    if value == 0 {
629        Err(NetError::config(field, "must be greater than zero"))
630    } else {
631        Ok(())
632    }
633}
634
635fn permits(value: usize, field: &str) -> Result<()> {
636    positive(value, field)?;
637    if value > Semaphore::MAX_PERMITS {
638        Err(NetError::config(
639            field,
640            "must not exceed Tokio Semaphore::MAX_PERMITS",
641        ))
642    } else {
643        Ok(())
644    }
645}
646
647fn allocation_size(value: usize, field: &str, allow_zero: bool) -> Result<()> {
648    if !allow_zero {
649        positive(value, field)?;
650    }
651    if value > isize::MAX as usize {
652        Err(NetError::config(
653            field,
654            "must not exceed isize::MAX for a byte allocation",
655        ))
656    } else {
657        Ok(())
658    }
659}
660
661fn nonzero_duration(value: Duration, field: &str) -> Result<()> {
662    if value.is_zero() {
663        Err(NetError::config(field, "must be greater than zero"))
664    } else {
665        Ok(())
666    }
667}
668
669pub(super) fn deadline(value: Duration, field: &str, allow_zero: bool) -> Result<()> {
670    if !allow_zero {
671        nonzero_duration(value, field)?;
672    }
673    if Instant::now().checked_add(value).is_none() {
674        Err(NetError::config(
675            field,
676            "must fit a monotonic Instant deadline",
677        ))
678    } else {
679        Ok(())
680    }
681}
682
683#[cfg(windows)]
684fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
685    if value.as_millis() == 0 || value.as_millis() >= u32::MAX as u128 {
686        Err(NetError::config(
687            field,
688            "must be at least one millisecond and below u32::MAX milliseconds",
689        ))
690    } else {
691        Ok(())
692    }
693}
694
695#[cfg(not(windows))]
696fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
697    if value.as_secs() == 0 || value.as_secs() > i32::MAX as u64 {
698        Err(NetError::config(
699            field,
700            "must be at least one second and fit i32 seconds",
701        ))
702    } else {
703        Ok(())
704    }
705}
706
707#[cfg(test)]
708#[path = "config_tests.rs"]
709mod tests;