Skip to main content

ntex_server/net/
mod.rs

1//! General purpose tcp server
2use std::sync::atomic::{AtomicUsize, Ordering};
3
4use ntex_util::services::Counter;
5
6mod accept;
7mod builder;
8mod config;
9mod factory;
10mod service;
11mod socket;
12mod state;
13mod test;
14
15pub use self::accept::{AcceptLoop, AcceptNotify, AcceptorCommand};
16pub use self::builder::{ServerBuilder, bind_addr, create_tcp_listener};
17pub use self::config::{ServiceConfig, ServiceRuntime};
18pub use self::service::StreamServer;
19pub use self::socket::{Connection, Stream};
20pub use self::state::{NoConfig, ServerAppConfig};
21pub use self::test::{TestServer, TestServerBuilder, build_test_server, test_server};
22
23pub type Server = crate::Server<Connection>;
24
25#[non_exhaustive]
26#[derive(Copy, Clone, Debug, PartialEq, Eq)]
27/// Server readiness status
28pub enum ServerStatus {
29    Ready,
30    NotReady,
31    WorkerFailed,
32}
33
34/// Socket id token
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub struct Token(usize);
37
38impl Token {
39    #[must_use]
40    #[allow(clippy::should_implement_trait)]
41    pub fn next(&mut self) -> Token {
42        let token = Token(self.0);
43        self.0 += 1;
44        token
45    }
46}
47
48/// Start server building process
49pub fn build() -> ServerBuilder {
50    ServerBuilder::default()
51}
52
53/// Start server with state building process
54pub fn build_with_cfg<Cfg>(state: Cfg) -> ServerBuilder<Cfg>
55where
56    Cfg: ServerAppConfig,
57{
58    ServerBuilder::new(state)
59}
60
61static MAX_CONNS: AtomicUsize = AtomicUsize::new(25600);
62
63thread_local! {
64    static MAX_CONNS_COUNTER: Counter = Counter::new(MAX_CONNS.load(Ordering::Relaxed));
65}
66
67/// Sets the maximum per-worker number of concurrent connections.
68///
69/// All socket listeners will stop accepting connections when this limit is
70/// reached for each worker.
71///
72/// By default max connections is set to a 25k per worker.
73pub(super) fn max_concurrent_connections(num: usize) {
74    MAX_CONNS.store(num, Ordering::Relaxed);
75    MAX_CONNS_COUNTER.with(|conns| conns.set_capacity(num));
76}
77
78pub(super) fn num_connections() -> usize {
79    MAX_CONNS_COUNTER.with(Counter::total)
80}