nitr_core/runtime/mod.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
6use mlua::{
7 FromLuaMulti, Function, HookTriggers, IntoLuaMulti, Lua, LuaOptions, LuaSerdeExt as _, StdLib,
8 Table, Thread, Value, Variadic, VmState, chunk::ChunkMode,
9};
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::time::{Duration, Instant};
14
15use crate::error::{Error, Result};
16
17pub(crate) mod pool;
18mod script;
19pub use script::eval_script;
20use script::load_error;
21#[cfg(test)]
22mod tests;
23
24pub use pool::{RuntimeGuard, RuntimePool};
25
26const MEMORY_LIMIT: usize = 8 * 1024 * 1024; // 8 MiB
27
28/// Default wall-clock budget per handler invocation.
29const EXEC_TIMEOUT: Duration = Duration::from_secs(30);
30
31/// How often (in Lua VM instructions) the execution-deadline hook runs.
32///
33/// Not a throughput knob. While a count hook is set, Lua 5.4 keeps the
34/// interpreter on its trap path for *every* instruction (`luaG_traceexec`
35/// returns 1 whenever the counter has not reached zero — `ldebug.c`), so
36/// the cost is per instruction whatever the interval; the interval only
37/// decides how often the Rust closure runs. Measured with the `hook`
38/// group in `crates/nitr/benches/runtime.rs` (2026-09-03, i7-6500U): a
39/// 100 000-iteration arithmetic loop takes 0.99 ms without the hook and
40/// 2.08 ms with it, and 2.06 ms at 4 000, 40 000 and 400 000 alike. That
41/// factor of two on pure interpreter time is the price of stopping
42/// `while true do end`, and raising this value would not recover any of
43/// it — it would only coarsen the deadline's resolution.
44const HOOK_INSTRUCTION_INTERVAL: u32 = 4000;
45
46/// Extra wall-clock grace given to the outer async timeout so the
47/// instruction hook (with its precise error message) fires first for
48/// CPU-bound overruns.
49const EXEC_TIMEOUT_GRACE: Duration = Duration::from_millis(100);
50
51/// The base-library patches every state carries, applied once at
52/// construction before any script loads.
53///
54/// **Text-only `load`.** Lua 5.4 performs no bytecode verification, so a
55/// hand-patched binary chunk (out-of-range register or constant indices)
56/// is type confusion inside the VM and, from there, arbitrary memory
57/// access in the process — a complete escape from the sandbox the memory
58/// limit and instruction hook enforce. The stock `load` defaults its mode
59/// to `"bt"`; this wrapper pins it to `"t"` whatever the caller asked for,
60/// and `string.dump` goes too, since producing bytecode is the other half
61/// of that primitive. `loadfile` and `dofile`, present only with `io`,
62/// are pinned the same way. The wrapper preserves the argument count: an
63/// explicit `nil` environment is not the same as an absent one.
64///
65/// **An uncatchable budget error.** The instruction hook raises an
66/// ordinary Lua error when the deadline passes, and the count restarts at
67/// every fire, so `while true do pcall(function() while true do end end)
68/// end` catches every trip inside the inner function and never lets the
69/// outer loop accumulate enough instructions to trip on its own — one
70/// request then holds a pooled state and a worker thread forever, past
71/// every timeout, because nothing ever yields. `pcall`, `xpcall`,
72/// `coroutine.resume` and a `load` reader function are the doors a caught
73/// error can come back through; each is wrapped so a failure caught
74/// *after* the deadline is re-raised as the budget error. The wrappers
75/// are Lua functions rather than Rust callbacks so a body that yields (an
76/// async builtin inside `pcall`) keeps working. The wrappers are inert
77/// until a deadline is armed: a budgeted call, or the load of a script.
78///
79/// **No finalizers.** Lua runs `__gc` metamethods with hooks disabled, so
80/// a finalizer is out of the budget's reach and a spinning one never
81/// returns. `setmetatable` refuses a metatable carrying `__gc`; Lua only
82/// registers a finalizer when the field is present at that call.
83const PRELUDE: &str = r##"
84local tripped, budget_msg = ...
85local raw_load, raw_pcall, raw_xpcall = load, pcall, xpcall
86local raw_setmetatable, rawget, type = setmetatable, rawget, type
87local select, error = select, error
88
89local function checked_load(chunk, ...)
90 if chunk == nil and tripped() then error(budget_msg, 0) end
91 return chunk, ...
92end
93load = function(chunk, name, _, ...)
94 if select("#", ...) > 0 then
95 return checked_load(raw_load(chunk, name, "t", (...)))
96 end
97 return checked_load(raw_load(chunk, name, "t"))
98end
99if string then string.dump = nil end
100
101if loadfile then
102 local raw_loadfile = loadfile
103 loadfile = function(name, _, ...)
104 if select("#", ...) > 0 then
105 return raw_loadfile(name, "t", (...))
106 end
107 return raw_loadfile(name, "t")
108 end
109 dofile = function(name)
110 local chunk, err = raw_loadfile(name, "t")
111 if not chunk then error(err, 0) end
112 return chunk()
113 end
114end
115
116setmetatable = function(t, mt)
117 if type(mt) == "table" and rawget(mt, "__gc") ~= nil then
118 error("setmetatable: __gc finalizers are not allowed", 2)
119 end
120 return raw_setmetatable(t, mt)
121end
122
123-- Cost, measured with the `pcall` group in crates/nitr/benches/runtime.rs
124-- (2026-09-03): the two extra frames and vararg round trips make a
125-- successful pcall about 100 ns slower (10 000 calls: 1.12 ms stock,
126-- 2.14 ms wrapped). Kept as is: the success path never crosses into
127-- Rust, and the uncatchable budget error is what stops
128-- `while true do pcall(...) end` from pinning a worker.
129local function guard(ok, ...)
130 if not ok and tripped() then error(budget_msg, 0) end
131 return ok, ...
132end
133pcall = function(...) return guard(raw_pcall(...)) end
134xpcall = function(...) return guard(raw_xpcall(...)) end
135if coroutine then
136 local raw_resume = coroutine.resume
137 coroutine.resume = function(...) return guard(raw_resume(...)) end
138end
139"##;
140
141/// The Lua runtime that provides an interface to execute Lua scripts and manage Lua state.
142/// It allows for registering Rust extension modules on the `nitr` namespace,
143/// running a configuration script, and calling Lua functions under the
144/// state's execution budget.
145#[derive(Debug)]
146pub struct Runtime {
147 lua: Lua,
148 cfg: Option<Table>,
149 /// Cached handler coroutine, reset and reused across requests to avoid
150 /// per-request thread allocation and hook installation.
151 thread: Option<Thread>,
152 /// Execution deadline for the instruction hook, in nanoseconds since
153 /// `epoch`. Stored atomically so the hook closure (installed once for
154 /// the whole state) reads the current request's deadline without
155 /// locking.
156 deadline: Arc<AtomicU64>,
157 epoch: Instant,
158 /// Set when a failure leaves this state unfit for reuse (memory limit
159 /// hit, panic). The pool rebuilds a poisoned state instead of handing
160 /// it to the next request.
161 poisoned: bool,
162 opts: RuntimeOpts,
163}
164
165/// Grants additional execution budget to a runtime while it produces a
166/// streaming response: each chunk handed to the client resets the
167/// instruction-hook deadline, so the budget applies per chunk-production
168/// slice instead of to the total stream lifetime.
169#[derive(Debug, Clone)]
170pub struct DeadlineHandle {
171 deadline: Arc<AtomicU64>,
172 epoch: Instant,
173 budget: Option<Duration>,
174}
175
176impl DeadlineHandle {
177 /// Grants another full execution budget from now. A no-op when the
178 /// runtime has no execution timeout configured.
179 pub fn extend(&self) {
180 if let Some(budget) = self.budget {
181 self.deadline.store(
182 (self.epoch.elapsed() + budget).as_nanos() as u64,
183 Ordering::Relaxed,
184 );
185 }
186 }
187}
188
189/// A deadline armed by [`Runtime::arm`], lifted on drop.
190struct Armed<'a>(&'a Runtime);
191
192impl Drop for Armed<'_> {
193 fn drop(&mut self) {
194 self.0.clear_deadline();
195 }
196}
197
198/// Options for configuring the Lua runtime.
199#[derive(Debug)]
200pub struct RuntimeOpts {
201 /// Lua standard libraries to load.
202 pub libs: mlua::StdLib,
203 /// Lua memory limit in bytes.
204 pub memory_limit: usize,
205 /// Development mode: reload the HTTP handler script before each call and
206 /// include error details (Lua tracebacks) in error responses.
207 pub dev_mode: bool,
208 /// Execution budget per handler invocation, enforced by an
209 /// instruction-count hook (CPU-bound loops) and an outer async timeout
210 /// (slow I/O). `None` disables both.
211 pub exec_timeout: Option<Duration>,
212 /// Directory `require` is confined to: `package.path` is pinned to it.
213 /// `None` skips only the pinning — every `package`-bearing state has
214 /// `package.loadlib` removed and `package.cpath` emptied regardless, so
215 /// native modules can never load.
216 pub package_dir: Option<PathBuf>,
217 /// Further `require` roots, tried in order after
218 /// [`package_dir`](Self::package_dir), each under the same rules (a
219 /// dotted-identifier name, text-only chunks, no path from
220 /// `package.path`). Ignored without a `package_dir`. `nitr test`
221 /// puts its tests directory here, so shared helpers load in test
222 /// states and never in the states that serve requests.
223 pub extra_package_dirs: Vec<PathBuf>,
224}
225
226impl Runtime {
227 /// It creates a new Lua runtime with default options.
228 ///
229 /// Such as some **built-in** libraries loaded and a default memory limit.
230 ///
231 /// `package` is not among them, so `require` is unavailable: confinement
232 /// needs a directory to pin to, and this constructor takes no arguments to
233 /// name one. Embedders that want module loading call [`Runtime::new_with`]
234 /// with both [`StdLib::PACKAGE`] and a
235 /// [`package_dir`](RuntimeOpts::package_dir).
236 pub fn new() -> Result<Self> {
237 // `io` and `os` are deliberately excluded from the defaults: they
238 // give scripts ambient filesystem/process access. Opt in via
239 // `RuntimeOpts::libs` when needed.
240 //
241 // `package` is excluded for a different reason: its confinement is
242 // conditional on `package_dir`, which this constructor cannot supply,
243 // so enabling it here would hand out a stock `package.path`. A default
244 // that is safe but less capable is the right default for a library.
245 Runtime::new_with(RuntimeOpts {
246 libs: StdLib::NONE
247 | StdLib::MATH
248 | StdLib::TABLE
249 | StdLib::STRING
250 | StdLib::UTF8
251 | StdLib::COROUTINE,
252 memory_limit: MEMORY_LIMIT,
253 dev_mode: false,
254 exec_timeout: Some(EXEC_TIMEOUT),
255 package_dir: None,
256 extra_package_dirs: Vec::new(),
257 })
258 }
259
260 /// It creates a new Lua runtime with specified options.
261 ///
262 /// For example, it allows for customizing the Lua standard libraries to load
263 /// like `io`, `math`, `os`, etc as well as the memory limits.
264 ///
265 /// Some scrubbing applies to every state, whatever the options:
266 /// `collectgarbage` is always removed (the memory limit is enforced by
267 /// the allocator, not the collector), and `package`-bearing states can
268 /// never load native modules — see
269 /// [`package_dir`](RuntimeOpts::package_dir).
270 pub fn new_with(opts: RuntimeOpts) -> Result<Self> {
271 let lua = Lua::new_with(opts.libs, LuaOptions::default())?;
272 lua.set_memory_limit(opts.memory_limit)?;
273
274 // The base library is always loaded, and it carries `dofile` and
275 // `loadfile` — reading and executing arbitrary files is the same
276 // ambient authority the excluded-by-default `io` library gates.
277 // They follow the same opt-in: absent unless IO was requested.
278 if !opts.libs.contains(StdLib::IO) {
279 let globals = lua.globals();
280 globals.set("dofile", Value::Nil)?;
281 globals.set("loadfile", Value::Nil)?;
282 }
283
284 // Not a confinement escape: the memory limit is enforced by the
285 // allocator, not the collector, so `collectgarbage("stop")` only
286 // reaches that limit sooner and poisons the state. It goes because no
287 // Nitr script has business pacing the collector, and `("count")` is a
288 // heap oracle.
289 lua.globals().set("collectgarbage", Value::Nil)?;
290
291 // Forbid loading native modules in every `package`-bearing state,
292 // not only the confined ones. mlua's safe constructor already stubs
293 // `package.loadlib` and the C-library searchers (`searchers[3]` is
294 // replaced, `[4]` removed — see mlua's `disable_c_modules`), so this
295 // is defense-in-depth over that guarantee, not the load-bearing
296 // layer: it is the scrub Nitr owns and tests, and the one that would
297 // survive if the state were ever built another way.
298 if opts.libs.contains(StdLib::PACKAGE) {
299 let package: Table = lua.globals().get("package")?;
300 package.set("loadlib", Value::Nil)?;
301 package.set("cpath", "")?;
302 // `searchpath(name, template)` takes its template as an
303 // argument, never from `package.path`, so no pinning reaches
304 // it: `package.searchpath("passwd", "/etc/?")` answers whether
305 // any file on the box exists and is readable. Nothing in Nitr
306 // uses it (the confined searcher below does its own lookup).
307 package.set("searchpath", Value::Nil)?;
308
309 // Confine `require` to the configured directory. Only the
310 // pinning is conditional: without a directory there is nothing
311 // to pin to.
312 //
313 // `package.path` is set for anything that reads it, but it is
314 // not what confines: the stock file searcher would honor a
315 // script's later reassignment of `package.path`, and it loads
316 // whatever it finds in whatever mode — bytecode included. The
317 // searcher installed here owns the directory itself, maps the
318 // module name to a path without ever consulting `package.path`,
319 // and compiles text only.
320 if let Some(dir) = &opts.package_dir {
321 let roots: Vec<PathBuf> = std::iter::once(dir)
322 .chain(&opts.extra_package_dirs)
323 .cloned()
324 .collect();
325 let shown = roots
326 .iter()
327 .map(|root| {
328 let shown = root.to_string_lossy();
329 format!("{shown}/?.lua;{shown}/?/init.lua")
330 })
331 .collect::<Vec<_>>()
332 .join(";");
333 package.set("path", shown)?;
334 let searchers: Table = package.get("searchers")?;
335 let preload: Value = searchers.get(1)?;
336 let confined = lua.create_table()?;
337 confined.set(1, preload)?;
338 confined.set(2, confined_searcher(&lua, roots)?)?;
339 package.set("searchers", confined)?;
340 }
341 }
342
343 let deadline = Arc::new(AtomicU64::new(u64::MAX));
344 let epoch = Instant::now();
345
346 // See `PRELUDE`. The tripped check reads the same deadline the hook
347 // does, so the two cannot disagree about whether the budget is gone.
348 let tripped = {
349 let deadline = deadline.clone();
350 lua.create_function(move |_, ()| {
351 Ok(epoch.elapsed().as_nanos() as u64 > deadline.load(Ordering::Relaxed))
352 })?
353 };
354 lua.load(PRELUDE)
355 .set_name("=nitr-prelude")
356 .call::<()>((tripped, crate::error::EXEC_BUDGET_MSG))?;
357
358 // Instruction-count hook: the only mechanism that can stop a
359 // CPU-bound loop (`while true do end` never reaches an await point,
360 // blocking both the async timeout and the executor).
361 //
362 // It is installed *globally* rather than per coroutine: Lua 5.4
363 // propagates a state's hook to threads created from it, so a
364 // `coroutine.create` inside a handler inherits the budget instead of
365 // escaping it.
366 if opts.exec_timeout.is_some() {
367 let deadline = deadline.clone();
368 lua.set_global_hook(
369 HookTriggers::new().every_nth_instruction(HOOK_INSTRUCTION_INTERVAL),
370 move |_, _| {
371 if epoch.elapsed().as_nanos() as u64 > deadline.load(Ordering::Relaxed) {
372 return Err(mlua::Error::RuntimeError(
373 crate::error::EXEC_BUDGET_MSG.into(),
374 ));
375 }
376 Ok(VmState::Continue)
377 },
378 )?;
379 }
380
381 Ok(Self {
382 lua,
383 cfg: None,
384 thread: None,
385 deadline,
386 epoch,
387 poisoned: false,
388 opts,
389 })
390 }
391
392 /// Whether a failure has left this state unfit for reuse (a memory
393 /// limit hit or a caught panic). The pool rebuilds a poisoned state
394 /// rather than handing it to the next request.
395 pub fn is_poisoned(&self) -> bool {
396 self.poisoned
397 }
398
399 /// Marks this state unfit for reuse. Used by the HTTP layer when a
400 /// panic is caught while the state is checked out.
401 pub fn poison(&mut self) {
402 self.poisoned = true;
403 }
404
405 /// Registers a Rust extension module: the closure runs now (and its
406 /// result is a table by Lua module convention), mounted at
407 /// `nitr.ext.<name>` — one level below the standard library, so a
408 /// module can never collide with a builtin. Fails when the name is
409 /// already taken, so two extensions cannot shadow each other.
410 ///
411 /// This is the embedding-side extension point; HTTP applications use
412 /// `ServerBuilder::module()` in the `nitr-http` crate, which applies
413 /// the closure to every pooled state.
414 ///
415 /// ## Error attribution
416 ///
417 /// An error a module raises should say which module failed. Wrap Rust
418 /// errors with a `module <name>` context and [`ErrorInfo`] classifies
419 /// them as `kind = "module"` with the module named; a module that
420 /// returns an opaque string makes its failures everyone's problem:
421 ///
422 /// ```ignore
423 /// t.set("query", lua.create_function(|_, sql: String| {
424 /// run(&sql).map_err(|err| mlua::Error::WithContext {
425 /// context: "module db".into(),
426 /// cause: std::sync::Arc::new(mlua::Error::external(err)),
427 /// })
428 /// })?)?;
429 /// ```
430 ///
431 /// [`ErrorInfo`]: crate::ErrorInfo
432 pub fn register_module<F>(&self, name: &str, f: F) -> Result
433 where
434 F: Fn(&Lua) -> mlua::Result<Table>,
435 {
436 let value = f(&self.lua)?;
437 crate::ns::mount(&self.lua, name, value)
438 }
439
440 /// It sets the Lua configuration script that runs once at server startup.
441 ///
442 /// The script is a plain Lua chunk in the same shape handler scripts
443 /// use: statements at the top level ending in `return { ... }`, with
444 /// the provided arguments available as its varargs (`local db = ...`).
445 ///
446 /// The Lua table containing the configuration fields can be accessed later
447 /// using the [`cfg()`](Self::cfg) method.
448 pub async fn register_cfg_fn(&mut self, cfg_src: &Path, args: impl IntoLuaMulti) -> Result {
449 let data = std::fs::read(cfg_src).map_err(|err| {
450 Error::Script(format!(
451 "failed to read the Lua configuration file {}: {err}",
452 cfg_src.display()
453 ))
454 })?;
455
456 let chunk = self
457 .load_chunk(data, cfg_src)
458 .map_err(|err| load_error(cfg_src, err))?;
459 // The chunk itself receives the arguments as its varargs, so the
460 // script sees `db` via `local db = ...` at the top. A failure while
461 // it runs (a misspelled `db:` method, a nil index) gets the same
462 // in-context rendering as a parse error. The run is budgeted like
463 // a call: a loop here would hang every boot and reload.
464 let value = {
465 let _armed = self.arm();
466 let call = chunk.call_async::<Value>(args);
467 match self.opts.exec_timeout {
468 Some(timeout) => tokio::time::timeout(timeout + EXEC_TIMEOUT_GRACE, call)
469 .await
470 .map_err(|_| Error::Timeout)?,
471 None => call.await,
472 }
473 .map_err(|err| load_error(cfg_src, err))?
474 };
475 let cfg = match value {
476 Value::Table(cfg) => cfg,
477 // The pre-1.0 wrapper form; point migrations at the new shape.
478 Value::Function(_) => {
479 return Err(Error::Script(format!(
480 "the configuration script {} returned a function; the \
481 `function(db) ... end` wrapper is no longer supported — \
482 take arguments via `local db = ...` at the top level and \
483 end the script with `return {{ ... }}`",
484 cfg_src.display()
485 )));
486 }
487 other => {
488 return Err(Error::Script(format!(
489 "the configuration script {} must return a table, got {}",
490 cfg_src.display(),
491 other.type_name()
492 )));
493 }
494 };
495
496 self.cfg = Some(cfg);
497 Ok(())
498 }
499
500 /// The underlying Lua state, for advanced customization beyond
501 /// [`register_module()`](Self::register_module).
502 pub fn lua(&self) -> &Lua {
503 &self.lua
504 }
505
506 /// The Lua configuration table that is returned after the script handler is invoked.
507 pub fn cfg(&self) -> Option<&Table> {
508 self.cfg.as_ref()
509 }
510
511 /// Serializes the configuration table into a plain-data snapshot that can
512 /// be injected into other runtimes with
513 /// [`set_cfg_snapshot()`](Self::set_cfg_snapshot).
514 ///
515 /// Returns `None` when no configuration script has been registered.
516 pub fn cfg_snapshot(&self) -> Result<Option<serde_json::Value>> {
517 let Some(cfg) = &self.cfg else {
518 return Ok(None);
519 };
520 let snapshot = serde_json::to_value(cfg).map_err(|err| {
521 Error::Config(format!(
522 "the configuration script must return plain data \
523 (tables, strings, numbers, booleans): {err}"
524 ))
525 })?;
526 Ok(Some(snapshot))
527 }
528
529 /// Injects a configuration snapshot produced by
530 /// [`cfg_snapshot()`](Self::cfg_snapshot) as this runtime's
531 /// configuration table.
532 pub fn set_cfg_snapshot(&mut self, snapshot: &serde_json::Value) -> Result {
533 match self.lua.to_value(snapshot)? {
534 Value::Table(table) => {
535 self.cfg = Some(table);
536 Ok(())
537 }
538 _ => Err(Error::Config(
539 "the configuration snapshot must be a table".into(),
540 )),
541 }
542 }
543
544 /// Returns the cached handler coroutine reset to the given function,
545 /// creating it when necessary.
546 ///
547 /// The handler runs in its own coroutine; the execution-deadline hook is
548 /// installed globally at construction and inherited by every thread,
549 /// including coroutines the script creates itself.
550 fn handler_thread(&mut self, http_fn: Function) -> Result<Thread> {
551 if let Some(thread) = self.thread.take()
552 && thread.reset(http_fn.clone()).is_ok()
553 {
554 return Ok(thread);
555 }
556 Ok(self.lua.create_thread(http_fn)?)
557 }
558
559 /// Calls a Lua function under the configured execution budget
560 /// ([`RuntimeOpts::exec_timeout`]): an instruction-count hook stops
561 /// CPU-bound overruns and an outer async timeout stops slow I/O
562 /// ([`Error::Timeout`]). The function runs on this runtime's cached
563 /// coroutine so the instruction-count hook applies.
564 pub async fn call_function<R: FromLuaMulti>(
565 &mut self,
566 f: Function,
567 args: impl IntoLuaMulti,
568 ) -> Result<R> {
569 let thread = self.handler_thread(f.clone())?;
570 let result = match self.opts.exec_timeout {
571 Some(timeout) => {
572 self.deadline.store(
573 (self.epoch.elapsed() + timeout).as_nanos() as u64,
574 Ordering::Relaxed,
575 );
576 // The async timeout covers the disjoint failure mode: time
577 // spent suspended in async I/O, where no Lua instructions
578 // execute and the hook cannot fire.
579 let timed = tokio::time::timeout(
580 timeout + EXEC_TIMEOUT_GRACE,
581 thread.clone().into_async::<R>(args)?,
582 )
583 .await;
584 match timed {
585 Ok(result) => result,
586 Err(_) => {
587 // The coroutine is still suspended inside whatever
588 // builtin it was awaiting, and the pending Rust
589 // future — with everything it holds, an open SQLite
590 // transaction among them — lives on that coroutine's
591 // stack. Dropping the thread handle would leave both
592 // to a later collection cycle the script cannot
593 // force (`collectgarbage` is gone), so the state
594 // could serve its next request with the previous
595 // one's work still in flight. Close the stack now
596 // and collect, so the future is dropped here.
597 //
598 // Measured (`gc_collect_loaded_state` in
599 // crates/nitr/benches/runtime.rs): a full
600 // collection over ~3 MiB of live tables is ~1 ms,
601 // paid once per timed-out request on this worker
602 // — nothing next to the budget that request
603 // already spent, so it stays inline rather than
604 // hopping to the blocking pool.
605 let _ = thread.reset(f);
606 let _ = self.lua.gc_collect();
607 self.thread = Some(thread);
608 self.clear_deadline();
609 return Err(Error::Timeout);
610 }
611 }
612 }
613 None => thread.clone().into_async::<R>(args)?.await,
614 };
615 // Keep the coroutine for the next request (reset() also recovers
616 // errored threads on Lua 5.4).
617 self.thread = Some(thread);
618 self.clear_deadline();
619 self.classify(result)
620 }
621
622 /// Arms the execution deadline for a stretch of work; the guard lifts
623 /// it again. A no-op without an execution timeout.
624 fn arm(&self) -> Armed<'_> {
625 if let Some(timeout) = self.opts.exec_timeout {
626 self.deadline.store(
627 (self.epoch.elapsed() + timeout).as_nanos() as u64,
628 Ordering::Relaxed,
629 );
630 }
631 Armed(self)
632 }
633
634 /// Runs `f` on this state under the execution budget, as a call is:
635 /// the load of a script has the same limits as the handlers in it.
636 pub fn budgeted<R>(&self, f: impl FnOnce(&Lua) -> Result<R>) -> Result<R> {
637 let _armed = self.arm();
638 f(&self.lua)
639 }
640
641 /// Lifts the deadline once a budgeted call has returned. The state is
642 /// idle between calls, and Lua that runs outside a call — a dev-mode
643 /// reload, an embedder's own `eval` — must not inherit a deadline the
644 /// last request already blew through: the hook would fire within 4000
645 /// instructions and the `pcall` guard would re-raise on every caught
646 /// error, so the "next" request would fail before it started.
647 fn clear_deadline(&self) {
648 self.deadline.store(u64::MAX, Ordering::Relaxed);
649 }
650
651 /// Calls a Lua function under the instruction-hook deadline only — no
652 /// outer async timeout — for long-lived streaming calls. The caller is
653 /// expected to keep granting budget via [`DeadlineHandle::extend()`] as
654 /// chunks are delivered; time suspended in async I/O (e.g. waiting for a
655 /// slow client) is deliberately unbounded.
656 pub async fn call_function_streaming<R: FromLuaMulti>(
657 &mut self,
658 f: Function,
659 args: impl IntoLuaMulti,
660 ) -> Result<R> {
661 let thread = self.handler_thread(f)?;
662 if let Some(timeout) = self.opts.exec_timeout {
663 self.deadline.store(
664 (self.epoch.elapsed() + timeout).as_nanos() as u64,
665 Ordering::Relaxed,
666 );
667 }
668 let result = thread.clone().into_async::<R>(args)?.await;
669 self.thread = Some(thread);
670 self.clear_deadline();
671 self.classify(result)
672 }
673
674 /// Converts a call outcome into a [`Result`], marking the state
675 /// poisoned when the failure is one it cannot cleanly recover from.
676 fn classify<R>(&mut self, result: mlua::Result<R>) -> Result<R> {
677 match result {
678 Ok(value) => Ok(value),
679 Err(err) => {
680 let err = Error::from(err);
681 if err.poisons_state() {
682 self.poisoned = true;
683 }
684 Err(err)
685 }
686 }
687 }
688
689 /// A handle for extending this runtime's execution deadline from
690 /// long-lived calls (see
691 /// [`call_function_streaming()`](Self::call_function_streaming)).
692 pub fn deadline_handle(&self) -> DeadlineHandle {
693 DeadlineHandle {
694 deadline: self.deadline.clone(),
695 epoch: self.epoch,
696 budget: self.opts.exec_timeout,
697 }
698 }
699
700 /// Whether this runtime operates in development mode.
701 pub fn dev_mode(&self) -> bool {
702 self.opts.dev_mode
703 }
704}
705
706/// The `require` searcher for a confined state: `a.b` resolves to
707/// `<root>/a/b.lua` or `<root>/a/b/init.lua` for each root in order, and
708/// nothing else.
709///
710/// The module name is restricted to a dotted identifier before it touches
711/// a path, so no spelling of a name can name a parent directory or an
712/// absolute location; the roots are captured at construction rather than
713/// read back from `package.path`, so a script cannot widen the search by
714/// reassigning that string. Chunks compile as text only, for the same
715/// reason `load` does (see [`PRELUDE`]).
716fn confined_searcher(lua: &Lua, roots: Vec<PathBuf>) -> mlua::Result<Function> {
717 lua.create_function(move |lua, name: String| {
718 let well_formed = !name.is_empty()
719 && name
720 .chars()
721 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
722 && name.split('.').all(|segment| !segment.is_empty());
723 if !well_formed {
724 let note = format!(
725 "\n\tmodule name '{name}' is not a dotted identifier (letters, digits and '_' \
726 between dots)"
727 );
728 return Ok(Variadic::from_iter([Value::String(
729 lua.create_string(note)?,
730 )]));
731 }
732 let rel = name.replace('.', "/");
733 let mut tried = String::new();
734 let candidates = roots.iter().flat_map(|dir| {
735 [
736 dir.join(format!("{rel}.lua")),
737 dir.join(&rel).join("init.lua"),
738 ]
739 });
740 for candidate in candidates {
741 match std::fs::read(&candidate) {
742 Ok(data) => {
743 let loader = lua
744 .load(data)
745 .set_name(format!("@{}", candidate.display()))
746 .set_mode(ChunkMode::Text)
747 .into_function()?;
748 let path = lua.create_string(candidate.to_string_lossy().as_bytes())?;
749 return Ok(Variadic::from_iter([
750 Value::Function(loader),
751 Value::String(path),
752 ]));
753 }
754 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
755 tried.push_str(&format!("\n\tno file '{}'", candidate.display()));
756 }
757 Err(err) => {
758 return Err(mlua::Error::RuntimeError(format!(
759 "failed to read module '{name}' at {}: {err}",
760 candidate.display()
761 )));
762 }
763 }
764 }
765 Ok(Variadic::from_iter([Value::String(
766 lua.create_string(tried)?,
767 )]))
768 })
769}