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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use crate::db::{ConnectOptions, Connection, Driver, ExecResult, Row};
use crate::Error;
use async_trait::async_trait;
use deadpool::managed::{
    Manager, Object, PoolBuilder, PoolError, RecycleError, RecycleResult, Timeouts,
};
use deadpool::Status;
use futures_core::future::BoxFuture;
use rbs::Value;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::time::Duration;

/// RBDC pool.
/// you can use just like any deadpool methods  pool.deref().close() and more...
#[derive(Clone)]
pub struct Pool {
    pub manager: ManagerPorxy,
    pub inner: deadpool::managed::Pool<ManagerPorxy>,
}

impl Pool {
    /// return driver name
    pub fn driver_type(&self) -> &str {
        self.manager.driver_type()
    }

    /// spawn task on runtime
    pub fn spawn_task<T>(&self, task: T)
    where
        T: Future + Send + 'static,
        T::Output: Send + 'static,
    {
        self.manager.spawn_task(task)
    }

    /**
     * Resize the pool. This change the `max_size` of the pool dropping
     * excess objects and/or making space for new ones.
     *
     * If the pool is closed this method does nothing. The [`Pool::status`] method
     * always reports a `max_size` of 0 for closed pools.
     */
    pub fn resize(&self, max_size: usize) {
        self.deref().resize(max_size);
    }

    /// Indicates whether this [`Pool`] has been closed.
    pub fn is_closed(&self) -> bool {
        self.deref().is_closed()
    }

    /// Closes this Pool.
    /// All current and future tasks waiting for Objects will return PoolError::Closed immediately.
    /// This operation resizes the pool to 0.
    pub fn close(&self) {
        self.deref().close();
    }

    /// Retrieves Status of this Pool.
    pub fn status(&self) -> Status {
        self.deref().status()
    }

    ///Get current timeout configuration
    pub fn timeouts(&self) -> Timeouts {
        self.deref().timeouts()
    }

    /// get connection
    pub async fn get(&self) -> Result<Object<ManagerPorxy>, PoolError<Error>> {
        self.deref().get().await
    }

    /// try get connection
    pub async fn try_get(&self) -> Result<Object<ManagerPorxy>, PoolError<Error>> {
        let mut t = self.deref().timeouts();
        t.wait = Some(Duration::ZERO);
        self.deref().timeout_get(&t).await
    }
}

impl Debug for Pool {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pool")
            .field("manager", &self.manager)
            .finish()
    }
}

#[derive(Clone, Debug)]
pub struct ManagerPorxy {
    pub inner: Arc<RBDCManager>,
}

impl ManagerPorxy {
    /// spawn task on runtime
    pub fn spawn_task<T>(&self, task: T)
    where
        T: Future + Send + 'static,
        T::Output: Send + 'static,
    {
        tokio::spawn(task);
    }
}

impl From<Arc<RBDCManager>> for ManagerPorxy {
    fn from(arg: Arc<RBDCManager>) -> Self {
        ManagerPorxy { inner: arg }
    }
}

impl Deref for ManagerPorxy {
    type Target = RBDCManager;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

#[derive(Debug)]
pub struct RBDCManager {
    pub driver: Box<dyn Driver>,
    pub option: Box<dyn ConnectOptions>,
}

pub struct DropBox {
    pub manager_proxy: ManagerPorxy,
    pub conn: Option<Box<dyn Connection>>,
}

impl Deref for DropBox {
    type Target = Box<dyn Connection>;

    fn deref(&self) -> &Self::Target {
        self.conn.as_ref().unwrap()
    }
}

impl DerefMut for DropBox {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.conn.as_mut().unwrap()
    }
}

impl Drop for DropBox {
    fn drop(&mut self) {
        if let Some(mut conn) = self.conn.take() {
            self.manager_proxy.spawn_task(async move {
                let _ = conn.close().await;
            });
        }
    }
}

#[async_trait]
impl Manager for ManagerPorxy {
    type Type = DropBox;
    type Error = Error;

    async fn create(&self) -> Result<Self::Type, Self::Error> {
        Ok(DropBox {
            manager_proxy: self.clone(),
            conn: Some(self.driver.connect_opt(self.option.as_ref()).await?),
        })
    }

