use burn_std::future::DynFut;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::str::FromStr;
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
pub struct Address {
pub(crate) inner: String,
}
impl FromStr for Address {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
inner: s.to_string(),
})
}
}
impl Display for Address {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}
pub trait Protocol: Clone + Send + Sync + 'static {
type Client: ProtocolClient;
type Server: ProtocolServer;
}
pub trait CommunicationError: Debug + Send + 'static {}
pub trait ProtocolClient: Send + Sync + 'static {
type Channel: CommunicationChannel<Error = Self::Error>;
type Error: CommunicationError;
fn connect(address: Address, route: &str) -> DynFut<Option<Self::Channel>>;
}
#[derive(new)]
pub struct Message {
pub data: bytes::Bytes,
}
pub trait ProtocolServer: Sized + Send + Sync + 'static {
type Channel: CommunicationChannel<Error = Self::Error>;
type Error: CommunicationError;
fn route<C, Fut>(self, path: &str, callback: C) -> Self
where
C: FnOnce(Self::Channel) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static;
fn serve<F>(
self,
shutdown: F,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static
where
F: Future<Output = ()> + Send + 'static;
}
pub trait CommunicationChannel: Send + 'static {
type Error: CommunicationError;
fn send(
&mut self,
message: Message,
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send;
fn recv(
&mut self,
) -> impl std::future::Future<Output = Result<Option<Message>, Self::Error>> + Send;
fn close(&mut self) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send;
}