1use std::{fmt, io, pin::Pin, sync::Arc};
2
3use ntex_io::{IoConfig, IoMetricsGroup};
4use ntex_service::{BindCtx, Ctx, Service, cfg::SharedCfg};
5use ntex_util::future::{Stream, join_all};
6use ntex_util::{HashMap, services::Counter, services::counter::CounterGuard};
7
8use crate::{ServerAppConfig, ServerConfiguration, metrics::WorkerSlot};
9
10use super::accept::{AcceptNotify, AcceptorCommand};
11use super::factory::{FactoryServiceType, NetService};
12use super::reuseport::Reuseport;
13use super::{Token, socket::Connection};
14
15pub struct StreamServer<Cfg> {
21 accept: AcceptNotify,
22 state: Arc<Cfg>,
23 services: Vec<FactoryServiceType<Cfg>>,
24 max_conns: usize,
25 reuseport: Option<Arc<Reuseport>>,
26}
27
28impl<Cfg: ServerAppConfig> StreamServer<Cfg> {
29 pub(crate) fn new(
30 accept: AcceptNotify,
31 state: Arc<Cfg>,
32 services: Vec<FactoryServiceType<Cfg>>,
33 max_conns: usize,
34 reuseport: Option<Arc<Reuseport>>,
35 ) -> Self {
36 Self {
37 accept,
38 state,
39 services,
40 max_conns,
41 reuseport,
42 }
43 }
44}
45
46impl<Cfg> fmt::Debug for StreamServer<Cfg> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.debug_struct("StreamServer")
49 .field("services", &self.services.len())
50 .field("max_conns", &self.max_conns)
51 .field("reuseport", &self.reuseport)
52 .finish()
53 }
54}
55
56impl<Cfg: ServerAppConfig> ServerConfiguration for StreamServer<Cfg> {
58 type Item = Connection;
59 type Service = StreamService;
60
61 async fn create(&self) -> io::Result<Self::Service> {
63 let cfg = self.state.create().await?;
65
66 let mut tokens = HashMap::default();
68 let mut services = Vec::new();
69 let group = IoMetricsGroup::current();
70
71 for info in &self.services {
72 for (svc, _, svc_tokens) in info.create(cfg.clone()).await.map_err(io::Error::other)? {
73 services.push(svc);
74 let idx = services.len() - 1;
75 for (token, cfg) in &svc_tokens {
76 group.register(&cfg.get::<IoConfig>());
78 tokens.insert(*token, (idx, cfg.clone()));
79 }
80 }
81 }
82
83 Ok(StreamService {
84 services,
85 tokens,
86 conns: Counter::new(self.max_conns),
87 metrics: WorkerSlot::current(),
88 })
89 }
90
91 fn pause(&self) {
93 if let Some(ref rp) = self.reuseport {
94 rp.pause();
95 }
96 self.accept.send(AcceptorCommand::Pause);
97 }
98
99 fn resume(&self) {
101 if let Some(ref rp) = self.reuseport {
102 rp.resume();
103 }
104 self.accept.send(AcceptorCommand::Resume);
105 }
106
107 fn terminate(&self) {
109 if let Some(ref rp) = self.reuseport {
110 rp.stop();
111 }
112 self.accept.send(AcceptorCommand::Terminate);
113 }
114
115 async fn stop(&self) {
117 if let Some(ref rp) = self.reuseport {
118 rp.stop();
119 }
120 let (tx, rx) = oneshot::channel();
121 self.accept.send(AcceptorCommand::Stop(tx));
122 let _ = rx.await;
123 }
124
125 fn incoming_cpu(&self, con: &Connection) -> Option<usize> {
126 con.incoming_cpu()
127 }
128
129 fn local_items(&self) -> Option<Pin<Box<dyn Stream<Item = Connection>>>> {
131 let local = self.reuseport.as_ref()?.local()?;
132 Some(Box::pin(local))
133 }
134}
135
136impl<Cfg: ServerAppConfig> Clone for StreamServer<Cfg> {
137 fn clone(&self) -> Self {
138 Self {
139 state: self.state.clone(),
140 accept: self.accept.clone(),
141 services: self.services.iter().map(|s| s.clo()).collect(),
142 max_conns: self.max_conns,
143 reuseport: self.reuseport.clone(),
144 }
145 }
146}
147
148pub struct StreamService {
150 tokens: HashMap<Token, (usize, SharedCfg)>,
151 services: Vec<Box<dyn NetService>>,
152 conns: Counter,
153 metrics: Option<Arc<WorkerSlot>>,
154}
155
156pub(crate) struct ConnGuard {
158 _guard: CounterGuard,
159 metrics: Option<Arc<WorkerSlot>>,
160}
161
162impl ConnGuard {
163 fn new(guard: CounterGuard, metrics: Option<Arc<WorkerSlot>>) -> Self {
164 if let Some(ref m) = metrics {
165 m.conn_opened();
166 }
167 Self {
168 _guard: guard,
169 metrics,
170 }
171 }
172}
173
174impl Drop for ConnGuard {
175 fn drop(&mut self) {
176 if let Some(ref m) = self.metrics {
177 m.conn_closed();
178 }
179 }
180}
181
182impl fmt::Debug for StreamService {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 f.debug_struct("StreamService")
185 .field("tokens", &self.tokens)
186 .field("conns", &self.conns)
187 .finish()
188 }
189}
190
191impl Service<(), Connection> for StreamService {
192 type Res = ();
193 type Error = ();
194
195 fn bind(&self, ctx: BindCtx<'_>) {
196 self.conns.bind(&ctx);
197 for service in &self.services {
198 service.bind(&ctx);
199 }
200 }
201
202 async fn ready(&self, _: Ctx<'_, Self, ()>) -> Result<(), Self::Error> {
203 if !self.conns.is_available() {
204 self.conns.available().await;
205 }
206 for (idx, svc) in self.services.iter().enumerate() {
207 if svc.ready().await.is_err() {
208 for (idx_, cfg) in self.tokens.values() {
209 if idx == *idx_ {
210 log::error!("{}: Service readiness has failed", cfg.tag());
211 break;
212 }
213 }
214 return Err(());
215 }
216 }
217
218 Ok(())
219 }
220
221 async fn shutdown(&self, _: Ctx<'_, Self, ()>) {
222 let _ = join_all(self.services.iter().map(|s| s.shutdown())).await;
223 log::info!(
224 "Worker service shutdown, {} connections",
225 self.conns.total()
226 );
227 }
228
229 #[allow(clippy::unused_async_trait_impl)]
230 async fn call(&self, con: Connection, _: Ctx<'_, Self, ()>) -> Result<(), ()> {
231 if let Some((idx, cfg)) = self.tokens.get(&con.token) {
232 let stream = con.io.convert(con.nodelay, cfg.clone()).map_err(|e| {
233 log::error!("Cannot convert to an async io stream: {e}");
234 })?;
235
236 let guard = ConnGuard::new(self.conns.get(), self.metrics.clone());
237 self.services[*idx].call(stream, guard);
238 Ok(())
239 } else {
240 log::error!("Cannot get handler service for connection: {con:?}");
241 Err(())
242 }
243 }
244}