protocol_registry.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. use async_std::sync::Mutex;
  2. use futures::future::BoxFuture;
  3. use std::future::Future;
  4. use super::protocol_base::ProtocolBase;
  5. use std::sync::Arc;
  6. //use super::protocol_base::ProtocolBasePtr;
  7. use crate::net::{ChannelPtr, P2pPtr};
  8. type ProtocolBasePtr = Arc<dyn ProtocolBase + Send + Sync>;
  9. type Constructor = Box<
  10. dyn Fn(ChannelPtr, P2pPtr) -> BoxFuture<'static, Arc<dyn ProtocolBase + Send + Sync>>
  11. + Send
  12. + Sync,
  13. >;
  14. pub struct ProtocolRegistry {
  15. protocol_constructors: Mutex<Vec<Constructor>>,
  16. }
  17. impl ProtocolRegistry {
  18. pub fn new() -> Self {
  19. Self { protocol_constructors: Mutex::new(Vec::new()) }
  20. }
  21. // add_protocol()?
  22. pub async fn register<C, F>(&self, constructor: C)
  23. where
  24. C: 'static + Fn(ChannelPtr, P2pPtr) -> F + Send + Sync,
  25. F: 'static + Future<Output = Arc<dyn ProtocolBase + Send + Sync>> + Send,
  26. {
  27. let constructor = move |channel, p2p| {
  28. Box::pin(constructor(channel, p2p)) as BoxFuture<'static, Arc<dyn ProtocolBase + Send + Sync>>
  29. };
  30. self.protocol_constructors.lock().await.push(Box::new(constructor));
  31. }
  32. pub async fn attach(&self, channel: ChannelPtr, p2p: P2pPtr) -> Vec<Arc<dyn ProtocolBase + Send + Sync>> {
  33. let mut protocols: Vec<Arc<dyn ProtocolBase + Send + Sync>> = Vec::new();
  34. for construct in self.protocol_constructors.lock().await.iter() {
  35. let protocol: Arc<dyn ProtocolBase + Send + Sync> =
  36. construct(channel.clone(), p2p.clone()).await;
  37. protocols.push(protocol)
  38. }
  39. protocols
  40. }
  41. }