pub mod node_config;
use std::net::SocketAddr;
use std::sync::Arc;
use bytes::Bytes;
pub use node_config::{NodeConfig, NodeConfigBuilder};
use tokio::sync::RwLock;
use tracing::trace;
use crate::{Gossip, Result};
pub struct Node {
pub config: NodeConfig,
protocol: Arc<RwLock<Gossip>>,
}
impl Node {
pub async fn new(config: NodeConfig) -> Result<Self> {
let protocol = Gossip::new(config.clone());
Ok(Self {
config,
protocol: Arc::new(RwLock::new(protocol)),
})
}
pub async fn start(&self) -> Result<()> {
let mut protocol = self.protocol.write().await;
protocol.start().await?;
trace!("Node started");
Ok(())
}
pub async fn broadcast(&self, data: impl Into<Bytes>) -> Result<()> {
let protocol = self.protocol.read().await;
protocol.broadcast(data.into()).await
}
pub async fn send_to_peer(&self, peer: SocketAddr, data: impl Into<Bytes>) -> Result<()> {
let protocol = self.protocol.read().await;
protocol.send_to_peer(peer, data.into()).await
}
pub async fn on_message<F>(&self, handler: F)
where
F: Fn(SocketAddr, Bytes) + Send + Sync + 'static,
{
let mut protocol = self.protocol.write().await;
protocol.set_message_handler(handler);
}
pub async fn local_addr(&self) -> Option<SocketAddr> {
let protocol = self.protocol.read().await;
protocol.local_addr().await
}
pub async fn peers(&self) -> Vec<SocketAddr> {
let protocol = self.protocol.read().await;
protocol.peer_list().await
}
pub async fn shutdown(&self) -> Result<()> {
let protocol = self.protocol.read().await;
protocol.shutdown().await?;
trace!("Node shut down");
Ok(())
}
}
impl Clone for Node {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
protocol: Arc::clone(&self.protocol),
}
}
}