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>,
306 pub control_write_timeout: Duration,
309 pub data_frame_write_timeout: Duration,
311 pub read_buffer_size: usize,
313 pub write_buffer_size: usize,
315 pub max_write_buffer_size: usize,
317 pub max_message_size: Option<usize>,
319 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 pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
342 pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
344 pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
345
346 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#[derive(Clone, Debug)]
405pub struct TcpConfig {
406 pub nodelay: bool,
408 pub send_buffer_size: Option<usize>,
410 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 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#[derive(Clone, Debug)]
444pub struct TcpKeepaliveConfig {
445 pub idle: Duration,
447 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 pub fn validate(&self) -> Result<()> {
463 nonzero_duration(self.idle, "tcp.keepalive.idle")?;
464 nonzero_duration(self.interval, "tcp.keepalive.interval")?;
465 #[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#[derive(Clone, Debug)]
509pub struct HeartbeatConfig {
510 pub interval: Duration,
513 pub pong_timeout: Duration,
515 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 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#[derive(Clone, Debug)]
547pub struct HeartbeatRetryConfig {
548 pub pong_recovery_attempts: usize,
550 pub pong_retry_interval: Duration,
553 pub ping_write_retries: usize,
555 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 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;