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!(/// The global connection cap.
647        max_connections, u32);
648    setter!(/// The per-listener connection cap.
649        max_per_listener, u32);
650    setter!(/// The listen backlog.
651        backlog, u32);
652    setter!(/// Connections accepted per wake-up.
653        accept_batch, u16);
654    setter!(/// Time for the PROXY header and TLS handshake together.
655        handshake_timeout, Duration);
656    setter!(/// Time to wait for the next exchange.
657        idle_timeout, Duration);
658    setter!(/// Time to wait for bytes during an exchange.
659        read_timeout, Duration);
660    setter!(/// Time to wait for the peer to take bytes.
661        write_timeout, Duration);
662    setter!(/// Time a parked connection may wait for its completion.
663        park_timeout, Duration);
664    setter!(/// The minimum transfer rate ([`MinRate::off`] to disable).
665        min_rate, MinRate);
666    setter!(/// Pool memory a connection's output may hold.
667        output_budget, u32);
668    setter!(/// Total bytes of buffers all workers may allocate. A quarter of it, shared
669        /// among the workers, is the most unfinished TLS handshakes may hold on the
670        /// reactor; see [`Limits::buffer_budget`].
671        buffer_budget, u64);
672    setter!(/// The drain deadline.
673        drain_timeout, Duration);
674    setter!(/// The largest refusal reply (at most 512).
675        refusal_bytes_max, u16);
676    setter!(/// The timer resolution (1 ms to 100 ms).
677        tick, Duration);
678    setter!(/// Adaptive deadlines under pressure.
679        pressure, Pressure);
680
681    /// The per-source concurrency cap and how sources are grouped.
682    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    /// The PROXY v2 address-and-TLV cap (up to 65,519).
688    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    /// The initial read buffer class and the largest a session may grow it to.
694    pub fn read_class(mut self, initial: SizeClass, max: SizeClass) -> Self {
695        self.limits.read_class = Some((initial, max));
696        self
697    }
698
699    /// A worker's completion queue length, rounded up to a power of two.
700    pub fn completion_queue(mut self, n: u32) -> Self {
701        self.limits.completion_queue = Some(n);
702        self
703    }
704
705    /// The graceful-close linger: time and bytes read and discarded.
706    pub fn graceful_linger(mut self, time: Duration, bytes: u32) -> Self {
707        self.limits.graceful_linger = Some((time, bytes));
708        self
709    }
710
711    /// Connection slots reserved for `lane` (lanes 0 to 7; applied from `0.6.0`).
712    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            // Rejected by `build` (field "lane_reserve").
716            None => self.bad_lane = true,
717        }
718        self
719    }
720
721    /// Checks the values that were set and returns the limits.
722    ///
723    /// # Errors
724    ///
725    /// `InvalidConfig { field, reason }` for the first rule broken, in the order
726    /// documented in `docs/API.md`.
727    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        /// A timeout over a year is refused (in seconds): `Instant + Duration` panics
738        /// on overflow, and "no limit" is not a limit a peer should be able to hold.
739        const TOO_LONG: ConfigReason = ConfigReason::TooLarge {
740            max: crate::time::LONGEST.as_secs(),
741        };
742        let l = &self.limits;
743        // Zero where zero is meaningless.
744        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/// The process's open-descriptor limit (`RLIMIT_NOFILE`, soft) on Unix: what
865/// `ServerBuilder::build` checks a global cap against. `None` where it is unlimited,
866/// and on Windows, where socket handles do not come from a small table. Use it to
867/// place a soft cap of your own under the one net-io would pick.
868///
869/// ```
870/// let cap = net_io::descriptor_limit().map_or(10_000, |n| n.saturating_sub(64));
871/// assert!(cap > 0);
872/// ```
873#[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    /// "No limit" spelled `Duration::MAX` is refused at build instead of panicking
940    /// on the first deadline (review finding).
941    #[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        // A later valid lane 7 does not hide the invalid one (review finding).
1022        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}