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
use flow_control::{Credits, FlowControlStrategy};
use futures::sync::mpsc;
use futures::sync::mpsc::Receiver;
use futures::sync::mpsc::Sender;
use futures::task;
use futures::task::Task;
use futures::Async;
use futures::Future;
use futures::Poll;
use protocol::codec::reader::FrameReader;
use protocol::codec::writer::FrameWriter;
use protocol::frames;
use protocol::frames::Frame;
use protocol::frames::FramingError;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use stream::IncomingStreams;
use stream::StreamId;
use stream::StreamState;
use tokio_io::AsyncRead;
use tokio_io::AsyncWrite;

type ConnectionId = u32;

#[derive(Debug)]
pub enum ConnectionError {
    InvalidStreamId,
    UnknownFrame,
    General,
    InsufficientCredit, // TODO this should really be in its own category, maybe in some nested ConnError
}

impl From<()> for ConnectionError {
    fn from(_: ()) -> Self {
        ConnectionError::General
    }
}

impl From<FramingError> for ConnectionError {
    fn from(_err: FramingError) -> Self {
        ConnectionError::General
    }
}

#[derive(Debug)]
pub struct ConnectionConfig {
    flow_control_strategy: FlowControlStrategy,
}
impl Default for ConnectionConfig {
    fn default() -> Self {
        ConnectionConfig {
            flow_control_strategy: FlowControlStrategy::Disabled,
        }
    }
}

/// Tracks connection-related state needed for driving I/O progress
#[derive(Debug)]
pub struct ConnectionContext {
    cfg: ConnectionConfig,
    /// ID of this connection
    id: ConnectionId,
    /// Stores the current connection error, if there is one
    err: Option<ConnectionError>,
    /// Stream management store
    pub(crate) stream_states: HashMap<StreamId, StreamState>,
    /// Channels for forwarding decoded frames to application
    pub(crate) stream_senders: HashMap<StreamId, Sender<frames::Frame>>,
    /// Channel for submitting frames for writing over the network
    outbound: Sender<Frame>,
    outbound_listener: Receiver<Frame>,
    new_streams: VecDeque<frames::StreamRequest>,

    /// Task which drives the connection's I/O progress
    pub(crate) conn_task: Option<Task>,
    /// Task which awaits new streams
    pub(crate) new_stream_task: Option<Task>,
}

/// Frame-handling helper
enum AsyncHandle<T> {
    Ready,
    NotReady(T),
}

// impl ConnectionContext
impl ConnectionContext {
    pub fn new(id: ConnectionId) -> Self {
        let (tx, rx) = mpsc::channel(1024);
        ConnectionContext {
            cfg: ConnectionConfig::default(), // TODO custommize
            id,
            err: None,
            conn_task: None,
            new_stream_task: None,
            stream_states: HashMap::new(),
            stream_senders: HashMap::new(),
            outbound: tx,
            outbound_listener: rx,
            new_streams: VecDeque::new(),
        }
    }

    pub fn get_stream_state_mut(&mut self, stream_id: &StreamId) -> Option<&mut StreamState> {
        self.stream_states.get_mut(stream_id)
    }

    /// Delegates work according to frame type
    fn handle_frame(&mut self, f: Frame) -> Result<AsyncHandle<Frame>, ConnectionError> {
        match f {
            Frame::StreamRequest(frame) => self.on_stream_request(frame),
            Frame::CreditUpdate(frame) => self.on_credit_update(frame),
            Frame::Data(frame) => self.on_data(frame),
            Frame::Ping(_, _) => Ok(AsyncHandle::Ready),
            Frame::Pong(_, _) => Ok(AsyncHandle::Ready),
            Frame::Unknown => Err(ConnectionError::UnknownFrame),
        }
    }

    fn on_stream_request(
        &mut self,
        request: frames::StreamRequest,
    ) -> Result<AsyncHandle<Frame>, ConnectionError> {
        let stream_id = request.stream_id;
        println!("on_stream_request {:?}", stream_id);
        match self.stream_states.get_mut(&stream_id) {
            Some(_) => return Err(ConnectionError::InvalidStreamId),
            None => (),
        }
        let (tx, rx) = mpsc::channel(1);
        let state = StreamState {
            credits: Credits::new(request.credit_capacity),
            data_buffer: VecDeque::new(),
            data: rx,
            send_task: None,
            recv_task: None,
        };
        self.stream_states.insert(stream_id, state);
        self.stream_senders.insert(stream_id, tx);

        self.new_streams.push_back(request);
        self.notify_new_stream_task();
        Ok(AsyncHandle::Ready)
    }

