Skip to main content

ntex_server/net/
mod.rs

1//! General-purpose network server.
2//!
3//! Use [`build()`] or [`ServerBuilder`] to register TCP or Unix domain socket
4//! services. Each worker receives its own service instance and processes
5//! connections on a single-threaded runtime.
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8use ntex_util::services::Counter;
9
10mod accept;
11mod builder;
12mod config;
13mod factory;
14mod service;
15mod socket;
16mod test;
17
18pub use crate::{NoConfig, ServerAppConfig};
19
20pub use self::accept::{AcceptLoop, AcceptNotify, AcceptorCommand};
21pub use self::builder::{ServerBuilder, bind_addr, create_tcp_listener};
22pub use self::config::{ServiceConfig, ServiceRuntime};
23pub use self::service::StreamServer;
24pub use self::socket::{Connection, Stream};
25pub use self::test::{TestServer, TestServerBuilder, build_test_server, test_server};
26
27pub type Server = crate::Server<Connection>;
28
29#[non_exhaustive]
30#[derive(Copy, Clone, Debug, PartialEq, Eq)]
31/// Server readiness status.
32pub enum ServerStatus {
33    /// All workers are ready to accept work.
34    Ready,
35    /// At least one worker is temporarily unavailable.
36    NotReady,
37    /// A worker failed.
38    WorkerFailed,
39}
40
41/// Identifier assigned to a registered listener.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct Token(usize);
44
45impl Token {
46    #[must_use]
47    #[allow(clippy::should_implement_trait)]
48    /// Returns the current token and advances this value to the next token.
49    pub fn next(&mut self) -> Token {
50        let token = Token(self.0);
51        self.0 += 1;
52        token
53    }
54}
55
56/// Creates a server builder with no application configuration.
57pub fn build() -> ServerBuilder {
58    ServerBuilder::default()
59}
60
61/// Creates a server builder with application configuration.
62pub fn build_with_config<Cfg>(state: Cfg) -> ServerBuilder<Cfg>
63where
64    Cfg: ServerAppConfig,
65{
66    ServerBuilder::new(state)
67}
68
69static MAX_CONNS: AtomicUsize = AtomicUsize::new(25600);
70
71thread_local! {
72    static MAX_CONNS_COUNTER: Counter = Counter::new(MAX_CONNS.load(Ordering::Relaxed));
73}
74
75/// Sets the maximum per-worker number of concurrent connections.
76///
77/// All socket listeners will stop accepting connections when this limit is
78/// reached for each worker.
79///
80/// By default max connections is set to a 25k per worker.
81pub(super) fn max_concurrent_connections(num: usize) {
82    MAX_CONNS.store(num, Ordering::Relaxed);
83    MAX_CONNS_COUNTER.with(|conns| conns.set_capacity(num));
84}
85
86pub(super) fn num_connections() -> usize {
87    MAX_CONNS_COUNTER.with(Counter::total)
88}