fedimint_core/net/
peers.rsuse 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 + 'static>);
impl<Msg> Deref for PeerConnections<Msg> {
type Target = dyn IPeerConnections<Msg> + Send + '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<M>
where
M: Serialize + DeserializeOwned + Unpin + Send,
{
async fn send(&mut self, recipient: Recipient, msg: M);
fn try_send(&self, recipient: Recipient, msg: M);
async fn receive(&mut self) -> Option<(PeerId, M)>;
fn into_dyn(self) -> PeerConnections<M>
where
Self: Sized + Send + 'static,
{
PeerConnections(Box::new(self))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Recipient {
Everyone,
Peer(PeerId),
}
#[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)>;
fn into_dyn(self) -> MuxPeerConnections<MuxKey, Msg>
where
Self: Sized + Send + Sync + Unpin + 'static,
{
MuxPeerConnections(Arc::new(self))
}
}