refactor: streamline master message handling by removing unnecessary Arc and Mutex usage, and reorganizing handler structure

This commit is contained in:
GW_MC
2026-05-31 09:41:33 +00:00
parent 93a36cb101
commit 8dbbeb4b24
4 changed files with 226 additions and 276 deletions

View File

@@ -0,0 +1,62 @@
use std::sync::Arc;
use nxmesh_proto::{AgentMessage, ConfigUpdate, MasterMessage, master_message::Payload};
use crate::service::master_handler::{MasterHandlerError, MessageResult};
#[async_trait::async_trait]
pub trait MasterMessageHandler: Send + Sync + 'static {
async fn handle_master_message(&self, message: MasterMessage) -> MessageResult<()>;
}
#[async_trait::async_trait]
pub trait OnConfigUpdateHandler: Send + Sync + 'static {
// Handle the config update message from master, write the config content to files, validate the new config and reload nginx
async fn on_config_update(&self, config_info: ConfigUpdate) -> MessageResult<()>;
}
pub struct HandlerImpl<OCH>
where
OCH: OnConfigUpdateHandler,
{
on_config_update_handler: Arc<OCH>,
}
impl<OCH> HandlerImpl<OCH>
where
OCH: OnConfigUpdateHandler,
{
pub fn new(on_config_update_handler: Arc<OCH>) -> Self {
Self {
on_config_update_handler,
}
}
}
#[async_trait::async_trait]
impl<OCH> MasterMessageHandler for HandlerImpl<OCH>
where
OCH: OnConfigUpdateHandler,
{
async fn handle_master_message(&self, message: MasterMessage) -> MessageResult<()> {
match message.payload {
Some(Payload::ConfigUpdate(config_info)) => {
self.on_config_update_handler
.on_config_update(config_info)
.await
}
Some(_) => {
// We should never receive other types of messages from the master, but we should handle it anyway
Err(MasterHandlerError::MessageHandlingError(
"Received unsupported master message type".to_string(),
))
}
None => {
// This should never happen as the master should always send a valid message, but we should handle it anyway
return Err(MasterHandlerError::MessageHandlingError(
"Received master message with empty payload".to_string(),
));
}
}
}
}