Fixed comments

This commit is contained in:
ccgauche 2021-03-01 21:29:18 +01:00
parent 4cffd2cadd
commit 9628dfaf99
12 changed files with 52 additions and 37 deletions

View File

@ -4,7 +4,7 @@ use network::{ParticipantError, StreamError};
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {
KickedByPlugin(String), Kicked(String),
NetworkErr(NetworkError), NetworkErr(NetworkError),
ParticipantErr(ParticipantError), ParticipantErr(ParticipantError),
StreamErr(StreamError), StreamErr(StreamError),

View File

@ -500,7 +500,7 @@ impl Client {
Err(RegisterError::AuthError(err)) => Err(Error::AuthErr(err)), Err(RegisterError::AuthError(err)) => Err(Error::AuthErr(err)),
Err(RegisterError::InvalidCharacter) => Err(Error::InvalidCharacter), Err(RegisterError::InvalidCharacter) => Err(Error::InvalidCharacter),
Err(RegisterError::NotOnWhitelist) => Err(Error::NotOnWhitelist), Err(RegisterError::NotOnWhitelist) => Err(Error::NotOnWhitelist),
Err(RegisterError::KickedByPlugin(err)) => Err(Error::KickedByPlugin(err)), Err(RegisterError::Kicked(err)) => Err(Error::Kicked(err)),
Err(RegisterError::Banned(reason)) => Err(Error::Banned(reason)), Err(RegisterError::Banned(reason)) => Err(Error::Banned(reason)),
Ok(()) => { Ok(()) => {
self.registered = true; self.registered = true;

View File

@ -191,7 +191,7 @@ pub enum RegisterError {
AlreadyLoggedIn, AlreadyLoggedIn,
AuthError(String), AuthError(String),
Banned(String), Banned(String),
KickedByPlugin(String), Kicked(String),
InvalidCharacter, InvalidCharacter,
NotOnWhitelist, NotOnWhitelist,
//TODO: InvalidAlias, //TODO: InvalidAlias,

View File

@ -106,6 +106,11 @@ impl MemoryManager {
) )
} }
/// This function writes an object to the wasm memory using the allocator if
/// necessary using length padding.
///
/// With length padding the first 8 bytes written are the length of the the
/// following slice (The object serialized).
pub fn write_data_as_pointer<T: Serialize>( pub fn write_data_as_pointer<T: Serialize>(
&self, &self,
memory: &Memory, memory: &Memory,
@ -125,32 +130,39 @@ impl MemoryManager {
&self, &self,
memory: &Memory, memory: &Memory,
allocator: &Function, allocator: &Function,
array: &[u8], bytes: &[u8],
) -> Result<(u64, u64), PluginModuleError> { ) -> Result<(u64, u64), PluginModuleError> {
let len = array.len(); let len = bytes.len();
let mem_position = self let mem_position = self
.get_pointer(len as u32, allocator) .get_pointer(len as u32, allocator)
.map_err(PluginModuleError::MemoryAllocation)? as usize; .map_err(PluginModuleError::MemoryAllocation)? as usize;
memory.view()[mem_position..mem_position + len] memory.view()[mem_position..mem_position + len]
.iter() .iter()
.zip(array.iter()) .zip(bytes.iter())
.for_each(|(cell, byte)| cell.set(*byte)); .for_each(|(cell, byte)| cell.set(*byte));
Ok((mem_position as u64, len as u64)) Ok((mem_position as u64, len as u64))
} }
/// This function writes bytes to the wasm memory using the allocator if
/// necessary using length padding.
///
/// With length padding the first 8 bytes written are the length of the the
/// following slice.
pub fn write_bytes_as_pointer( pub fn write_bytes_as_pointer(
&self, &self,
memory: &Memory, memory: &Memory,
allocator: &Function, allocator: &Function,
array: &[u8], bytes: &[u8],
) -> Result<u64, PluginModuleError> { ) -> Result<u64, PluginModuleError> {
let len = array.len(); let len = bytes.len();
let mem_position = self let mem_position = self
.get_pointer(len as u32 + 8, allocator) .get_pointer(len as u32 + 8, allocator)
.map_err(PluginModuleError::MemoryAllocation)? as usize; .map_err(PluginModuleError::MemoryAllocation)? as usize;
// Here we write the length as le bytes followed by the slice data itself in
// WASM memory
memory.view()[mem_position..mem_position + len + 8] memory.view()[mem_position..mem_position + len + 8]
.iter() .iter()
.zip((len as u64).to_le_bytes().iter().chain(array.iter())) .zip((len as u64).to_le_bytes().iter().chain(bytes.iter()))
.for_each(|(cell, byte)| cell.set(*byte)); .for_each(|(cell, byte)| cell.set(*byte));
Ok(mem_position as u64) Ok(mem_position as u64)
} }

View File

@ -84,7 +84,6 @@ impl Plugin {
pub fn execute_prepared<T>( pub fn execute_prepared<T>(
&self, &self,
ecs: &World, ecs: &World,
event_name: &str,
event: &PreparedEventQuery<T>, event: &PreparedEventQuery<T>,
) -> Result<Vec<T::Response>, PluginError> ) -> Result<Vec<T::Response>, PluginError>
where where
@ -93,11 +92,11 @@ impl Plugin {
self.modules self.modules
.iter() .iter()
.flat_map(|module| { .flat_map(|module| {
module.try_execute(ecs, event_name, event).map(|x| { module.try_execute(ecs, event).map(|x| {
x.map_err(|e| { x.map_err(|e| {
PluginError::PluginModuleError( PluginError::PluginModuleError(
self.data.name.to_owned(), self.data.name.to_owned(),
event_name.to_owned(), event.get_function_name().to_owned(),
e, e,
) )
}) })
@ -123,7 +122,6 @@ impl PluginMgr {
pub fn execute_prepared<T>( pub fn execute_prepared<T>(
&self, &self,
ecs: &World, ecs: &World,
event_name: &str,
event: &PreparedEventQuery<T>, event: &PreparedEventQuery<T>,
) -> Result<Vec<T::Response>, PluginError> ) -> Result<Vec<T::Response>, PluginError>
where where
@ -132,23 +130,18 @@ impl PluginMgr {
Ok(self Ok(self
.plugins .plugins
.par_iter() .par_iter()
.map(|plugin| plugin.execute_prepared(ecs, event_name, event)) .map(|plugin| plugin.execute_prepared(ecs, event))
.collect::<Result<Vec<_>, _>>()? .collect::<Result<Vec<_>, _>>()?
.into_iter() .into_iter()
.flatten() .flatten()
.collect()) .collect())
} }
pub fn execute_event<T>( pub fn execute_event<T>(&self, ecs: &World, event: &T) -> Result<Vec<T::Response>, PluginError>
&self,
ecs: &World,
event_name: &str,
event: &T,
) -> Result<Vec<T::Response>, PluginError>
where where
T: Event, T: Event,
{ {
self.execute_prepared(ecs, event_name, &PreparedEventQuery::new(event)?) self.execute_prepared(ecs, &PreparedEventQuery::new(event)?)
} }
pub fn from_dir<P: AsRef<Path>>(path: P) -> Result<Self, PluginError> { pub fn from_dir<P: AsRef<Path>>(path: P) -> Result<Self, PluginError> {

View File

@ -111,19 +111,18 @@ impl PluginModule {
pub fn try_execute<T>( pub fn try_execute<T>(
&self, &self,
ecs: &World, ecs: &World,
event_name: &str,
request: &PreparedEventQuery<T>, request: &PreparedEventQuery<T>,
) -> Option<Result<T::Response, PluginModuleError>> ) -> Option<Result<T::Response, PluginModuleError>>
where where
T: Event, T: Event,
{ {
if !self.events.contains(event_name) { if !self.events.contains(&request.function_name) {
return None; return None;
} }
// Store the ECS Pointer for later use in `retreives` // Store the ECS Pointer for later use in `retreives`
let bytes = match self.ecs.execute_with(ecs, || { let bytes = match self.ecs.execute_with(ecs, || {
let mut state = self.wasm_state.lock().unwrap(); let mut state = self.wasm_state.lock().unwrap();
execute_raw(self, &mut state, event_name, &request.bytes) execute_raw(self, &mut state, &request.function_name, &request.bytes)
}) { }) {
Ok(e) => e, Ok(e) => e,
Err(e) => return Some(Err(e)), Err(e) => return Some(Err(e)),
@ -136,6 +135,7 @@ impl PluginModule {
/// reencoding for each module in every plugin) /// reencoding for each module in every plugin)
pub struct PreparedEventQuery<T> { pub struct PreparedEventQuery<T> {
bytes: Vec<u8>, bytes: Vec<u8>,
function_name: String,
_phantom: PhantomData<T>, _phantom: PhantomData<T>,
} }
@ -149,9 +149,12 @@ impl<T: Event> PreparedEventQuery<T> {
{ {
Ok(Self { Ok(Self {
bytes: bincode::serialize(&event).map_err(PluginError::Encoding)?, bytes: bincode::serialize(&event).map_err(PluginError::Encoding)?,
function_name: event.get_event_name(),
_phantom: PhantomData::default(), _phantom: PhantomData::default(),
}) })
} }
pub fn get_function_name(&self) -> &str { &self.function_name }
} }
pub fn from_u128(i: u128) -> (u64, u64) { pub fn from_u128(i: u128) -> (u64, u64) {
@ -202,8 +205,8 @@ fn execute_raw(
.call(&[Value::I64(to_i64(mem_position)), Value::I64(to_i64(len))]) .call(&[Value::I64(to_i64(mem_position)), Value::I64(to_i64(len))])
.map_err(PluginModuleError::RunFunction)?; .map_err(PluginModuleError::RunFunction)?;
// Waiting for `multi-value` to be added to LLVM. So we encode the two i32 as an // Waiting for `multi-value` to be added to LLVM. So we encode a pointer to a
// i64 // u128 that represent [u64; 2]
let u128_pointer = from_i64( let u128_pointer = from_i64(
function_result[0] function_result[0]
@ -215,6 +218,8 @@ fn execute_raw(
// We read the return object and deserialize it // We read the return object and deserialize it
// The first 8 bytes are encoded as le and represent the pointer to the data
// The next 8 bytes are encoded as le and represent the length of the data
Ok(memory_manager::read_bytes( Ok(memory_manager::read_bytes(
&module.memory, &module.memory,
u64::from_le_bytes(bytes[0..8].try_into().unwrap()), u64::from_le_bytes(bytes[0..8].try_into().unwrap()),

View File

@ -209,10 +209,8 @@ impl State {
#[cfg(feature = "plugins")] #[cfg(feature = "plugins")]
ecs.insert(match PluginMgr::from_assets() { ecs.insert(match PluginMgr::from_assets() {
Ok(plugin_mgr) => { Ok(plugin_mgr) => {
if let Err(e) = if let Err(e) = plugin_mgr
plugin_mgr.execute_event(&ecs, "on_load", &plugin_api::event::PluginLoadEvent { .execute_event(&ecs, &plugin_api::event::PluginLoadEvent { game_mode })
game_mode,
})
{ {
tracing::error!(?e, "Failed to run plugin init"); tracing::error!(?e, "Failed to run plugin init");
tracing::info!( tracing::info!(

View File

@ -31,6 +31,8 @@ pub enum RetrieveResult {
pub trait Event: Serialize + DeserializeOwned + Send + Sync { pub trait Event: Serialize + DeserializeOwned + Send + Sync {
type Response: Serialize + DeserializeOwned + Send + Sync; type Response: Serialize + DeserializeOwned + Send + Sync;
fn get_event_name(&self) -> String;
} }
pub mod event { pub mod event {
@ -46,6 +48,8 @@ pub mod event {
impl Event for ChatCommandEvent { impl Event for ChatCommandEvent {
type Response = Result<Vec<String>, String>; type Response = Result<Vec<String>, String>;
fn get_event_name(&self) -> String { format!("on_command_{}", self.command) }
} }
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
@ -61,12 +65,14 @@ pub mod event {
impl Event for PlayerJoinEvent { impl Event for PlayerJoinEvent {
type Response = PlayerJoinResult; type Response = PlayerJoinResult;
fn get_event_name(&self) -> String { "on_join".to_owned() }
} }
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[repr(u8)] #[repr(u8)]
pub enum PlayerJoinResult { pub enum PlayerJoinResult {
CloseConnection(String), Kick(String),
None, None,
} }
@ -81,6 +87,8 @@ pub mod event {
impl Event for PluginLoadEvent { impl Event for PluginLoadEvent {
type Response = (); type Response = ();
fn get_event_name(&self) -> String { "on_load".to_owned() }
} }
// #[derive(Serialize, Deserialize, Debug)] // #[derive(Serialize, Deserialize, Debug)]

View File

@ -36,7 +36,7 @@ static COUNTER: AtomicBool = AtomicBool::new(false);
#[event_handler] #[event_handler]
pub fn on_join(input: PlayerJoinEvent) -> PlayerJoinResult { pub fn on_join(input: PlayerJoinEvent) -> PlayerJoinResult {
if COUNTER.swap(!COUNTER.load(Ordering::SeqCst), Ordering::SeqCst) { if COUNTER.swap(!COUNTER.load(Ordering::SeqCst), Ordering::SeqCst) {
PlayerJoinResult::CloseConnection(format!("You are a cheater {:?}", input)) PlayerJoinResult::Kick(format!("You are a cheater {:?}", input))
} else { } else {
PlayerJoinResult::None PlayerJoinResult::None
} }

View File

@ -1037,7 +1037,6 @@ impl Server {
let plugin_manager = self.state.ecs().read_resource::<PluginMgr>(); let plugin_manager = self.state.ecs().read_resource::<PluginMgr>();
let rs = plugin_manager.execute_event( let rs = plugin_manager.execute_event(
self.state.ecs(), self.state.ecs(),
&format!("on_command_{}", &kwd),
&plugin_api::event::ChatCommandEvent { &plugin_api::event::ChatCommandEvent {
command: kwd.clone(), command: kwd.clone(),
command_args: args.split(' ').map(|x| x.to_owned()).collect(), command_args: args.split(' ').map(|x| x.to_owned()).collect(),

View File

@ -79,14 +79,14 @@ impl LoginProvider {
return Err(RegisterError::NotOnWhitelist); return Err(RegisterError::NotOnWhitelist);
} }
match plugin_manager.execute_event(&world, "on_join", &PlayerJoinEvent { match plugin_manager.execute_event(&world, &PlayerJoinEvent {
player_name: username.clone(), player_name: username.clone(),
player_id: *uuid.as_bytes(), player_id: *uuid.as_bytes(),
}) { }) {
Ok(e) => { Ok(e) => {
for i in e.into_iter() { for i in e.into_iter() {
if let PlayerJoinResult::CloseConnection(a) = i { if let PlayerJoinResult::Kick(a) = i {
return Err(RegisterError::KickedByPlugin(a)); return Err(RegisterError::Kicked(a));
} }
} }
}, },

View File

@ -134,7 +134,7 @@ impl PlayState for MainMenuState {
localized_strings.get("main.login.authentication_error"), localized_strings.get("main.login.authentication_error"),
e e
), ),
client::Error::KickedByPlugin(e) => e, client::Error::Kicked(e) => e,
client::Error::TooManyPlayers => { client::Error::TooManyPlayers => {
localized_strings.get("main.login.server_full").into() localized_strings.get("main.login.server_full").into()
}, },