#![allow(warnings)]
use streaming::Message;
use tokio_service::Service;
use futures::{Future, Async, Poll, Stream, AsyncSink, Sink};
use futures::sync::mpsc;
use futures::sync::oneshot;
use std::{fmt, io};
use std::cell::RefCell;
pub struct ClientProxy<R, S, E> {
tx: RefCell<mpsc::UnboundedSender<io::Result<Envelope<R, S, E>>>>,
}
impl<R, S, E> Clone for ClientProxy<R, S, E> {
fn clone(&self) -> Self {
ClientProxy {
tx: RefCell::new(self.tx.borrow().clone()),
}
}
}
pub struct Response<T, E> {
inner: oneshot::Receiver<Result<T, E>>,
}
type Envelope<R, S, E> = (R, oneshot::Sender<Result<S, E>>);
pub type Pair<R, S, E> = (ClientProxy<R, S, E>, Receiver<R, S, E>);
pub type Receiver<R, S, E> = mpsc::UnboundedReceiver<io::Result<Envelope<R, S, E>>>;
pub fn pair<R, S, E>() -> Pair<R, S, E> {
let (tx, rx) = mpsc::unbounded();
let client = ClientProxy { tx: RefCell::new(tx) };
(client, rx)
}
impl<R, S, E: From<io::Error>> Service for ClientProxy<R, S, E> {
type Request = R;
type Response = S;
type Error = E;
type Future = Response<S, E>;
fn call(&self, request: R) -> Self::Future {
let (tx, rx) = oneshot::channel();
let _ = mpsc::UnboundedSender::send(&mut self.tx.borrow_mut(),
Ok((request, tx)));
Response { inner: rx }
}
}
impl<R, S, E> fmt::Debug for ClientProxy<R, S, E>
where R: fmt::Debug,
S: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ClientProxy {{ ... }}")
}
}
impl<T, E> Future for Response<T, E>
where E: From<io::Error>,
{
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<T, E> {
match self.inner.poll() {
Ok(Async::Ready(Ok(v))) => Ok(Async::Ready(v)),
Ok(Async::Ready(Err(e))) => Err(e),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(_) => {
let e = io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe");
Err(e.into())
}
}
}
}
impl<T, E> fmt::Debug for Response<T, E>
where T: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Response {{ ... }}")
}
}