]> git.lizzy.rs Git - mt_rudp.git/blob - src/recv.rs
Get rid of Cell usage
[mt_rudp.git] / src / recv.rs
1 use crate::{prelude::*, ticker, RecvChan, RecvWorker, RudpShare, Split};
2 use async_recursion::async_recursion;
3 use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
4 use std::{
5     cell::OnceCell,
6     collections::HashMap,
7     io,
8     pin::Pin,
9     sync::Arc,
10     time::{Duration, Instant},
11 };
12 use tokio::sync::{mpsc, watch, Mutex};
13
14 fn to_seqnum(seqnum: u16) -> usize {
15     (seqnum as usize) & (REL_BUFFER - 1)
16 }
17
18 type Result<T> = std::result::Result<T, Error>;
19
20 impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
21     pub fn new(
22         udp_rx: R,
23         share: Arc<RudpShare<S>>,
24         close: watch::Receiver<bool>,
25         pkt_tx: mpsc::UnboundedSender<InPkt>,
26     ) -> Self {
27         Self {
28             udp_rx,
29             share,
30             close,
31             pkt_tx,
32             chans: Arc::new(
33                 (0..NUM_CHANS as u8)
34                     .map(|num| {
35                         Mutex::new(RecvChan {
36                             num,
37                             packets: (0..REL_BUFFER).map(|_| None).collect(),
38                             seqnum: INIT_SEQNUM,
39                             splits: HashMap::new(),
40                         })
41                     })
42                     .collect(),
43             ),
44         }
45     }
46
47     pub async fn run(&self) {
48         use Error::*;
49
50         let cleanup_chans = Arc::clone(&self.chans);
51         let mut cleanup_close = self.close.clone();
52         self.share
53             .tasks
54             .lock()
55             .await
56             /*.build_task()
57             .name("cleanup_splits")*/
58             .spawn(async move {
59                 let timeout = Duration::from_secs(TIMEOUT);
60
61                 ticker!(timeout, cleanup_close, {
62                     for chan_mtx in cleanup_chans.iter() {
63                         let mut chan = chan_mtx.lock().await;
64                         chan.splits = chan
65                             .splits
66                             .drain_filter(
67                                 |_k, v| !matches!(v.timestamp, Some(t) if t.elapsed() < timeout),
68                             )
69                             .collect();
70                     }
71                 });
72             });
73
74         let mut close = self.close.clone();
75         let timeout = tokio::time::sleep(Duration::from_secs(TIMEOUT));
76         tokio::pin!(timeout);
77
78         loop {
79             if let Err(e) = self.handle(self.recv_pkt(&mut close, timeout.as_mut()).await) {
80                 // TODO: figure out whether this is a good idea
81                 if let RemoteDisco(to) = e {
82                     self.pkt_tx.send(Err(RemoteDisco(to))).ok();
83                 }
84
85                 #[allow(clippy::single_match)]
86                 match e {
87                                         // anon5's mt notifies the peer on timeout, C++ MT does not
88                                         LocalDisco /*| RemoteDisco(true)*/ => drop(
89                                                 self.share
90                                                         .send(
91                                                                 PktType::Ctl,
92                                                                 Pkt {
93                                                                         unrel: true,
94                                                                         chan: 0,
95                                                                         data: &[CtlType::Disco as u8],
96                                                                 },
97                                                         )
98                                                         .await
99                                                         .ok(),
100                                         ),
101                                         _ => {}
102                                 }
103
104                 break;
105             }
106         }
107     }
108
109     async fn recv_pkt(
110         &self,
111         close: &mut watch::Receiver<bool>,
112         timeout: Pin<&mut tokio::time::Sleep>,
113     ) -> Result<()> {
114         use Error::*;
115
116         let mut cursor = io::Cursor::new(tokio::select! {
117             pkt = self.udp_rx.recv() => pkt?,
118             _ = tokio::time::sleep_until(timeout.deadline()) => return Err(RemoteDisco(true)),
119             _ = close.changed() => return Err(LocalDisco),
120         });
121
122         timeout.reset(tokio::time::Instant::now() + Duration::from_secs(TIMEOUT));
123
124         let proto_id = cursor.read_u32::<BigEndian>()?;
125         if proto_id != PROTO_ID {
126             return Err(InvalidProtoId(proto_id));
127         }
128
129         let _peer_id = cursor.read_u16::<BigEndian>()?;
130
131         let n_chan = cursor.read_u8()?;
132         let mut chan = self
133             .chans
134             .get(n_chan as usize)
135             .ok_or(InvalidChannel(n_chan))?
136             .lock()
137             .await;
138
139         self.process_pkt(cursor, true, &mut chan).await
140     }
141
142     #[async_recursion]
143     async fn process_pkt(
144         &self,
145         mut cursor: io::Cursor<Vec<u8>>,
146         unrel: bool,
147         chan: &mut RecvChan,
148     ) -> Result<()> {
149         use Error::*;
150
151         match cursor.read_u8()?.try_into()? {
152             PktType::Ctl => match cursor.read_u8()?.try_into()? {
153                 CtlType::Ack => {
154                     println!("Ack");
155
156                     let seqnum = cursor.read_u16::<BigEndian>()?;
157                     if let Some(ack) = self.share.chans[chan.num as usize]
158                         .lock()
159                         .await
160                         .acks
161                         .remove(&seqnum)
162                     {
163                         ack.tx.send(true).ok();
164                     }
165                 }
166                 CtlType::SetPeerID => {
167                     println!("SetPeerID");
168
169                     let mut id = self.share.remote_id.write().await;
170
171                     if *id != PeerID::Nil as u16 {
172                         return Err(PeerIDAlreadySet);
173                     }
174
175                     *id = cursor.read_u16::<BigEndian>()?;
176                 }
177                 CtlType::Ping => {
178                     println!("Ping");
179                 }
180                 CtlType::Disco => {
181                     println!("Disco");
182                     return Err(RemoteDisco(false));
183                 }
184             },
185             PktType::Orig => {
186                 println!("Orig");
187
188                 self.pkt_tx.send(Ok(Pkt {
189                     chan: chan.num,
190                     unrel,
191                     data: cursor.remaining_slice().into(),
192                 }))?;
193             }
194             PktType::Split => {
195                 println!("Split");
196
197                 let seqnum = cursor.read_u16::<BigEndian>()?;
198                 let chunk_index = cursor.read_u16::<BigEndian>()? as usize;
199                 let chunk_count = cursor.read_u16::<BigEndian>()? as usize;
200
201                 let mut split = chan.splits.entry(seqnum).or_insert_with(|| Split {
202                     got: 0,
203                     chunks: (0..chunk_count).map(|_| OnceCell::new()).collect(),
204                     timestamp: None,
205                 });
206
207                 if split.chunks.len() != chunk_count {
208                     return Err(InvalidChunkCount(split.chunks.len(), chunk_count));
209                 }
210
211                 if split
212                     .chunks
213                     .get(chunk_index)
214                     .ok_or(InvalidChunkIndex(chunk_index, chunk_count))?
215                     .set(cursor.remaining_slice().into())
216                     .is_ok()
217                 {
218                     split.got += 1;
219                 }
220
221                 split.timestamp = if unrel { Some(Instant::now()) } else { None };
222
223                 if split.got == chunk_count {
224                     self.pkt_tx.send(Ok(Pkt {
225                         chan: chan.num,
226                         unrel,
227                         data: split
228                             .chunks
229                             .iter()
230                             .flat_map(|chunk| chunk.get().unwrap().iter())
231                             .copied()
232                             .collect(),
233                     }))?;
234
235                     chan.splits.remove(&seqnum);
236                 }
237             }
238             PktType::Rel => {
239                 println!("Rel");
240
241                 let seqnum = cursor.read_u16::<BigEndian>()?;
242                 chan.packets[to_seqnum(seqnum)].replace(cursor.remaining_slice().into());
243
244                 let mut ack_data = Vec::with_capacity(3);
245                 ack_data.write_u8(CtlType::Ack as u8)?;
246                 ack_data.write_u16::<BigEndian>(seqnum)?;
247
248                 self.share
249                     .send(
250                         PktType::Ctl,
251                         Pkt {
252                             unrel: true,
253                             chan: chan.num,
254                             data: &ack_data,
255                         },
256                     )
257                     .await?;
258
259                 fn next_pkt(chan: &mut RecvChan) -> Option<Vec<u8>> {
260                     chan.packets[to_seqnum(chan.seqnum)].take()
261                 }
262
263                 while let Some(pkt) = next_pkt(chan) {
264                     self.handle(self.process_pkt(io::Cursor::new(pkt), false, chan).await)?;
265                     chan.seqnum = chan.seqnum.overflowing_add(1).0;
266                 }
267             }
268         }
269
270         Ok(())
271     }
272
273     fn handle(&self, res: Result<()>) -> Result<()> {
274         use Error::*;
275
276         match res {
277             Ok(v) => Ok(v),
278             Err(RemoteDisco(to)) => Err(RemoteDisco(to)),
279             Err(LocalDisco) => Err(LocalDisco),
280             Err(e) => Ok(self.pkt_tx.send(Err(e))?),
281         }
282     }
283 }