Skip to main content

net_io/
limits.rs

1//! Every bound net-io enforces, in one value.
2
3use std::time::Duration;
4
5use crate::addr::PrefixPolicy;
6use crate::driver::DriverKind;
7use crate::error::{ConfigReason, NetError};
8use crate::info::Lane;
9
10/// Lanes that can hold a connection reservation (0 to 7).
11const RESERVED_LANES: usize = 8;
12
13/// A minimum transfer rate, checked per direction while that direction is active.
14///
15/// # Examples
16///
17/// ```
18/// use std::time::Duration;
19/// let rate = net_io::MinRate::new(512, Duration::from_secs(10));
20/// assert_eq!(rate.grace, Duration::from_secs(5));
21/// assert!(net_io::MinRate::off().is_off());
22/// ```
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct MinRate {
25    /// Bytes per second the peer must reach over the window.
26    pub bytes_per_sec: u32,
27    /// The sliding window.
28    pub window: Duration,
29    /// How long after a direction becomes active the check starts.
30    pub grace: Duration,
31    /// How often the rate is checked.
32    pub check: Duration,
33}
34
35impl MinRate {
36    /// No minimum rate.
37    #[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    /// `bytes_per_sec` over `window`, after a 5 s grace, checked every second.
48    #[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    /// Whether the rate check is off.
59    #[must_use]
60    pub const fn is_off(&self) -> bool {
61        self.bytes_per_sec == 0
62    }
63}
64
65/// Adaptive deadlines: past `high` of `max_connections`, the handshake and idle
66/// deadlines of new and waiting connections are multiplied by `factor`, down to 1 s,
67/// until the count falls below `low`. No cost below the threshold beyond one check
68/// per connection opened or closed.
69///
70/// ```
71/// let p = net_io::Pressure::default();
72/// assert!(p.high > p.low);
73/// ```
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct Pressure {
76    /// Fraction of `max_connections` above which deadlines shrink.
77    pub high: f32,
78    /// Fraction below which they return to normal.
79    pub low: f32,
80    /// The multiplier applied to handshake and idle timeouts.
81    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/// A buffer size class: a power of two from 1 KiB to 1 MiB.
95///
96/// ```
97/// use net_io::SizeClass;
98/// assert_eq!(SizeClass::MEDIUM.bytes(), 16 * 1024);
99/// assert!(SizeClass::new(3000).is_err());
100/// assert_eq!(SizeClass::new(2048).unwrap().bytes(), 2048);
101/// ```
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
103pub struct SizeClass(u32);
104
105impl SizeClass {
106    /// 4 KiB.
107    pub const SMALL: SizeClass = SizeClass(4 * 1024);
108    /// 16 KiB.
109    pub const MEDIUM: SizeClass = SizeClass(16 * 1024);
110    /// 64 KiB.
111    pub const LARGE: SizeClass = SizeClass(64 * 1024);
112
113    /// A class of `bytes`.
114    ///
115    /// # Errors
116    ///
117    /// `InvalidConfig { field: "size_class" }` unless `bytes` is a power of two from 1 KiB to 1 MiB.
118    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    /// The size in bytes.
141    #[must_use]
142    pub const fn bytes(self) -> u32 {
143        self.0
144    }
145}
146
147/// Every bound net-io enforces. Unset values take the defaults of the driver
148/// that runs the connection.
149///
150/// # Examples
151///
152/// ```
153/// use net_io::{DriverKind, Limits, MinRate};
154/// use std::time::Duration;
155///
156/// let limits = Limits::builder()
157///     .max_connections(20_000)
158///     .idle_timeout(Duration::from_secs(15))
159///     .min_rate(MinRate::new(512, Duration::from_secs(10)))
160///     .build()?;
161/// assert_eq!(limits.max_connections(), Some(20_000));
162/// assert_eq!(limits.read_timeout(), None);
163/// assert_eq!(limits.resolve(DriverKind::Blocking).read_timeout(), Some(Duration::from_secs(30)));
164/// # Ok::<(), net_io::NetError>(())
165/// ```
166#[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/// The resolved values a running connection uses.
194#[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    /// Slots each of the most important lanes keeps free from the less important.
221    pub lane_reserve: [u32; RESERVED_LANES],
222}
223
224impl Effective {
225    /// The slots the lanes more important than `lane` keep free.
226    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    /// The defaults of `driver` (blocking, or the reactor).
234    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    /// A builder with every value unset.
269    ///
270    /// ```
271    /// let limits = net_io::Limits::builder().max_connections(100).build()?;
272    /// assert_eq!(limits.max_per_source(), None);
273    /// # Ok::<(), net_io::NetError>(())
274    /// ```
275    pub fn builder() -> LimitsBuilder {
276        LimitsBuilder::default()
277    }
278
279    /// Every value set to the reactor's defaults.
280    ///
281    /// ```
282    /// assert_eq!(net_io::Limits::reactor_defaults().max_connections(), Some(10_000));
283    /// ```
284    #[must_use]
285    pub fn reactor_defaults() -> Limits {
286        Limits::from_effective(&Effective::defaults(DriverKind::Reactor))
287    }
288
289    /// Every value set to the blocking driver's defaults.
290    ///
291    /// ```
292    /// assert_eq!(net_io::Limits::blocking_defaults().idle_timeout(), Some(std::time::Duration::from_secs(5)));
293    /// ```
294    #[must_use]
295    pub fn blocking_defaults() -> Limits {
296        Limits::from_effective(&Effective::defaults(DriverKind::Blocking))
297    }
298
299    /// A builder starting from these values.
300    ///
301    /// Every value carried over counts as set, so lowering `max_connections`
302    /// below a carried-over `max_per_listener` fails validation. Start from
303    /// [`Limits::builder`] to let dependent values follow `max_connections`.
304    ///
305    /// ```
306    /// let limits = net_io::Limits::blocking_defaults().to_builder().max_connections(256).build()?;
307    /// assert_eq!(limits.max_connections(), Some(256));
308    /// # Ok::<(), net_io::NetError>(())
309    /// ```
310    pub fn to_builder(&self) -> LimitsBuilder {
311        LimitsBuilder {
312            limits: self.clone(),
313            bad_lane: false,
314        }
315    }
316
317    /// These limits with unset values filled from `driver`'s defaults.
318    ///
319    /// ```
320    /// let limits = net_io::Limits::builder().max_connections(10).build()?;
321    /// let resolved = limits.resolve(net_io::DriverKind::Blocking);
322    /// assert_eq!(resolved.max_per_source().map(|(n, _)| n), Some(10));
323    /// # Ok::<(), net_io::NetError>(())
324    /// ```
325    #[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    /// Checks the resolved values against each other, the worker count, and the
334    /// process's descriptor limit.
335    ///
336    /// # Errors
337    ///
338    /// `InvalidConfig { field, reason }` for the first rule broken.
339    ///
340    /// ```
341    /// let limits = net_io::Limits::builder().max_connections(1_000_000).build()?;
342    /// assert!(limits.validate(4, Some(1024)).is_err());
343    /// # Ok::<(), net_io::NetError>(())
344    /// ```
345    pub fn validate(&self, workers: u16, descriptor_limit: Option<u64>) -> Result<(), NetError> {
346        // Rules that need only the values themselves.
347        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    /// The resolved values for `driver`.
375    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    /// Values from `other` where it sets them, otherwise from `self` (listener overrides).
416    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    /// The global connection cap.
477    #[must_use]
478    pub fn max_connections(&self) -> Option<u32> {
479        self.max_connections
480    }
481    /// The per-listener connection cap.
482    #[must_use]
483    pub fn max_per_listener(&self) -> Option<u32> {
484        self.max_per_listener
485    }
486    /// The per-source concurrency cap and how sources are grouped. Each listener
487    /// applies its own value to its own connections. Every open connection counts,
488    /// including one finishing a graceful close, so a client at the cap that
489    /// reconnects at once can be refused until its last connection is closed.
490    #[must_use]
491    pub fn max_per_source(&self) -> Option<(u32, PrefixPolicy)> {
492        self.max_per_source
493    }
494    /// The listen backlog.
495    #[must_use]
496    pub fn backlog(&self) -> Option<u32> {
497        self.backlog
498    }
499    /// Connections accepted per wake-up.
500    #[must_use]
501    pub fn accept_batch(&self) -> Option<u16> {
502        self.accept_batch
503    }
504    /// Time for the PROXY header and TLS handshake together.
505    #[must_use]
506    pub fn handshake_timeout(&self) -> Option<Duration> {
507        self.handshake_timeout
508    }
509    /// Time to wait for the next exchange.
510    #[must_use]
511    pub fn idle_timeout(&self) -> Option<Duration> {
512        self.idle_timeout
513    }
514    /// Time to wait for bytes during an exchange.
515    #[must_use]
516    pub fn read_timeout(&self) -> Option<Duration> {
517        self.read_timeout
518    }
519    /// Time to wait for the peer to take bytes.
520    #[must_use]
521    pub fn write_timeout(&self) -> Option<Duration> {
522        self.write_timeout
523    }
524    /// Time a parked connection may wait for its completion.
525    #[must_use]
526    pub fn park_timeout(&self) -> Option<Duration> {
527        self.park_timeout
528    }
529    /// The minimum transfer rate.
530    #[must_use]
531    pub fn min_rate(&self) -> Option<MinRate> {
532        self.min_rate
533    }
534    /// The PROXY v2 address-and-TLV cap.
535    #[must_use]
536    pub fn proxy_header_max(&self) -> Option<u16> {
537        self.proxy_header_max
538    }
539    /// The initial and maximum read buffer class.
540    #[must_use]
541    pub fn read_class(&self) -> Option<(SizeClass, SizeClass)> {
542        self.read_class
543    }
544    /// Pool memory a connection's output may hold.
545    #[must_use]
546    pub fn output_budget(&self) -> Option<u32> {
547        self.output_budget
548    }
549    /// A worker's completion queue length.
550    #[must_use]
551    pub fn completion_queue(&self) -> Option<u32> {
552        self.completion_queue
553    }
554    /// Total bytes of buffers all workers may allocate.
555    #[must_use]
556    pub fn buffer_budget(&self) -> Option<u64> {
557        self.buffer_budget
558    }
559    /// The drain deadline.
560    #[must_use]
561    pub fn drain_timeout(&self) -> Option<Duration> {
562        self.drain_timeout
563    }
564    /// The graceful-close linger: time and bytes read and discarded.
565    #[must_use]
566    pub fn graceful_linger(&self) -> Option<(Duration, u32)> {
567        self.graceful_linger
568    }
569    /// The largest refusal reply.
570    #[must_use]
571    pub fn refusal_bytes_max(&self) -> Option<u16> {
572        self.refusal_bytes_max
573    }
574    /// The timer resolution.
575    #[must_use]
576    pub fn tick(&self) -> Option<Duration> {
577        self.tick
578    }
579    /// Adaptive deadlines under pressure.
580    #[must_use]
581    pub fn pressure(&self) -> Option<Pressure> {
582        self.pressure
583    }
584    /// The connection slots reserved for `lane` (lanes 0 to 7).
585    #[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
594/// Descriptors a configuration needs: connections, two wake descriptors per
595/// worker, and a fixed reserve for listeners and the spare descriptor.
596pub(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/// Builds [`Limits`]; every setter is optional.
605///
606/// ```
607/// use net_io::{ConfigReason, Limits, NetError};
608/// let err = Limits::builder().max_connections(100).max_per_listener(200).build().unwrap_err();
609/// assert!(matches!(err, NetError::InvalidConfig { field: "max_per_listener", reason: ConfigReason::AboveGlobal }));
610/// assert!(Limits::builder().max_connections(100).build().is_ok());
611/// ```
612#[must_use]
613#[derive(Clone, Debug, Default)]
614pub struct LimitsBuilder {
615    limits: Limits,
616    /// A `lane_reserve` for a lane that does not exist, refused by `build`.
617    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
630/// The most connections one server holds: the source tables are sized from it.
631pub(crate) const MAX_CONNECTIONS: u32 = 1 << 20;
632
633impl LimitsBuilder {
634    setter!(/// The global connection cap.
635        max_connections, u32);
636    setter!(/// The per-listener connection cap.
637        max_per_listener, u32);
638    setter!(/// The listen backlog.
639        backlog, u32);
640    setter!(/// Connections accepted per wake-up.
641        accept_batch, u16);
642    setter!(/// Time for the PROXY header and TLS handshake together.
643        handshake_timeout, Duration);
644    setter!(/// Time to wait for the next exchange.
645        idle_timeout, Duration);
646    setter!(/// Time to wait for bytes during an exchange.
647        read_timeout, Duration);
648    setter!(/// Time to wait for the peer to take bytes.
649        write_timeout, Duration);
650    setter!(/// Time a parked connection may wait for its completion.
651        park_timeout, Duration);
652    setter!(/// The minimum transfer rate ([`MinRate::off`] to disable).
653        min_rate, MinRate);
654    setter!(/// Pool memory a connection's output may hold.
655        output_budget, u32);
656    setter!(/// Total bytes of buffers all workers may allocate.
657        buffer_budget, u64);
658    setter!(/// The drain deadline.
659        drain_timeout, Duration);
660    setter!(/// The largest refusal reply (at most 512).
661        refusal_bytes_max, u16);
662    setter!(/// The timer resolution (1 ms to 100 ms).
663        tick, Duration);
664    setter!(/// Adaptive deadlines under pressure.
665        pressure, Pressure);
666
667    /// The per-source concurrency cap and how sources are grouped.
668    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    /// The PROXY v2 address-and-TLV cap (up to 65,519).
674    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    /// The initial read buffer class and the largest a session may grow it to.
680    pub fn read_class(mut self, initial: SizeClass, max: SizeClass) -> Self {
681        self.limits.read_class = Some((initial, max));
682        self
683    }
684
685    /// A worker's completion queue length, rounded up to a power of two.
686    pub fn completion_queue(mut self, n: u32) -> Self {
687        self.limits.completion_queue = Some(n);
688        self
689    }
690
691    /// The graceful-close linger: time and bytes read and discarded.
692    pub fn graceful_linger(mut self, time: Duration, bytes: u32) -> Self {
693        self.limits.graceful_linger = Some((time, bytes));
694        self
695    }
696
697    /// Connection slots reserved for `lane` (lanes 0 to 7; applied from `0.6.0`).
698    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            // Rejected by `build` (field "lane_reserve").
702            None => self.bad_lane = true,
703        }
704        self
705    }
706
707    /// Checks the values that were set and returns the limits.
708    ///
709    /// # Errors
710    ///
711    /// `InvalidConfig { field, reason }` for the first rule broken, in the order
712    /// documented in `docs/API.md`.
713    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        /// A timeout over a year is refused (in seconds): `Instant + Duration` panics
724        /// on overflow, and "no limit" is not a limit a peer should be able to hold.
725        const TOO_LONG: ConfigReason = ConfigReason::TooLarge {
726            max: crate::time::LONGEST.as_secs(),
727        };
728        let l = &self.limits;
729        // Zero where zero is meaningless.
730        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/// The process's open-descriptor limit (`RLIMIT_NOFILE`, soft) on Unix: what
851/// `ServerBuilder::build` checks a global cap against. `None` where it is unlimited,
852/// and on Windows, where socket handles do not come from a small table. Use it to
853/// place a soft cap of your own under the one net-io would pick.
854///
855/// ```
856/// let cap = net_io::descriptor_limit().map_or(10_000, |n| n.saturating_sub(64));
857/// assert!(cap > 0);
858/// ```
859#[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    /// "No limit" spelled `Duration::MAX` is refused at build instead of panicking
926    /// on the first deadline (review finding).
927    #[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        // A later valid lane 7 does not hide the invalid one (review finding).
1008        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}