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]
568 pub fn buffer_budget(&self) -> Option<u64> {
569 self.buffer_budget
570 }
571 #[must_use]
573 pub fn drain_timeout(&self) -> Option<Duration> {
574 self.drain_timeout
575 }
576 #[must_use]
578 pub fn graceful_linger(&self) -> Option<(Duration, u32)> {
579 self.graceful_linger
580 }
581 #[must_use]
583 pub fn refusal_bytes_max(&self) -> Option<u16> {
584 self.refusal_bytes_max
585 }
586 #[must_use]
588 pub fn tick(&self) -> Option<Duration> {
589 self.tick
590 }
591 #[must_use]
593 pub fn pressure(&self) -> Option<Pressure> {
594 self.pressure
595 }
596 #[must_use]
598 pub fn lane_reserve(&self, lane: Lane) -> Option<u32> {
599 self.lane_reserve
600 .get(usize::from(lane.0))
601 .copied()
602 .flatten()
603 }
604}
605
606pub(crate) fn descriptors_needed(max_connections: u32, workers: u16) -> u64 {
609 u64::from(max_connections) + 2 * u64::from(workers) + 32
610}
611
612fn invalid(field: &'static str, reason: ConfigReason) -> NetError {
613 NetError::InvalidConfig { field, reason }
614}
615
616#[must_use]
625#[derive(Clone, Debug, Default)]
626pub struct LimitsBuilder {
627 limits: Limits,
628 bad_lane: bool,
630}
631
632macro_rules! setter {
633 ($(#[$m:meta])* $name:ident, $t:ty) => {
634 $(#[$m])*
635 pub fn $name(mut self, value: $t) -> Self {
636 self.limits.$name = Some(value);
637 self
638 }
639 };
640}
641
642pub(crate) const MAX_CONNECTIONS: u32 = 1 << 20;
644
645impl LimitsBuilder {
646 setter!(max_connections, u32);
648 setter!(max_per_listener, u32);
650 setter!(backlog, u32);
652 setter!(accept_batch, u16);
654 setter!(handshake_timeout, Duration);
656 setter!(idle_timeout, Duration);
658 setter!(read_timeout, Duration);
660 setter!(write_timeout, Duration);
662 setter!(park_timeout, Duration);
664 setter!(min_rate, MinRate);
666 setter!(output_budget, u32);
668 setter!(buffer_budget, u64);
672 setter!(drain_timeout, Duration);
674 setter!(refusal_bytes_max, u16);
676 setter!(tick, Duration);
678 setter!(pressure, Pressure);
680
681 pub fn max_per_source(mut self, n: u32, policy: PrefixPolicy) -> Self {
683 self.limits.max_per_source = Some((n, policy));
684 self
685 }
686
687 pub fn proxy_header_max(mut self, v2_body_bytes: u16) -> Self {
689 self.limits.proxy_header_max = Some(v2_body_bytes);
690 self
691 }
692
693 pub fn read_class(mut self, initial: SizeClass, max: SizeClass) -> Self {
695 self.limits.read_class = Some((initial, max));
696 self
697 }
698
699 pub fn completion_queue(mut self, n: u32) -> Self {
701 self.limits.completion_queue = Some(n);
702 self
703 }
704
705 pub fn graceful_linger(mut self, time: Duration, bytes: u32) -> Self {
707 self.limits.graceful_linger = Some((time, bytes));
708 self
709 }
710
711 pub fn lane_reserve(mut self, lane: Lane, slots: u32) -> Self {
713 match self.limits.lane_reserve.get_mut(usize::from(lane.0)) {
714 Some(slot) => *slot = Some(slots),
715 None => self.bad_lane = true,
717 }
718 self
719 }
720
721 pub fn build(self) -> Result<Limits, NetError> {
728 self.check()?;
729 let mut limits = self.limits;
730 if let Some(n) = limits.completion_queue {
731 limits.completion_queue = Some(n.next_power_of_two());
732 }
733 Ok(limits)
734 }
735
736 fn check(&self) -> Result<(), NetError> {
737 const TOO_LONG: ConfigReason = ConfigReason::TooLarge {
740 max: crate::time::LONGEST.as_secs(),
741 };
742 let l = &self.limits;
743 let zeros: [(&'static str, bool); 6] = [
745 ("max_connections", l.max_connections == Some(0)),
746 ("backlog", l.backlog == Some(0)),
747 ("accept_batch", l.accept_batch == Some(0)),
748 ("max_per_source", matches!(l.max_per_source, Some((0, _)))),
749 ("completion_queue", l.completion_queue == Some(0)),
750 ("output_budget", l.output_budget == Some(0)),
751 ];
752 for (field, zero) in zeros {
753 if zero {
754 return Err(invalid(field, ConfigReason::Zero));
755 }
756 }
757 if let Some(max) = l.max_connections {
758 if l.max_per_listener.is_some_and(|n| n > max) {
759 return Err(invalid("max_per_listener", ConfigReason::AboveGlobal));
760 }
761 if l.max_per_source.is_some_and(|(n, _)| n > max) {
762 return Err(invalid("max_per_source", ConfigReason::AboveGlobal));
763 }
764 }
765 if let Some(tick) = l.tick {
766 if tick < Duration::from_millis(1) {
767 return Err(invalid("tick", ConfigReason::TooSmall { min: 1 }));
768 }
769 if tick > Duration::from_millis(100) {
770 return Err(invalid("tick", ConfigReason::TooLarge { max: 100 }));
771 }
772 }
773 let tick = l.tick.unwrap_or(Duration::from_millis(1));
774 let timeouts: [(&'static str, Option<Duration>); 6] = [
775 ("handshake_timeout", l.handshake_timeout),
776 ("idle_timeout", l.idle_timeout),
777 ("read_timeout", l.read_timeout),
778 ("write_timeout", l.write_timeout),
779 ("park_timeout", l.park_timeout),
780 ("drain_timeout", l.drain_timeout),
781 ];
782 for (field, value) in timeouts {
783 if value.is_some_and(|d| d < tick) {
784 return Err(invalid(field, ConfigReason::BelowTick));
785 }
786 if value.is_some_and(|d| d > crate::time::LONGEST) {
787 return Err(invalid(field, TOO_LONG));
788 }
789 }
790 let long = |d: Duration| d > crate::time::LONGEST;
791 if l.min_rate
792 .is_some_and(|r| long(r.grace) || long(r.window) || long(r.check))
793 {
794 return Err(invalid("min_rate", TOO_LONG));
795 }
796 if l.graceful_linger.is_some_and(|(d, _)| long(d)) {
797 return Err(invalid("graceful_linger", TOO_LONG));
798 }
799 if l.max_connections.is_some_and(|n| n > MAX_CONNECTIONS) {
800 return Err(invalid(
801 "max_connections",
802 ConfigReason::TooLarge {
803 max: u64::from(MAX_CONNECTIONS),
804 },
805 ));
806 }
807 if let Some(rate) = l.min_rate {
808 if !rate.is_off() {
809 if rate.check.is_zero() || rate.grace.is_zero() {
810 return Err(invalid("min_rate", ConfigReason::Zero));
811 }
812 if rate.window < rate.check {
813 return Err(invalid("min_rate", ConfigReason::WindowBelowCheck));
814 }
815 }
816 }
817 if let Some((initial, max)) = l.read_class {
818 if max < initial {
819 return Err(invalid("read_class", ConfigReason::Inconsistent));
820 }
821 }
822 if l.refusal_bytes_max.is_some_and(|n| n > 512) {
823 return Err(invalid(
824 "refusal_bytes_max",
825 ConfigReason::TooLarge { max: 512 },
826 ));
827 }
828 if l.proxy_header_max.is_some_and(|n| n > 65_519) {
829 return Err(invalid(
830 "proxy_header_max",
831 ConfigReason::TooLarge { max: 65_519 },
832 ));
833 }
834 if l.completion_queue.is_some_and(|n| n > 1 << 20) {
835 return Err(invalid(
836 "completion_queue",
837 ConfigReason::TooLarge { max: 1 << 20 },
838 ));
839 }
840 if let Some(p) = l.pressure {
841 let factor_ok = p.factor > 0.0 && p.factor <= 1.0;
842 let ordered = p.high.partial_cmp(&p.low) == Some(std::cmp::Ordering::Greater);
843 if !ordered
844 || !factor_ok
845 || !(0.0..=1.0).contains(&p.high)
846 || !(0.0..=1.0).contains(&p.low)
847 {
848 return Err(invalid("pressure", ConfigReason::Inconsistent));
849 }
850 }
851 if self.bad_lane {
852 return Err(invalid("lane_reserve", ConfigReason::TooLarge { max: 7 }));
853 }
854 let reserved: u64 = l.lane_reserve.iter().flatten().map(|n| u64::from(*n)).sum();
855 if let Some(max) = l.max_connections {
856 if reserved > u64::from(max) {
857 return Err(invalid("lane_reserve", ConfigReason::AboveGlobal));
858 }
859 }
860 Ok(())
861 }
862}
863
864#[must_use]
874pub fn descriptor_limit() -> Option<u64> {
875 crate::sys::descriptor_limit()
876}
877
878#[cfg(test)]
879mod tests {
880 use super::*;
881
882 #[test]
883 fn test_unset_values_take_driver_defaults() {
884 let l = Limits::builder().build().unwrap();
885 assert_eq!(
886 l.effective(DriverKind::Blocking).idle_timeout,
887 Duration::from_secs(5)
888 );
889 assert_eq!(
890 l.effective(DriverKind::Reactor).idle_timeout,
891 Duration::from_secs(60)
892 );
893 }
894
895 #[test]
896 fn test_dependent_defaults_follow_max_connections() {
897 let l = Limits::builder().max_connections(10).build().unwrap();
898 let e = l.effective(DriverKind::Reactor);
899 assert_eq!(e.max_per_listener, 10);
900 assert_eq!(e.max_per_source, 10);
901 }
902
903 #[test]
904 fn test_zero_values_rejected() {
905 for b in [
906 Limits::builder().max_connections(0),
907 Limits::builder().backlog(0),
908 Limits::builder().accept_batch(0),
909 Limits::builder().max_per_source(0, PrefixPolicy::DEFAULT),
910 Limits::builder().completion_queue(0),
911 Limits::builder().output_budget(0),
912 ] {
913 assert!(matches!(
914 b.build(),
915 Err(NetError::InvalidConfig {
916 reason: ConfigReason::Zero,
917 ..
918 })
919 ));
920 }
921 }
922
923 #[test]
924 fn test_timeout_below_tick_rejected() {
925 let err = Limits::builder()
926 .tick(Duration::from_millis(100))
927 .read_timeout(Duration::from_millis(50))
928 .build()
929 .unwrap_err();
930 assert!(matches!(
931 err,
932 NetError::InvalidConfig {
933 field: "read_timeout",
934 reason: ConfigReason::BelowTick
935 }
936 ));
937 }
938
939 #[test]
942 fn test_timeouts_over_a_year_and_huge_caps_rejected() {
943 for field in ["idle_timeout", "read_timeout", "drain_timeout"] {
944 let b = Limits::builder();
945 let b = match field {
946 "idle_timeout" => b.idle_timeout(Duration::MAX),
947 "read_timeout" => b.read_timeout(Duration::from_secs(400 * 86_400)),
948 _ => b.drain_timeout(Duration::MAX),
949 };
950 let err = b.build().unwrap_err();
951 assert!(
952 matches!(err, NetError::InvalidConfig { field: f, reason: ConfigReason::TooLarge { .. } } if f == field),
953 "{err:?}"
954 );
955 }
956 assert!(
957 Limits::builder()
958 .idle_timeout(Duration::from_secs(365 * 86_400))
959 .build()
960 .is_ok()
961 );
962 let err = Limits::builder()
963 .max_connections(u32::MAX)
964 .build()
965 .unwrap_err();
966 assert!(matches!(
967 err,
968 NetError::InvalidConfig {
969 field: "max_connections",
970 reason: ConfigReason::TooLarge { .. }
971 }
972 ));
973 }
974
975 #[test]
976 fn test_min_rate_window_below_check_rejected() {
977 let rate = MinRate {
978 bytes_per_sec: 10,
979 window: Duration::from_millis(500),
980 grace: Duration::from_secs(1),
981 check: Duration::from_secs(1),
982 };
983 assert!(matches!(
984 Limits::builder().min_rate(rate).build(),
985 Err(NetError::InvalidConfig {
986 reason: ConfigReason::WindowBelowCheck,
987 ..
988 })
989 ));
990 assert!(Limits::builder().min_rate(MinRate::off()).build().is_ok());
991 }
992
993 #[test]
994 fn test_bounds_too_large() {
995 assert!(Limits::builder().refusal_bytes_max(513).build().is_err());
996 assert!(Limits::builder().refusal_bytes_max(512).build().is_ok());
997 assert!(Limits::builder().proxy_header_max(65_520).build().is_err());
998 assert!(
999 Limits::builder()
1000 .completion_queue((1 << 20) + 1)
1001 .build()
1002 .is_err()
1003 );
1004 }
1005
1006 #[test]
1007 fn test_completion_queue_rounded_to_power_of_two() {
1008 let l = Limits::builder().completion_queue(1000).build().unwrap();
1009 assert_eq!(l.completion_queue(), Some(1024));
1010 }
1011
1012 #[test]
1013 fn test_pressure_and_lane_reserve_validation() {
1014 let bad = Pressure {
1015 high: 0.5,
1016 low: 0.6,
1017 factor: 0.5,
1018 };
1019 assert!(Limits::builder().pressure(bad).build().is_err());
1020 assert!(Limits::builder().lane_reserve(Lane(8), 1).build().is_err());
1021 assert!(
1023 Limits::builder()
1024 .lane_reserve(Lane(8), 1)
1025 .lane_reserve(Lane(7), 1)
1026 .build()
1027 .is_err()
1028 );
1029 assert!(
1030 Limits::builder()
1031 .max_connections(10)
1032 .lane_reserve(Lane(0), 6)
1033 .lane_reserve(Lane(1), 5)
1034 .build()
1035 .is_err()
1036 );
1037 }
1038
1039 #[test]
1040 fn test_validate_descriptor_limit_and_budget() {
1041 let l = Limits::builder().max_connections(1000).build().unwrap();
1042 assert!(matches!(
1043 l.validate(4, Some(500)),
1044 Err(NetError::InvalidConfig {
1045 reason: ConfigReason::DescriptorLimit { have: 500, .. },
1046 ..
1047 })
1048 ));
1049 assert!(l.validate(4, Some(100_000)).is_ok());
1050 let small = Limits::builder().buffer_budget(1024).build().unwrap();
1051 assert!(matches!(
1052 small.validate(4, None),
1053 Err(NetError::InvalidConfig {
1054 reason: ConfigReason::BudgetBelowWorkers { .. },
1055 ..
1056 })
1057 ));
1058 }
1059
1060 #[test]
1061 fn test_overlay_takes_listener_values() {
1062 let base = Limits::builder()
1063 .max_connections(100)
1064 .idle_timeout(Duration::from_secs(9))
1065 .build()
1066 .unwrap();
1067 let over = Limits::builder()
1068 .idle_timeout(Duration::from_secs(1))
1069 .build()
1070 .unwrap();
1071 let merged = base.overlay(&over);
1072 assert_eq!(merged.max_connections(), Some(100));
1073 assert_eq!(merged.idle_timeout(), Some(Duration::from_secs(1)));
1074 }
1075
1076 #[test]
1077 fn test_resolve_sets_every_value() {
1078 let r = Limits::default().resolve(DriverKind::Blocking);
1079 assert!(
1080 r.max_connections().is_some() && r.tick().is_some() && r.graceful_linger().is_some()
1081 );
1082 }
1083}