mlua_isle/handle.rs
1//! Isle — the public handle for interacting with the Lua thread.
2
3use crate::error::{panic_message, IsleError, LuaFailure};
4use crate::hook::CancelToken;
5use crate::task::Task;
6use crate::thread;
7use crate::Request;
8use std::sync::mpsc;
9use std::sync::Mutex;
10use std::thread::JoinHandle;
11
12/// Handle to a thread-isolated Lua VM.
13///
14/// `Isle` owns the communication channel and the join handle for the
15/// Lua thread. All operations are thread-safe (`Isle: Send + Sync`).
16///
17/// # Lifecycle
18///
19/// 1. [`Isle::spawn`] creates the Lua VM on a dedicated thread.
20/// 2. Use [`eval`](Isle::eval), [`call`](Isle::call), or [`exec`](Isle::exec)
21/// to run code.
22/// 3. [`shutdown`](Isle::shutdown) sends a graceful stop signal and
23/// joins the thread.
24///
25/// If the `Isle` is dropped without calling `shutdown`, the channel
26/// disconnects and the Lua thread exits on its next receive attempt.
27#[must_use = "use .shutdown() for clean thread join; dropping without shutdown leaks the thread"]
28pub struct Isle {
29 tx: mpsc::Sender<Request>,
30 join: Mutex<Option<JoinHandle<()>>>,
31}
32
33impl Isle {
34 /// Spawn a new Lua VM on a dedicated thread.
35 ///
36 /// The `init` closure runs on the Lua thread before any requests
37 /// are processed. Use it to register globals, install mlua-pkg
38 /// resolvers, load mlua-batteries, etc.
39 ///
40 /// # Errors
41 ///
42 /// Returns [`IsleError::Init`] if the init closure fails (or the OS
43 /// refuses to start the thread), and [`IsleError::ThreadPanic`] with
44 /// the panic message if the init closure panics.
45 pub fn spawn<F>(init: F) -> Result<Self, IsleError>
46 where
47 F: FnOnce(&mlua::Lua) -> Result<(), mlua::Error> + Send + 'static,
48 {
49 let (tx, rx) = mpsc::channel::<Request>();
50 let (init_tx, init_rx) = mpsc::channel::<Result<(), IsleError>>();
51
52 let join = std::thread::Builder::new()
53 .name("mlua-isle".into())
54 .spawn(move || {
55 let lua = mlua::Lua::new();
56 // Before `init`: captures `xpcall` while the globals are
57 // intact (see `protect`).
58 match crate::protect::install(&lua)
59 .and_then(|()| {
60 init(&lua).map_err(|e| IsleError::Init(LuaFailure::from_mlua(&e)))
61 })
62 .and_then(|()| crate::runtime::attach_after_init(&lua, None).map(drop))
63 {
64 Ok(()) => {
65 let _ = init_tx.send(Ok(()));
66 thread::run_loop(lua, rx);
67 }
68 Err(e) => {
69 let _ = init_tx.send(Err(e));
70 }
71 }
72 })
73 .map_err(|e| IsleError::Init(LuaFailure::from_mlua(&mlua::Error::external(e))))?;
74
75 // Wait for init to complete. A closed channel means the thread
76 // ended without reporting: the init closure panicked.
77 match init_rx.recv() {
78 Ok(result) => result?,
79 Err(_) => {
80 let payload = join.join().err();
81 return Err(IsleError::ThreadPanic(
82 payload.as_deref().and_then(panic_message),
83 ));
84 }
85 }
86
87 Ok(Self {
88 tx,
89 join: Mutex::new(Some(join)),
90 })
91 }
92
93 /// Evaluate a Lua chunk (blocking) and convert its return values
94 /// to `T`. Equivalent to `spawn_eval(code).wait()`.
95 ///
96 /// The conversion ([`FromLuaMulti`](mlua::FromLuaMulti)) runs on the
97 /// Lua thread, so any `T: FromLuaMulti + Send + 'static` works: a
98 /// single value (`String`, `i64`, `f64`, `bool`,
99 /// [`BString`](mlua::BString) for the raw bytes of a Lua string), `()`
100 /// to ignore the result, `Option<T>` for a result that may be `nil`,
101 /// or a tuple for several return values. Values tied to the VM
102 /// (`Table`, `Function`, `Value`, `MultiValue`) are not `Send`
103 /// without mlua's `send` feature and then do not compile here; use
104 /// [`exec`](Self::exec) to convert them on the Lua thread, or ask for
105 /// a [`RegistryKey`](mlua::RegistryKey), which is `Send`, and read
106 /// the value back in a later `exec`.
107 ///
108 /// ```rust
109 /// # use mlua_isle::Isle;
110 /// let isle = Isle::spawn(|_| Ok(())).unwrap();
111 /// let n: i64 = isle.eval("return 1 + 1").unwrap();
112 /// assert_eq!(n, 2);
113 /// let (a, b) = isle.eval::<(i64, String)>("return 1, 'x'").unwrap();
114 /// assert_eq!((a, b.as_str()), (1, "x"));
115 /// assert_eq!(isle.eval::<Option<String>>("return nil").unwrap(), None);
116 /// # isle.shutdown().unwrap();
117 /// ```
118 ///
119 /// A Lua error is [`IsleError::Lua`], and so is a return value that
120 /// does not convert to `T` (kind
121 /// [`Conversion`](crate::LuaErrorKind::Conversion)). A `FromLua` of
122 /// your own that fails with an error raised by Lua code it runs (a
123 /// `__index` metamethod, say) is `Lua` with that error's kind, not
124 /// `Conversion`; the conversion runs under the request's token, so
125 /// a cancel while it runs Lua code is `Cancelled`. When the
126 /// request's token was cancelled, the result is
127 /// [`IsleError::Cancelled`] even if the Lua code caught the cancel
128 /// and raised an error of its own (the same rule as coroutine
129 /// requests and `Vm::run`); this holds for `call` too.
130 pub fn eval<T>(&self, code: &str) -> Result<T, IsleError>
131 where
132 T: mlua::FromLuaMulti + Send + 'static,
133 {
134 self.spawn_eval(code).wait()
135 }
136
137 /// Evaluate a Lua chunk, returning a cancellable [`Task`].
138 pub fn spawn_eval<T>(&self, code: &str) -> Task<T>
139 where
140 T: mlua::FromLuaMulti + Send + 'static,
141 {
142 let code = code.to_string();
143 self.submit(move |lua, cancel| thread::execute_eval(lua, &code, cancel))
144 }
145
146 /// Call a named global Lua function (blocking) and convert its
147 /// return values to `T`.
148 ///
149 /// `args` is converted on the Lua thread
150 /// ([`IntoLuaMulti`](mlua::IntoLuaMulti)): `()` for no arguments, a
151 /// value, a tuple such as `(1, true, "x")`, or a
152 /// [`Variadic`](mlua::Variadic) for a number of arguments known only
153 /// at run time (a `Vec` is one argument, a table). The result
154 /// follows the rules of [`eval`](Self::eval). A global that is not
155 /// a function is [`IsleError::NotFound`].
156 pub fn call<A, T>(&self, func: &str, args: A) -> Result<T, IsleError>
157 where
158 A: mlua::IntoLuaMulti + Send + 'static,
159 T: mlua::FromLuaMulti + Send + 'static,
160 {
161 self.spawn_call(func, args).wait()
162 }
163
164 /// Call a named global Lua function, returning a cancellable [`Task`].
165 pub fn spawn_call<A, T>(&self, func: &str, args: A) -> Task<T>
166 where
167 A: mlua::IntoLuaMulti + Send + 'static,
168 T: mlua::FromLuaMulti + Send + 'static,
169 {
170 let func = func.to_string();
171 self.submit(move |lua, cancel| thread::execute_call(lua, &func, args, cancel))
172 }
173
174 /// Execute an arbitrary closure on the Lua thread (blocking).
175 ///
176 /// The closure receives `&Lua` and can perform any operation; its
177 /// `T` crosses back as is (no conversion). This is the escape
178 /// hatch for complex interactions that don't fit into `eval` or
179 /// `call`, and the place to turn a value tied to the VM (a `Table`)
180 /// into a `Send` one. `?` works on `mlua::Result` inside the
181 /// closure (`IsleError: From<mlua::Error>`).
182 ///
183 /// **Note:** The cancel hook only fires during Lua instruction
184 /// execution. If the closure blocks in Rust code (e.g. HTTP
185 /// calls, file I/O), cancellation will not take effect until
186 /// control returns to the Lua VM.
187 pub fn exec<F, T>(&self, f: F) -> Result<T, IsleError>
188 where
189 F: FnOnce(&mlua::Lua) -> Result<T, IsleError> + Send + 'static,
190 T: Send + 'static,
191 {
192 self.spawn_exec(f).wait()
193 }
194
195 /// Execute a closure on the Lua thread, returning a cancellable [`Task`].
196 pub fn spawn_exec<F, T>(&self, f: F) -> Task<T>
197 where
198 F: FnOnce(&mlua::Lua) -> Result<T, IsleError> + Send + 'static,
199 T: Send + 'static,
200 {
201 self.submit(move |lua, cancel| thread::execute_exec(lua, f, cancel))
202 }
203
204 /// Send a job that runs `run` on the Lua thread and sends its
205 /// result back through the returned task's channel.
206 fn submit<T, R>(&self, run: R) -> Task<T>
207 where
208 T: Send + 'static,
209 R: FnOnce(&mlua::Lua, &CancelToken) -> Result<T, IsleError> + Send + 'static,
210 {
211 let cancel = CancelToken::new();
212 let (resp_tx, resp_rx) = mpsc::channel();
213
214 let req = Request::Run {
215 job: Box::new(move |lua, cancel| {
216 let _ = resp_tx.send(run(lua, cancel));
217 }),
218 cancel: cancel.clone(),
219 };
220
221 if self.tx.send(req).is_err() {
222 // Channel closed — return a task that immediately errors
223 let (err_tx, err_rx) = mpsc::channel();
224 let _ = err_tx.send(Err(IsleError::Shutdown));
225 return Task::new(err_rx, cancel);
226 }
227
228 Task::new(resp_rx, cancel)
229 }
230
231 /// Graceful shutdown: signal the Lua thread to exit and join it.
232 ///
233 /// After shutdown, all subsequent requests will return
234 /// [`IsleError::Shutdown`].
235 ///
236 /// # Errors
237 ///
238 /// [`IsleError::ThreadPanic`] if the Lua thread panicked (a request
239 /// whose Rust code panicked ends the thread; that request itself
240 /// returns [`IsleError::RecvFailed`]), with the panic message when
241 /// the payload is a `&str` or a `String`.
242 pub fn shutdown(self) -> Result<(), IsleError> {
243 let _ = self.tx.send(Request::Shutdown);
244 let handle = self
245 .join
246 .lock()
247 .map_err(|_| IsleError::ThreadPanic(None))?
248 .take();
249 if let Some(join) = handle {
250 join.join()
251 .map_err(|p| IsleError::ThreadPanic(panic_message(p.as_ref())))?;
252 }
253 Ok(())
254 }
255
256 /// Check if the Lua thread is still alive.
257 pub fn is_alive(&self) -> bool {
258 self.join
259 .lock()
260 .ok()
261 .and_then(|guard| guard.as_ref().map(|j| !j.is_finished()))
262 .unwrap_or(false)
263 }
264}
265
266impl Drop for Isle {
267 fn drop(&mut self) {
268 // Send shutdown signal; ignore errors (channel may already be closed)
269 let _ = self.tx.send(Request::Shutdown);
270 // Don't join on drop — let the thread exit on its own.
271 // Use explicit shutdown() for a clean join.
272 }
273}