Skip to main content

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//! # Removed in 0.9.0
46//!
47//! The in-thread API of 0.7, deprecated in 0.8.0, is removed.  Each old
48//! name and its `runtime` replacement:
49//!
50//! | 0.7 (removed) | since 0.8 |
51//! |---|---|
52//! | `run_root(lua, token, f, args)` | [`Vm::attach`](runtime::Vm::attach) once, then `vm.run(&token, f, args)` |
53//! | `cancellable(fut)` (root) | `runtime::cancellable(fut)` |
54//! | `current_token()` (root) | [`runtime::current_token()`] |
55//! | `hooks::install(lua)` | [`Vm::attach(lua, config)`](runtime::Vm::attach) |
56//! | `hooks::configure` / `hooks::config` | [`Vm::set_config`](runtime::Vm::set_config) / [`Vm::config`](runtime::Vm::config) |
57//! | `hooks::add_hook` / `hooks::remove_hook` | [`Vm::add_hook`](runtime::Vm::add_hook) / [`Vm::remove_hook`](runtime::Vm::remove_hook) |
58//! | `hooks::CancelConfig` | [`runtime::Config`] |
59//! | `hooks::HookId` | [`runtime::HookId`] |
60//! | `tasks::install(lua)` (`tokio`) | `Vm::attach(lua, config)?.task_lib()` (`tokio`) |
61//! | the `hooks` / `tasks` modules | [`runtime`] |
62//!
63//! # Example
64//!
65//! ```rust
66//! use mlua_isle::Isle;
67//!
68//! let isle = Isle::spawn(|lua| {
69//!     lua.globals().set("greeting", "hello")?;
70//!     Ok(())
71//! }).unwrap();
72//!
73//! let result: String = isle.eval("return greeting").unwrap();
74//! assert_eq!(result, "hello");
75//!
76//! isle.shutdown().unwrap();
77//! ```
78
79mod error;
80mod handle;
81mod hook;
82mod hub;
83#[cfg(feature = "pool")]
84mod pool;
85mod protect;
86pub mod runtime;
87mod task;
88mod thread;
89
90#[cfg(feature = "tokio")]
91mod async_isle;
92#[cfg(all(feature = "pool", feature = "tokio"))]
93mod async_pool;
94#[cfg(feature = "tokio")]
95mod async_task;
96#[cfg(feature = "tokio")]
97mod chan;
98#[cfg(feature = "tokio")]
99mod host_chan;
100#[cfg(feature = "tokio")]
101mod scope;
102#[cfg(feature = "tokio")]
103mod select;
104#[cfg(feature = "tokio")]
105mod task_lib;
106
107pub use error::{Cancelled, IsleError, LuaErrorKind, LuaFailure};
108pub use handle::Isle;
109pub use hook::CancelToken;
110pub use task::Task;
111
112#[cfg(feature = "pool")]
113pub use pool::{IslePool, PoolConfig, PoolStrategy, PooledIsle};
114
115#[cfg(feature = "tokio")]
116pub use async_isle::{AsyncIsle, AsyncIsleBuilder, AsyncIsleDriver, IsleFunction};
117#[cfg(all(feature = "pool", feature = "tokio"))]
118pub use async_pool::{AsyncIslePool, AsyncPooledIsle};
119#[cfg(feature = "tokio")]
120pub use async_task::AsyncTask;
121
122/// The work of one request, run on the VM thread.
123///
124/// A job owns everything its request needs: the code or the arguments,
125/// and the typed sender its result goes back through.  It converts the
126/// result on the VM thread (`FromLuaMulti`, or the `exec` closure's own
127/// `T`) and sends a `Send` value, so the request type needs no type
128/// parameter.  A coroutine job `spawn_local`s its future and returns.
129pub(crate) type Job = Box<dyn FnOnce(&mlua::Lua, &CancelToken) + Send>;
130
131/// Request sent from a handle ([`Isle`], `AsyncIsle`) to the VM thread.
132pub(crate) enum Request {
133    /// Run a job under the request's cancel token.
134    Run { job: Job, cancel: CancelToken },
135    /// Graceful shutdown.
136    Shutdown,
137}