use mlua::{
FromLuaMulti, Function, HookTriggers, IntoLuaMulti, Lua, LuaOptions, LuaSerdeExt as _, StdLib,
Table, Thread, Value, Variadic, VmState, chunk::ChunkMode,
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::error::{Error, Result};
pub(crate) mod pool;
mod script;
pub use script::eval_script;
use script::load_error;
#[cfg(test)]
mod tests;
pub use pool::{RuntimeGuard, RuntimePool};
const MEMORY_LIMIT: usize = 8 * 1024 * 1024;
const EXEC_TIMEOUT: Duration = Duration::from_secs(30);
const HOOK_INSTRUCTION_INTERVAL: u32 = 4000;
const EXEC_TIMEOUT_GRACE: Duration = Duration::from_millis(100);
const PRELUDE: &str = r##"
local tripped, budget_msg = ...
local raw_load, raw_pcall, raw_xpcall = load, pcall, xpcall
local raw_setmetatable, rawget, type = setmetatable, rawget, type
local select, error = select, error
local function checked_load(chunk, ...)
if chunk == nil and tripped() then error(budget_msg, 0) end
return chunk, ...
end
load = function(chunk, name, _, ...)
if select("#", ...) > 0 then
return checked_load(raw_load(chunk, name, "t", (...)))
end
return checked_load(raw_load(chunk, name, "t"))
end
if string then string.dump = nil end
if loadfile then
local raw_loadfile = loadfile
loadfile = function(name, _, ...)
if select("#", ...) > 0 then
return raw_loadfile(name, "t", (...))
end
return raw_loadfile(name, "t")
end
dofile = function(name)
local chunk, err = raw_loadfile(name, "t")
if not chunk then error(err, 0) end
return chunk()
end
end
setmetatable = function(t, mt)
if type(mt) == "table" and rawget(mt, "__gc") ~= nil then
error("setmetatable: __gc finalizers are not allowed", 2)
end
return raw_setmetatable(t, mt)
end
-- Cost, measured with the `pcall` group in crates/nitr/benches/runtime.rs
-- (2026-09-03): the two extra frames and vararg round trips make a
-- successful pcall about 100 ns slower (10 000 calls: 1.12 ms stock,
-- 2.14 ms wrapped). Kept as is: the success path never crosses into
-- Rust, and the uncatchable budget error is what stops
-- `while true do pcall(...) end` from pinning a worker.
local function guard(ok, ...)
if not ok and tripped() then error(budget_msg, 0) end
return ok, ...
end
pcall = function(...) return guard(raw_pcall(...)) end
xpcall = function(...) return guard(raw_xpcall(...)) end
if coroutine then
local raw_resume = coroutine.resume
coroutine.resume = function(...) return guard(raw_resume(...)) end
end
"##;
#[derive(Debug)]
pub struct Runtime {
lua: Lua,
cfg: Option<Table>,
thread: Option<Thread>,
deadline: Arc<AtomicU64>,
epoch: Instant,
poisoned: bool,
opts: RuntimeOpts,
}
#[derive(Debug, Clone)]
pub struct DeadlineHandle {
deadline: Arc<AtomicU64>,
epoch: Instant,
budget: Option<Duration>,
}
impl DeadlineHandle {
pub fn extend(&self) {
if let Some(budget) = self.budget {
self.deadline.store(
(self.epoch.elapsed() + budget).as_nanos() as u64,
Ordering::Relaxed,
);
}
}
}
struct Armed<'a>(&'a Runtime);
impl Drop for Armed<'_> {
fn drop(&mut self) {
self.0.clear_deadline();
}
}
#[derive(Debug)]
pub struct RuntimeOpts {
pub libs: mlua::StdLib,
pub memory_limit: usize,
pub dev_mode: bool,
pub exec_timeout: Option<Duration>,
pub package_dir: Option<PathBuf>,
pub extra_package_dirs: Vec<PathBuf>,
}
impl Runtime {
pub fn new() -> Result<Self> {
Runtime::new_with(RuntimeOpts {
libs: StdLib::NONE
| StdLib::MATH
| StdLib::TABLE
| StdLib::STRING
| StdLib::UTF8
| StdLib::COROUTINE,
memory_limit: MEMORY_LIMIT,
dev_mode: false,
exec_timeout: Some(EXEC_TIMEOUT),
package_dir: None,
extra_package_dirs: Vec::new(),
})
}
pub fn new_with(opts: RuntimeOpts) -> Result<Self> {
let lua = Lua::new_with(opts.libs, LuaOptions::default())?;
lua.set_memory_limit(opts.memory_limit)?;
if !opts.libs.contains(StdLib::IO) {
let globals = lua.globals();
globals.set("dofile", Value::Nil)?;
globals.set("loadfile", Value::Nil)?;
}
lua.globals().set("collectgarbage", Value::Nil)?;
if opts.libs.contains(StdLib::PACKAGE) {
let package: Table = lua.globals().get("package")?;
package.set("loadlib", Value::Nil)?;
package.set("cpath", "")?;
package.set("searchpath", Value::Nil)?;
if let Some(dir) = &opts.package_dir {
let roots: Vec<PathBuf> = std::iter::once(dir)
.chain(&opts.extra_package_dirs)
.cloned()
.collect();
let shown = roots
.iter()
.map(|root| {
let shown = root.to_string_lossy();
format!("{shown}/?.lua;{shown}/?/init.lua")
})
.collect::<Vec<_>>()
.join(";");
package.set("path", shown)?;
let searchers: Table = package.get("searchers")?;
let preload: Value = searchers.get(1)?;
let confined = lua.create_table()?;
confined.set(1, preload)?;
confined.set(2, confined_searcher(&lua, roots)?)?;
package.set("searchers", confined)?;
}
}
let deadline = Arc::new(AtomicU64::new(u64::MAX));
let epoch = Instant::now();
let tripped = {
let deadline = deadline.clone();
lua.create_function(move |_, ()| {
Ok(epoch.elapsed().as_nanos() as u64 > deadline.load(Ordering::Relaxed))
})?
};
lua.load(PRELUDE)
.set_name("=nitr-prelude")
.call::<()>((tripped, crate::error::EXEC_BUDGET_MSG))?;
if opts.exec_timeout.is_some() {
let deadline = deadline.clone();
lua.set_global_hook(
HookTriggers::new().every_nth_instruction(HOOK_INSTRUCTION_INTERVAL),
move |_, _| {
if epoch.elapsed().as_nanos() as u64 > deadline.load(Ordering::Relaxed) {
return Err(mlua::Error::RuntimeError(
crate::error::EXEC_BUDGET_MSG.into(),
));
}
Ok(VmState::Continue)
},
)?;
}
Ok(Self {
lua,
cfg: None,
thread: None,
deadline,
epoch,
poisoned: false,
opts,
})
}
pub fn is_poisoned(&self) -> bool {
self.poisoned
}
pub fn poison(&mut self) {
self.poisoned = true;
}
pub fn register_module<F>(&self, name: &str, f: F) -> Result
where
F: Fn(&Lua) -> mlua::Result<Table>,
{
let value = f(&self.lua)?;
crate::ns::mount(&self.lua, name, value)
}
pub async fn register_cfg_fn(&mut self, cfg_src: &Path, args: impl IntoLuaMulti) -> Result {
let data = std::fs::read(cfg_src).map_err(|err| {
Error::Script(format!(
"failed to read the Lua configuration file {}: {err}",
cfg_src.display()
))
})?;
let chunk = self
.load_chunk(data, cfg_src)
.map_err(|err| load_error(cfg_src, err))?;
let value = {
let _armed = self.arm();
let call = chunk.call_async::<Value>(args);
match self.opts.exec_timeout {
Some(timeout) => tokio::time::timeout(timeout + EXEC_TIMEOUT_GRACE, call)
.await
.map_err(|_| Error::Timeout)?,
None => call.await,
}
.map_err(|err| load_error(cfg_src, err))?
};
let cfg = match value {
Value::Table(cfg) => cfg,
Value::Function(_) => {
return Err(Error::Script(format!(
"the configuration script {} returned a function; the \
`function(db) ... end` wrapper is no longer supported — \
take arguments via `local db = ...` at the top level and \
end the script with `return {{ ... }}`",
cfg_src.display()
)));
}
other => {
return Err(Error::Script(format!(
"the configuration script {} must return a table, got {}",
cfg_src.display(),
other.type_name()
)));
}
};
self.cfg = Some(cfg);
Ok(())
}
pub fn lua(&self) -> &Lua {
&self.lua
}
pub fn cfg(&self) -> Option<&Table> {
self.cfg.as_ref()
}
pub fn cfg_snapshot(&self) -> Result<Option<serde_json::Value>> {
let Some(cfg) = &self.cfg else {
return Ok(None);
};
let snapshot = serde_json::to_value(cfg).map_err(|err| {
Error::Config(format!(
"the configuration script must return plain data \
(tables, strings, numbers, booleans): {err}"
))
})?;
Ok(Some(snapshot))
}
pub fn set_cfg_snapshot(&mut self, snapshot: &serde_json::Value) -> Result {
match self.lua.to_value(snapshot)? {
Value::Table(table) => {
self.cfg = Some(table);
Ok(())
}
_ => Err(Error::Config(
"the configuration snapshot must be a table".into(),
)),
}
}
fn handler_thread(&mut self, http_fn: Function) -> Result<Thread> {
if let Some(thread) = self.thread.take()
&& thread.reset(http_fn.clone()).is_ok()
{
return Ok(thread);
}
Ok(self.lua.create_thread(http_fn)?)
}
pub async fn call_function<R: FromLuaMulti>(
&mut self,
f: Function,
args: impl IntoLuaMulti,
) -> Result<R> {
let thread = self.handler_thread(f.clone())?;
let result = match self.opts.exec_timeout {
Some(timeout) => {
self.deadline.store(
(self.epoch.elapsed() + timeout).as_nanos() as u64,
Ordering::Relaxed,
);
let timed = tokio::time::timeout(
timeout + EXEC_TIMEOUT_GRACE,
thread.clone().into_async::<R>(args)?,
)
.await;
match timed {
Ok(result) => result,
Err(_) => {
let _ = thread.reset(f);
let _ = self.lua.gc_collect();
self.thread = Some(thread);
self.clear_deadline();
return Err(Error::Timeout);
}
}
}
None => thread.clone().into_async::<R>(args)?.await,
};
self.thread = Some(thread);
self.clear_deadline();
self.classify(result)
}
fn arm(&self) -> Armed<'_> {
if let Some(timeout) = self.opts.exec_timeout {
self.deadline.store(
(self.epoch.elapsed() + timeout).as_nanos() as u64,
Ordering::Relaxed,
);
}
Armed(self)
}
pub fn budgeted<R>(&self, f: impl FnOnce(&Lua) -> Result<R>) -> Result<R> {
let _armed = self.arm();
f(&self.lua)
}
fn clear_deadline(&self) {
self.deadline.store(u64::MAX, Ordering::Relaxed);
}
pub async fn call_function_streaming<R: FromLuaMulti>(
&mut self,
f: Function,
args: impl IntoLuaMulti,
) -> Result<R> {
let thread = self.handler_thread(f)?;
if let Some(timeout) = self.opts.exec_timeout {
self.deadline.store(
(self.epoch.elapsed() + timeout).as_nanos() as u64,
Ordering::Relaxed,
);
}
let result = thread.clone().into_async::<R>(args)?.await;
self.thread = Some(thread);
self.clear_deadline();
self.classify(result)
}
fn classify<R>(&mut self, result: mlua::Result<R>) -> Result<R> {
match result {
Ok(value) => Ok(value),
Err(err) => {
let err = Error::from(err);
if err.poisons_state() {
self.poisoned = true;
}
Err(err)
}
}
}
pub fn deadline_handle(&self) -> DeadlineHandle {
DeadlineHandle {
deadline: self.deadline.clone(),
epoch: self.epoch,
budget: self.opts.exec_timeout,
}
}
pub fn dev_mode(&self) -> bool {
self.opts.dev_mode
}
}
fn confined_searcher(lua: &Lua, roots: Vec<PathBuf>) -> mlua::Result<Function> {
lua.create_function(move |lua, name: String| {
let well_formed = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
&& name.split('.').all(|segment| !segment.is_empty());
if !well_formed {
let note = format!(
"\n\tmodule name '{name}' is not a dotted identifier (letters, digits and '_' \
between dots)"
);
return Ok(Variadic::from_iter([Value::String(
lua.create_string(note)?,
)]));
}
let rel = name.replace('.', "/");
let mut tried = String::new();
let candidates = roots.iter().flat_map(|dir| {
[
dir.join(format!("{rel}.lua")),
dir.join(&rel).join("init.lua"),
]
});
for candidate in candidates {
match std::fs::read(&candidate) {
Ok(data) => {
let loader = lua
.load(data)
.set_name(format!("@{}", candidate.display()))
.set_mode(ChunkMode::Text)
.into_function()?;
let path = lua.create_string(candidate.to_string_lossy().as_bytes())?;
return Ok(Variadic::from_iter([
Value::Function(loader),
Value::String(path),
]));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
tried.push_str(&format!("\n\tno file '{}'", candidate.display()));
}
Err(err) => {
return Err(mlua::Error::RuntimeError(format!(
"failed to read module '{name}' at {}: {err}",
candidate.display()
)));
}
}
}
Ok(Variadic::from_iter([Value::String(
lua.create_string(tried)?,
)]))
})
}