mod connection;
mod frame;
mod pubsub;
mod upgrade;
pub use connection::WebSocket;
pub use frame::{CloseFrame, Message};
pub use pubsub::ChannelManager;
pub use upgrade::WebSocketUpgrade;
#[cfg(any(test, feature = "test-helpers"))]
pub mod test_helpers {
pub use super::connection::WebSocket;
pub use super::frame::{CloseFrame, Frame, Message, OpCode};
pub use super::pubsub::ChannelManager;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::mpsc;
pub fn create_websocket<T>(
data: T,
sender: mpsc::Sender<Message>,
channel_manager: Arc<ChannelManager>,
connection_id: uuid::Uuid,
remote_addr: Option<SocketAddr>,
config: Arc<super::WebSocketConfig>,
) -> WebSocket<T> {
super::connection::WebSocket::new(
data,
sender,
channel_manager,
connection_id,
remote_addr,
config,
)
}
}
#[async_trait::async_trait]
pub trait WebSocketHandler: Send + Sync {
type Data: Send + Sync + 'static;
async fn on_open(&self, ws: &WebSocket<Self::Data>) {
let _ = ws;
}
async fn on_message(&self, ws: &WebSocket<Self::Data>, msg: Message);
async fn on_close(&self, ws: &WebSocket<Self::Data>, code: u16, reason: &str) {
let _ = (ws, code, reason);
}
async fn on_drain(&self, ws: &WebSocket<Self::Data>) {
let _ = ws;
}
async fn on_error(&self, ws: &WebSocket<Self::Data>, error: std::io::Error) {
let _ = (ws, error);
}
}
#[derive(Debug, Clone)]
pub struct WebSocketConfig {
pub max_message_size: usize,
pub max_frame_size: usize,
pub ping_interval: Option<u64>,
pub ping_timeout: u64,
pub compression: bool,
pub write_buffer_size: usize,
pub max_write_queue_size: usize,
pub subprotocols: Vec<String>,
}
impl Default for WebSocketConfig {
fn default() -> Self {
Self {
max_message_size: 64 * 1024 * 1024, max_frame_size: 16 * 1024 * 1024, ping_interval: Some(30), ping_timeout: 10, compression: false,
write_buffer_size: 128 * 1024, max_write_queue_size: 1024,
subprotocols: vec![],
}
}
}