1 use crate::{error::Error, *};
2 use async_recursion::async_recursion;
3 use byteorder::{BigEndian, ReadBytesExt};
5 cell::{Cell, OnceCell},
10 time::{Duration, Instant},
12 use tokio::sync::{mpsc, Mutex};
14 fn to_seqnum(seqnum: u16) -> usize {
15 (seqnum as usize) & (REL_BUFFER - 1)
18 type Result<T> = std::result::Result<T, Error>;
21 timestamp: Option<Instant>,
22 chunks: Vec<OnceCell<Vec<u8>>>,
27 packets: Vec<Cell<Option<Vec<u8>>>>, // char ** 😛
28 splits: HashMap<u16, Split>,
33 pub struct RecvWorker<R: UdpReceiver, S: UdpSender> {
34 share: Arc<RudpShare<S>>,
35 close: watch::Receiver<bool>,
36 chans: Arc<Vec<Mutex<RecvChan>>>,
37 pkt_tx: mpsc::UnboundedSender<InPkt>,
41 impl<R: UdpReceiver, S: UdpSender> RecvWorker<R, S> {
44 share: Arc<RudpShare<S>>,
45 close: watch::Receiver<bool>,
46 pkt_tx: mpsc::UnboundedSender<InPkt>,
58 packets: (0..REL_BUFFER).map(|_| Cell::new(None)).collect(),
60 splits: HashMap::new(),
68 pub async fn run(&self) {
71 let cleanup_chans = Arc::clone(&self.chans);
72 let mut cleanup_close = self.close.clone();
78 .name("cleanup_splits")*/
80 let timeout = Duration::from_secs(TIMEOUT);
82 ticker!(timeout, cleanup_close, {
83 for chan_mtx in cleanup_chans.iter() {
84 let mut chan = chan_mtx.lock().await;
88 |_k, v| !matches!(v.timestamp, Some(t) if t.elapsed() < timeout),
95 let mut close = self.close.clone();
96 let timeout = tokio::time::sleep(Duration::from_secs(TIMEOUT));
100 if let Err(e) = self.handle(self.recv_pkt(&mut close, timeout.as_mut()).await) {
101 // TODO: figure out whether this is a good idea
102 if let RemoteDisco(to) = e {
103 self.pkt_tx.send(Err(RemoteDisco(to))).ok();
107 // anon5's mt notifies the peer on timeout, C++ MT does not
108 LocalDisco /*| RemoteDisco(true)*/ => drop(
115 data: &[CtlType::Disco as u8],
131 close: &mut watch::Receiver<bool>,
132 timeout: Pin<&mut tokio::time::Sleep>,
136 // TODO: reset timeout
137 let mut cursor = io::Cursor::new(tokio::select! {
138 pkt = self.udp_rx.recv() => pkt?,
139 _ = tokio::time::sleep_until(timeout.deadline()) => return Err(RemoteDisco(true)),
140 _ = close.changed() => return Err(LocalDisco),
143 timeout.reset(tokio::time::Instant::now() + Duration::from_secs(TIMEOUT));
145 let proto_id = cursor.read_u32::<BigEndian>()?;
146 if proto_id != PROTO_ID {
147 return Err(InvalidProtoId(proto_id));
150 let _peer_id = cursor.read_u16::<BigEndian>()?;
152 let n_chan = cursor.read_u8()?;
155 .get(n_chan as usize)
156 .ok_or(InvalidChannel(n_chan))?
160 self.process_pkt(cursor, true, &mut chan).await
164 async fn process_pkt(
166 mut cursor: io::Cursor<Vec<u8>>,
172 match cursor.read_u8()?.try_into()? {
173 PktType::Ctl => match cursor.read_u8()?.try_into()? {
177 let seqnum = cursor.read_u16::<BigEndian>()?;
178 if let Some(ack) = self.share.chans[chan.num as usize]
184 ack.tx.send(true).ok();
187 CtlType::SetPeerID => {
188 println!("SetPeerID");
190 let mut id = self.share.remote_id.write().await;
192 if *id != PeerID::Nil as u16 {
193 return Err(PeerIDAlreadySet);
196 *id = cursor.read_u16::<BigEndian>()?;
203 return Err(RemoteDisco(false));
209 self.pkt_tx.send(Ok(Pkt {
212 data: cursor.remaining_slice().into(),
218 let seqnum = cursor.read_u16::<BigEndian>()?;
219 let chunk_index = cursor.read_u16::<BigEndian>()? as usize;
220 let chunk_count = cursor.read_u16::<BigEndian>()? as usize;
222 let mut split = chan.splits.entry(seqnum).or_insert_with(|| Split {
224 chunks: (0..chunk_count).map(|_| OnceCell::new()).collect(),
228 if split.chunks.len() != chunk_count {
229 return Err(InvalidChunkCount(split.chunks.len(), chunk_count));
235 .ok_or(InvalidChunkIndex(chunk_index, chunk_count))?
236 .set(cursor.remaining_slice().into())
242 split.timestamp = if unrel { Some(Instant::now()) } else { None };
244 if split.got == chunk_count {
245 self.pkt_tx.send(Ok(Pkt {
251 .flat_map(|chunk| chunk.get().unwrap().iter())
256 chan.splits.remove(&seqnum);
262 let seqnum = cursor.read_u16::<BigEndian>()?;
263 chan.packets[to_seqnum(seqnum)].set(Some(cursor.remaining_slice().into()));
265 let mut ack_data = Vec::with_capacity(3);
266 ack_data.write_u8(CtlType::Ack as u8)?;
267 ack_data.write_u16::<BigEndian>(seqnum)?;
280 fn next_pkt(chan: &mut RecvChan) -> Option<Vec<u8>> {
281 chan.packets[to_seqnum(chan.seqnum)].take()
284 while let Some(pkt) = next_pkt(chan) {
285 self.handle(self.process_pkt(io::Cursor::new(pkt), false, chan).await)?;
286 chan.seqnum = chan.seqnum.overflowing_add(1).0;
294 fn handle(&self, res: Result<()>) -> Result<()> {
299 Err(RemoteDisco(to)) => Err(RemoteDisco(to)),
300 Err(LocalDisco) => Err(LocalDisco),
301 Err(e) => Ok(self.pkt_tx.send(Err(e))?),