protocol_registry.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use async_std::sync::Mutex;
  2. use futures::future::BoxFuture;
  3. use std::future::Future;
  4. use log::debug;
  5. use crate::net::{session::SessionBitflag, ChannelPtr, P2pPtr, protocol::ProtocolBasePtr};
  6. type Constructor = Box<
  7. dyn Fn(ChannelPtr, P2pPtr) -> BoxFuture<'static, ProtocolBasePtr>
  8. + Send
  9. + Sync,
  10. >;
  11. pub struct ProtocolRegistry {
  12. protocol_constructors: Mutex<Vec<(SessionBitflag, Constructor)>>,
  13. }
  14. impl ProtocolRegistry {
  15. pub fn new() -> Self {
  16. Self { protocol_constructors: Mutex::new(Vec::new()) }
  17. }
  18. // add_protocol()?
  19. pub async fn register<C, F>(&self, session_flags: SessionBitflag, constructor: C)
  20. where
  21. C: 'static + Fn(ChannelPtr, P2pPtr) -> F + Send + Sync,
  22. F: 'static + Future<Output = ProtocolBasePtr> + Send,
  23. {
  24. let constructor = move |channel, p2p| {
  25. Box::pin(constructor(channel, p2p))
  26. as BoxFuture<'static, ProtocolBasePtr>
  27. };
  28. self.protocol_constructors.lock().await.push((session_flags, Box::new(constructor)));
  29. }
  30. pub async fn attach(
  31. &self,
  32. selector_id: SessionBitflag,
  33. channel: ChannelPtr,
  34. p2p: P2pPtr,
  35. ) -> Vec<ProtocolBasePtr> {
  36. let mut protocols: Vec<ProtocolBasePtr> = Vec::new();
  37. for (session_flags, construct) in self.protocol_constructors.lock().await.iter() {
  38. // Skip protocols that are not registered for this session
  39. if selector_id & session_flags == 0 {
  40. continue
  41. }
  42. let protocol: ProtocolBasePtr =
  43. construct(channel.clone(), p2p.clone()).await;
  44. debug!(target: "net", "Attached {}", protocol.name());
  45. protocols.push(protocol)
  46. }
  47. protocols
  48. }
  49. }