    fn on_credit_update(
        &mut self,
        _request: frames::CreditUpdate,
    ) -> Result<AsyncHandle<Frame>, ConnectionError> {
        // TODO
        Ok(AsyncHandle::Ready)
    }

    fn on_data(&mut self, data: frames::Data) -> Result<AsyncHandle<Frame>, ConnectionError> {
        let stream_id = data.stream_id;

        let stream_state = match self.stream_states.get_mut(&stream_id) {
            None => return Err(ConnectionError::InvalidStreamId),
            Some(state) => state,
        };
        let sender = self.stream_senders.get_mut(&stream_id).unwrap();
        if let Async::NotReady = sender.poll_ready().map_err(|_| ConnectionError::General)? {
            return Ok(AsyncHandle::NotReady(Frame::Data(data)));
        }

        let frame_size = data.payload_ref().len() as u32;
        if self.cfg.flow_control_strategy != FlowControlStrategy::Disabled {
            if !stream_state.credits.has_capacity(frame_size) {
                return Err(ConnectionError::InsufficientCredit);
            }
            let _res = stream_state.credits.use_credit(frame_size);
        }

        // TODO should really leverage futures executor for this logic
        if let Err(err) = sender.try_send(frames::Frame::Data(data)) {
            return Ok(AsyncHandle::NotReady(err.into_inner()));
        }

        Ok(AsyncHandle::Ready)
    }

    /// Returns true if the connection has an error
    pub fn has_err(&self) -> bool {
        self.err.is_some()
    }

    /// Stores an error for this connection
    fn set_err(&mut self, err: ConnectionError) {
        self.err = Some(err);
    }

    /// Notifies all connection-related `Task`s
    fn notify_all(&mut self) {
        self.notify_conn_task();
        self.notify_new_stream_task();
    }

    // Notifies connection-driving task to wake up
    fn notify_conn_task(&mut self) {
        if let Some(task) = self.conn_task.take() {
            task.notify()
        }
    }
    // Notifies stream-listening task to wake up
    fn notify_new_stream_task(&mut self) {
        if let Some(task) = self.new_stream_task.take() {
            task.notify()
        }
    }

    pub fn next_stream(&mut self) -> Option<frames::StreamRequest> {
        self.new_streams.pop_front()
    }

    /// Returns the number of credits available for the stream, or `Async::NotReady` if there are none.
    ///
    /// Upon returning `Async::NotReady` the current task is stored and will be woken up once
    /// additional credits are assigned in `on_credit_update`.
    pub fn poll_stream_capacity(&mut self, stream_id: StreamId) -> Poll<u32, ConnectionError> {
        if self.has_err() {
            return Err(ConnectionError::General);
        }
        try_ready!(
            self.poll_conn_capacity()
                .map_err(|_| ConnectionError::InsufficientCredit)
        );
        let stream_state = match self.stream_states.get_mut(&stream_id) {
            None => {
                return Err(ConnectionError::InvalidStreamId);
            }
            Some(state) => state,
        };
        let remaining = stream_state.credits.available();
        if remaining == 0 {
            stream_state.send_task = Some(task::current());
            return Ok(Async::NotReady);
        }
        Ok(Async::Ready(remaining))
    }

    pub fn sender(&self) -> Sender<Frame> {
        self.outbound.clone()
    }

    pub fn poll_conn_capacity(&mut self) -> Poll<(), ()> {
        self.outbound.poll_ready().map_err(|_| ())
    }

    pub fn send_frame(&mut self, frame: Frame) -> Result<(), ConnectionError> {
        if let Frame::Data(ref data) = frame {
            // Flow control checks
            let stream_state = match self.stream_states.get_mut(&data.stream_id) {
                None => {
                    return Err(ConnectionError::InvalidStreamId);
                }
                Some(state) => state,
            };

            // TODO move into own FC module
            if self.cfg.flow_control_strategy != FlowControlStrategy::Disabled {
                let size = data.payload_ref().len() as u32;
                if !stream_state.credits.has_capacity(size) {
                    return Err(ConnectionError::InsufficientCredit);
                }
                let _res = stream_state.credits.use_credit(size);
            }
        }
        // TODO handle res error
        let _res = self.outbound.try_send(frame);
        self.notify_conn_task();
        Ok(())
    }

