aboutsummaryrefslogtreecommitdiff
path: root/p2p/src/monitor/mod.rs
blob: 4ecb43186b190f7d49fb09957dc5746d200ca483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
mod event;

use std::sync::Arc;

use karyon_core::event::{EventListener, EventSys, EventValue, EventValueTopic};

use karyon_net::Endpoint;

pub(crate) use event::{ConnEvent, DiscvEvent, PPEvent};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{Config, PeerID};

/// Responsible for network and system monitoring.
///
/// It use event emitter to notify the registerd listeners about new events.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
///
/// use smol::Executor;
///
/// use karyon_p2p::{
///     Config, Backend, PeerID, keypair::{KeyPair, KeyPairType}, monitor::ConnectionEvent,
/// };
///
/// async {
///     
///     // Create a new Executor
///     let ex = Arc::new(Executor::new());
///
///     let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
///     let backend = Backend::new(&key_pair, Config::default(), ex.into());
///
///     // Create a new Subscription
///     let monitor =  backend.monitor();
///     
///     let listener = monitor.register::<ConnectionEvent>().await;
///     
///     let new_event = listener.recv().await;
/// };
/// ```
pub struct Monitor {
    event_sys: Arc<EventSys<MonitorTopic>>,
    config: Arc<Config>,
}

impl Monitor {
    /// Creates a new Monitor
    pub(crate) fn new(config: Arc<Config>) -> Self {
        Self {
            event_sys: EventSys::new(),
            config,
        }
    }

    /// Sends a new monitor event to subscribers.
    pub(crate) async fn notify<E: ToEventStruct>(&self, event: E) {
        if self.config.enable_monitor {
            let event = event.to_struct();
            self.event_sys.emit(&event).await
        }
    }

    /// Registers a new event listener for the provided topic.
    pub async fn register<E>(&self) -> EventListener<MonitorTopic, E>
    where
        E: Clone + EventValue + EventValueTopic<Topic = MonitorTopic>,
    {
        self.event_sys.register(&E::topic()).await
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum MonitorTopic {
    Connection,
    PeerPool,
    Discovery,
}

pub(super) trait ToEventStruct: Sized {
    type EventStruct: From<Self> + Clone + EventValueTopic<Topic = MonitorTopic> + EventValue;
    fn to_struct(self) -> Self::EventStruct {
        self.into()
    }
}

impl ToEventStruct for ConnEvent {
    type EventStruct = ConnectionEvent;
}

impl ToEventStruct for PPEvent {
    type EventStruct = PeerPoolEvent;
}

impl ToEventStruct for DiscvEvent {
    type EventStruct = DiscoveryEvent;
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ConnectionEvent {
    pub event: String,
    pub date: i64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub endpoint: Option<Endpoint>,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PeerPoolEvent {
    pub event: String,
    pub date: i64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub peer_id: Option<PeerID>,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DiscoveryEvent {
    pub event: String,
    pub date: i64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub endpoint: Option<Endpoint>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub size: Option<usize>,
}

impl From<ConnEvent> for ConnectionEvent {
    fn from(event: ConnEvent) -> Self {
        let endpoint = event.get_endpoint().cloned();
        Self {
            endpoint,
            event: event.variant_name().to_string(),
            date: get_current_timestamp(),
        }
    }
}

impl From<PPEvent> for PeerPoolEvent {
    fn from(event: PPEvent) -> Self {
        let peer_id = event.get_peer_id().cloned();
        Self {
            peer_id,
            event: event.variant_name().to_string(),
            date: get_current_timestamp(),
        }
    }
}

impl From<DiscvEvent> for DiscoveryEvent {
    fn from(event: DiscvEvent) -> Self {
        let (endpoint, size) = event.get_endpoint_and_size();
        Self {
            endpoint: endpoint.cloned(),
            size,
            event: event.variant_name().to_string(),
            date: get_current_timestamp(),
        }
    }
}

impl EventValue for ConnectionEvent {
    fn id() -> &'static str {
        "ConnectionEvent"
    }
}

impl EventValue for PeerPoolEvent {
    fn id() -> &'static str {
        "PeerPoolEvent"
    }
}

impl EventValue for DiscoveryEvent {
    fn id() -> &'static str {
        "DiscoveryEvent"
    }
}

impl EventValueTopic for ConnectionEvent {
    type Topic = MonitorTopic;
    fn topic() -> Self::Topic {
        MonitorTopic::Connection
    }
}

impl EventValueTopic for PeerPoolEvent {
    type Topic = MonitorTopic;
    fn topic() -> Self::Topic {
        MonitorTopic::PeerPool
    }
}

impl EventValueTopic for DiscoveryEvent {
    type Topic = MonitorTopic;
    fn topic() -> Self::Topic {
        MonitorTopic::Discovery
    }
}

fn get_current_timestamp() -> i64 {
    chrono::Utc::now().timestamp()
}