Skip to main content

net_io/server/
mod.rs

1//! The server: listeners, workers, the door, drain, and shutdown.
2
3mod engine;
4#[cfg(feature = "reactor")]
5mod reactor;
6mod source;
7
8use std::any::TypeId;
9use std::fmt;
10use std::net::{SocketAddr, ToSocketAddrs};
11use std::path::PathBuf;
12use std::sync::Arc;
13use std::thread::JoinHandle;
14use std::time::{Duration, Instant};
15
16use crate::control::ControlLine;
17use crate::driver::DriverKind;
18use crate::error::{CloseReason, ConfigReason, KillReason, NetError, RefusalCause};
19use crate::events::{EventSink, NoopSink};
20use crate::gate::Gate;
21use crate::handoff::ListenerHandle;
22use crate::id::{ConnectionId, ListenerId, WorkerId};
23use crate::limits::Limits;
24use crate::opts::{ListenOptions, LocalOptions};
25use crate::proxy::ProxyMode;
26use crate::session::SessionFactory;
27use crate::tcp::{ListenerInfo, TcpConnection};
28use crate::time::Clock;
29use crate::tls::ErasedAcceptor;
30use crate::tls::{NoTls, TlsAcceptor};
31use crate::trusted::TrustedProxies;
32
33pub(crate) use engine::Shared;
34
35/// Whether the server is accepting.
36///
37/// ```
38/// assert_ne!(net_io::DoorState::Open, net_io::DoorState::Closed);
39/// ```
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum DoorState {
42    /// Accepting new connections.
43    Open,
44    /// Not accepting; listening sockets stay open.
45    Closed,
46}
47
48/// What a drain did.
49///
50/// ```
51/// let r = net_io::DrainReport { graceful: 3, killed: 1, took: std::time::Duration::from_millis(40) };
52/// assert_eq!(r.graceful + r.killed, 4);
53/// ```
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub struct DrainReport {
56    /// Connections that finished before the deadline.
57    pub graceful: u32,
58    /// Connections killed at the deadline.
59    pub killed: u32,
60    /// How long the drain took.
61    pub took: Duration,
62}
63
64/// Counters summed over the workers.
65///
66/// ```no_run
67/// let server = net_io::serve("127.0.0.1:0", |_c| Ok(()))?;
68/// let stats = server.stats();
69/// println!("{} open, {} accepted", stats.open, stats.accepted);
70/// # Ok::<(), net_io::NetError>(())
71/// ```
72#[non_exhaustive]
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub struct Stats {
75    /// Connections open now.
76    pub open: u64,
77    /// Connections accepted.
78    pub accepted: u64,
79    /// Connections refused.
80    pub refused: u64,
81    /// Connections closed.
82    pub closed: u64,
83    /// Bytes received.
84    pub bytes_in: u64,
85    /// Bytes sent.
86    pub bytes_out: u64,
87    /// Writes the gate denied.
88    pub egress_denied: u64,
89    /// Connections killed.
90    pub killed: u64,
91    /// Connections closed for the minimum rate.
92    pub slow_peers: u64,
93    /// Connections closed by a timeout.
94    pub timeouts: u64,
95    /// Times the process ran out of descriptors.
96    pub descriptor_pressure: u64,
97    /// Completions for connections that had closed.
98    pub stale_completions: u64,
99    /// Sessions that panicked.
100    pub session_panics: u64,
101    /// Reactor workers whose loop ended on a panic or a failed wait. Such a worker
102    /// takes no more connections (the others take them, and its own listening
103    /// sockets, instead); its connections were closed when it ended.
104    pub workers_lost: u64,
105    /// Worker threads a stop left running: their connection was killed at the
106    /// drain's deadline, but its owner did not return within the grace after it (a
107    /// blocking handler that never touches its socket). Each ends on its own.
108    pub workers_detached: u64,
109    refused_by: [u64; RefusalCause::COUNT],
110    closed_by: [u64; CloseReason::COUNT],
111}
112
113impl Stats {
114    /// Refusals with this cause (gate codes summed).
115    #[must_use]
116    pub fn refused_for(&self, cause: RefusalCause) -> u64 {
117        self.refused_by[cause.index()]
118    }
119
120    /// Closes with this reason's variant (inner values ignored).
121    #[must_use]
122    pub fn closed_for(&self, reason: CloseReason) -> u64 {
123        self.closed_by[reason.index()]
124    }
125
126    /// Every close reason with a non-zero count, one entry per variant (inner
127    /// values are not kept: `Killed` carries reason 0, `Io` class `Other(0)`).
128    ///
129    /// ```no_run
130    /// let server = net_io::serve("127.0.0.1:0", |_c| Ok(()))?;
131    /// for (reason, n) in server.stats().closes() {
132    ///     println!("{}: {n}", reason.as_str());
133    /// }
134    /// # Ok::<(), net_io::NetError>(())
135    /// ```
136    pub fn closes(&self) -> impl Iterator<Item = (CloseReason, u64)> + '_ {
137        CloseReason::BY_INDEX
138            .iter()
139            .zip(self.closed_by.iter())
140            .filter(|(_, n)| **n > 0)
141            .map(|(r, n)| (*r, *n))
142    }
143
144    /// Every refusal cause with a non-zero count (gate codes summed under `Gate(0)`).
145    pub fn refusals(&self) -> impl Iterator<Item = (RefusalCause, u64)> + '_ {
146        RefusalCause::BY_INDEX
147            .iter()
148            .zip(self.refused_by.iter())
149            .filter(|(_, n)| **n > 0)
150            .map(|(r, n)| (*r, *n))
151    }
152}
153
154/// One listener of a server.
155///
156/// ```
157/// use net_io::{ListenerSpec, Limits};
158/// let spec = ListenerSpec::tcp("127.0.0.1:0")
159///     .name("admin")
160///     .limits(Limits::builder().max_per_listener(10).build()?);
161/// # let _ = spec;
162/// # Ok::<(), net_io::NetError>(())
163/// ```
164#[must_use]
165#[derive(Debug)]
166pub struct ListenerSpec {
167    pub(crate) addrs: Result<Vec<SocketAddr>, String>,
168    pub(crate) options: Option<ListenOptions>,
169    pub(crate) name: Option<String>,
170    pub(crate) limits: Limits,
171    pub(crate) proxy: ProxyMode,
172    pub(crate) trusted: Option<Arc<TrustedProxies>>,
173    pub(crate) tls: bool,
174    pub(crate) unix: Option<(PathBuf, LocalOptions)>,
175    #[cfg(all(windows, feature = "local"))]
176    pub(crate) pipe: Option<(String, crate::pipe::PipeOptions)>,
177    #[cfg(feature = "udp")]
178    pub(crate) udp: Option<crate::udp::UdpOptions>,
179    pub(crate) adopt: Option<ListenerHandle>,
180    pub(crate) lockdown_allowed: bool,
181    /// Reactor workers of this listener's own (`ListenerSpec::workers`).
182    pub(crate) workers: Option<u16>,
183}
184
185impl ListenerSpec {
186    /// The global cap is the server's: a listener caps itself with
187    /// `max_per_listener`. Taking `max_connections` here would let a listener lift
188    /// the server's cap and the descriptor budget checked against it.
189    fn check_listener_limits(&self) -> Result<(), NetError> {
190        if self.limits.max_connections().is_some() {
191            return Err(NetError::InvalidConfig {
192                field: "max_connections",
193                reason: ConfigReason::Inconsistent,
194            });
195        }
196        Ok(())
197    }
198
199    /// A TCP listener on `addr` (resolved now; a failure is reported by `build`).
200    pub fn tcp<A: ToSocketAddrs>(addr: A) -> ListenerSpec {
201        ListenerSpec {
202            addrs: addr
203                .to_socket_addrs()
204                .map(|i| i.collect())
205                .map_err(|e| e.to_string()),
206            options: None,
207            name: None,
208            limits: Limits::default(),
209            proxy: ProxyMode::Off,
210            trusted: None,
211            tls: false,
212            unix: None,
213            #[cfg(all(windows, feature = "local"))]
214            pipe: None,
215            #[cfg(feature = "udp")]
216            udp: None,
217            adopt: None,
218            lockdown_allowed: false,
219            workers: None,
220        }
221    }
222
223    /// Keeps admitting under `ControlState::Lockdown`, for the listener an operator
224    /// comes in through while everything else is refused.
225    pub fn lockdown_allowed(mut self, on: bool) -> ListenerSpec {
226        self.lockdown_allowed = on;
227        self
228    }
229
230    /// On the reactor, `n` workers of this listener's own, besides the server's
231    /// `workers`: its connections run only there, and no other listener's do, so a
232    /// flood on a public listener cannot take an admin listener's threads (serve-net
233    /// request 6). Fixed at build: `Server::add_listener` refuses it, as do the
234    /// blocking driver (keep its threads with `Limits::lane_reserve`) and per-worker
235    /// listeners (`InvalidConfig`). Each worker is a thread and an event loop.
236    ///
237    /// ```
238    /// use net_io::ListenerSpec;
239    /// let admin = ListenerSpec::tcp("127.0.0.1:9900").workers(1);
240    /// # let _ = admin;
241    /// ```
242    pub fn workers(mut self, n: u16) -> ListenerSpec {
243        self.workers = Some(n);
244        self
245    }
246
247    /// A TCP listener with explicit options (their backlog wins over the limits').
248    pub fn tcp_with<A: ToSocketAddrs>(addr: A, options: ListenOptions) -> ListenerSpec {
249        ListenerSpec {
250            options: Some(options),
251            ..ListenerSpec::tcp(addr)
252        }
253    }
254
255    /// A UDP socket served by the [`UdpSession`](crate::UdpSession) that
256    /// `ServerBuilder::udp_sessions` makes (feature `udp`). A thread of its own reads
257    /// it, with the door and a stop like any listener, and the socket's budgets and
258    /// amplification guard apply.
259    ///
260    /// ```
261    /// use net_io::{ListenerSpec, UdpOptions};
262    /// let spec = ListenerSpec::udp("0.0.0.0:5353", UdpOptions::new());
263    /// # let _ = spec;
264    /// ```
265    #[cfg(feature = "udp")]
266    pub fn udp<A: ToSocketAddrs>(addr: A, options: crate::udp::UdpOptions) -> ListenerSpec {
267        ListenerSpec {
268            udp: Some(options),
269            ..ListenerSpec::tcp(addr)
270        }
271    }
272
273    /// A named pipe listener on `\\\\.\\pipe\\<name>` (feature `local`, Windows).
274    /// Remote clients are always rejected, and connections carry `Transport::Pipe`,
275    /// the client's pid, and no IP address: the per-source cap does not apply. With
276    /// `proxy`, every peer is trusted: the pipe's security decides who may connect.
277    ///
278    /// ```no_run
279    /// use net_io::{ListenerSpec, PipeOptions};
280    /// let spec = ListenerSpec::pipe("myapp-control", PipeOptions::new());
281    /// # let _ = spec;
282    /// ```
283    #[cfg(all(windows, feature = "local"))]
284    pub fn pipe(name: &str, options: crate::pipe::PipeOptions) -> ListenerSpec {
285        ListenerSpec {
286            pipe: Some((name.to_owned(), options)),
287            ..ListenerSpec::tcp(std::net::SocketAddr::from(([127, 0, 0, 1], 0)))
288        }
289    }
290
291    /// A Unix domain socket listener at `path` (feature `local`; on Windows, AF_UNIX,
292    /// where NTFS ACLs replace `options`' mode and owner). The socket file gets
293    /// `options`' mode and owner before it listens, and is removed at shutdown if it
294    /// is still the file this server created. Connections carry `Transport::Unix`, the peer's
295    /// credentials, and no IP address: the per-source cap does not apply, and a
296    /// `BlockingHandler` receives them as a `TcpConnection` whose `peer_addr` is
297    /// unspecified. With `proxy`, every peer is trusted: the socket file's
298    /// permissions decide who may connect.
299    ///
300    /// ```
301    /// use net_io::{ListenerSpec, LocalOptions};
302    /// let spec = ListenerSpec::unix("/run/myapp/api.sock", LocalOptions::new().group_access(33));
303    /// # let _ = spec;
304    /// ```
305    pub fn unix(path: impl Into<PathBuf>, options: LocalOptions) -> ListenerSpec {
306        ListenerSpec {
307            addrs: Ok(Vec::new()),
308            options: None,
309            name: None,
310            limits: Limits::default(),
311            proxy: ProxyMode::Off,
312            trusted: None,
313            tls: false,
314            unix: Some((path.into(), options)),
315            lockdown_allowed: false,
316            workers: None,
317            #[cfg(all(windows, feature = "local"))]
318            pipe: None,
319            #[cfg(feature = "udp")]
320            udp: None,
321            adopt: None,
322        }
323    }
324
325    /// A listener this process was given: inherited from systemd or a FastCGI
326    /// manager, received in a hand-off, or released by another server. Its name
327    /// is the handle's unless [`ListenerSpec::name`] sets one. The socket is not
328    /// bound again; options set at bind time stay as they are, and the backlog is
329    /// reported as unknown. An adopted Unix socket's file is left in place at
330    /// shutdown (the next bind removes it as stale).
331    ///
332    /// ```no_run
333    /// use net_io::ListenerSpec;
334    /// for inherited in net_io::systemd()? {
335    ///     let spec = ListenerSpec::adopt(inherited.handle);
336    ///     # let _ = spec;
337    /// }
338    /// # Ok::<(), net_io::InheritError>(())
339    /// ```
340    pub fn adopt(handle: ListenerHandle) -> ListenerSpec {
341        ListenerSpec {
342            addrs: Ok(Vec::new()),
343            options: None,
344            name: None,
345            limits: Limits::default(),
346            proxy: ProxyMode::Off,
347            trusted: None,
348            tls: false,
349            unix: None,
350            #[cfg(all(windows, feature = "local"))]
351            pipe: None,
352            #[cfg(feature = "udp")]
353            udp: None,
354            adopt: Some(handle),
355            lockdown_allowed: false,
356            workers: None,
357        }
358    }
359
360    /// A name (up to 64 bytes) for events and hand-off.
361    pub fn name(mut self, name: &str) -> ListenerSpec {
362        self.name = Some(name.to_owned());
363        self
364    }
365
366    /// Per-listener caps and deadlines; values set here override the server's.
367    pub fn limits(mut self, limits: Limits) -> ListenerSpec {
368        self.limits = limits;
369        self
370    }
371
372    /// Requires a PROXY protocol header on every connection (feature `proxy`).
373    /// Peers outside the trusted proxies are closed before any byte is read.
374    ///
375    /// ```
376    /// use net_io::{ListenerSpec, ProxyMode, ProxyVersions};
377    /// let spec = ListenerSpec::tcp("127.0.0.1:0").proxy(ProxyMode::Required { versions: ProxyVersions::Both });
378    /// # let _ = spec;
379    /// ```
380    pub fn proxy(mut self, mode: ProxyMode) -> ListenerSpec {
381        self.proxy = mode;
382        self
383    }
384
385    /// Serves TLS on this listener through the builder's acceptor
386    /// ([`ServerBuilder::tls`], feature `tls`).
387    pub fn tls(mut self, on: bool) -> ListenerSpec {
388        self.tls = on;
389        self
390    }
391
392    /// The proxies trusted on this listener, instead of the server's list.
393    pub fn trusted_proxies(mut self, proxies: TrustedProxies) -> ListenerSpec {
394        self.trusted = Some(Arc::new(proxies));
395        self
396    }
397}
398
399/// What runs per connection; the unset state (no `build` exists for it).
400#[derive(Clone, Copy, Debug, Default)]
401pub struct NoWork;
402
403/// What `ServerBuilder::udp_sessions` produces when a server has no TCP work; programs
404/// never name it.
405#[cfg(feature = "udp")]
406#[derive(Debug)]
407pub struct UdpOnly;
408
409/// The builder's gate until `ServerBuilder::gate` names one: every connection is
410/// admitted, in the most important lane, as with [`AllowAll`](crate::AllowAll), and
411/// no gate check runs on the write path.
412///
413/// ```
414/// use net_io::{AdmitStage, ConnectionInfo, Gate, NoGate};
415/// let info = ConnectionInfo::for_testing("127.0.0.1:9".parse().unwrap());
416/// assert!(NoGate.admit(&info, AdmitStage::Accept).is_ok());
417/// ```
418#[derive(Clone, Copy, Debug, Default)]
419pub struct NoGate;
420
421impl Gate for NoGate {
422    type Ticket = ();
423    #[inline(always)]
424    fn admit(
425        &self,
426        _info: &crate::info::ConnectionInfo,
427        _stage: crate::gate::AdmitStage,
428    ) -> Result<crate::gate::Admitted<()>, crate::gate::Refusal> {
429        Ok(crate::gate::Admitted {
430            lane: crate::info::Lane::MOST_IMPORTANT,
431            ticket: (),
432            tag: crate::info::GateTag(0),
433        })
434    }
435    #[inline(always)]
436    fn readmit(
437        &self,
438        _ticket: &mut (),
439        _info: &crate::info::ConnectionInfo,
440    ) -> Result<(), crate::gate::Refusal> {
441        Ok(())
442    }
443    #[inline(always)]
444    fn check(
445        &self,
446        _ticket: &mut (),
447        _write: &crate::gate::WriteCheck,
448    ) -> Result<(), crate::gate::Denial> {
449        Ok(())
450    }
451}
452
453/// Where workers run.
454///
455/// ```
456/// let pinned = net_io::Placement::Explicit(vec![0, 2, 4, 6]);
457/// # let _ = pinned;
458/// ```
459#[non_exhaustive]
460#[derive(Clone, Debug, Default, PartialEq, Eq)]
461pub enum Placement {
462    /// The OS decides.
463    #[default]
464    Off,
465    /// Worker `n` on CPU `n`, wrapping around.
466    PinPerCore,
467    /// Worker `n` on `cpus[n % cpus.len()]`.
468    Explicit(Vec<usize>),
469}
470
471/// What `ServerBuilder::sessions` produces; programs never name it.
472#[derive(Debug)]
473pub struct Sessions<F> {
474    pub(crate) factory: F,
475}
476
477#[cfg(feature = "reactor")]
478impl<F> Sessions<F> {
479    pub(crate) fn factory(&self) -> &F {
480        &self.factory
481    }
482}
483
484/// What `ServerBuilder::handler` produces; programs never name it.
485pub struct BlockingHandler<H> {
486    pub(crate) handler: H,
487}
488
489impl<H> fmt::Debug for BlockingHandler<H> {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        f.write_str("BlockingHandler")
492    }
493}
494
495pub(crate) mod sealed {
496    pub trait Sealed {}
497}
498
499/// What runs per connection: [`Sessions`] or a [`BlockingHandler`]. Sealed.
500pub trait Workload: sealed::Sealed + engine::Serve + Send + Sync + 'static {}
501
502#[cfg(feature = "udp")]
503impl sealed::Sealed for UdpOnly {}
504#[cfg(feature = "udp")]
505impl Workload for UdpOnly {}
506
507impl<F: SessionFactory> sealed::Sealed for Sessions<F> {}
508impl<F: SessionFactory> Workload for Sessions<F> {}
509
510impl<H> sealed::Sealed for BlockingHandler<H> where
511    H: Fn(&mut TcpConnection) -> Result<(), NetError> + Send + Sync + 'static
512{
513}
514impl<H> Workload for BlockingHandler<H> where
515    H: Fn(&mut TcpConnection) -> Result<(), NetError> + Send + Sync + 'static
516{
517}
518
519/// Builds a [`Server`]. A builder without `sessions`/`handler` has no `build`
520/// method: forgetting it is a compile error. Without `gate` every connection is
521/// admitted ([`NoGate`], as [`AllowAll`](crate::AllowAll)).
522///
523/// # Examples
524///
525/// ```no_run
526/// use net_io::{AllowAll, DriverKind, Limits, ListenerSpec, ServerBuilder};
527/// use std::time::{Duration, Instant};
528///
529/// let server = ServerBuilder::new()
530///     .listener(ListenerSpec::tcp("0.0.0.0:8080").name("public"))
531///     .listener(ListenerSpec::tcp("127.0.0.1:9090").name("admin"))
532///     .driver(DriverKind::Blocking)
533///     .workers(64)
534///     .limits(Limits::builder().idle_timeout(Duration::from_secs(5)).build()?)
535///     .handler(|conn| { conn.send_all(b"hello\n")?; Ok(()) })
536///     .gate(AllowAll)
537///     .build()?;              // listeners bound, workers started, door closed
538/// // ... drop privileges here ...
539/// server.open_door()?;
540/// let report = server.shutdown(Instant::now() + Duration::from_secs(30));
541/// println!("{report:?}");
542/// # Ok::<(), net_io::NetError>(())
543/// ```
544#[must_use]
545pub struct ServerBuilder<W = NoWork, G = NoGate, S = NoopSink, T = NoTls> {
546    listeners: Vec<ListenerSpec>,
547    driver: DriverKind,
548    workers: Option<u16>,
549    limits: Limits,
550    work: W,
551    gate: G,
552    sink: S,
553    tls: T,
554    control: Option<Arc<dyn ControlLine>>,
555    wipe: bool,
556    clock: Option<Arc<dyn Clock>>,
557    trusted: Option<Arc<TrustedProxies>>,
558    placement: Placement,
559    #[cfg(feature = "udp")]
560    udp: Option<Arc<dyn crate::udp::UdpSessionFactory>>,
561}
562
563impl ServerBuilder {
564    /// An empty builder.
565    pub fn new() -> ServerBuilder {
566        ServerBuilder {
567            listeners: Vec::new(),
568            driver: DriverKind::Auto,
569            workers: None,
570            limits: Limits::default(),
571            work: NoWork,
572            gate: NoGate,
573            sink: NoopSink,
574            tls: NoTls,
575            control: None,
576            wipe: true,
577            clock: None,
578            trusted: None,
579            placement: Placement::Off,
580            #[cfg(feature = "udp")]
581            udp: None,
582        }
583    }
584}
585
586impl Default for ServerBuilder {
587    fn default() -> ServerBuilder {
588        ServerBuilder::new()
589    }
590}
591
592impl<W, G, S, T> ServerBuilder<W, G, S, T> {
593    fn map<W2, G2, S2, T2>(
594        self,
595        f: impl FnOnce(W, G, S, T) -> (W2, G2, S2, T2),
596    ) -> ServerBuilder<W2, G2, S2, T2> {
597        let ServerBuilder {
598            listeners,
599            driver,
600            workers,
601            limits,
602            work,
603            gate,
604            sink,
605            tls,
606            control,
607            wipe,
608            clock,
609            trusted,
610            placement,
611            #[cfg(feature = "udp")]
612            udp,
613        } = self;
614        let (work, gate, sink, tls) = f(work, gate, sink, tls);
615        ServerBuilder {
616            listeners,
617            driver,
618            workers,
619            limits,
620            work,
621            gate,
622            sink,
623            tls,
624            control,
625            wipe,
626            clock,
627            trusted,
628            placement,
629            #[cfg(feature = "udp")]
630            udp,
631        }
632    }
633
634    /// The proxies whose PROXY headers are believed, for every listener that
635    /// requires one and has no list of its own.
636    pub fn trusted_proxies(mut self, proxies: TrustedProxies) -> Self {
637        self.trusted = Some(Arc::new(proxies));
638        self
639    }
640
641    /// Adds a listener (at most 64).
642    pub fn listener(mut self, spec: ListenerSpec) -> Self {
643        self.listeners.push(spec);
644        self
645    }
646
647    /// The driver (default `Auto`).
648    pub fn driver(mut self, kind: DriverKind) -> Self {
649        self.driver = kind;
650        self
651    }
652
653    /// Pins workers to CPUs (`Unsupported` on macOS). A worker that stays on one CPU
654    /// keeps its cache; the cost is that the OS can no longer move it off a busy CPU.
655    pub fn placement(mut self, placement: Placement) -> Self {
656        self.placement = placement;
657        self
658    }
659
660    /// Worker threads (default 128 on the blocking driver; 1 to 4,096).
661    pub fn workers(mut self, n: u16) -> Self {
662        self.workers = Some(n);
663        self
664    }
665
666    /// The server's limits; unset values take the driver's defaults.
667    pub fn limits(mut self, limits: Limits) -> Self {
668        self.limits = limits;
669        self
670    }
671
672    /// Runs a sans-IO session per connection.
673    pub fn sessions<F: SessionFactory>(self, factory: F) -> ServerBuilder<Sessions<F>, G, S, T> {
674        self.map(|_, g, s, t| (Sessions { factory }, g, s, t))
675    }
676
677    /// Runs a blocking handler per connection (on the blocking driver).
678    pub fn handler<H>(self, handler: H) -> ServerBuilder<BlockingHandler<H>, G, S, T>
679    where
680        H: Fn(&mut TcpConnection) -> Result<(), NetError> + Send + Sync + 'static,
681    {
682        self.map(|_, g, s, t| (BlockingHandler { handler }, g, s, t))
683    }
684
685    /// The TLS engine for listeners with `ListenerSpec::tls(true)` (feature `tls`).
686    pub fn tls<T2: TlsAcceptor>(self, acceptor: T2) -> ServerBuilder<W, G, S, T2> {
687        self.map(|w, g, s, _| (w, g, s, acceptor))
688    }
689
690    /// The connection gate (default: none, every connection admitted).
691    pub fn gate<G2: Gate>(self, gate: G2) -> ServerBuilder<W, G2, S, T> {
692        self.map(|w, _, s, t| (w, gate, s, t))
693    }
694
695    /// The event sink (default `NoopSink`).
696    pub fn events<S2: EventSink>(self, sink: S2) -> ServerBuilder<W, G, S2, T> {
697        self.map(|w, g, _, t| (w, g, sink, t))
698    }
699
700    /// The control line (default: none).
701    pub fn control<C: ControlLine>(mut self, line: Arc<C>) -> Self {
702        self.control = Some(line);
703        self
704    }
705
706    /// Zero the used part of every buffer when it returns to a pool (default on).
707    pub fn wipe_buffers(mut self, on: bool) -> Self {
708        self.wipe = on;
709        self
710    }
711
712    /// The clock deadlines read (tests inject a `ManualClock`).
713    pub fn clock<K: Clock>(mut self, clock: Arc<K>) -> Self {
714        self.clock = Some(clock);
715        self
716    }
717}
718
719#[cfg(feature = "udp")]
720impl<G, S, T> ServerBuilder<NoWork, G, S, T> {
721    /// Serves UDP listeners only; a TCP listener then fails `build`. One thread per
722    /// listener, and no worker pool.
723    ///
724    /// ```no_run
725    /// use std::net::SocketAddr;
726    /// use net_io::{AllowAll, ListenerInfo, ListenerSpec, ServerBuilder, UdpContext, UdpOptions, UdpSession};
727    /// struct Echo;
728    /// impl UdpSession for Echo {
729    ///     fn on_datagram(&mut self, cx: &mut UdpContext<'_>, from: SocketAddr, bytes: &[u8]) {
730    ///         let _ = cx.send_to(bytes, from);
731    ///     }
732    /// }
733    /// let server = ServerBuilder::new()
734    ///     .listener(ListenerSpec::udp("0.0.0.0:7000", UdpOptions::new()))
735    ///     .udp_sessions(|_: &ListenerInfo| Echo)
736    ///     .gate(AllowAll)
737    ///     .build()?;
738    /// server.open_door()?;
739    /// # Ok::<(), net_io::NetError>(())
740    /// ```
741    pub fn udp_sessions<F>(self, factory: F) -> ServerBuilder<UdpOnly, G, S, T>
742    where
743        F: crate::udp::UdpSessionFactory,
744    {
745        let mut b = self.map(|_, g, s, t| (UdpOnly, g, s, t));
746        b.udp = Some(Arc::new(factory));
747        b.workers.get_or_insert(1);
748        b
749    }
750}
751
752#[cfg(feature = "udp")]
753impl<W: Workload, G, S, T> ServerBuilder<W, G, S, T> {
754    /// Serves the UDP listeners beside this server's TCP work.
755    pub fn udp_sessions<F>(mut self, factory: F) -> Self
756    where
757        F: crate::udp::UdpSessionFactory,
758    {
759        self.udp = Some(Arc::new(factory));
760        self
761    }
762}
763
764impl<W, G, S, T> ServerBuilder<W, G, S, T>
765where
766    W: Workload,
767    G: Gate,
768    S: EventSink,
769    T: TlsAcceptor,
770{
771    /// Validates everything, binds the listeners, starts the workers, and returns
772    /// the server with the door **closed**.
773    ///
774    /// # Errors
775    ///
776    /// `InvalidConfig` (`field` names the method), bind errors, `Unsupported` for a
777    /// driver this version does not have.
778    pub fn build(self) -> Result<Server, NetError> {
779        // A handler holds its worker for the whole connection (blocking pool only).
780        let requested = match self.driver {
781            DriverKind::Auto if <W as engine::Serve>::BLOCKING_ONLY => DriverKind::Blocking,
782            other => other,
783        };
784        let driver = match requested.resolve() {
785            DriverKind::Reactor if <W as engine::Serve>::BLOCKING_ONLY => {
786                return Err(invalid("driver", ConfigReason::Inconsistent));
787            }
788            DriverKind::Reactor if !DriverKind::reactor_built() => {
789                return Err(NetError::Unsupported {
790                    feature: "the reactor driver",
791                    platform: std::env::consts::OS,
792                });
793            }
794            DriverKind::Uring => {
795                return Err(NetError::Unsupported {
796                    feature: "the io_uring driver (after 1.0.0)",
797                    platform: std::env::consts::OS,
798                });
799            }
800            kind => kind,
801        };
802        if self.listeners.is_empty() {
803            return Err(invalid("listener", ConfigReason::Missing));
804        }
805        if self.listeners.len() > 64 {
806            return Err(invalid("listener", ConfigReason::TooLarge { max: 64 }));
807        }
808        let workers = self.workers.unwrap_or_else(|| {
809            if driver == DriverKind::Reactor {
810                std::thread::available_parallelism()
811                    .map_or(4, |n| u16::try_from(n.get()).unwrap_or(4096).min(4096))
812            } else {
813                128
814            }
815        });
816        if workers == 0 {
817            return Err(invalid("workers", ConfigReason::Zero));
818        }
819        if workers > 4096 {
820            return Err(invalid("workers", ConfigReason::TooLarge { max: 4096 }));
821        }
822        let mut listeners = self.listeners;
823        let has_tls = TypeId::of::<T>() != TypeId::of::<NoTls>();
824        let mut names = Vec::new();
825        #[cfg(feature = "udp")]
826        for spec in &listeners {
827            if (spec.udp.is_some() && self.udp.is_none())
828                || (spec.udp.is_none() && <W as engine::Serve>::UDP_ONLY)
829            {
830                return Err(invalid("udp_sessions", ConfigReason::Inconsistent));
831            }
832            if spec.udp.is_some() && (spec.tls || spec.proxy != ProxyMode::Off) {
833                return Err(invalid("udp", ConfigReason::Inconsistent));
834            }
835        }
836        for spec in &mut listeners {
837            check_spec(spec, self.trusted.as_ref(), has_tls, &names)?;
838            if let Some(n) = &spec.name {
839                names.push(n.clone());
840            }
841        }
842        // On the blocking driver an unset global cap is one connection per worker;
843        // on the reactor the default, but never more than the descriptors allow.
844        let limits = if self.limits.max_connections().is_none() {
845            let cap = if driver == DriverKind::Reactor {
846                reactor_default_cap(workers)
847            } else {
848                u32::from(workers)
849            };
850            self.limits.to_builder().max_connections(cap).build()?
851        } else {
852            self.limits.clone()
853        };
854        limits.validate_for(driver, workers, crate::sys::descriptor_limit())?;
855        for spec in &listeners {
856            spec.check_listener_limits()?;
857            limits
858                .overlay(&spec.limits)
859                .validate_for(driver, workers, None)?;
860        }
861        if self.placement != Placement::Off && !crate::sys::CAN_PIN {
862            return Err(NetError::Unsupported {
863                feature: "worker placement",
864                platform: std::env::consts::OS,
865            });
866        }
867        if self.placement == Placement::Explicit(Vec::new()) {
868            return Err(invalid("placement", ConfigReason::Zero));
869        }
870        let tls: Option<Arc<dyn ErasedAcceptor>> = if has_tls {
871            Some(Arc::new(self.tls))
872        } else {
873            None
874        };
875        engine::start(engine::Config {
876            tls,
877            trusted: self.trusted,
878            listeners,
879            driver,
880            workers,
881            limits,
882            work: self.work,
883            gate: self.gate,
884            sink: self.sink,
885            control: self.control,
886            wipe: self.wipe,
887            clock: self.clock,
888            placement: self.placement,
889            #[cfg(feature = "udp")]
890            udp: self.udp,
891        })
892    }
893}
894
895/// The reactor's default global cap: 10,000, less where the process's descriptor
896/// limit would not hold it.
897fn reactor_default_cap(workers: u16) -> u32 {
898    let wanted = 10_000u32;
899    match crate::sys::descriptor_limit() {
900        Some(have) => {
901            let spare = u64::from(workers).saturating_mul(2) + 64;
902            let room = have.saturating_sub(spare).clamp(16, u64::from(wanted));
903            u32::try_from(room).unwrap_or(wanted)
904        }
905        None => wanted,
906    }
907}
908
909fn invalid(field: &'static str, reason: ConfigReason) -> NetError {
910    NetError::InvalidConfig { field, reason }
911}
912
913/// Where `Server::adopt` registers a connection: the listener (by name) whose
914/// limits and caps apply, and an optional starting lane (the gate may change it).
915///
916/// ```
917/// let spec = net_io::AdoptSpec::new("main").lane(net_io::Lane(1));
918/// # let _ = spec;
919/// ```
920#[must_use]
921#[derive(Clone, Debug, PartialEq, Eq)]
922pub struct AdoptSpec {
923    listener: String,
924    lane: Option<crate::info::Lane>,
925}
926
927impl AdoptSpec {
928    /// Registers on the listener named `listener`.
929    pub fn new(listener: &str) -> AdoptSpec {
930        AdoptSpec {
931            listener: listener.to_owned(),
932            lane: None,
933        }
934    }
935
936    /// The lane the connection starts in, before the gate's admission.
937    pub fn lane(mut self, lane: crate::info::Lane) -> AdoptSpec {
938        self.lane = Some(lane);
939        self
940    }
941}
942
943/// The checks `build` and `add_listener` run on one listener: the features it
944/// needs, a TLS engine, trusted proxies (resolved into the spec), and its name.
945fn check_spec(
946    spec: &mut ListenerSpec,
947    server_trusted: Option<&Arc<TrustedProxies>>,
948    has_tls: bool,
949    taken: &[String],
950) -> Result<(), NetError> {
951    if spec.name.is_none() {
952        spec.name = spec
953            .adopt
954            .as_ref()
955            .and_then(|h| h.name())
956            .map(str::to_owned);
957    }
958    let unix = spec.unix.is_some()
959        || spec
960            .adopt
961            .as_ref()
962            .is_some_and(|h| h.kind() == crate::info::Transport::Unix);
963    if unix && !cfg!(feature = "local") {
964        return Err(NetError::Unsupported {
965            feature: "Unix domain sockets (the `local` feature)",
966            platform: std::env::consts::OS,
967        });
968    }
969    if spec.tls {
970        if !cfg!(feature = "tls") {
971            return Err(NetError::Unsupported {
972                feature: "TLS (the `tls` feature)",
973                platform: std::env::consts::OS,
974            });
975        }
976        if !has_tls {
977            return Err(invalid("tls", ConfigReason::Missing));
978        }
979    }
980    if spec.proxy != ProxyMode::Off {
981        if !cfg!(feature = "proxy") {
982            return Err(NetError::Unsupported {
983                feature: "PROXY protocol (the `proxy` feature)",
984                platform: std::env::consts::OS,
985            });
986        }
987        // On a Unix socket the file's permissions decide who may connect.
988        if !unix {
989            let trusted = spec.trusted.clone().or_else(|| server_trusted.cloned());
990            match trusted {
991                Some(t) if !t.is_empty() => spec.trusted = Some(t),
992                // Required without anyone to trust would refuse every connection.
993                _ => return Err(invalid("trusted_proxies", ConfigReason::Missing)),
994            }
995        }
996    }
997    if let Some(n) = &spec.name {
998        if n.len() > 64 {
999            return Err(invalid("name", ConfigReason::TooLarge { max: 64 }));
1000        }
1001        if taken.contains(n) {
1002            return Err(invalid("name", ConfigReason::Inconsistent));
1003        }
1004    }
1005    Ok(())
1006}
1007
1008/// A running server. Dropping it stops it (with a drain), so keep it and call
1009/// [`Server::wait_for_stop`] to run until a stop is requested.
1010#[must_use = "dropping a Server stops it; call wait_for_stop() to run until a stop is requested"]
1011pub struct Server {
1012    pub(crate) shared: Arc<Shared>,
1013    pub(crate) threads: Vec<JoinHandle<()>>,
1014    pub(crate) listeners: Vec<ListenerInfo>,
1015    pub(crate) stopped: bool,
1016}
1017
1018impl Server {
1019    /// Starts accepting on every listener; a second call is a no-op.
1020    ///
1021    /// # Errors
1022    ///
1023    /// `ShuttingDown` while draining or after shutdown; `ForkedChild`.
1024    pub fn open_door(&self) -> Result<(), NetError> {
1025        self.shared.open_door()
1026    }
1027
1028    /// Stops accepting within one loop iteration; listening sockets stay open. Idempotent.
1029    pub fn close_door(&self) {
1030        self.shared.close_door();
1031    }
1032
1033    /// Whether the server is accepting.
1034    #[must_use]
1035    pub fn door(&self) -> DoorState {
1036        self.shared.door()
1037    }
1038
1039    /// Closes the door, tells sessions to finish, closes idle connections at once
1040    /// (one that has received nothing yet once `Limits::first_request_grace` from its
1041    /// accept has passed), waits for the rest until `deadline`, then kills them with
1042    /// `DrainDeadline`.
1043    ///
1044    /// Returns once every connection closed, or 2 s after the kill at the latest: a
1045    /// kill shuts the socket and wakes its owner, but a thread cannot be stopped from
1046    /// outside, so a blocking handler that computes, sleeps, or waits on a lock
1047    /// without touching its connection keeps running (and its connection open,
1048    /// still counted in `stats().open`) until it returns.
1049    pub fn drain(&self, deadline: Instant) -> DrainReport {
1050        self.shared.drain(deadline)
1051    }
1052
1053    /// Drains, then closes the listening sockets and joins every thread. Bounded as
1054    /// [`Server::drain`] is: a worker thread still held by a connection the drain
1055    /// gave up on is left detached, counted in `Stats::workers_detached` (read it
1056    /// through a [`ServerHandle`]), and ends when its handler returns.
1057    pub fn shutdown(mut self, deadline: Instant) -> DrainReport {
1058        self.stop(deadline)
1059    }
1060
1061    /// Blocks until a stop is requested (`ServerHandle::request_stop`, or the
1062    /// control line moves to `Draining` or `Stopping`), then shuts down.
1063    pub fn wait_for_stop(mut self) -> DrainReport {
1064        let deadline = self.shared.wait_for_stop_request();
1065        self.stop(deadline)
1066    }
1067
1068    fn stop(&mut self, deadline: Instant) -> DrainReport {
1069        if self.stopped {
1070            return DrainReport {
1071                graceful: 0,
1072                killed: 0,
1073                took: Duration::ZERO,
1074            };
1075        }
1076        self.stopped = true;
1077        let report = self.shared.drain(deadline);
1078        self.shared.stop_threads();
1079        self.shared.join_workers(std::mem::take(&mut self.threads));
1080        self.shared.join_listeners();
1081        report
1082    }
1083
1084    /// Registers a dialed connection exactly like an accepted one on the
1085    /// listener named in `spec`: a new id, the caps, `Gate::admit` with
1086    /// `AdmitStage::Adopt`, that listener's limits, the server's handler or
1087    /// sessions, its kill handle, and its events. For back-channels and outbound
1088    /// connections a server should run and revoke like its own. A gate the
1089    /// connection had from `set_gate` is closed (`SessionClosed`) first.
1090    ///
1091    /// # Errors
1092    ///
1093    /// `Refused { cause }` (caps, the gate, `Busy`; the connection was reset),
1094    /// `InvalidConfig { field: "listener" }` (no listener with that name),
1095    /// `InvalidConfig { field: "connection" }` (a TLS connection, or bytes read
1096    /// ahead), `ShuttingDown`, `ForkedChild`, `Closed`.
1097    ///
1098    /// ```no_run
1099    /// use net_io::{AdoptSpec, AllowAll, ListenerSpec, ServerBuilder};
1100    /// let server = ServerBuilder::new()
1101    ///     .listener(ListenerSpec::tcp("127.0.0.1:7000").name("main"))
1102    ///     .handler(|conn| { conn.send_all(b"hello, upstream\n")?; Ok(()) })
1103    ///     .gate(AllowAll)
1104    ///     .build()?;
1105    /// let upstream = net_io::connect("10.0.0.9:9000")?;
1106    /// let id = server.adopt(upstream, AdoptSpec::new("main"))?;
1107    /// # let _ = id;
1108    /// # Ok::<(), net_io::NetError>(())
1109    /// ```
1110    pub fn adopt(&self, conn: TcpConnection, spec: AdoptSpec) -> Result<ConnectionId, NetError> {
1111        let mut conn = conn;
1112        let link = conn.take_link().ok_or(NetError::Closed)?;
1113        let (Some(peer), Some(local)) =
1114            (link.info.peer.socket_addr(), link.info.local.socket_addr())
1115        else {
1116            return Err(invalid("connection", ConfigReason::Inconsistent));
1117        };
1118        let stream = link
1119            .into_stream(CloseReason::SessionClosed)
1120            .and_then(crate::sys::Stream::into_tcp)
1121            .ok_or(invalid("connection", ConfigReason::Inconsistent))?;
1122        self.shared
1123            .adopt(stream, peer, local, &spec.listener, spec.lane)
1124    }
1125
1126    /// Owned duplicates of every listening socket, for a hand-off to the next
1127    /// process (`send_listeners`, Unix). This server keeps
1128    /// accepting meanwhile, so the new process can start before this one stops
1129    /// (decision D-042); a later `shutdown` closes only this server's copies, and
1130    /// a Unix socket file stays in place for the new process.
1131    ///
1132    /// # Errors
1133    ///
1134    /// `Os` when a socket cannot be duplicated, `ForkedChild`.
1135    pub fn release_listeners(&self) -> Result<Vec<ListenerHandle>, NetError> {
1136        self.shared.release_listeners()
1137    }
1138
1139    /// Binds one more listener on the running server and starts its accept
1140    /// thread. Its door is closed until the next [`Server::open_door`] (which
1141    /// opens every listener's door); the same checks as `build` apply. The id is
1142    /// new: ids of removed listeners are never reused.
1143    ///
1144    /// # Errors
1145    ///
1146    /// As `build` for the listener; `InvalidConfig { field: "listener" }` past 64
1147    /// listeners, `ShuttingDown`, `ForkedChild`.
1148    ///
1149    /// ```no_run
1150    /// use net_io::{AllowAll, ListenerSpec, ServerBuilder};
1151    /// let mut server = ServerBuilder::new()
1152    ///     .listener(ListenerSpec::tcp("127.0.0.1:8080"))
1153    ///     .handler(|conn| { conn.send_all(b"hi\n")?; Ok(()) })
1154    ///     .gate(AllowAll)
1155    ///     .build()?;
1156    /// server.open_door()?;
1157    /// let added = server.add_listener(ListenerSpec::tcp("127.0.0.1:8081").name("extra"))?;
1158    /// server.open_door()?; // opens the new listener's door
1159    /// # let _ = added;
1160    /// # Ok::<(), net_io::NetError>(())
1161    /// ```
1162    pub fn add_listener(&mut self, spec: ListenerSpec) -> Result<ListenerId, NetError> {
1163        let mut spec = spec;
1164        if self.listeners.len() >= 64 {
1165            return Err(invalid("listener", ConfigReason::TooLarge { max: 64 }));
1166        }
1167        let names: Vec<String> = self
1168            .listeners
1169            .iter()
1170            .filter_map(|l| l.name.clone())
1171            .collect();
1172        check_spec(
1173            &mut spec,
1174            self.shared.trusted.as_ref(),
1175            self.shared.tls.is_some(),
1176            &names,
1177        )?;
1178        let workers = u16::try_from(self.shared.worker_count()).unwrap_or(u16::MAX);
1179        spec.check_listener_limits()?;
1180        self.shared.base_limits.overlay(&spec.limits).validate_for(
1181            self.shared.driver(),
1182            workers,
1183            None,
1184        )?;
1185        let info = self.shared.add_listener(spec)?;
1186        let id = info.id;
1187        self.listeners.push(info);
1188        Ok(id)
1189    }
1190
1191    /// Closes one listener's socket at once (its connections keep running),
1192    /// then drains them: idle ones close now, the rest may finish until
1193    /// `deadline` and are then killed (`DrainDeadline`). Other listeners and
1194    /// their connections are not touched. Bounded as [`Server::drain`] is.
1195    ///
1196    /// # Errors
1197    ///
1198    /// `InvalidConfig { field: "listener", reason: Missing }` for an unknown id,
1199    /// `ForkedChild`.
1200    pub fn remove_listener(
1201        &mut self,
1202        id: ListenerId,
1203        deadline: Instant,
1204    ) -> Result<DrainReport, NetError> {
1205        let report = self.shared.remove_listener(id, deadline)?;
1206        self.listeners.retain(|l| l.id != id);
1207        Ok(report)
1208    }
1209
1210    /// A cloneable handle for other threads.
1211    #[must_use]
1212    pub fn handle(&self) -> ServerHandle {
1213        ServerHandle {
1214            shared: self.shared.clone(),
1215        }
1216    }
1217
1218    /// Counters summed over the workers.
1219    #[must_use]
1220    pub fn stats(&self) -> Stats {
1221        self.shared.stats()
1222    }
1223
1224    /// Facts about each listener.
1225    #[must_use]
1226    pub fn listeners(&self) -> &[ListenerInfo] {
1227        &self.listeners
1228    }
1229}
1230
1231impl Drop for Server {
1232    fn drop(&mut self) {
1233        let deadline = Instant::now() + self.shared.drain_timeout;
1234        self.stop(deadline);
1235    }
1236}
1237
1238impl fmt::Debug for Server {
1239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1240        f.debug_struct("Server")
1241            .field("listeners", &self.listeners)
1242            .field("door", &self.door())
1243            .finish()
1244    }
1245}
1246
1247/// A cloneable handle to a running server, safe to use from any thread.
1248///
1249/// ```no_run
1250/// let server = net_io::serve("127.0.0.1:7000", |conn| { conn.send_all(b"hi\n")?; Ok(()) })?;
1251/// let handle = server.handle();
1252/// std::thread::spawn(move || {
1253///     // ... wait for a signal from the application's signal library ...
1254///     handle.request_stop();
1255/// });
1256/// let report = server.wait_for_stop();
1257/// println!("drained: {} graceful, {} killed in {:?}", report.graceful, report.killed, report.took);
1258/// # Ok::<(), net_io::NetError>(())
1259/// ```
1260#[derive(Clone)]
1261pub struct ServerHandle {
1262    pub(crate) shared: Arc<Shared>,
1263}
1264
1265impl ServerHandle {
1266    /// Aborts the connection `id`; `false` if it already closed or belongs to another server.
1267    pub fn kill(&self, id: ConnectionId, reason: KillReason) -> bool {
1268        self.shared.kill(id, reason)
1269    }
1270
1271    /// Closes the connection `id` after what it already queued goes out: its session
1272    /// is given no more input, the output it queued is sent, then FIN and a linger
1273    /// that reads and discards until the peer closes, all within `within` from when
1274    /// its worker sees the request (on the reactor only what was queued then goes
1275    /// out; on the blocking pool a write already in progress finishes). The close reason is
1276    /// `CloseReason::Killed(reason)`. A `kill` meanwhile (or a stop's deadline) ends
1277    /// it at once with a reset. `false` if it already closed, was already killed,
1278    /// or belongs to another server.
1279    ///
1280    /// For an ejector with a denial to deliver: `kill` resets the connection, and a
1281    /// reset can destroy bytes the peer has not read yet (decision D-182).
1282    ///
1283    /// ```no_run
1284    /// use std::time::Duration;
1285    /// # let server = net_io::serve("127.0.0.1:0", |_| Ok(()))?;
1286    /// # let id = net_io::ConnectionId::new(1).unwrap();
1287    /// let handle = server.handle();
1288    /// handle.close_after_flush(id, net_io::KillReason(9), Duration::from_millis(100));
1289    /// # Ok::<(), net_io::NetError>(())
1290    /// ```
1291    pub fn close_after_flush(
1292        &self,
1293        id: ConnectionId,
1294        reason: KillReason,
1295        within: Duration,
1296    ) -> bool {
1297        self.shared.close_after_flush(id, reason, within)
1298    }
1299
1300    /// Stops accepting.
1301    pub fn close_door(&self) {
1302        self.shared.close_door();
1303    }
1304
1305    /// Makes `Server::wait_for_stop` return after the drain. Does not block.
1306    pub fn request_stop(&self) {
1307        self.shared.request_stop(None);
1308    }
1309
1310    /// Interrupts every worker's and acceptor's wait so a control-line change is seen at once.
1311    pub fn wake_all(&self) {
1312        self.shared.wake_all();
1313    }
1314
1315    /// The completion queue of `worker`.
1316    #[must_use]
1317    pub fn completer(&self, worker: WorkerId) -> Option<crate::completer::Completer> {
1318        self.shared.completer(worker)
1319    }
1320
1321    /// Counters summed over the workers.
1322    #[must_use]
1323    pub fn stats(&self) -> Stats {
1324        self.shared.stats()
1325    }
1326
1327    /// Whether the server is accepting.
1328    #[must_use]
1329    pub fn door(&self) -> DoorState {
1330        self.shared.door()
1331    }
1332}
1333
1334impl fmt::Debug for ServerHandle {
1335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1336        f.debug_struct("ServerHandle")
1337            .field("door", &self.door())
1338            .finish()
1339    }
1340}
1341
1342impl Stats {
1343    pub(crate) fn from_parts(
1344        mut base: Stats,
1345        refused_by: [u64; RefusalCause::COUNT],
1346        closed_by: [u64; CloseReason::COUNT],
1347    ) -> Stats {
1348        base.refused_by = refused_by;
1349        base.closed_by = closed_by;
1350        base
1351    }
1352}