use crate::common::MessageParser;
use crate::common::message::parser::PRE_NEGOTIATION_PARSER;
use crate::server::connection::ConnectionManager;
use crate::server::events::ServerMessageWrapper;
use crate::transport::events::{ConnectionEvent, ConnectionObserver};
use std::sync::Arc;
use tracing::{debug, error, warn};
struct ConnectionState {
info: crate::server::connection::ConnectionInfo,
negotiation_completed: bool,
negotiation_confirmed: bool,
cached_parser: Option<Arc<MessageParser>>,
cached_pipeline: Option<Arc<crate::common::message::pipeline::MessagePipeline>>,
}
pub struct ConnectionHandlerObserverAdapter {
handler: Arc<ServerMessageWrapper>,
connection_id: String,
connection_manager: Arc<ConnectionManager>,
server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
}
impl ConnectionHandlerObserverAdapter {
pub fn new(
handler: Arc<ServerMessageWrapper>,
connection_id: String,
connection_manager: Arc<ConnectionManager>,
server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
) -> Self {
Self {
handler,
connection_id,
connection_manager,
server_core,
}
}
async fn handle_message_event(
handler: &Arc<ServerMessageWrapper>,
data: Vec<u8>,
conn_id: Arc<str>,
manager: Arc<ConnectionManager>,
server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
) {
let manager_trait =
Arc::clone(&manager) as Arc<dyn crate::server::connection::ConnectionManagerTrait>;
let conn_id_clone = Arc::clone(&conn_id);
if let Err(e) = manager_trait.update_connection_active(&conn_id_clone).await {
tracing::warn!(
"[ConnectionHandlerObserverAdapter] 更新连接活跃时间失败(连接可能不存在): connection_id={}, error={}",
conn_id,
e
);
}
let connection_state = Self::get_connection_state(&manager, &conn_id);
if connection_state.negotiation_completed {
Self::handle_negotiated_message(
handler,
data,
conn_id,
manager,
connection_state.info,
connection_state.negotiation_confirmed,
connection_state.cached_parser,
connection_state.cached_pipeline,
)
.await;
} else {
Self::handle_pre_negotiation_message(handler, data, conn_id, manager, server_core)
.await;
}
}
fn get_connection_state(manager: &Arc<ConnectionManager>, conn_id: &str) -> ConnectionState {
manager
.get_connection(conn_id)
.map(|(_, info)| ConnectionState {
negotiation_completed: info.negotiation_completed,
negotiation_confirmed: info.negotiation_confirmed,
cached_parser: info.cached_parser.clone(),
cached_pipeline: info.cached_pipeline.clone(),
info: info.clone(),
})
.unwrap_or_else(|| {
let default_info =
crate::server::connection::ConnectionInfo::new(conn_id.to_string(), true);
ConnectionState {
info: default_info,
negotiation_completed: false,
negotiation_confirmed: false,
cached_parser: None,
cached_pipeline: None,
}
})
}
#[allow(clippy::too_many_arguments)]
async fn handle_negotiated_message(
handler: &Arc<ServerMessageWrapper>,
data: Vec<u8>,
conn_id: Arc<str>,
manager: Arc<ConnectionManager>,
connection_info: crate::server::connection::ConnectionInfo,
negotiation_confirmed: bool,
cached_parser: Option<Arc<MessageParser>>,
cached_pipeline: Option<Arc<crate::common::message::pipeline::MessagePipeline>>,
) {
if let Ok(frame) = PRE_NEGOTIATION_PARSER.parse(&data)
&& Self::is_negotiation_ready_message(&frame)
{
if let Err(e) = (*manager).mark_negotiation_confirmed(&conn_id) {
error!(
"[ConnectionHandlerObserverAdapter] 标记协商确认失败: connection_id={}, error={}",
conn_id, e
);
} else {
debug!(
"[ConnectionHandlerObserverAdapter] ✅ 协商已确认: connection_id={},之后将严格使用协商后的 parser",
conn_id
);
}
return;
}
let allow_fallback = !negotiation_confirmed;
let compression = connection_info.compression.clone();
let encryption = connection_info.encryption.clone();
let parser = cached_parser.unwrap_or_else(|| {
error!(
"[ConnectionHandlerObserverAdapter] 协商已完成但缓存 parser 不存在,回退到动态创建: connection_id={}",
conn_id
);
std::sync::Arc::new(crate::common::MessageParser::new(
connection_info.serialization_format,
compression.clone(),
encryption.clone(),
))
});
if encryption != crate::common::encryption::EncryptionAlgorithm::None {
let encryptor_name = encryption.as_str();
if !crate::common::encryption::EncryptionUtil::is_registered(&encryptor_name) {
let registered = crate::common::encryption::EncryptionUtil::list_registered();
error!(
"[ConnectionHandlerObserverAdapter] 加密器未注册: connection_id={}, encryption={:?}, registered={:?}",
conn_id, encryption, registered
);
return;
}
}
let frame = match parser.parse_with_fallback(&data, allow_fallback) {
Ok(frame) => frame,
Err(e) => {
let encryptor_status = if encryption
!= crate::common::encryption::EncryptionAlgorithm::None
{
let encryptor_name = encryption.as_str();
if crate::common::encryption::EncryptionUtil::is_registered(&encryptor_name) {
"registered".to_string()
} else {
format!(
"NOT registered (registered: {:?})",
crate::common::encryption::EncryptionUtil::list_registered()
)
}
} else {
"none".to_string()
};
let data_preview: Vec<u8> = data.iter().take(16).cloned().collect();
error!(
"[ConnectionHandlerObserverAdapter] 解析消息失败(协商后): connection_id={}, format={:?}, compression={:?}, encryption={:?} ({}), confirmed={}, allow_fallback={}, error={}, data_len={}, data_preview={:?}",
conn_id,
connection_info.serialization_format,
compression,
encryption,
encryptor_status,
negotiation_confirmed,
allow_fallback,
e,
data.len(),
data_preview
);
return;
}
};
if let Some(pipeline) = cached_pipeline {
match pipeline.process_frame(&frame, Some(&conn_id)).await {
Ok(pipeline_response) => {
if pipeline_response.is_some() {
debug!(
"[ConnectionHandlerObserverAdapter] Pipeline 返回了响应,但继续调用 handle_frame: connection_id={}",
conn_id
);
}
}
Err(e) => {
error!(
"[ConnectionHandlerObserverAdapter] Pipeline 处理失败: connection_id={}, error={}",
conn_id, e
);
}
}
}
Self::handle_frame_safely(handler, &frame, &conn_id).await;
}
async fn handle_pre_negotiation_message(
handler: &Arc<ServerMessageWrapper>,
data: Vec<u8>,
conn_id: Arc<str>,
manager: Arc<ConnectionManager>,
server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
) {
match PRE_NEGOTIATION_PARSER.parse(&data) {
Ok(frame) => {
if Self::is_connect_message(&frame) {
Self::handle_connect_message(handler, &frame, &conn_id, manager, server_core)
.await; } else {
if let Some((_, conn_info)) = (*manager).get_connection(&conn_id) {
warn!(
"[ConnectionHandlerObserverAdapter] 收到非 CONNECT 消息但协商未完成: connection_id={}, negotiation_completed={}, negotiation_confirmed={}, format={:?}, compression={:?}, encryption={:?}",
conn_id,
conn_info.negotiation_completed,
conn_info.negotiation_confirmed,
conn_info.serialization_format,
conn_info.compression,
conn_info.encryption
);
} else {
warn!(
"[ConnectionHandlerObserverAdapter] 收到非 CONNECT 消息但协商未完成: connection_id={}, 连接不存在",
conn_id
);
}
Self::handle_frame_safely(handler, &frame, &conn_id).await;
}
}
Err(e) => {
error!(
"[ConnectionHandlerObserverAdapter] 解析消息失败(协商前): connection_id={}, error={}",
conn_id, e
);
}
}
}
async fn handle_frame_safely(
handler: &Arc<ServerMessageWrapper>,
frame: &crate::common::protocol::Frame,
conn_id: &str,
) {
use crate::server::ConnectionHandler;
if let Err(e) = ConnectionHandler::handle_frame(handler.as_ref(), frame, conn_id).await {
error!(
"[ConnectionHandlerObserverAdapter] 处理消息失败: connection_id={}, error={}",
conn_id, e
);
}
}
async fn handle_connect_message(
_handler: &Arc<ServerMessageWrapper>,
frame: &crate::common::protocol::Frame,
conn_id: &Arc<str>,
manager: Arc<ConnectionManager>,
server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
) {
let Some((connection, _)) = manager.get_connection(conn_id) else {
error!(
"[ConnectionHandlerObserverAdapter] 连接不存在,无法处理 CONNECT: connection_id={}",
conn_id
);
return;
};
let Some(server_core) = &server_core else {
error!(
"[ConnectionHandlerObserverAdapter] ServerCore 未初始化,无法处理 CONNECT: connection_id={}",
conn_id
);
return;
};
if let Err(e) = server_core
.handle_connect_complete(frame, conn_id, connection)
.await
{
error!(
"[ConnectionHandlerObserverAdapter] 处理 CONNECT 消息失败: connection_id={}, error={}",
conn_id, e
);
}
}
fn is_connect_message(frame: &crate::common::protocol::Frame) -> bool {
frame.command.as_ref().and_then(|cmd| {
if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
Some(sys_cmd.r#type == SysType::Connect as i32)
} else {
None
}
}).unwrap_or(false)
}
fn is_negotiation_ready_message(frame: &crate::common::protocol::Frame) -> bool {
frame.command.as_ref().and_then(|cmd| {
if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
Some(sys_cmd.r#type == SysType::NegotiationReady as i32)
} else {
None
}
}).unwrap_or(false)
}
}
impl ConnectionObserver for ConnectionHandlerObserverAdapter {
fn on_event(&self, event: &ConnectionEvent) {
match event {
ConnectionEvent::Message(data) => {
let handler = Arc::clone(&self.handler);
let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
let manager = Arc::clone(&self.connection_manager);
let server_core = self.server_core.clone();
let data = data.to_vec();
tokio::spawn(async move {
Self::handle_message_event(&handler, data, conn_id, manager, server_core).await;
});
}
ConnectionEvent::Connected => {
debug!(
"[ConnectionHandlerObserverAdapter] transport connected; wait for CONNECT negotiation: connection_id={}",
self.connection_id
);
}
ConnectionEvent::Disconnected(reason) => {
let handler = Arc::clone(&self.handler);
let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
let reason_str: Arc<str> = Arc::from(reason.as_str());
tokio::spawn(async move {
use crate::server::ConnectionHandler;
if let Err(e) =
ConnectionHandler::on_disconnect(handler.as_ref(), &conn_id).await
{
warn!(
"[ConnectionHandlerObserverAdapter] 处理断开事件失败: connection_id={}, reason={}, error={}",
conn_id, reason_str, e
);
}
});
}
ConnectionEvent::Error(err) => {
let handler = Arc::clone(&self.handler);
let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
let error_msg = err.to_string();
let error_str: Arc<str> = Arc::from(error_msg.as_str());
tokio::spawn(async move {
if let Err(e) = handler.on_error(&conn_id, &error_str).await {
error!(
"[ConnectionHandlerObserverAdapter] 处理错误事件失败: connection_id={}, error={}",
conn_id, e
);
}
});
}
}
}
}