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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! This crate provides a wrapper around streams that allow multiple, independent
//! tasks to read from the same underlying stream. Each handle is assigned a key,
//! and each received item is given to a function to compute a key, determining
//! which handle receives the item. There is always default handle which receives
//! an item if the result of the key function does not match any other handle.
#![deny(missing_docs)]

extern crate futures;
extern crate ordermap;

#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
#[cfg(test)]
extern crate void;
#[cfg(test)]
extern crate atm_async_utils;

use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::Hash;
use std::rc::Rc;

use futures::{Stream, Poll, Async};
use futures::task::{Task, current};
use ordermap::OrderMap;

/// Create a new `MCS`, wrapping the given stream.
pub fn mcs<S: Stream, K: Copy + Eq + Hash, F: Fn(&S::Item) -> K>(stream: S,
                                                                 key_fn: F)
                                                                 -> MCS<S, K, F> {
    MCS { shared: Rc::new(RefCell::new(Shared::new(stream, key_fn))) }
}

/// A handle to a stream that receives all items without a corresponding `KeyMCS`.
///
/// If one of the key handles triggers an error, the error is emitted on the main
/// `MCS`. Further calls to `poll` after an error has been emitted panic.
pub struct MCS<S: Stream, K, F> {
    shared: Rc<RefCell<Shared<S, K, F>>>,
}

impl<S, K, F> MCS<S, K, F>
    where S: Stream,
          K: Copy + Eq + Hash,
          F: Fn(&S::Item) -> K
{
    /// Create a `KeyMCS` handle to the underlying stream. The handle receives all
    /// items for which the `key_fn` returns `key`.
    ///
    /// Panics if there is already a handle for that key.
    pub fn key_handle(&self, key: K) -> KeyMCS<S, K, F> {
        KeyMCS::new(self.shared.clone(), key)
    }

    /// Create a `KeyMCS` handle to the underlying stream. The handle receives all
    /// items for which the `key_fn` returns `key`. This returns `None` if there
    /// is already a handle for the given key.
    pub fn try_key_handle(&self, key: K) -> Option<KeyMCS<S, K, F>> {
        KeyMCS::try_new(self.shared.clone(), key)
    }

    /// Consume the `MCS` and return ownership of the wrapped stream. If the
    /// stream did not terminate before calling this, subsequent calls to `poll`
    /// on a `KeyMCS` will panic.
    pub fn into_inner(self) -> S {
        self.shared.borrow_mut().inner.take().unwrap()
    }
}

impl<S, K, F> Stream for MCS<S, K, F>
    where S: Stream,
          K: Copy + Eq + Hash,
          F: Fn(&S::Item) -> K
{
    type Item = S::Item;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        self.shared.borrow_mut().poll_default()
    }
}

/// A handle to a stream that receives all items for which the `key_fn` returns
/// the value associated with this `KeyMCS`.
///
/// All errors are emitted on the main `MCS`. A `KeyMCS` just signals errors by
/// emitting `Err(())`.
pub struct KeyMCS<S: Stream, K: Eq + Hash, F> {
    shared: Rc<RefCell<Shared<S, K, F>>>,
    key: K,
}

impl<S: Stream, K, F> KeyMCS<S, K, F>
    where S: Stream,
          K: Copy + Eq + Hash,
          F: Fn(&S::Item) -> K
{
    fn new(shared: Rc<RefCell<Shared<S, K, F>>>, key: K) -> KeyMCS<S, K, F> {
        assert!(shared.borrow_mut().register_key(key),
                "Tried to register duplicate handles");
        KeyMCS { shared, key }
    }

    fn try_new(shared: Rc<RefCell<Shared<S, K, F>>>, key: K) -> Option<KeyMCS<S, K, F>> {
        if shared.borrow_mut().register_key(key) {
            Some(KeyMCS { shared, key })
        } else {
            None
        }
    }

    /// Create a `KeyMCS` handle to the underlying stream. The handle receives all
    /// items for which the `key_fn` returns `key`.
    ///
    /// Panics if there is already a handle for that key.
    pub fn key_handle(&self, key: K) -> KeyMCS<S, K, F> {
        KeyMCS::new(self.shared.clone(), key)
    }

    /// Create a `KeyMCS` handle to the underlying stream. The handle receives all
    /// items for which the `key_fn` returns `key`. This returns `None` if there
    /// is already a handle for the given key.
    pub fn try_key_handle(&self, key: K) -> Option<KeyMCS<S, K, F>> {
        KeyMCS::try_new(self.shared.clone(), key)
    }
}

