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 queues: QueueLimits,
17 pub dispatch: DispatchLimits,
19 pub requests: RequestLimits,
21 pub frames: FrameConfig,
23 pub tcp: TcpConfig,
25 pub heartbeat: Option<HeartbeatConfig>,
27 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 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#[derive(Clone, Debug)]
72pub struct QueueLimit {
73 pub max_items: usize,
75 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 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#[derive(Clone, Debug)]
109pub struct QueueLimits {
110 pub commands: usize,
112 pub io_events: usize,
114 pub normal: QueueLimit,
116 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 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#[derive(Clone, Debug)]
151pub struct DispatchLimits {
152 pub incoming: QueueLimit,
154 pub message_subscriptions: usize,
156 pub message_deliveries: usize,
158 pub message_callback_workers: usize,
160 pub state_subscriptions: usize,
162 pub state_callback_workers: usize,
164 pub event_subscriptions: usize,
166 pub event_callback_workers: usize,
168 pub task_subscriptions: usize,
170 pub task_callback_workers: usize,
172 pub task_events: QueueLimit,
176 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 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#[derive(Clone, Debug)]
251pub struct RequestLimits {
252 pub max_pending: usize,
255 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 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#[derive(Clone, Debug)]
284pub struct FrameConfig {
285 pub data_frame_payload_size: Option<usize>,
289 pub control_write_timeout: Duration,
292 pub data_frame_write_timeout: Duration,
294 pub read_buffer_size: usize,
296 pub write_buffer_size: usize,
298 pub max_write_buffer_size: usize,
300 pub max_message_size: Option<usize>,
302 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 pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
325 pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
327 pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
328
329 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#[derive(Clone, Debug)]
388pub struct TcpConfig {
389 pub nodelay: bool,
391 pub send_buffer_size: Option<usize>,
393 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 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#[derive(Clone, Debug)]
427pub struct TcpKeepaliveConfig {
428 pub idle: Duration,
430 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 pub fn validate(&self) -> Result<()> {
446 nonzero_duration(self.idle, "tcp.keepalive.idle")?;
447 nonzero_duration(self.interval, "tcp.keepalive.interval")?;
448 #[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#[derive(Clone, Debug)]
492pub struct HeartbeatConfig {
493 pub interval: Duration,
496 pub pong_timeout: Duration,
498 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 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#[derive(Clone, Debug)]
530pub struct HeartbeatRetryConfig {
531 pub pong_recovery_attempts: usize,
533 pub pong_retry_interval: Duration,
536 pub ping_write_retries: usize,
538 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 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;