LCOV - code coverage report
Current view: top level - libs/desim/src - network.rs (source / functions) Coverage Total Hit
Test: 465a86b0c1fda0069b3e0f6c1c126e6b635a1f72.info Lines: 92.9 % 269 250
Test Date: 2024-06-25 15:47:26 Functions: 95.8 % 24 23

            Line data    Source code
       1              : use std::{
       2              :     cmp::Ordering,
       3              :     collections::{BinaryHeap, VecDeque},
       4              :     fmt::{self, Debug},
       5              :     ops::DerefMut,
       6              :     sync::{mpsc, Arc},
       7              : };
       8              : 
       9              : use parking_lot::{
      10              :     lock_api::{MappedMutexGuard, MutexGuard},
      11              :     Mutex, RawMutex,
      12              : };
      13              : use rand::rngs::StdRng;
      14              : use tracing::debug;
      15              : 
      16              : use crate::{
      17              :     executor::{self, ThreadContext},
      18              :     options::NetworkOptions,
      19              :     proto::NetEvent,
      20              :     proto::NodeEvent,
      21              : };
      22              : 
      23              : use super::{chan::Chan, proto::AnyMessage};
      24              : 
      25              : pub struct NetworkTask {
      26              :     options: Arc<NetworkOptions>,
      27              :     connections: Mutex<Vec<VirtualConnection>>,
      28              :     /// min-heap of connections having something to deliver.
      29              :     events: Mutex<BinaryHeap<Event>>,
      30              :     task_context: Arc<ThreadContext>,
      31              : }
      32              : 
      33              : impl NetworkTask {
      34         4056 :     pub fn start_new(options: Arc<NetworkOptions>, tx: mpsc::Sender<Arc<NetworkTask>>) {
      35         4056 :         let ctx = executor::get_thread_ctx();
      36         4056 :         let task = Arc::new(Self {
      37         4056 :             options,
      38         4056 :             connections: Mutex::new(Vec::new()),
      39         4056 :             events: Mutex::new(BinaryHeap::new()),
      40         4056 :             task_context: ctx,
      41         4056 :         });
      42         4056 : 
      43         4056 :         // send the task upstream
      44         4056 :         tx.send(task.clone()).unwrap();
      45         4056 : 
      46         4056 :         // start the task
      47         4056 :         task.start();
      48         4056 :     }
      49              : 
      50       271413 :     pub fn start_new_connection(self: &Arc<Self>, rng: StdRng, dst_accept: Chan<NodeEvent>) -> TCP {
      51       271413 :         let now = executor::now();
      52       271413 :         let connection_id = self.connections.lock().len();
      53       271413 : 
      54       271413 :         let vc = VirtualConnection {
      55       271413 :             connection_id,
      56       271413 :             dst_accept,
      57       271413 :             dst_sockets: [Chan::new(), Chan::new()],
      58       271413 :             state: Mutex::new(ConnectionState {
      59       271413 :                 buffers: [NetworkBuffer::new(None), NetworkBuffer::new(Some(now))],
      60       271413 :                 rng,
      61       271413 :             }),
      62       271413 :         };
      63       271413 :         vc.schedule_timeout(self);
      64       271413 :         vc.send_connect(self);
      65       271413 : 
      66       271413 :         let recv_chan = vc.dst_sockets[0].clone();
      67       271413 :         self.connections.lock().push(vc);
      68       271413 : 
      69       271413 :         TCP {
      70       271413 :             net: self.clone(),
      71       271413 :             conn_id: connection_id,
      72       271413 :             dir: 0,
      73       271413 :             recv_chan,
      74       271413 :         }
      75       271413 :     }
      76              : }
      77              : 
      78              : // private functions
      79              : impl NetworkTask {
      80              :     /// Schedule to wakeup network task (self) `after_ms` later to deliver
      81              :     /// messages of connection `id`.
      82      1392679 :     fn schedule(&self, id: usize, after_ms: u64) {
      83      1392679 :         self.events.lock().push(Event {
      84      1392679 :             time: executor::now() + after_ms,
      85      1392679 :             conn_id: id,
      86      1392679 :         });
      87      1392679 :         self.task_context.schedule_wakeup(after_ms);
      88      1392679 :     }
      89              : 
      90              :     /// Get locked connection `id`.
      91      1855422 :     fn get(&self, id: usize) -> MappedMutexGuard<'_, RawMutex, VirtualConnection> {
      92      1855422 :         MutexGuard::map(self.connections.lock(), |connections| {
      93      1855422 :             connections.get_mut(id).unwrap()
      94      1855422 :         })
      95      1855422 :     }
      96              : 
      97      1309451 :     fn collect_pending_events(&self, now: u64, vec: &mut Vec<Event>) {
      98      1309451 :         vec.clear();
      99      1309451 :         let mut events = self.events.lock();
     100      2614848 :         while let Some(event) = events.peek() {
     101      2598163 :             if event.time > now {
     102      1292766 :                 break;
     103      1305397 :             }
     104      1305397 :             let event = events.pop().unwrap();
     105      1305397 :             vec.push(event);
     106              :         }
     107      1309451 :     }
     108              : 
     109         4056 :     fn start(self: &Arc<Self>) {
     110         4056 :         debug!("started network task");
     111              : 
     112         4056 :         let mut events = Vec::new();
     113              :         loop {
     114      1313507 :             let now = executor::now();
     115      1313507 :             self.collect_pending_events(now, &mut events);
     116              : 
     117      1313507 :             for event in events.drain(..) {
     118      1305397 :                 let conn = self.get(event.conn_id);
     119      1305397 :                 conn.process(self);
     120      1305397 :             }
     121              : 
     122              :             // block until wakeup
     123      1309451 :             executor::yield_me(-1);
     124              :         }
     125              :     }
     126              : }
     127              : 
     128              : // 0 - from node(0) to node(1)
     129              : // 1 - from node(1) to node(0)
     130              : type MessageDirection = u8;
     131              : 
     132         2570 : fn sender_str(dir: MessageDirection) -> &'static str {
     133         2570 :     match dir {
     134          422 :         0 => "client",
     135         2148 :         1 => "server",
     136            0 :         _ => unreachable!(),
     137              :     }
     138         2570 : }
     139              : 
     140          694 : fn receiver_str(dir: MessageDirection) -> &'static str {
     141          694 :     match dir {
     142          316 :         0 => "server",
     143          378 :         1 => "client",
     144            0 :         _ => unreachable!(),
     145              :     }
     146          694 : }
     147              : 
     148              : /// Virtual connection between two nodes.
     149              : /// Node 0 is the creator of the connection (client),
     150              : /// and node 1 is the acceptor (server).
     151              : struct VirtualConnection {
     152              :     connection_id: usize,
     153              :     /// one-off chan, used to deliver Accept message to dst
     154              :     dst_accept: Chan<NodeEvent>,
     155              :     /// message sinks
     156              :     dst_sockets: [Chan<NetEvent>; 2],
     157              :     state: Mutex<ConnectionState>,
     158              : }
     159              : 
     160              : struct ConnectionState {
     161              :     buffers: [NetworkBuffer; 2],
     162              :     rng: StdRng,
     163              : }
     164              : 
     165              : impl VirtualConnection {
     166              :     /// Notify the future about the possible timeout.
     167       800183 :     fn schedule_timeout(&self, net: &NetworkTask) {
     168       800183 :         if let Some(timeout) = net.options.keepalive_timeout {
     169       800183 :             net.schedule(self.connection_id, timeout);
     170       800183 :         }
     171       800183 :     }
     172              : 
     173              :     /// Send the handshake (Accept) to the server.
     174       271413 :     fn send_connect(&self, net: &NetworkTask) {
     175       271413 :         let now = executor::now();
     176       271413 :         let mut state = self.state.lock();
     177       271413 :         let delay = net.options.connect_delay.delay(&mut state.rng);
     178       271413 :         let buffer = &mut state.buffers[0];
     179       271413 :         assert!(buffer.buf.is_empty());
     180       271413 :         assert!(!buffer.recv_closed);
     181       271413 :         assert!(!buffer.send_closed);
     182       271413 :         assert!(buffer.last_recv.is_none());
     183              : 
     184       271413 :         let delay = if let Some(ms) = delay {
     185       211287 :             ms
     186              :         } else {
     187        60126 :             debug!("NET: TCP #{} dropped connect", self.connection_id);
     188        60126 :             buffer.send_closed = true;
     189        60126 :             return;
     190              :         };
     191              : 
     192              :         // Send a message into the future.
     193       211287 :         buffer
     194       211287 :             .buf
     195       211287 :             .push_back((now + delay, AnyMessage::InternalConnect));
     196       211287 :         net.schedule(self.connection_id, delay);
     197       271413 :     }
     198              : 
     199              :     /// Transmit some of the messages from the buffer to the nodes.
     200      1305397 :     fn process(&self, net: &Arc<NetworkTask>) {
     201      1305397 :         let now = executor::now();
     202      1305397 : 
     203      1305397 :         let mut state = self.state.lock();
     204              : 
     205      3916191 :         for direction in 0..2 {
     206      2610794 :             self.process_direction(
     207      2610794 :                 net,
     208      2610794 :                 state.deref_mut(),
     209      2610794 :                 now,
     210      2610794 :                 direction as MessageDirection,
     211      2610794 :                 &self.dst_sockets[direction ^ 1],
     212      2610794 :             );
     213      2610794 :         }
     214              : 
     215              :         // Close the one side of the connection by timeout if the node
     216              :         // has not received any messages for a long time.
     217      1305397 :         if let Some(timeout) = net.options.keepalive_timeout {
     218      1305397 :             let mut to_close = [false, false];
     219      3916191 :             for direction in 0..2 {
     220      2610794 :                 let buffer = &mut state.buffers[direction];
     221      2610794 :                 if buffer.recv_closed {
     222       536533 :                     continue;
     223      2074261 :                 }
     224      2074261 :                 if let Some(last_recv) = buffer.last_recv {
     225      1880831 :                     if now - last_recv >= timeout {
     226       404453 :                         debug!(
     227            0 :                             "NET: connection {} timed out at {}",
     228            0 :                             self.connection_id,
     229            0 :                             receiver_str(direction as MessageDirection)
     230              :                         );
     231       404453 :                         let node_idx = direction ^ 1;
     232       404453 :                         to_close[node_idx] = true;
     233      1476378 :                     }
     234       193430 :                 }
     235              :             }
     236      1305397 :             drop(state);
     237              : 
     238      2610794 :             for (node_idx, should_close) in to_close.iter().enumerate() {
     239      2610794 :                 if *should_close {
     240       404453 :                     self.close(node_idx);
     241      2206341 :                 }
     242              :             }
     243            0 :         }
     244      1305397 :     }
     245              : 
     246              :     /// Process messages in the buffer in the given direction.
     247      2610794 :     fn process_direction(
     248      2610794 :         &self,
     249      2610794 :         net: &Arc<NetworkTask>,
     250      2610794 :         state: &mut ConnectionState,
     251      2610794 :         now: u64,
     252      2610794 :         direction: MessageDirection,
     253      2610794 :         to_socket: &Chan<NetEvent>,
     254      2610794 :     ) {
     255      2610794 :         let buffer = &mut state.buffers[direction as usize];
     256      2610794 :         if buffer.recv_closed {
     257       536533 :             assert!(buffer.buf.is_empty());
     258      2074261 :         }
     259              : 
     260      3139564 :         while !buffer.buf.is_empty() && buffer.buf.front().unwrap().0 <= now {
     261       528770 :             let msg = buffer.buf.pop_front().unwrap().1;
     262       528770 : 
     263       528770 :             buffer.last_recv = Some(now);
     264       528770 :             self.schedule_timeout(net);
     265       528770 : 
     266       528770 :             if let AnyMessage::InternalConnect = msg {
     267       200481 :                 // TODO: assert to_socket is the server
     268       200481 :                 let server_to_client = TCP {
     269       200481 :                     net: net.clone(),
     270       200481 :                     conn_id: self.connection_id,
     271       200481 :                     dir: direction ^ 1,
     272       200481 :                     recv_chan: to_socket.clone(),
     273       200481 :                 };
     274       200481 :                 // special case, we need to deliver new connection to a separate channel
     275       200481 :                 self.dst_accept.send(NodeEvent::Accept(server_to_client));
     276       328289 :             } else {
     277       328289 :                 to_socket.send(NetEvent::Message(msg));
     278       328289 :             }
     279              :         }
     280      2610794 :     }
     281              : 
     282              :     /// Try to send a message to the buffer, optionally dropping it and
     283              :     /// determining delivery timestamp.
     284       518865 :     fn send(&self, net: &NetworkTask, direction: MessageDirection, msg: AnyMessage) {
     285       518865 :         let now = executor::now();
     286       518865 :         let mut state = self.state.lock();
     287              : 
     288       518865 :         let (delay, close) = if let Some(ms) = net.options.send_delay.delay(&mut state.rng) {
     289       475065 :             (ms, false)
     290              :         } else {
     291        43800 :             (0, true)
     292              :         };
     293              : 
     294       518865 :         let buffer = &mut state.buffers[direction as usize];
     295       518865 :         if buffer.send_closed {
     296        56167 :             debug!(
     297            0 :                 "NET: TCP #{} dropped message {:?} (broken pipe)",
     298              :                 self.connection_id, msg
     299              :             );
     300        56167 :             return;
     301       462698 :         }
     302       462698 : 
     303       462698 :         if close {
     304        32759 :             debug!(
     305            0 :                 "NET: TCP #{} dropped message {:?} (pipe just broke)",
     306              :                 self.connection_id, msg
     307              :             );
     308        32759 :             buffer.send_closed = true;
     309        32759 :             return;
     310       429939 :         }
     311       429939 : 
     312       429939 :         if buffer.recv_closed {
     313        48730 :             debug!(
     314            0 :                 "NET: TCP #{} dropped message {:?} (recv closed)",
     315              :                 self.connection_id, msg
     316              :             );
     317        48730 :             return;
     318       381209 :         }
     319       381209 : 
     320       381209 :         // Send a message into the future.
     321       381209 :         buffer.buf.push_back((now + delay, msg));
     322       381209 :         net.schedule(self.connection_id, delay);
     323       518865 :     }
     324              : 
     325              :     /// Close the connection. Only one side of the connection will be closed,
     326              :     /// and no further messages will be delivered. The other side will not be notified.
     327       435613 :     fn close(&self, node_idx: usize) {
     328       435613 :         let mut state = self.state.lock();
     329       435613 :         let recv_buffer = &mut state.buffers[1 ^ node_idx];
     330       435613 :         if recv_buffer.recv_closed {
     331         2145 :             debug!(
     332            0 :                 "NET: TCP #{} closed twice at {}",
     333            0 :                 self.connection_id,
     334            0 :                 sender_str(node_idx as MessageDirection),
     335              :             );
     336         2145 :             return;
     337       433468 :         }
     338       433468 : 
     339       433468 :         debug!(
     340            0 :             "NET: TCP #{} closed at {}",
     341            0 :             self.connection_id,
     342            0 :             sender_str(node_idx as MessageDirection),
     343              :         );
     344       433468 :         recv_buffer.recv_closed = true;
     345       433468 :         for msg in recv_buffer.buf.drain(..) {
     346        40473 :             debug!(
     347            0 :                 "NET: TCP #{} dropped message {:?} (closed)",
     348              :                 self.connection_id, msg
     349              :             );
     350              :         }
     351              : 
     352       433468 :         let send_buffer = &mut state.buffers[node_idx];
     353       433468 :         send_buffer.send_closed = true;
     354       433468 :         drop(state);
     355       433468 : 
     356       433468 :         // TODO: notify the other side?
     357       433468 : 
     358       433468 :         self.dst_sockets[node_idx].send(NetEvent::Closed);
     359       435613 :     }
     360              : }
     361              : 
     362              : struct NetworkBuffer {
     363              :     /// Messages paired with time of delivery
     364              :     buf: VecDeque<(u64, AnyMessage)>,
     365              :     /// True if the connection is closed on the receiving side,
     366              :     /// i.e. no more messages from the buffer will be delivered.
     367              :     recv_closed: bool,
     368              :     /// True if the connection is closed on the sending side,
     369              :     /// i.e. no more messages will be added to the buffer.
     370              :     send_closed: bool,
     371              :     /// Last time a message was delivered from the buffer.
     372              :     /// If None, it means that the server is the receiver and
     373              :     /// it has not yet aware of this connection (i.e. has not
     374              :     /// received the Accept).
     375              :     last_recv: Option<u64>,
     376              : }
     377              : 
     378              : impl NetworkBuffer {
     379       542826 :     fn new(last_recv: Option<u64>) -> Self {
     380       542826 :         Self {
     381       542826 :             buf: VecDeque::new(),
     382       542826 :             recv_closed: false,
     383       542826 :             send_closed: false,
     384       542826 :             last_recv,
     385       542826 :         }
     386       542826 :     }
     387              : }
     388              : 
     389              : /// Single end of a bidirectional network stream without reordering (TCP-like).
     390              : /// Reads are implemented using channels, writes go to the buffer inside VirtualConnection.
     391              : pub struct TCP {
     392              :     net: Arc<NetworkTask>,
     393              :     conn_id: usize,
     394              :     dir: MessageDirection,
     395              :     recv_chan: Chan<NetEvent>,
     396              : }
     397              : 
     398              : impl Debug for TCP {
     399         1802 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     400         1802 :         write!(f, "TCP #{} ({})", self.conn_id, sender_str(self.dir),)
     401         1802 :     }
     402              : }
     403              : 
     404              : impl TCP {
     405              :     /// Send a message to the other side. It's guaranteed that it will not arrive
     406              :     /// before the arrival of all messages sent earlier.
     407       518865 :     pub fn send(&self, msg: AnyMessage) {
     408       518865 :         let conn = self.net.get(self.conn_id);
     409       518865 :         conn.send(&self.net, self.dir, msg);
     410       518865 :     }
     411              : 
     412              :     /// Get a channel to receive incoming messages.
     413      3422339 :     pub fn recv_chan(&self) -> Chan<NetEvent> {
     414      3422339 :         self.recv_chan.clone()
     415      3422339 :     }
     416              : 
     417      2348618 :     pub fn connection_id(&self) -> usize {
     418      2348618 :         self.conn_id
     419      2348618 :     }
     420              : 
     421        31160 :     pub fn close(&self) {
     422        31160 :         let conn = self.net.get(self.conn_id);
     423        31160 :         conn.close(self.dir as usize);
     424        31160 :     }
     425              : }
     426              : struct Event {
     427              :     time: u64,
     428              :     conn_id: usize,
     429              : }
     430              : 
     431              : // BinaryHeap is a max-heap, and we want a min-heap. Reverse the ordering here
     432              : // to get that.
     433              : impl PartialOrd for Event {
     434      8042835 :     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
     435      8042835 :         Some(self.cmp(other))
     436      8042835 :     }
     437              : }
     438              : 
     439              : impl Ord for Event {
     440      8042835 :     fn cmp(&self, other: &Self) -> Ordering {
     441      8042835 :         (other.time, other.conn_id).cmp(&(self.time, self.conn_id))
     442      8042835 :     }
     443              : }
     444              : 
     445              : impl PartialEq for Event {
     446            0 :     fn eq(&self, other: &Self) -> bool {
     447            0 :         (other.time, other.conn_id) == (self.time, self.conn_id)
     448            0 :     }
     449              : }
     450              : 
     451              : impl Eq for Event {}
        

Generated by: LCOV version 2.1-beta