ntex_server/
pool.rs

1use ntex_util::time::Millis;
2
3use crate::{Server, ServerConfiguration};
4
5const DEFAULT_SHUTDOWN_TIMEOUT: Millis = Millis::from_secs(30);
6
7#[derive(Debug, Copy, Clone)]
8/// Server builder
9pub struct WorkerPool {
10    pub(crate) num: usize,
11    pub(crate) no_signals: bool,
12    pub(crate) stop_runtime: bool,
13    pub(crate) shutdown_timeout: Millis,
14    pub(crate) affinity: bool,
15}
16
17impl Default for WorkerPool {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl WorkerPool {
24    /// Create new Server builder instance
25    pub fn new() -> Self {
26        let num = core_affinity::get_core_ids()
27            .map(|v| v.len())
28            .unwrap_or_else(|| {
29                std::thread::available_parallelism().map_or(2, std::num::NonZeroUsize::get)
30            });
31
32        WorkerPool {
33            num,
34            no_signals: false,
35            stop_runtime: false,
36            shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
37            affinity: false,
38        }
39    }
40
41    /// Set number of workers to start.
42    ///
43    /// By default server uses number of available logical cpu as workers
44    /// count.
45    pub fn workers(mut self, num: usize) -> Self {
46        self.num = num;
47        self
48    }
49
50    /// Stop current ntex runtime when manager get dropped.
51    ///
52    /// By default "stop runtime" is disabled.
53    pub fn stop_runtime(mut self) -> Self {
54        self.stop_runtime = true;
55        self
56    }
57
58    /// Disable signal handling.
59    ///
60    /// By default signal handling is enabled.
61    pub fn disable_signals(mut self) -> Self {
62        self.no_signals = true;
63        self
64    }
65
66    /// Timeout for graceful workers shutdown.
67    ///
68    /// After receiving a stop signal, workers have this much time to finish
69    /// serving requests. Workers still alive after the timeout are force
70    /// dropped.
71    ///
72    /// By default shutdown timeout sets to 30 seconds.
73    pub fn shutdown_timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
74        self.shutdown_timeout = timeout.into();
75        self
76    }
77
78    /// Enable core affinity
79    ///
80    /// By default affinity is disabled.
81    pub fn enable_affinity(mut self) -> Self {
82        self.affinity = true;
83        self
84    }
85
86    /// Starts processing incoming items and return server controller.
87    pub fn run<F: ServerConfiguration>(self, factory: F) -> Server<F::Item> {
88        crate::manager::ServerManager::start(self, factory)
89    }
90}