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
use error::Error::{self, ArgumentError, OperationError};
use error::Result;
use Client;
use coll::options::FindOptions;
use command_type::CommandType;
use connstring::Host;
use cursor::Cursor;
use stream::{Stream, StreamConnector};
use wire_protocol::flags::OpQueryFlags;
use bufstream::BufStream;
use std::fmt;
use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
pub static DEFAULT_POOL_SIZE: usize = 5;
#[derive(Clone)]
pub struct ConnectionPool {
pub host: Host,
inner: Arc<Mutex<Pool>>,
wait_lock: Arc<Condvar>,
stream_connector: StreamConnector,
}
impl fmt::Debug for ConnectionPool {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ConnectionPool")
.field("host", &self.host)
.finish()
}
}
struct Pool {
pub size: usize,
pub len: Arc<AtomicUsize>,
sockets: Vec<BufStream<Stream>>,
iteration: usize,
}
pub struct PooledStream {
socket: Option<BufStream<Stream>>,
pool: Arc<Mutex<Pool>>,
wait_lock: Arc<Condvar>,
iteration: usize,
successful_handshake: bool,
}
impl PooledStream {
pub fn get_socket(&mut self) -> &mut BufStream<Stream> {
self.socket.as_mut().unwrap()
}
}
impl Drop for PooledStream {
fn drop(&mut self) {
if !self.successful_handshake {
return;
}
if let Ok(mut locked) = self.pool.lock() {
if self.iteration == locked.iteration {
locked.sockets.push(self.socket.take().unwrap());
self.wait_lock.notify_one();
}
}
}
}
impl ConnectionPool {
pub fn new(host: Host, connector: StreamConnector) -> ConnectionPool {
ConnectionPool::with_size(host, connector, DEFAULT_POOL_SIZE)
}
pub fn with_size(host: Host, connector: StreamConnector, size: usize) -> ConnectionPool {
ConnectionPool {
host: host,
wait_lock: Arc::new(Condvar::new()),
inner: Arc::new(Mutex::new(Pool {
len: Arc::new(ATOMIC_USIZE_INIT),
size: size,
sockets: Vec::with_capacity(size),
iteration: 0,
})),
stream_connector: connector,
}
}
pub fn set_size(&self, size: usize) -> Result<()> {
if size < 1 {
Err(ArgumentError(String::from(
"The connection pool size must be greater than zero.",
)))
} else {
let mut locked = self.inner.lock()?;
locked.size = size;
Ok(())
}
}
pub fn clear(&self) {
if let Ok(mut locked) = self.inner.lock() {
locked.iteration += 1;
locked.sockets.clear();
locked.len.store(0, Ordering::SeqCst);
}
}
pub fn acquire_stream(&self, client: Client) -> Result<PooledStream> {
let mut locked = self.inner.lock()?;
if locked.size == 0 {
return Err(OperationError(String::from(
"The connection pool does not allow connections; increase the size of the pool.",
)));
}
loop {
if let Some(stream) = locked.sockets.pop() {
return Ok(PooledStream {
socket: Some(stream),
pool: self.inner.clone(),
wait_lock: self.wait_lock.clone(),
iteration: locked.iteration,
successful_handshake: true,
});
}
let len = locked.len.load(Ordering::SeqCst);
if len < locked.size {
let socket = self.connect()?;
let mut stream = PooledStream {
socket: Some(socket),
pool: self.inner.clone(),
wait_lock: self.wait_lock.clone(),
iteration: locked.iteration,
successful_handshake: false,
};
self.handshake(client, &mut stream)?;
let _ = locked.len.fetch_add(1, Ordering::SeqCst);
return Ok(stream);
}
locked = self.wait_lock.wait(locked)?;
}
}
fn connect(&self) -> Result<BufStream<Stream>> {
match self.stream_connector.connect(
&self.host.host_name[..],
self.host.port,
) {
Ok(s) => Ok(BufStream::new(s)),
Err(e) => Err(Error::from(e)),
}
}
fn handshake(&self, client: Client, stream: &mut PooledStream) -> Result<()> {
let mut options = FindOptions::new();
options.limit = Some(1);
options.batch_size = Some(1);
let flags = OpQueryFlags::with_find_options(&options);
Cursor::query_with_stream(
stream,
client,
String::from("local.$cmd"),
flags,
doc! {
"isMaster": 1i32,
"client": {
"driver": {
"name": ::DRIVER_NAME,
"version": env!("CARGO_PKG_VERSION"),
},
"os": {
"type": ::std::env::consts::OS,
"architecture": ::std::env::consts::ARCH
}
},
},
options,
CommandType::IsMaster,
false,
None,
)?;
stream.successful_handshake = true;
Ok(())
}
}