-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
318 lines (261 loc) · 10.3 KB
/
main.rs
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::node::{Node, State};
use clap::Parser;
use lib::{command::ClientCommand, network::Receiver};
use log::{info, warn};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use tokio::task::JoinHandle;
mod command_ext;
mod node;
pub const CHANNEL_CAPACITY: usize = 1_000;
#[derive(Parser)]
#[clap(author, version, about)]
struct Cli {
/// The network port of the node where to send txs.
#[clap(short, long, value_parser, value_name = "UINT", default_value_t = 6100)]
client_port: u16,
#[clap(short, long, value_parser, value_name = "UINT", default_value_t = 6200)]
network_port: u16,
/// The network address of the node where to send txs.
#[clap(short, long, value_parser, value_name = "UINT", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
address: IpAddr,
/// If running as a replica, this is the address of the primary
#[clap(
long,
value_parser,
value_name = "ADDR",
use_value_delimiter = true,
value_delimiter = ' '
)]
peers: Vec<SocketAddr>,
/// If view-change mechanism is enabled, you can set the delta time (in ms)
#[clap(short, long, value_parser, value_name = "UINT")]
view_change_delta_ms: Option<u16>,
/// The key/value store command to execute.
#[clap(subcommand)]
command: Option<ClientCommand>,
}
#[tokio::main(flavor = "multi_thread")]
async fn main() {
let cli = Cli::parse();
info!(
"Node socket for client request {}:{}, network request: {}:{}",
cli.address, cli.client_port, cli.address, cli.network_port
);
simple_logger::SimpleLogger::new().env().init().unwrap();
let network_address = SocketAddr::new(cli.address, cli.client_port);
let client_address = SocketAddr::new(cli.address, cli.network_port);
// because the Client application does not work with this (sends a ClientCommand not wrapped in Command())
// if the CLI has a command, this works as a client
if let Some(cmd) = cli.command {
return send_command(client_address, cmd).await;
}
let node = Node::new(
cli.peers,
&format!(".db_{}", network_address.port()),
network_address,
cli.view_change_delta_ms,
);
info!(
"Node: Running on {}. Primary = {}...",
node.socket_address,
matches!(node.get_state(), State::Primary)
);
let (_, network_handle, _) = spawn_node_tasks(network_address, client_address, node).await;
network_handle.await.unwrap();
}
async fn spawn_node_tasks(
network_address: SocketAddr,
client_address: SocketAddr,
mut node: Node,
) -> (JoinHandle<()>, JoinHandle<()>, JoinHandle<()>) {
// listen for peer network tcp connections
let (network_tcp_receiver, network_channel_receiver) = Receiver::new(network_address);
let network_handle = tokio::spawn(async move {
network_tcp_receiver.run().await;
});
// listen for client command tcp connections
let (client_tcp_receiver, client_channel_receiver) = Receiver::new(client_address);
let client_handle = tokio::spawn(async move {
client_tcp_receiver.run().await;
});
// run a task to manage the blockchain node state, listening for messages from client and network
let node_handle = tokio::spawn(async move {
node.run(network_channel_receiver, client_channel_receiver)
.await;
});
(node_handle, network_handle, client_handle)
}
async fn send_command(socket_addr: SocketAddr, command: ClientCommand) {
// using a reliable sender to get a response back
match command.send_to(socket_addr).await {
Ok(Some(value)) => info!("{}", value),
Ok(None) => info!("null"),
Err(error) => warn!("ERROR {}", error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use lib::command::ClientCommand;
use std::fs;
use tokio::time::{sleep, Duration};
#[ctor::ctor]
fn init() {
simple_logger::SimpleLogger::new().env().init().unwrap();
fs::remove_dir_all(db_path("")).unwrap_or_default();
}
fn db_path(suffix: &str) -> String {
format!(".db_test/{suffix}")
}
#[tokio::test(flavor = "multi_thread")]
async fn test_only_primary_server() {
let network_address_primary: SocketAddr = "127.0.0.1:6380".parse().unwrap();
let client_address_primary: SocketAddr = "127.0.0.1:6381".parse().unwrap();
fs::remove_dir_all(".db_test_primary1").unwrap_or_default();
let primary = node::Node::new(
vec![network_address_primary],
&db_path("primary"),
network_address_primary,
Some(100),
);
spawn_node_tasks(network_address_primary, client_address_primary, primary).await;
sleep(Duration::from_millis(10)).await;
let reply = ClientCommand::Get {
key: "k1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
assert!(reply.is_none());
let _ = ClientCommand::Set {
key: "k1".to_string(),
value: "v1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
sleep(Duration::from_millis(10)).await;
let reply = ClientCommand::Get {
key: "k1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
assert!(reply.is_some());
assert_eq!("v1".to_string(), reply.unwrap());
}
#[tokio::test()]
async fn test_replicated_server() {
fs::remove_dir_all(".db_test_primary2").unwrap_or_default();
fs::remove_dir_all(".db_test_backup2").unwrap_or_default();
let network_address_primary: SocketAddr = "127.0.0.1:6480".parse().unwrap();
let client_address_primary: SocketAddr = "127.0.0.1:6481".parse().unwrap();
let network_address_replica: SocketAddr = "127.0.0.1:6580".parse().unwrap();
let client_address_replica: SocketAddr = "127.0.0.1:6581".parse().unwrap();
let backup = node::Node::new(
vec![network_address_primary, network_address_replica],
&db_path("backup2"),
network_address_replica,
Some(100),
);
let primary = node::Node::new(
vec![network_address_primary, network_address_replica],
&db_path("primary2"),
network_address_primary,
Some(100),
);
spawn_node_tasks(network_address_primary, client_address_primary, primary).await;
spawn_node_tasks(network_address_replica, client_address_replica, backup).await;
sleep(Duration::from_millis(10)).await;
// get null value
let reply = ClientCommand::Get {
key: "k1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
assert!(reply.is_none());
// set a value on primary
let _ = ClientCommand::Set {
key: "k1".to_string(),
value: "v1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
sleep(Duration::from_millis(100)).await;
// get value on primary
let reply = ClientCommand::Get {
key: "k1".to_string(),
}
.send_to(client_address_primary)
.await
.unwrap();
assert!(reply.is_some());
assert_eq!("v1".to_string(), reply.unwrap());
sleep(Duration::from_millis(100)).await;
// get value on replica to make sure it was replicated
let reply = ClientCommand::Get {
key: "k1".to_string(),
}
.send_to(client_address_replica)
.await
.unwrap();
assert!(reply.is_some());
assert_eq!("v1".to_string(), reply.unwrap());
}
#[tokio::test()]
async fn test_view_change() {
let network_address_primary: SocketAddr = "127.0.0.1:10000".parse().unwrap();
let client_address_primary: SocketAddr = "127.0.0.1:10001".parse().unwrap();
let network_address_replica: SocketAddr = "127.0.0.1:10002".parse().unwrap();
let client_address_replica: SocketAddr = "127.0.0.1:10003".parse().unwrap();
let backup = Box::new(node::Node::new(
vec![network_address_primary, network_address_replica],
&db_path("backup3"),
network_address_replica,
Some(100),
));
let primary = Box::new(node::Node::new(
vec![network_address_primary, network_address_replica],
&db_path("primary3"),
network_address_primary,
Some(100),
));
let backup_raw = &*backup as *const Node;
let primary_raw = &*primary as *const Node;
spawn_node_tasks_test(network_address_primary, client_address_primary, primary).await;
spawn_node_tasks_test(network_address_replica, client_address_replica, backup).await;
sleep(Duration::from_millis(1500)).await;
unsafe {
// because ownership moves to spawn_node_tasks_test(), we have to deref the raw pointers
// which will have the same memory location because they were boxed
assert!((*backup_raw).current_view > 0);
assert!((*primary_raw).current_view > 0);
}
}
// in order for the `move` not to change Node's memory location, this function takes a Box<Node> instead of a <Node>
async fn spawn_node_tasks_test(
network_address: SocketAddr,
client_address: SocketAddr,
mut node: Box<Node>,
) -> (JoinHandle<()>, JoinHandle<()>, JoinHandle<()>) {
// listen for peer network tcp connections
let (network_tcp_receiver, network_channel_receiver) = Receiver::new(network_address);
let network_handle = tokio::spawn(async move {
network_tcp_receiver.run().await;
});
// listen for client command tcp connections
let (client_tcp_receiver, client_channel_receiver) = Receiver::new(client_address);
let client_handle = tokio::spawn(async move {
client_tcp_receiver.run().await;
});
// run a task to manage the blockchain node state, listening for messages from client and network
let node_handle = tokio::spawn(async move {
(*node)
.run(network_channel_receiver, client_channel_receiver)
.await;
});
(node_handle, network_handle, client_handle)
}
}