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
use std::collections::HashMap;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use std::pin::Pin;

use futures::prelude::*;
use futures::stream::Stream;
use futures::channel::mpsc::{channel, Receiver as ChannelReceiver, Sender as ChannelSender};
use futures::channel::{oneshot, oneshot::Sender as OneshotSender};
use futures::task::{Context, Poll};
use async_trait::async_trait;

use crate::connector::Connector;
use crate::muxed::Muxed;

/// Mux is a futures based request response multiplexer.
/// This provides a Source interface to drain messages sent, and receives messages via the handle() method,
/// allowing responses to be consumed and requests forwarded on.
///
/// ReqId is the request ReqId type
/// Target is the target for the Req or Resp to be sent to
/// Req and Resp are the request and response messages
/// Ctx is a a shared context
pub struct Mux<ReqId, Target, Req, Resp, E, Ctx> {
    requests: Arc<Mutex<HashMap<ReqId, Box<OneshotSender<Resp>>>>>,

    sender: ChannelSender<(ReqId, Target, Muxed<Req, Resp>, Ctx)>,
    receiver: Arc<Mutex<ChannelReceiver<(ReqId, Target, Muxed<Req, Resp>, Ctx)>>>,

    _addr: PhantomData<Target>,
    _req: PhantomData<Req>,
    _err: PhantomData<E>,
    _ctx: PhantomData<Ctx>,
}

impl<ReqId, Target, Req, Resp, E, Ctx> Clone for Mux<ReqId, Target, Req, Resp, E, Ctx>
where
    ReqId: std::cmp::Eq + std::hash::Hash + std::fmt::Debug + Clone + Send + 'static,
    Target: Debug + Send + 'static,
    Req: Debug + Send + 'static,
    Resp: Debug + Send + 'static,
    E: Debug + Send + 'static,
    Ctx: Debug + Clone + Send + 'static,
{
    fn clone(&self) -> Self {
        Mux {
            requests: self.requests.clone(),
            sender: self.sender.clone(),
            receiver: self.receiver.clone(),
            _ctx: PhantomData,
            _addr: PhantomData,
            _req: PhantomData,
            _err: PhantomData,
        }
    }
}

impl<ReqId, Target, Req, Resp, E, Ctx> Mux<ReqId, Target, Req, Resp, E, Ctx>
where
    ReqId: std::cmp::Eq + std::hash::Hash + std::fmt::Debug + Clone + Send + 'static,
    Target: Debug + Send + 'static,
    Req: Debug + Send + 'static,
    Resp: Debug + Send + 'static,
    E: Debug + Send + 'static,
    Ctx: Debug + Clone + Send + 'static,
{
    /// Create a new mux over the provided sender
    pub fn new() -> Mux<ReqId, Target, Req, Resp, E, Ctx> {
        let (tx, rx) = channel(0);

        Mux {
            requests: Arc::new(Mutex::new(HashMap::new())),
            sender: tx,
            receiver: Arc::new(Mutex::new(rx)),
            _ctx: PhantomData,
            _addr: PhantomData,
            _req: PhantomData,
            _err: PhantomData,
        }
    }

    /// Handle a muxed received message
    /// This either returns a pending response or passes request messages on
    pub fn handle(
        &mut self, id: ReqId, addr: Target, message: Muxed<Req, Resp>) -> Result<Option<(Target, Req)>, E> {
        let r = match message {
            // Requests get passed through the mux
            Muxed::Request(req) => Some((addr, req)),
            // Responses get matched with outstanding requests
            Muxed::Response(resp) => {
                self.handle_resp(id, addr, resp)?;
                None
            }
        };

        Ok(r)
    }

    /// Handle a pre-decoded response message
    pub fn handle_resp(&mut self, id: ReqId, _target: Target, resp: Resp) -> Result<(), E> {
        let ch = { self.requests.lock().unwrap().remove(&id) };
        if let Some(ch) = ch {
            ch.send(resp).unwrap();
        } else {
            info!("Response id: '{:?}', no request pending", id);
        }
        Ok(())
    }
}

#[async_trait]
impl<ReqId, Target, Req, Resp, E, Ctx> Connector<ReqId, Target, Req, Resp, E, Ctx>
    for Mux<ReqId, Target, Req, Resp, E, Ctx>
where
    ReqId: std::cmp::Eq + std::hash::Hash + Debug + Clone + Send + 'static,
    Target: Debug + Send + 'static,
    Req: Debug + Send + 'static,
    Resp: Debug + Send + 'static,
    E: Debug + Send + 'static,
    Ctx: Debug + Clone + Send + 'static,
{
    /// Send and register a request
    async fn request(
        &mut self, ctx: Ctx, id: ReqId, addr: Target, req: Req,
    ) -> Result<Resp, E> {
        // Create future channel
        let (tx, rx) = oneshot::channel();

        // Save response to map
        { self.requests
            .lock()
            .unwrap()
            .insert(id.clone(), Box::new(tx)) };

        // Send request and return channel future
        let mut sender = self.sender.clone();

        match sender.send((id, addr, Muxed::Request(req), ctx)).await {
            Ok(_) => (),
            Err(e) => panic!(e),
        };

        let res = match rx.await {
            Ok(r) => r,
            Err(e) => panic!(e),
        };

        Ok(res)
    }

    async fn respond(
        &mut self, ctx: Ctx, id: ReqId, addr: Target, resp: Resp,
    ) -> Result<(), E> {
        // Send request and return channel future
        let mut sender = self.sender.clone();

        match sender.send((id, addr, Muxed::Response(resp), ctx)).await {
            Ok(_) => (),
            Err(e) => panic!(e),
        };

        Ok(())
    }
}

// Stream implementation to allow polling from mux
impl<ReqId, Target, Req, Resp, E, Ctx> Stream for Mux<ReqId, Target, Req, Resp, E, Ctx> {
    type Item = (ReqId, Target, Muxed<Req, Resp>, Ctx);

    // Poll to read pending requests
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        self.receiver.lock().unwrap().poll_next_unpin(cx)
    }
}


#[cfg(test)]
mod tests {
    extern crate futures;
    use futures::prelude::*;
    use futures::executor::block_on;

    use super::*;

    #[derive(PartialEq, Debug, Copy, Clone)]
    struct A(u64);
    #[derive(PartialEq, Debug, Copy, Clone)]
    struct B(u64);
    #[derive(PartialEq, Debug, Copy, Clone)]
    struct C(u64);

    #[test]
    fn test_mux() {
        let mut mux: Mux<u16, u32, A, B, (), C> = Mux::new();

        let req_id = 10;
        let addr = 12;
        let req = A(20);
        let resp = B(30);

        let ctx_out = C(40);
        let ctx_in = C(50);

        // Make a request and check the response
        let mut m = mux.clone();
        let a = async {
            let r = m.request(ctx_out, req_id, addr, req).await.unwrap();
            assert_eq!(resp, r);
        }.boxed();

        // Respond to request
        let b = async {
            while let Some((i, a, m, c)) = mux.next().await {
                assert_eq!(i, req_id);
                assert_eq!(a, addr);
                assert_eq!(m.req(), Some(req));
                assert_eq!(c, ctx_out);
    
                let resp = resp.clone();
                
                mux.handle_resp(req_id, addr, resp).unwrap();
            }
        }.boxed();

        // Run using select
        // a will finish, b will poll forever
        let _ = block_on(future::select(a, b));

    }
}