protocol_bar.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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::sync::Arc;
  19. use async_trait::async_trait;
  20. use log::{debug, error, info};
  21. use tinyjson::JsonValue;
  22. use darkfi::{
  23. impl_p2p_message,
  24. net::{
  25. metering::MeteringConfiguration,
  26. protocol::protocol_generic::{
  27. ProtocolGenericAction, ProtocolGenericHandler, ProtocolGenericHandlerPtr,
  28. },
  29. session::SESSION_DEFAULT,
  30. Message, P2pPtr,
  31. },
  32. rpc::jsonrpc::JsonSubscriber,
  33. system::ExecutorPtr,
  34. util::time::NanoTimestamp,
  35. Error, Result,
  36. };
  37. use darkfi_serial::{SerialDecodable, SerialEncodable};
  38. /// Structure represening a bar message
  39. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  40. pub struct Bar {
  41. /// Bar message
  42. pub message: String,
  43. }
  44. impl_p2p_message!(
  45. Bar,
  46. "bar",
  47. 0,
  48. 0,
  49. MeteringConfiguration { threshold: 0, sleep_step: 0, expiry_time: NanoTimestamp::from_secs(0) }
  50. );
  51. /// Atomic pointer to the `ProtocolBar` handler.
  52. pub type ProtocolBarHandlerPtr = Arc<ProtocolBarHandler>;
  53. /// Handler managing `ProtocolBar` messages, over a generic P2P protocol.
  54. pub struct ProtocolBarHandler {
  55. /// The generic handler for `ProtocolBar` messages.
  56. handler: ProtocolGenericHandlerPtr<Bar, Bar>,
  57. }
  58. impl ProtocolBarHandler {
  59. /// Initialize a generic prototocol handler for `ProtocolBar` messages
  60. /// and registers it to the provided P2P network, using the default session flag.
  61. pub async fn init(p2p: &P2pPtr) -> ProtocolBarHandlerPtr {
  62. debug!(
  63. target: "damd::proto::protocol_bar::init",
  64. "Adding ProtocolBar to the protocol registry"
  65. );
  66. let handler = ProtocolGenericHandler::new(p2p, "ProtocolBar", SESSION_DEFAULT).await;
  67. Arc::new(Self { handler })
  68. }
  69. /// Start the `ProtocolBar` background task.
  70. pub async fn start(&self, executor: &ExecutorPtr, subscriber: JsonSubscriber) -> Result<()> {
  71. debug!(
  72. target: "damd::proto::protocol_bar::start",
  73. "Starting ProtocolBar handler task..."
  74. );
  75. self.handler.task.clone().start(
  76. handle_receive_bar(self.handler.clone(), subscriber),
  77. |res| async move {
  78. match res {
  79. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  80. Err(e) => error!(target: "damd::proto::protocol_bar::start", "Failed starting ProtocolBar handler task: {e}"),
  81. }
  82. },
  83. Error::DetachedTaskStopped,
  84. executor.clone(),
  85. );
  86. debug!(
  87. target: "damd::proto::protocol_bar::start",
  88. "ProtocolBar handler task started!"
  89. );
  90. Ok(())
  91. }
  92. /// Stop the `ProtocolBar` background task.
  93. pub async fn stop(&self) {
  94. debug!(target: "damd::proto::protocol_bar::stop", "Terminating ProtocolBar handler task...");
  95. self.handler.task.stop().await;
  96. debug!(target: "damd::proto::protocol_bar::stop", "ProtocolBar handler task terminated!");
  97. }
  98. }
  99. /// Background handler function for ProtocolBar.
  100. async fn handle_receive_bar(
  101. handler: ProtocolGenericHandlerPtr<Bar, Bar>,
  102. subscriber: JsonSubscriber,
  103. ) -> Result<()> {
  104. debug!(target: "damd::proto::protocol_bar::handle_receive_bar", "START");
  105. loop {
  106. // Wait for a new bar message
  107. let (channel, bar) = match handler.receiver.recv().await {
  108. Ok(r) => r,
  109. Err(e) => {
  110. debug!(
  111. target: "damd::proto::protocol_bar::handle_receive_bar",
  112. "recv fail: {e}"
  113. );
  114. continue
  115. }
  116. };
  117. let notification = format!("Received bar message from {channel}: {}", bar.message);
  118. info!(target: "damd::proto::protocol_bar::handle_receive_bar", "{notification}");
  119. // Notify subscriber
  120. subscriber.notify(vec![JsonValue::String(notification)].into()).await;
  121. // Signal handler to broadcast the message to rest nodes
  122. handler.send_action(channel, ProtocolGenericAction::Broadcast).await;
  123. }
  124. }