impl<S, K, F> Drop for KeyMCS<S, K, F>
    where S: Stream,
          K: Eq + Hash
{
    /// Deregisters the key of this `KeyMCS`.
    fn drop(&mut self) {
        self.shared.borrow_mut().deregister_key(&self.key);
    }
}

impl<S, K, F> Stream for KeyMCS<S, K, F>
    where S: Stream,
          K: Copy + Eq + Hash,
          F: Fn(&S::Item) -> K
{
    type Item = S::Item;
    type Error = ();

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        self.shared.borrow_mut().poll_handle(self.key)
    }
}

enum StreamState {
    Active,
    Done,
    Errored,
}

struct Shared<S: Stream, K, F> {
    inner: Option<S>,
    key_fn: F,
    // The keys of all currently active handles.
    active_keys: HashSet<K>,
    current: Option<(S::Item, K)>,
    tasks: OrderMap<K, Task>,
    default_task: Option<Task>,
    state: StreamState,
    error: Option<S::Error>,
}

impl<S, K, F> Shared<S, K, F>
    where S: Stream,
          K: Eq + Hash
{
    fn new(inner: S, key_fn: F) -> Shared<S, K, F> {
        Shared {
            inner: Some(inner),
            key_fn,
            active_keys: HashSet::new(),
            current: None,
            tasks: OrderMap::new(),
            default_task: None,
            state: StreamState::Active,
            error: None,
        }
    }

    fn register_key(&mut self, key: K) -> bool {
        self.active_keys.insert(key)
    }

    fn deregister_key(&mut self, key: &K) {
        self.tasks.remove(key);
        self.current
            .take()
            .map(|(current_item, current_key)| {
                     if current_key == *key {
                         self.default_task.take().map(|default| default.notify());
                     }
                     self.current = Some((current_item, current_key));
                 });
        self.active_keys.remove(key);
    }
}

