Skip to main content

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