protocol_registry.rs 1.5 KB

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