Skip to main content

ntex_io/
cfg.rs

1//! I/O buffer, timeout, and frame-rate configuration.
2
3use std::sync::Arc;
4
5use ntex_bytes::BytePageSize;
6#[cfg(feature = "tracker")]
7use ntex_bytes::BytesTracker;
8use ntex_service::cfg::{CfgContext, Configuration};
9use ntex_util::{time::Millis, time::Seconds};
10
11use crate::{IoMetrics, IoMetricsGroup};
12
13#[derive(Debug)]
14/// Shared configuration for an [`crate::Io`] stream.
15pub struct IoConfig {
16    connect_timeout: Millis,
17    keepalive_timeout: Seconds,
18    shutdown_timeout: Seconds,
19    frame_read_rate: Option<FrameReadRate>,
20    write_timeout: Seconds,
21
22    // read side configuration
23    read_size_min: BytePageSize,
24    read_size_max: BytePageSize,
25    read_backpressure: usize,
26    #[cfg(feature = "tracker")]
27    buf_tracker: BufTracker,
28
29    // write side configuration
30    write_size: BytePageSize,
31    write_backpressure: usize,
32    write_buf_threshold: usize,
33
34    metrics: bool,
35
36    // shared config
37    pub(crate) config: CfgContext,
38}
39
40impl Default for IoConfig {
41    fn default() -> Self {
42        IoConfig::new()
43    }
44}
45
46impl Configuration for IoConfig {
47    const NAME: &str = "IO Configuration";
48
49    fn ctx(&self) -> &CfgContext {
50        &self.config
51    }
52
53    fn set_ctx(&mut self, ctx: CfgContext) {
54        self.config = ctx;
55    }
56}
57
58/// Minimum read rate required while decoding one frame.
59#[derive(Copy, Clone, Debug)]
60pub struct FrameReadRate {
61    /// Initial read timeout.
62    pub timeout: Seconds,
63    /// Maximum cumulative timeout for the frame.
64    pub max_timeout: Seconds,
65    /// Byte-progress threshold that must be exceeded to extend the deadline.
66    ///
67    /// Progress must be strictly greater than this value for another `timeout`
68    /// period to be granted.
69    pub rate: u32,
70}
71
72/// Memory attribution of read buffers, see
73/// [`IoConfig::set_buf_tracker`].
74#[cfg(feature = "tracker")]
75#[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
76#[derive(Clone, Debug, Default)]
77#[non_exhaustive]
78pub enum BufTracker {
79    /// Read buffers are not attributed.
80    #[default]
81    Disabled,
82    /// Each connection charges its read buffers to its own tracker.
83    PerConnection,
84    /// All connections of the configuration charge their read buffers to
85    /// the same tracker.
86    Shared(BytesTracker),
87}
88
89impl IoConfig {
90    /// Returns the metrics connections created with this configuration on
91    /// the current thread report to.
92    ///
93    /// These are the configuration's own metrics if it has metrics enabled or
94    /// is registered in the thread's group, and the group's shared `other`
95    /// metrics otherwise, see [`IoMetricsGroup`].
96    pub fn metrics(&self) -> Arc<IoMetrics> {
97        IoMetricsGroup::current_metrics(self)
98    }
99
100    #[inline]
101    /// Returns `true` if the configuration has its own metrics, see
102    /// [`set_metrics`](Self::set_metrics).
103    pub fn metrics_enabled(&self) -> bool {
104        self.metrics
105    }
106
107    #[must_use]
108    /// Gives connections of this configuration their own metrics.
109    ///
110    /// By default connections report to the shared `other` metrics of the
111    /// thread's [`IoMetricsGroup`], unless the configuration is registered
112    /// with [`IoMetricsGroup::register`], as server listener configurations
113    /// are. Each enabled configuration keeps its metrics on every thread it is
114    /// used on, do not enable metrics for short-lived configurations.
115    ///
116    /// I/O metrics are always collected. Disabling only removes the
117    /// configuration's own metrics, its connections then report to the shared
118    /// `other` metrics, or to the registered metrics of a server listener
119    /// configuration.
120    pub fn set_metrics(mut self, enabled: bool) -> Self {
121        self.metrics = enabled;
122        self
123    }
124
125    #[inline]
126    #[must_use]
127    /// Creates an I/O configuration with default settings.
128    pub fn new() -> IoConfig {
129        IoConfig {
130            config: CfgContext::default(),
131            connect_timeout: Millis::ZERO,
132            keepalive_timeout: Seconds(0),
133            shutdown_timeout: Seconds(1),
134            frame_read_rate: None,
135
136            read_size_min: BytePageSize::Size4,
137            read_size_max: BytePageSize::Size64,
138            read_backpressure: BytePageSize::Size32.capacity(),
139            #[cfg(feature = "tracker")]
140            buf_tracker: BufTracker::Disabled,
141
142            write_timeout: Seconds(0),
143            write_size: BytePageSize::Size16,
144            write_backpressure: BytePageSize::Size64.capacity(),
145            write_buf_threshold: BytePageSize::Size16.half_capacity(),
146            metrics: false,
147        }
148    }
149
150    #[inline]
151    /// Returns the shared configuration tag.
152    pub fn tag(&self) -> &str {
153        self.config.tag()
154    }
155
156    #[inline]
157    /// Returns the connection timeout.
158    pub fn connect_timeout(&self) -> Millis {
159        self.connect_timeout
160    }
161
162    #[inline]
163    /// Returns the keep-alive timeout.
164    pub fn keepalive_timeout(&self) -> Seconds {
165        self.keepalive_timeout
166    }
167
168    #[inline]
169    /// Returns the graceful shutdown timeout.
170    pub fn shutdown_timeout(&self) -> Seconds {
171        self.shutdown_timeout
172    }
173
174    #[inline]
175    /// Returns the frame read-rate configuration.
176    pub fn frame_read_rate(&self) -> Option<&FrameReadRate> {
177        self.frame_read_rate.as_ref()
178    }
179
180    #[inline]
181    /// Returns the smallest page size of read buffers.
182    ///
183    /// Connections start reading into pages of this size, see
184    /// [`set_read_size`](Self::set_read_size).
185    pub fn read_size_min(&self) -> BytePageSize {
186        self.read_size_min
187    }
188
189    #[inline]
190    /// Returns the largest page size of read buffers.
191    ///
192    /// The read page size of a connection adapts to its input up to this
193    /// size, see [`set_read_size`](Self::set_read_size).
194    pub fn read_size_max(&self) -> BytePageSize {
195        self.read_size_max
196    }
197
198    #[inline]
199    /// Returns the read backpressure high watermark.
200    ///
201    /// Read backpressure is enabled once buffered input reaches it and
202    /// released once it falls to half of it, see
203    /// [`set_read_backpressure`](Self::set_read_backpressure).
204    pub fn read_backpressure(&self) -> usize {
205        self.read_backpressure
206    }
207
208    #[inline]
209    #[cfg(feature = "tracker")]
210    #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
211    /// Returns the read buffer attribution, see
212    /// [`set_buf_tracker`](Self::set_buf_tracker).
213    pub fn buf_tracker(&self) -> &BufTracker {
214        &self.buf_tracker
215    }
216
217    #[inline]
218    /// Returns the write backpressure timeout.
219    ///
220    /// A zero value means the timeout is disabled.
221    pub fn write_timeout(&self) -> Seconds {
222        self.write_timeout
223    }
224
225    #[inline]
226    /// Returns the write backpressure high watermark.
227    ///
228    /// Write backpressure is released once outstanding output falls to half of
229    /// it, see [`set_write_backpressure`](Self::set_write_backpressure).
230    pub fn write_backpressure(&self) -> usize {
231        self.write_backpressure
232    }
233
234    #[inline]
235    /// Buffered input size that releases read backpressure.
236    pub(crate) fn read_half(&self) -> usize {
237        self.read_backpressure >> 1
238    }
239
240    #[inline]
241    /// Outstanding output size that releases write backpressure.
242    pub(crate) fn write_half(&self) -> usize {
243        self.write_backpressure >> 1
244    }
245
246    #[inline]
247    /// Returns the write-buffer page size.
248    pub fn write_size(&self) -> BytePageSize {
249        self.write_size
250    }
251
252    #[inline]
253    /// Returns the buffered write size that triggers an earlier send.
254    pub fn write_buf_threshold(&self) -> usize {
255        self.write_buf_threshold
256    }
257
258    /// Sets the connection timeout.
259    ///
260    /// A zero duration disables the timeout. It is disabled by default.
261    #[must_use]
262    pub fn set_connect_timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
263        self.connect_timeout = timeout.into();
264        self
265    }
266
267    /// Sets the keep-alive timeout.
268    ///
269    /// The dispatcher runs the timer only while the connection is idle: no
270    /// input is buffered, no partial frame is being read, and no decoded
271    /// frames are being handled. It starts when the dispatcher enters this
272    /// idle state, including after all decoded frames have been handled.
273    /// Partial frames are bounded by
274    /// [frame read-rate](Self::set_frame_read_rate) limits instead, and write
275    /// backpressure by the [write timeout](Self::set_write_timeout).
276    ///
277    /// A zero duration disables the timeout. It is disabled by default.
278    /// `ntex-dispatcher`'s `Dispatcher::keepalive_timeout()` overrides it for
279    /// one dispatcher.
280    #[must_use]
281    pub fn set_keepalive_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
282        self.keepalive_timeout = timeout.into();
283        self
284    }
285
286    /// Sets the graceful shutdown timeout.
287    ///
288    /// A graceful shutdown runs in two phases, and this single timeout bounds
289    /// them together rather than applying to each one:
290    ///
291    /// 1. **Filter shutdown.** Both directions stay open, so a filter can emit
292    ///    its closing data and still read the peer's. A TLS filter sends its
293    ///    `close_notify` here, and a WebSocket filter its close frame.
294    /// 2. **Transport shutdown.** The remaining output is drained to the peer.
295    ///    The read side is paused, and whatever the peer still sent is
296    ///    discarded, then the connection is closed.
297    ///
298    /// The deadline is armed when the first phase begins and is not restarted
299    /// for the second, so a filter that shuts down slowly leaves less time to
300    /// drain. Expiry in the first phase moves on to the second rather than
301    /// giving up; only expiry in the second terminates the connection, and
302    /// output that has not reached the transport is then lost. Either way
303    /// [`crate::Io::shutdown`] reports a timed-out error once the transport
304    /// has stopped.
305    ///
306    /// The timeout also applies when no application output is pending: a
307    /// filter may still be waiting for the peer to complete its shutdown
308    /// exchange. If both phases can finish immediately, the deadline has no
309    /// observable effect.
310    ///
311    /// The default is one second.
312    ///
313    /// # Panics
314    ///
315    /// Panics if `timeout` is zero. Without a deadline, a peer that never
316    /// completes the exchange, or never reads the remaining output, could
317    /// hold the connection open forever.
318    #[must_use]
319    pub fn set_shutdown_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
320        let timeout = timeout.into();
321        assert!(
322            timeout.non_zero(),
323            "shutdown timeout must be greater than zero"
324        );
325        self.shutdown_timeout = timeout;
326        self
327    }
328
329    /// Sets read-rate parameters for a single decoded frame.
330    ///
331    /// Rate tracking starts when a new connection arrives, for its first
332    /// frame, and later whenever a decoder returns no complete item after
333    /// receiving partial frame data, whether the data is left in the read
334    /// buffer or consumed into the decoder's own state. The dispatcher then
335    /// allows one `timeout` period for additional data to arrive.
336    ///
337    /// When that period expires, the dispatcher compares the bytes received
338    /// for the frame since the previous check with `rate`:
339    ///
340    /// - If the progress is greater than `rate`, the deadline is extended by
341    ///   another `timeout` period.
342    /// - If the progress is at most `rate`, frame decoding fails with a read
343    ///   timeout.
344    /// - Completing the frame clears the timer and resets rate tracking for the
345    ///   next frame.
346    ///
347    /// `max_timeout` limits the cumulative time allowed for one frame. A zero
348    /// value permits an unlimited number of extensions while the required rate
349    /// is maintained. A non-zero value is enforced in whole `timeout` periods,
350    /// so the effective limit is rounded up to a multiple of `timeout` and is
351    /// never shorter than the initial period.
352    ///
353    /// A zero `timeout` disables frame read-rate enforcement and ignores
354    /// `max_timeout` and `rate`. With a non-zero timeout and `rate` set to zero,
355    /// any positive byte progress permits another period.
356    ///
357    /// A new connection must therefore deliver its first frame within these
358    /// limits, unless the dispatcher is built with `ntex-dispatcher`'s
359    /// `Dispatcher::skip_first_frame_timeout()`. After a frame has been
360    /// decoded, idle connections with no partial frame are governed separately
361    /// by [`set_keepalive_timeout`](Self::set_keepalive_timeout).
362    ///
363    /// The timer is stopped while write backpressure is active, when frames
364    /// are not decoded, and a new period starts once decoding resumes. While
365    /// the service is not ready the timer is stopped as well, and tracking
366    /// restarts with a fresh period and `max_timeout` budget once the service
367    /// is ready.
368    ///
369    /// Frame read-rate enforcement is disabled by default.
370    #[must_use]
371    pub fn set_frame_read_rate(
372        mut self,
373        timeout: Seconds,
374        max_timeout: Seconds,
375        rate: u32,
376    ) -> Self {
377        self.frame_read_rate = if timeout.is_zero() {
378            None
379        } else {
380            Some(FrameReadRate {
381                timeout,
382                max_timeout,
383                rate,
384            })
385        };
386        self
387    }
388
389    /// Sets the write backpressure timeout.
390    ///
391    /// Write backpressure is enabled when outstanding output reaches the
392    /// [write buffer](Self::set_write_backpressure) high watermark and disabled once the
393    /// peer has accepted enough of it. The timeout covers that whole period:
394    /// if backpressure is still enabled when it expires, the dispatcher stops
395    /// with a write timeout. Each backpressure period starts a fresh timeout,
396    /// however much the peer read during the previous one. Without a write
397    /// timeout, a peer that stops reading during backpressure can hold the
398    /// connection open indefinitely.
399    ///
400    /// The timeout does not apply once backpressure is disabled, even though
401    /// output is still outstanding. A peer that stops reading at that point
402    /// can leave up to half of the high watermark unwritten; only the
403    /// [keep-alive timeout](Self::set_keepalive_timeout), when enabled, bounds
404    /// such a connection until it is shut down.
405    ///
406    /// Reads paused because output produced by reading, for example replies
407    /// to peer pings, has not drained are not covered either. While the
408    /// dispatcher is idle, the keep-alive timeout bounds them. Application
409    /// output written during such a pause enables write backpressure.
410    ///
411    /// Outside the dispatcher, the timeout also bounds each wait for output in
412    /// [`Io::send`](crate::Io::send), [`Io::flush`](crate::Io::flush) and
413    /// [`IoRef::write_ready`](crate::IoRef::write_ready). A wait that does not
414    /// complete in time fails with [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut),
415    /// and the connection is left open for the caller to close. The polling
416    /// methods, such as [`Io::poll_flush`](crate::Io::poll_flush), are not
417    /// bounded.
418    ///
419    /// A zero duration disables the timeout. It is disabled by default, so
420    /// a peer that does not read can pin the connection and its buffered
421    /// output. Servers that accept untrusted peers should set it.
422    #[must_use]
423    pub fn set_write_timeout(mut self, timeout: Seconds) -> Self {
424        self.write_timeout = timeout;
425        self
426    }
427
428    /// Sets the range of read-buffer page sizes.
429    ///
430    /// Each connection reads into pages of its own page size, which starts at
431    /// `min` and adapts to the connection's input between `min` and `max`.
432    /// Input that arrives in batches larger than the page capacity, such as
433    /// streamed bodies or large frames, grows the page size of the next read
434    /// buffers to fit a batch, so it is read with fewer and larger transport
435    /// reads. After several batches in a row that would fit in half of the
436    /// next smaller page size, the page size shrinks by one step. Connections
437    /// with small messages keep small pages, which also bounds the memory a
438    /// partial frame or a split-off frame holds.
439    ///
440    /// Within a batch a buffer grows with [`BytesMut::reserve_more`](ntex_bytes::BytesMut::reserve_more) once less
441    /// than [`BytePageSize::low`] of its page size remains: the data is
442    /// compacted within its page when that leaves room for half a page,
443    /// otherwise the buffer moves to the next page size.
444    ///
445    /// The page size does not depend on the read backpressure watermark, see
446    /// [`set_read_backpressure`](Self::set_read_backpressure). A single read
447    /// can fill a page larger than the watermark, reads are paused only after
448    /// the buffered input reaches it.
449    ///
450    /// Read buffers come from the per-thread page cache of `ntex-bytes`,
451    /// shared with write buffers and all configurations, see
452    /// [`ntex_bytes::set_page_cache_size`]. A buffer returns to the cache of
453    /// the thread that drops its last reference. Buffers grown beyond the
454    /// largest page size are freed. A connection holding
455    /// unconsumed input, such as the start of a frame that has not fully
456    /// arrived, keeps its whole read buffer, so each such connection uses at
457    /// least one page until the rest arrives. Read-rate timeouts,
458    /// see [`set_frame_read_rate`](Self::set_frame_read_rate), bound how long
459    /// a slow peer can hold it.
460    ///
461    /// Frames that a codec splits off the read buffer, such as `Bytes`
462    /// payloads, share its allocation. A frame kept alive keeps the whole
463    /// read buffer allocated, it returns to the cache only once the last such
464    /// frame is dropped, so retaining many small frames can use far more
465    /// memory than their size.
466    /// Copy long-lived frames or call [`Bytes::trimdown`](ntex_bytes::Bytes::trimdown)
467    /// on them to release the rest of the buffer.
468    ///
469    /// Set `min` and `max` to the same size to read into pages of a fixed
470    /// size. The default range is 4 KiB to 64 KiB.
471    ///
472    /// # Panics
473    ///
474    /// Panics if `min` or `max` is [`BytePageSize::Unset`], or `min` is
475    /// larger than `max`.
476    #[must_use]
477    pub fn set_read_size(mut self, min: BytePageSize, max: BytePageSize) -> Self {
478        assert!(
479            min != BytePageSize::Unset && max != BytePageSize::Unset,
480            "read buffer page size must be set"
481        );
482        assert!(
483            min.capacity() <= max.capacity(),
484            "read buffer min page size must not be larger than max"
485        );
486        self.read_size_min = min;
487        self.read_size_max = max;
488        self
489    }
490
491    /// Sets the read backpressure watermark.
492    ///
493    /// Read backpressure is enabled when the application-facing read buffer
494    /// reaches `size` bytes and released once it falls to half of it. It does
495    /// not affect the read page size, see [`set_read_size`](Self::set_read_size).
496    ///
497    /// The default watermark is the capacity of a 32 KiB page.
498    ///
499    /// # Panics
500    ///
501    /// Panics if `size` is zero.
502    #[must_use]
503    pub fn set_read_backpressure(mut self, size: usize) -> Self {
504        assert!(size > 0, "read backpressure must be greater than zero");
505        self.read_backpressure = size;
506        self
507    }
508
509    /// Sets the memory attribution of read buffers.
510    ///
511    /// Read buffers of connections are charged to a
512    /// [`BytesTracker`], which reports the live allocations and bytes.
513    /// [`BufTracker::PerConnection`] gives each connection its own
514    /// tracker, [`BufTracker::Shared`] charges all connections of the
515    /// configuration to one tracker. Write buffers are not attributed.
516    ///
517    /// A read buffer stays charged until its last handle is dropped,
518    /// including `Bytes` frames split off it, on any thread and after the
519    /// connection is closed. The charge is the allocation size, header
520    /// included. Buffers in the page cache are not charged, io-uring
521    /// provided-buffer pages are charged once data is received into them.
522    /// Data copied out of a read buffer is not charged, such as small frames
523    /// stored inline or the result of
524    /// [`Bytes::trimdown`](ntex_bytes::Bytes::trimdown). A tracker does not
525    /// keep the connection alive.
526    ///
527    /// A shared tracker is an atomic counter updated by every connection on
528    /// every worker thread, it is contended under load.
529    ///
530    /// The default is [`BufTracker::Disabled`].
531    #[must_use]
532    #[cfg(feature = "tracker")]
533    #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
534    pub fn set_buf_tracker(mut self, tracker: BufTracker) -> Self {
535        self.buf_tracker = tracker;
536        self
537    }
538
539    /// Sets the write-buffer page size.
540    ///
541    /// Write buffers are represented as a sequence of reusable byte pages.
542    /// `size` selects the capacity category used when those buffers allocate
543    /// new internal pages, including the intermediate write buffers created
544    /// between filter layers. [`BytePages`](ntex_bytes::BytePages) may also
545    /// contain externally supplied [`BytePage`](ntex_bytes::BytePage),
546    /// [`Bytes`](ntex_bytes::Bytes), or `Vec<u8>` segments; this setting does
547    /// not resize or copy those segments.
548    ///
549    /// Smaller pages reduce unused capacity for connections that usually
550    /// produce small writes. Larger pages can reduce allocation and page-list
551    /// overhead for connections that regularly buffer larger writes. This
552    /// setting does not limit the total amount of buffered data or determine
553    /// the size of individual transport write operations.
554    ///
555    /// Changing the page size on an active connection through
556    /// [`Io::set_config`](crate::Io::set_config) updates the allocation
557    /// category for future pages in every existing write buffer. Pages that
558    /// have already been allocated retain their current capacity. Filter
559    /// layers added later use the new page size.
560    ///
561    /// The page size is independent of the eager-write threshold and write
562    /// backpressure watermarks. Changing it does not update values configured
563    /// by [`set_write_buf_threshold`](Self::set_write_buf_threshold) or
564    /// [`set_write_backpressure`](Self::set_write_backpressure).
565    ///
566    /// The default page size is 16 KiB.
567    ///
568    /// # Panics
569    ///
570    /// Panics if `size` is [`BytePageSize::Unset`].
571    #[must_use]
572    pub fn set_write_size(mut self, size: BytePageSize) -> Self {
573        assert!(
574            size != BytePageSize::Unset,
575            "write buffer page size must be set"
576        );
577        self.write_size = size;
578        self
579    }
580
581    /// Sets the write buffer threshold.
582    ///
583    /// Application code can encode multiple items during one dispatcher turn.
584    /// Normally, the transport write task is scheduled to run after that work
585    /// yields, so all items produced during the turn may accumulate in the
586    /// write buffer and be sent as one large burst.
587    ///
588    /// When the buffered size reaches `size` while the transport write task is
589    /// paused, `Io` asks the transport handle to start writing immediately.
590    /// This eager write attempt occurs synchronously with buffer consolidation,
591    /// before the current application or dispatcher turn necessarily
592    /// completes. If bytes remain afterward, the normal write task is
593    /// scheduled to continue delivery. Data below the threshold is delivered
594    /// through that normal scheduled path.
595    ///
596    /// The threshold is a latency and write-burst tuning parameter. It does not
597    /// limit write-buffer growth, provide a flush guarantee, or control write
598    /// backpressure; use [`set_write_backpressure`](Self::set_write_backpressure) for
599    /// backpressure watermarks and [`Io::flush`](crate::Io::flush) when a
600    /// caller must wait for buffered data to be written.
601    ///
602    /// Set `size` to zero to disable eager writes when this configuration is
603    /// used to construct an [`Io`](crate::Io). The default is 8 KiB, derived
604    /// from the default 16 KiB page size when [`IoConfig::new`] is called.
605    /// Changing the page size later does not recalculate this threshold.
606    ///
607    /// Replacing an active connection's configuration with
608    /// [`Io::set_config`](crate::Io::set_config) enables or disables eager
609    /// writes according to the replacement threshold.
610    ///
611    /// Eager writes depend on the transport. The io-uring transport ignores
612    /// the threshold: it delivers buffered output through the scheduled write
613    /// operation, and the sends of all connections are submitted together
614    /// once per runtime turn.
615    ///
616    /// [`IoMetricsSnapshot`](crate::IoMetricsSnapshot) counts eager, partial
617    /// eager and scheduled writes for tuning the threshold.
618    #[must_use]
619    pub fn set_write_buf_threshold(mut self, size: usize) -> Self {
620        self.write_buf_threshold = size;
621        self
622    }
623
624    /// Sets the write-buffer backpressure watermark.
625    ///
626    /// Write backpressure is enabled at `size` bytes of outstanding output and
627    /// must be greater than zero. Backpressure is released after the
628    /// outstanding size falls to half of this value. Outstanding output is the
629    /// buffered output plus any output a transport has taken ownership of but
630    /// not yet written to the peer.
631    ///
632    /// Output is held in [`BytePages`](ntex_bytes::BytePages), which are sized
633    /// by [`set_write_size`](Self::set_write_size).
634    ///
635    /// The default high watermark is 64 KiB.
636    ///
637    /// # Panics
638    ///
639    /// Panics if `size` is zero.
640    #[must_use]
641    pub fn set_write_backpressure(mut self, size: usize) -> Self {
642        assert!(size > 0, "write backpressure must be greater than zero");
643        self.write_backpressure = size;
644        self
645    }
646}
647
648#[cfg(test)]
649mod tests {
650    use ntex_service::cfg::SharedCfg;
651
652    use super::*;
653
654    /// STATEMENT: Buffer backpressure settings determine their half-watermarks.
655    ///
656    /// HOW:
657    /// - Set distinct read and write limits and check each limit and its half.
658    #[test]
659    fn buffer_configuration() {
660        let cfg = IoConfig::new()
661            .set_read_backpressure(4096)
662            .set_write_backpressure(2048);
663
664        assert_eq!(cfg.read_backpressure(), 4096);
665        assert_eq!(cfg.read_half(), 2048);
666        assert_eq!(cfg.write_backpressure(), 2048);
667        assert_eq!(cfg.write_half(), 1024);
668    }
669
670    /// STATEMENT: Read page sizes can change independently of backpressure limits.
671    ///
672    /// HOW:
673    /// - Check default sizes and limits, then change page ranges and the write limit.
674    /// - Verify the read watermark stays unchanged and the requested sizes are retained.
675    #[test]
676    fn read_size_configuration() {
677        let default = BytePageSize::Size32.capacity();
678        let cfg = IoConfig::new();
679        assert_eq!(cfg.read_size_min(), BytePageSize::Size4);
680        assert_eq!(cfg.read_size_max(), BytePageSize::Size64);
681        assert_eq!(cfg.read_backpressure(), default);
682        assert_eq!(cfg.read_half(), default / 2);
683        assert_eq!(cfg.write_backpressure(), BytePageSize::Size64.capacity());
684
685        // the read size does not change the backpressure watermark
686        let cfg = cfg
687            .set_read_size(BytePageSize::Size8, BytePageSize::Size8)
688            .set_write_backpressure(2048);
689        assert_eq!(cfg.read_size_min(), BytePageSize::Size8);
690        assert_eq!(cfg.read_size_max(), BytePageSize::Size8);
691        assert_eq!(cfg.read_backpressure(), default);
692        assert_eq!(cfg.write_backpressure(), 2048);
693        assert_eq!(cfg.write_half(), 1024);
694
695        let cfg = cfg.set_read_size(BytePageSize::Size16, BytePageSize::Size256);
696        assert_eq!(cfg.read_size_min(), BytePageSize::Size16);
697        assert_eq!(cfg.read_size_max(), BytePageSize::Size256);
698        assert_eq!(cfg.read_backpressure(), default);
699    }
700
701    /// STATEMENT: Changing read page sizes preserves explicitly configured backpressure.
702    ///
703    /// HOW:
704    /// - Set a 64 KiB read limit, select 4 KiB pages, and check the limit and half-watermark.
705    #[test]
706    fn read_backpressure_configuration() {
707        let cfg = IoConfig::new()
708            .set_read_backpressure(64 * 1024)
709            .set_read_size(BytePageSize::Size4, BytePageSize::Size4);
710        assert_eq!(cfg.read_size_min(), BytePageSize::Size4);
711        assert_eq!(cfg.read_backpressure(), 64 * 1024);
712        assert_eq!(cfg.read_half(), 32 * 1024);
713    }
714
715    /// STATEMENT: An unset maximum read page size is rejected.
716    ///
717    /// HOW:
718    /// - Pass `BytePageSize::Unset` as the maximum and expect the page-size panic.
719    #[test]
720    #[should_panic(expected = "read buffer page size must be set")]
721    fn unset_read_size() {
722        let _ = IoConfig::new().set_read_size(BytePageSize::Size4, BytePageSize::Unset);
723    }
724
725    /// STATEMENT: The minimum read page size cannot exceed the maximum.
726    ///
727    /// HOW:
728    /// - Configure a 16 KiB minimum and 8 KiB maximum and expect the range-validation panic.
729    #[test]
730    #[should_panic(expected = "read buffer min page size must not be larger than max")]
731    fn inverted_read_size() {
732        let _ = IoConfig::new().set_read_size(BytePageSize::Size16, BytePageSize::Size8);
733    }
734    /// STATEMENT: An unset write page size is rejected.
735    ///
736    /// HOW:
737    /// - Set the write size to `BytePageSize::Unset` and expect the page-size panic.
738    #[test]
739    #[should_panic(expected = "write buffer page size must be set")]
740    fn unset_write_size() {
741        let _ = IoConfig::new().set_write_size(BytePageSize::Unset);
742    }
743
744    /// STATEMENT: Read backpressure requires a positive watermark.
745    ///
746    /// HOW:
747    /// - Set the read watermark to zero and expect the backpressure-validation panic.
748    #[test]
749    #[should_panic(expected = "read backpressure must be greater than zero")]
750    fn zero_read_backpressure() {
751        let _ = IoConfig::new().set_read_backpressure(0);
752    }
753
754    /// STATEMENT: Frame read-rate settings retain their values and a zero timeout disables them.
755    ///
756    /// HOW:
757    /// - Configure timeouts and a byte rate, check all fields, then disable with `Seconds::ZERO`.
758    #[test]
759    fn frame_read_rate_configuration() {
760        let cfg = IoConfig::new().set_frame_read_rate(Seconds(1), Seconds(3), 128);
761        let rate = cfg.frame_read_rate().unwrap();
762        assert_eq!(rate.timeout, Seconds(1));
763        assert_eq!(rate.max_timeout, Seconds(3));
764        assert_eq!(rate.rate, 128);
765
766        let cfg = cfg.set_frame_read_rate(Seconds::ZERO, Seconds(10), 1024);
767        assert!(cfg.frame_read_rate().is_none());
768    }
769
770    /// STATEMENT: Connection settings and a shared configuration tag remain accessible.
771    ///
772    /// HOW:
773    /// - Check default and overridden timeouts and write size.
774    /// - Put the configuration in `SharedCfg` and verify its tag and keepalive timeout.
775    #[test]
776    fn config_accessors() {
777        let cfg = IoConfig::new();
778        assert_eq!(cfg.connect_timeout(), Millis::ZERO);
779        assert_eq!(cfg.keepalive_timeout(), Seconds(0));
780        assert_eq!(cfg.write_size(), BytePageSize::Size16);
781
782        let cfg = cfg
783            .set_connect_timeout(Millis(500))
784            .set_keepalive_timeout(Seconds(7))
785            .set_write_size(BytePageSize::Size4);
786        assert_eq!(cfg.connect_timeout(), Millis(500));
787        assert_eq!(cfg.keepalive_timeout(), Seconds(7));
788        assert_eq!(cfg.write_size(), BytePageSize::Size4);
789
790        let shared = SharedCfg::new("CFG-TAG").add(cfg).build();
791        let cfg = shared.get::<IoConfig>();
792        assert_eq!(cfg.tag(), "CFG-TAG");
793        assert_eq!(cfg.keepalive_timeout(), Seconds(7));
794    }
795
796    /// STATEMENT: Write timeouts default to disabled and can be enabled and disabled again.
797    ///
798    /// HOW:
799    /// - Check the default, set three seconds, then reset to `Seconds::ZERO`.
800    #[test]
801    fn write_timeout_configuration() {
802        let cfg = IoConfig::new();
803        assert!(cfg.write_timeout().is_zero());
804
805        let cfg = cfg.set_write_timeout(Seconds(3));
806        assert_eq!(cfg.write_timeout(), Seconds(3));
807
808        let cfg = cfg.set_write_timeout(Seconds::ZERO);
809        assert!(cfg.write_timeout().is_zero());
810    }
811
812    /// STATEMENT: Write backpressure requires a positive watermark.
813    ///
814    /// HOW:
815    /// - Set the write watermark to zero and expect the backpressure-validation panic.
816    #[test]
817    #[should_panic(expected = "write backpressure must be greater than zero")]
818    fn zero_write_backpressure() {
819        let _ = IoConfig::new().set_write_backpressure(0);
820    }
821
822    /// STATEMENT: Shutdown timeouts cannot be disabled with a zero duration.
823    ///
824    /// HOW:
825    /// - Set the shutdown timeout to `Seconds::ZERO` and expect the validation panic.
826    #[test]
827    #[should_panic(expected = "shutdown timeout must be greater than zero")]
828    fn zero_shutdown_timeout_is_rejected() {
829        let _ = IoConfig::new().set_shutdown_timeout(Seconds::ZERO);
830    }
831
832    /// STATEMENT: Buffer tracking supports disabled, per-connection, and shared modes.
833    ///
834    /// HOW:
835    /// - Check the default mode, select each enabled mode, and verify shared tracker identity.
836    #[cfg(feature = "tracker")]
837    #[test]
838    fn buf_tracker() {
839        let cfg = IoConfig::new();
840        assert!(matches!(cfg.buf_tracker(), BufTracker::Disabled));
841
842        let cfg = cfg.set_buf_tracker(BufTracker::PerConnection);
843        assert!(matches!(cfg.buf_tracker(), BufTracker::PerConnection));
844
845        let tracker = BytesTracker::new();
846        let cfg = cfg.set_buf_tracker(BufTracker::Shared(tracker.clone()));
847        let BufTracker::Shared(t) = cfg.buf_tracker() else {
848            panic!("expected a shared tracker");
849        };
850        assert!(t.ptr_eq(&tracker));
851    }
852}