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
use crate::transports::tokio_core::reactor;
use crate::transports::Result;
use crate::{Error, RequestId};
use futures::sync::oneshot;
use futures::{self, Future};
use std::sync::{self, atomic, Arc};
use std::{fmt, mem, thread};

/// Event Loop Handle.
/// NOTE: Event loop is stopped when handle is dropped!
#[derive(Debug)]
pub struct EventLoopHandle {
    remote: Option<Remote>,
    thread: Option<thread::JoinHandle<()>>,
}

impl EventLoopHandle {
    /// Creates a new `EventLoopHandle` and transport given the transport initializer.
    pub fn spawn<T, F>(func: F) -> Result<(Self, T)>
    where
        F: FnOnce(&reactor::Handle) -> Result<T>,
        F: Send + 'static,
        T: Send + 'static,
    {
        let done = Arc::new(atomic::AtomicBool::new(false));
        let (tx, rx) = sync::mpsc::sync_channel(1);
        let done2 = done.clone();

        let eloop = thread::spawn(move || {
            let run = move || {
                let event_loop = reactor::Core::new()?;
                let http = func(&event_loop.handle())?;
                Ok((http, event_loop))
            };

            let send = move |result| {
                tx.send(result).expect("Receiving end is always waiting.");
            };

            let res = run();
            match res {
                Err(e) => send(Err(e)),
                Ok((http, mut event_loop)) => {
                    send(Ok((http, event_loop.remote())));

                    while !done2.load(atomic::Ordering::Relaxed) {
                        event_loop.turn(None);
                    }
                }
            }
        });

        rx.recv().expect("Thread is always spawned.").map(|(http, remote)| {
            (
                EventLoopHandle {
                    thread: Some(eloop),
                    remote: Some(Remote { remote, done }),
                },
                http,
            )
        })
    }

    /// Returns event loop remote.
    pub fn remote(&self) -> &reactor::Remote {
        self.remote
            .as_ref()
            .map(|remote| &remote.remote)
            .expect("Remote is available when EventLoopHandle is alive.")
    }

    /// Convert this handle into a `Remote`.
    ///
    /// Note while dropping `EventLoopHandle` will stop
    /// the underlying event loop, dropping the `Remote` will not.
    /// You need manually call `Remote::stop` to stop the background thread.
    pub fn into_remote(mut self) -> Remote {
        self.remote.take().expect("Remote can be taken only once.")
    }
}

impl Drop for EventLoopHandle {
    fn drop(&mut self) {
        if let Some(remote) = self.remote.take() {
            remote.stop();

            self.thread
                .take()
                .expect("We never touch thread except for drop; drop happens only once; qed")
                .join()
                .expect("Thread should shut down cleanly.");
        }
    }
}

/// A remote to event loop running in the background.
#[derive(Debug)]
pub struct Remote {
    remote: reactor::Remote,
    done: Arc<atomic::AtomicBool>,
}

impl Remote {
    /// Returns the underlying event loop remote.
    pub fn remote(&self) -> &reactor::Remote {
        &self.remote
    }

    /// Stop the background event loop.
    pub fn stop(self) {
        self.done.store(true, atomic::Ordering::Relaxed);
        self.remote.spawn(|_| Ok(()));
    }
}

type PendingResult<O> = oneshot::Receiver<Result<O>>;

enum RequestState<O> {
    Sending(Option<Result<()>>, PendingResult<O>),
    WaitingForResponse(PendingResult<O>),
    Done,
}

/// A future representing a response to a pending request.
pub struct Response<T, O> {
    id: RequestId,
    state: RequestState<O>,
    extract: T,
}

impl<T, O> Response<T, O> {
    /// Creates a new `Response`
    pub fn new(id: RequestId, result: Result<()>, rx: PendingResult<O>, extract: T) -> Self {
        Response {
            id,
            extract,
            state: RequestState::Sending(Some(result), rx),
        }
    }
}

impl<T, O, Out> Future for Response<T, O>
where
    T: Fn(O) -> Result<Out>,
    Out: fmt::Debug,
{
    type Item = Out;
    type Error = Error;

    fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
        loop {
            let extract = &self.extract;
            match self.state {
                RequestState::Sending(ref mut result, _) => {
                    log::trace!("[{}] Request pending.", self.id);
                    if let Some(Err(e)) = result.take() {
                        return Err(e);
                    }
                }
                RequestState::WaitingForResponse(ref mut rx) => {
                    log::trace!("[{}] Checking response.", self.id);
                    let result = try_ready!(rx.poll().map_err(|_| Error::Io(::std::io::ErrorKind::TimedOut.into())));
                    log::trace!("[{}] Extracting result.", self.id);
                    return result.and_then(|x| extract(x)).map(futures::Async::Ready);
                }
                RequestState::Done => {
                    return Err(Error::Unreachable);
                }
            }
            // Proceeed to the next state
            let state = mem::replace(&mut self.state, RequestState::Done);
            self.state = if let RequestState::Sending(_, rx) = state {
                RequestState::WaitingForResponse(rx)
            } else {
                state
            }
        }
    }
}