-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathlib.rs
More file actions
257 lines (223 loc) · 7.75 KB
/
lib.rs
File metadata and controls
257 lines (223 loc) · 7.75 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use std::str::FromStr;
use std::time::Duration;
use anyhow::{bail, Context, Result};
use futures::{FutureExt, StreamExt};
use libp2p::swarm::{keep_alive, NetworkBehaviour, SwarmEvent};
use libp2p::{identify, identity, ping, Multiaddr, PeerId};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
mod arch;
use arch::{build_transport, init_logger, swarm_builder, Instant, RedisClient};
pub async fn run_test(
transport: &str,
ip: &str,
is_dialer: bool,
test_timeout_seconds: u64,
redis_addr: &str,
) -> Result<Report> {
init_logger();
let test_timeout = Duration::from_secs(test_timeout_seconds);
let transport = transport.parse().context("Couldn't parse transport")?;
let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
let redis_client = RedisClient::new(redis_addr).context("Could not connect to redis")?;
// Build the transport from the passed ENV var.
let (boxed_transport, local_addr) = build_transport(local_key.clone(), ip, transport)?;
let mut swarm = swarm_builder(
boxed_transport,
Behaviour {
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
// Need to include identify until https://github.com/status-im/nim-libp2p/issues/924 is resolved.
identify: identify::Behaviour::new(identify::Config::new(
"/interop-tests".to_owned(),
local_key.public(),
)),
},
local_peer_id,
)
.build();
log::info!("Running ping test: {}", swarm.local_peer_id());
let mut maybe_id = None;
// See https://github.com/libp2p/rust-libp2p/issues/4071.
if transport == Transport::WebRtcDirect {
maybe_id = Some(swarm.listen_on(local_addr.parse()?)?);
}
// Run a ping interop test. Based on `is_dialer`, either dial the address
// retrieved via `listenAddr` key over the redis connection. Or wait to be pinged and have
// `dialerDone` key ready on the redis connection.
match is_dialer {
true => {
let result: Vec<String> = redis_client
.blpop("listenerAddr", test_timeout.as_secs())
.await?;
let other = result
.get(1)
.context("Failed to wait for listener to be ready")?;
let handshake_start = Instant::now();
swarm.dial(other.parse::<Multiaddr>()?)?;
log::info!("Test instance, dialing multiaddress on: {}.", other);
let rtt = loop {
if let Some(SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
result: Ok(rtt),
..
}))) = swarm.next().await
{
log::info!("Ping successful: {rtt:?}");
break rtt.as_micros() as f32 / 1000.;
}
};
let handshake_plus_ping = handshake_start.elapsed().as_micros() as f32 / 1000.;
Ok(Report {
handshake_plus_one_rtt_millis: handshake_plus_ping,
ping_rtt_millis: rtt,
})
}
false => {
// Listen if we haven't done so already.
// This is a hack until https://github.com/libp2p/rust-libp2p/issues/4071 is fixed at which point we can do this unconditionally here.
let id = match maybe_id {
None => swarm.listen_on(local_addr.parse()?)?,
Some(id) => id,
};
log::info!(
"Test instance, listening for incoming connections on: {:?}.",
local_addr
);
loop {
if let Some(SwarmEvent::NewListenAddr {
listener_id,
address,
}) = swarm.next().await
{
if address.to_string().contains("127.0.0.1") {
continue;
}
if listener_id == id {
let ma = format!("{address}/p2p/{local_peer_id}");
redis_client.rpush("listenerAddr", ma).await?;
break;
}
}
}
// Drive Swarm while we await for `dialerDone` to be ready.
futures::future::select(
async move {
loop {
swarm.next().await;
}
}
.boxed(),
arch::sleep(test_timeout),
)
.await;
// The loop never ends so if we get here, we hit the timeout.
bail!("Test should have been killed by the test runner!");
}
}
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub async fn run_test_wasm(
transport: &str,
ip: &str,
is_dialer: bool,
test_timeout_secs: u64,
base_url: &str,
) -> Result<(), JsValue> {
let result = run_test(transport, ip, is_dialer, test_timeout_secs, base_url).await;
log::info!("Sending test result: {result:?}");
reqwest::Client::new()
.post(&format!("http://{}/results", base_url))
.json(&result.map_err(|e| e.to_string()))
.send()
.await?
.error_for_status()
.map_err(|e| format!("Sending test result failed: {e}"))?;
Ok(())
}
/// A request to redis proxy that will pop the value from the list
/// and will wait for it being inserted until a timeout is reached.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct BlpopRequest {
pub key: String,
pub timeout: u64,
}
/// A report generated by the test
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Report {
#[serde(rename = "handshakePlusOneRTTMillis")]
handshake_plus_one_rtt_millis: f32,
#[serde(rename = "pingRTTMilllis")]
ping_rtt_millis: f32,
}
/// Supported transports by rust-libp2p.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Transport {
Tcp,
QuicV1,
WebRtcDirect,
Ws,
Webtransport,
}
impl FromStr for Transport {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(match s {
"tcp" => Self::Tcp,
"quic-v1" => Self::QuicV1,
"webrtc-direct" => Self::WebRtcDirect,
"ws" => Self::Ws,
"webtransport" => Self::Webtransport,
other => bail!("unknown transport {other}"),
})
}
}
/// Supported stream multiplexers by rust-libp2p.
#[derive(Clone, Debug)]
pub enum Muxer {
Mplex,
Yamux,
}
impl FromStr for Muxer {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(match s {
"mplex" => Self::Mplex,
"yamux" => Self::Yamux,
other => bail!("unknown muxer {other}"),
})
}
}
/// Supported security protocols by rust-libp2p.
#[derive(Clone, Debug)]
pub enum SecProtocol {
Noise,
Tls,
}
impl FromStr for SecProtocol {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(match s {
"noise" => Self::Noise,
"tls" => Self::Tls,
other => bail!("unknown security protocol {other}"),
})
}
}
#[derive(NetworkBehaviour)]
struct Behaviour {
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
identify: identify::Behaviour,
}
/// Helper function to get a ENV variable into an test parameter like `Transport`.
pub fn from_env<T>(env_var: &str) -> Result<T>
where
T: FromStr<Err = anyhow::Error>,
{
std::env::var(env_var)
.with_context(|| format!("{env_var} environment variable is not set"))?
.parse()
.map_err(Into::into)
}