1use crate::{
2 Acceptor, ArcHandler, QuicConfig, RuntimeTrait, Server, ServerHandle,
3 running_config::RunningConfig,
4};
5use async_cell::sync::AsyncCell;
6use futures_lite::StreamExt;
7use std::{cell::OnceCell, net::SocketAddr, pin::pin, sync::Arc};
8use trillium::{Handler, Headers, HttpConfig, Info, KnownHeaderName, SERVER, Swansong, TypeSet};
9use trillium_http::ServerConfig;
10use url::Url;
11
12#[derive(Debug)]
54pub struct Config<ServerType: Server, AcceptorType, QuicType: QuicConfig<ServerType> = ()> {
55 pub(crate) acceptor: AcceptorType,
56 pub(crate) quic: QuicType,
57 pub(crate) binding: Option<ServerType>,
58 pub(crate) host: Option<String>,
59 pub(crate) server_config_cell: Arc<AsyncCell<Arc<ServerConfig>>>,
60 pub(crate) max_connections: Option<usize>,
61 pub(crate) nodelay: bool,
62 pub(crate) port: Option<u16>,
63 pub(crate) register_signals: bool,
64 pub(crate) runtime: ServerType::Runtime,
65 pub(crate) server_config: ServerConfig,
66}
67
68impl<ServerType, AcceptorType, QuicType> Config<ServerType, AcceptorType, QuicType>
69where
70 ServerType: Server,
71 AcceptorType: Acceptor<ServerType::Transport>,
72 QuicType: QuicConfig<ServerType>,
73{
74 pub fn run(self, handler: impl Handler) {
81 self.runtime.clone().block_on(self.run_async(handler));
82 }
83
84 pub async fn run_async(self, mut handler: impl Handler) {
90 let Self {
91 runtime,
92 acceptor,
93 quic,
94 mut max_connections,
95 nodelay,
96 binding,
97 host,
98 port,
99 register_signals,
100 server_config,
101 server_config_cell,
102 } = self;
103
104 #[cfg(unix)]
105 if max_connections.is_none() {
106 max_connections = rlimit::getrlimit(rlimit::Resource::NOFILE)
107 .ok()
108 .and_then(|(soft, _hard)| soft.try_into().ok())
109 .map(|limit: usize| ((limit as f32) * 0.75) as usize);
110 };
111
112 log::debug!("using max connections of {:?}", max_connections);
113
114 let host = host
115 .or_else(|| std::env::var("HOST").ok())
116 .unwrap_or_else(|| "localhost".into());
117 let port = port
118 .or_else(|| {
119 std::env::var("PORT")
120 .ok()
121 .map(|x| x.parse().expect("PORT must be an unsigned integer"))
122 })
123 .unwrap_or(8080);
124
125 let listener = binding
126 .inspect(|_| log::debug!("taking prebound listener"))
127 .unwrap_or_else(|| ServerType::from_host_and_port(&host, port));
128
129 let swansong = server_config.swansong().clone();
130
131 let mut info = Info::from(server_config)
132 .with_state(runtime.clone().into())
133 .with_state(runtime.clone());
134
135 info.state_entry::<Headers>()
136 .or_default()
137 .try_insert(KnownHeaderName::Server, SERVER);
138
139 listener.init(&mut info);
140
141 let quic_binding = if let Some(socket_addr) = info.tcp_socket_addr().copied() {
142 let quic_binding = quic
143 .bind(socket_addr, runtime.clone(), &mut info)
144 .map(|r| r.expect("failed to bind QUIC endpoint"));
145
146 if quic_binding.is_some() {
147 info.state_entry::<Headers>()
148 .or_default()
149 .try_insert_with(KnownHeaderName::AltSvc, || {
150 format!("h3=\":{}\"", socket_addr.port())
151 });
152 }
153
154 quic_binding
155 } else {
156 None
157 };
158
159 insert_url(info.as_mut(), acceptor.is_secure());
160
161 handler.init(&mut info).await;
162
163 let server_config = Arc::new(ServerConfig::from(info));
164
165 server_config_cell.set(server_config.clone());
166
167 if register_signals {
168 let runtime = runtime.clone();
169 runtime.clone().spawn(async move {
170 let mut signals = pin!(runtime.hook_signals([2, 3, 15]));
171 while signals.next().await.is_some() {
172 let guard_count = swansong.guard_count();
173 if swansong.state().is_shutting_down() {
174 eprintln!(
175 "\nSecond interrupt, shutting down harshly (dropping {guard_count} \
176 guards)"
177 );
178 std::process::exit(1);
179 } else {
180 println!(
181 "\nShutting down gracefully. Waiting for {guard_count} shutdown \
182 guards to drop.\nControl-c again to force."
183 );
184 swansong.shut_down();
185 }
186 }
187 });
188 }
189
190 let handler = ArcHandler::new(handler);
191
192 if let Some(quic_binding) = quic_binding {
193 let server_config = server_config.clone();
194 let handler = handler.clone();
195 let runtime: crate::Runtime = runtime.clone().into();
196 runtime.clone().spawn(crate::h3::run_h3(
197 quic_binding,
198 server_config,
199 handler,
200 runtime,
201 ));
202 }
203
204 let running_config = Arc::new(RunningConfig {
205 acceptor,
206 max_connections,
207 server_config,
208 runtime,
209 nodelay,
210 });
211
212 running_config.run_async(listener, handler).await;
213 }
214
215 pub fn spawn(self, handler: impl Handler) -> ServerHandle {
220 let server_handle = self.handle();
221 self.runtime.clone().spawn(self.run_async(handler));
222 server_handle
223 }
224
225 pub fn handle(&self) -> ServerHandle {
228 ServerHandle {
229 swansong: self.server_config.swansong().clone(),
230 server_config: self.server_config_cell.clone(),
231 received_server_config: OnceCell::new(),
232 runtime: self.runtime().into(),
233 }
234 }
235
236 pub fn with_port(mut self, port: u16) -> Self {
239 if self.has_binding() {
240 eprintln!(
241 "constructing a config with both a port and a pre-bound listener will ignore the \
242 port. this may be a panic in the future"
243 );
244 }
245 self.port = Some(port);
246 self
247 }
248
249 pub fn with_host(mut self, host: &str) -> Self {
253 if self.has_binding() {
254 eprintln!(
255 "constructing a config with both a host and a pre-bound listener will ignore the \
256 host. this may be a panic in the future"
257 );
258 }
259 self.host = Some(host.into());
260 self
261 }
262
263 pub fn without_signals(mut self) -> Self {
268 self.register_signals = false;
269 self
270 }
271
272 pub fn with_nodelay(mut self) -> Self {
276 self.nodelay = true;
277 self
278 }
279
280 pub fn with_socketaddr(self, socketaddr: SocketAddr) -> Self {
284 self.with_host(&socketaddr.ip().to_string())
285 .with_port(socketaddr.port())
286 }
287
288 pub fn with_acceptor<A: Acceptor<ServerType::Transport>>(
290 self,
291 acceptor: A,
292 ) -> Config<ServerType, A, QuicType> {
293 Config {
294 acceptor,
295 quic: self.quic,
296 host: self.host,
297 port: self.port,
298 nodelay: self.nodelay,
299 register_signals: self.register_signals,
300 max_connections: self.max_connections,
301 server_config_cell: self.server_config_cell,
302 server_config: self.server_config,
303 binding: self.binding,
304 runtime: self.runtime,
305 }
306 }
307
308 pub fn with_quic<Q: QuicConfig<ServerType>>(
310 self,
311 quic: Q,
312 ) -> Config<ServerType, AcceptorType, Q> {
313 Config {
314 acceptor: self.acceptor,
315 quic,
316 host: self.host,
317 port: self.port,
318 nodelay: self.nodelay,
319 register_signals: self.register_signals,
320 max_connections: self.max_connections,
321 server_config_cell: self.server_config_cell,
322 server_config: self.server_config,
323 binding: self.binding,
324 runtime: self.runtime,
325 }
326 }
327
328 pub fn with_swansong(mut self, swansong: Swansong) -> Self {
330 self.server_config.set_swansong(swansong);
331 self
332 }
333
334 pub fn with_max_connections(mut self, max_connections: Option<usize>) -> Self {
338 self.max_connections = max_connections;
339 self
340 }
341
342 pub fn with_http_config(mut self, http_config: HttpConfig) -> Self {
346 *self.server_config.http_config_mut() = http_config;
347 self
348 }
349
350 pub fn with_prebound_server(mut self, server: impl Into<ServerType>) -> Self {
362 if self.host.is_some() {
363 eprintln!(
364 "constructing a config with both a host and a pre-bound listener will ignore the \
365 host. this may be a panic in the future"
366 );
367 }
368
369 if self.port.is_some() {
370 eprintln!(
371 "constructing a config with both a port and a pre-bound listener will ignore the \
372 port. this may be a panic in the future"
373 );
374 }
375
376 self.binding = Some(server.into());
377 self
378 }
379
380 fn has_binding(&self) -> bool {
381 self.binding.is_some()
382 }
383
384 pub fn runtime(&self) -> ServerType::Runtime {
386 self.runtime.clone()
387 }
388
389 pub fn port(&self) -> Option<u16> {
391 self.port
392 }
393
394 pub fn host(&self) -> Option<&str> {
396 self.host.as_deref()
397 }
398}
399
400impl<ServerType: Server> Config<ServerType, ()> {
401 pub fn new() -> Self {
403 Self::default()
404 }
405}
406
407impl<ServerType: Server> Default for Config<ServerType, ()> {
408 fn default() -> Self {
409 Self {
410 acceptor: (),
411 quic: (),
412 port: None,
413 host: None,
414 nodelay: false,
415 register_signals: cfg!(unix),
416 max_connections: None,
417 server_config_cell: AsyncCell::shared(),
418 binding: None,
419 runtime: ServerType::runtime(),
420 server_config: Default::default(),
421 }
422 }
423}
424
425fn insert_url(state: &mut TypeSet, secure: bool) -> Option<()> {
426 let socket_addr = state.get::<SocketAddr>().copied()?;
427 let vacant_entry = state.entry::<Url>().into_vacant()?;
428
429 let host = if socket_addr.ip().is_loopback() {
430 "localhost".to_string()
431 } else {
432 socket_addr.ip().to_string()
433 };
434
435 let url = match (secure, socket_addr.port()) {
436 (true, 443) => format!("https://{host}"),
437 (false, 80) => format!("http://{host}"),
438 (true, port) => format!("https://{host}:{port}/"),
439 (false, port) => format!("http://{host}:{port}/"),
440 };
441
442 let url = Url::parse(&url).ok()?;
443
444 vacant_entry.insert(url);
445 Some(())
446}