use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use async_trait::async_trait;
use fedimint_core::PeerId;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::task::Cancellable;
#[cfg(not(target_family = "wasm"))]
pub mod fake;
pub struct PeerConnections<Msg>(Box<dyn IPeerConnections<Msg> + Send + Unpin + 'static>);
impl<Msg> Deref for PeerConnections<Msg> {
type Target = dyn IPeerConnections<Msg> + Send + Unpin + 'static;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl<Msg> DerefMut for PeerConnections<Msg> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.0
}
}
#[async_trait]
pub trait IPeerConnections<Msg>
where
Msg: Serialize + DeserializeOwned + Unpin + Send,
{
async fn send(&mut self, peers: &[PeerId], msg: Msg) -> Cancellable<()>;
async fn receive(&mut self) -> Cancellable<(PeerId, Msg)>;
async fn ban_peer(&mut self, peer: PeerId);
fn into_dyn(self) -> PeerConnections<Msg>
where
Self: Sized + Send + Unpin + 'static,
{
PeerConnections(Box::new(self))
}
}
#[derive(Clone)]
pub struct MuxPeerConnections<MuxKey, Msg>(
Arc<dyn IMuxPeerConnections<MuxKey, Msg> + Send + Sync + Unpin + 'static>,
);
impl<MuxKey, Msg> Deref for MuxPeerConnections<MuxKey, Msg> {
type Target = dyn IMuxPeerConnections<MuxKey, Msg> + Send + Sync + Unpin + 'static;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
#[async_trait]
pub trait IMuxPeerConnections<MuxKey, Msg>
where
Msg: Serialize + DeserializeOwned + Unpin + Send,
MuxKey: Serialize + DeserializeOwned + Unpin + Send,
{
async fn send(&self, peers: &[PeerId], mux_key: MuxKey, msg: Msg) -> Cancellable<()>;
async fn receive(&self, mux_key: MuxKey) -> Cancellable<(PeerId, Msg)>;
async fn ban_peer(&self, peer: PeerId);
fn into_dyn(self) -> MuxPeerConnections<MuxKey, Msg>
where
Self: Sized + Send + Sync + Unpin + 'static,
{
MuxPeerConnections(Arc::new(self))
}
}