use crate::{
Acceptor, ArcHandler, QuicConfig, RuntimeTrait, Server, ServerHandle,
running_config::RunningConfig,
};
use async_cell::sync::AsyncCell;
use futures_lite::StreamExt;
use std::{cell::OnceCell, net::SocketAddr, pin::pin, sync::Arc};
use trillium::{Handler, Headers, HttpConfig, Info, KnownHeaderName, Swansong, TypeSet};
use trillium_http::HttpContext;
use url::Url;
#[derive(Debug)]
pub struct Config<ServerType: Server, AcceptorType, QuicType: QuicConfig<ServerType> = ()> {
pub(crate) acceptor: AcceptorType,
pub(crate) quic: QuicType,
pub(crate) binding: Option<ServerType>,
pub(crate) host: Option<String>,
pub(crate) context_cell: Arc<AsyncCell<Arc<HttpContext>>>,
pub(crate) max_connections: Option<usize>,
pub(crate) nodelay: bool,
pub(crate) port: Option<u16>,
pub(crate) register_signals: bool,
pub(crate) runtime: ServerType::Runtime,
pub(crate) context: HttpContext,
}
impl<ServerType, AcceptorType, QuicType> Config<ServerType, AcceptorType, QuicType>
where
ServerType: Server,
AcceptorType: Acceptor<ServerType::Transport>,
QuicType: QuicConfig<ServerType>,
{
pub fn run(self, handler: impl Handler) {
self.runtime.clone().block_on(self.run_async(handler));
}
pub async fn run_async(self, mut handler: impl Handler) {
#[cfg_attr(not(unix), allow(unused_mut))]
let Self {
runtime,
acceptor,
quic,
mut max_connections,
nodelay,
binding,
host,
port,
register_signals,
context,
context_cell,
} = self;
#[cfg(unix)]
if max_connections.is_none() {
max_connections = rlimit::getrlimit(rlimit::Resource::NOFILE)
.ok()
.and_then(|(soft, _hard)| soft.try_into().ok())
.map(|limit: usize| ((limit as f32) * 0.75) as usize);
};
log::debug!("using max connections of {:?}", max_connections);
let host = host
.or_else(|| std::env::var("HOST").ok())
.unwrap_or_else(|| "localhost".into());
let port = port
.or_else(|| {
std::env::var("PORT")
.ok()
.map(|x| x.parse().expect("PORT must be an unsigned integer"))
})
.unwrap_or(8080);
let listener = binding
.inspect(|_| log::debug!("taking prebound listener"))
.unwrap_or_else(|| ServerType::from_host_and_port(&host, port));
let swansong = context.swansong().clone();
let mut info = Info::from(context)
.with_shared_state(runtime.clone().into())
.with_shared_state(runtime.clone());
info.shared_state_entry::<Headers>()
.or_default()
.try_insert(KnownHeaderName::Server, trillium::headers::server_header());
listener.init(&mut info);
let quic_binding = if let Some(socket_addr) = info.tcp_socket_addr().copied() {
let quic_binding = quic
.bind(socket_addr, runtime.clone(), &mut info)
.map(|r| r.expect("failed to bind QUIC endpoint"));
if quic_binding.is_some() {
info.shared_state_entry::<Headers>()
.or_default()
.try_insert_with(KnownHeaderName::AltSvc, || -> &'static str {
format!("h3=\":{}\"", socket_addr.port()).leak()
});
}
quic_binding
} else {
None
};
insert_url(info.as_mut(), acceptor.is_secure());
handler.init(&mut info).await;
let context = Arc::new(HttpContext::from(info));
context_cell.set(context.clone());
if register_signals {
let runtime = runtime.clone();
runtime.clone().spawn(async move {
let mut signals = pin!(runtime.hook_signals([2, 3, 15]));
while signals.next().await.is_some() {
let guard_count = swansong.guard_count();
if swansong.state().is_shutting_down() {
eprintln!(
"\nSecond interrupt, shutting down harshly (dropping {guard_count} \
guards)"
);
std::process::exit(1);
} else {
println!(
"\nShutting down gracefully. Waiting for {guard_count} shutdown \
guards to drop.\nControl-c again to force."
);
swansong.shut_down();
}
}
});
}
let handler = ArcHandler::new(handler);
if let Some(quic_binding) = quic_binding {
let context = context.clone();
let handler = handler.clone();
runtime.clone().spawn(crate::h3::run_h3(
quic_binding,
context,
handler,
runtime.clone(),
));
}
let running_config = Arc::new(RunningConfig {
acceptor,
max_connections,
context,
runtime,
nodelay,
});
running_config.run_async(listener, handler).await;
}
pub fn spawn(self, handler: impl Handler) -> ServerHandle {
let server_handle = self.handle();
self.runtime.clone().spawn(self.run_async(handler));
server_handle
}
pub fn handle(&self) -> ServerHandle {
ServerHandle {
swansong: self.context.swansong().clone(),
context: self.context_cell.clone(),
received_context: OnceCell::new(),
runtime: self.runtime().into(),
}
}
pub fn with_port(mut self, port: u16) -> Self {
if self.has_binding() {
log::warn!(
"constructing a config with both a port and a pre-bound listener will ignore the \
port"
);
}
self.port = Some(port);
self
}
pub fn with_host(mut self, host: &str) -> Self {
if self.has_binding() {
log::warn!(
"constructing a config with both a host and a pre-bound listener will ignore the \
host"
);
}
self.host = Some(host.into());
self
}
pub fn without_signals(mut self) -> Self {
self.register_signals = false;
self
}
pub fn with_nodelay(mut self) -> Self {
self.nodelay = true;
self
}
pub fn with_socketaddr(self, socketaddr: SocketAddr) -> Self {
self.with_host(&socketaddr.ip().to_string())
.with_port(socketaddr.port())
}
pub fn with_acceptor<A: Acceptor<ServerType::Transport>>(
self,
acceptor: A,
) -> Config<ServerType, A, QuicType> {
Config {
acceptor,
quic: self.quic,
host: self.host,
port: self.port,
nodelay: self.nodelay,
register_signals: self.register_signals,
max_connections: self.max_connections,
context_cell: self.context_cell,
context: self.context,
binding: self.binding,
runtime: self.runtime,
}
}
pub fn with_quic<Q: QuicConfig<ServerType>>(
self,
quic: Q,
) -> Config<ServerType, AcceptorType, Q> {
Config {
acceptor: self.acceptor,
quic,
host: self.host,
port: self.port,
nodelay: self.nodelay,
register_signals: self.register_signals,
max_connections: self.max_connections,
context_cell: self.context_cell,
context: self.context,
binding: self.binding,
runtime: self.runtime,
}
}
pub fn with_swansong(mut self, swansong: Swansong) -> Self {
self.context.set_swansong(swansong);
self
}
pub fn with_max_connections(mut self, max_connections: Option<usize>) -> Self {
self.max_connections = max_connections;
self
}
pub fn with_http_config(mut self, config: HttpConfig) -> Self {
*self.context.config_mut() = config;
self
}
pub fn with_prebound_server(mut self, server: impl Into<ServerType>) -> Self {
if self.host.is_some() {
log::warn!(
"constructing a config with both a host and a pre-bound listener will ignore the \
host"
);
}
if self.port.is_some() {
log::warn!(
"constructing a config with both a port and a pre-bound listener will ignore the \
port"
);
}
self.binding = Some(server.into());
self
}
fn has_binding(&self) -> bool {
self.binding.is_some()
}
pub fn runtime(&self) -> ServerType::Runtime {
self.runtime.clone()
}
pub fn port(&self) -> Option<u16> {
self.port
}
pub fn host(&self) -> Option<&str> {
self.host.as_deref()
}
pub fn with_shared_state<T: Send + Sync + 'static>(mut self, state: T) -> Self {
self.context.shared_state_mut().insert(state);
self
}
pub fn set_shared_state<T: Send + Sync + 'static>(&mut self, state: T) -> &mut Self {
self.context.shared_state_mut().insert(state);
self
}
}
impl<ServerType: Server> Config<ServerType, ()> {
pub fn new() -> Self {
Self::default()
}
}
impl<ServerType: Server> Default for Config<ServerType, ()> {
fn default() -> Self {
Self {
acceptor: (),
quic: (),
port: None,
host: None,
nodelay: false,
register_signals: cfg!(unix),
max_connections: None,
context_cell: AsyncCell::shared(),
binding: None,
runtime: ServerType::runtime(),
context: Default::default(),
}
}
}
fn insert_url(state: &mut TypeSet, secure: bool) -> Option<()> {
let socket_addr = state.get::<SocketAddr>().copied()?;
let vacant_entry = state.entry::<Url>().into_vacant()?;
let host = if socket_addr.ip().is_loopback() {
"localhost".to_string()
} else {
socket_addr.ip().to_string()
};
let url = match (secure, socket_addr.port()) {
(true, 443) => format!("https://{host}"),
(false, 80) => format!("http://{host}"),
(true, port) => format!("https://{host}:{port}/"),
(false, port) => format!("http://{host}:{port}/"),
};
let url = Url::parse(&url).ok()?;
vacant_entry.insert(url);
Some(())
}