1use crate::error::NetError;
2use crate::Result;
3use std::time::{Duration, Instant};
4use tokio::sync::Semaphore;
5
6const MAX_FIXED_CALLBACK_WORKERS: usize = 256;
9const MAX_HEARTBEAT_PONG_RECOVERY_ATTEMPTS: usize = 10;
10const MAX_HEARTBEAT_PING_WRITE_RETRIES: usize = 1024;
11
12#[derive(Clone, Debug)]
14pub struct WebSocketClientConfig {
15 pub default_send_retry_policy: super::WsSendRetryPolicy,
17 pub default_request_retry_policy: super::WsRequestRetryPolicy,
19 pub queues: QueueLimits,
21 pub dispatch: DispatchLimits,
23 pub requests: RequestLimits,
25 pub frames: FrameConfig,
27 pub tcp: TcpConfig,
29 pub heartbeat: Option<HeartbeatConfig>,
31 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 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#[derive(Clone, Debug)]
89pub struct QueueLimit {
90 pub max_items: usize,
92 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 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#[derive(Clone, Debug)]
126pub struct QueueLimits {
127 pub commands: usize,
129 pub io_events: usize,
131 pub normal: QueueLimit,
133 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 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#[derive(Clone, Debug)]
168pub struct DispatchLimits {
169 pub incoming: QueueLimit,
171 pub message_subscriptions: usize,
173 pub message_deliveries: usize,
175 pub message_callback_workers: usize,
177 pub state_subscriptions: usize,
179 pub state_callback_workers: usize,
181 pub event_subscriptions: usize,
183 pub event_callback_workers: usize,
185 pub task_subscriptions: usize,
187 pub task_callback_workers: usize,
189 pub task_events: QueueLimit,
193 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 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#[derive(Clone, Debug)]
268pub struct RequestLimits {
269 pub max_pending: usize,
272 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 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#[derive(Clone, Debug)]
301pub struct FrameConfig {
302 pub data_frame_payload_size: Option<usize>,
310 pub control_write_timeout: Duration,
315 pub data_frame_write_timeout: Duration,
320 pub read_buffer_size: usize,
322 pub write_buffer_size: usize,
324 pub max_write_buffer_size: usize,
326 pub max_message_size: Option<usize>,
328 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 pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
351 pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
353 pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
354
355 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#[derive(Clone, Debug)]
414pub struct TcpConfig {
415 pub nodelay: bool,
417 pub send_buffer_size: Option<usize>,
419 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 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#[derive(Clone, Debug)]
453pub struct TcpKeepaliveConfig {
454 pub idle: Duration,
456 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 pub fn validate(&self) -> Result<()> {
472 nonzero_duration(self.idle, "tcp.keepalive.idle")?;
473 nonzero_duration(self.interval, "tcp.keepalive.interval")?;
474 #[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#[derive(Clone, Debug)]
518pub struct HeartbeatConfig {
519 pub interval: Duration,
522 pub pong_timeout: Duration,
531 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 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#[derive(Clone, Debug)]
563pub struct HeartbeatRetryConfig {
564 pub pong_recovery_attempts: usize,
566 pub pong_retry_interval: Duration,
569 pub ping_write_retries: usize,
571 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 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;