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
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;
use std::thread::{self, JoinHandle};
use event_loop::SENDER;
use std::net::SocketAddr;
use mio::{self, Token};
use result::{ThrustResult, ThrustError};
use tangle::{Future, Async};
use std::io::Cursor;
use protocol::*;
use binary_protocol::*;
use reactor::{self, Dispatch, Message, Id};
use util;

#[derive(Debug)]
pub enum Role {
    /// A server will be tasked with actually calling a user defined
    /// RPC method and dispatching the response back to the event loop.
    Server(SocketAddr),
    /// A client is tasked with sending an initial RPC and dispatching a response.
    ///
    Client(SocketAddr)
}

pub enum Incoming {
    /// Method name, data buf, and response channel.
    Call(String, Vec<u8>, Sender<(ThriftMessage, BinaryDeserializer<Cursor<Vec<u8>>>)>),
    Shutdown
}

/// A middleman between incoming and outgoing messages from the event loop and
/// clients or servers. Each instance of a server or client has it's own Dispatcher.
///
/// Dispatchers run in their own thread and only expose a channel interface. This makes it
/// extremely easy to do multi-threading by simply cloning the dispatcher.
pub struct Dispatcher {
    role: Role,
    /// The connection token as used and exposed by the event loop. This is required
    /// to know where to send and receive Rpc calls.
    token: Token,
    data_rx: Receiver<Dispatch>,
    /// The channel to communicate with the event loop.
    event_loop: mio::Sender<Message>,
    rx: Receiver<Incoming>,
    /// The response queue that is used to match up outgoing requests with future
    /// responses. Each response has it's own sender channel.
    queue: HashMap<String, Sender<(ThriftMessage, BinaryDeserializer<Cursor<Vec<u8>>>)>>
}

impl Dispatcher {
    pub fn spawn(role: Role) -> ThrustResult<(JoinHandle<ThrustResult<()>>, Sender<Incoming>)> {
        let (ret_tx, ret_rx) = channel();
        let handle = thread::spawn(move || {
            let (sender, receiver) = channel();
            ret_tx.send(sender);

            let (id_tx, id_rx) = channel();
            let event_loop_sender = SENDER.clone();
            let (data_tx, data_rx) = channel();

            match role {
                Role::Server(addr) => {
                    event_loop_sender.send(Message::Bind(addr, id_tx, data_tx))?;
                },
                Role::Client(addr) => {
                    event_loop_sender.send(Message::Connect(addr, id_tx, data_tx))?;
                }
            }

            let Id(token) = id_rx.recv()?;

            Dispatcher {
                role: role,
                token: token,
                data_rx: data_rx,
                event_loop: event_loop_sender,
                rx: receiver,
                queue: HashMap::new()
            }.run()
        });

        Ok((handle, ret_rx.recv()?))
    }

    pub fn run(mut self) -> ThrustResult<()> {
        let rx = self.rx;
        let event_loop_rx = self.data_rx;

        loop {
            select! {
                user_msg = rx.recv() => {
                    match user_msg {
                        Ok(Incoming::Shutdown) => break,
                        Ok(Incoming::Call(method, buf, tx)) => {
                            self.event_loop.send(Message::Rpc(self.token, buf));
                            self.queue.insert(method, tx);
                        },
                        // The sender-part of the channel has been disconnected.
                        Err(err) => break
                    }
                },
                event_loop_msg = event_loop_rx.recv() => {
                    match event_loop_msg {
                        Ok(Dispatch::Data(token, buf)) => {
                            let mut de = BinaryDeserializer::new(Cursor::new(buf));
                            let msg = de.read_message_begin()?;

                            match msg.ty {
                                ThriftMessageType::Call => {
                                    if let Role::Client(_) = self.role {
                                        // A client isn't supposed to receive RPC calls.
                                    } else {
                                        // The server has received a call, so let's reply:
                                        let buf = util::create_empty_thrift_message("foobar123", ThriftMessageType::Reply);
                                        self.event_loop.send(Message::Rpc(token, buf));
                                    }
                                },
                                ThriftMessageType::Reply => {
                                    if let Role::Server(_) = self.role {
                                        // Servers never get a reply message. Ignore.
                                    } else {
                                        // Look into the request cache.
                                        match self.queue.remove(&msg.name) {
                                            Some(tx) => {
                                                tx.send((msg, de))?;
                                            },
                                            None => {}
                                        }
                                    }
                                },
                                _ => {}
                            }

                        },
                        Err(err) => break
                    }
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tangle::{Future, Async};
    use std::net::SocketAddr;
    use std::io::Cursor;
    use reactor::{Reactor, Message};
    use event_loop::SENDER;
    use protocol::{ThriftMessage, ThriftMessageType};
    use binary_protocol::BinaryDeserializer;
    use std::sync::mpsc::channel;
    use util;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn should_create_server_dispatcher() {
        let addr = "127.0.0.1:5495".parse().unwrap();
        let (handle, tx) = Dispatcher::spawn(Role::Server(addr)).unwrap();
    }

    #[test]
    fn should_start_server() {
        let addr: SocketAddr = "127.0.0.1:5955".parse().unwrap();
        let (handle_server, server) = Dispatcher::spawn(Role::Server(addr.clone())).unwrap();
        thread::sleep(Duration::from_millis(30));
        let (handle_client, client) = Dispatcher::spawn(Role::Client(addr.clone())).unwrap();

        let buf = util::create_empty_thrift_message("foobar123", ThriftMessageType::Call);

        let (res, future) = Future::<(ThriftMessage, BinaryDeserializer<Cursor<Vec<u8>>>)>::channel();
        client.send(Incoming::Call("foobar123".to_string(), buf, res)).unwrap();

        let (res_tx, res_rx) = channel();
        let cloned = res_tx.clone();
        future.and_then(move |(msg, de)| {
            println!("[test]: Received: {:?}", msg);
            SENDER.clone().send(Message::Shutdown);
            res_tx.send(0);
            Async::Ok(())
        });

        // Ensure that the test exists after at least 3 seconds if the response was not
        // received.
        thread::spawn(move || -> Result<(), ()> {
            thread::sleep(Duration::from_millis(3000));
            SENDER.clone().send(Message::Shutdown);
            panic!("Test timeout was hit. This means the Reactor did not shutdown and a response was not received.");
            cloned.send(1);
        });

        Reactor::run().join();

        assert_eq!(res_rx.recv().unwrap(), 0);
    }
}