Skip to main content

ntex/http/
config.rs

1use std::{cell::Cell, cell::RefCell, rc::Rc, time};
2
3use crate::http::header::HeaderValue;
4use crate::io::{IoRef, cfg::FrameReadRate};
5use crate::service::cfg::{CfgContext, Configuration};
6use crate::time::{Millis, Seconds, sleep};
7use crate::{channel::oneshot, util::BytePages, util::BytesMut, util::HashSet};
8
9#[derive(Debug, PartialEq, Eq, Clone, Copy)]
10/// Server keep-alive behavior.
11///
12/// A zero timeout always disables persistent connections. Use
13/// [`KeepAlive::Os`] for persistent connections without an idle timeout.
14pub enum KeepAlive {
15    /// Close an idle connection after this timeout.
16    ///
17    /// `Timeout(Seconds::ZERO)` is equivalent to [`KeepAlive::Disabled`].
18    Timeout(Seconds),
19    /// Keep the connection open until the peer or operating system closes it.
20    Os,
21    /// Disable persistent connections.
22    Disabled,
23}
24
25impl KeepAlive {
26    /// Returns the idle timeout and whether persistent connections are enabled.
27    fn state(self) -> (Seconds, bool) {
28        match self {
29            KeepAlive::Timeout(val) if !val.is_zero() => (val, true),
30            KeepAlive::Timeout(_) | KeepAlive::Disabled => (Seconds::ZERO, false),
31            KeepAlive::Os => (Seconds::ZERO, true),
32        }
33    }
34}
35
36/// Converts whole seconds into a timeout.
37///
38/// Values above `u16::MAX` saturate to `u16::MAX` seconds, and zero disables
39/// persistent connections.
40impl From<usize> for KeepAlive {
41    fn from(keepalive: usize) -> Self {
42        KeepAlive::Timeout(Seconds::from(keepalive))
43    }
44}
45
46/// Converts a duration into a timeout; zero disables persistent connections.
47impl From<Seconds> for KeepAlive {
48    fn from(keepalive: Seconds) -> Self {
49        KeepAlive::Timeout(keepalive)
50    }
51}
52
53/// Converts `None` into [`KeepAlive::Disabled`] and `Some` like `usize`.
54impl From<Option<usize>> for KeepAlive {
55    fn from(keepalive: Option<usize>) -> Self {
56        keepalive.map_or(KeepAlive::Disabled, KeepAlive::from)
57    }
58}
59
60#[derive(Debug)]
61#[allow(clippy::struct_excessive_bools)]
62/// Configuration shared by HTTP/1 and HTTP/2 server services.
63///
64/// The default configuration enables persistent HTTP/1 connections with a
65/// five-second idle timeout, allows 96 headers, limits the request or status
66/// line to 16 KiB and the message-head buffer to 64 KiB, applies a
67/// one-second initial request-header timeout and closes HTTP/1 connections
68/// that stay write-backpressured for ten seconds. Request-target validation,
69/// request-target normalization and HTTP/1 Host-header validation are disabled
70/// by default.
71pub struct HttpServiceConfig {
72    pub(super) keep_alive: Seconds,
73    pub(super) ka_enabled: bool,
74    pub(super) headers_vec: bool,
75    pub(super) validate_host: bool,
76    pub(super) validate_target: bool,
77    pub(super) normalize_target: bool,
78    pub(super) max_headers: u16,
79    pub(super) max_buf_size: usize,
80    pub(super) max_start_line_size: usize,
81    pub(super) headers_read_rate: Option<FrameReadRate>,
82    pub(super) payload_read_rate: Option<FrameReadRate>,
83    pub(super) write_timeout: Seconds,
84    pub(super) half_close: bool,
85    #[cfg(all(feature = "ws", feature = "compress"))]
86    pub(crate) ws_deflate: Option<crate::ws::DeflateConfig>,
87
88    config: CfgContext,
89}
90
91impl Default for HttpServiceConfig {
92    fn default() -> Self {
93        HttpServiceConfig::new()
94    }
95}
96
97impl Configuration for HttpServiceConfig {
98    const NAME: &str = "Http service configuration";
99
100    fn ctx(&self) -> &CfgContext {
101        &self.config
102    }
103
104    fn set_ctx(&mut self, ctx: CfgContext) {
105        self.config = ctx;
106    }
107}
108
109impl HttpServiceConfig {
110    #[must_use]
111    /// Creates an HTTP service configuration with default settings.
112    pub fn new() -> HttpServiceConfig {
113        Self::new_inner(KeepAlive::Timeout(Seconds(5)), Seconds::ONE)
114    }
115
116    fn new_inner(keep_alive: KeepAlive, client_timeout: Seconds) -> HttpServiceConfig {
117        let (keep_alive, ka_enabled) = keep_alive.state();
118
119        HttpServiceConfig {
120            keep_alive,
121            ka_enabled,
122            headers_read_rate: Some(FrameReadRate {
123                rate: 256,
124                timeout: client_timeout,
125                max_timeout: client_timeout + Seconds(15),
126            }),
127            max_headers: 96,
128            max_buf_size: 64 * 1024,
129            max_start_line_size: 16 * 1024,
130            headers_vec: false,
131            validate_host: false,
132            validate_target: false,
133            normalize_target: false,
134            payload_read_rate: None,
135            write_timeout: Seconds(10),
136            half_close: false,
137            #[cfg(all(feature = "ws", feature = "compress"))]
138            ws_deflate: None,
139            config: CfgContext::default(),
140        }
141    }
142
143    #[must_use]
144    /// Sets the maximum number of headers in a message.
145    ///
146    /// Every header field counts, including repeated header names. HTTP/2
147    /// pseudo-header fields do not count.
148    ///
149    /// Requests exceeding this limit are rejected with
150    /// `431 Request Header Fields Too Large`; an HTTP/2 connection stays open
151    /// and only the offending stream is answered. The default is 96.
152    ///
153    /// HTTP/2 also applies its own decoder limit, set by
154    /// [`Http2ServiceConfig::set_max_headers`](crate::http::h2::Http2ServiceConfig::set_max_headers),
155    /// before this check; streams exceeding that limit are refused with
156    /// `REFUSED_STREAM` instead, so the stricter of the two limits applies.
157    pub fn set_max_headers(mut self, val: u16) -> Self {
158        self.max_headers = val;
159        self
160    }
161
162    #[must_use]
163    /// Sets the maximum cumulative size of an HTTP message head.
164    ///
165    /// The request or response line, headers, and terminating empty line may
166    /// occupy up to and including this number of bytes. Larger message heads
167    /// are rejected. The default is 64 KiB.
168    pub fn set_max_buf_size(mut self, val: usize) -> Self {
169        self.max_buf_size = val;
170        self
171    }
172
173    #[must_use]
174    /// Sets the maximum size of an HTTP/1 request or status line.
175    ///
176    /// The line, including its line end, may occupy up to and including this
177    /// number of bytes. Requests with a longer request line are rejected with
178    /// `414 URI Too Long`, or with `400 Bad Request` when the method alone
179    /// exceeds the limit. The line is also limited by
180    /// [`set_max_buf_size`](Self::set_max_buf_size). The default is 16 KiB.
181    pub fn set_max_start_line_size(mut self, val: usize) -> Self {
182        self.max_start_line_size = val;
183        self
184    }
185
186    #[must_use]
187    /// Sets the server keep-alive behavior.
188    ///
189    /// By default, idle persistent connections are closed after five seconds.
190    /// The keep-alive timeout does not apply before the first request. If
191    /// request-head timing is disabled, it also bounds a partially received
192    /// request head after the first request.
193    ///
194    /// A zero timeout, such as `0` or `Seconds::ZERO`, disables persistent
195    /// connections. Use [`KeepAlive::Os`] for persistent connections without
196    /// an idle timeout. Integer timeouts above `u16::MAX` seconds saturate.
197    pub fn set_keepalive<W: Into<KeepAlive>>(mut self, val: W) -> Self {
198        (self.keep_alive, self.ka_enabled) = val.into().state();
199        self
200    }
201
202    #[must_use]
203    /// Sets the keep-alive timeout.
204    ///
205    /// A zero duration disables persistent connections rather than selecting
206    /// an unlimited timeout. Use [`KeepAlive::Os`] with
207    /// [`set_keepalive`](Self::set_keepalive) to leave connection lifetime to
208    /// the peer or operating system. The default is five seconds.
209    pub fn set_keepalive_timeout(mut self, timeout: Seconds) -> Self {
210        (self.keep_alive, self.ka_enabled) = KeepAlive::Timeout(timeout).state();
211        self
212    }
213
214    #[must_use]
215    /// Sets the initial timeout for reading request headers.
216    ///
217    /// A new connection must send the first byte of its first request within
218    /// this period, otherwise it is rejected with `408 Request Timeout`. The
219    /// request-head read rate starts with that byte, and this period is also
220    /// its measurement interval. A zero duration disables header-read timing.
221    /// A new connection can then wait indefinitely for its first request,
222    /// while on a persistent connection the keep-alive timeout bounds both
223    /// waiting for the next request and reading its head. The default is one
224    /// second.
225    ///
226    /// HTTP/1 timers have one-second resolution, a timeout can expire up to
227    /// one second later than configured.
228    ///
229    /// This sets the measurement interval of the request-head read rate. The
230    /// cumulative limit and required rate configured by
231    /// [`set_headers_read_rate`](Self::set_headers_read_rate) are kept. If
232    /// header-read timing was disabled, it is enabled again with the default
233    /// rate of 256 bytes and a cumulative limit of `timeout` plus 15 seconds.
234    pub fn set_client_timeout(mut self, timeout: Seconds) -> Self {
235        if timeout.is_zero() {
236            self.headers_read_rate = None;
237        } else {
238            let mut rate = self.headers_read_rate.unwrap_or(FrameReadRate {
239                rate: 256,
240                timeout,
241                max_timeout: timeout + Seconds(15),
242            });
243            rate.timeout = timeout;
244            self.headers_read_rate = Some(rate);
245        }
246        self
247    }
248
249    #[must_use]
250    /// Sets the HTTP/1 write backpressure timeout.
251    ///
252    /// Write backpressure is enabled when outstanding output reaches the I/O
253    /// write buffer high watermark, and disabled once the peer has accepted
254    /// enough of it. If backpressure is still enabled when the timeout
255    /// expires, the connection is closed, and the HTTP/1 control service
256    /// receives a peer-gone event with an [`io::ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut)
257    /// error. An unfinished request payload stream receives a
258    /// [`PayloadError::Io`](crate::http::error::PayloadError::Io) with the
259    /// same error kind. Each backpressure period starts a fresh timeout.
260    ///
261    /// Without a write timeout, a client that stops reading responses can hold
262    /// the connection open indefinitely. Payload read-rate timing is paused
263    /// during write backpressure and resumes once it is disabled.
264    ///
265    /// Timers have one-second resolution, the timeout can expire up to one
266    /// second later than configured. A zero duration disables the timeout. The
267    /// default is ten seconds, so a client must accept roughly half of the
268    /// write buffer high watermark within that time. Raise it for clients on
269    /// very slow links.
270    pub fn set_write_timeout(mut self, timeout: Seconds) -> Self {
271        self.write_timeout = timeout;
272        self
273    }
274
275    #[must_use]
276    /// Keeps streaming an HTTP/1 response after the client half-closes the
277    /// connection.
278    ///
279    /// A client that closes its side of the connection is treated as gone:
280    /// when the read side reaches EOF, all buffered requests are handled and
281    /// the response body has no data ready, the dispatcher drops the body and
282    /// closes the connection. Otherwise an idle streaming response, e.g.
283    /// server-sent events, would hold the connection until the body produces
284    /// its next chunk.
285    ///
286    /// Enable this for clients that shut down their write side after sending
287    /// the request and still expect the full response. Such a response then
288    /// ends only when the body completes or a write fails. Responses that are
289    /// ready are sent either way. This setting does not affect HTTP/2. It is
290    /// disabled by default.
291    pub fn set_half_close(mut self, enabled: bool) -> Self {
292        self.half_close = enabled;
293        self
294    }
295
296    #[must_use]
297    #[cfg(all(feature = "ws", feature = "compress"))]
298    /// Accepts the WebSocket `permessage-deflate` extension (RFC 7692).
299    ///
300    /// [`web::ws::start()`](crate::web::ws::start) accepts the client's offer
301    /// within the limits of `cfg`, see
302    /// [`DeflateConfig::negotiate()`](crate::ws::DeflateConfig::negotiate).
303    /// Text and binary messages are then compressed in both directions.
304    ///
305    /// The extension is not accepted by default.
306    pub fn set_ws_deflate(mut self, cfg: crate::ws::DeflateConfig) -> Self {
307        self.ws_deflate = Some(cfg);
308        self
309    }
310
311    #[must_use]
312    /// Preserves headers in their original order and casing.
313    ///
314    /// When enabled, decoded headers are additionally copied into
315    /// [`RequestHead::headers_vec`](crate::http::RequestHead::headers_vec) or
316    /// [`ResponseHead::headers_vec`](crate::http::ResponseHead::headers_vec).
317    /// The normal header map remains populated. This is disabled by default.
318    pub fn set_headers_vec(mut self, enabled: bool) -> Self {
319        self.headers_vec = enabled;
320        self
321    }
322
323    #[must_use]
324    /// Enables validation of the HTTP/1 `Host` request header.
325    ///
326    /// When enabled, requests are rejected with `400 Bad Request` if a
327    /// `Host` value is not a valid host and optional port. Requests with more
328    /// than one `Host` header, HTTP/1.1 requests without a `Host` header and
329    /// requests with an empty `Host` value whose target has no authority
330    /// (origin-form or asterisk-form) are always rejected, regardless of this
331    /// setting, see
332    /// [RFC 9112 section 3.2](https://www.rfc-editor.org/rfc/rfc9112#section-3.2).
333    /// This setting does not affect HTTP/2. It is disabled by default.
334    pub fn set_host_validation(mut self, enabled: bool) -> Self {
335        self.validate_host = enabled;
336        self
337    }
338
339    #[must_use]
340    /// Enables request-target validation, without normalization, during HTTP
341    /// decoding.
342    ///
343    /// Disabled by default. When enabled, HTTP/1 and HTTP/2 reject malformed
344    /// targets and method-inappropriate forms with `400 Bad Request`, the same
345    /// checks [`Self::set_request_target_normalization`] performs, but pass
346    /// valid targets on with their exact spelling. For example `/%ZZ` is
347    /// rejected while `/%41/../b` reaches the application unchanged. Use it for
348    /// proxies and for applications that verify signatures over the raw target.
349    ///
350    /// Normalization always validates first, so this setting has no effect
351    /// while normalization is enabled.
352    ///
353    /// ```
354    /// use ntex::{SharedCfg, http::HttpServiceConfig};
355    ///
356    /// let config = SharedCfg::new("HTTP")
357    ///     .add(HttpServiceConfig::new().set_request_target_validation(true));
358    /// ```
359    pub fn set_request_target_validation(mut self, enabled: bool) -> Self {
360        self.validate_target = enabled;
361        self
362    }
363
364    pub(super) fn target_policy(&self) -> super::helpers::TargetPolicy {
365        use super::helpers::TargetPolicy;
366
367        if self.normalize_target {
368            TargetPolicy::Normalize
369        } else if self.validate_target {
370            TargetPolicy::Validate
371        } else {
372            TargetPolicy::Raw
373        }
374    }
375
376    #[must_use]
377    /// Enables request-target validation and normalization during HTTP decoding.
378    ///
379    /// Both are disabled by default. When enabled, HTTP/1 and HTTP/2 reject
380    /// malformed targets and method-inappropriate forms with `400 Bad Request`,
381    /// then normalize valid targets using [`urly::Url::normalize`].
382    /// Normalization failures also produce `400 Bad Request`. Disabling
383    /// normalization does not disable validation enabled with
384    /// [`Self::set_request_target_validation`].
385    ///
386    /// Processing happens before application middleware, filters, routing and
387    /// lower-level HTTP service handlers. They all receive the normalized URI.
388    /// For HTTP/2 the URI holds only `:path`; the normalized `:scheme` and
389    /// `:authority` are available from [`RequestHead::scheme`](super::RequestHead::scheme)
390    /// and [`RequestHead::authority`](super::RequestHead::authority).
391    /// Application rewrites are not automatically validated or normalized again.
392    ///
393    /// HTTP/1 Host-header validation is controlled separately by
394    /// [`Self::set_host_validation`]. Mandatory protocol checks, URL
395    /// representation limits, rejection of asterisk-form (`*`) targets for
396    /// methods other than OPTIONS and, for HTTP/1, rejection of raw non-ASCII
397    /// bytes in the request target remain enforced regardless of these
398    /// settings.
399    /// The router's existing per-segment percent-decoding is also unchanged.
400    ///
401    /// ```
402    /// use ntex::{SharedCfg, http::HttpServiceConfig};
403    ///
404    /// let config = SharedCfg::new("HTTP")
405    ///     .add(HttpServiceConfig::new().set_request_target_normalization(true));
406    /// ```
407    pub fn set_request_target_normalization(mut self, enabled: bool) -> Self {
408        self.normalize_target = enabled;
409        self
410    }
411
412    #[must_use]
413    /// Sets read-rate limits for request headers.
414    ///
415    /// This setting protects HTTP/1 connections from clients that send a
416    /// request line or headers too slowly. The timer starts when the first
417    /// bytes of a request head arrive, on a new connection as well as on a
418    /// persistent one. Until the first byte of the first request arrives, a
419    /// new connection waits for at most one `timeout` interval, the
420    /// [client timeout](Self::set_client_timeout), without rate extension.
421    ///
422    /// `timeout` is the duration of one measurement interval. When an interval
423    /// expires, the dispatcher grants another interval only if more than
424    /// `rate` new bytes were received. The request head must complete before
425    /// the cumulative `max_timeout` is exhausted. All newly received
426    /// request-head bytes count toward progress, including request-line and
427    /// header bytes that the incremental parser has already consumed.
428    ///
429    /// A zero `timeout` disables request-head timing. The first request of a
430    /// connection is then unbounded, and the keep-alive timeout bounds waiting
431    /// for and reading each following request head. A zero `max_timeout`
432    /// removes the cumulative limit, allowing the deadline to be extended
433    /// indefinitely while the required read rate is maintained. When
434    /// `max_timeout` is not an exact multiple of `timeout`, the final
435    /// measurement interval is shortened so the cumulative limit is not
436    /// exceeded. Intervals have one-second resolution and can expire up to one
437    /// second later than configured.
438    ///
439    /// If the request head misses its deadline, the HTTP/1 control service
440    /// receives
441    /// [`ProtocolError::SlowRequestTimeout`](crate::http::h1::ProtocolError::SlowRequestTimeout).
442    /// The default control service responds with `408 Request Timeout` and
443    /// closes the connection.
444    ///
445    /// By default, the timeout is 1 second and the maximum timeout is 16
446    /// seconds, with more than 256 bytes required for each extension.
447    ///
448    /// # Example
449    ///
450    /// ```rust
451    /// use ntex::http::HttpServiceConfig;
452    /// use ntex::time::Seconds;
453    ///
454    /// let config = HttpServiceConfig::new().set_headers_read_rate(
455    ///     Seconds(2),  // measurement interval
456    ///     Seconds(10), // maximum time for one request head
457    ///     512,         // bytes required to extend the deadline for next 2 seconds
458    /// );
459    /// ```
460    pub fn set_headers_read_rate(
461        mut self,
462        timeout: Seconds,
463        max_timeout: Seconds,
464        rate: u32,
465    ) -> Self {
466        if timeout.is_zero() {
467            self.headers_read_rate = None;
468        } else {
469            self.headers_read_rate = Some(FrameReadRate {
470                rate,
471                timeout,
472                max_timeout,
473            });
474        }
475        self
476    }
477
478    #[must_use]
479    /// Sets read-rate limits for request payloads.
480    ///
481    /// This setting protects HTTP/1 connections from clients that send a
482    /// request body too slowly. The timer starts when the dispatcher begins
483    /// decoding a request payload. For a request with `Expect: 100-continue`,
484    /// it starts only once `100 Continue` has been sent, the request has been
485    /// passed to the application, or a response has been sent and the rest of
486    /// the payload is read, because the client does not send the body before
487    /// that. At the end of each `timeout` interval, another interval is
488    /// granted only if more than `rate` bytes were decoded.
489    ///
490    /// The timer runs only while the dispatcher can read and forward payload
491    /// data. It is paused while application payload backpressure or response
492    /// write backpressure prevents further reads, so those conditions are not
493    /// treated as a slow network peer. Write backpressure is bounded by the
494    /// [write timeout](Self::set_write_timeout). Pausing preserves the unused
495    /// portion of the current measurement interval, and resuming continues
496    /// that interval rather than starting a new one, so the bytes decoded
497    /// before and after the pause are measured together. If the interval
498    /// expired before the pause, already received payload data is decoded
499    /// on resume and then the read rate is checked. The timer stops when the
500    /// complete payload has been decoded.
501    ///
502    /// A zero `timeout` disables payload timing. A zero `max_timeout` removes
503    /// the cumulative limit, allowing the deadline to be extended indefinitely
504    /// while the required read rate is maintained. When `max_timeout` is not
505    /// an exact multiple of `timeout`, the final measurement interval is
506    /// shortened so the cumulative limit is not exceeded. Intervals have
507    /// one-second resolution and can expire up to one second later than
508    /// configured.
509    ///
510    /// If the payload misses its deadline, its stream receives a timed-out
511    /// [`PayloadError`](crate::http::error::PayloadError), and the HTTP/1
512    /// control service receives
513    /// [`ProtocolError::SlowPayloadTimeout`](crate::http::h1::ProtocolError::SlowPayloadTimeout).
514    /// The default control service responds with `408 Request Timeout` and
515    /// closes the connection.
516    ///
517    /// Payload read-rate limiting is disabled by default.
518    ///
519    /// # Example
520    ///
521    /// ```rust
522    /// use ntex::http::HttpServiceConfig;
523    /// use ntex::time::Seconds;
524    ///
525    /// let config = HttpServiceConfig::new().set_payload_read_rate(
526    ///     Seconds(2),  // measurement interval
527    ///     Seconds(30), // maximum time for one request payload
528    ///     1024,        // bytes required to extend the deadline
529    /// );
530    /// ```
531    pub fn set_payload_read_rate(
532        mut self,
533        timeout: Seconds,
534        max_timeout: Seconds,
535        rate: u32,
536    ) -> Self {
537        if timeout.is_zero() {
538            self.payload_read_rate = None;
539        } else {
540            self.payload_read_rate = Some(FrameReadRate {
541                rate,
542                timeout,
543                max_timeout,
544            });
545        }
546        self
547    }
548}
549
550bitflags::bitflags! {
551    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
552    struct Flags: u8 {
553        /// Shutdown service
554        const SHUTDOWN   = 0b0000_0010;
555    }
556}
557
558#[derive(Clone)]
559pub(super) struct DispatcherConfig(Rc<DispatcherConfigInner>);
560
561struct DispatcherConfigInner {
562    flags: Cell<Flags>,
563    idx: Cell<usize>,
564    pub(super) inflight: RefCell<HashSet<IoRef>>,
565    rx: Cell<Option<oneshot::Receiver<()>>>,
566    tx: Cell<Option<oneshot::Sender<()>>>,
567}
568
569impl Default for DispatcherConfig {
570    fn default() -> Self {
571        let (tx, rx) = oneshot::channel();
572
573        DispatcherConfig(Rc::new(DispatcherConfigInner {
574            idx: Cell::new(0),
575            flags: Cell::new(Flags::empty()),
576            rx: Cell::new(Some(rx)),
577            tx: Cell::new(Some(tx)),
578            inflight: RefCell::new(HashSet::default()),
579        }))
580    }
581}
582
583impl DispatcherConfig {
584    /// Get connection id
585    pub(super) fn next_id(&self) -> usize {
586        let id = self.0.idx.get();
587        self.0.idx.set(id + 1);
588        id
589    }
590
591    /// Registers an in-flight connection.
592    ///
593    /// Returns the guard that unregisters the connection when dropped, and
594    /// the number of in-flight connections.
595    pub(super) fn insert_io(&self, io: &IoRef) -> (InflightGuard, usize) {
596        let mut inflight = self.0.inflight.borrow_mut();
597        inflight.insert(io.clone());
598        let guard = InflightGuard {
599            config: self.clone(),
600            io: io.clone(),
601        };
602        (guard, inflight.len())
603    }
604
605    /// Service is shutting down
606    pub(super) fn is_shutdown(&self) -> bool {
607        self.0.flags.get().contains(Flags::SHUTDOWN)
608    }
609
610    pub(super) fn shutdown(&self) -> usize {
611        ntex_h2::ServiceConfig::shutdown();
612
613        let mut flags = self.0.flags.get();
614        flags.insert(Flags::SHUTDOWN);
615        self.0.flags.set(flags);
616
617        let inflight = self.0.inflight.borrow();
618        for io in inflight.iter() {
619            io.notify_dispatcher();
620        }
621        inflight.len()
622    }
623
624    pub(super) async fn wait_shutdown(&self) {
625        if let Some(rx) = self.0.rx.take() {
626            let _ = rx.await;
627        }
628    }
629
630    pub(super) fn notify_shutdown(&self) {
631        if let Some(tx) = self.0.tx.take() {
632            let _ = tx.send(());
633        }
634    }
635}
636
637/// Unregisters an in-flight connection when dropped.
638///
639/// The connection is unregistered even if its future is dropped before it
640/// completes, a pending shutdown is notified once no connections are left.
641pub(super) struct InflightGuard {
642    config: DispatcherConfig,
643    io: IoRef,
644}
645
646impl Drop for InflightGuard {
647    fn drop(&mut self) {
648        let inflight = {
649            let mut inflight = self.config.0.inflight.borrow_mut();
650            inflight.remove(&self.io);
651            inflight.len()
652        };
653        if inflight == 0 && self.config.is_shutdown() {
654            self.config.notify_shutdown();
655        }
656    }
657}
658
659const DATE_VALUE_LENGTH_HDR: usize = 39;
660const DATE_VALUE_DEFAULT: [u8; DATE_VALUE_LENGTH_HDR] =
661    *b"date: 00000000000000000000000000000\r\n\r\n";
662
663#[derive(Debug, Copy, Clone)]
664/// Generates the cached HTTP `Date` header used by the protocol encoders.
665///
666/// The cached value is refreshed periodically and avoids formatting the
667/// current system time for every response. Applications normally do not need
668/// to use this type directly.
669pub struct DateService;
670
671thread_local! {
672    static DATE: DateServiceInner = DateServiceInner::new();
673}
674
675#[derive(Debug)]
676struct DateServiceInner {
677    current: Cell<bool>,
678    current_time: Cell<time::Instant>,
679    current_date: Cell<[u8; DATE_VALUE_LENGTH_HDR]>,
680    current_value: RefCell<Option<HeaderValue>>,
681}
682
683impl DateServiceInner {
684    fn new() -> Self {
685        DateServiceInner {
686            current: Cell::new(false),
687            current_time: Cell::new(time::Instant::now()),
688            current_date: Cell::new(DATE_VALUE_DEFAULT),
689            current_value: RefCell::new(None),
690        }
691    }
692
693    fn update(&self) {
694        self.current.set(true);
695        self.current_time.set(time::Instant::now());
696
697        let mut bytes = DATE_VALUE_DEFAULT;
698        let dt = httpdate::HttpDate::from(time::SystemTime::now()).to_string();
699        bytes[6..35].copy_from_slice(dt.as_ref());
700        self.current_date.set(bytes);
701        *self.current_value.borrow_mut() = None;
702    }
703}
704
705impl DateService {
706    fn check_date() {
707        DATE.with(|date| {
708            if !date.current.get() {
709                date.update();
710
711                // periodic date update
712                crate::rt::spawn_detached(async move {
713                    sleep(Millis(500)).await;
714                    DATE.with(|date| {
715                        date.current.set(false);
716                    });
717                });
718            }
719        });
720    }
721
722    /// Returns the current date as a `Date` header value.
723    ///
724    /// The value is shared until the next date update.
725    pub(super) fn header_value() -> HeaderValue {
726        DateService::check_date();
727        DATE.with(|date| {
728            date.current_value
729                .borrow_mut()
730                .get_or_insert_with(|| {
731                    // validated once per date update
732                    HeaderValue::from_bytes(&date.current_date.get()[6..35])
733                        .expect("formatted date is visible ASCII")
734                })
735                .clone()
736        })
737    }
738
739    #[doc(hidden)]
740    pub fn set_date_header(&self, dst: &mut BytesMut) {
741        DateService::check_date();
742        DATE.with(|date| dst.extend_from_slice(&date.current_date.get()));
743    }
744
745    #[doc(hidden)]
746    pub fn set_date_header2(&self, dst: &mut BytePages) {
747        DateService::check_date();
748        DATE.with(|date| dst.extend_from_slice(&date.current_date.get()));
749    }
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    /// STATEMENT: Date header serialization reuses cached values until the date service invalidates them.
757    ///
758    /// HOW:
759    /// - Compare repeated `BytesMut` writes, and a `BytePages` write, with each other and match the cached header value.
760    /// - Update the service, verify cache invalidation, and check the regenerated value length.
761    #[crate::rt_test]
762    async fn test_date() {
763        let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH_HDR);
764        DateService.set_date_header(&mut buf1);
765        let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH_HDR);
766        DateService.set_date_header(&mut buf2);
767        assert_eq!(buf1, buf2);
768
769        let mut pages = BytePages::default();
770        DateService.set_date_header2(&mut pages);
771        assert_eq!(pages.freeze(), &buf1[..]);
772
773        // the header value is the cached date
774        let value = DateService::header_value();
775        assert_eq!(value.as_bytes(), &buf1[6..35]);
776        assert_eq!(DateService::header_value(), value);
777        DATE.with(DateServiceInner::update);
778        assert!(DATE.with(|date| date.current_value.borrow().is_none()));
779        assert_eq!(DateService::header_value().len(), 29);
780    }
781
782    /// STATEMENT: Integer conversions saturate oversized timeouts instead of wrapping them.
783    ///
784    /// HOW:
785    /// - Convert absent, zero, normal, `u16::MAX`, and overflowing `usize` and `Option<usize>` values.
786    /// - Check `None` becomes `Disabled` and `65536` saturates to `Seconds(u16::MAX)` rather than wrapping to zero.
787    #[test]
788    fn keep_alive() {
789        assert_eq!(KeepAlive::Disabled, Option::<usize>::None.into());
790        for (val, expected) in [
791            (0, 0),
792            (10, 10),
793            (usize::from(u16::MAX), u16::MAX),
794            (usize::from(u16::MAX) + 1, u16::MAX),
795            (usize::from(u16::MAX) + 11, u16::MAX),
796        ] {
797            assert_eq!(KeepAlive::Timeout(Seconds(expected)), val.into());
798            assert_eq!(KeepAlive::Timeout(Seconds(expected)), Some(val).into());
799        }
800
801        let cfg = HttpServiceConfig::new().set_keepalive(usize::from(u16::MAX) + 1);
802        assert_eq!(cfg.keep_alive, Seconds(u16::MAX));
803        assert!(cfg.ka_enabled);
804    }
805
806    /// STATEMENT: Keepalive modes distinguish OS-managed persistence, disabled persistence, and configured timeouts, and every zero timeout disables persistence.
807    ///
808    /// HOW:
809    /// - Apply `Os`, `Disabled`, nonzero timeouts and zero timeouts through `set_keepalive` (`KeepAlive`, `Seconds`, `usize`, `Option<usize>`) and `set_keepalive_timeout`.
810    /// - Compare the stored timeout and enablement fields; all zero forms must match `Disabled`.
811    #[test]
812    fn keep_alive_settings() {
813        let cfg = HttpServiceConfig::new().set_keepalive(KeepAlive::Os);
814        assert_eq!(cfg.keep_alive, Seconds::ZERO);
815        assert!(cfg.ka_enabled);
816
817        let cfg = HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled);
818        assert_eq!(cfg.keep_alive, Seconds::ZERO);
819        assert!(!cfg.ka_enabled);
820
821        let cfg = HttpServiceConfig::new().set_keepalive(10);
822        assert_eq!(cfg.keep_alive, Seconds(10));
823        assert!(cfg.ka_enabled);
824
825        let cfg = HttpServiceConfig::new().set_keepalive_timeout(Seconds(30));
826        assert_eq!(cfg.keep_alive, Seconds(30));
827        assert!(cfg.ka_enabled);
828
829        for cfg in [
830            HttpServiceConfig::new().set_keepalive(KeepAlive::Timeout(Seconds::ZERO)),
831            HttpServiceConfig::new().set_keepalive(Seconds::ZERO),
832            HttpServiceConfig::new().set_keepalive(0),
833            HttpServiceConfig::new().set_keepalive(Some(0)),
834            HttpServiceConfig::new().set_keepalive_timeout(Seconds::ZERO),
835        ] {
836            assert_eq!(cfg.keep_alive, Seconds::ZERO);
837            assert!(!cfg.ka_enabled);
838        }
839    }
840
841    /// STATEMENT: Zero read-rate intervals disable header and payload rate enforcement.
842    ///
843    /// HOW:
844    /// - Configure nonzero rates, verify both are present, then replace intervals with zero and check both are absent.
845    #[test]
846    fn read_rate_settings() {
847        let cfg = HttpServiceConfig::new()
848            .set_headers_read_rate(Seconds(1), Seconds(5), 128)
849            .set_payload_read_rate(Seconds(1), Seconds(5), 128);
850        assert!(cfg.headers_read_rate.is_some());
851        assert!(cfg.payload_read_rate.is_some());
852
853        let cfg = cfg
854            .set_headers_read_rate(Seconds::ZERO, Seconds(5), 128)
855            .set_payload_read_rate(Seconds::ZERO, Seconds(5), 128);
856        assert!(cfg.headers_read_rate.is_none());
857        assert!(cfg.payload_read_rate.is_none());
858    }
859}