use std::future::Future;
use crate::error::TransportError;
use ahp_types::messages::JsonRpcMessage;
#[derive(Debug, Clone, PartialEq)]
pub enum TransportMessage {
Parsed(JsonRpcMessage),
Text(String),
Binary(Vec<u8>),
}
impl TransportMessage {
pub fn into_parsed(self) -> Result<JsonRpcMessage, TransportError> {
match self {
TransportMessage::Parsed(m) => Ok(m),
TransportMessage::Text(s) => {
serde_json::from_str(&s).map_err(|e| TransportError::Protocol(e.to_string()))
}
TransportMessage::Binary(b) => {
serde_json::from_slice(&b).map_err(|e| TransportError::Protocol(e.to_string()))
}
}
}
pub fn encode(msg: &JsonRpcMessage) -> Result<Self, TransportError> {
let s = serde_json::to_string(msg).map_err(|e| TransportError::Protocol(e.to_string()))?;
Ok(TransportMessage::Text(s))
}
}
pub trait Transport: Send + 'static {
fn send(
&mut self,
msg: TransportMessage,
) -> impl Future<Output = Result<(), TransportError>> + Send;
fn recv(
&mut self,
) -> impl Future<Output = Result<Option<TransportMessage>, TransportError>> + Send;
fn close(&mut self) -> impl Future<Output = Result<(), TransportError>> + Send {
async { Ok(()) }
}
}