protocol_registry.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use log::debug;
  19. use smol::{
  20. future::{Boxed, Future},
  21. lock::Mutex,
  22. };
  23. use super::{
  24. super::{channel::ChannelPtr, p2p::P2pPtr, session::SessionBitFlag},
  25. protocol_base::ProtocolBasePtr,
  26. };
  27. type Constructor = Box<dyn Fn(ChannelPtr, P2pPtr) -> Boxed<ProtocolBasePtr> + Send + Sync>;
  28. #[derive(Default)]
  29. pub struct ProtocolRegistry {
  30. constructors: Mutex<Vec<(SessionBitFlag, Constructor)>>,
  31. }
  32. impl ProtocolRegistry {
  33. /// Instantiate a new [`ProtocolRegistry`]
  34. pub fn new() -> Self {
  35. Self::default()
  36. }
  37. /// `add_protocol()?`
  38. pub async fn register<C, F>(&self, session_flags: SessionBitFlag, constructor: C)
  39. where
  40. C: 'static + Fn(ChannelPtr, P2pPtr) -> F + Send + Sync,
  41. F: 'static + Future<Output = ProtocolBasePtr> + Send,
  42. {
  43. let constructor =
  44. move |channel, p2p| Box::pin(constructor(channel, p2p)) as Boxed<ProtocolBasePtr>;
  45. self.constructors.lock().await.push((session_flags, Box::new(constructor)));
  46. }
  47. pub async fn attach(
  48. &self,
  49. selector_id: SessionBitFlag,
  50. channel: ChannelPtr,
  51. p2p: P2pPtr,
  52. ) -> Vec<ProtocolBasePtr> {
  53. let mut protocols = vec![];
  54. for (session_flags, construct) in self.constructors.lock().await.iter() {
  55. // Skip protocols that are not registered for this session
  56. if selector_id & session_flags == 0 {
  57. debug!(target: "net::protocol_registry", "Skipping {selector_id:#b}, {session_flags:#b}");
  58. continue
  59. }
  60. let protocol = construct(channel.clone(), p2p.clone()).await;
  61. debug!(target: "net::protocol_registry", "Attached {}", protocol.name());
  62. protocols.push(protocol);
  63. }
  64. protocols
  65. }
  66. }