very early version of plugin system

This commit is contained in:
Luuk van Oijen
2023-11-12 15:31:15 +01:00
parent 0b6ad43fbb
commit 8ee6ba16f2
7 changed files with 244 additions and 2 deletions

View File

@@ -0,0 +1,38 @@
use super::Backend;
use mlua::prelude::*;
pub struct BackendLua {
lua: Lua,
}
impl BackendLua {
pub fn new() -> Self {
let lua = Lua::new();
Self {
lua,
}
}
}
impl Backend for BackendLua {
fn load(&mut self, code: String) -> anyhow::Result<()> {
self.lua.load(code).exec().map_err(|e| { error!("[LUA] {:?}", e); e })?;
Ok(())
}
fn load_api(&mut self) -> anyhow::Result<()> {
let print_fn = self.lua.create_function(|_lua, (msg,): (String,)| {
info!("[LUA] {}", msg);
Ok(())
})?;
let api = self.lua.create_table()?;
api.set("print", print_fn)?;
self.lua.globals().set("MP", api)?;
Ok(())
}
}

51
src/server/plugins/mod.rs Normal file
View File

@@ -0,0 +1,51 @@
pub mod backend_lua;
use tokio::runtime::Runtime;
use tokio::sync::mpsc::{self, Sender, Receiver};
pub trait Backend {
fn load(&mut self, code: String) -> anyhow::Result<()>;
fn load_api(&mut self) -> anyhow::Result<()> { Ok(()) }
}
#[derive(Debug)]
pub enum PluginBoundPluginEvent {
}
#[derive(Debug)]
pub enum ServerBoundPluginEvent {
PluginLoaded,
}
pub struct Plugin {
runtime: Runtime,
tx: Sender<PluginBoundPluginEvent>,
rx: Receiver<ServerBoundPluginEvent>,
}
impl Plugin {
pub fn new(backend: Box<dyn Backend>) -> Self {
let runtime = Runtime::new().expect("Failed to create a tokio Runtime!");
let (pb_tx, mut pb_rx) = mpsc::channel(1_000);
let (sb_tx, sb_rx) = mpsc::channel(1_000);
runtime.spawn(async move {
if sb_tx.send(ServerBoundPluginEvent::PluginLoaded).await.is_err() {
error!("Plugin communication channels somehow already closed!");
return;
}
loop {
if let Some(message) = pb_rx.recv().await {
debug!("Received message: {:?}", message);
} else {
return;
}
}
});
Self {
runtime,
tx: pb_tx,
rx: sb_rx,
}
}
}