    pub fn poll_complete<T: AsyncWrite>(&mut self, tx: &mut FrameWriter<T>) -> Poll<(), ()> {
        use futures::Stream;

        try_ready!(tx.poll_buffer_ready().map_err(|_| ()));

        while let Some(frame) = try_ready!(self.outbound_listener.poll()) {
            // TODO handle err
            let _res = try_ready!(tx.buffer_and_flush(frame).map_err(|_| ()));
            try_ready!(tx.poll_buffer_ready().map_err(|_| ()));
        }
        Ok(Async::Ready(()))
    }
}

pub type SharedConnectionContext = Arc<Mutex<ConnectionContext>>;
pub type SharedFrameWriter<O> = Arc<Mutex<FrameWriter<O>>>;

struct IoHandle<I: AsyncRead, O: AsyncWrite> {
    rx: FrameReader<I>,
    tx: SharedFrameWriter<O>,
}

impl<I: AsyncRead, O: AsyncWrite> IoHandle<I, O> {
    pub fn new(rx: I, tx: O) -> Self {
        IoHandle {
            rx: FrameReader::new(rx),
            tx: Arc::new(Mutex::new(FrameWriter::new(tx))),
        }
    }

    pub fn clone_writer(&mut self) -> SharedFrameWriter<O> {
        self.tx.clone()
    }
}

pub struct ConnectionDriver<I: AsyncRead, O: AsyncWrite> {
    handle: IoHandle<I, O>,
    ctx: SharedConnectionContext,
    head_of_line: Option<Frame>,
}

impl<I: AsyncRead, O: AsyncWrite> ConnectionDriver<I, O> {
    pub fn with_io(reader: I, writer: O, id: u32) -> Self {
        let ctx = ConnectionContext::new(id);
        let ctx = Arc::new(Mutex::new(ctx));
        let handle = IoHandle::new(reader, writer);

        ConnectionDriver {
            head_of_line: None,
            handle,
            ctx,
        }
    }

    /// Returns a Stream which resolves to new stream IDs
    pub fn incoming_streams(&mut self) -> IncomingStreams {
        IncomingStreams::new(self.clone_ctx())
    }

    pub fn clone_ctx(&mut self) -> SharedConnectionContext {
        self.ctx.clone()
    }

    pub fn clone_writer(&mut self) -> SharedFrameWriter<O> {
        self.handle.clone_writer()
    }

    pub fn poll_read_progress(&mut self) -> Poll<(), ConnectionError> {
        use std::borrow::BorrowMut;

        let rx = self.handle.rx.borrow_mut();

        loop {
            // Continue looping until error, connection is closed, or there is nothing more to read
            let cur = match self.head_of_line.take() {
                None => try_ready!(rx.poll_frame()),
                Some(head) => Some(head),
            };
            match cur {
                None => return Ok(Async::Ready(())),
                Some(frame) => {
                    let mut ctx = self.ctx.lock().unwrap();
                    match ctx.handle_frame(frame) {
                        Ok(AsyncHandle::Ready) => (),
                        Ok(AsyncHandle::NotReady(f)) => {
                            self.head_of_line = Some(f);
                            return Ok(Async::NotReady);
                        }
                        Err(why) => {
                            println!("handle_frame err: {:?}", why);
                        }
                    }
                }
            }
        }
    }

    // TODO errors
    pub fn poll_write_progress(&mut self) -> Poll<(), ()> {
        let mut ctx = self.ctx.lock().unwrap();
        println!("poll write progress");
        let ctx = &mut *ctx;

        let mut tx = self.handle.tx.lock().unwrap();
        let tx = &mut *tx;

        ctx.poll_complete(tx)
    }
}

impl<I: AsyncRead, O: AsyncWrite> Future for ConnectionDriver<I, O> {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match self.poll_read_progress() {
                Ok(Async::Ready(())) => {
                    return Ok(Async::Ready(()));
                }
                Ok(Async::NotReady) => {
                    try_ready!(self.poll_write_progress());

                    // Store this task as the one responsible for making connection progress
                    match self.ctx.lock() {
                        Ok(mut ctx) => {
                            ctx.conn_task = Some(task::current());
                        }
                        Err(_) => {
                            // Should this ever be possible?
                            let mut ctx = self.ctx.lock().unwrap();
                            println!("Mutex poisoned");
                            ctx.set_err(ConnectionError::General);
                            return Err(());
                        }
                    }
                    return Ok(Async::NotReady);
                }
                Err(err) => {
                    let mut ctx = self.ctx.lock().unwrap();
                    println!("Closing conn with err: {:?}", err);
                    ctx.set_err(err);
                    return Err(());
                }
            }
        }
    }
}