protocol_generic.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 std::{clone::Clone, collections::HashMap, sync::Arc};
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use smol::{
  22. channel::{Receiver, Sender},
  23. lock::RwLock,
  24. Executor,
  25. };
  26. use super::{
  27. super::{
  28. channel::ChannelPtr, message::Message, message_publisher::MessageSubscription,
  29. session::SessionBitFlag,
  30. },
  31. protocol_base::{ProtocolBase, ProtocolBasePtr},
  32. protocol_jobs_manager::{ProtocolJobsManager, ProtocolJobsManagerPtr},
  33. P2pPtr,
  34. };
  35. use crate::{system::StoppableTask, Error, Result};
  36. /// Defines generic messages protocol action signal.
  37. #[derive(Debug)]
  38. pub enum ProtocolGenericAction {
  39. /// Broadcast message to rest nodes
  40. Broadcast,
  41. /// Skip message broadcast
  42. Skip,
  43. /// Stop the channel entirely
  44. Stop,
  45. }
  46. pub type ProtocolGenericHandlerPtr<M> = Arc<ProtocolGenericHandler<M>>;
  47. /// Defines a hanlder for generic messages, consisting of
  48. /// a message receiver, action signal senders mapped by each
  49. /// channel ID, and a stoppable task to run the handler in
  50. /// the background.
  51. pub struct ProtocolGenericHandler<M: Message + Clone> {
  52. // Since smol channels close if all senders or all receivers
  53. // get dropped, we will keep one here to remain alive with the
  54. // handler.
  55. sender: Sender<(u32, M)>,
  56. pub receiver: Receiver<(u32, M)>,
  57. senders: RwLock<HashMap<u32, Sender<ProtocolGenericAction>>>,
  58. pub task: Arc<StoppableTask>,
  59. }
  60. impl<M: Message + Clone> ProtocolGenericHandler<M> {
  61. pub async fn new(
  62. p2p: &P2pPtr,
  63. name: &'static str,
  64. session: SessionBitFlag,
  65. ) -> ProtocolGenericHandlerPtr<M> {
  66. let (sender, receiver) = smol::channel::unbounded::<(u32, M)>();
  67. let senders = RwLock::new(HashMap::new());
  68. let task = StoppableTask::new();
  69. let handler = Arc::new(Self { sender, receiver, senders, task });
  70. let _handler = handler.clone();
  71. p2p.protocol_registry()
  72. .register(session, move |channel, p2p| {
  73. let handler = _handler.clone();
  74. async move { ProtocolGeneric::init(channel, name, handler, p2p).await.unwrap() }
  75. })
  76. .await;
  77. handler
  78. }
  79. /// Registers a new channel sender to the handler map.
  80. /// Additionally, looks for stale(closed) channels and prunes then from it.
  81. async fn register_channel_sender(&self, channel: u32, sender: Sender<ProtocolGenericAction>) {
  82. let mut lock = self.senders.write().await;
  83. lock.insert(channel, sender);
  84. let mut stale = vec![];
  85. for (channel, sender) in lock.iter() {
  86. if sender.is_closed() {
  87. stale.push(*channel);
  88. }
  89. }
  90. for channel in stale {
  91. lock.remove(&channel);
  92. }
  93. drop(lock);
  94. }
  95. /// Sends provided protocol generic action to requested channel, if it exists.
  96. pub async fn send_action(&self, channel: u32, action: ProtocolGenericAction) {
  97. debug!(
  98. target: "net::protocol_generic::ProtocolGenericHandler::send_action",
  99. "Sending action {action:?} to channel {channel}..."
  100. );
  101. let mut lock = self.senders.write().await;
  102. let Some(sender) = lock.get(&channel) else {
  103. debug!(
  104. target: "net::protocol_generic::ProtocolGenericHandler::send_action",
  105. "Channel wasn't found."
  106. );
  107. drop(lock);
  108. return
  109. };
  110. if let Err(e) = sender.send(action).await {
  111. debug!(
  112. target: "net::protocol_generic::ProtocolGenericHandler::send_action",
  113. "Channel {channel} send fail: {e}"
  114. );
  115. lock.remove(&channel);
  116. };
  117. drop(lock);
  118. }
  119. }
  120. /// Defines generic messages protocol.
  121. pub struct ProtocolGeneric<M: Message + Clone> {
  122. /// The P2P channel message subcription
  123. msg_sub: MessageSubscription<M>,
  124. /// The generic message smol channel sender
  125. sender: Sender<(u32, M)>,
  126. /// Action signal smol channel receiver
  127. receiver: Receiver<ProtocolGenericAction>,
  128. /// The P2P channel the protocol is serving
  129. channel: ChannelPtr,
  130. /// Pointer to the whole P2P instance
  131. p2p: P2pPtr,
  132. /// Pointer to the protocol job manager
  133. jobsman: ProtocolJobsManagerPtr,
  134. }
  135. impl<M: Message + Clone> ProtocolGeneric<M> {
  136. /// Initialize a new generic protocol.
  137. pub async fn init(
  138. channel: ChannelPtr,
  139. name: &'static str,
  140. handler: ProtocolGenericHandlerPtr<M>,
  141. p2p: P2pPtr,
  142. ) -> Result<ProtocolBasePtr> {
  143. debug!(
  144. target: "net::protocol_generic::init",
  145. "Adding generic protocol for message {name} to the protocol registry"
  146. );
  147. // Add the message dispatcher
  148. let msg_subsystem = channel.message_subsystem();
  149. msg_subsystem.add_dispatch::<M>().await;
  150. // Create the message subscription
  151. let msg_sub = channel.subscribe_msg::<M>().await?;
  152. // Create a new sender channel
  153. let (action_sender, receiver) = smol::channel::bounded(1);
  154. handler.register_channel_sender(channel.info.id, action_sender).await;
  155. Ok(Arc::new(Self {
  156. msg_sub,
  157. sender: handler.sender.clone(),
  158. receiver,
  159. channel: channel.clone(),
  160. p2p,
  161. jobsman: ProtocolJobsManager::new(name, channel),
  162. }))
  163. }
  164. /// Runs the message queue. We listen for the specified structure message,
  165. /// and when one is received, we send it to our smol channel. Afterwards,
  166. /// we wait for an action signal, specifying whether or not we should
  167. /// propagate the message to rest nodes or skip it.
  168. async fn handle_receive_message(self: Arc<Self>) -> Result<()> {
  169. debug!(
  170. target: "net::protocol_generic::handle_receive_message",
  171. "START"
  172. );
  173. let exclude_list = vec![self.channel.address().clone()];
  174. loop {
  175. // Wait for a new message
  176. let msg = match self.msg_sub.receive().await {
  177. Ok(m) => m,
  178. Err(e) => {
  179. debug!(
  180. target: "net::protocol_generic::handle_receive_message",
  181. "[{}] recv fail: {e}", self.jobsman.clone().name()
  182. );
  183. continue
  184. }
  185. };
  186. let msg_copy = (*msg).clone();
  187. // Send the message across the smol channel
  188. if let Err(e) = self.sender.send((self.channel.info.id, msg_copy.clone())).await {
  189. debug!(
  190. target: "net::protocol_generic::handle_receive_message",
  191. "[{}] sending to channel fail: {e}", self.jobsman.clone().name()
  192. );
  193. continue
  194. }
  195. // Wait for action signal
  196. let action = match self.receiver.recv().await {
  197. Ok(a) => a,
  198. Err(e) => {
  199. debug!(
  200. target: "net::protocol_generic::handle_receive_message",
  201. "[{}] action signal recv fail: {e}", self.jobsman.clone().name()
  202. );
  203. continue
  204. }
  205. };
  206. // Handle action signal
  207. match action {
  208. ProtocolGenericAction::Broadcast => {
  209. self.p2p.broadcast_with_exclude(&msg_copy, &exclude_list).await
  210. }
  211. ProtocolGenericAction::Skip => {
  212. debug!(
  213. target: "net::protocol_generic::handle_receive_message",
  214. "[{}] Skip action signal received.", self.jobsman.clone().name()
  215. );
  216. }
  217. ProtocolGenericAction::Stop => {
  218. self.channel.stop().await;
  219. return Err(Error::ChannelStopped)
  220. }
  221. }
  222. }
  223. }
  224. }
  225. #[async_trait]
  226. impl<M: Message + Clone> ProtocolBase for ProtocolGeneric<M> {
  227. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  228. debug!(target: "net::protocol_generic::start", "START");
  229. self.jobsman.clone().start(ex.clone());
  230. self.jobsman.clone().spawn(self.clone().handle_receive_message(), ex).await;
  231. debug!(target: "net::protocol_generic::start", "END");
  232. Ok(())
  233. }
  234. fn name(&self) -> &'static str {
  235. self.jobsman.clone().name()
  236. }
  237. }