1use crate::error::NetError;
2use crate::Result;
3use std::time::{Duration, Instant};
4use tokio::sync::Semaphore;
5
6const MAX_FIXED_CALLBACK_WORKERS: usize = 256;
9
10#[derive(Clone, Debug)]
12pub struct WebSocketClientConfig {
13 pub queues: QueueLimits,
15 pub dispatch: DispatchLimits,
17 pub requests: RequestLimits,
19 pub frames: FrameConfig,
21 pub tcp: TcpConfig,
23 pub heartbeat: Option<HeartbeatConfig>,
25 pub close_timeout: Duration,
28}
29
30impl Default for WebSocketClientConfig {
31 fn default() -> Self {
32 Self {
33 queues: QueueLimits::default(),
34 dispatch: DispatchLimits::default(),
35 requests: RequestLimits::default(),
36 frames: FrameConfig::default(),
37 tcp: TcpConfig::default(),
38 heartbeat: Some(HeartbeatConfig::default()),
39 close_timeout: Duration::from_secs(2),
40 }
41 }
42}
43
44impl WebSocketClientConfig {
45 pub fn validate(&self) -> Result<()> {
47 self.queues.validate()?;
48 self.dispatch.validate()?;
49 self.requests.validate()?;
50 self.frames.validate()?;
51 self.tcp.validate()?;
52 if let Some(heartbeat) = &self.heartbeat {
53 heartbeat.validate()?;
54 }
55 deadline(self.close_timeout, "close_timeout", false)?;
56 if self.frames.data_frame_payload_size.is_none() {
57 let payload = self
58 .queues
59 .normal
60 .max_bytes
61 .max(self.queues.urgent.max_bytes);
62 self.frames.validate_outgoing_payload(payload)?;
63 }
64 Ok(())
65 }
66}
67
68#[derive(Clone, Debug)]
70pub struct QueueLimit {
71 pub max_items: usize,
73 pub max_bytes: usize,
75}
76
77impl Default for QueueLimit {
78 fn default() -> Self {
79 Self {
80 max_items: 128,
81 max_bytes: 1024 * 1024,
82 }
83 }
84}
85
86impl QueueLimit {
87 pub fn validate(&self) -> Result<()> {
89 self.validate_fields("max_items", "max_bytes")
90 }
91
92 pub(super) fn validate_fields(&self, items_field: &str, bytes_field: &str) -> Result<()> {
93 permits(self.max_items, items_field)?;
94 permits(self.max_bytes, bytes_field)?;
95 if self.max_bytes > u32::MAX as usize {
96 return Err(NetError::config(
97 bytes_field,
98 "must fit a u32 byte allowance",
99 ));
100 }
101 Ok(())
102 }
103}
104
105#[derive(Clone, Debug)]
107pub struct QueueLimits {
108 pub commands: usize,
110 pub io_events: usize,
112 pub normal: QueueLimit,
114 pub urgent: QueueLimit,
116}
117
118impl Default for QueueLimits {
119 fn default() -> Self {
120 Self {
121 commands: 128,
122 io_events: 128,
123 normal: QueueLimit {
124 max_items: 1024,
125 max_bytes: 16 * 1024 * 1024,
126 },
127 urgent: QueueLimit {
128 max_items: 64,
129 max_bytes: 1024 * 1024,
130 },
131 }
132 }
133}
134
135impl QueueLimits {
136 pub fn validate(&self) -> Result<()> {
138 permits(self.commands, "queues.commands")?;
139 permits(self.io_events, "queues.io_events")?;
140 self.normal
141 .validate_fields("queues.normal.max_items", "queues.normal.max_bytes")?;
142 self.urgent
143 .validate_fields("queues.urgent.max_items", "queues.urgent.max_bytes")
144 }
145}
146
147#[derive(Clone, Debug)]
149pub struct DispatchLimits {
150 pub incoming: QueueLimit,
152 pub message_subscriptions: usize,
154 pub message_deliveries: usize,
156 pub message_callback_workers: usize,
158 pub state_subscriptions: usize,
160 pub state_callback_workers: usize,
162 pub event_subscriptions: usize,
164 pub event_callback_workers: usize,
166 pub task_subscriptions: usize,
168 pub task_callback_workers: usize,
170 pub task_events: QueueLimit,
174 pub blocking_handshake_jobs: usize,
176}
177
178impl Default for DispatchLimits {
179 fn default() -> Self {
180 Self {
181 incoming: QueueLimit {
182 max_items: 256,
183 max_bytes: 64 * 1024 * 1024,
184 },
185 message_subscriptions: 64,
186 message_deliveries: 1024,
187 message_callback_workers: 1,
188 state_subscriptions: 64,
189 state_callback_workers: 2,
190 event_subscriptions: 64,
191 event_callback_workers: 2,
192 task_subscriptions: 64,
193 task_callback_workers: 2,
194 task_events: QueueLimit {
195 max_items: 1024,
196 max_bytes: 16 * 1024 * 1024,
197 },
198 blocking_handshake_jobs: 8,
199 }
200 }
201}
202
203impl DispatchLimits {
204 pub fn validate(&self) -> Result<()> {
206 self.incoming
207 .validate_fields("dispatch.incoming.max_items", "dispatch.incoming.max_bytes")?;
208 for (value, field) in [
209 (self.message_subscriptions, "dispatch.message_subscriptions"),
210 (self.message_deliveries, "dispatch.message_deliveries"),
211 (
212 self.message_callback_workers,
213 "dispatch.message_callback_workers",
214 ),
215 (self.state_subscriptions, "dispatch.state_subscriptions"),
216 (self.event_subscriptions, "dispatch.event_subscriptions"),
217 (self.task_subscriptions, "dispatch.task_subscriptions"),
218 (
219 self.blocking_handshake_jobs,
220 "dispatch.blocking_handshake_jobs",
221 ),
222 ] {
223 permits(value, field)?;
224 }
225 for (value, field) in [
226 (
227 self.state_callback_workers,
228 "dispatch.state_callback_workers",
229 ),
230 (
231 self.event_callback_workers,
232 "dispatch.event_callback_workers",
233 ),
234 (self.task_callback_workers, "dispatch.task_callback_workers"),
235 ] {
236 if value == 0 || value > MAX_FIXED_CALLBACK_WORKERS {
237 return Err(NetError::config(field, "must be between 1 and 256"));
238 }
239 }
240 self.task_events.validate_fields(
241 "dispatch.task_events.max_items",
242 "dispatch.task_events.max_bytes",
243 )
244 }
245}
246
247#[derive(Clone, Debug)]
249pub struct RequestLimits {
250 pub max_pending: usize,
253 pub manual_response_grace: Duration,
257}
258
259impl Default for RequestLimits {
260 fn default() -> Self {
261 Self {
262 max_pending: 4096,
263 manual_response_grace: Duration::from_secs(2),
264 }
265 }
266}
267
268impl RequestLimits {
269 pub fn validate(&self) -> Result<()> {
271 permits(self.max_pending, "requests.max_pending")?;
272 deadline(
273 self.manual_response_grace,
274 "requests.manual_response_grace",
275 true,
276 )
277 }
278}
279
280#[derive(Clone, Debug)]
282pub struct FrameConfig {
283 pub data_frame_payload_size: Option<usize>,
287 pub control_write_timeout: Duration,
290 pub data_frame_write_timeout: Duration,
292 pub read_buffer_size: usize,
294 pub write_buffer_size: usize,
296 pub max_write_buffer_size: usize,
298 pub max_message_size: Option<usize>,
300 pub max_frame_size: Option<usize>,
303}
304
305impl Default for FrameConfig {
306 fn default() -> Self {
307 Self {
308 data_frame_payload_size: Some(Self::DEFAULT_DATA_FRAME_PAYLOAD_SIZE),
309 control_write_timeout: Duration::from_millis(1500),
310 data_frame_write_timeout: Duration::from_millis(1500),
311 read_buffer_size: 128 * 1024,
312 write_buffer_size: 128 * 1024,
313 max_write_buffer_size: 4 * 1024 * 1024,
314 max_message_size: Some(64 * 1024 * 1024),
315 max_frame_size: Some(16 * 1024 * 1024),
316 }
317 }
318}
319
320impl FrameConfig {
321 pub const MIN_DATA_FRAME_PAYLOAD_SIZE: usize = 1024;
323 pub const DEFAULT_DATA_FRAME_PAYLOAD_SIZE: usize = 32 * 1024;
325 pub(crate) const MAX_CLIENT_FRAME_OVERHEAD: usize = 14;
326
327 pub fn validate(&self) -> Result<()> {
329 deadline(
330 self.control_write_timeout,
331 "frames.control_write_timeout",
332 false,
333 )?;
334 deadline(
335 self.data_frame_write_timeout,
336 "frames.data_frame_write_timeout",
337 false,
338 )?;
339 allocation_size(self.read_buffer_size, "frames.read_buffer_size", false)?;
340 allocation_size(self.write_buffer_size, "frames.write_buffer_size", true)?;
341 allocation_size(
342 self.max_write_buffer_size,
343 "frames.max_write_buffer_size",
344 false,
345 )?;
346 if self.max_write_buffer_size <= self.write_buffer_size {
347 return Err(NetError::config(
348 "frames.max_write_buffer_size",
349 "must exceed frames.write_buffer_size",
350 ));
351 }
352 for (limit, field) in [
353 (self.max_message_size, "frames.max_message_size"),
354 (self.max_frame_size, "frames.max_frame_size"),
355 ] {
356 if let Some(size) = limit {
357 allocation_size(size, field, false)?;
358 }
359 }
360 if let Some(size) = self.data_frame_payload_size {
361 if size < Self::MIN_DATA_FRAME_PAYLOAD_SIZE
362 || size
363 .checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD)
364 .is_none_or(|size| size > isize::MAX as usize)
365 {
366 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"));
367 }
368 self.validate_outgoing_payload(size)?;
369 }
370 Ok(())
371 }
372
373 fn validate_outgoing_payload(&self, payload: usize) -> Result<()> {
374 match payload.checked_add(Self::MAX_CLIENT_FRAME_OVERHEAD) {
375 Some(required) if required <= self.max_write_buffer_size => Ok(()),
376 _ => Err(NetError::config(
377 "frames.max_write_buffer_size",
378 "must hold one outgoing frame payload and its 14-byte header",
379 )),
380 }
381 }
382}
383
384#[derive(Clone, Debug)]
386pub struct TcpConfig {
387 pub nodelay: bool,
389 pub send_buffer_size: Option<usize>,
391 pub keepalive: Option<TcpKeepaliveConfig>,
393}
394
395impl Default for TcpConfig {
396 fn default() -> Self {
397 Self {
398 nodelay: true,
399 send_buffer_size: None,
400 keepalive: None,
401 }
402 }
403}
404
405impl TcpConfig {
406 pub fn validate(&self) -> Result<()> {
408 if let Some(size) = self.send_buffer_size {
409 if size == 0 || size > i32::MAX as usize {
410 return Err(NetError::config(
411 "tcp.send_buffer_size",
412 "must be between 1 and i32::MAX for the native socket option",
413 ));
414 }
415 }
416 if let Some(keepalive) = &self.keepalive {
417 keepalive.validate()?;
418 }
419 Ok(())
420 }
421}
422
423#[derive(Clone, Debug)]
425pub struct TcpKeepaliveConfig {
426 pub idle: Duration,
428 pub interval: Duration,
430}
431
432impl Default for TcpKeepaliveConfig {
433 fn default() -> Self {
434 Self {
435 idle: Duration::from_secs(5),
436 interval: Duration::from_secs(2),
437 }
438 }
439}
440
441impl TcpKeepaliveConfig {
442 pub fn validate(&self) -> Result<()> {
444 nonzero_duration(self.idle, "tcp.keepalive.idle")?;
445 nonzero_duration(self.interval, "tcp.keepalive.interval")?;
446 #[cfg(windows)]
449 {
450 native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
451 native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
452 }
453 #[cfg(all(
454 unix,
455 not(any(
456 target_os = "haiku",
457 target_os = "openbsd",
458 target_os = "nto",
459 target_os = "vita"
460 ))
461 ))]
462 native_keepalive_duration(self.idle, "tcp.keepalive.idle")?;
463 #[cfg(any(
464 target_os = "aix",
465 target_os = "android",
466 target_os = "dragonfly",
467 target_os = "emscripten",
468 target_os = "freebsd",
469 target_os = "fuchsia",
470 target_os = "hurd",
471 target_os = "illumos",
472 target_os = "ios",
473 target_os = "visionos",
474 target_os = "linux",
475 target_os = "macos",
476 target_os = "netbsd",
477 target_os = "tvos",
478 target_os = "watchos",
479 target_os = "cygwin",
480 target_os = "nuttx",
481 all(target_os = "wasi", not(target_env = "p1"))
482 ))]
483 native_keepalive_duration(self.interval, "tcp.keepalive.interval")?;
484 Ok(())
485 }
486}
487
488#[derive(Clone, Debug)]
490pub struct HeartbeatConfig {
491 pub interval: Duration,
494 pub pong_timeout: Duration,
496}
497
498impl Default for HeartbeatConfig {
499 fn default() -> Self {
500 Self {
501 interval: Duration::from_secs(20),
502 pong_timeout: Duration::from_secs(45),
503 }
504 }
505}
506
507impl HeartbeatConfig {
508 pub fn validate(&self) -> Result<()> {
510 deadline(self.interval, "heartbeat.interval", false)?;
511 deadline(self.pong_timeout, "heartbeat.pong_timeout", false)
512 }
513}
514
515fn positive(value: usize, field: &str) -> Result<()> {
516 if value == 0 {
517 Err(NetError::config(field, "must be greater than zero"))
518 } else {
519 Ok(())
520 }
521}
522
523fn permits(value: usize, field: &str) -> Result<()> {
524 positive(value, field)?;
525 if value > Semaphore::MAX_PERMITS {
526 Err(NetError::config(
527 field,
528 "must not exceed Tokio Semaphore::MAX_PERMITS",
529 ))
530 } else {
531 Ok(())
532 }
533}
534
535fn allocation_size(value: usize, field: &str, allow_zero: bool) -> Result<()> {
536 if !allow_zero {
537 positive(value, field)?;
538 }
539 if value > isize::MAX as usize {
540 Err(NetError::config(
541 field,
542 "must not exceed isize::MAX for a byte allocation",
543 ))
544 } else {
545 Ok(())
546 }
547}
548
549fn nonzero_duration(value: Duration, field: &str) -> Result<()> {
550 if value.is_zero() {
551 Err(NetError::config(field, "must be greater than zero"))
552 } else {
553 Ok(())
554 }
555}
556
557pub(super) fn deadline(value: Duration, field: &str, allow_zero: bool) -> Result<()> {
558 if !allow_zero {
559 nonzero_duration(value, field)?;
560 }
561 if Instant::now().checked_add(value).is_none() {
562 Err(NetError::config(
563 field,
564 "must fit a monotonic Instant deadline",
565 ))
566 } else {
567 Ok(())
568 }
569}
570
571#[cfg(windows)]
572fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
573 if value.as_millis() == 0 || value.as_millis() >= u32::MAX as u128 {
574 Err(NetError::config(
575 field,
576 "must be at least one millisecond and below u32::MAX milliseconds",
577 ))
578 } else {
579 Ok(())
580 }
581}
582
583#[cfg(not(windows))]
584fn native_keepalive_duration(value: Duration, field: &str) -> Result<()> {
585 if value.as_secs() == 0 || value.as_secs() > i32::MAX as u64 {
586 Err(NetError::config(
587 field,
588 "must be at least one second and fit i32 seconds",
589 ))
590 } else {
591 Ok(())
592 }
593}
594
595#[cfg(test)]
596#[path = "config_tests.rs"]
597mod tests;