mlua_isle/lib.rs
1//! Thread-isolated Lua VM with cancellation for mlua.
2//!
3//! `mlua-isle` runs a Lua VM on a dedicated thread and communicates via
4//! channels. This solves two fundamental problems with mlua:
5//!
6//! 1. **`Lua` is `!Send`** — it cannot cross thread boundaries. By
7//! confining the VM to one thread and sending requests over a channel,
8//! callers on any thread (UI, async runtime, etc.) can interact with
9//! Lua without `Send` issues.
10//!
11//! 2. **Cancellation** — long-running Lua code (including blocking Rust
12//! callbacks like HTTP calls) can be interrupted via a cancel token
13//! that triggers both a Lua debug hook and a caller-side signal.
14//!
15//! # Architecture
16//!
17//! ```text
18//! ┌─────────────────┐ mpsc ┌──────────────────┐
19//! │ caller thread │─────────►│ Lua thread │
20//! │ (UI / async) │ │ (mlua confined) │
21//! │ │◄─────────│ │
22//! │ Isle handle │ oneshot │ Lua VM + hook │
23//! └─────────────────┘ └──────────────────┘
24//! ```
25//!
26//! # Layers
27//!
28//! The crate has two layers:
29//!
30//! - **The actor layer** (crate root): [`Isle`], `AsyncIsle` and the
31//! pools put a VM on a thread of their own; `Send` handles send
32//! requests over channels.
33//! - **The in-thread layer** ([`runtime`]): for a host that owns the
34//! [`mlua::Lua`] and drives the executor itself.
35//! [`runtime::Vm`] owns the VM's debug hook, its
36//! [`runtime::Config`] (cancel grace, preemption) and the `task`
37//! library, and runs a root coroutine under a [`CancelToken`]
38//! (`Vm::run`, `tokio` feature).
39//!
40//! The actors are built on [`runtime`]: each attaches a [`runtime::Vm`]
41//! to its VM, and a coroutine request is a `Vm::run`. The [`runtime`]
42//! module docs are the canonical description of the in-thread layer:
43//! its contracts, the hook, and the Lua `task` library.
44//!
45//! # Moved to `runtime` in 0.8.0
46//!
47//! The in-thread API of 0.7 is deprecated; each old name forwards to
48//! its `runtime` replacement and will be removed in the release after
49//! 0.8.0.
50//!
51//! | 0.7 | 0.8 |
52//! |---|---|
53//! | `run_root(lua, token, f, args)` | [`Vm::attach`](runtime::Vm::attach) once, then `vm.run(&token, f, args)` |
54//! | `cancellable(fut)` (root) | `runtime::cancellable(fut)` |
55//! | `current_token()` (root) | [`runtime::current_token()`] |
56//! | `hooks::install(lua)` | [`Vm::attach(lua, config)`](runtime::Vm::attach) |
57//! | `hooks::configure` / `hooks::config` | [`Vm::set_config`](runtime::Vm::set_config) / [`Vm::config`](runtime::Vm::config) |
58//! | `hooks::add_hook` / `hooks::remove_hook` | [`Vm::add_hook`](runtime::Vm::add_hook) / [`Vm::remove_hook`](runtime::Vm::remove_hook) |
59//! | `hooks::CancelConfig` | [`runtime::Config`] (the old name is an alias) |
60//! | `hooks::HookId` | [`runtime::HookId`] |
61//! | `tasks::install(lua)` (`tokio`) | `Vm::attach(lua, config)?.task_lib()` (`tokio`) |
62//! | the `hooks` / `tasks` modules | [`runtime`] |
63//!
64//! # Example
65//!
66//! ```rust
67//! use mlua_isle::Isle;
68//!
69//! let isle = Isle::spawn(|lua| {
70//! lua.globals().set("greeting", "hello")?;
71//! Ok(())
72//! }).unwrap();
73//!
74//! let result: String = isle.eval("return greeting").unwrap();
75//! assert_eq!(result, "hello");
76//!
77//! isle.shutdown().unwrap();
78//! ```
79
80mod error;
81mod handle;
82mod hook;
83#[deprecated(
84 since = "0.8.0",
85 note = "use `mlua_isle::runtime` (`Vm`, `Config`, `HookId`)"
86)]
87pub mod hooks;
88mod hub;
89#[cfg(feature = "pool")]
90mod pool;
91mod protect;
92pub mod runtime;
93mod task;
94mod thread;
95
96#[cfg(feature = "tokio")]
97mod async_isle;
98#[cfg(all(feature = "pool", feature = "tokio"))]
99mod async_pool;
100#[cfg(feature = "tokio")]
101mod async_task;
102#[cfg(feature = "tokio")]
103mod scope;
104#[cfg(feature = "tokio")]
105mod task_lib;
106#[cfg(feature = "tokio")]
107#[deprecated(since = "0.8.0", note = "use `mlua_isle::runtime::Vm::task_lib`")]
108pub mod tasks;
109
110pub use error::{Cancelled, IsleError, LuaErrorKind, LuaFailure};
111pub use handle::Isle;
112pub use hook::CancelToken;
113pub use task::Task;
114
115#[cfg(feature = "pool")]
116pub use pool::{IslePool, PoolConfig, PoolStrategy, PooledIsle};
117
118#[cfg(feature = "tokio")]
119pub use async_isle::{AsyncIsle, AsyncIsleBuilder, AsyncIsleDriver};
120#[cfg(all(feature = "pool", feature = "tokio"))]
121pub use async_pool::{AsyncIslePool, AsyncPooledIsle};
122#[cfg(feature = "tokio")]
123pub use async_task::AsyncTask;
124
125/// Token of the request or task currently executing on this thread.
126/// Forwards to [`runtime::current_token`].
127#[deprecated(since = "0.8.0", note = "use `mlua_isle::runtime::current_token`")]
128pub fn current_token() -> Option<CancelToken> {
129 runtime::current_token()
130}
131
132/// Make an async host function's future stop when the calling request
133/// or task is cancelled. Forwards to `runtime::cancellable`.
134#[cfg(feature = "tokio")]
135#[deprecated(since = "0.8.0", note = "use `mlua_isle::runtime::cancellable`")]
136pub async fn cancellable<F, T>(fut: F) -> mlua::Result<T>
137where
138 F: std::future::Future<Output = mlua::Result<T>>,
139{
140 runtime::cancellable(fut).await
141}
142
143/// Run `func(args)` as a root coroutine under `token`. Forwards to
144/// [`Vm::run`](runtime::Vm::run) on the VM's [`Vm`](runtime::Vm),
145/// attaching it with its stored config first if it is not attached.
146///
147/// Migration: `Vm::attach(&lua, config)?` once, then
148/// `vm.run(&token, func, args).await`.
149///
150/// # Errors
151///
152/// As [`Vm::run`](runtime::Vm::run), plus the error of
153/// [`Vm::attach`](runtime::Vm::attach) when the VM was not attached.
154#[cfg(feature = "tokio")]
155#[deprecated(
156 since = "0.8.0",
157 note = "use `mlua_isle::runtime::Vm::attach` once, then `vm.run(&token, f, args)`"
158)]
159pub async fn run_root(
160 lua: &mlua::Lua,
161 token: CancelToken,
162 func: mlua::Function,
163 args: mlua::MultiValue,
164) -> Result<mlua::MultiValue, IsleError> {
165 runtime::of_or_attach(lua)?.run(&token, func, args).await
166}
167
168/// The work of one request, run on the VM thread.
169///
170/// A job owns everything its request needs: the code or the arguments,
171/// and the typed sender its result goes back through. It converts the
172/// result on the VM thread (`FromLuaMulti`, or the `exec` closure's own
173/// `T`) and sends a `Send` value, so the request type needs no type
174/// parameter. A coroutine job `spawn_local`s its future and returns.
175pub(crate) type Job = Box<dyn FnOnce(&mlua::Lua, &CancelToken) + Send>;
176
177/// Request sent from a handle ([`Isle`], `AsyncIsle`) to the VM thread.
178pub(crate) enum Request {
179 /// Run a job under the request's cancel token.
180 Run { job: Job, cancel: CancelToken },
181 /// Graceful shutdown.
182 Shutdown,
183}