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    ///
556    /// Each worker's pool keeps at most the budget divided by the workers in its
557    /// free lists and frees what is released above that, and a pool that needs a
558    /// buffer of one size with the budget spent frees the buffers it keeps of other
559    /// sizes first, so the budget comes back after a burst.
560    ///
561    /// On the reactor a TLS connection takes its two buffers (the largest read class
562    /// in, 64 KiB out) only when its first bytes arrive, and the connections whose
563    /// handshake has not finished may hold at most a quarter of the budget, divided
564    /// by the workers, on each worker (at least one handshake each). A connection
565    /// whose handshake would take buffers above that is closed with
566    /// `Limit(BufferBudget)`; plaintext connections keep the rest.
567    #[must_use]
568    pub fn buffer_budget(&self) -> Option<u64> {
569        self.buffer_budget
570    }
571    /// The drain deadline.
572    #[must_use]
573    pub fn drain_timeout(&self) -> Option<Duration> {
574        self.drain_timeout
575    }
576    /// The graceful-close linger: time and bytes read and discarded.
577    #[must_use]
578    pub fn graceful_linger(&self) -> Option<(Duration, u32)> {
579        self.graceful_linger
580    }
581    /// The largest refusal reply.
582    #[must_use]
583    pub fn refusal_bytes_max(&self) -> Option<u16> {
584        self.refusal_bytes_max
585    }
586    /// The timer resolution.
587    #[must_use]
588    pub fn tick(&self) -> Option<Duration> {
589        self.tick
590    }
591    /// Adaptive deadlines under pressure.
592    #[must_use]
593    pub fn pressure(&self) -> Option<Pressure> {
594        self.pressure
595    }
596    /// The connection slots reserved for `lane` (lanes 0 to 7).
597    #[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
606/// Descriptors a configuration needs: connections, two wake descriptors per
607/// worker, and a fixed reserve for listeners and the spare descriptor.
608pub(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/// Builds [`Limits`]; every setter is optional.
617///
618/// ```
619/// use net_io::{ConfigReason, Limits, NetError};
620/// let err = Limits::builder().max_connections(100).max_per_listener(200).build().unwrap_err();
621/// assert!(matches!(err, NetError::InvalidConfig { field: "max_per_listener", reason: ConfigReason::AboveGlobal }));
622/// assert!(Limits::builder().max_connections(100).build().is_ok());
623/// ```
624#[must_use]
625#[derive(Clone, Debug, Default)]
626pub struct LimitsBuilder {
627    limits: Limits,
628    /// A `lane_reserve` for a lane that does not exist, refused by `build`.
629    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
642/// The most connections one server holds: the source tables are sized from it.
643pub(crate) const MAX_CONNECTIONS: u32 = 1 << 20;
644
645impl LimitsBuilder {
646    setter!(
647        /// The global connection cap.
648        max_connections,
649        u32
650    );
651    setter!(
652        /// The per-listener connection cap.
653        max_per_listener,
654        u32
655    );
656    setter!(
657        /// The listen backlog.
658        backlog,
659        u32
660    );
661    setter!(
662        /// Connections accepted per wake-up.
663        accept_batch,
664        u16
665    );
666    setter!(
667        /// Time for the PROXY header and TLS handshake together.
668        handshake_timeout,
669        Duration
670    );
671    setter!(
672        /// Time to wait for the next exchange.
673        idle_timeout,
674        Duration
675    );
676    setter!(
677        /// Time to wait for bytes during an exchange.
678        read_timeout,
679        Duration
680    );
681    setter!(
682        /// Time to wait for the peer to take bytes.
683        write_timeout,
684        Duration
685    );
686    setter!(
687        /// Time a parked connection may wait for its completion.
688        park_timeout,
689        Duration
690    );
691    setter!(
692        /// The minimum transfer rate ([`MinRate::off`] to disable).
693        min_rate,
694        MinRate
695    );
696    setter!(
697        /// Pool memory a connection's output may hold.
698        output_budget,
699        u32
700    );
701    setter!(
702        /// Total bytes of buffers all workers may allocate. A quarter of it, shared
703        /// among the workers, is the most unfinished TLS handshakes may hold on the
704        /// reactor; see [`Limits::buffer_budget`].
705        buffer_budget,
706        u64
707    );
708    setter!(
709        /// The drain deadline.
710        drain_timeout,
711        Duration
712    );
713    setter!(
714        /// The largest refusal reply (at most 512).
715        refusal_bytes_max,
716        u16
717    );
718    setter!(
719        /// The timer resolution (1 ms to 100 ms).
720        tick,
721        Duration
722    );
723    setter!(
724        /// Adaptive deadlines under pressure.
725        pressure,
726        Pressure
727    );
728
729    /// The per-source concurrency cap and how sources are grouped.
730    pub fn max_per_source(mut self, n: u32, policy: PrefixPolicy) -> Self {
731        self.limits.max_per_source = Some((n, policy));
732        self
733    }
734
735    /// The PROXY v2 address-and-TLV cap (up to 65,519).
736    pub fn proxy_header_max(mut self, v2_body_bytes: u16) -> Self {
737        self.limits.proxy_header_max = Some(v2_body_bytes);
738        self
739    }
740
741    /// The initial read buffer class and the largest a session may grow it to.
742    pub fn read_class(mut self, initial: SizeClass, max: SizeClass) -> Self {
743        self.limits.read_class = Some((initial, max));
744        self
745    }
746
747    /// A worker's completion queue length, rounded up to a power of two.
748    pub fn completion_queue(mut self, n: u32) -> Self {
749        self.limits.completion_queue = Some(n);
750        self
751    }
752
753    /// The graceful-close linger: time and bytes read and discarded.
754    pub fn graceful_linger(mut self, time: Duration, bytes: u32) -> Self {
755        self.limits.graceful_linger = Some((time, bytes));
756        self
757    }
758
759    /// Connection slots reserved for `lane` (lanes 0 to 7; applied from `0.6.0`).
760    pub fn lane_reserve(mut self, lane: Lane, slots: u32) -> Self {
761        match self.limits.lane_reserve.get_mut(usize::from(lane.0)) {
762            Some(slot) => *slot = Some(slots),
763            // Rejected by `build` (field "lane_reserve").
764            None => self.bad_lane = true,
765        }
766        self
767    }
768
769    /// Checks the values that were set and returns the limits.
770    ///
771    /// # Errors
772    ///
773    /// `InvalidConfig { field, reason }` for the first rule broken, in the order
774    /// documented in `docs/API.md`.
775    pub fn build(self) -> Result<Limits, NetError> {
776        self.check()?;
777        let mut limits = self.limits;
778        if let Some(n) = limits.completion_queue {
779            limits.completion_queue = Some(n.next_power_of_two());
780        }
781        Ok(limits)
782    }
783
784    fn check(&self) -> Result<(), NetError> {
785        /// A timeout over a year is refused (in seconds): `Instant + Duration` panics
786        /// on overflow, and "no limit" is not a limit a peer should be able to hold.
787        const TOO_LONG: ConfigReason = ConfigReason::TooLarge {
788            max: crate::time::LONGEST.as_secs(),
789        };
790        let l = &self.limits;
791        // Zero where zero is meaningless.
792        let zeros: [(&'static str, bool); 6] = [
793            ("max_connections", l.max_connections == Some(0)),
794            ("backlog", l.backlog == Some(0)),
795            ("accept_batch", l.accept_batch == Some(0)),
796            ("max_per_source", matches!(l.max_per_source, Some((0, _)))),
797            ("completion_queue", l.completion_queue == Some(0)),
798            ("output_budget", l.output_budget == Some(0)),
799        ];
800        for (field, zero) in zeros {
801            if zero {
802                return Err(invalid(field, ConfigReason::Zero));
803            }
804        }
805        if let Some(max) = l.max_connections {
806            if l.max_per_listener.is_some_and(|n| n > max) {
807                return Err(invalid("max_per_listener", ConfigReason::AboveGlobal));
808            }
809            if l.max_per_source.is_some_and(|(n, _)| n > max) {
810                return Err(invalid("max_per_source", ConfigReason::AboveGlobal));
811            }
812        }
813        if let Some(tick) = l.tick {
814            if tick < Duration::from_millis(1) {
815                return Err(invalid("tick", ConfigReason::TooSmall { min: 1 }));
816            }
817            if tick > Duration::from_millis(100) {
818                return Err(invalid("tick", ConfigReason::TooLarge { max: 100 }));
819            }
820        }
821        let tick = l.tick.unwrap_or(Duration::from_millis(1));
822        let timeouts: [(&'static str, Option<Duration>); 6] = [
823            ("handshake_timeout", l.handshake_timeout),
824            ("idle_timeout", l.idle_timeout),
825            ("read_timeout", l.read_timeout),
826            ("write_timeout", l.write_timeout),
827            ("park_timeout", l.park_timeout),
828            ("drain_timeout", l.drain_timeout),
829        ];
830        for (field, value) in timeouts {
831            if value.is_some_and(|d| d < tick) {
832                return Err(invalid(field, ConfigReason::BelowTick));
833            }
834            if value.is_some_and(|d| d > crate::time::LONGEST) {
835                return Err(invalid(field, TOO_LONG));
836            }
837        }
838        let long = |d: Duration| d > crate::time::LONGEST;
839        if l.min_rate
840            .is_some_and(|r| long(r.grace) || long(r.window) || long(r.check))
841        {
842            return Err(invalid("min_rate", TOO_LONG));
843        }
844        if l.graceful_linger.is_some_and(|(d, _)| long(d)) {
845            return Err(invalid("graceful_linger", TOO_LONG));
846        }
847        if l.max_connections.is_some_and(|n| n > MAX_CONNECTIONS) {
848            return Err(invalid(
849                "max_connections",
850                ConfigReason::TooLarge {
851                    max: u64::from(MAX_CONNECTIONS),
852                },
853            ));
854        }
855        if let Some(rate) = l.min_rate {
856            if !rate.is_off() {
857                if rate.check.is_zero() || rate.grace.is_zero() {
858                    return Err(invalid("min_rate", ConfigReason::Zero));
859                }
860                if rate.window < rate.check {
861                    return Err(invalid("min_rate", ConfigReason::WindowBelowCheck));
862                }
863            }
864        }
865        if let Some((initial, max)) = l.read_class {
866            if max < initial {
867                return Err(invalid("read_class", ConfigReason::Inconsistent));
868            }
869        }
870        if l.refusal_bytes_max.is_some_and(|n| n > 512) {
871            return Err(invalid(
872                "refusal_bytes_max",
873                ConfigReason::TooLarge { max: 512 },
874            ));
875        }
876        if l.proxy_header_max.is_some_and(|n| n > 65_519) {
877            return Err(invalid(
878                "proxy_header_max",
879                ConfigReason::TooLarge { max: 65_519 },
880            ));
881        }
882        if l.completion_queue.is_some_and(|n| n > 1 << 20) {
883            return Err(invalid(
884                "completion_queue",
885                ConfigReason::TooLarge { max: 1 << 20 },
886            ));
887        }
888        if let Some(p) = l.pressure {
889            let factor_ok = p.factor > 0.0 && p.factor <= 1.0;
890            let ordered = p.high.partial_cmp(&p.low) == Some(std::cmp::Ordering::Greater);
891            if !ordered
892                || !factor_ok
893                || !(0.0..=1.0).contains(&p.high)
894                || !(0.0..=1.0).contains(&p.low)
895            {
896                return Err(invalid("pressure", ConfigReason::Inconsistent));
897            }
898        }
899        if self.bad_lane {
900            return Err(invalid("lane_reserve", ConfigReason::TooLarge { max: 7 }));
901        }
902        let reserved: u64 = l.lane_reserve.iter().flatten().map(|n| u64::from(*n)).sum();
903        if let Some(max) = l.max_connections {
904            if reserved > u64::from(max) {
905                return Err(invalid("lane_reserve", ConfigReason::AboveGlobal));
906            }
907        }
908        Ok(())
909    }
910}
911
912/// The process's open-descriptor limit (`RLIMIT_NOFILE`, soft) on Unix: what
913/// `ServerBuilder::build` checks a global cap against. `None` where it is unlimited,
914/// and on Windows, where socket handles do not come from a small table. Use it to
915/// place a soft cap of your own under the one net-io would pick.
916///
917/// ```
918/// let cap = net_io::descriptor_limit().map_or(10_000, |n| n.saturating_sub(64));
919/// assert!(cap > 0);
920/// ```
921#[must_use]
922pub fn descriptor_limit() -> Option<u64> {
923    crate::sys::descriptor_limit()
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929
930    #[test]
931    fn test_unset_values_take_driver_defaults() {
932        let l = Limits::builder().build().unwrap();
933        assert_eq!(
934            l.effective(DriverKind::Blocking).idle_timeout,
935            Duration::from_secs(5)
936        );
937        assert_eq!(
938            l.effective(DriverKind::Reactor).idle_timeout,
939            Duration::from_secs(60)
940        );
941    }
942
943    #[test]
944    fn test_dependent_defaults_follow_max_connections() {
945        let l = Limits::builder().max_connections(10).build().unwrap();
946        let e = l.effective(DriverKind::Reactor);
947        assert_eq!(e.max_per_listener, 10);
948        assert_eq!(e.max_per_source, 10);
949    }
950
951    #[test]
952    fn test_zero_values_rejected() {
953        for b in [
954            Limits::builder().max_connections(0),
955            Limits::builder().backlog(0),
956            Limits::builder().accept_batch(0),
957            Limits::builder().max_per_source(0, PrefixPolicy::DEFAULT),
958            Limits::builder().completion_queue(0),
959            Limits::builder().output_budget(0),
960        ] {
961            assert!(matches!(
962                b.build(),
963                Err(NetError::InvalidConfig {
964                    reason: ConfigReason::Zero,
965                    ..
966                })
967            ));
968        }
969    }
970
971    #[test]
972    fn test_timeout_below_tick_rejected() {
973        let err = Limits::builder()
974            .tick(Duration::from_millis(100))
975            .read_timeout(Duration::from_millis(50))
976            .build()
977            .unwrap_err();
978        assert!(matches!(
979            err,
980            NetError::InvalidConfig {
981                field: "read_timeout",
982                reason: ConfigReason::BelowTick
983            }
984        ));
985    }
986
987    /// "No limit" spelled `Duration::MAX` is refused at build instead of panicking
988    /// on the first deadline (review finding).
989    #[test]
990    fn test_timeouts_over_a_year_and_huge_caps_rejected() {
991        for field in ["idle_timeout", "read_timeout", "drain_timeout"] {
992            let b = Limits::builder();
993            let b = match field {
994                "idle_timeout" => b.idle_timeout(Duration::MAX),
995                "read_timeout" => b.read_timeout(Duration::from_secs(400 * 86_400)),
996                _ => b.drain_timeout(Duration::MAX),
997            };
998            let err = b.build().unwrap_err();
999            assert!(
1000                matches!(err, NetError::InvalidConfig { field: f, reason: ConfigReason::TooLarge { .. } } if f == field),
1001                "{err:?}"
1002            );
1003        }
1004        assert!(
1005            Limits::builder()
1006                .idle_timeout(Duration::from_secs(365 * 86_400))
1007                .build()
1008                .is_ok()
1009        );
1010        let err = Limits::builder()
1011            .max_connections(u32::MAX)
1012            .build()
1013            .unwrap_err();
1014        assert!(matches!(
1015            err,
1016            NetError::InvalidConfig {
1017                field: "max_connections",
1018                reason: ConfigReason::TooLarge { .. }
1019            }
1020        ));
1021    }
1022
1023    #[test]
1024    fn test_min_rate_window_below_check_rejected() {
1025        let rate = MinRate {
1026            bytes_per_sec: 10,
1027            window: Duration::from_millis(500),
1028            grace: Duration::from_secs(1),
1029            check: Duration::from_secs(1),
1030        };
1031        assert!(matches!(
1032            Limits::builder().min_rate(rate).build(),
1033            Err(NetError::InvalidConfig {
1034                reason: ConfigReason::WindowBelowCheck,
1035                ..
1036            })
1037        ));
1038        assert!(Limits::builder().min_rate(MinRate::off()).build().is_ok());
1039    }
1040
1041    #[test]
1042    fn test_bounds_too_large() {
1043        assert!(Limits::builder().refusal_bytes_max(513).build().is_err());
1044        assert!(Limits::builder().refusal_bytes_max(512).build().is_ok());
1045        assert!(Limits::builder().proxy_header_max(65_520).build().is_err());
1046        assert!(
1047            Limits::builder()
1048                .completion_queue((1 << 20) + 1)
1049                .build()
1050                .is_err()
1051        );
1052    }
1053
1054    #[test]
1055    fn test_completion_queue_rounded_to_power_of_two() {
1056        let l = Limits::builder().completion_queue(1000).build().unwrap();
1057        assert_eq!(l.completion_queue(), Some(1024));
1058    }
1059
1060    #[test]
1061    fn test_pressure_and_lane_reserve_validation() {
1062        let bad = Pressure {
1063            high: 0.5,
1064            low: 0.6,
1065            factor: 0.5,
1066        };
1067        assert!(Limits::builder().pressure(bad).build().is_err());
1068        assert!(Limits::builder().lane_reserve(Lane(8), 1).build().is_err());
1069        // A later valid lane 7 does not hide the invalid one (review finding).
1070        assert!(
1071            Limits::builder()
1072                .lane_reserve(Lane(8), 1)
1073                .lane_reserve(Lane(7), 1)
1074                .build()
1075                .is_err()
1076        );
1077        assert!(
1078            Limits::builder()
1079                .max_connections(10)
1080                .lane_reserve(Lane(0), 6)
1081                .lane_reserve(Lane(1), 5)
1082                .build()
1083                .is_err()
1084        );
1085    }
1086
1087    #[test]
1088    fn test_validate_descriptor_limit_and_budget() {
1089        let l = Limits::builder().max_connections(1000).build().unwrap();
1090        assert!(matches!(
1091            l.validate(4, Some(500)),
1092            Err(NetError::InvalidConfig {
1093                reason: ConfigReason::DescriptorLimit { have: 500, .. },
1094                ..
1095            })
1096        ));
1097        assert!(l.validate(4, Some(100_000)).is_ok());
1098        let small = Limits::builder().buffer_budget(1024).build().unwrap();
1099        assert!(matches!(
1100            small.validate(4, None),
1101            Err(NetError::InvalidConfig {
1102                reason: ConfigReason::BudgetBelowWorkers { .. },
1103                ..
1104            })
1105        ));
1106    }
1107
1108    #[test]
1109    fn test_overlay_takes_listener_values() {
1110        let base = Limits::builder()
1111            .max_connections(100)
1112            .idle_timeout(Duration::from_secs(9))
1113            .build()
1114            .unwrap();
1115        let over = Limits::builder()
1116            .idle_timeout(Duration::from_secs(1))
1117            .build()
1118            .unwrap();
1119        let merged = base.overlay(&over);
1120        assert_eq!(merged.max_connections(), Some(100));
1121        assert_eq!(merged.idle_timeout(), Some(Duration::from_secs(1)));
1122    }
1123
1124    #[test]
1125    fn test_resolve_sets_every_value() {
1126        let r = Limits::default().resolve(DriverKind::Blocking);
1127        assert!(
1128            r.max_connections().is_some() && r.tick().is_some() && r.graceful_linger().is_some()
1129        );
1130    }
1131}