From 6f0d6787908938567dc850d6e3bd9d15fd01e25e Mon Sep 17 00:00:00 2001 From: meehl <12648828+meehl@users.noreply.github.com> Date: Fri, 28 Aug 2026 20:11:25 +0200 Subject: [PATCH] Add better docs for subscripts --- src/pob/subscript.rs | 148 +++++++++++++++++++++++++------------------ 1 file changed, 88 insertions(+), 60 deletions(-) diff --git a/src/pob/subscript.rs b/src/pob/subscript.rs index 2efc229..6044747 100644 --- a/src/pob/subscript.rs +++ b/src/pob/subscript.rs @@ -2,12 +2,12 @@ use crate::{pob::PathOfBuilding, pob::api::get_callback}; use anyhow::{Result, anyhow}; use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Value}; use std::{ - collections::VecDeque, path::PathBuf, sync::mpsc::{Receiver, Sender, channel}, thread::JoinHandle, }; +/// The outcome of a [`Subscript`] that has finished. #[derive(Debug)] pub enum SubscriptResult { SubscriptFinished { @@ -22,11 +22,13 @@ pub enum SubscriptResult { #[derive(Default)] pub struct SubscriptManager { - current_id: u64, + next_id: u64, scripts: Vec, } impl SubscriptManager { + /// Starts a new subscript running `script_text` on its own thread and returns the id it was + /// assigned. pub fn push( &mut self, script_dir: PathBuf, @@ -35,8 +37,8 @@ impl SubscriptManager { nonblocking_calls: Vec, arguments: NativeMultiValue, ) -> u64 { - let id = self.current_id; - self.current_id += 1; + let id = self.next_id; + self.next_id += 1; let subscript = Subscript::new( id, @@ -50,6 +52,7 @@ impl SubscriptManager { id } + /// Advances all running subscripts by one step. pub fn process(&mut self, lua: &Lua) -> Vec { let mut results = vec![]; @@ -66,21 +69,27 @@ impl SubscriptManager { results } + /// Returns `true` if at least one subscript is running. pub fn has_running_subscripts(&self) -> bool { !self.scripts.is_empty() } + /// Returns `true` if the subscript with the given id is running. pub fn is_running(&self, subscript_id: u64) -> bool { - self.scripts.iter().any(|ss| ss.id == subscript_id) + self.scripts + .iter() + .any(|subscript| subscript.id == subscript_id) } } +/// A request sent from a subscript's thread to the main thread, asking it to invoke a function +/// defined in the main Lua instance on the subscript's behalf. enum SubscriptCall { Blocking { function_name: String, arguments: NativeMultiValue, // used to send return values of function back to thread - return_values_sender: Sender>, + reply_tx: Sender>, }, NonBlocking { function_name: String, @@ -88,26 +97,28 @@ enum SubscriptCall { }, } +/// A Lua script running on its own thread, in a separate `Lua` instance. pub struct Subscript { id: u64, handle: Option>>, - receiver: Receiver, + /// Receives `SubscriptCall`s sent by the proxy functions running in the subscript's s thread. + call_rx: Receiver, } -// Subscripts are lua scripts that are executed in their own instance on a separate -// thread. +// Subscripts are lua scripts that are executed in their own instance on a separate thread. // -// When a subscript needs to call a function defined in the main instance, a -// `SubscriptCall` message is send over a channel. At the beginning of each frame, -// the main thread checks for messages and executes the requested function with the -// provided arguments on behalf of the subscript. -// For `BlockingCall`, the subscript waits for the main thread to send the return -// values of the function back over another channel. -// For `NonBlockingCall`, the subscript doesn't wait on any return values and keeps -// executing the script after sending the message. -// Subscripts are required to explicitly specify the names of all (non)-blocking -// function calls that appear in the script. +// When a subscript needs to call a function defined in the main instance, a `SubscriptCall` +// message is send over a channel. At the beginning of each frame, the main thread checks for +// messages and executes the requested function with the provided arguments on behalf of the +// subscript. For `BlockingCall`, the subscript waits for the main thread to send the return +// values of the function back over another channel. For `NonBlockingCall`, the subscript doesn't +// wait on any return values and keeps executing the script after sending the message. Subscripts +// are required to explicitly specify the names of all (non)-blocking function calls that appear in +// the script. impl Subscript { + /// Spawns a new thread, creates a fresh `Lua` instance on it, registers proxy functions for + /// `blocking_calls` and `nonblocking_calls`, and starts running `script_text` with + /// `arguments`. pub fn new( id: u64, script_text: String, @@ -116,10 +127,10 @@ impl Subscript { arguments: NativeMultiValue, script_dir: PathBuf, ) -> Self { - let (tx, rx) = channel(); + let (call_tx, call_rx) = channel(); let handle = std::thread::spawn(move || { - profiling::register_thread!(format!("Subscript {} Thread", id)); + profiling::register_thread!(format!("Subscript {id} Thread")); // unsafe required to load C modules (curl) let lua = unsafe { Lua::unsafe_new() }; @@ -128,32 +139,36 @@ impl Subscript { // TODO: this is awkward, move package path registration out of PoB? PathOfBuilding::register_package_paths(&lua, &script_dir)?; + // register a proxy for each allowed blocking call. + // forwards the call to the main thread and blocks on `reply_rx` until the main thread + // sends back the return values for function_name in blocking_calls { - let thread_tx = tx.clone(); + let call_tx = call_tx.clone(); lua.globals().set( function_name.clone(), lua.create_function(move |_, args: MultiValue| { - let (tx_return, rx_return) = channel(); - thread_tx + let (reply_tx, reply_rx) = channel(); + call_tx .send(SubscriptCall::Blocking { function_name: function_name.clone(), arguments: args.try_into()?, - return_values_sender: tx_return, + reply_tx, }) .unwrap(); - // this blocks until we receive return values - let return_values = rx_return.recv().map_err(|e| anyhow!("{e}"))??; + let return_values = reply_rx.recv().map_err(|e| anyhow!("{e}"))??; Ok(return_values) })?, )?; } + // register a proxy for each allowed non-blocking call. + // forwards the call to the main thread and returns immediately for function_name in nonblocking_calls { - let thread_tx = tx.clone(); + let call_tx = call_tx.clone(); lua.globals().set( function_name.clone(), lua.create_function(move |_, args: MultiValue| { - thread_tx + call_tx .send(SubscriptCall::NonBlocking { function_name: function_name.clone(), arguments: args.try_into()?, @@ -171,12 +186,15 @@ impl Subscript { Self { id, handle: Some(handle), - receiver: rx, + call_rx, } } + /// Handles pending `SubscriptCall`s. + /// + /// Does nothing if there is no pending call. fn handle_calls(&self, lua: &Lua) { - let call = match self.receiver.try_recv() { + let call = match self.call_rx.try_recv() { Ok(call) => call, // no pending call, or thread disconnected which is handled on join Err(_) => return, @@ -189,13 +207,14 @@ impl Subscript { SubscriptCall::Blocking { function_name, arguments, - return_values_sender, + reply_tx: return_values_sender, } => { let result = func .map_err(anyhow::Error::from) .and_then(|f| Ok(f.call::((function_name, arguments))?)) .and_then(NativeMultiValue::try_from); - // send return values back to thread + // if the subscript's thread has already gone away, there's nowhere to send the + // result, so ignore the error let _ = return_values_sender.send(result); } SubscriptCall::NonBlocking { @@ -203,53 +222,62 @@ impl Subscript { arguments, } => { if let Ok(func) = func { - // we can ignore return values for non-blocking calls + // return values of non-blocking calls are discarded let _ = func.call::<()>((function_name, arguments)); } } } } + /// If the subscript's thread has finished, joins it and returns the resulting + /// `SubscriptResult`. fn try_join(&mut self) -> Option { - if self.handle.as_ref().is_some_and(JoinHandle::is_finished) { - let event = match self.handle.take().unwrap().join() { - Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished { - id: self.id, - return_values, - }, - Ok(Err(err)) => SubscriptResult::SubscriptError { - id: self.id, - error: err.to_string(), - }, - // the thread panicked - Err(_) => SubscriptResult::SubscriptError { - id: self.id, - error: String::from("Subscript thread panicked!"), - }, - }; - Some(event) - } else { - None + if !self.handle.as_ref().is_some_and(JoinHandle::is_finished) { + return None; } + + let event = match self.handle.take().unwrap().join() { + Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished { + id: self.id, + return_values, + }, + Ok(Err(err)) => SubscriptResult::SubscriptError { + id: self.id, + error: err.to_string(), + }, + // the thread panicked + Err(_) => SubscriptResult::SubscriptError { + id: self.id, + error: String::from("Subscript thread panicked!"), + }, + }; + Some(event) } } -// used to move arguments and return values between lua instances -// some lua values are associated with their instance and using them with another -// instance is not allowed. -#[derive(Debug)] -pub struct NativeMultiValue(VecDeque); - +/// Instance-independent stand-in for `mlua::Value`. +/// +/// Values produced by one Lua instance (in particular strings) cannot be used directly with +/// another Lua instance. `NativeValue` acts as a stand-in to freely move between the main instance +/// and a subscript's instance. It only covers the types that are actually exchanged, namely `nil`, +/// booleans, numbers, and string. #[derive(Debug)] pub enum NativeValue { Nil, Number(Number), Integer(Integer), Boolean(bool), - // Lua strings may not be valid UTF-8, so use Vec instead of String + // Lua strings may not be valid UTF-8, so store as raw bytes instead of String String(Vec), } +/// Instance-independent stand-in for `mlua::MultiValue`. +/// +/// Used to pass function arguments and return values between the main Lua instance and a +/// subscript's Lua instance. +#[derive(Debug)] +pub struct NativeMultiValue(Vec); + impl TryFrom for NativeValue { type Error = anyhow::Error;