Skip to main content

nitr_http/server/
builder.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! [`ServerBuilder`]: configuration of a [`Server`] and the build-time
7//! checks (config validation, pending migrations, TLS material).
8
9use std::path::PathBuf;
10use std::sync::atomic::AtomicBool;
11use std::sync::{Arc, RwLock};
12
13use tokio::sync::Semaphore;
14
15use crate::config::Config;
16use crate::protect::Protection;
17#[cfg(any(feature = "db", feature = "openapi"))]
18use nitr_core::Error;
19use nitr_core::Result;
20use nitr_std::Builtins;
21
22use super::pool::{build_runtimes, new_pool};
23use super::{Module, Server, SetupFn};
24
25/// Refuses to start while a migration is pending.
26///
27/// The alternative — applying them at boot — is how two instances of a
28/// rolling deployment race to change the same schema, each believing it is
29/// the only one. Making it an explicit step means somebody chose when it
30/// happened.
31#[cfg(not(feature = "db"))]
32fn check_migrations(_cfg: &Config) -> Result {
33    // Without the `db` builtin there is no connection to check against;
34    // `register_builtins` is what reports the misconfiguration.
35    Ok(())
36}
37
38#[cfg(feature = "db")]
39fn check_migrations(cfg: &Config) -> Result {
40    let Some(db) = &cfg.database else {
41        return Ok(());
42    };
43    let Some(dir) = db.migrations() else {
44        return Ok(());
45    };
46    let conn = nitr_std::db_open(&db.path, &db.pragmas())?;
47    let pending = nitr_std::migrate::pending(&conn, &dir)?;
48    if pending.is_empty() {
49        return Ok(());
50    }
51    Err(Error::Config(format!(
52        "{} migration(s) pending ({}). Run `nitr migrate` first.",
53        pending.len(),
54        pending.join(", ")
55    )))
56}
57
58/// Builder for [`Server`].
59///
60/// Individual setters override values from [`config()`](Self::config).
61#[derive(Default)]
62pub struct ServerBuilder {
63    cfg: Config,
64    builtins: Option<Builtins>,
65    setup_fns: Vec<SetupFn>,
66    modules: Vec<Module>,
67    listener: Option<std::net::TcpListener>,
68    health_listener: Option<std::net::TcpListener>,
69    cache: Option<nitr_std::Cache>,
70}
71
72impl ServerBuilder {
73    /// Bulk-applies a loaded [`Config`] (e.g. from `nitr.toml`).
74    /// Setters called afterwards override it.
75    pub fn config(mut self, cfg: Config) -> Self {
76        self.cfg = cfg;
77        self
78    }
79
80    /// Address the server binds to.
81    pub fn listen(mut self, addr: std::net::SocketAddr) -> Self {
82        self.cfg.listen = addr;
83        self
84    }
85
86    /// Serves on an already-bound listener instead of binding
87    /// [`listen`](Self::listen).
88    ///
89    /// This closes the window between choosing a port and binding it: a
90    /// caller can bind port 0 (the OS picks a free one), read the real
91    /// address, and hand the listener over — nothing else can take the
92    /// port in between. That makes it the right tool for tests and for
93    /// socket-activation setups where the supervisor owns the socket.
94    pub fn listener(mut self, listener: std::net::TcpListener) -> Self {
95        self.listener = Some(listener);
96        self
97    }
98
99    /// Serves the health probes on an already-bound listener instead of
100    /// binding `[health] bind`.
101    ///
102    /// The probe-port counterpart of [`listener`](Self::listener), closing
103    /// the same choose-then-bind window: reserve port 0, read the real
104    /// address, hand the listener over. Ignored when `[health] enabled`
105    /// is off.
106    pub fn health_listener(mut self, listener: std::net::TcpListener) -> Self {
107        self.health_listener = Some(listener);
108        self
109    }
110
111    /// The handler script, loaded once per Lua state at startup and on
112    /// every reload; its routes serve the requests.
113    pub fn handler_script(mut self, path: impl Into<PathBuf>) -> Self {
114        self.cfg.handler_script = path.into();
115        self
116    }
117
118    /// Lua script executed exactly once at startup; its returned table is
119    /// passed to the handler on every request.
120    pub fn config_script(mut self, path: impl Into<PathBuf>) -> Self {
121        self.cfg.config_script = Some(path.into());
122        self
123    }
124
125    /// Directory for the `template` builtin (`[templating] dir`).
126    pub fn templates_dir(mut self, path: impl Into<PathBuf>) -> Self {
127        self.cfg.templating.dir = Some(path.into());
128        self
129    }
130
131    /// SQLite database file for the `conn` builtin.
132    pub fn database(mut self, path: impl Into<PathBuf>) -> Self {
133        match &mut self.cfg.database {
134            Some(db) => db.path = path.into(),
135            None => self.cfg.database = Some(crate::config::DatabaseConfig::new(path)),
136        }
137        self
138    }
139
140    /// Standard library (`nitr.*`) features to expose; overrides the
141    /// `[std] features` list from the configuration file. Without either,
142    /// the minimal default set ([`Builtins::minimal()`]) is enabled.
143    pub fn builtins(mut self, builtins: Builtins) -> Self {
144        self.builtins = Some(builtins);
145        self
146    }
147
148    /// Number of pooled Lua states (max concurrently executing handlers).
149    pub fn workers(mut self, n: usize) -> Self {
150        self.cfg.workers = n;
151        self
152    }
153
154    /// Development mode: hot-reload the handler script on change.
155    pub fn dev_mode(mut self, on: bool) -> Self {
156        self.cfg.dev_mode = on;
157        self
158    }
159
160    /// Registers a Rust extension module: the closure runs once per pooled
161    /// state (and again on every reload) and its returned table is mounted
162    /// at `nitr.ext.<name>` — one level below the standard library, so a
163    /// module can never collide with a builtin (present or future).
164    /// Registration fails at build time when two modules share a name.
165    ///
166    /// ```ignore
167    /// // Scripts call it as nitr.ext.greet.hello("world").
168    /// Server::builder().module("greet", |lua| {
169    ///     let t = lua.create_table()?;
170    ///     t.set("hello", lua.create_function(|_, name: String| {
171    ///         Ok(format!("Hello, {name}!"))
172    ///     })?)?;
173    ///     Ok(t)
174    /// })
175    /// ```
176    pub fn module<F>(mut self, name: impl Into<String>, f: F) -> Self
177    where
178        F: Fn(&mlua::Lua) -> mlua::Result<mlua::Table> + Send + Sync + 'static,
179    {
180        self.modules.push((name.into(), Arc::new(f)));
181        self
182    }
183
184    /// The storage behind `nitr.cache`, instead of a fresh one sized by
185    /// `[cache]`. `nitr test` hands its test states the same instance, so
186    /// what a handler caches is observable from a test. Unused when the
187    /// `cache` builtin is not enabled.
188    pub fn cache(mut self, cache: nitr_std::Cache) -> Self {
189        self.cache = Some(cache);
190        self
191    }
192
193    /// Registers a closure that customizes each pooled Lua state — the
194    /// low-level escape hatch behind [`module()`](Self::module). It runs
195    /// once per state, before the configuration script and handler are
196    /// loaded.
197    pub fn setup<F>(mut self, f: F) -> Self
198    where
199        F: Fn(&mlua::Lua) -> mlua::Result<()> + Send + Sync + 'static,
200    {
201        self.setup_fns.push(Box::new(f));
202        self
203    }
204
205    /// Builds the server: creates the runtime pool, runs the configuration
206    /// script exactly once, snapshots its result into every state, and
207    /// compiles the handler. Fails fast on any configuration or script error.
208    pub async fn build(self) -> Result<Server> {
209        let cfg = self.cfg;
210        // A contradictory policy fails the boot rather than surfacing later
211        // as a header combination a browser quietly ignores.
212        cfg.validate()?;
213        let builtins = match self.builtins {
214            Some(b) => b,
215            None => cfg.builtins()?,
216        };
217        let setup_fns = Arc::new(self.setup_fns);
218        let modules = Arc::new(self.modules);
219
220        // Pending migrations stop the boot. Applying them here instead
221        // would mean two instances rolling out at once race to change the
222        // schema, each believing it is alone.
223        check_migrations(&cfg)?;
224        // Spooled uploads and half-saved parts a crashed process left behind.
225        #[cfg(feature = "multipart")]
226        if let Some(root) = &cfg.multipart.upload_dir {
227            crate::validation::spool::sweep(root);
228        }
229
230        // Built once and shared by every state, including states built by
231        // a later reload: a cache that empties whenever the handler script
232        // changes is a cache that never warms.
233        let supplied = self.cache;
234        let cache = builtins
235            .contains(nitr_std::Builtins::CACHE)
236            .then(|| supplied.unwrap_or_else(|| nitr_std::Cache::new(cfg.cache_options())));
237
238        let built = build_runtimes(&cfg, builtins, &setup_fns, &modules, cache.as_ref()).await?;
239        let cfg_snapshot = built.snapshot.clone();
240        // The document is built from the bootstrap state before the pool
241        // exists, so a document over its bound is a build failure like a
242        // duplicate route.
243        let protection = Protection::new(&cfg);
244        #[cfg(feature = "openapi")]
245        let docs = protection.docs_slot();
246        #[cfg(feature = "openapi")]
247        {
248            let document = super::pool::build_docs(&cfg, &built.runtimes)?;
249            match docs.write() {
250                Ok(mut slot) => *slot = Some(document),
251                // Unreachable in practice: nothing else holds the lock yet.
252                Err(_) => return Err(Error::Config("the docs lock is poisoned".into())),
253            }
254        }
255        let pool = new_pool(built, &cfg, builtins, &setup_fns, &modules, cache.clone());
256
257        let max_streams = cfg.effective_max_streams();
258
259        // The certificate and key are read exactly here: once, before a
260        // port exists, so a broken pair is a build failure (`nitr check`
261        // catches it) instead of a listener that accepts TCP and then
262        // fails every handshake — which from the outside is
263        // indistinguishable from a network fault.
264        #[cfg(feature = "tls")]
265        let tls = Arc::new(RwLock::new(load_tls(&cfg.tls)?));
266
267        // Owned from here, before the caller writes a pidfile: a reload
268        // sent to a server that is not serving yet is dropped, never fatal
269        // (the default disposition of `SIGHUP` is to terminate).
270        #[cfg(unix)]
271        let reload_signal = {
272            use tokio::signal::unix::{SignalKind, signal};
273            match signal(SignalKind::hangup()) {
274                Ok(signal) => Some(signal),
275                Err(err) => {
276                    tracing::warn!("failed to install the SIGHUP reload handler: {err}");
277                    None
278                }
279            }
280        };
281        Ok(Server {
282            protection: Arc::new(protection),
283            #[cfg(unix)]
284            reload_signal,
285            #[cfg(feature = "openapi")]
286            docs,
287            cfg,
288            builtins,
289            setup_fns,
290            modules,
291            pool: Arc::new(RwLock::new(Arc::new(pool))),
292            streams: Arc::new(Semaphore::new(max_streams)),
293            max_streams,
294            listener: self.listener,
295            health_listener: self.health_listener,
296            ready: Arc::new(AtomicBool::new(true)),
297            cache,
298            cfg_snapshot,
299            reloading: Arc::new(std::sync::atomic::AtomicU8::new(0)),
300            #[cfg(feature = "tls")]
301            tls,
302        })
303    }
304}
305
306/// Builds the shared TLS acceptor from `[tls]`, or `None` when the
307/// listener is plaintext.
308///
309/// The whole certificate/key read happens in this one call, so every
310/// connection afterwards clones an `Arc` rather than touching the
311/// filesystem. Renewed material arrives by `SIGHUP`: the reload path
312/// re-runs this same loading routine against the same paths and swaps
313/// the acceptor only when the new pair validates.
314#[cfg(feature = "tls")]
315fn load_tls(cfg: &crate::config::TlsConfig) -> Result<Option<tokio_rustls::TlsAcceptor>> {
316    if !cfg.enabled {
317        return Ok(None);
318    }
319    let loaded = crate::tls::load(cfg)?;
320    tracing::info!(
321        "TLS enabled: {} certificate(s), minimum version {}, ALPN {:?}",
322        loaded.certs,
323        cfg.min_version.as_deref().unwrap_or("1.2"),
324        crate::tls::ALPN_PROTOCOLS.map(String::from_utf8_lossy),
325    );
326    Ok(Some(tokio_rustls::TlsAcceptor::from(loaded.config)))
327}