aboutsummaryrefslogtreecommitdiff
path: root/p2p/src/monitor.rs
blob: cbbd40c757414730daba6362e35d7ff17f043220 (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
use std::fmt;

use crate::PeerID;

use karyon_core::pubsub::{ArcPublisher, Publisher, Subscription};

use karyon_net::Endpoint;

/// Responsible for network and system monitoring.
///
/// It use pub-sub pattern to notify the subscribers with new events.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
///
/// use smol::Executor;
///
/// use karyon_p2p::{Config, Backend, PeerID, keypair::{KeyPair, KeyPairType}};
///
/// 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 sub =  backend.monitor().await;
///     
///     let event = sub.recv().await;
/// };
/// ```
pub struct Monitor {
    inner: ArcPublisher<MonitorEvent>,
}

impl Monitor {
    /// Creates a new Monitor
    pub(crate) fn new() -> Monitor {
        Self {
            inner: Publisher::new(),
        }
    }

    /// Sends a new monitor event to all subscribers.
    pub async fn notify(&self, event: &MonitorEvent) {
        self.inner.notify(event).await;
    }

    /// Subscribes to listen to new events.
    pub async fn subscribe(&self) -> Subscription<MonitorEvent> {
        self.inner.subscribe().await
    }
}

/// Defines various type of event that can be monitored.
#[derive(Clone, Debug)]
pub enum MonitorEvent {
    Conn(ConnEvent),
    PeerPool(PeerPoolEvent),
    Discovery(DiscoveryEvent),
}

/// Defines connection-related events.
#[derive(Clone, Debug)]
pub enum ConnEvent {
    Connected(Endpoint),
    ConnectRetried(Endpoint),
    ConnectFailed(Endpoint),
    Accepted(Endpoint),
    AcceptFailed,
    Disconnected(Endpoint),
    Listening(Endpoint),
    ListenFailed(Endpoint),
}

/// Defines `PeerPool` events.
#[derive(Clone, Debug)]
pub enum PeerPoolEvent {
    NewPeer(PeerID),
    RemovePeer(PeerID),
}

/// Defines `Discovery` events.
#[derive(Clone, Debug)]
pub enum DiscoveryEvent {
    LookupStarted(Endpoint),
    LookupFailed(Endpoint),
    LookupSucceeded(Endpoint, usize),
    RefreshStarted,
}

impl fmt::Display for MonitorEvent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = match self {
            MonitorEvent::Conn(e) => format!("Connection Event: {e}"),
            MonitorEvent::PeerPool(e) => format!("PeerPool Event: {e}"),
            MonitorEvent::Discovery(e) => format!("Discovery Event: {e}"),
        };
        write!(f, "{}", val)
    }
}

impl fmt::Display for ConnEvent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = match self {
            ConnEvent::Connected(endpoint) => format!("Connected: {endpoint}"),
            ConnEvent::ConnectFailed(endpoint) => format!("ConnectFailed: {endpoint}"),
            ConnEvent::ConnectRetried(endpoint) => format!("ConnectRetried: {endpoint}"),
            ConnEvent::AcceptFailed => "AcceptFailed".to_string(),
            ConnEvent::Accepted(endpoint) => format!("Accepted: {endpoint}"),
            ConnEvent::Disconnected(endpoint) => format!("Disconnected: {endpoint}"),
            ConnEvent::Listening(endpoint) => format!("Listening: {endpoint}"),
            ConnEvent::ListenFailed(endpoint) => format!("ListenFailed: {endpoint}"),
        };
        write!(f, "{}", val)
    }
}

impl fmt::Display for PeerPoolEvent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = match self {
            PeerPoolEvent::NewPeer(pid) => format!("NewPeer: {pid}"),
            PeerPoolEvent::RemovePeer(pid) => format!("RemovePeer: {pid}"),
        };
        write!(f, "{}", val)
    }
}

impl fmt::Display for DiscoveryEvent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = match self {
            DiscoveryEvent::LookupStarted(endpoint) => format!("LookupStarted: {endpoint}"),
            DiscoveryEvent::LookupFailed(endpoint) => format!("LookupFailed: {endpoint}"),
            DiscoveryEvent::LookupSucceeded(endpoint, len) => {
                format!("LookupSucceeded: {endpoint} {len}")
            }
            DiscoveryEvent::RefreshStarted => "RefreshStarted".to_string(),
        };
        write!(f, "{}", val)
    }
}

impl From<ConnEvent> for MonitorEvent {
    fn from(val: ConnEvent) -> Self {
        MonitorEvent::Conn(val)
    }
}

impl From<PeerPoolEvent> for MonitorEvent {
    fn from(val: PeerPoolEvent) -> Self {
        MonitorEvent::PeerPool(val)
    }
}

impl From<DiscoveryEvent> for MonitorEvent {
    fn from(val: DiscoveryEvent) -> Self {
        MonitorEvent::Discovery(val)
    }
}