use async_trait::async_trait;
use libp2prs_core::upgrade::UpgradeInfo;
use libp2prs_core::{Multiaddr, PeerId};
use libp2prs_runtime::task;
use std::error::Error;
use crate::connection::Connection;
use crate::substream::Substream;
use crate::{Control, ProtocolId};
pub trait Notifiee {
fn connected(&mut self, _conn: &mut Connection) {}
fn disconnected(&mut self, _conn: &mut Connection) {}
fn identified(&mut self, _peer: PeerId) {}
fn address_changed(&mut self, _addrs: Vec<Multiaddr>) {}
}
pub trait ProtocolImpl {
fn handler(&self) -> IProtocolHandler;
fn start(self, _swarm: Control) -> Option<task::TaskHandle<()>>
where
Self: Sized,
{
None
}
}
#[async_trait]
pub trait ProtocolHandler: UpgradeInfo + Notifiee {
async fn handle(&mut self, stream: Substream, info: <Self as UpgradeInfo>::Info) -> Result<(), Box<dyn Error>>;
fn box_clone(&self) -> IProtocolHandler;
}
pub type IProtocolHandler = Box<dyn ProtocolHandler<Info = ProtocolId> + Send + Sync>;
impl Clone for IProtocolHandler {
fn clone(&self) -> Self {
self.box_clone()
}
}
pub struct DummyProtocol;
#[allow(clippy::new_without_default)]
impl DummyProtocol {
pub fn new() -> Self {
DummyProtocol
}
}
impl ProtocolImpl for DummyProtocol {
fn handler(&self) -> IProtocolHandler {
Box::new(DummyProtocolHandler)
}
}
#[derive(Clone)]
struct DummyProtocolHandler;
impl UpgradeInfo for DummyProtocolHandler {
type Info = ProtocolId;
fn protocol_info(&self) -> Vec<Self::Info> {
vec![
ProtocolId::from(b"/dummy/1.0.0" as &[u8]),
ProtocolId::from(b"/dummy/2.0.0" as &[u8]),
]
}
}
impl Notifiee for DummyProtocolHandler {}
#[async_trait]
impl ProtocolHandler for DummyProtocolHandler {
async fn handle(&mut self, stream: Substream, info: <Self as UpgradeInfo>::Info) -> Result<(), Box<dyn Error>> {
log::trace!("Dummy Protocol handling inbound {:?} {:?}", stream, info);
Ok(())
}
fn box_clone(&self) -> IProtocolHandler {
Box::new(self.clone())
}
}