1use std::time::Duration;
4
5use crate::addr::PrefixPolicy;
6use crate::driver::DriverKind;
7use crate::error::{ConfigReason, NetError};
8use crate::info::Lane;
9
10const RESERVED_LANES: usize = 8;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct MinRate {
25 pub bytes_per_sec: u32,
27 pub window: Duration,
29 pub grace: Duration,
31 pub check: Duration,
33}
34
35impl MinRate {
36 #[must_use]
38 pub const fn off() -> MinRate {
39 MinRate {
40 bytes_per_sec: 0,
41 window: Duration::from_secs(10),
42 grace: Duration::from_secs(5),
43 check: Duration::from_secs(1),
44 }
45 }
46
47 #[must_use]
49 pub const fn new(bytes_per_sec: u32, window: Duration) -> MinRate {
50 MinRate {
51 bytes_per_sec,
52 window,
53 grace: Duration::from_secs(5),
54 check: Duration::from_secs(1),
55 }
56 }
57
58 #[must_use]
60 pub const fn is_off(&self) -> bool {
61 self.bytes_per_sec == 0
62 }
63}
64
65#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct Pressure {
76 pub high: f32,
78 pub low: f32,
80 pub factor: f32,
82}
83
84impl Default for Pressure {
85 fn default() -> Pressure {
86 Pressure {
87 high: 0.8,
88 low: 0.6,
89 factor: 0.25,
90 }
91 }
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
103pub struct SizeClass(u32);
104
105impl SizeClass {
106 pub const SMALL: SizeClass = SizeClass(4 * 1024);
108 pub const MEDIUM: SizeClass = SizeClass(16 * 1024);
110 pub const LARGE: SizeClass = SizeClass(64 * 1024);
112
113 pub const fn new(bytes: u32) -> Result<SizeClass, NetError> {
119 if !bytes.is_power_of_two() {
120 return Err(NetError::InvalidConfig {
121 field: "size_class",
122 reason: ConfigReason::Inconsistent,
123 });
124 }
125 if bytes < 1024 {
126 return Err(NetError::InvalidConfig {
127 field: "size_class",
128 reason: ConfigReason::TooSmall { min: 1024 },
129 });
130 }
131 if bytes > 1024 * 1024 {
132 return Err(NetError::InvalidConfig {
133 field: "size_class",
134 reason: ConfigReason::TooLarge { max: 1024 * 1024 },
135 });
136 }
137 Ok(SizeClass(bytes))
138 }
139
140 #[must_use]
142 pub const fn bytes(self) -> u32 {
143 self.0
144 }
145}
146
147#[non_exhaustive]
167#[derive(Clone, Debug, Default, PartialEq)]
168pub struct Limits {
169 max_connections: Option<u32>,
170 max_per_listener: Option<u32>,
171 max_per_source: Option<(u32, PrefixPolicy)>,
172 backlog: Option<u32>,
173 accept_batch: Option<u16>,
174 handshake_timeout: Option<Duration>,
175 idle_timeout: Option<Duration>,
176 read_timeout: Option<Duration>,
177 write_timeout: Option<Duration>,
178 park_timeout: Option<Duration>,
179 min_rate: Option<MinRate>,
180 proxy_header_max: Option<u16>,
181 read_class: Option<(SizeClass, SizeClass)>,
182 output_budget: Option<u32>,
183 completion_queue: Option<u32>,
184 buffer_budget: Option<u64>,
185 drain_timeout: Option<Duration>,
186 graceful_linger: Option<(Duration, u32)>,
187 refusal_bytes_max: Option<u16>,
188 tick: Option<Duration>,
189 pressure: Option<Pressure>,
190 lane_reserve: [Option<u32>; RESERVED_LANES],
191}
192
193#[derive(Clone, Copy, Debug, PartialEq)]
195pub(crate) struct Effective {
196 pub max_connections: u32,
197 pub max_per_listener: u32,
198 pub max_per_source: u32,
199 pub source_policy: PrefixPolicy,
200 pub backlog: u32,
201 pub accept_batch: u16,
202 pub handshake_timeout: Duration,
203 pub idle_timeout: Duration,
204 pub read_timeout: Duration,
205 pub write_timeout: Duration,
206 pub park_timeout: Duration,
207 pub min_rate: MinRate,
208 pub proxy_header_max: u16,
209 pub read_class: SizeClass,
210 pub read_class_max: SizeClass,
211 pub output_budget: u32,
212 pub completion_queue: u32,
213 pub buffer_budget: u64,
214 pub drain_timeout: Duration,
215 pub graceful_linger: Duration,
216 pub graceful_linger_bytes: u32,
217 pub refusal_bytes_max: u16,
218 pub tick: Duration,
219 pub pressure: Option<Pressure>,
220 pub lane_reserve: [u32; RESERVED_LANES],
222}
223
224impl Effective {
225 pub(crate) fn reserved_above(&self, lane: Lane) -> u32 {
227 self.lane_reserve
228 .iter()
229 .take(usize::from(lane.0))
230 .fold(0u32, |sum, r| sum.saturating_add(*r))
231 }
232
233 pub(crate) fn defaults(driver: DriverKind) -> Effective {
235 let blocking = driver.resolve() == DriverKind::Blocking;
236 let max_connections = if blocking { 128 } else { 10_000 };
237 Effective {
238 max_connections,
239 max_per_listener: max_connections,
240 max_per_source: if blocking { 16 } else { 256 },
241 source_policy: PrefixPolicy::DEFAULT,
242 backlog: 1024,
243 accept_batch: if blocking { 16 } else { 64 },
244 handshake_timeout: Duration::from_secs(10),
245 idle_timeout: Duration::from_secs(if blocking { 5 } else { 60 }),
246 read_timeout: Duration::from_secs(30),
247 write_timeout: Duration::from_secs(30),
248 park_timeout: Duration::from_secs(30),
249 min_rate: MinRate::new(256, Duration::from_secs(10)),
250 proxy_header_max: 1024,
251 read_class: SizeClass::MEDIUM,
252 read_class_max: SizeClass::LARGE,
253 output_budget: 64 * 1024,
254 completion_queue: if blocking { 1 } else { 1024 },
255 buffer_budget: if blocking { 64 << 20 } else { 512 << 20 },
256 drain_timeout: Duration::from_secs(30),
257 graceful_linger: Duration::from_secs(2),
258 graceful_linger_bytes: 64 * 1024,
259 refusal_bytes_max: 512,
260 tick: Duration::from_millis(if blocking { 10 } else { 1 }),
261 pressure: None,
262 lane_reserve: [0; RESERVED_LANES],
263 }
264 }
265}
266
267impl Limits {
268 pub fn builder() -> LimitsBuilder {
276 LimitsBuilder::default()
277 }
278
279 #[must_use]
285 pub fn reactor_defaults() -> Limits {
286 Limits::from_effective(&Effective::defaults(DriverKind::Reactor))
287 }
288
289 #[must_use]
295 pub fn blocking_defaults() -> Limits {
296 Limits::from_effective(&Effective::defaults(DriverKind::Blocking))
297 }
298
299 pub fn to_builder(&self) -> LimitsBuilder {
311 LimitsBuilder {
312 limits: self.clone(),
313 bad_lane: false,
314 }
315 }
316
317 #[must_use]
326 pub fn resolve(&self, driver: DriverKind) -> Limits {
327 let mut out = Limits::from_effective(&self.effective(driver));
328 out.pressure = self.pressure;
329 out.lane_reserve = self.lane_reserve;
330 out
331 }
332
333 pub fn validate(&self, workers: u16, descriptor_limit: Option<u64>) -> Result<(), NetError> {
346 LimitsBuilder {
348 limits: self.clone(),
349 bad_lane: false,
350 }
351 .check()?;
352 let e = self.effective(DriverKind::Blocking);
353 let need_budget = u64::from(workers)
354 .saturating_mul(u64::from(e.read_class_max.bytes()))
355 .saturating_mul(2);
356 if e.buffer_budget < need_budget {
357 return Err(invalid(
358 "buffer_budget",
359 ConfigReason::BudgetBelowWorkers { need: need_budget },
360 ));
361 }
362 if let Some(have) = descriptor_limit {
363 let need = descriptors_needed(e.max_connections, workers);
364 if need > have {
365 return Err(invalid(
366 "max_connections",
367 ConfigReason::DescriptorLimit { have, need },
368 ));
369 }
370 }
371 Ok(())
372 }
373
374 pub(crate) fn effective(&self, driver: DriverKind) -> Effective {
376 let d = Effective::defaults(driver);
377 let max_connections = self.max_connections.unwrap_or(d.max_connections);
378 let (max_per_source, source_policy) = self
379 .max_per_source
380 .unwrap_or((d.max_per_source.min(max_connections), d.source_policy));
381 let (read_class, read_class_max) =
382 self.read_class.unwrap_or((d.read_class, d.read_class_max));
383 let (graceful_linger, graceful_linger_bytes) = self
384 .graceful_linger
385 .unwrap_or((d.graceful_linger, d.graceful_linger_bytes));
386 Effective {
387 max_connections,
388 max_per_listener: self.max_per_listener.unwrap_or(max_connections),
389 max_per_source,
390 source_policy,
391 backlog: self.backlog.unwrap_or(d.backlog),
392 accept_batch: self.accept_batch.unwrap_or(d.accept_batch),
393 handshake_timeout: self.handshake_timeout.unwrap_or(d.handshake_timeout),
394 idle_timeout: self.idle_timeout.unwrap_or(d.idle_timeout),
395 read_timeout: self.read_timeout.unwrap_or(d.read_timeout),
396 write_timeout: self.write_timeout.unwrap_or(d.write_timeout),
397 park_timeout: self.park_timeout.unwrap_or(d.park_timeout),
398 min_rate: self.min_rate.unwrap_or(d.min_rate),
399 proxy_header_max: self.proxy_header_max.unwrap_or(d.proxy_header_max),
400 read_class,
401 read_class_max,
402 output_budget: self.output_budget.unwrap_or(d.output_budget),
403 completion_queue: self.completion_queue.unwrap_or(d.completion_queue),
404 buffer_budget: self.buffer_budget.unwrap_or(d.buffer_budget),
405 drain_timeout: self.drain_timeout.unwrap_or(d.drain_timeout),
406 graceful_linger,
407 graceful_linger_bytes,
408 refusal_bytes_max: self.refusal_bytes_max.unwrap_or(d.refusal_bytes_max),
409 tick: self.tick.unwrap_or(d.tick),
410 pressure: self.pressure,
411 lane_reserve: self.lane_reserve.map(|v| v.unwrap_or(0)),
412 }
413 }
414
415 pub(crate) fn overlay(&self, other: &Limits) -> Limits {
417 macro_rules! pick {
418 ($($f:ident),*) => { Limits { $($f: other.$f.or(self.$f),)* lane_reserve: {
419 let mut r = self.lane_reserve;
420 for (i, v) in other.lane_reserve.iter().enumerate() { if v.is_some() { r[i] = *v; } }
421 r
422 } } };
423 }
424 pick!(
425 max_connections,
426 max_per_listener,
427 max_per_source,
428 backlog,
429 accept_batch,
430 handshake_timeout,
431 idle_timeout,
432 read_timeout,
433 write_timeout,
434 park_timeout,
435 min_rate,
436 proxy_header_max,
437 read_class,
438 output_budget,
439 completion_queue,
440 buffer_budget,
441 drain_timeout,
442 graceful_linger,
443 refusal_bytes_max,
444 tick,
445 pressure
446 )
447 }
448
449 fn from_effective(e: &Effective) -> Limits {
450 Limits {
451 max_connections: Some(e.max_connections),
452 max_per_listener: Some(e.max_per_listener),
453 max_per_source: Some((e.max_per_source, e.source_policy)),
454 backlog: Some(e.backlog),
455 accept_batch: Some(e.accept_batch),
456 handshake_timeout: Some(e.handshake_timeout),
457 idle_timeout: Some(e.idle_timeout),
458 read_timeout: Some(e.read_timeout),
459 write_timeout: Some(e.write_timeout),
460 park_timeout: Some(e.park_timeout),
461 min_rate: Some(e.min_rate),
462 proxy_header_max: Some(e.proxy_header_max),
463 read_class: Some((e.read_class, e.read_class_max)),
464 output_budget: Some(e.output_budget),
465 completion_queue: Some(e.completion_queue),
466 buffer_budget: Some(e.buffer_budget),
467 drain_timeout: Some(e.drain_timeout),
468 graceful_linger: Some((e.graceful_linger, e.graceful_linger_bytes)),
469 refusal_bytes_max: Some(e.refusal_bytes_max),
470 tick: Some(e.tick),
471 pressure: None,
472 lane_reserve: [None; RESERVED_LANES],
473 }
474 }
475
476 #[must_use]
478 pub fn max_connections(&self) -> Option<u32> {
479 self.max_connections
480 }
481 #[must_use]
483 pub fn max_per_listener(&self) -> Option<u32> {
484 self.max_per_listener
485 }
486 #[must_use]
491 pub fn max_per_source(&self) -> Option<(u32, PrefixPolicy)> {
492 self.max_per_source
493 }
494 #[must_use]
496 pub fn backlog(&self) -> Option<u32> {
497 self.backlog
498 }
499 #[must_use]
501 pub fn accept_batch(&self) -> Option<u16> {
502 self.accept_batch
503 }
504 #[must_use]
506 pub fn handshake_timeout(&self) -> Option<Duration> {
507 self.handshake_timeout
508 }
509 #[must_use]
511 pub fn idle_timeout(&self) -> Option<Duration> {
512 self.idle_timeout
513 }
514 #[must_use]
516 pub fn read_timeout(&self) -> Option<Duration> {
517 self.read_timeout
518 }
519 #[must_use]
521 pub fn write_timeout(&self) -> Option<Duration> {
522 self.write_timeout
523 }
524 #[must_use]
526 pub fn park_timeout(&self) -> Option<Duration> {
527 self.park_timeout
528 }
529 #[must_use]
531 pub fn min_rate(&self) -> Option<MinRate> {
532 self.min_rate
533 }
534 #[must_use]
536 pub fn proxy_header_max(&self) -> Option<u16> {
537 self.proxy_header_max
538 }
539 #[must_use]
541 pub fn read_class(&self) -> Option<(SizeClass, SizeClass)> {
542 self.read_class
543 }
544 #[must_use]
546 pub fn output_budget(&self) -> Option<u32> {
547 self.output_budget
548 }
549 #[must_use]
551 pub fn completion_queue(&self) -> Option<u32> {
552 self.completion_queue
553 }
554 #[must_use]
556 pub fn buffer_budget(&self) -> Option<u64> {
557 self.buffer_budget
558 }
559 #[must_use]
561 pub fn drain_timeout(&self) -> Option<Duration> {
562 self.drain_timeout
563 }
564 #[must_use]
566 pub fn graceful_linger(&self) -> Option<(Duration, u32)> {
567 self.graceful_linger
568 }
569 #[must_use]
571 pub fn refusal_bytes_max(&self) -> Option<u16> {
572 self.refusal_bytes_max
573 }
574 #[must_use]
576 pub fn tick(&self) -> Option<Duration> {
577 self.tick
578 }
579 #[must_use]
581 pub fn pressure(&self) -> Option<Pressure> {
582 self.pressure
583 }
584 #[must_use]
586 pub fn lane_reserve(&self, lane: Lane) -> Option<u32> {
587 self.lane_reserve
588 .get(usize::from(lane.0))
589 .copied()
590 .flatten()
591 }
592}
593
594pub(crate) fn descriptors_needed(max_connections: u32, workers: u16) -> u64 {
597 u64::from(max_connections) + 2 * u64::from(workers) + 32
598}
599
600fn invalid(field: &'static str, reason: ConfigReason) -> NetError {
601 NetError::InvalidConfig { field, reason }
602}
603
604#[must_use]
613#[derive(Clone, Debug, Default)]
614pub struct LimitsBuilder {
615 limits: Limits,
616 bad_lane: bool,
618}
619
620macro_rules! setter {
621 ($(#[$m:meta])* $name:ident, $t:ty) => {
622 $(#[$m])*
623 pub fn $name(mut self, value: $t) -> Self {
624 self.limits.$name = Some(value);
625 self
626 }
627 };
628}
629
630pub(crate) const MAX_CONNECTIONS: u32 = 1 << 20;
632
633impl LimitsBuilder {
634 setter!(max_connections, u32);
636 setter!(max_per_listener, u32);
638 setter!(backlog, u32);
640 setter!(accept_batch, u16);
642 setter!(handshake_timeout, Duration);
644 setter!(idle_timeout, Duration);
646 setter!(read_timeout, Duration);
648 setter!(write_timeout, Duration);
650 setter!(park_timeout, Duration);
652 setter!(min_rate, MinRate);
654 setter!(output_budget, u32);
656 setter!(buffer_budget, u64);
658 setter!(drain_timeout, Duration);
660 setter!(refusal_bytes_max, u16);
662 setter!(tick, Duration);
664 setter!(pressure, Pressure);
666
667 pub fn max_per_source(mut self, n: u32, policy: PrefixPolicy) -> Self {
669 self.limits.max_per_source = Some((n, policy));
670 self
671 }
672
673 pub fn proxy_header_max(mut self, v2_body_bytes: u16) -> Self {
675 self.limits.proxy_header_max = Some(v2_body_bytes);
676 self
677 }
678
679 pub fn read_class(mut self, initial: SizeClass, max: SizeClass) -> Self {
681 self.limits.read_class = Some((initial, max));
682 self
683 }
684
685 pub fn completion_queue(mut self, n: u32) -> Self {
687 self.limits.completion_queue = Some(n);
688 self
689 }
690
691 pub fn graceful_linger(mut self, time: Duration, bytes: u32) -> Self {
693 self.limits.graceful_linger = Some((time, bytes));
694 self
695 }
696
697 pub fn lane_reserve(mut self, lane: Lane, slots: u32) -> Self {
699 match self.limits.lane_reserve.get_mut(usize::from(lane.0)) {
700 Some(slot) => *slot = Some(slots),
701 None => self.bad_lane = true,
703 }
704 self
705 }
706
707 pub fn build(self) -> Result<Limits, NetError> {
714 self.check()?;
715 let mut limits = self.limits;
716 if let Some(n) = limits.completion_queue {
717 limits.completion_queue = Some(n.next_power_of_two());
718 }
719 Ok(limits)
720 }
721
722 fn check(&self) -> Result<(), NetError> {
723 const TOO_LONG: ConfigReason = ConfigReason::TooLarge {
726 max: crate::time::LONGEST.as_secs(),
727 };
728 let l = &self.limits;
729 let zeros: [(&'static str, bool); 6] = [
731 ("max_connections", l.max_connections == Some(0)),
732 ("backlog", l.backlog == Some(0)),
733 ("accept_batch", l.accept_batch == Some(0)),
734 ("max_per_source", matches!(l.max_per_source, Some((0, _)))),
735 ("completion_queue", l.completion_queue == Some(0)),
736 ("output_budget", l.output_budget == Some(0)),
737 ];
738 for (field, zero) in zeros {
739 if zero {
740 return Err(invalid(field, ConfigReason::Zero));
741 }
742 }
743 if let Some(max) = l.max_connections {
744 if l.max_per_listener.is_some_and(|n| n > max) {
745 return Err(invalid("max_per_listener", ConfigReason::AboveGlobal));
746 }
747 if l.max_per_source.is_some_and(|(n, _)| n > max) {
748 return Err(invalid("max_per_source", ConfigReason::AboveGlobal));
749 }
750 }
751 if let Some(tick) = l.tick {
752 if tick < Duration::from_millis(1) {
753 return Err(invalid("tick", ConfigReason::TooSmall { min: 1 }));
754 }
755 if tick > Duration::from_millis(100) {
756 return Err(invalid("tick", ConfigReason::TooLarge { max: 100 }));
757 }
758 }
759 let tick = l.tick.unwrap_or(Duration::from_millis(1));
760 let timeouts: [(&'static str, Option<Duration>); 6] = [
761 ("handshake_timeout", l.handshake_timeout),
762 ("idle_timeout", l.idle_timeout),
763 ("read_timeout", l.read_timeout),
764 ("write_timeout", l.write_timeout),
765 ("park_timeout", l.park_timeout),
766 ("drain_timeout", l.drain_timeout),
767 ];
768 for (field, value) in timeouts {
769 if value.is_some_and(|d| d < tick) {
770 return Err(invalid(field, ConfigReason::BelowTick));
771 }
772 if value.is_some_and(|d| d > crate::time::LONGEST) {
773 return Err(invalid(field, TOO_LONG));
774 }
775 }
776 let long = |d: Duration| d > crate::time::LONGEST;
777 if l.min_rate
778 .is_some_and(|r| long(r.grace) || long(r.window) || long(r.check))
779 {
780 return Err(invalid("min_rate", TOO_LONG));
781 }
782 if l.graceful_linger.is_some_and(|(d, _)| long(d)) {
783 return Err(invalid("graceful_linger", TOO_LONG));
784 }
785 if l.max_connections.is_some_and(|n| n > MAX_CONNECTIONS) {
786 return Err(invalid(
787 "max_connections",
788 ConfigReason::TooLarge {
789 max: u64::from(MAX_CONNECTIONS),
790 },
791 ));
792 }
793 if let Some(rate) = l.min_rate {
794 if !rate.is_off() {
795 if rate.check.is_zero() || rate.grace.is_zero() {
796 return Err(invalid("min_rate", ConfigReason::Zero));
797 }
798 if rate.window < rate.check {
799 return Err(invalid("min_rate", ConfigReason::WindowBelowCheck));
800 }
801 }
802 }
803 if let Some((initial, max)) = l.read_class {
804 if max < initial {
805 return Err(invalid("read_class", ConfigReason::Inconsistent));
806 }
807 }
808 if l.refusal_bytes_max.is_some_and(|n| n > 512) {
809 return Err(invalid(
810 "refusal_bytes_max",
811 ConfigReason::TooLarge { max: 512 },
812 ));
813 }
814 if l.proxy_header_max.is_some_and(|n| n > 65_519) {
815 return Err(invalid(
816 "proxy_header_max",
817 ConfigReason::TooLarge { max: 65_519 },
818 ));
819 }
820 if l.completion_queue.is_some_and(|n| n > 1 << 20) {
821 return Err(invalid(
822 "completion_queue",
823 ConfigReason::TooLarge { max: 1 << 20 },
824 ));
825 }
826 if let Some(p) = l.pressure {
827 let factor_ok = p.factor > 0.0 && p.factor <= 1.0;
828 let ordered = p.high.partial_cmp(&p.low) == Some(std::cmp::Ordering::Greater);
829 if !ordered
830 || !factor_ok
831 || !(0.0..=1.0).contains(&p.high)
832 || !(0.0..=1.0).contains(&p.low)
833 {
834 return Err(invalid("pressure", ConfigReason::Inconsistent));
835 }
836 }
837 if self.bad_lane {
838 return Err(invalid("lane_reserve", ConfigReason::TooLarge { max: 7 }));
839 }
840 let reserved: u64 = l.lane_reserve.iter().flatten().map(|n| u64::from(*n)).sum();
841 if let Some(max) = l.max_connections {
842 if reserved > u64::from(max) {
843 return Err(invalid("lane_reserve", ConfigReason::AboveGlobal));
844 }
845 }
846 Ok(())
847 }
848}
849
850#[must_use]
860pub fn descriptor_limit() -> Option<u64> {
861 crate::sys::descriptor_limit()
862}
863
864#[cfg(test)]
865mod tests {
866 use super::*;
867
868 #[test]
869 fn test_unset_values_take_driver_defaults() {
870 let l = Limits::builder().build().unwrap();
871 assert_eq!(
872 l.effective(DriverKind::Blocking).idle_timeout,
873 Duration::from_secs(5)
874 );
875 assert_eq!(
876 l.effective(DriverKind::Reactor).idle_timeout,
877 Duration::from_secs(60)
878 );
879 }
880
881 #[test]
882 fn test_dependent_defaults_follow_max_connections() {
883 let l = Limits::builder().max_connections(10).build().unwrap();
884 let e = l.effective(DriverKind::Reactor);
885 assert_eq!(e.max_per_listener, 10);
886 assert_eq!(e.max_per_source, 10);
887 }
888
889 #[test]
890 fn test_zero_values_rejected() {
891 for b in [
892 Limits::builder().max_connections(0),
893 Limits::builder().backlog(0),
894 Limits::builder().accept_batch(0),
895 Limits::builder().max_per_source(0, PrefixPolicy::DEFAULT),
896 Limits::builder().completion_queue(0),
897 Limits::builder().output_budget(0),
898 ] {
899 assert!(matches!(
900 b.build(),
901 Err(NetError::InvalidConfig {
902 reason: ConfigReason::Zero,
903 ..
904 })
905 ));
906 }
907 }
908
909 #[test]
910 fn test_timeout_below_tick_rejected() {
911 let err = Limits::builder()
912 .tick(Duration::from_millis(100))
913 .read_timeout(Duration::from_millis(50))
914 .build()
915 .unwrap_err();
916 assert!(matches!(
917 err,
918 NetError::InvalidConfig {
919 field: "read_timeout",
920 reason: ConfigReason::BelowTick
921 }
922 ));
923 }
924
925 #[test]
928 fn test_timeouts_over_a_year_and_huge_caps_rejected() {
929 for field in ["idle_timeout", "read_timeout", "drain_timeout"] {
930 let b = Limits::builder();
931 let b = match field {
932 "idle_timeout" => b.idle_timeout(Duration::MAX),
933 "read_timeout" => b.read_timeout(Duration::from_secs(400 * 86_400)),
934 _ => b.drain_timeout(Duration::MAX),
935 };
936 let err = b.build().unwrap_err();
937 assert!(
938 matches!(err, NetError::InvalidConfig { field: f, reason: ConfigReason::TooLarge { .. } } if f == field),
939 "{err:?}"
940 );
941 }
942 assert!(
943 Limits::builder()
944 .idle_timeout(Duration::from_secs(365 * 86_400))
945 .build()
946 .is_ok()
947 );
948 let err = Limits::builder()
949 .max_connections(u32::MAX)
950 .build()
951 .unwrap_err();
952 assert!(matches!(
953 err,
954 NetError::InvalidConfig {
955 field: "max_connections",
956 reason: ConfigReason::TooLarge { .. }
957 }
958 ));
959 }
960
961 #[test]
962 fn test_min_rate_window_below_check_rejected() {
963 let rate = MinRate {
964 bytes_per_sec: 10,
965 window: Duration::from_millis(500),
966 grace: Duration::from_secs(1),
967 check: Duration::from_secs(1),
968 };
969 assert!(matches!(
970 Limits::builder().min_rate(rate).build(),
971 Err(NetError::InvalidConfig {
972 reason: ConfigReason::WindowBelowCheck,
973 ..
974 })
975 ));
976 assert!(Limits::builder().min_rate(MinRate::off()).build().is_ok());
977 }
978
979 #[test]
980 fn test_bounds_too_large() {
981 assert!(Limits::builder().refusal_bytes_max(513).build().is_err());
982 assert!(Limits::builder().refusal_bytes_max(512).build().is_ok());
983 assert!(Limits::builder().proxy_header_max(65_520).build().is_err());
984 assert!(
985 Limits::builder()
986 .completion_queue((1 << 20) + 1)
987 .build()
988 .is_err()
989 );
990 }
991
992 #[test]
993 fn test_completion_queue_rounded_to_power_of_two() {
994 let l = Limits::builder().completion_queue(1000).build().unwrap();
995 assert_eq!(l.completion_queue(), Some(1024));
996 }
997
998 #[test]
999 fn test_pressure_and_lane_reserve_validation() {
1000 let bad = Pressure {
1001 high: 0.5,
1002 low: 0.6,
1003 factor: 0.5,
1004 };
1005 assert!(Limits::builder().pressure(bad).build().is_err());
1006 assert!(Limits::builder().lane_reserve(Lane(8), 1).build().is_err());
1007 assert!(
1009 Limits::builder()
1010 .lane_reserve(Lane(8), 1)
1011 .lane_reserve(Lane(7), 1)
1012 .build()
1013 .is_err()
1014 );
1015 assert!(
1016 Limits::builder()
1017 .max_connections(10)
1018 .lane_reserve(Lane(0), 6)
1019 .lane_reserve(Lane(1), 5)
1020 .build()
1021 .is_err()
1022 );
1023 }
1024
1025 #[test]
1026 fn test_validate_descriptor_limit_and_budget() {
1027 let l = Limits::builder().max_connections(1000).build().unwrap();
1028 assert!(matches!(
1029 l.validate(4, Some(500)),
1030 Err(NetError::InvalidConfig {
1031 reason: ConfigReason::DescriptorLimit { have: 500, .. },
1032 ..
1033 })
1034 ));
1035 assert!(l.validate(4, Some(100_000)).is_ok());
1036 let small = Limits::builder().buffer_budget(1024).build().unwrap();
1037 assert!(matches!(
1038 small.validate(4, None),
1039 Err(NetError::InvalidConfig {
1040 reason: ConfigReason::BudgetBelowWorkers { .. },
1041 ..
1042 })
1043 ));
1044 }
1045
1046 #[test]
1047 fn test_overlay_takes_listener_values() {
1048 let base = Limits::builder()
1049 .max_connections(100)
1050 .idle_timeout(Duration::from_secs(9))
1051 .build()
1052 .unwrap();
1053 let over = Limits::builder()
1054 .idle_timeout(Duration::from_secs(1))
1055 .build()
1056 .unwrap();
1057 let merged = base.overlay(&over);
1058 assert_eq!(merged.max_connections(), Some(100));
1059 assert_eq!(merged.idle_timeout(), Some(Duration::from_secs(1)));
1060 }
1061
1062 #[test]
1063 fn test_resolve_sets_every_value() {
1064 let r = Limits::default().resolve(DriverKind::Blocking);
1065 assert!(
1066 r.max_connections().is_some() && r.tick().is_some() && r.graceful_linger().is_some()
1067 );
1068 }
1069}