    async fn recycle(&self, conn: &mut Self::Type) -> RecycleResult<Self::Error> {
        match conn.ping().await {
            Ok(_) => Ok(()),
            Err(e) => {
                //shutdown connection
                if let Some(mut conn) = conn.conn.take() {
                    let _ = conn.close().await;
                }
                return Err(RecycleError::Message(format!(
                    "Connection is ping fail={}",
                    e
                )));
            }
        }
    }
}

impl RBDCManager {
    pub fn new<D: Driver + 'static>(driver: D, url: &str) -> Result<Self, Error> {
        let mut option = driver.default_option();
        option.set_uri(url)?;
        Ok(Self {
            driver: Box::new(driver),
            option: option,
        })
    }
    pub fn new_opt<D: Driver + 'static, Option: ConnectOptions>(driver: D, option: Option) -> Self {
        Self {
            driver: Box::new(driver),
            option: Box::new(option),
        }
    }

    pub fn new_opt_box(driver: Box<dyn Driver>, option: Box<dyn ConnectOptions>) -> Self {
        Self {
            driver: driver,
            option: option,
        }
    }

    pub fn driver_type(&self) -> &str {
        self.driver.name()
    }
}

impl Deref for Pool {
    type Target = deadpool::managed::Pool<ManagerPorxy>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Pool {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl Pool {
    pub fn new_url<Driver: crate::db::Driver + 'static>(
        d: Driver,
        url: &str,
    ) -> Result<Self, Error> {
        let manager = ManagerPorxy::from(Arc::new(RBDCManager::new(d, url)?));
        let p = Pool::builder(manager.clone())
            .build()
            .map_err(|e| Error::from(e.to_string()))?;
        let pool = Pool {
            manager: manager,
            inner: p,
        };
        Ok(pool)
    }
    pub fn new<Driver: crate::db::Driver + 'static, ConnectOptions: crate::db::ConnectOptions>(
        d: Driver,
        o: ConnectOptions,
    ) -> Result<Self, Error> {
        let manager = ManagerPorxy::from(Arc::new(RBDCManager::new_opt(d, o)));
        let inner = Pool::builder(manager.clone())
            .build()
            .map_err(|e| Error::from(e.to_string()))?;
        Ok(Pool {
            manager: manager,
            inner: inner,
        })
    }

    pub fn new_box(d: Box<dyn Driver>, o: Box<dyn ConnectOptions>) -> Result<Self, Error> {
        let manager = ManagerPorxy::from(Arc::new(RBDCManager::new_opt_box(d, o)));
        let inner = Pool::builder(manager.clone())
            .build()
            .map_err(|e| Error::from(e.to_string()))?;
        Ok(Pool {
            manager: manager,
            inner: inner,
        })
    }

    pub fn new_builder(
        builder: PoolBuilder<ManagerPorxy, Object<ManagerPorxy>>,
        d: Box<dyn Driver>,
        o: Box<dyn ConnectOptions>,
    ) -> Result<Self, Error> {
        let manager = ManagerPorxy::from(Arc::new(RBDCManager::new_opt_box(d, o)));
        Ok(Pool {
            manager: manager,
            inner: builder.build().map_err(|e| Error::from(e.to_string()))?,
        })
    }

    pub fn builder(m: ManagerPorxy) -> PoolBuilder<ManagerPorxy, Object<ManagerPorxy>> {
        deadpool::managed::Pool::builder(m)
    }
}

impl Connection for Object<ManagerPorxy> {
    fn get_rows(
        &mut self,
        sql: &str,
        params: Vec<Value>,
    ) -> BoxFuture<Result<Vec<Box<dyn Row>>, Error>> {
        self.deref_mut().get_rows(sql, params)
    }

    fn exec(&mut self, sql: &str, params: Vec<Value>) -> BoxFuture<Result<ExecResult, Error>> {
        self.deref_mut().exec(sql, params)
    }

    fn close(&mut self) -> BoxFuture<Result<(), Error>> {
        self.deref_mut().close()
    }

    fn ping(&mut self) -> BoxFuture<Result<(), Error>> {
        self.deref_mut().ping()
    }
}

#[test]
fn test_pool() {}