ant_node/
event.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use crate::error::{Error, Result};
10
11use ant_evm::AttoTokens;
12use ant_protocol::{NetworkAddress, storage::ChunkAddress};
13use serde::{Deserialize, Serialize};
14use tokio::sync::broadcast;
15
16const NODE_EVENT_CHANNEL_SIZE: usize = 500;
17
18/// Channel where users of the public API can listen to events broadcasted by the node.
19#[derive(Clone)]
20pub struct NodeEventsChannel(broadcast::Sender<NodeEvent>);
21
22/// Type of channel receiver where events are broadcasted to by the node.
23pub type NodeEventsReceiver = broadcast::Receiver<NodeEvent>;
24
25impl Default for NodeEventsChannel {
26    fn default() -> Self {
27        Self(broadcast::channel(NODE_EVENT_CHANNEL_SIZE).0)
28    }
29}
30
31impl NodeEventsChannel {
32    /// Returns a new receiver to listen to the channel.
33    /// Multiple receivers can be actively listening.
34    pub fn subscribe(&self) -> broadcast::Receiver<NodeEvent> {
35        self.0.subscribe()
36    }
37
38    // Broadcast a new event, meant to be a helper only used by the ant-node's internals.
39    pub(crate) fn broadcast(&self, event: NodeEvent) {
40        let event_string = format!("{event:?}");
41        if let Err(err) = self.0.send(event) {
42            debug!(
43                "Error occurred when trying to broadcast a node event ({event_string:?}): {err}"
44            );
45        }
46    }
47
48    /// Returns the number of active receivers
49    pub fn receiver_count(&self) -> usize {
50        self.0.receiver_count()
51    }
52}
53
54/// Type of events broadcasted by the node to the public API.
55#[derive(Clone, Serialize, custom_debug::Debug, Deserialize)]
56pub enum NodeEvent {
57    /// The node has been connected to the network
58    ConnectedToNetwork,
59    /// A Chunk has been stored in local storage
60    ChunkStored(ChunkAddress),
61    /// A new reward was received
62    RewardReceived(AttoTokens, NetworkAddress),
63    /// One of the sub event channel closed and unrecoverable.
64    ChannelClosed,
65    /// Terminates the node
66    TerminateNode(String),
67}
68
69impl NodeEvent {
70    /// Convert NodeEvent to bytes
71    pub fn to_bytes(&self) -> Result<Vec<u8>> {
72        rmp_serde::to_vec(&self).map_err(|_| Error::NodeEventParsingFailed)
73    }
74
75    /// Get NodeEvent from bytes
76    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
77        rmp_serde::from_slice(bytes).map_err(|_| Error::NodeEventParsingFailed)
78    }
79}