Skip to main content

mlua_isle/
handle.rs

1//! Isle — the public handle for interacting with the Lua thread.
2
3use crate::error::IsleError;
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.
43    pub fn spawn<F>(init: F) -> Result<Self, IsleError>
44    where
45        F: FnOnce(&mlua::Lua) -> Result<(), mlua::Error> + Send + 'static,
46    {
47        let (tx, rx) = mpsc::channel::<Request>();
48        let (init_tx, init_rx) = mpsc::channel::<Result<(), IsleError>>();
49
50        let join = std::thread::Builder::new()
51            .name("mlua-isle".into())
52            .spawn(move || {
53                let lua = mlua::Lua::new();
54                match init(&lua)
55                    .map_err(|e| IsleError::Init(e.to_string()))
56                    .and_then(|()| crate::hooks::install(&lua))
57                {
58                    Ok(()) => {
59                        let _ = init_tx.send(Ok(()));
60                        thread::run_loop(lua, rx);
61                    }
62                    Err(e) => {
63                        let _ = init_tx.send(Err(e));
64                    }
65                }
66            })
67            .map_err(|e| IsleError::Init(format!("thread spawn failed: {e}")))?;
68
69        // Wait for init to complete
70        init_rx
71            .recv()
72            .map_err(|e| IsleError::Init(format!("init channel closed: {e}")))??;
73
74        Ok(Self {
75            tx,
76            join: Mutex::new(Some(join)),
77        })
78    }
79
80    /// Evaluate a Lua chunk (blocking).
81    ///
82    /// Returns the result as a string.  Equivalent to
83    /// `spawn_eval(code).wait()`.
84    pub fn eval(&self, code: &str) -> Result<String, IsleError> {
85        self.spawn_eval(code).wait()
86    }
87
88    /// Evaluate a Lua chunk, returning a cancellable [`Task`].
89    pub fn spawn_eval(&self, code: &str) -> Task {
90        let cancel = CancelToken::new();
91        let (resp_tx, resp_rx) = mpsc::channel();
92
93        let req = Request::Eval {
94            code: code.to_string(),
95            cancel: cancel.clone(),
96            tx: resp_tx,
97        };
98
99        if self.tx.send(req).is_err() {
100            // Channel closed — return a task that immediately errors
101            let (err_tx, err_rx) = mpsc::channel();
102            let _ = err_tx.send(Err(IsleError::Shutdown));
103            return Task::new(err_rx, cancel);
104        }
105
106        Task::new(resp_rx, cancel)
107    }
108
109    /// Call a named global Lua function with string arguments (blocking).
110    pub fn call(&self, func: &str, args: &[&str]) -> Result<String, IsleError> {
111        self.spawn_call(func, args).wait()
112    }
113
114    /// Call a named global Lua function, returning a cancellable [`Task`].
115    pub fn spawn_call(&self, func: &str, args: &[&str]) -> Task {
116        let cancel = CancelToken::new();
117        let (resp_tx, resp_rx) = mpsc::channel();
118
119        let req = Request::Call {
120            func: func.to_string(),
121            args: args.iter().map(|s| s.to_string()).collect(),
122            cancel: cancel.clone(),
123            tx: resp_tx,
124        };
125
126        if self.tx.send(req).is_err() {
127            let (err_tx, err_rx) = mpsc::channel();
128            let _ = err_tx.send(Err(IsleError::Shutdown));
129            return Task::new(err_rx, cancel);
130        }
131
132        Task::new(resp_rx, cancel)
133    }
134
135    /// Execute an arbitrary closure on the Lua thread (blocking).
136    ///
137    /// The closure receives `&Lua` and can perform any operation.
138    /// This is the escape hatch for complex interactions that don't
139    /// fit into `eval` or `call`.
140    ///
141    /// **Note:** The cancel hook only fires during Lua instruction
142    /// execution.  If the closure blocks in Rust code (e.g. HTTP
143    /// calls, file I/O), cancellation will not take effect until
144    /// control returns to the Lua VM.
145    pub fn exec<F>(&self, f: F) -> Result<String, IsleError>
146    where
147        F: FnOnce(&mlua::Lua) -> Result<String, IsleError> + Send + 'static,
148    {
149        self.spawn_exec(f).wait()
150    }
151
152    /// Execute a closure on the Lua thread, returning a cancellable [`Task`].
153    pub fn spawn_exec<F>(&self, f: F) -> Task
154    where
155        F: FnOnce(&mlua::Lua) -> Result<String, IsleError> + Send + 'static,
156    {
157        let cancel = CancelToken::new();
158        let (resp_tx, resp_rx) = mpsc::channel();
159
160        let req = Request::Exec {
161            f: Box::new(f),
162            cancel: cancel.clone(),
163            tx: resp_tx,
164        };
165
166        if self.tx.send(req).is_err() {
167            let (err_tx, err_rx) = mpsc::channel();
168            let _ = err_tx.send(Err(IsleError::Shutdown));
169            return Task::new(err_rx, cancel);
170        }
171
172        Task::new(resp_rx, cancel)
173    }
174
175    /// Graceful shutdown: signal the Lua thread to exit and join it.
176    ///
177    /// After shutdown, all subsequent requests will return
178    /// [`IsleError::Shutdown`].
179    pub fn shutdown(self) -> Result<(), IsleError> {
180        let _ = self.tx.send(Request::Shutdown);
181        let handle = self.join.lock().map_err(|_| IsleError::ThreadPanic)?.take();
182        if let Some(join) = handle {
183            join.join().map_err(|_| IsleError::ThreadPanic)?;
184        }
185        Ok(())
186    }
187
188    /// Check if the Lua thread is still alive.
189    pub fn is_alive(&self) -> bool {
190        self.join
191            .lock()
192            .ok()
193            .and_then(|guard| guard.as_ref().map(|j| !j.is_finished()))
194            .unwrap_or(false)
195    }
196}
197
198impl Drop for Isle {
199    fn drop(&mut self) {
200        // Send shutdown signal; ignore errors (channel may already be closed)
201        let _ = self.tx.send(Request::Shutdown);
202        // Don't join on drop — let the thread exit on its own.
203        // Use explicit shutdown() for a clean join.
204    }
205}