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, Swansong, TypeSet};
9use trillium_http::HttpContext;
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) context_cell: Arc<AsyncCell<Arc<HttpContext>>>,
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) context: HttpContext,
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 context,
101 context_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 = context.swansong().clone();
130
131 let mut info = Info::from(context)
132 .with_shared_state(runtime.clone().into())
133 .with_shared_state(runtime.clone());
134
135 info.shared_state_entry::<Headers>()
136 .or_default()
137 .try_insert(KnownHeaderName::Server, trillium::headers::server_header());
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.shared_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 context = Arc::new(HttpContext::from(info));
164
165 context_cell.set(context.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 context = context.clone();
194 let handler = handler.clone();
195 let runtime: crate::Runtime = runtime.clone().into();
196 runtime
197 .clone()
198 .spawn(crate::h3::run_h3(quic_binding, context, handler, runtime));
199 }
200
201 let running_config = Arc::new(RunningConfig {
202 acceptor,
203 max_connections,
204 context,
205 runtime,
206 nodelay,
207 });
208
209 running_config.run_async(listener, handler).await;
210 }
211
212 pub fn spawn(self, handler: impl Handler) -> ServerHandle {
219 let server_handle = self.handle();
220 self.runtime.clone().spawn(self.run_async(handler));
221 server_handle
222 }
223
224 pub fn handle(&self) -> ServerHandle {
227 ServerHandle {
228 swansong: self.context.swansong().clone(),
229 context: self.context_cell.clone(),
230 received_context: OnceCell::new(),
231 runtime: self.runtime().into(),
232 }
233 }
234
235 pub fn with_port(mut self, port: u16) -> Self {
238 if self.has_binding() {
239 log::warn!(
240 "constructing a config with both a port and a pre-bound listener will ignore the \
241 port"
242 );
243 }
244 self.port = Some(port);
245 self
246 }
247
248 pub fn with_host(mut self, host: &str) -> Self {
252 if self.has_binding() {
253 log::warn!(
254 "constructing a config with both a host and a pre-bound listener will ignore the \
255 host"
256 );
257 }
258 self.host = Some(host.into());
259 self
260 }
261
262 pub fn without_signals(mut self) -> Self {
267 self.register_signals = false;
268 self
269 }
270
271 pub fn with_nodelay(mut self) -> Self {
275 self.nodelay = true;
276 self
277 }
278
279 pub fn with_socketaddr(self, socketaddr: SocketAddr) -> Self {
283 self.with_host(&socketaddr.ip().to_string())
284 .with_port(socketaddr.port())
285 }
286
287 pub fn with_acceptor<A: Acceptor<ServerType::Transport>>(
289 self,
290 acceptor: A,
291 ) -> Config<ServerType, A, QuicType> {
292 Config {
293 acceptor,
294 quic: self.quic,
295 host: self.host,
296 port: self.port,
297 nodelay: self.nodelay,
298 register_signals: self.register_signals,
299 max_connections: self.max_connections,
300 context_cell: self.context_cell,
301 context: self.context,
302 binding: self.binding,
303 runtime: self.runtime,
304 }
305 }
306
307 pub fn with_quic<Q: QuicConfig<ServerType>>(
309 self,
310 quic: Q,
311 ) -> Config<ServerType, AcceptorType, Q> {
312 Config {
313 acceptor: self.acceptor,
314 quic,
315 host: self.host,
316 port: self.port,
317 nodelay: self.nodelay,
318 register_signals: self.register_signals,
319 max_connections: self.max_connections,
320 context_cell: self.context_cell,
321 context: self.context,
322 binding: self.binding,
323 runtime: self.runtime,
324 }
325 }
326
327 pub fn with_swansong(mut self, swansong: Swansong) -> Self {
329 self.context.set_swansong(swansong);
330 self
331 }
332
333 pub fn with_max_connections(mut self, max_connections: Option<usize>) -> Self {
337 self.max_connections = max_connections;
338 self
339 }
340
341 pub fn with_http_config(mut self, config: HttpConfig) -> Self {
345 *self.context.config_mut() = config;
346 self
347 }
348
349 pub fn with_prebound_server(mut self, server: impl Into<ServerType>) -> Self {
361 if self.host.is_some() {
362 log::warn!(
363 "constructing a config with both a host and a pre-bound listener will ignore the \
364 host"
365 );
366 }
367
368 if self.port.is_some() {
369 log::warn!(
370 "constructing a config with both a port and a pre-bound listener will ignore the \
371 port"
372 );
373 }
374
375 self.binding = Some(server.into());
376 self
377 }
378
379 fn has_binding(&self) -> bool {
380 self.binding.is_some()
381 }
382
383 pub fn runtime(&self) -> ServerType::Runtime {
385 self.runtime.clone()
386 }
387
388 pub fn port(&self) -> Option<u16> {
390 self.port
391 }
392
393 pub fn host(&self) -> Option<&str> {
395 self.host.as_deref()
396 }
397
398 pub fn with_shared_state<T: Send + Sync + 'static>(mut self, state: T) -> Self {
410 self.context.shared_state_mut().insert(state);
411 self
412 }
413
414 pub fn set_shared_state<T: Send + Sync + 'static>(&mut self, state: T) -> &mut Self {
426 self.context.shared_state_mut().insert(state);
427 self
428 }
429}
430
431impl<ServerType: Server> Config<ServerType, ()> {
432 pub fn new() -> Self {
434 Self::default()
435 }
436}
437
438impl<ServerType: Server> Default for Config<ServerType, ()> {
439 fn default() -> Self {
440 Self {
441 acceptor: (),
442 quic: (),
443 port: None,
444 host: None,
445 nodelay: false,
446 register_signals: cfg!(unix),
447 max_connections: None,
448 context_cell: AsyncCell::shared(),
449 binding: None,
450 runtime: ServerType::runtime(),
451 context: Default::default(),
452 }
453 }
454}
455
456fn insert_url(state: &mut TypeSet, secure: bool) -> Option<()> {
457 let socket_addr = state.get::<SocketAddr>().copied()?;
458 let vacant_entry = state.entry::<Url>().into_vacant()?;
459
460 let host = if socket_addr.ip().is_loopback() {
461 "localhost".to_string()
462 } else {
463 socket_addr.ip().to_string()
464 };
465
466 let url = match (secure, socket_addr.port()) {
467 (true, 443) => format!("https://{host}"),
468 (false, 80) => format!("http://{host}"),
469 (true, port) => format!("https://{host}:{port}/"),
470 (false, port) => format!("http://{host}:{port}/"),
471 };
472
473 let url = Url::parse(&url).ok()?;
474
475 vacant_entry.insert(url);
476 Some(())
477}