impl<S, K, F> Shared<S, K, F>
    where S: Stream,
          K: Copy + Eq + Hash,
          F: Fn(&S::Item) -> K
{
    fn poll_default(&mut self) -> Poll<Option<S::Item>, S::Error> {
        match self.state {
            StreamState::Done => {
                self.notify_next_handle();
                Ok(Async::Ready(None))
            }

            StreamState::Errored => {
                self.notify_next_handle();
                Err(self.error
                        .take()
                        .expect("Polled MCS after it yielded an error"))
            }

            StreamState::Active => {
                match self.current.take() {
                    None => {
                        let mut inner = self.inner.take().unwrap();
                        // No item buffered, poll inner stream.
                        match inner.poll() {
                            Ok(Async::Ready(Some(item))) => {
                                // Got new item, buffer it and call poll_default again.
                                let key = (self.key_fn)(&item);
                                self.current = Some((item, key));
                                self.inner = Some(inner);
                                return self.poll_default();
                            }
                            Ok(Async::Ready(None)) => {
                                self.state = StreamState::Done;
                                self.notify_next_handle();
                                self.inner = Some(inner);
                                Ok(Async::Ready(None))
                            }
                            Ok(Async::NotReady) => {
                                // No item available, park.
                                self.default_task = Some(current());
                                self.inner = Some(inner);
                                Ok(Async::NotReady)
                            }
                            Err(err) => {
                                self.state = StreamState::Errored;
                                self.notify_next_handle();
                                self.inner = Some(inner);
                                Err(err)
                            }
                        }
                    }

                    Some((item, key)) => {
                        // There's a buffered item + key.
                        if self.active_keys.contains(&key) {
                            // There's a handle for this key, notify it if its blocking.
                            self.default_task = Some(current());
                            self.tasks.remove(&key).map(|task| task.notify());
                            self.current = Some((item, key));
                            Ok(Async::NotReady)
                        } else {
                            // No handle for this key, emit it.
                            // Also notify the next parked task.
                            self.notify_next_handle();
                            Ok(Async::Ready(Some(item)))
                        }
                    }
                }
            }
        }
    }

    fn poll_handle(&mut self, key: K) -> Poll<Option<S::Item>, ()> {
        match self.state {
            StreamState::Done => {
                self.notify_next_handle();
                Ok(Async::Ready(None))
            }

            StreamState::Errored => {
                self.notify_next_handle();
                Err(())
            }

            StreamState::Active => {
                match self.current.take() {
                    None => {
                        let mut inner = self.inner.take().expect("Polled key handle after calling into_inner on the default handle");
                        // No item buffered, poll inner stream.
                        match inner.poll() {
                            Ok(Async::Ready(Some(item))) => {
                                // Got new item, buffer it and call poll_handle again.
                                let item_key = (self.key_fn)(&item);
                                self.current = Some((item, item_key));
                                self.inner = Some(inner);
                                self.poll_handle(key)
                            }
                            Ok(Async::Ready(None)) => {
                                // End of underlying stream.
                                self.notify_default_or_next();
                                self.state = StreamState::Done;
                                self.inner = Some(inner);
                                Ok(Async::Ready(None))
                            }
                            Ok(Async::NotReady) => {
                                // No item available, park.
                                self.tasks.insert(key, current());
                                self.inner = Some(inner);
                                Ok(Async::NotReady)
                            }
                            Err(err) => {
                                self.state = StreamState::Errored;
                                self.error = Some(err);
                                self.notify_default_or_next();
                                self.inner = Some(inner);
                                Err(())
                            }
                        }
                    }

                    Some((item, buffered_key)) => {
                        // There's a buffered item + key.
                        if buffered_key == key {
                            // We should emit the item, also notify the next parked task.
                            self.notify_default_or_next();
                            Ok(Async::Ready(Some(item)))
                        } else {
                            // Not our key, store item, park and let another task handle it.
                            self.tasks.insert(key, current());
                            self.current = Some((item, buffered_key));

                            self.tasks
                                .remove(&buffered_key)
                                .map_or_else(|| self.notify_default(), |task| task.notify());

                            Ok(Async::NotReady)
                        }
                    }
                }
            }
        }
    }

    // notify the next key handle
    fn notify_next_handle(&mut self) {
        self.tasks.pop().map(|(_, task)| task.notify());
    }

    // notify the default handle
    fn notify_default(&mut self) {
        self.default_task.take().map(|default| default.notify());
    }

    // notify the default handle or the next key handle if default can't be notified
    fn notify_default_or_next(&mut self) {
        self.default_task
            .take()
            .map_or_else(|| self.notify_next_handle(), |default| default.notify());
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    use futures::{Future, Stream, Sink};
    use futures::stream::iter_ok;
    use futures::future::ok;

    use quickcheck::{QuickCheck, StdGen};
    use rand;
    use atm_async_utils::test_channel::*;
    use atm_async_utils::test_stream::*;

    #[test]
    fn test_success() {
        let rng = StdGen::new(rand::thread_rng(), 50);
        let mut quickcheck = QuickCheck::new().gen(rng).tests(1000);
        quickcheck.quickcheck(success as fn(usize) -> bool);
    }

    fn success(buf_size: usize) -> bool {
        let (sender, receiver) = test_channel::<u8, (), ()>(buf_size + 1);

        let default = mcs(receiver, |x| match x {
            y if y % 3 == 0 => 1,
            y if y % 5 == 0 => 2,
            _ => 0,
        });

        let s1 = default.key_handle(1);
        let s2 = default.key_handle(2);

        let sending = sender.send_all(iter_ok::<_, ()>(0..20));

        let (_, threes, fives, defaults) = sending
            .join4(s1.collect(),
                   s2.collect(),
                   default.map_err(|_| ()).collect())
            .wait()
            .unwrap();

        return (threes == vec![0, 3, 6, 9, 12, 15, 18]) && (fives == vec![5, 10]) &&
               (defaults == vec![1, 2, 4, 7, 8, 11, 13, 14, 16, 17, 19]);
    }

    #[test]
    fn test_error() {
        let (sender, receiver) = test_channel::<bool, bool, u8>(8);
        let default = mcs(TestStream::new(receiver,
                                          vec![PollOp::Delegate,
                                               PollOp::Err(13),
                                               PollOp::Delegate,
                                               PollOp::Delegate]),
                          |x| *x);
        let r1 = default.key_handle(true);
        let r2 = default.key_handle(false);

        let sending = sender
            .send_all(iter_ok::<_, bool>(0..8).map(|_| false))
            .map(|_| true);

        let default = default
            .for_each(|_| ok(()))
            .map(|_| false)
            .or_else(|err| ok(err == 13));
        let r1 = r1.for_each(|_| ok(()))
            .map(|_| false)
            .or_else(|err| ok(err == ()));
        let r2 = r2.for_each(|_| ok(()))
            .map(|_| false)
            .or_else(|err| ok(err == ()));
        let receiving = default.join3(r1, r2);

        let (_, (worked0, worked1, worked2)) = sending.join(receiving).wait().unwrap();
        assert!(worked0 && worked1 && worked2);
    }
}