Skip to main content

Runtime

Struct Runtime 

Source
pub struct Runtime { /* private fields */ }
Expand description

The Lua runtime that provides an interface to execute Lua scripts and manage Lua state. It allows for registering Rust extension modules on the nitr namespace, running a configuration script, and calling Lua functions under the state’s execution budget.

Implementations§

Source§

impl Runtime

Source

pub fn eval_script(&self, path: &Path) -> Result<Value>

Loads and evaluates a Lua script file, returning the resulting value.

This does not interpret the result; callers decide what the script is expected to return (e.g. a handler function or an application object).

Source§

impl Runtime

Source

pub fn new() -> Result<Self>

It creates a new Lua runtime with default options.

Such as some built-in libraries loaded and a default memory limit.

package is not among them, so require is unavailable: confinement needs a directory to pin to, and this constructor takes no arguments to name one. Embedders that want module loading call Runtime::new_with with both StdLib::PACKAGE and a package_dir.

Source

pub fn new_with(opts: RuntimeOpts) -> Result<Self>

It creates a new Lua runtime with specified options.

For example, it allows for customizing the Lua standard libraries to load like io, math, os, etc as well as the memory limits.

Some scrubbing applies to every state, whatever the options: collectgarbage is always removed (the memory limit is enforced by the allocator, not the collector), and package-bearing states can never load native modules — see package_dir.

Source

pub fn is_poisoned(&self) -> bool

Whether a failure has left this state unfit for reuse (a memory limit hit or a caught panic). The pool rebuilds a poisoned state rather than handing it to the next request.

Source

pub fn poison(&mut self)

Marks this state unfit for reuse. Used by the HTTP layer when a panic is caught while the state is checked out.

Source

pub fn register_module<F>(&self, name: &str, f: F) -> Result
where F: Fn(&Lua) -> Result<Table>,

Registers a Rust extension module: the closure runs now (and its result is a table by Lua module convention), mounted at nitr.ext.<name> — one level below the standard library, so a module can never collide with a builtin. Fails when the name is already taken, so two extensions cannot shadow each other.

This is the embedding-side extension point; HTTP applications use ServerBuilder::module() in the nitr-http crate, which applies the closure to every pooled state.

§Error attribution

An error a module raises should say which module failed. Wrap Rust errors with a module <name> context and ErrorInfo classifies them as kind = "module" with the module named; a module that returns an opaque string makes its failures everyone’s problem:

ⓘ
t.set("query", lua.create_function(|_, sql: String| {
    run(&sql).map_err(|err| mlua::Error::WithContext {
        context: "module db".into(),
        cause: std::sync::Arc::new(mlua::Error::external(err)),
    })
})?)?;
Source

pub async fn register_cfg_fn( &mut self, cfg_src: &Path, args: impl IntoLuaMulti, ) -> Result

It sets the Lua configuration script that runs once at server startup.

The script is a plain Lua chunk in the same shape handler scripts use: statements at the top level ending in return { ... }, with the provided arguments available as its varargs (local db = ...).

The Lua table containing the configuration fields can be accessed later using the cfg() method.

Source

pub fn lua(&self) -> &Lua

The underlying Lua state, for advanced customization beyond register_module().

Source

pub fn cfg(&self) -> Option<&Table>

The Lua configuration table that is returned after the script handler is invoked.

Source

pub fn cfg_snapshot(&self) -> Result<Option<Value>>

Serializes the configuration table into a plain-data snapshot that can be injected into other runtimes with set_cfg_snapshot().

Returns None when no configuration script has been registered.

Source

pub fn set_cfg_snapshot(&mut self, snapshot: &Value) -> Result

Injects a configuration snapshot produced by cfg_snapshot() as this runtime’s configuration table.

Source

pub async fn call_function<R: FromLuaMulti>( &mut self, f: Function, args: impl IntoLuaMulti, ) -> Result<R>

Calls a Lua function under the configured execution budget (RuntimeOpts::exec_timeout): an instruction-count hook stops CPU-bound overruns and an outer async timeout stops slow I/O (Error::Timeout). The function runs on this runtime’s cached coroutine so the instruction-count hook applies.

Source

pub fn budgeted<R>(&self, f: impl FnOnce(&Lua) -> Result<R>) -> Result<R>

Runs f on this state under the execution budget, as a call is: the load of a script has the same limits as the handlers in it.

Source

pub async fn call_function_streaming<R: FromLuaMulti>( &mut self, f: Function, args: impl IntoLuaMulti, ) -> Result<R>

Calls a Lua function under the instruction-hook deadline only — no outer async timeout — for long-lived streaming calls. The caller is expected to keep granting budget via DeadlineHandle::extend() as chunks are delivered; time suspended in async I/O (e.g. waiting for a slow client) is deliberately unbounded.

Source

pub fn deadline_handle(&self) -> DeadlineHandle

A handle for extending this runtime’s execution deadline from long-lived calls (see call_function_streaming()).

Source

pub fn dev_mode(&self) -> bool

Whether this runtime operates in development mode.

Trait Implementations§

Source§

impl Debug for Runtime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSend for T
where T: Send,

Source§

impl<T> MaybeSync for T
where T: Sync,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more