use crate::common::error::Result;
use crate::common::protocol::Frame;
use crate::server::connection::ConnectionManagerTrait;
use async_trait::async_trait;
use std::sync::Arc;
#[async_trait]
pub trait ServerHandle: Send + Sync {
async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()>;
async fn send_to_connections(&self, connection_ids: &[String], frame: &Frame) -> (i32, i32) {
let mut success = 0i32;
let mut failure = 0i32;
for connection_id in connection_ids {
match self.send_to(connection_id, frame).await {
Ok(()) => success += 1,
Err(_) => failure += 1,
}
}
(success, failure)
}
async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()>;
async fn broadcast(&self, frame: &Frame) -> Result<()>;
async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()>;
async fn disconnect(&self, connection_id: &str) -> Result<()>;
fn connection_count(&self) -> usize;
fn user_count(&self) -> usize;
}
pub struct DefaultServerHandle {
connection_manager: Arc<dyn ConnectionManagerTrait>,
}
impl DefaultServerHandle {
pub fn new(connection_manager: Arc<dyn ConnectionManagerTrait>) -> Self {
Self { connection_manager }
}
}
#[async_trait]
impl ServerHandle for DefaultServerHandle {
async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
self.connection_manager
.send_frame_to(connection_id, frame, None)
.await
}
async fn send_to_connections(&self, connection_ids: &[String], frame: &Frame) -> (i32, i32) {
self.connection_manager
.send_frame_to_connections(connection_ids, frame)
.await
}
async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
self.connection_manager
.send_frame_to_user(user_id, frame, None)
.await
}
async fn broadcast(&self, frame: &Frame) -> Result<()> {
self.connection_manager.broadcast_frame(frame, None).await
}
async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
self.connection_manager
.broadcast_frame_except(frame, exclude_connection_id, None)
.await
}
async fn disconnect(&self, connection_id: &str) -> Result<()> {
self.connection_manager
.remove_connection(connection_id)
.await
}
fn connection_count(&self) -> usize {
self.connection_manager.connection_count_snapshot()
}
fn user_count(&self) -> usize {
self.connection_manager.user_count_snapshot()
}
}