use super::types::{MessageKind, RequestId, Topic};
use crate::error::TransportResult;
#[derive(Clone, Debug)]
pub enum WsMessage {
Text(String),
Binary(Vec<u8>),
}
impl WsMessage {
pub fn text(s: impl Into<String>) -> Self {
Self::Text(s.into())
}
pub fn binary(data: impl Into<Vec<u8>>) -> Self {
Self::Binary(data.into())
}
pub fn as_text(&self) -> Option<&str> {
match self {
Self::Text(s) => Some(s),
Self::Binary(_) => None,
}
}
pub fn as_bytes(&self) -> &[u8] {
match self {
Self::Text(s) => s.as_bytes(),
Self::Binary(b) => b,
}
}
pub fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
pub fn is_binary(&self) -> bool {
matches!(self, Self::Binary(_))
}
}
pub trait ProtocolHandler: Send + Sync + 'static {
fn on_connect(&self) -> Vec<WsMessage> {
Vec::new()
}
fn build_auth_message(&self) -> Option<WsMessage> {
None
}
fn is_auth_success(&self, message: &str) -> bool {
let _ = message;
true
}
fn is_auth_failure(&self, message: &str) -> bool {
let _ = message;
false
}
fn classify_message(&self, message: &str) -> MessageKind;
fn extract_request_id(&self, message: &str) -> Option<RequestId>;
fn extract_topic(&self, message: &str) -> Option<Topic>;
fn build_subscribe(&self, topics: &[Topic], request_id: RequestId) -> WsMessage;
fn build_unsubscribe(&self, topics: &[Topic], request_id: RequestId) -> WsMessage;
fn build_ping(&self) -> Option<WsMessage> {
None
}
fn build_pong(&self, ping_data: &[u8]) -> Option<WsMessage> {
let _ = ping_data;
None
}
fn decode_binary(&self, data: &[u8]) -> TransportResult<String> {
String::from_utf8(data.to_vec()).map_err(Into::into)
}
fn is_server_ping(&self, message: &str) -> bool {
let _ = message;
false
}
fn is_pong_response(&self, message: &str) -> bool {
let _ = message;
false
}
fn is_subscription_success(&self, message: &str, topics: &[Topic]) -> bool {
let _ = (message, topics);
false
}
fn should_reconnect(&self, message: &str) -> bool {
let _ = message;
false
}
fn generate_request_id(&self) -> RequestId {
RequestId::new()
}
fn inject_request_id(&self, message: WsMessage, request_id: &RequestId) -> WsMessage {
let _ = request_id;
message
}
}