use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, RwLock};
use tokio::sync::Semaphore;
use crate::config::Config;
use crate::protect::Protection;
#[cfg(any(feature = "db", feature = "openapi"))]
use nitr_core::Error;
use nitr_core::Result;
use nitr_std::Builtins;
use super::pool::{build_runtimes, new_pool};
use super::{Module, Server, SetupFn};
#[cfg(not(feature = "db"))]
fn check_migrations(_cfg: &Config) -> Result {
Ok(())
}
#[cfg(feature = "db")]
fn check_migrations(cfg: &Config) -> Result {
let Some(db) = &cfg.database else {
return Ok(());
};
let Some(dir) = db.migrations() else {
return Ok(());
};
let conn = nitr_std::db_open(&db.path, &db.pragmas())?;
let pending = nitr_std::migrate::pending(&conn, &dir)?;
if pending.is_empty() {
return Ok(());
}
Err(Error::Config(format!(
"{} migration(s) pending ({}). Run `nitr migrate` first.",
pending.len(),
pending.join(", ")
)))
}
#[derive(Default)]
pub struct ServerBuilder {
cfg: Config,
builtins: Option<Builtins>,
setup_fns: Vec<SetupFn>,
modules: Vec<Module>,
listener: Option<std::net::TcpListener>,
health_listener: Option<std::net::TcpListener>,
cache: Option<nitr_std::Cache>,
}
impl ServerBuilder {
pub fn config(mut self, cfg: Config) -> Self {
self.cfg = cfg;
self
}
pub fn listen(mut self, addr: std::net::SocketAddr) -> Self {
self.cfg.listen = addr;
self
}
pub fn listener(mut self, listener: std::net::TcpListener) -> Self {
self.listener = Some(listener);
self
}
pub fn health_listener(mut self, listener: std::net::TcpListener) -> Self {
self.health_listener = Some(listener);
self
}
pub fn handler_script(mut self, path: impl Into<PathBuf>) -> Self {
self.cfg.handler_script = path.into();
self
}
pub fn config_script(mut self, path: impl Into<PathBuf>) -> Self {
self.cfg.config_script = Some(path.into());
self
}
pub fn templates_dir(mut self, path: impl Into<PathBuf>) -> Self {
self.cfg.templating.dir = Some(path.into());
self
}
pub fn database(mut self, path: impl Into<PathBuf>) -> Self {
match &mut self.cfg.database {
Some(db) => db.path = path.into(),
None => self.cfg.database = Some(crate::config::DatabaseConfig::new(path)),
}
self
}
pub fn builtins(mut self, builtins: Builtins) -> Self {
self.builtins = Some(builtins);
self
}
pub fn workers(mut self, n: usize) -> Self {
self.cfg.workers = n;
self
}
pub fn dev_mode(mut self, on: bool) -> Self {
self.cfg.dev_mode = on;
self
}
pub fn module<F>(mut self, name: impl Into<String>, f: F) -> Self
where
F: Fn(&mlua::Lua) -> mlua::Result<mlua::Table> + Send + Sync + 'static,
{
self.modules.push((name.into(), Arc::new(f)));
self
}
pub fn cache(mut self, cache: nitr_std::Cache) -> Self {
self.cache = Some(cache);
self
}
pub fn setup<F>(mut self, f: F) -> Self
where
F: Fn(&mlua::Lua) -> mlua::Result<()> + Send + Sync + 'static,
{
self.setup_fns.push(Box::new(f));
self
}
pub async fn build(self) -> Result<Server> {
let cfg = self.cfg;
cfg.validate()?;
let builtins = match self.builtins {
Some(b) => b,
None => cfg.builtins()?,
};
let setup_fns = Arc::new(self.setup_fns);
let modules = Arc::new(self.modules);
check_migrations(&cfg)?;
#[cfg(feature = "multipart")]
if let Some(root) = &cfg.multipart.upload_dir {
crate::validation::spool::sweep(root);
}
let supplied = self.cache;
let cache = builtins
.contains(nitr_std::Builtins::CACHE)
.then(|| supplied.unwrap_or_else(|| nitr_std::Cache::new(cfg.cache_options())));
let built = build_runtimes(&cfg, builtins, &setup_fns, &modules, cache.as_ref()).await?;
let cfg_snapshot = built.snapshot.clone();
let protection = Protection::new(&cfg);
#[cfg(feature = "openapi")]
let docs = protection.docs_slot();
#[cfg(feature = "openapi")]
{
let document = super::pool::build_docs(&cfg, &built.runtimes)?;
match docs.write() {
Ok(mut slot) => *slot = Some(document),
Err(_) => return Err(Error::Config("the docs lock is poisoned".into())),
}
}
let pool = new_pool(built, &cfg, builtins, &setup_fns, &modules, cache.clone());
let max_streams = cfg.effective_max_streams();
#[cfg(feature = "tls")]
let tls = Arc::new(RwLock::new(load_tls(&cfg.tls)?));
#[cfg(unix)]
let reload_signal = {
use tokio::signal::unix::{SignalKind, signal};
match signal(SignalKind::hangup()) {
Ok(signal) => Some(signal),
Err(err) => {
tracing::warn!("failed to install the SIGHUP reload handler: {err}");
None
}
}
};
Ok(Server {
protection: Arc::new(protection),
#[cfg(unix)]
reload_signal,
#[cfg(feature = "openapi")]
docs,
cfg,
builtins,
setup_fns,
modules,
pool: Arc::new(RwLock::new(Arc::new(pool))),
streams: Arc::new(Semaphore::new(max_streams)),
max_streams,
listener: self.listener,
health_listener: self.health_listener,
ready: Arc::new(AtomicBool::new(true)),
cache,
cfg_snapshot,
reloading: Arc::new(std::sync::atomic::AtomicU8::new(0)),
#[cfg(feature = "tls")]
tls,
})
}
}
#[cfg(feature = "tls")]
fn load_tls(cfg: &crate::config::TlsConfig) -> Result<Option<tokio_rustls::TlsAcceptor>> {
if !cfg.enabled {
return Ok(None);
}
let loaded = crate::tls::load(cfg)?;
tracing::info!(
"TLS enabled: {} certificate(s), minimum version {}, ALPN {:?}",
loaded.certs,
cfg.min_version.as_deref().unwrap_or("1.2"),
crate::tls::ALPN_PROTOCOLS.map(String::from_utf8_lossy),
);
Ok(Some(tokio_rustls::TlsAcceptor::from(loaded.config)))
}