use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use hyper::Method;
use matchit::Router;
use mlua::{AnyUserData, Function, Lua, UserData, UserDataMethods, Value, Variadic};
use nitr_core::{Error, Result};
use crate::openapi::AppMeta;
use crate::validation::{InputEnv, InputSchemas};
mod compile;
mod meta;
mod options;
use compile::compile;
use options::{caller_site, route_options};
const APP_STATE_KEY: &str = "nitr::app_state";
const METHOD_NAMES: &[(&str, Method)] = &[
("get", Method::GET),
("post", Method::POST),
("put", Method::PUT),
("delete", Method::DELETE),
("patch", Method::PATCH),
("head", Method::HEAD),
("options", Method::OPTIONS),
];
fn lock(def: &Mutex<AppDef>) -> mlua::Result<std::sync::MutexGuard<'_, AppDef>> {
def.lock()
.map_err(|_| mlua::Error::RuntimeError("the app definition lock is poisoned".into()))
}
pub(crate) type Site = Option<(String, u32)>;
struct RouteDef {
method: Method,
path: String,
fns: Vec<Function>,
error_fn: Option<Function>,
invalid_fn: Option<Function>,
input: Option<mlua::Table>,
doc: Option<mlua::Table>,
rate_limit: Option<(u32, std::time::Duration)>,
site: Site,
}
#[derive(Default)]
struct AppDef {
middleware: Vec<Function>,
routes: Vec<RouteDef>,
error_fn: Option<Function>,
invalid_fn: Option<Function>,
statics: Vec<crate::static_files::StaticMount>,
api_doc: Option<(mlua::Table, Site)>,
}
pub(crate) struct LuaApp(Arc<Mutex<AppDef>>);
pub(crate) struct LuaGroup {
def: Arc<Mutex<AppDef>>,
prefix: String,
state: Mutex<GroupState>,
}
#[derive(Default)]
struct GroupState {
middleware: Vec<Function>,
sealed: bool,
}
#[allow(clippy::too_many_arguments)]
fn register_route(
lua: &Lua,
def: &Mutex<AppDef>,
name: &str,
method: &Method,
prefix: &str,
group_middleware: &[Function],
path: String,
mut args: Variadic<Value>,
) -> mlua::Result<()> {
let options = match args.last() {
Some(Value::Table(opts)) => {
let parsed = route_options(name, &path, opts)?;
args.pop();
parsed
}
_ => options::RouteOptions::default(),
};
let route_fns = args
.into_iter()
.map(|value| match value {
Value::Function(f) => Ok(f),
other => Err(mlua::Error::RuntimeError(format!(
"app:{name}(\"{path}\", ...) takes handler functions \
and an optional trailing options table, got {}",
other.type_name()
))),
})
.collect::<mlua::Result<Vec<Function>>>()?;
if route_fns.is_empty() {
return Err(mlua::Error::RuntimeError(format!(
"app:{name}(\"{path}\", ...) requires a handler function"
)));
}
if !path.starts_with('/') {
return Err(mlua::Error::RuntimeError(format!(
"route path `{path}` must start with `/`"
)));
}
let mut fns = group_middleware.to_vec();
fns.extend(route_fns);
let site = caller_site(lua);
lock(def)?.routes.push(RouteDef {
method: method.clone(),
path: join_prefix(prefix, &path),
fns,
error_fn: options.error_fn,
invalid_fn: options.invalid_fn,
input: options.input,
doc: options.doc,
rate_limit: options.rate_limit,
site,
});
Ok(())
}
fn group_prefix(parent: &str, prefix: &str) -> mlua::Result<String> {
if !prefix.starts_with('/') {
return Err(mlua::Error::RuntimeError(format!(
"group prefix `{prefix}` must start with `/`"
)));
}
Ok(join_prefix(parent, prefix.trim_end_matches('/')))
}
fn join_prefix(prefix: &str, path: &str) -> String {
match path {
"/" if !prefix.is_empty() => prefix.to_string(),
_ => format!("{prefix}{path}"),
}
}
fn make_group(
lua: &Lua,
def: &Arc<Mutex<AppDef>>,
parent_prefix: &str,
middleware: Vec<Function>,
(prefix, body): (String, Option<Function>),
) -> mlua::Result<AnyUserData> {
let group = lua.create_userdata(LuaGroup {
def: def.clone(),
prefix: group_prefix(parent_prefix, &prefix)?,
state: Mutex::new(GroupState {
middleware,
sealed: false,
}),
})?;
if let Some(body) = body {
body.call::<()>(&group)?;
}
Ok(group)
}
impl UserData for LuaGroup {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
for (name, method) in METHOD_NAMES {
let method = method.clone();
methods.add_method(
*name,
move |lua, this, (path, args): (String, Variadic<Value>)| {
let middleware = {
let mut state = lock_group(&this.state)?;
state.sealed = true;
state.middleware.clone()
};
register_route(
lua,
&this.def,
name,
&method,
&this.prefix,
&middleware,
path,
args,
)
},
);
}
methods.add_method("use", |_, this, mw: Function| {
let mut state = lock_group(&this.state)?;
if state.sealed {
return Err(mlua::Error::RuntimeError(
"group:use() must be called before registering routes or nested groups".into(),
));
}
state.middleware.push(mw);
Ok(())
});
methods.add_method("group", |lua, this, args: (String, Option<Function>)| {
let middleware = {
let mut state = lock_group(&this.state)?;
state.sealed = true;
state.middleware.clone()
};
make_group(lua, &this.def, &this.prefix, middleware, args)
});
}
}
fn lock_group(state: &Mutex<GroupState>) -> mlua::Result<std::sync::MutexGuard<'_, GroupState>> {
state
.lock()
.map_err(|_| mlua::Error::RuntimeError("the group definition lock is poisoned".into()))
}
impl UserData for LuaApp {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
for (name, method) in METHOD_NAMES {
let method = method.clone();
methods.add_method(
*name,
move |lua, this, (path, args): (String, Variadic<Value>)| {
register_route(lua, &this.0, name, &method, "", &[], path, args)
},
);
}
methods.add_method("group", |lua, this, args: (String, Option<Function>)| {
make_group(lua, &this.0, "", Vec::new(), args)
});
methods.add_method("on_invalid", |_, this, f: Function| {
lock(&this.0)?.invalid_fn = Some(f);
Ok(())
});
methods.add_method("doc", |lua, this, table: mlua::Table| {
let site = caller_site(lua);
let mut def = lock(&this.0)?;
if let Some((_, first)) = &def.api_doc {
return Err(mlua::Error::RuntimeError(format!(
"app:doc() called twice\n --> {} (first call)\n --> {} (called again here)",
options::site_label(first),
options::site_label(&site)
)));
}
def.api_doc = Some((table, site));
Ok(())
});
methods.add_method("use", |_, this, mw: Function| {
let mut def = lock(&this.0)?;
if !def.routes.is_empty() {
return Err(mlua::Error::RuntimeError(
"app:use() must be called before registering routes".into(),
));
}
def.middleware.push(mw);
Ok(())
});
methods.add_method("on_error", |_, this, f: Function| {
lock(&this.0)?.error_fn = Some(f);
Ok(())
});
methods.add_method(
"static",
|_, this, (mount, dir, opts): (String, String, Option<mlua::Table>)| {
let (spa, cache_control, dotfiles) = match opts {
Some(opts) => (
opts.get::<Option<bool>>("spa")?.unwrap_or(false),
opts.get::<Option<String>>("cache_control")?,
opts.get::<Option<bool>>("dotfiles")?.unwrap_or(false),
),
None => (false, None, false),
};
lock(&this.0)?.statics.push(
crate::static_files::StaticMount::new(mount, dir, spa, cache_control)
.dotfiles(dotfiles),
);
Ok(())
},
);
}
}
pub(crate) struct Dispatch(pub(crate) Box<CompiledApp>);
pub(crate) struct Chain {
pub(crate) fns: Function,
pub(crate) handler: Function,
pub(crate) method: Method,
pub(crate) path: String,
pub(crate) site: Site,
pub(crate) error_fn: Option<Function>,
pub(crate) input: Option<(Arc<InputSchemas>, AnyUserData)>,
pub(crate) rate: Option<Arc<crate::protect::RateLimiter>>,
}
pub(crate) struct CompiledApp {
pub(crate) router: Arc<Router<HashMap<Method, usize>>>,
pub(crate) chains: Vec<Chain>,
}
pub(crate) enum Lookup {
Route {
index: usize,
params: Vec<(String, String)>,
},
Options(Vec<Method>),
MethodNotAllowed(Vec<Method>),
NotFound,
}
impl CompiledApp {
pub(crate) fn lookup(&self, method: &Method, path: &str) -> Lookup {
lookup(&self.router, method, path)
}
}
pub(crate) struct Routing {
router: Arc<Router<HashMap<Method, usize>>>,
fingerprint: u64,
pub(crate) statics: Arc<Vec<crate::static_files::StaticMount>>,
pub(crate) limits: Vec<Option<Arc<crate::protect::RateLimiter>>>,
}
impl Routing {
pub(crate) fn lookup(&self, method: &Method, path: &str) -> Lookup {
lookup(&self.router, method, path)
}
}
pub(crate) fn routing(lua: &Lua) -> Result<Routing> {
let ud = state(lua)?;
let state = ud.borrow::<AppState>()?;
let app = &state.dispatch.0;
Ok(Routing {
router: app.router.clone(),
fingerprint: state.fingerprint,
statics: state.statics.clone(),
limits: app.chains.iter().map(|chain| chain.rate.clone()).collect(),
})
}
pub(crate) fn routed_chain<R>(
lua: &Lua,
routing: &Routing,
index: usize,
take: impl FnOnce(&Chain) -> R,
) -> Result<Option<R>> {
let ud = state(lua)?;
let state = ud.borrow::<AppState>()?;
if state.fingerprint != routing.fingerprint {
return Ok(None);
}
Ok(state.dispatch.0.chains.get(index).map(take))
}
fn route_fingerprint(chains: &[Chain]) -> u64 {
use std::hash::{Hash as _, Hasher as _};
let mut hasher = std::hash::DefaultHasher::new();
for chain in chains {
chain.method.as_str().hash(&mut hasher);
chain.path.hash(&mut hasher);
}
hasher.finish()
}
fn lookup(router: &Router<HashMap<Method, usize>>, method: &Method, path: &str) -> Lookup {
let Ok(matched) = router.at(path) else {
return Lookup::NotFound;
};
let route = matched.value.get(method).or_else(|| {
(*method == Method::HEAD)
.then(|| matched.value.get(&Method::GET))
.flatten()
});
match route {
Some(&index) => Lookup::Route {
index,
params: matched
.params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
},
None if *method == Method::OPTIONS => {
Lookup::Options(matched.value.keys().cloned().collect())
}
None => Lookup::MethodNotAllowed(matched.value.keys().cloned().collect()),
}
}
pub(crate) fn script_path(lua: &Lua) -> Option<PathBuf> {
state(lua)
.ok()
.and_then(|ud| ud.borrow::<AppState>().ok().map(|s| s.script.clone()))
}
pub(crate) struct AppState {
pub(crate) dispatch: Dispatch,
pub(crate) statics: Arc<Vec<crate::static_files::StaticMount>>,
#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
pub(crate) meta: Arc<AppMeta>,
fingerprint: u64,
script: PathBuf,
}
impl UserData for AppState {}
pub(crate) fn register_nitr_app(lua: &Lua) -> Result<()> {
let nitr = nitr_core::nitr_table(lua)?;
nitr.set(
"app",
lua.create_function(|_, ()| Ok(LuaApp(Arc::new(Mutex::new(AppDef::default())))))?,
)?;
Ok(())
}
pub(crate) fn load(
lua: &Lua,
script: &Path,
base_statics: &[crate::static_files::StaticMount],
input_env: &InputEnv,
) -> Result<bool> {
let value = nitr_core::eval_script(lua, script)?;
let compiled = compile(lua, value, script, input_env)?;
let has_files = compiled
.dispatch
.0
.chains
.iter()
.any(|c| c.input.as_ref().is_some_and(|(i, _)| i.has_file_rules()));
nitr_std::validation::freeze_messages(lua);
let mut statics = compiled.statics;
let script_dir = script.parent().unwrap_or_else(|| Path::new("."));
for mount in &mut statics {
if mount.dir.is_relative() {
mount.dir = script_dir.join(&mount.dir);
}
}
if input_env.static_dirs_optional {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
statics.retain(|mount| {
let exists = mount.dir.is_dir();
if !exists && !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
tracing::warn!(
"app:static(\"{}\", ...): directory {} does not exist yet: the mount is \
skipped by this command, and `nitr run` refuses it",
mount.mount,
mount.dir.display()
);
}
exists
});
} else if let Some(mount) = statics.iter().find(|mount| !mount.dir.is_dir()) {
return Err(Error::Script(format!(
"app:static(\"{}\", ...): directory {} does not exist; a relative \
directory is resolved against the handler script's",
mount.mount,
mount.dir.display()
)));
}
statics.extend_from_slice(base_statics);
statics.sort_by_key(|m| std::cmp::Reverse(m.mount.len()));
let fingerprint = route_fingerprint(&compiled.dispatch.0.chains);
let state = lua.create_userdata(AppState {
dispatch: compiled.dispatch,
statics: Arc::new(statics),
meta: Arc::new(compiled.meta),
fingerprint,
script: script.to_path_buf(),
})?;
lua.set_named_registry_value(APP_STATE_KEY, state)?;
Ok(has_files)
}
pub(crate) fn state(lua: &Lua) -> Result<AnyUserData> {
lua.named_registry_value::<AnyUserData>(APP_STATE_KEY)
.map_err(|_| Error::Script("no HTTP handler has been loaded".into()))
}
#[cfg(test)]
mod tests {
use super::*;
fn loaded(script: &str) -> (Lua, tempfile_path::Guard) {
let lua = Lua::new();
let path = tempfile_path::write("routing", script);
register_nitr_app(&lua).expect("nitr.app");
let env = InputEnv {
upload_root: None,
reserved: Vec::new(),
trust_forwarded_for: false,
static_dirs_optional: false,
};
load(&lua, &path.0, &[], &env).expect("load");
(lua, path)
}
#[test]
fn shared_routing_only_applies_to_a_state_with_the_same_route_set() {
let (a, _ka) = loaded(
"local app = nitr.app()
app:get('/a/:id', function() end)
return app",
);
let (b, _kb) = loaded(
"local app = nitr.app()
app:get('/a/:id', function() end)
app:get('/a/special', function() end)
return app",
);
let routing_a = routing(&a).expect("routing");
let Lookup::Route { index, .. } = routing_a.lookup(&Method::GET, "/a/special") else {
panic!("a routes /a/special to its :id route");
};
assert!(
routed_chain(&a, &routing_a, index, |chain| chain.path.clone())
.expect("same state")
.is_some()
);
assert!(
routed_chain(&b, &routing_a, index, |chain| chain.path.clone())
.expect("other state")
.is_none(),
"a state with another route set routes itself"
);
}
}
#[cfg(test)]
mod tempfile_path {
use std::path::PathBuf;
pub(super) struct Guard(pub(super) PathBuf);
impl Drop for Guard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
pub(super) fn write(label: &str, content: &str) -> Guard {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("nitr-app-{label}-{}-{id}.lua", std::process::id()));
std::fs::write(&path, content).expect("write script");
Guard(path)
}
}