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
use byteorder::{BigEndian, ByteOrder}; use bytes::Bytes; use futures::sync::{mpsc, BiLock}; use futures::{Async, Poll, Stream}; use std::collections::HashMap; use util::SeqGenerator; component! { ChannelManager : ChannelManagerInner { sequence: SeqGenerator<u16> = SeqGenerator::new(0), channels: HashMap<u16, mpsc::UnboundedSender<(u8, Bytes)>> = HashMap::new(), } } #[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)] pub struct ChannelError; pub struct Channel { receiver: mpsc::UnboundedReceiver<(u8, Bytes)>, state: ChannelState, } pub struct ChannelHeaders(BiLock<Channel>); pub struct ChannelData(BiLock<Channel>); pub enum ChannelEvent { Header(u8, Vec<u8>), Data(Bytes), } #[derive(Clone)] enum ChannelState { Header(Bytes), Data, Closed, } impl ChannelManager { pub fn allocate(&self) -> (u16, Channel) { let (tx, rx) = mpsc::unbounded(); let seq = self.lock(|inner| { let seq = inner.sequence.get(); inner.channels.insert(seq, tx); seq }); let channel = Channel { receiver: rx, state: ChannelState::Header(Bytes::new()), }; (seq, channel) } pub(crate) fn dispatch(&self, cmd: u8, mut data: Bytes) { use std::collections::hash_map::Entry; let id: u16 = BigEndian::read_u16(data.split_to(2).as_ref()); self.lock(|inner| { if let Entry::Occupied(entry) = inner.channels.entry(id) { let _ = entry.get().unbounded_send((cmd, data)); } }); } } impl Channel { fn recv_packet(&mut self) -> Poll<Bytes, ChannelError> { let (cmd, packet) = match self.receiver.poll() { Ok(Async::Ready(t)) => t.expect("channel closed"), Ok(Async::NotReady) => return Ok(Async::NotReady), Err(()) => unreachable!(), }; if cmd == 0xa { let code = BigEndian::read_u16(&packet.as_ref()[..2]); error!("channel error: {} {}", packet.len(), code); self.state = ChannelState::Closed; Err(ChannelError) } else { Ok(Async::Ready(packet)) } } pub fn split(self) -> (ChannelHeaders, ChannelData) { let (headers, data) = BiLock::new(self); (ChannelHeaders(headers), ChannelData(data)) } } impl Stream for Channel { type Item = ChannelEvent; type Error = ChannelError; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { match self.state.clone() { ChannelState::Closed => panic!("Polling already terminated channel"), ChannelState::Header(mut data) => { if data.len() == 0 { data = try_ready!(self.recv_packet()); } let length = BigEndian::read_u16(data.split_to(2).as_ref()) as usize; if length == 0 { assert_eq!(data.len(), 0); self.state = ChannelState::Data; } else { let header_id = data.split_to(1).as_ref()[0]; let header_data = data.split_to(length - 1).as_ref().to_owned(); self.state = ChannelState::Header(data); let event = ChannelEvent::Header(header_id, header_data); return Ok(Async::Ready(Some(event))); } } ChannelState::Data => { let data = try_ready!(self.recv_packet()); if data.len() == 0 { self.receiver.close(); self.state = ChannelState::Closed; return Ok(Async::Ready(None)); } else { let event = ChannelEvent::Data(data); return Ok(Async::Ready(Some(event))); } } } } } } impl Stream for ChannelData { type Item = Bytes; type Error = ChannelError; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { let mut channel = match self.0.poll_lock() { Async::Ready(c) => c, Async::NotReady => return Ok(Async::NotReady), }; loop { match try_ready!(channel.poll()) { Some(ChannelEvent::Header(..)) => (), Some(ChannelEvent::Data(data)) => return Ok(Async::Ready(Some(data))), None => return Ok(Async::Ready(None)), } } } } impl Stream for ChannelHeaders { type Item = (u8, Vec<u8>); type Error = ChannelError; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { let mut channel = match self.0.poll_lock() { Async::Ready(c) => c, Async::NotReady => return Ok(Async::NotReady), }; match try_ready!(channel.poll()) { Some(ChannelEvent::Header(id, data)) => Ok(Async::Ready(Some((id, data)))), Some(ChannelEvent::Data(..)) | None => Ok(Async::Ready(None)), } } }