Skip to main content

ntex_server/net/
builder.rs

1use std::{fmt, io, net, sync::Arc};
2
3use ntex_io::Io;
4use ntex_rt::System;
5use ntex_service::{IntoService, Service, cfg::SharedCfg};
6use ntex_util::time::Millis;
7use socket2::{Domain, SockAddr, Socket, Type};
8
9use crate::{Affinity, LoadBalancing, NoConfig, Server, ServerAppConfig, WorkerPool};
10
11use super::accept::{AcceptLoop, replicate};
12use super::config::ServiceConfig;
13use super::factory::{self, FactoryServiceType};
14use super::reuseport::{Reuseport, Sockets};
15use super::{Connection, StreamServer, Token, socket::Listener};
16
17/// Builder for a network server.
18///
19/// Register listeners and their service factories, configure the worker pool,
20/// and call [`run`](Self::run) to start the server.
21pub struct ServerBuilder<Cfg = NoConfig> {
22    name: String,
23    token: Token,
24    backlog: i32,
25    state: Arc<Cfg>,
26    services: Vec<FactoryServiceType<Cfg>>,
27    sockets: Vec<(Token, String, Listener)>,
28    accept: AcceptLoop,
29    acceptors: usize,
30    max_conns: usize,
31    pool: WorkerPool,
32}
33
34impl Default for ServerBuilder {
35    fn default() -> Self {
36        Self::new(NoConfig)
37    }
38}
39
40impl<Cfg> ServerBuilder<Cfg>
41where
42    Cfg: ServerAppConfig,
43{
44    #[must_use]
45    /// Creates a server builder with the specified application configuration.
46    pub fn new(cfg: Cfg) -> ServerBuilder<Cfg> {
47        let sys = System::current();
48        let mut accept = AcceptLoop::default();
49        accept.name(sys.name());
50        if sys.testing() {
51            accept.testing();
52        }
53
54        ServerBuilder {
55            accept,
56            acceptors: 1,
57            max_conns: super::DEFAULT_MAX_CONNS,
58            name: sys.name().to_string(),
59            token: Token(0),
60            state: Arc::new(cfg),
61            services: Vec::new(),
62            sockets: Vec::new(),
63            backlog: 2048,
64            pool: WorkerPool::default().name(sys.name()),
65        }
66    }
67
68    #[must_use]
69    /// Sets the server name.
70    ///
71    /// The name is also used for the accept and worker thread names. It
72    /// defaults to the current system name.
73    pub fn name<T: AsRef<str>>(mut self, name: T) -> Self {
74        self.name = name.as_ref().to_string();
75        self.accept.name(self.name.as_str());
76        self.pool = self.pool.name(self.name.as_str());
77        self
78    }
79
80    #[must_use]
81    /// Sets the number of worker threads to start.
82    ///
83    /// By default, the server uses the number of available logical CPUs.
84    ///
85    /// # Panics
86    ///
87    /// Panics if `num` is zero.
88    pub fn workers(mut self, num: usize) -> Self {
89        self.pool = self.pool.workers(num);
90        self
91    }
92
93    #[must_use]
94    /// Sets the maximum number of pending connections.
95    ///
96    /// This refers to the number of clients that can be waiting to be served.
97    /// Exceeding this number results in the client getting an error when
98    /// attempting to connect. It should only affect servers under significant
99    /// load.
100    ///
101    /// Generally set in the 64-2048 range. Default value is 2048.
102    ///
103    /// It applies to listeners created by later [`bind`](Self::bind) and
104    /// [`configure`](Self::configure) calls. It does not affect listeners
105    /// passed to [`listen`](Self::listen) or `listen_uds`.
106    pub fn backlog(mut self, num: i32) -> Self {
107        self.backlog = num;
108        self.accept.backlog(num);
109        self
110    }
111
112    #[must_use]
113    /// Sets the number of accept threads.
114    ///
115    /// Each accept thread has its own `SO_REUSEPORT` copy of every TCP
116    /// listener, and the kernel spreads incoming connections between them.
117    /// This raises the connection rate the server can accept. Listeners
118    /// passed to [`listen`](Self::listen) get `SO_REUSEPORT` enabled as well.
119    /// Copies use the [`backlog`](Self::backlog) value. Unix domain listeners
120    /// are served by a single accept thread.
121    ///
122    /// Multiple accept threads are supported on Linux and Android. On other
123    /// platforms, a single thread is used.
124    ///
125    /// By default, the server uses a single accept thread. One thread is
126    /// usually enough, add more only if the accept thread is saturated.
127    pub fn acceptors(mut self, num: usize) -> Self {
128        self.acceptors = num;
129        self
130    }
131
132    #[must_use]
133    /// Sets the maximum per-worker number of concurrent connections.
134    ///
135    /// A worker stops taking new connections while it is at this limit. When
136    /// no worker can take a connection, the listeners stop accepting.
137    ///
138    /// The limit belongs to this server: each of its workers counts only
139    /// connections for this server, and other servers in the process are not
140    /// affected.
141    ///
142    /// The default is 25,600 connections per worker.
143    pub fn max_connections(mut self, num: usize) -> Self {
144        self.max_conns = num;
145        self
146    }
147
148    #[must_use]
149    /// Stops the current ntex runtime after the server has stopped.
150    ///
151    /// By default, "stop runtime" is disabled.
152    pub fn stop_runtime(mut self) -> Self {
153        self.pool = self.pool.stop_runtime();
154        self
155    }
156
157    #[must_use]
158    /// Stops the server when one of the workers fails.
159    ///
160    /// A worker fails when it panics or its service cannot be created. The
161    /// stop is graceful only if [`graceful_shutdown`](Self::graceful_shutdown)
162    /// is enabled. Without this option, a failed worker is restarted.
163    ///
164    /// By default, "stop on panic" is disabled.
165    pub fn stop_on_panic(mut self) -> Self {
166        self.pool = self.pool.stop_on_panic();
167        self
168    }
169
170    #[must_use]
171    /// Disables signal handling.
172    ///
173    /// By default, the server stops on SIGINT, SIGTERM, and SIGQUIT.
174    pub fn disable_signals(mut self) -> Self {
175        self.pool = self.pool.disable_signals();
176        self
177    }
178
179    #[must_use]
180    /// Sets the CPU affinity of worker threads.
181    ///
182    /// See [`WorkerPool::affinity`].
183    pub fn affinity(mut self, affinity: Affinity) -> Self {
184        self.pool = self.pool.affinity(affinity);
185        self
186    }
187
188    #[must_use]
189    /// Sets how new connections are distributed between workers.
190    ///
191    /// See [`WorkerPool::load_balancing`].
192    pub fn load_balancing(mut self, balancing: LoadBalancing) -> Self {
193        self.pool = self.pool.load_balancing(balancing);
194        self
195    }
196
197    #[must_use]
198    /// Enables graceful shutdown on SIGQUIT, fatal signals, and panics.
199    ///
200    /// When enabled, SIGQUIT, SIGSEGV, SIGABRT, application panics, and
201    /// worker failures with "stop on panic" stop the server gracefully.
202    /// SIGTERM always stops gracefully and SIGINT always stops immediately.
203    /// SIGSEGV and SIGABRT require runtime fatal signal handling, application
204    /// panics require runtime panic handling.
205    ///
206    /// By default, these events stop the server immediately.
207    pub fn graceful_shutdown(mut self) -> Self {
208        self.pool = self.pool.graceful_shutdown();
209        self
210    }
211
212    #[must_use]
213    /// Timeout for graceful worker shutdown.
214    ///
215    /// After receiving a stop signal, workers have this much time to finish
216    /// serving requests. Workers that are still alive after the timeout are
217    /// forcefully dropped.
218    ///
219    /// This bounds the worker as a whole, not an individual connection. Each
220    /// connection is bound separately by `IoConfig::set_shutdown_timeout`, so
221    /// this value should leave room for the connections a worker is still
222    /// draining to shut down themselves.
223    ///
224    /// By default, the timeout is set to 30 seconds.
225    pub fn graceful_shutdown_timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
226        self.pool = self.pool.graceful_shutdown_timeout(timeout);
227        self
228    }
229
230    /// Runs asynchronous configuration as part of the server building
231    /// process.
232    ///
233    /// Listeners registered on the [`ServiceConfig`] are added to the server.
234    /// Services for them are attached per worker in
235    /// [`ServiceConfig::on_worker_start`]. This is useful for moving parts of
236    /// the configuration to a different module or library.
237    pub async fn configure<F>(mut self, f: F) -> io::Result<Self>
238    where
239        F: AsyncFnOnce(ServiceConfig<Cfg>) -> io::Result<()>,
240    {
241        let cfg = ServiceConfig::new(self.token, self.backlog);
242
243        f(cfg.clone()).await?;
244
245        let (token, sockets, factory) = cfg.into_factory();
246        self.token = token;
247        self.sockets.extend(sockets);
248        self.services.push(factory);
249
250        Ok(self)
251    }
252
253    #[allow(clippy::needless_pass_by_value)]
254    /// Binds TCP listeners and registers a service factory.
255    ///
256    /// A listener is created for every address resolved from `addr`. Binding
257    /// succeeds if at least one of them binds; addresses that fail to bind
258    /// are skipped.
259    ///
260    /// `cfg` is the I/O configuration for accepted connections. `factory` is
261    /// called once per worker with that worker's application state and
262    /// returns the connection service.
263    pub fn bind<F, S, I>(
264        mut self,
265        name: impl AsRef<str>,
266        addr: impl net::ToSocketAddrs,
267        cfg: impl Into<SharedCfg>,
268        factory: F,
269    ) -> io::Result<Self>
270    where
271        F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
272        S: Service<Cfg::State, Io> + 'static,
273        I: IntoService<S, Cfg::State, Io> + 'static,
274    {
275        let cfg = cfg.into();
276        let sockets = bind_addr(addr, self.backlog)?;
277
278        let mut tokens = Vec::new();
279        for lst in sockets {
280            let token = self.token.next();
281            self.sockets
282                .push((token, name.as_ref().to_string(), Listener::from_tcp(lst)));
283            tokens.push((token, cfg.clone()));
284        }
285
286        self.services.push(factory::create_factory_service(
287            name.as_ref().to_string(),
288            tokens,
289            factory,
290        ));
291
292        Ok(self)
293    }
294
295    #[cfg(unix)]
296    /// Binds a Unix domain socket and registers a service factory.
297    ///
298    /// Any existing file at `addr` is removed before binding. The socket file
299    /// is removed again when the server stops. See [`bind`](Self::bind) for
300    /// `cfg` and `factory`.
301    pub fn bind_uds<F, I, S>(
302        self,
303        name: impl AsRef<str>,
304        addr: impl AsRef<std::path::Path>,
305        cfg: impl Into<SharedCfg>,
306        factory: F,
307    ) -> io::Result<Self>
308    where
309        F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
310        I: IntoService<S, Cfg::State, Io> + 'static,
311        S: Service<Cfg::State, Io> + 'static,
312    {
313        use std::os::unix::net::UnixListener;
314
315        // The path must not exist when we try to bind.
316        // Try to remove it to avoid bind error.
317        if let Err(e) = std::fs::remove_file(addr.as_ref()) {
318            // NotFound is expected and not an issue. Anything else is.
319            if e.kind() != std::io::ErrorKind::NotFound {
320                return Err(e);
321            }
322        }
323
324        let lst = UnixListener::bind(addr)?;
325        self.listen_uds(name, lst, cfg.into(), factory)
326    }
327
328    #[cfg(unix)]
329    /// Registers a service factory for an existing Unix domain listener.
330    ///
331    /// This is useful for socket activation, including listeners acquired
332    /// through systemd. The listener is switched to non-blocking mode. See
333    /// [`bind`](Self::bind) for `cfg` and `factory`.
334    pub fn listen_uds<F, I, S>(
335        mut self,
336        name: impl AsRef<str>,
337        lst: std::os::unix::net::UnixListener,
338        cfg: impl Into<SharedCfg>,
339        factory: F,
340    ) -> io::Result<Self>
341    where
342        F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
343        I: IntoService<S, Cfg::State, Io> + 'static,
344        S: Service<Cfg::State, Io> + 'static,
345    {
346        let token = self.token.next();
347        self.services.push(factory::create_factory_service(
348            name.as_ref().to_string(),
349            vec![(token, cfg.into())],
350            factory,
351        ));
352        self.sockets
353            .push((token, name.as_ref().to_string(), Listener::from_uds(lst)));
354        Ok(self)
355    }
356
357    /// Registers a service factory for an existing TCP listener.
358    ///
359    /// The listener is switched to non-blocking mode. See
360    /// [`bind`](Self::bind) for `cfg` and `factory`.
361    pub fn listen<F, S, I>(
362        mut self,
363        name: impl AsRef<str>,
364        lst: net::TcpListener,
365        cfg: impl Into<SharedCfg>,
366        factory: F,
367    ) -> io::Result<Self>
368    where
369        F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
370        S: Service<Cfg::State, Io> + 'static,
371        I: IntoService<S, Cfg::State, Io> + 'static,
372    {
373        let token = self.token.next();
374        self.services.push(factory::create_factory_service(
375            name.as_ref().to_string(),
376            vec![(token, cfg.into())],
377            factory,
378        ));
379        self.sockets
380            .push((token, name.as_ref().to_string(), Listener::from_tcp(lst)));
381        Ok(self)
382    }
383
384    /// Starts processing incoming connections and returns a server controller.
385    ///
386    /// # Panics
387    ///
388    /// Panics if no listener has been registered.
389    pub fn run(mut self) -> Server<Connection> {
390        assert!(
391            !self.sockets.is_empty(),
392            "Server should have at least one bound socket"
393        );
394        self.accept.acceptors(self.acceptors);
395
396        let names: Vec<_> = self
397            .sockets
398            .iter()
399            .map(|sock| (sock.1.clone(), sock.2.local_addr().to_string()))
400            .collect();
401        let use_reuseport = self.pool.balancing == LoadBalancing::Reuseport && {
402            let supported = cfg!(any(target_os = "linux", target_os = "android"))
403                && ntex_net::is_tcp_listener_supported();
404            if !supported {
405                log::warn!("Reuseport load balancing is not supported, using an accept thread");
406            }
407            supported
408        };
409
410        let workers = self.pool.num;
411        let mut slots: Vec<Sockets> = (0..workers).map(|_| Vec::new()).collect();
412        let mut accept_socks = Vec::new();
413        for (idx, (token, name, lst)) in self.sockets.into_iter().enumerate() {
414            log::info!("Starting \"{name}\" service on {lst}");
415            if use_reuseport && let Listener::Tcp(_) = lst {
416                let copies = replicate(&lst, workers - 1, self.backlog);
417                if copies.len() == workers - 1
418                    && let Listener::Tcp(lst) = lst
419                {
420                    slots[0].push((idx, token, lst));
421                    for (n, copy) in copies.into_iter().enumerate() {
422                        match copy {
423                            Listener::Tcp(copy) => slots[n + 1].push((idx, token, copy)),
424                            // replicate() creates tcp listeners only
425                            #[cfg(unix)]
426                            Listener::Uds(_) => {}
427                        }
428                    }
429                    continue;
430                }
431                log::warn!("Cannot replicate {lst}, using an accept thread");
432            }
433            accept_socks.push((idx, token, lst));
434        }
435        let reuseport = (use_reuseport && slots.iter().any(|s| !s.is_empty()))
436            .then(|| Arc::new(Reuseport::new(slots)));
437
438        let srv = StreamServer::new(
439            self.accept.notify(),
440            self.state,
441            self.services,
442            self.max_conns,
443            reuseport.clone(),
444        );
445        let svc = self.pool.run(srv);
446
447        svc.metrics_ref().listeners(names);
448        if let Some(rp) = reuseport
449            && let Some(metrics) = svc.metrics_ref().accept_slot()
450        {
451            rp.set_metrics(metrics);
452        }
453        if !accept_socks.is_empty() {
454            self.accept.start_with(accept_socks, &svc);
455        }
456
457        svc
458    }
459}
460
461impl<Cfg> fmt::Debug for ServerBuilder<Cfg> {
462    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463        f.debug_struct("ServerBuilder")
464            .field("name", &self.name)
465            .field("token", &self.token)
466            .field("backlog", &self.backlog)
467            .field("sockets", &self.sockets)
468            .field("accept", &self.accept)
469            .field("acceptors", &self.acceptors)
470            .field("max_conns", &self.max_conns)
471            .field("worker-pool", &self.pool)
472            .finish()
473    }
474}
475
476/// Binds TCP listeners for every address resolved from `addr`.
477///
478/// Succeeds if at least one address binds and returns only the listeners that
479/// bound. Otherwise, returns the last bind error.
480pub fn bind_addr<S: net::ToSocketAddrs>(
481    addr: S,
482    backlog: i32,
483) -> io::Result<Vec<net::TcpListener>> {
484    let mut err = None;
485    let mut succ = false;
486    let mut sockets = Vec::new();
487    for addr in addr.to_socket_addrs()? {
488        match create_tcp_listener(addr, backlog) {
489            Ok(lst) => {
490                succ = true;
491                sockets.push(lst);
492            }
493            Err(e) => err = Some(e),
494        }
495    }
496
497    if succ {
498        Ok(sockets)
499    } else if let Some(e) = err.take() {
500        Err(e)
501    } else {
502        Err(io::Error::new(
503            io::ErrorKind::InvalidInput,
504            "Cannot bind to address.",
505        ))
506    }
507}
508
509/// Creates and binds a TCP listener with the specified listen backlog.
510pub fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
511    let builder = match addr {
512        net::SocketAddr::V4(_) => Socket::new(Domain::IPV4, Type::STREAM, None)?,
513        net::SocketAddr::V6(_) => Socket::new(Domain::IPV6, Type::STREAM, None)?,
514    };
515
516    // On Windows, this allows rebinding sockets which are actively in use,
517    // which allows “socket hijacking”, so we explicitly don't set it here.
518    // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
519    #[cfg(not(windows))]
520    builder.set_reuse_address(true)?;
521
522    builder.bind(&SockAddr::from(addr))?;
523    builder.listen(backlog)?;
524    Ok(net::TcpListener::from(builder))
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530
531    /// STATEMENT: `bind_addr` fails when there are no addresses.
532    ///
533    /// HOW:
534    /// - Call it with an empty address list.
535    /// - Expect an error.
536    #[test]
537    fn test_bind_addr() {
538        let addrs: Vec<net::SocketAddr> = Vec::new();
539        assert!(bind_addr(&addrs[..], 10).is_err());
540    }
541
542    /// STATEMENT: `ServerBuilder` debug output names the type.
543    ///
544    /// HOW:
545    /// - Format a default builder.
546    /// - Expect `ServerBuilder` in the output.
547    #[ntex::test]
548    async fn test_debug() {
549        let builder = ServerBuilder::default();
550        assert!(format!("{builder:?}").contains("ServerBuilder"));
551    }
552
553    /// STATEMENT: A wakeup of a paused accept loop does not re-register its
554    /// listeners, so connections stay in the listen backlog until resume.
555    ///
556    /// HOW:
557    /// - Start a server, wait until it is ready, and pause it.
558    /// - Wake the paused accept loop with `AcceptorCommand::Timer`.
559    /// - Connect a client and check that the listener metrics count no
560    ///   accepted connection after 200ms.
561    /// - Resume the server and check that the connection is accepted.
562    #[ntex::test]
563    async fn test_paused_wakeup_does_not_accept() {
564        use crate::ServerStatus;
565        use crate::net::AcceptorCommand;
566        use ntex_service::{cfg::SharedCfg, fn_service};
567
568        let lst = net::TcpListener::bind("127.0.0.1:0").unwrap();
569        let addr = lst.local_addr().unwrap();
570        let builder = ServerBuilder::default()
571            .workers(1)
572            .acceptors(1)
573            .disable_signals()
574            .listen("test", lst, SharedCfg::default(), async |&()| {
575                fn_service(async |_: ntex_io::Io| Ok::<_, ()>(()))
576            })
577            .unwrap();
578        let notify = builder.accept.notify();
579        let srv = builder.run();
580        ntex_util::time::timeout(Millis(3000), async {
581            while srv.status() != ServerStatus::Ready {
582                srv.status_changed().await;
583            }
584        })
585        .await
586        .unwrap();
587
588        srv.pause().await;
589        ntex_util::time::sleep(Millis(100)).await;
590        notify.send(AcceptorCommand::Timer);
591        ntex_util::time::sleep(Millis(100)).await;
592
593        let _conn = net::TcpStream::connect(addr).unwrap();
594        ntex_util::time::sleep(Millis(200)).await;
595        assert_eq!(srv.metrics().listeners[0].accepted, 0);
596
597        srv.resume().await;
598        ntex_util::time::timeout(Millis(3000), async {
599            while srv.metrics().listeners[0].accepted == 0 {
600                ntex_util::time::sleep(Millis(10)).await;
601            }
602        })
603        .await
604        .unwrap();
605        srv.stop(false).await;
606    }
607}