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
#![feature(async_await)]

use diesel::{
    dsl::Limit,
    query_dsl::{
        methods::{ExecuteDsl, LimitDsl, LoadQuery},
        RunQueryDsl,
    },
    r2d2::{ConnectionManager, Pool},
    result::QueryResult,
    Connection,
};
use futures::{
    future::{poll_fn, BoxFuture},
    FutureExt, TryFutureExt,
};
use std::{error::Error as StdError, fmt};
use tokio_threadpool::BlockingError;

pub type AsyncResult<R> = Result<R, AsyncError>;

#[derive(Debug)]
pub enum AsyncError {
    // Attempt to run an async operation while not in a
    // tokio worker pool
    NotInPool(BlockingError),

    // Failed to checkout a connection
    Checkout(r2d2::Error),

    // The query failed in some way
    Error(diesel::result::Error),
}

// TODO: Forward displays
impl fmt::Display for AsyncError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

// TODO: Forward causes
impl StdError for AsyncError {}

pub trait AsyncConnection<Conn>
where
    Conn: 'static + Connection,
{
    fn run<R, Func>(&self, f: Func) -> BoxFuture<AsyncResult<R>>
    where
        R: 'static + Send,
        Func: 'static + FnOnce(&Conn) -> QueryResult<R> + Send;

    fn transaction<R, Func>(&self, f: Func) -> BoxFuture<AsyncResult<R>>
    where
        R: 'static + Send,
        Func: 'static + FnOnce(&Conn) -> QueryResult<R> + Send;
}

impl<Conn> AsyncConnection<Conn> for Pool<ConnectionManager<Conn>>
where
    Conn: 'static + Connection,
{
    #[inline]
    fn run<R, Func>(&self, f: Func) -> BoxFuture<AsyncResult<R>>
    where
        R: 'static + Send,
        Func: 'static + FnOnce(&Conn) -> QueryResult<R> + Send,
    {
        FutureExt::boxed(blocking(move || {
            let conn = self.get().map_err(AsyncError::Checkout)?;
            f(&*conn).map_err(AsyncError::Error)
        }))
    }

    #[inline]
    fn transaction<R, Func>(&self, f: Func) -> BoxFuture<AsyncResult<R>>
    where
        R: 'static + Send,
        Func: 'static + FnOnce(&Conn) -> QueryResult<R> + Send,
    {
        FutureExt::boxed(blocking(move || {
            let conn = self.get().map_err(AsyncError::Checkout)?;
            conn.transaction(|| f(&*conn)).map_err(AsyncError::Error)
        }))
    }
}

pub trait AsyncRunQueryDsl<Conn, AsyncConn>
where
    Conn: 'static + Connection,
{
    fn execute_async(self, asc: &AsyncConn) -> BoxFuture<AsyncResult<usize>>
    where
        Self: ExecuteDsl<Conn>;

    fn load_async<U>(self, asc: &AsyncConn) -> BoxFuture<AsyncResult<Vec<U>>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>;

    fn get_result_async<U>(self, asc: &AsyncConn) -> BoxFuture<AsyncResult<U>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>;

    fn get_results_async<U>(self, asc: &AsyncConn) -> BoxFuture<AsyncResult<Vec<U>>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>;

    fn first_async<U>(self, asc: &AsyncConn) -> BoxFuture<AsyncResult<U>>
    where
        U: 'static + Send,
        Self: LimitDsl,
        Limit<Self>: LoadQuery<Conn, U>;
}

impl<T, Conn> AsyncRunQueryDsl<Conn, Pool<ConnectionManager<Conn>>> for T
where
    T: 'static + Send + RunQueryDsl<Conn>,
    Conn: 'static + Connection,
{
    fn execute_async(self, asc: &Pool<ConnectionManager<Conn>>) -> BoxFuture<AsyncResult<usize>>
    where
        Self: ExecuteDsl<Conn>,
    {
        asc.run(|conn| self.execute(&*conn))
    }

    fn load_async<U>(self, asc: &Pool<ConnectionManager<Conn>>) -> BoxFuture<AsyncResult<Vec<U>>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>,
    {
        asc.run(|conn| self.load(&*conn))
    }

    fn get_result_async<U>(self, asc: &Pool<ConnectionManager<Conn>>) -> BoxFuture<AsyncResult<U>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>,
    {
        asc.run(|conn| self.get_result(&*conn))
    }

    fn get_results_async<U>(
        self,
        asc: &Pool<ConnectionManager<Conn>>,
    ) -> BoxFuture<AsyncResult<Vec<U>>>
    where
        U: 'static + Send,
        Self: LoadQuery<Conn, U>,
    {
        asc.run(|conn| self.get_results(&*conn))
    }

    fn first_async<U>(self, asc: &Pool<ConnectionManager<Conn>>) -> BoxFuture<AsyncResult<U>>
    where
        U: 'static + Send,
        Self: LimitDsl,
        Limit<Self>: LoadQuery<Conn, U>,
    {
        asc.run(|conn| self.first(&*conn))
    }
}

// Convert a `Poll` from futures v0.1 to a `Poll` from futures v0.3
// https://github.com/rust-lang-nursery/futures-rs/blob/526259e3e25e65cc32653f6a8e0244db2faccb2e/futures-util/src/compat/compat01as03.rs#L135
fn poll_01_to_03<T, E>(x: Result<futures01::Async<T>, E>) -> futures::task::Poll<Result<T, E>> {
    match x? {
        futures01::Async::Ready(t) => futures::task::Poll::Ready(Ok(t)),
        futures01::Async::NotReady => futures::task::Poll::Pending,
    }
}

// Run a closure with blocking IO
async fn blocking<R, F>(f: F) -> AsyncResult<R>
where
    R: Send,
    F: FnOnce() -> AsyncResult<R>,
{
    let mut f = Some(f);
    Ok(poll_fn(move |_| {
        poll_01_to_03(tokio_threadpool::blocking(|| {
            (f.take().expect("call FnOnce more than once"))()
        }))
    })
    .map_err(AsyncError::NotInPool)
    .unwrap_or_else(|err| Err(err))
    .await?)
}