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
extern crate futures_promises;
extern crate tokio;

use futures::sync::mpsc::Sender;
use futures::{
    future::Future,
    sink::Sink,
    stream::{SplitSink, SplitStream, Stream},
    sync::mpsc::channel,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::{
    codec::{Decoder, Encoder, Framed},
    io::{AsyncRead, AsyncWrite},
};

use futures_promises::promises::{Promise, PromiseHandle};

/// A simple interface to interact with a tokio sink.
///
/// Should always be constructed by a call to some IoManager's get_writer().
pub struct IoWriter<Codec>
where
    Codec: Encoder,
{
    tx: futures::sync::mpsc::Sender<<Codec as Encoder>::Item>,
}

impl<Codec> Clone for IoWriter<Codec>
where
    Codec: Encoder,
{
    fn clone(&self) -> Self {
        IoWriter {
            tx: self.tx.clone(),
        }
    }
}

impl<Codec> IoWriter<Codec>
where
    Codec: Encoder,
    <Codec as tokio::codec::Encoder>::Item: std::marker::Send + 'static,
{
    /// Forwards the frame to the tokio sink associated with the IoManager that build this instance.
    pub fn write(&mut self, frame: <Codec as Encoder>::Item) -> PromiseHandle<()> {
        let promise = Promise::new();
        let handle = promise.get_handle();
        tokio::spawn(self.tx.clone().send(frame).then(move |result| {
            match result {
                Ok(_) => promise.resolve(()),
                Err(e) => {
                    promise.reject(format!("{}", e));
                }
            };
            Ok::<(), ()>(())
        }));
        handle
    }
}

pub trait Filter<Codec>:
    FnMut(<Codec as Decoder>::Item, &mut IoWriter<Codec>) -> Option<<Codec as Decoder>::Item>
    + std::marker::Send
    + 'static
where
    Codec: Decoder,
{
}

impl<T, Codec> Filter<Codec> for T
where
    T: FnMut(<Codec as Decoder>::Item, &mut IoWriter<Codec>) -> Option<<Codec as Decoder>::Item>
        + std::marker::Send
        + 'static,
    Codec: Decoder,
{
}

pub trait ErrorHandler<Codec>:
    FnMut(<Codec as Decoder>::Error) + std::marker::Send + 'static
where
    Codec: Decoder,
{
}

impl<T, Codec> ErrorHandler<Codec> for T
where
    T: FnMut(<Codec as Decoder>::Error) + std::marker::Send + 'static,
    Codec: Decoder,
{
}

pub struct IoManagerBuilder<Codec, Io, F, EH>
where
    Codec: Decoder + Encoder + std::marker::Send + 'static,
    <Codec as Encoder>::Item: std::marker::Send,
    <Codec as Encoder>::Error: std::marker::Send,
    <Codec as Decoder>::Item: std::marker::Send + Clone,
    <Codec as Decoder>::Error: std::marker::Send,
    Io: AsyncRead + AsyncWrite + std::marker::Send + 'static,
    F: FnMut(<Codec as Decoder>::Item, &mut IoWriter<Codec>) -> Option<<Codec as Decoder>::Item>
        + std::marker::Send
        + 'static,
    EH: FnMut(<Codec as Decoder>::Error) + std::marker::Send + 'static,
{
    sink: SplitSink<Framed<Io, Codec>>,
    stream: SplitStream<Framed<Io, Codec>>,
    filter: Option<F>,
    error_handler: Option<EH>,
}

impl<Codec, Io, F, EH> IoManagerBuilder<Codec, Io, F, EH>
where
    Codec: Decoder + Encoder + std::marker::Send + 'static,
    <Codec as Encoder>::Item: std::marker::Send,
    <Codec as Encoder>::Error: std::marker::Send,
    <Codec as Decoder>::Item: std::marker::Send + Clone,
    <Codec as Decoder>::Error: std::marker::Send,
    Io: AsyncRead + AsyncWrite + std::marker::Send + 'static,
    F: Filter<Codec>,
    EH: ErrorHandler<Codec>,
{
    pub fn new(sink: SplitSink<Framed<Io, Codec>>, stream: SplitStream<Framed<Io, Codec>>) -> Self {
        Self {
            sink,
            stream,
            filter: None,
            error_handler: None,
        }
    }

    pub fn with_filter(mut self, filter: F) -> Self {
        self.filter = Some(filter);
        self
    }

    pub fn with_error_handler(mut self, handler: EH) -> Self {
        self.error_handler = Some(handler);
        self
    }

    pub fn build(self) -> IoManager<Codec> {
        IoManager::constructor(self.sink, self.stream, self.filter, self.error_handler)
    }
}

/// A simplified interface to interact with tokio's streams and sinks.
///
/// Allows easy subscription to the stream's frames, and easy sending to the sink.
pub struct IoManager<Codec>
where
    Codec: Encoder + Decoder,
{
    tx: futures::sync::mpsc::Sender<<Codec as Encoder>::Item>,
    subscribers: Arc<Mutex<HashMap<u32, futures::sync::mpsc::Sender<<Codec as Decoder>::Item>>>>,
    next_handle: Mutex<u32>,
}

impl<Codec> IoManager<Codec>
where
    Codec: Decoder + Encoder + std::marker::Send + 'static,
    <Codec as Encoder>::Item: std::marker::Send,
    <Codec as Encoder>::Error: std::marker::Send,
    <Codec as Decoder>::Item: std::marker::Send + Clone,
    <Codec as Decoder>::Error: std::marker::Send,
{
    /// SHOULD ALWAYS BE CALLED FROM INSIDE A TOKIO RUNTIME!
    ///
    /// Builds a new `IoManager` from the provided `sink` and `stream` with no filter.
    ///
    /// You can provide a filter to run on each `frame` before sending said frames to callbacks.
    /// To provide a filter, use `with_filter(sink, stream, callback)`.
    pub fn new<Io>(
        sink: SplitSink<Framed<Io, Codec>>,
        stream: SplitStream<Framed<Io, Codec>>,
    ) -> Self
    where
        Io: AsyncRead + AsyncWrite + std::marker::Send + 'static,
    {
        Self::constructor(
            sink,
            stream,
            None::<
                (fn(
                    <Codec as Decoder>::Item,
                    &mut IoWriter<Codec>,
                ) -> Option<<Codec as Decoder>::Item>),
            >,
            None::<fn(<Codec as Decoder>::Error)>,
        )
    }

    /// SHOULD ALWAYS BE CALLED FROM INSIDE A TOKIO RUNTIME!
    ///
    /// Builds a new IoManager from the provided sink and stream.
    /// You can provide a filter to run on each frame before sending said frames to callbacks.
    ///
    /// Callbacks will not be called if the filter returned None, so if you intend on only having a single callback,
    /// using `filter=callback` with a callback that always returns `None` will save you the cost of the multiple
    /// callbacks handling provided by the `subscibe(callback)` API
    pub fn with_filter<Io, F>(
        sink: SplitSink<Framed<Io, Codec>>,
        stream: SplitStream<Framed<Io, Codec>>,
        filter: F,
    ) -> Self
    where
        Io: AsyncWrite + AsyncRead + std::marker::Send + 'static,
        F: Filter<Codec>,
    {
        Self::constructor(
            sink,
            stream,
            Some(filter),
            None::<fn(<Codec as Decoder>::Error)>,
        )
    }

    pub fn constructor<Io, F, EH>(
        sink: SplitSink<Framed<Io, Codec>>,
        stream: SplitStream<Framed<Io, Codec>>,
        mut filter: Option<F>,
        error_handler: Option<EH>,
    ) -> Self
    where
        Io: AsyncWrite + AsyncRead + std::marker::Send + 'static,
        F: Filter<Codec>,
        EH: ErrorHandler<Codec>,
    {
        let (sink_tx, sink_rx) = channel::<<Codec as Encoder>::Item>(10);
        let sink_task = sink_rx.forward(sink.sink_map_err(|_| ())).map(|_| ());
        tokio::spawn(sink_task);
        let mut filter_writer = IoWriter {
            tx: sink_tx.clone(),
        };

        let subscribers = Arc::new(Mutex::new(HashMap::<
            u32,
            futures::sync::mpsc::Sender<<Codec as Decoder>::Item>,
        >::new()));
        let stream_subscribers_reference = subscribers.clone();
        let stream_task = stream
            .for_each(move |frame: <Codec as Decoder>::Item| {
                let frame = match &mut filter {
                    None => Some(frame),
                    Some(function) => function(frame, &mut filter_writer),
                };
                match frame {
                    Some(frame) => {
                        for (_handle, tx) in stream_subscribers_reference.lock().unwrap().iter_mut()
                        {
                            match tx.start_send(frame.clone()) {
                                Ok(_) => {}
                                Err(error) => {
                                    eprintln!("Stream Subscriber Error: {}", error);
                                }
                            };
                        }
                    }
                    None => {}
                }
                Ok(())
            })
            .map_err(|e| match error_handler {
                None => (),
                Some(mut handler) => handler(e),
            });
        tokio::spawn(stream_task);
        IoManager {
            tx: sink_tx,
            subscribers,
            next_handle: Mutex::new(0),
        }
    }

    /// deprecated: use `on_receive()` instead, unless you NEED an `mpsc::Sender` to be notified.
    ///
    /// `subscriber` will receive any data polled from the internal stream.
    pub fn subscribe_mpsc_sender(
        &self,
        subscriber: futures::sync::mpsc::Sender<<Codec as Decoder>::Item>,
    ) -> u32 {
        let mut map = self.subscribers.lock().unwrap();
        let mut handle_guard = self.next_handle.lock().unwrap();
        let handle = handle_guard.clone();
        *handle_guard += 1;
        map.insert(handle.clone(), subscriber);
        handle
    }

    /// `callback` will be called for each `frame` polled from the internal stream.
    pub fn on_receive<F>(&self, callback: F) -> u32
    where
        F: FnMut(<Codec as Decoder>::Item) -> Result<(), ()> + std::marker::Send + 'static,
        <Codec as Decoder>::Item: std::marker::Send + 'static,
    {
        let (tx, rx): (
            futures::sync::mpsc::Sender<<Codec as Decoder>::Item>,
            futures::sync::mpsc::Receiver<<Codec as Decoder>::Item>,
        ) = channel::<<Codec as Decoder>::Item>(10);
        let on_frame = rx.for_each(callback).map(|_| ());
        tokio::spawn(on_frame);
        self.subscribe_mpsc_sender(tx)
    }

    /// Removes the callback with `key`handle. `key` should be a value returned by either
    /// `on_receive()` or `subscribe_mpsc_sender()`.
    ///
    /// Returns the `mpsc::Sender` that used to be notified upon new frames, just in case.
    pub fn extract_callback(&self, key: &u32) -> Option<Sender<<Codec as Decoder>::Item>> {
        let mut map = self.subscribers.lock().unwrap();
        map.remove(key)
    }

    /// Returns an `IoWriter` that will forward data to the associated tokio sink.
    pub fn get_writer(&self) -> IoWriter<Codec> {
        IoWriter {
            tx: self.tx.clone(),
        }
    }
}

/// Inspired by bkwilliams, these aliases will probably stay, but you shouldn't rely too much on them
pub mod silly_aliases {
    pub type DoWhenever<T> = crate::IoManager<T>;
    pub type PushWhenever<T> = crate::IoWriter<T>;
}

/// DEPRECATED: These aliases will be discarded whenever an actual API change happens
pub mod legacy_aliases {
    pub type AsyncReadWriter<T> = crate::IoManager<T>;
    pub type AsyncWriter<T> = crate::IoWriter<T>;
}