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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use crate::message_table::{MsgTableParts, CONNECTION_TYPE_MID, DISCONNECT_TYPE_MID, RESPONSE_TYPE_MID};
use crate::net::{CId, CIdSpec, Config, DeserFn, ErasedNetMsg, NetMsg, Status, Transport};
use crate::tcp::TcpCon;
use crate::udp::UdpCon;
use crate::MId;
use hashbrown::HashMap;
use log::{debug, error, trace};
use std::any::{type_name, Any, TypeId};
use std::collections::VecDeque;
use std::io;
use std::io::ErrorKind::{InvalidData, WouldBlock};
use std::io::{Error, ErrorKind};
use std::net::{SocketAddr, TcpListener};
use std::time::{Duration, Instant};
pub struct Server {
current_cid: CId,
config: Config,
msg_buff: Vec<Vec<ErasedNetMsg>>,
new_cons: Vec<(TcpCon, CId, Instant)>,
disconnected: VecDeque<(CId, Status)>,
listener: TcpListener,
tcp: HashMap<CId, TcpCon>,
udp: UdpCon,
cid_addr: HashMap<CId, SocketAddr>,
addr_cid: HashMap<SocketAddr, CId>,
parts: MsgTableParts,
}
impl Server {
pub fn new(
mut listen_addr: SocketAddr,
parts: MsgTableParts,
config: Config,
) -> io::Result<Self> {
let listener = TcpListener::bind(listen_addr)?;
listen_addr = listener.local_addr().unwrap();
listener.set_nonblocking(true)?;
let udp = UdpCon::new(listen_addr, None, config.max_msg_size)?;
debug!("New server created at {}.", listen_addr);
let mid_count = parts.tid_map.len();
let mut msg_buff = Vec::with_capacity(mid_count);
for _i in 0..mid_count {
msg_buff.push(vec![]);
}
Ok(Server {
current_cid: 0,
config,
msg_buff,
new_cons: vec![],
disconnected: VecDeque::new(),
listener,
tcp: HashMap::new(),
udp,
cid_addr: Default::default(),
addr_cid: Default::default(),
parts,
})
}
pub fn config(&self) -> &Config {
&self.config
}
pub fn disconnect<T: Any + Send + Sync>(&mut self, discon_msg: &T, cid: CId) -> io::Result<()> {
if !self.alive(cid) {
return Err(io::Error::new(ErrorKind::InvalidData, "Invalid CId."));
}
debug!("Disconnecting CId {}", cid);
self.send_to(cid, discon_msg)?;
self.tcp.get_mut(&cid).unwrap().close()?;
self.disconnected.push_back((cid, Status::Closed));
Ok(())
}
pub fn handle_new_con<C: Any + Send + Sync, R: Any + Send + Sync>(
&mut self,
mut hook: impl FnMut(CId, C) -> (bool, R),
) -> bool {
self.start_incoming();
if self.new_cons.len() == 0 { return false; }
let deser_fn = self.parts.deser[CONNECTION_TYPE_MID];
let mut accepted = vec![];
let mut rejected = vec![];
let mut dead = vec![];
for (idx, (con, cid, time)) in self.new_cons.iter_mut().enumerate() {
match Self::handle_con_helper::<C>(deser_fn, con, self.config.timeout, time) {
Ok(c) => {
let (acc, resp) = hook(*cid, c);
if acc {
accepted.push((idx, resp));
} else {
rejected.push((idx, resp));
}
break;
}
Err(e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => {
error!("IO error occurred while handling a pending connection. {}", e);
dead.push(idx);
}
}
}
let handled = accepted.len() > 0 || rejected.len() > 0;
for (idx, resp) in accepted {
let (con, cid, _) = self.new_cons.remove(idx);
self.accept_incoming(cid, con, &resp);
}
for (idx, resp) in rejected {
let (con, cid, _) = self.new_cons.remove(idx);
self.reject_incoming(cid, con, &resp);
}
for idx in dead {
self.new_cons.remove(idx);
}
handled
}
pub fn handle_new_cons<C: Any + Send + Sync, R: Any + Send + Sync>(
&mut self,
mut hook: impl FnMut(CId, C) -> (bool, R),
) -> u32 {
self.start_incoming();
if self.new_cons.len() == 0 { return 0; }
let deser_fn = self.parts.deser[CONNECTION_TYPE_MID];
let mut accepted = vec![];
let mut rejected = vec![];
let mut dead = vec![];
for (idx, (con, cid, time)) in self.new_cons.iter_mut().enumerate() {
match Self::handle_con_helper::<C>(deser_fn, con, self.config.timeout, time) {
Ok(c) => {
let (acc, resp) = hook(*cid, c);
if acc {
accepted.push((idx, resp));
} else {
rejected.push((idx, resp));
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => {
error!("IO error occurred while handling a pending connection. {}", e);
dead.push(idx);
}
}
}
let handled = accepted.len() + rejected.len();
for (idx, resp) in accepted {
let (con, cid, _) = self.new_cons.remove(idx);
self.accept_incoming(cid, con, &resp);
}
for (idx, resp) in rejected {
let (con, cid, _) = self.new_cons.remove(idx);
self.reject_incoming(cid, con, &resp);
}
for idx in dead {
self.new_cons.remove(idx);
}
handled as u32
}
fn handle_con_helper<C: Any + Send + Sync>(
deser_fn: DeserFn,
con: &mut TcpCon,
timeout: Duration,
time: &Instant,
) -> io::Result<C> {
if time.elapsed() > timeout {
return Err(Error::new(
ErrorKind::TimedOut,
"The new connection did not send a connection message in time.",
));
}
let (mid, msg) = con.recv()?;
if mid != CONNECTION_TYPE_MID {
let e_msg = format!("Expected MId {}, got MId {}.", CONNECTION_TYPE_MID, mid);
return Err(Error::new(ErrorKind::InvalidData, e_msg));
}
let con_msg = deser_fn(msg).map_err(|o| {
Error::new(
ErrorKind::InvalidData,
format!("Encountered a deserialization error when handling a new connection. {}", o),
)
})?;
let con_msg = *con_msg.downcast::<C>().unwrap();
Ok(con_msg)
}
fn start_incoming(&mut self,) {
while self.new_cons.len() < self.config.max_con_handle {
if let Ok((stream, _addr)) = self.listener.accept() {
debug!("New connection attempt.");
stream.set_nonblocking(true).unwrap();
let tcp_con = TcpCon::from_stream(stream, self.config.max_msg_size);
let cid = self.new_cid();
self.new_cons.push((tcp_con, cid, Instant::now()));
} else {
break;
}
}
}
fn accept_incoming<R: Any + Send + Sync>(
&mut self,
cid: CId,
con: TcpCon,
resp: &R,
) {
let addr = con.peer_addr().unwrap();
self.add_tcp_con_cid(cid, con);
if let Err(e) = self.send_to(cid, resp) {
error!("IO error occurred while responding to a pending connection. {} at {}", e, addr);
} else {
debug!("Accepted new connection {} at {}.", cid, addr);
}
}
fn reject_incoming<R: Any + Send + Sync>(
&self,
cid: CId,
con: TcpCon,
resp: &R,
) {
let ser = self.parts.ser[RESPONSE_TYPE_MID];
let payload = match ser(resp) {
Ok(p) => p,
Err(e) => {
error!("{}", e);
return;
},
};
let addr = con.peer_addr().unwrap();
if let Err(e) = con.send(RESPONSE_TYPE_MID, &payload) {
error!("IO error occurred while responding to a pending connection. {} at {}", e, addr);
} else {
debug!("Rejected new connection {} at {}.", cid, addr);
}
}
pub fn handle_disconnect(&mut self, mut hook: impl FnMut(CId, Status)) -> bool {
while let Some((cid, status)) = self.disconnected.pop_front() {
if !self.alive(cid) { continue; }
hook(cid, status);
debug!("Removing CId {}", cid);
self.rm_tcp_con(cid).unwrap();
return true;
}
false
}
pub fn handle_disconnects(&mut self, mut hook: impl FnMut(CId, Status)) -> u32 {
let mut i = 0;
while let Some((cid, status)) = self.disconnected.pop_front() {
if !self.alive(cid) { continue; }
hook(cid, status);
debug!("Removing CId {}", cid);
self.rm_tcp_con(cid).unwrap();
i += 1;
}
i
}
fn send_tcp(&self, cid: CId, mid: MId, payload: &[u8]) -> io::Result<()> {
let tcp = match self.tcp.get(&cid) {
Some(tcp) => tcp,
None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
};
tcp.send(mid, payload)
}
fn send_udp(&self, cid: CId, mid: MId, payload: &[u8]) -> io::Result<()> {
let addr = match self.cid_addr.get(&cid) {
Some(addr) => *addr,
None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
};
self.udp.send_to(addr, mid, payload)
}
fn recv_tcp(&mut self, cid: CId) -> io::Result<(MId, ErasedNetMsg)> {
let tcp = match self.tcp.get_mut(&cid) {
Some(tcp) => tcp,
None => return Err(Error::new(ErrorKind::InvalidData, "Invalid CId.")),
};
let (mid, bytes) = tcp.recv()?;
if !self.parts.valid_mid(mid) {
let e_msg = format!(
"TCP: Got a message specifying MId {}, but the maximum MId is {}.",
mid,
self.parts.mid_count()
);
return Err(Error::new(ErrorKind::InvalidData, e_msg));
}
let deser_fn = self.parts.deser[mid];
let msg = deser_fn(bytes)?;
let net_msg = ErasedNetMsg {
cid,
time: None,
msg,
};
Ok((mid, net_msg))
}
fn recv_udp(&mut self) -> io::Result<(MId, ErasedNetMsg)> {
let (from, mid, time, bytes) = self.udp.recv_from()?;
if !self.parts.valid_mid(mid) {
let e_msg = format!(
"TCP: Got a message specifying MId {}, but the maximum MId is {}.",
mid,
self.parts.mid_count()
);
return Err(Error::new(ErrorKind::InvalidData, e_msg));
}
let deser_fn = self.parts.deser[mid];
let msg = deser_fn(bytes)?;
let cid = match self.addr_cid.get(&from) {
Some(&cid) if self.alive(cid) => cid,
_ => {
return Err(Error::new(
ErrorKind::Other,
"Received data from a address that is not connected.",
))
}
};
let net_msg = ErasedNetMsg {
cid,
time: Some(time),
msg,
};
Ok((mid, net_msg))
}
pub fn send_to<T: Any + Send + Sync>(&self, cid: CId, msg: &T) -> io::Result<()> {
let tid = TypeId::of::<T>();
if !self.valid_tid(tid) {
return Err(io::Error::new(
ErrorKind::InvalidData,
"Type not registered.",
));
}
let mid = self.parts.tid_map[&tid];
let transport = self.parts.transports[mid];
let ser_fn = self.parts.ser[mid];
let b = ser_fn(msg)?;
trace!(
"Sending message of MId {}, len {}, to CId {}",
mid,
b.len(),
cid
);
match transport {
Transport::TCP => self.send_tcp(cid, mid, &b[..]),
Transport::UDP => self.send_udp(cid, mid, &b[..]),
}?;
Ok(())
}
pub fn broadcast<T: Any + Send + Sync>(&self, msg: &T) -> io::Result<()> {
for cid in self.cids() {
self.send_to(cid, msg)?;
}
Ok(())
}
pub fn send_spec<T: Any + Send + Sync>(&self, spec: CIdSpec, msg: &T) -> io::Result<()> {
for cid in self.cids().filter(|cid| spec.matches(*cid)) {
self.send_to(cid, msg)?;
}
Ok(())
}
pub fn recv<'s, T: Any + Send + Sync>(&'s self) -> impl Iterator<Item = NetMsg<T>> + 's {
let tid = TypeId::of::<T>();
if !self.parts.valid_tid(tid) {
panic!("Type ({}) not registered.", type_name::<T>());
}
let mid = self.parts.tid_map[&tid];
self.msg_buff[mid]
.iter()
.map(|m| m.to_typed::<T>().unwrap())
}
pub fn try_recv<'s, T: Any + Send + Sync>(
&'s self,
) -> Option<impl Iterator<Item = NetMsg<T>> + 's> {
let tid = TypeId::of::<T>();
let mid = *self.parts.tid_map.get(&tid)?;
Some(
self.msg_buff[mid]
.iter()
.map(|m| m.to_typed::<T>().unwrap()),
)
}
pub fn recv_spec<T: Any + Send + Sync>(
&self,
spec: CIdSpec,
) -> impl Iterator<Item = NetMsg<T>> + '_ {
let tid = TypeId::of::<T>();
if !self.parts.valid_tid(tid) {
panic!("Type ({}) not registered.", type_name::<T>());
}
let mid = self.parts.tid_map[&tid];
self.msg_buff[mid]
.iter()
.filter(move |net_msg| spec.matches(net_msg.cid))
.map(|net_msg| net_msg.to_typed().unwrap())
}
pub fn try_recv_spec<T: Any + Send + Sync>(
&self,
spec: CIdSpec,
) -> Option<impl Iterator<Item = NetMsg<T>> + '_> {
let tid = TypeId::of::<T>();
let mid = *self.parts.tid_map.get(&tid)?;
Some(
self.msg_buff[mid]
.iter()
.filter(move |net_msg| spec.matches(net_msg.cid))
.map(|net_msg| net_msg.to_typed().unwrap()),
)
}
pub fn recv_msgs(&mut self) -> u32 {
let mut i = 0;
for cid in self.cids().collect::<Vec<_>>() {
loop {
let msg = self.recv_tcp(cid);
if self.handle_tcp_msg(&mut i, cid, msg) {
break;
}
}
}
loop {
let msg = self.recv_udp();
if self.handle_udp_msg(&mut i, msg) {
break;
}
}
i
}
fn handle_tcp_msg(
&mut self,
count: &mut u32,
cid: CId,
msg: io::Result<(MId, ErasedNetMsg)>,
) -> bool {
match msg {
Err(e) if e.kind() == WouldBlock => true,
Err(e) => {
error!(
"TCP({}): IO error occurred while receiving data. {}",
cid, e
);
self.disconnected.push_back((cid, Status::Dropped(e)));
true
}
Ok((mid, net_msg)) => {
*count += 1;
if mid == DISCONNECT_TYPE_MID {
debug!("Disconnecting peer {}", cid);
self.disconnected
.push_back((cid, Status::Disconnected(net_msg.msg)));
return true;
}
self.msg_buff[mid].push(net_msg);
false
}
}
}
fn handle_udp_msg(&mut self, count: &mut u32, msg: io::Result<(MId, ErasedNetMsg)>) -> bool {
match msg {
Err(e) if e.kind() == WouldBlock => true,
Err(e) => {
error!("UDP: IO error occurred while receiving data. {}", e);
true
}
Ok((mid, net_msg)) => {
*count += 1;
self.msg_buff[mid].push(net_msg);
false
}
}
}
pub fn clear_msgs(&mut self) {
for buff in self.msg_buff.iter_mut() {
buff.clear();
}
}
pub fn listen_addr(&self) -> SocketAddr {
self.listener.local_addr().unwrap()
}
pub fn cids(&self) -> impl Iterator<Item = CId> + '_ {
self.cid_addr.keys().map(|cid| *cid)
}
pub fn alive(&self, cid: CId) -> bool {
self.cid_addr.contains_key(&cid)
}
pub fn valid_tid(&self, tid: TypeId) -> bool {
self.parts.valid_tid(tid)
}
pub fn connection_count(&self) -> usize {
self.cid_addr.len()
}
pub fn addr_of(&self, cid: CId) -> Option<SocketAddr> {
self.cid_addr.get(&cid).map(|o| *o)
}
pub fn cid_of(&self, addr: SocketAddr) -> Option<CId> {
self.addr_cid.get(&addr).map(|o| *o)
}
fn new_cid(&mut self) -> CId {
self.current_cid += 1;
self.current_cid
}
fn add_tcp_con_cid(&mut self, cid: CId, con: TcpCon) {
let peer_addr = con.peer_addr().unwrap();
self.tcp.insert(cid, con);
self.addr_cid.insert(peer_addr, cid);
self.cid_addr.insert(cid, peer_addr);
}
fn rm_tcp_con(&mut self, cid: CId) -> io::Result<()> {
self.tcp
.remove(&cid)
.ok_or(Error::new(InvalidData, "Invalid CId."))?;
let addr = self.cid_addr.remove(&cid).unwrap();
self.addr_cid.remove(&addr);
Ok(())
}
}