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
|
use std::{sync::Arc, time::Duration};
use async_channel::{Receiver, Sender};
use async_trait::async_trait;
use bincode::{Decode, Encode};
use log::trace;
use rand::{rngs::OsRng, RngCore};
use karyon_core::{
async_runtime::Executor,
async_util::{select, sleep, timeout, Either, TaskGroup, TaskResult},
util::decode,
};
use karyon_net::Error as NetError;
use crate::{
peer::Peer,
protocol::{Protocol, ProtocolEvent, ProtocolID},
version::Version,
Result,
};
const MAX_FAILUERS: u32 = 3;
#[derive(Clone, Debug, Encode, Decode)]
enum PingProtocolMsg {
Ping([u8; 32]),
Pong([u8; 32]),
}
pub struct PingProtocol {
peer: Arc<Peer>,
ping_interval: u64,
ping_timeout: u64,
task_group: TaskGroup,
}
impl PingProtocol {
#[allow(clippy::new_ret_no_self)]
pub fn new(
peer: Arc<Peer>,
ping_interval: u64,
ping_timeout: u64,
executor: Executor,
) -> Arc<dyn Protocol> {
Arc::new(Self {
peer,
ping_interval,
ping_timeout,
task_group: TaskGroup::with_executor(executor),
})
}
async fn recv_loop(&self, pong_chan: Sender<[u8; 32]>) -> Result<()> {
loop {
let event = self.peer.recv::<Self>().await?;
let msg_payload = match event.clone() {
ProtocolEvent::Message(m) => m,
ProtocolEvent::Shutdown => {
break;
}
};
let (msg, _) = decode::<PingProtocolMsg>(&msg_payload)?;
match msg {
PingProtocolMsg::Ping(nonce) => {
trace!("Received Ping message {:?}", nonce);
self.peer
.send(Self::id(), &PingProtocolMsg::Pong(nonce))
.await?;
trace!("Send back Pong message {:?}", nonce);
}
PingProtocolMsg::Pong(nonce) => {
pong_chan.send(nonce).await?;
}
}
}
Ok(())
}
async fn ping_loop(&self, chan: Receiver<[u8; 32]>) -> Result<()> {
let rng = &mut OsRng;
let mut retry = 0;
while retry < MAX_FAILUERS {
sleep(Duration::from_secs(self.ping_interval)).await;
let mut ping_nonce: [u8; 32] = [0; 32];
rng.fill_bytes(&mut ping_nonce);
trace!("Send Ping message {:?}", ping_nonce);
self.peer
.send(Self::id(), &PingProtocolMsg::Ping(ping_nonce))
.await?;
// Wait for Pong message
let d = Duration::from_secs(self.ping_timeout);
let pong_msg = match timeout(d, chan.recv()).await {
Ok(m) => m?,
Err(_) => {
retry += 1;
continue;
}
};
trace!("Received Pong message {:?}", pong_msg);
if pong_msg != ping_nonce {
retry += 1;
continue;
}
retry = 0;
}
Err(NetError::Timeout.into())
}
}
#[async_trait]
impl Protocol for PingProtocol {
async fn start(self: Arc<Self>) -> Result<()> {
trace!("Start Ping protocol");
let stop_signal = async_channel::bounded::<Result<()>>(1);
let (pong_chan, pong_chan_recv) = async_channel::bounded(1);
self.task_group.spawn(
{
let this = self.clone();
async move { this.ping_loop(pong_chan_recv.clone()).await }
},
|res| async move {
if let TaskResult::Completed(result) = res {
let _ = stop_signal.0.send(result).await;
}
},
);
let result = select(self.recv_loop(pong_chan), stop_signal.1.recv()).await;
self.task_group.cancel().await;
match result {
Either::Left(res) => {
trace!("Receive loop stopped {:?}", res);
res
}
Either::Right(res) => {
let res = res?;
trace!("Ping loop stopped {:?}", res);
res
}
}
}
fn version() -> Result<Version> {
"0.1.0".parse()
}
fn id() -> ProtocolID {
"PING".into()
}
}
|