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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use serde::{Deserialize, Serialize};
use net2::TcpStreamExt;
use rmp_serde;
use rand::{self, Rand};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::sync::{Arc, Mutex, RwLock};
use std::collections::HashMap;
use std::ops::Deref;
use std::fmt::Debug;
use std::hash::Hash;
use std::{fmt, mem};
use std::time::Duration;
use std::thread::{self, JoinHandle};
use std::io::BufWriter;
use super::stats::{StatReader, StatWriter, Stats};
use super::queue::Queue;
pub trait Message: Serialize + Deserialize + Send + Sync + Clone + 'static {}
impl<T> Message for T where T: Serialize + Deserialize + Send + Sync + Clone + 'static {}
pub trait NodeId: Serialize + Deserialize + Send + Sync + Debug + Clone + Eq + Hash + 'static {}
impl<T> NodeId for T where T: Serialize + Deserialize + Send + Sync + Debug + Clone + Eq + Hash + 'static {}
pub trait InitMessage: Serialize + Deserialize + Send + Sync + Clone + Debug + 'static {}
impl<T> InitMessage for T where T: Serialize + Deserialize + Send + Sync + Clone + Debug + 'static {}
#[derive(Debug, PartialEq, Hash, Ord, Eq, PartialOrd)]
pub enum Error<N>
where N: NodeId
{
AlreadyClosed,
OpenError,
ConnectionError,
SendError,
ReadError,
NotConnected(N),
ConnectionAborted,
CloseError,
}
#[derive(PartialEq, Debug)]
pub enum Event<M: Message, N: NodeId, I: InitMessage> {
Message(N, M),
ConnectionRequest(ConnectionRequest<M, N, I>),
Connected(N),
Disconnected(N),
Closing,
Closed,
}
pub struct CloseGuard<M: Message, N: NodeId, I: InitMessage>(Node<M, N, I>);
impl<M: Message, N: NodeId, I: InitMessage> Drop for CloseGuard<M, N, I> {
fn drop(&mut self) {
self.close().expect("Failed to close node");
}
}
impl<M: Message, N: NodeId, I: InitMessage> Deref for CloseGuard<M, N, I> {
type Target = Node<M, N, I>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub struct NodeStats<N: NodeId> {
pub connections: HashMap<N, ConnectionStats>,
}
pub struct NodeInner<M: Message, N: NodeId, I: InitMessage> {
node_id: N,
events: Queue<Event<M, N, I>>,
sockets: Mutex<Vec<(Arc<TcpListener>, JoinHandle<Result<(), Error<N>>>)>>,
connections: RwLock<HashMap<N, Connection<M, N, I>>>,
closed: RwLock<bool>,
connection_timeout: Mutex<Duration>,
stats_halflife_time: Mutex<Duration>,
init_message: Mutex<I>,
}
#[derive(Clone)]
pub struct Node<M: Message, N: NodeId, I: InitMessage>(Arc<NodeInner<M, N, I>>);
impl<M: Message, N: NodeId, I: InitMessage> Deref for Node<M, N, I> {
type Target = NodeInner<M, N, I>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<M: Message, N: NodeId, I: InitMessage> Node<M, N, I> {
pub fn new(node_id: N, init_message: I) -> CloseGuard<M, N, I> {
CloseGuard(Node(Arc::new(NodeInner {
node_id: node_id,
events: Queue::new(),
sockets: Mutex::new(Vec::new()),
connections: RwLock::new(HashMap::new()),
closed: RwLock::new(false),
connection_timeout: Mutex::new(Duration::from_secs(60)),
stats_halflife_time: Mutex::new(Duration::from_secs(60)),
init_message: Mutex::new(init_message),
})))
}
pub fn set_connection_timeout(&self, dur: Duration) {
*self.connection_timeout.lock().expect("Lock poisoned") = dur;
}
pub fn connection_timeout(&self) -> Duration {
*self.connection_timeout.lock().expect("Lock poisoned")
}
pub fn set_stats_halflife_time(&self, dur: Duration) {
*self.stats_halflife_time.lock().expect("Lock poisoned") = dur;
}
pub fn stats_halflife_time(&self) -> Duration {
*self.stats_halflife_time.lock().expect("Lock poisoned")
}
pub fn set_init_message(&self, init: I) {
*self.init_message.lock().expect("Lock poisoned") = init;
}
pub fn init_message(&self) -> I {
self.init_message.lock().expect("Lock poisoned").clone()
}
pub fn listen<A: ToSocketAddrs>(&self, addr: A) -> Result<SocketAddr, Error<N>> {
if *self.closed.read().expect("Lock poisoned") {
return Err(Error::AlreadyClosed);
}
let mut nodes = self.sockets.lock().expect("Lock poisoned");
let node: Arc<TcpListener> = Arc::new(try!(TcpListener::bind(addr).map_err(|_| Error::OpenError)));
let cloned_self = self.clone();
let cloned_node = node.clone();
let used_addr = node.local_addr().expect("Failed to get local address");
let join = thread::spawn(move || cloned_self.run_node(cloned_node));
nodes.push((node, join));
Ok(used_addr)
}
pub fn listen_defaults(&self) -> Result<(), Error<N>> {
try!(self.listen("0.0.0.0:0"));
try!(self.listen("[::0]:0"));
Ok(())
}
pub fn addresses(&self) -> Vec<SocketAddr> {
let mut addrs = Vec::new();
for &(ref sock, _) in
&self.sockets.lock().expect("Lock poisoned") as &Vec<(Arc<TcpListener>, _)> {
addrs.push(sock.local_addr().expect("Failed to obtain address"));
}
addrs
}
pub fn receive(&self) -> Event<M, N, I> {
match self.events.get() {
Some(evt) => evt,
None => Event::Closed,
}
}
#[cfg(feature = "nightly")]
pub fn receive_timeout(&self, timeout: Duration) -> Option<Event<M, N, I>> {
match self.events.get_timeout(timeout) {
Some(Some(evt)) => Some(evt),
Some(None) => Some(Event::Closed),
None => None,
}
}
pub fn node_id(&self) -> N {
self.node_id.clone()
}
fn handle_message(&self, src: N, msg: M) {
self.events.put(Event::Message(src, msg));
}
fn add_connection(&self, con: Connection<M, N, I>) {
let id = con.node_id().clone();
self.connections.write().expect("Lock poisoned").insert(id.clone(), con);
self.events.put(Event::Connected(id));
}
fn del_connection(&self, id: &N) {
self.connections.write().expect("Lock poisoned").remove(id);
self.events.put(Event::Disconnected(id.clone()));
}
fn get_connection(&self, id: &N) -> Option<Connection<M, N, I>> {
self.connections.read().expect("Lock poisoned").get(id).map(|v| v.clone())
}
pub fn is_connected(&self, id: &N) -> bool {
self.connections.read().expect("Lock poisoned").contains_key(id)
}
pub fn connection_count(&self) -> usize {
self.connections.read().expect("Lock poisoned").len()
}
fn get_connections(&self) -> Vec<Connection<M, N, I>> {
self.connections.read().expect("Lock poisoned").values().map(|c| c.clone()).collect()
}
pub fn stats(&self) -> NodeStats<N> {
let mut stats = NodeStats { connections: HashMap::new() };
for (id, con) in self.connections.read().expect("Lock poisoned").iter() {
stats.connections.insert(id.clone(), con.stats());
}
stats
}
fn run_node(&self, socket: Arc<TcpListener>) -> Result<(), Error<N>> {
loop {
let (sock, _) = try!(socket.accept().map_err(|_| Error::ConnectionError));
let req = try!(ConnectionRequest::new(self.clone(), sock));
self.events.put(Event::ConnectionRequest(req));
}
}
pub fn send(&self, dst: &N, msg: &M) -> Result<(), Error<N>> {
if dst == &self.node_id {
self.handle_message(dst.clone(), msg.clone());
return Ok(());
}
match self.get_connection(dst) {
Some(con) => con.send(msg),
None => Err(Error::NotConnected(dst.clone())),
}
}
pub fn connect_request<A: ToSocketAddrs>(&self, addr: A) -> Result<ConnectionRequest<M, N, I>, Error<N>> {
if *self.closed.read().expect("Lock poisoned") {
return Err(Error::AlreadyClosed);
}
let sock = try!(TcpStream::connect(addr).map_err(|_| Error::ConnectionError));
Ok(try!(ConnectionRequest::new(self.clone(), sock)))
}
pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> Result<N, Error<N>> {
let req = try!(self.connect_request(addr));
let id = req.node_id().clone();
req.accept();
Ok(id)
}
pub fn lookup_connection<A: ToSocketAddrs>(&self, addr: A) -> Option<N> {
let lock = self.connections.read().expect("Lock poisoned");
for (id, con) in &lock as &HashMap<N, Connection<M, N, I>> {
let sock_addr = con.get_address();
for a in addr.to_socket_addrs().unwrap() {
if a == sock_addr {
return Some(id.clone());
}
}
}
None
}
fn shutdown_socket(&self, socket: &TcpListener) -> Result<(), Error<N>> {
let socket = unsafe { mem::transmute::<&TcpListener, &TcpStream>(socket) };
socket.shutdown(Shutdown::Both).map_err(|_| Error::CloseError)
}
fn accept_connection(&self, con: Connection<M, N, I>) {
self.add_connection(con.clone());
thread::spawn(move || con.run());
}
pub fn close(&self) -> Result<(), Error<N>> {
self.events.put(Event::Closing);
*self.closed.write().expect("Lock poisoned") = true;
let mut sockets = self.sockets.lock().expect("Lock poisoned");
while let Some((s, j)) = sockets.pop() {
try!(self.shutdown_socket(&s));
j.join().expect("Failed to join").ok();
}
for c in self.get_connections() {
let _ = c.close();
}
self.events.put(Event::Closed);
self.events.close();
Ok(())
}
}
impl<M: Message, N: NodeId, I: InitMessage> Node<M, N, I> where N: Rand {
pub fn with_random_id(init: I) -> CloseGuard<M, N, I> {
Node::new(rand::random::<N>(), init)
}
}
impl<M: Message, N: NodeId> Node<M, N, ()> {
pub fn without_init(node_id: N) -> CloseGuard<M, N, ()> {
Node::new(node_id, ())
}
}
impl<M: Message, N: NodeId> Node<M, N, ()> where N: Rand {
pub fn create_default() -> CloseGuard<M, N, ()> {
Node::new(rand::random::<N>(), ())
}
}
pub struct ConnectionStats {
pub write_total: u64,
pub write_rate: f64,
pub write_idle: Duration,
pub read_total: u64,
pub read_rate: f64,
pub read_idle: Duration,
}
pub struct ConnectionRequest<M: Message, N: NodeId, I: InitMessage> {
node: Node<M, N, I>,
socket: TcpStream,
init: I,
node_id: N,
}
impl<M: Message, N: NodeId, I: InitMessage> PartialEq for ConnectionRequest<M, N, I> {
fn eq(&self, other: &Self) -> bool {
self.node_id == other.node_id &&
self.socket.peer_addr().unwrap() == other.socket.peer_addr().unwrap() &&
self.socket.local_addr().unwrap() == other.socket.local_addr().unwrap()
}
}
impl<M: Message, N: NodeId, I: InitMessage> fmt::Debug for ConnectionRequest<M, N, I> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt,
"ConnectionRequest(from: {:?}, node_id: {:?}, init: {:?})",
self.socket.peer_addr().unwrap(),
self.node_id,
self.init)
}
}
impl<M: Message, N: NodeId, I: InitMessage> ConnectionRequest<M, N, I> {
fn new(node: Node<M, N, I>, mut socket: TcpStream) -> Result<Self, Error<N>> {
try!(socket.set_nodelay(true).map_err(|_| Error::ConnectionError));
try!(socket.set_read_timeout(Some(node.connection_timeout()))
.map_err(|_| Error::ConnectionError));
{
let mut writer = rmp_serde::Serializer::new(&mut socket);
try!((node.init_message(), node.node_id())
.serialize(&mut writer)
.map_err(|_| Error::SendError));
}
let (init, node_id) = {
let mut reader = rmp_serde::Deserializer::new(&socket);
try!(Deserialize::deserialize(&mut reader).map_err(|_| Error::ReadError))
};
Ok(ConnectionRequest {
node: node,
socket: socket,
init: init,
node_id: node_id,
})
}
pub fn init_message(&self) -> &I {
&self.init
}
pub fn node_id(&self) -> &N {
&self.node_id
}
pub fn accept(self) {
let con = Connection::new(self.node.clone(), self.socket, self.node_id);
self.node.accept_connection(con);
}
pub fn reject(self) {
drop(self.socket);
}
}
pub struct ConnectionInner<M: Message, N: NodeId, I: InitMessage> {
node: Node<M, N, I>,
socket: Mutex<TcpStream>,
writer: Mutex<StatWriter<TcpStream>>,
writer_stats: Arc<RwLock<Stats>>,
reader: Mutex<rmp_serde::Deserializer<StatReader<TcpStream>>>,
reader_stats: Arc<RwLock<Stats>>,
node_id: N,
}
#[derive(Clone)]
pub struct Connection<M: Message, N: NodeId, I: InitMessage>(Arc<ConnectionInner<M, N, I>>);
impl<M: Message, N: NodeId, I: InitMessage> Deref for Connection<M, N, I> {
type Target = ConnectionInner<M, N, I>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<M: Message, N: NodeId, I: InitMessage> Connection<M, N, I> {
fn new(node: Node<M, N, I>, socket: TcpStream, node_id: N) -> Self {
let writer = StatWriter::new(socket.try_clone().expect("Failed to clone socket"),
node.stats_halflife_time());
let writer_stats = writer.stats();
let input = StatReader::new(socket.try_clone().expect("Failed to clone socket"),
node.stats_halflife_time());
let reader_stats = input.stats();
let reader = rmp_serde::Deserializer::new(input);
Connection(Arc::new(ConnectionInner {
node: node,
writer: Mutex::new(writer),
writer_stats: writer_stats,
reader: Mutex::new(reader),
reader_stats: reader_stats,
socket: Mutex::new(socket),
node_id: node_id,
}))
}
fn node_id(&self) -> &N {
&self.node_id
}
fn get_address(&self) -> SocketAddr {
self.socket.lock().expect("Lock poisoned").peer_addr().unwrap()
}
fn stats(&self) -> ConnectionStats {
let reader_stats = self.reader_stats.read().expect("Lock poisoned");
let writer_stats = self.writer_stats.read().expect("Lock poisoned");
ConnectionStats {
write_total: writer_stats.total(),
write_rate: writer_stats.rate(),
write_idle: writer_stats.idle_time(),
read_total: reader_stats.total(),
read_rate: reader_stats.rate(),
read_idle: reader_stats.idle_time(),
}
}
fn send(&self, msg: &M) -> Result<(), Error<N>> {
let mut lock = self.writer.lock().expect("Lock poisoned");
let mut bufwriter = BufWriter::new(&mut lock as &mut StatWriter<TcpStream>);
let mut writer = rmp_serde::Serializer::new(&mut bufwriter);
msg.serialize(&mut writer).map_err(|_| Error::SendError)
}
fn run(&self) -> Result<(), Error<N>> {
let res = self.run_inner();
self.node.del_connection(&self.node_id);
res
}
fn run_inner(&self) -> Result<(), Error<N>> {
let mut reader = self.reader.lock().expect("Lock poisoned");
loop {
let msg = try!(M::deserialize(&mut reader as &mut rmp_serde::Deserializer<StatReader<TcpStream>>).map_err(|_| Error::ReadError));
self.node.handle_message(self.node_id.clone(), msg);
}
}
fn close(&self) -> Result<(), Error<N>> {
Ok(try!(self.socket.lock().expect("Lock poisoned").shutdown(Shutdown::Both).map_err(|_| Error::CloseError)))
}
}