ntex_server/lib.rs
1//! Worker-based server infrastructure for ntex.
2//!
3//! [`WorkerPool`] runs services across one or more worker threads. The [`net`]
4//! module builds TCP and Unix domain socket servers on top of that pool.
5//! [`Server`] is the controller used to pause, resume, stop, or await a running
6//! server.
7
8#![deny(clippy::pedantic)]
9#![allow(
10 async_fn_in_trait,
11 clippy::clone_on_copy,
12 clippy::must_use_candidate,
13 clippy::missing_fields_in_debug,
14 clippy::missing_errors_doc,
15 clippy::missing_panics_doc,
16 clippy::unused_async
17)]
18
19use ntex_service::Service;
20
21mod manager;
22pub mod net;
23mod pool;
24mod server;
25mod state;
26mod wrk;
27
28pub use self::pool::WorkerPool;
29pub use self::server::Server;
30pub use self::state::{NoConfig, ServerAppConfig};
31pub use self::wrk::{Worker, WorkerStatus, WorkerStop};
32
33/// Identifier assigned to a server worker.
34#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
35pub struct WorkerId(pub(crate) usize);
36
37impl WorkerId {
38 pub(self) fn next(&mut self) -> WorkerId {
39 let id = WorkerId(self.0);
40 self.0 += 1;
41 id
42 }
43}
44
45/// Worker service configuration.
46pub trait ServerConfiguration: Send + Clone + 'static {
47 /// Item dispatched to a worker service.
48 type Item: Send + 'static;
49 /// Service created independently for each worker.
50 type Service: Service<(), Self::Item, Res = (), Error = ()> + 'static;
51
52 /// Creates the service used by one worker.
53 async fn create(&self) -> std::io::Result<Self::Service>;
54
55 /// Called when the server is paused.
56 ///
57 /// Besides explicit [`Server::pause`] calls, the server pauses itself
58 /// while no worker is available to accept items.
59 fn pause(&self) {}
60
61 /// Called when the server is resumed.
62 ///
63 /// Besides explicit [`Server::resume`] calls, the server resumes itself
64 /// once a worker becomes available again.
65 fn resume(&self) {}
66
67 /// Called when the server's command loop exits.
68 ///
69 /// This happens after a stop requested through [`Server::stop`] or a
70 /// signal, graceful or not, once [`stop`](Self::stop) has completed.
71 fn terminate(&self) {}
72
73 /// Performs asynchronous cleanup when the server stops.
74 ///
75 /// Called once, before the workers are stopped.
76 async fn stop(&self) {}
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn worker_id_next() {
85 let mut id = WorkerId::default();
86 assert_eq!(id.next(), WorkerId(0));
87 assert_eq!(id.next(), WorkerId(1));
88 assert_eq!(id, WorkerId(2));
89 }
90}