-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
261 lines (215 loc) · 6.21 KB
/
lib.rs
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
mod event;
use futures::select;
use futures::StreamExt;
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures_channel::oneshot::{channel, Sender};
pub use async_trait::async_trait;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Drop;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[async_trait]
pub trait Manager: Send + Sync + 'static {
type Connection: Send + Sync + 'static;
type Error: Debug + Send + Sync + 'static;
async fn connect(&self) -> std::result::Result<Self::Connection, Self::Error>;
}
#[async_trait]
pub trait Checker: Send {
type Connection: Send + Sync + 'static;
type Error: Debug + Send + Sync + 'static;
async fn check(&self, conn: &Self::Connection) -> std::result::Result<(), Self::Error>;
}
pub struct DummyChecker<C, E> {
c: PhantomData<C>,
e: PhantomData<E>,
}
impl<C, E> DummyChecker<C, E> {
fn new() -> Self {
Self {
c: PhantomData,
e: PhantomData,
}
}
}
#[async_trait]
impl<C, E> Checker for DummyChecker<C, E>
where
C: Sync + Send + 'static,
E: Debug + Send + Sync + 'static,
{
type Connection = C;
type Error = E;
async fn check(&self, conn: &C) -> std::result::Result<(), E> {
Ok(())
}
}
struct PoolBackend<M: Manager> {
requests: UnboundedReceiver<GetRequest<M>>,
idles: Vec<M::Connection>,
pendings: Vec<GetRequest<M>>,
num_open: i64,
max_open: i64,
}
impl<M: Manager> PoolBackend<M> {
fn new(max_open: i64, requests: UnboundedReceiver<GetRequest<M>>) -> Self {
Self {
requests,
idles: Vec::new(),
pendings: Vec::new(),
num_open: 0,
max_open,
}
}
async fn run(mut self, manager: M) -> Result<()> {
let mut requests = self.requests.fuse();
let (recycle_tx, recycle_rx) = unbounded::<M::Connection>();
let mut recycle = recycle_rx.fuse();
let (open_tx, open_rx) = unbounded::<()>();
let new_conns = recycle_tx.clone();
async_std::task::spawn(async move {
let worker = Worker::new(manager);
worker.run(open_rx, new_conns).await
});
macro_rules! respond_req {
() => {
while self.idles.len() > 0 && self.pendings.len() > 0 {
let pending = self.pendings.swap_remove(0);
let idle = self.idles.swap_remove(0);
let conn = Conn::<M>::new(idle, recycle_tx.clone());
pending.respond(conn);
}
};
}
macro_rules! maybe_open_conn {
() => {
let mut can_open = self.max_open - self.num_open;
let num_pendings = self.pendings.len() as i64;
if num_pendings < can_open {
can_open = num_pendings;
}
while can_open > 0 {
open_tx.unbounded_send(()).ok();
can_open -= 1;
self.num_open += 1;
}
};
}
loop {
respond_req!();
select! {
req = requests.next() => {
let req = req.unwrap();
self.pendings.push(req);
maybe_open_conn!();
},
conn = recycle.next() => {
let raw = conn.unwrap();
self.idles.push(raw);
respond_req!();
},
}
}
}
}
struct Worker<M: Manager> {
manager: M,
}
impl<M: Manager> Worker<M> {
fn new(manager: M) -> Self {
Self { manager }
}
async fn run(self, mut ch: UnboundedReceiver<()>, tx: UnboundedSender<M::Connection>) {
while let Some(_) = ch.next().await {
let raw = self.manager.connect().await.unwrap();
tx.unbounded_send(raw).unwrap();
}
}
}
pub struct Pool<
M: Manager,
C: Checker = DummyChecker<<M as Manager>::Connection, <M as Manager>::Error>,
> {
tx: UnboundedSender<GetRequest<M>>,
checker: Arc<C>,
}
impl<M: Manager> Pool<M> {
pub fn new(manager: M, max_open: i64) -> Self {
let (req_tx, req_rx) = unbounded();
let backend = PoolBackend::new(max_open, req_rx);
async_std::task::spawn(async move { backend.run(manager).await });
Self {
tx: req_tx,
checker: Arc::new(DummyChecker::new()),
}
}
}
impl<M: Manager, C> Pool<M, C>
where
C: Checker<Connection = M::Connection, Error = M::Error>,
{
pub async fn get(&self) -> Result<Conn<M>> {
let (tx, rx) = channel();
let req = GetRequest::new(tx);
// Fix me
self.tx.unbounded_send(req).ok();
let conn = rx.await?;
self.checker
.check(&conn.raw.as_ref().unwrap())
.await
.unwrap();
Ok(conn)
}
}
impl<M: Manager, C: Checker> Clone for Pool<M, C> {
fn clone(&self) -> Self {
Pool {
tx: self.tx.clone(),
checker: self.checker.clone(),
}
}
}
struct GetRequest<M: Manager> {
tx: Sender<Conn<M>>,
}
impl<M: Manager> GetRequest<M> {
fn new(tx: Sender<Conn<M>>) -> Self {
Self { tx }
}
fn respond(self, conn: Conn<M>) {
self.tx.send(conn).ok();
}
}
#[derive(Debug)]
pub struct Conn<M: Manager> {
raw: Option<M::Connection>,
recycle_ch: UnboundedSender<M::Connection>,
}
impl<M: Manager> Conn<M> {
fn new(raw: M::Connection, recycle_ch: UnboundedSender<M::Connection>) -> Self {
Self {
raw: Some(raw),
recycle_ch,
}
}
}
impl<M: Manager> Drop for Conn<M> {
fn drop(&mut self) {
if let Some(raw) = self.raw.take() {
self.recycle_ch.unbounded_send(raw).unwrap();
}
}
}
impl<M: Manager> Deref for Conn<M> {
type Target = M::Connection;
fn deref(&self) -> &Self::Target {
&self.raw.as_ref().unwrap()
}
}
impl<M: Manager> DerefMut for Conn<M> {
fn deref_mut(&mut self) -> &mut M::Connection {
self.raw.as_mut().unwrap()
}
}