use std::iter::FromIterator;
use futures::{future, Future};
use tokio_core::reactor::Handle;
use error::{Error, ErrorKind};
use job::Job;
use rabbitmq::{Exchange, ExchangeBuilder, RabbitmqBroker};
#[derive(Debug)]
pub struct ClientBuilder {
connection_url: String,
exchanges: Vec<Exchange>,
handle: Option<Handle>,
}
impl Default for ClientBuilder {
fn default() -> ClientBuilder {
ClientBuilder {
connection_url: "amqp://localhost/%2f".into(),
exchanges: Vec::new(),
handle: None,
}
}
}
impl ClientBuilder {
pub fn new() -> Self {
ClientBuilder::default()
}
pub fn connection_url(mut self, url: &str) -> Self {
self.connection_url = url.into();
self
}
pub fn exchanges<EIter>(mut self, exchanges: EIter) -> Self
where
EIter: IntoIterator<Item = ExchangeBuilder>,
{
self.exchanges
.extend(exchanges.into_iter().map(|e| e.build()));
self
}
pub fn handle(mut self, handle: Handle) -> Self {
self.handle = Some(handle);
self
}
pub fn build(self) -> Box<Future<Item = Client, Error = Error>> {
if self.handle.is_none() {
return Box::new(future::err(ErrorKind::NoHandle.into()));
}
let task = RabbitmqBroker::new_with_handle(
&self.connection_url,
self.exchanges,
vec![],
self.handle.unwrap(),
).and_then(|broker| Ok(Client { broker }));
Box::new(task)
}
}
#[derive(Debug)]
pub struct Client {
broker: RabbitmqBroker,
}
impl Client {
pub(crate) fn send(&self, job: &Job) -> Box<Future<Item = (), Error = Error>> {
let task = self.broker.send(job);
Box::new(task)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
#[test]
fn test_auto_impl_traits() {
assert_send::<Client>();
assert_sync::<Client>();
}
}