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
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use std::{
sync::Arc,
time::{Duration, Instant},
};
use futures::prelude::*;
use redis::{aio::ConnectionLike, Cmd, ErrorKind, Pipeline, RedisError, RedisFuture, Value};
use tokio::time::timeout;
use crate::pools::pool_internal::Managed;
use crate::{config::DefaultCommandTimeout, Poolable};
/// A connection that has been taken from the pool.
///
/// The connection returns when dropped unless there was an error.
///
/// Pooled connection implements `redis::async::ConnectionLike`
/// to easily integrate with code that already uses `redis-rs`.
pub struct PoolConnection<T: Poolable = ConnectionFlavour> {
/// Track whether the connection is still in a valid state.
///
/// If a future gets cancelled it is likely that the connection
/// is not in a valid state anymore. For stateless connections this
/// field is useless.
pub(crate) connection_state_ok: bool,
pub(crate) managed: Option<Managed<T>>,
pub(crate) command_timeout: Option<Duration>,
}
impl<T: Poolable> PoolConnection<T> {
pub fn default_command_timeout<TO: Into<DefaultCommandTimeout>>(&mut self, timeout: TO) {
self.command_timeout = timeout.into().to_duration_opt();
}
fn get_connection(&mut self) -> Result<&mut T, IoError> {
let managed = if let Some(managed) = &mut self.managed {
managed
} else {
return Err(IoError::new(
IoErrorKind::ConnectionAborted,
"connection is broken due to a previous io error",
));
};
if let Some(connection) = managed.connection_mut() {
Ok(connection)
} else {
Err(IoError::new(
IoErrorKind::ConnectionAborted,
"inner connection is invalid. THIS IS A BUG!",
))
}
}
/// Invalidate the managed internal connection to prevent it from returning
/// to the pool and also immediately drop the invalidated managed connection to
/// trigger the creation of a new one
fn invalidate(&mut self) {
if let Some(mut managed) = self.managed.take() {
managed.invalidate()
}
self.managed = None;
}
}
impl<T: Poolable> ConnectionLike for PoolConnection<T>
where
T: ConnectionLike,
{
fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value> {
async move {
self.connection_state_ok = false;
let command_timeout = self.command_timeout;
let conn = self.get_connection()?;
let f = conn.req_packed_command(cmd);
let r = if let Some(command_timeout) = command_timeout {
let started = Instant::now();
match timeout(command_timeout, f).await {
Ok(r) => r,
Err(_) => {
let message = format!(
"command timeout after {:?} on `req_packed_command`.",
started.elapsed()
);
let err: RedisError =
(ErrorKind::IoError, "command timeout", message).into();
Err(err)
}
}
} else {
f.await
};
match r {
Ok(value) => {
self.connection_state_ok = true;
Ok(value)
}
Err(err) => {
match err.kind() {
// ErrorKind::ResponseError is a hack because the
// parsing files with 0 bytes and an unexpected EOF
// This behaviour need clarification.
// See https://github.com/mitsuhiko/redis-rs/issues/320
ErrorKind::IoError | ErrorKind::ResponseError => {
// TODO: Can we get a new connection?
self.invalidate();
}
_ => {
self.connection_state_ok = true;
}
}
Err(err)
}
}
}
.boxed()
}
fn req_packed_commands<'a>(
&'a mut self,
pipeline: &'a Pipeline,
offset: usize,
count: usize,
) -> RedisFuture<'a, Vec<Value>> {
async move {
self.connection_state_ok = false;
let command_timeout = self.command_timeout;
let conn = self.get_connection()?;
let f = conn.req_packed_commands(pipeline, offset, count);
let r = if let Some(command_timeout) = command_timeout {
let started = Instant::now();
match timeout(command_timeout, f).await {
Ok(r) => r,
Err(_) => {
let message = format!(
"command timeout after {:?} on `req_packed_commands`.",
started.elapsed()
);
let err: RedisError =
(ErrorKind::IoError, "command timeout", message).into();
Err(err)
}
}
} else {
f.await
};
match r {
Ok(values) => {
self.connection_state_ok = true;
Ok(values)
}
Err(err) => {
match err.kind() {
// ErrorKind::ResponseError is a hack because the
// parsing files with 0 bytes and an unexpected EOF
// This behaviour need clarification.
// See https://github.com/mitsuhiko/redis-rs/issues/320
ErrorKind::IoError | ErrorKind::ResponseError => {
// TODO: Can we get a new connection?
self.invalidate();
}
_ => {
self.connection_state_ok = true;
}
}
Err(err)
}
}
}
.boxed()
}
fn get_db(&self) -> i64 {
if let Some(conn) = self.managed.as_ref() {
conn.get_db()
} else {
-1
}
}
}
impl<T: Poolable> Drop for PoolConnection<T> {
fn drop(&mut self) {
if !self.connection_state_ok {
self.invalidate();
}
}
}
pub enum ConnectionFlavour {
RedisRs(redis::aio::Connection, Arc<String>),
// Tls(?)
}
impl Poolable for ConnectionFlavour {
fn connected_to(&self) -> &str {
match self {
ConnectionFlavour::RedisRs(_, c) => &c,
}
}
}
impl ConnectionLike for ConnectionFlavour {
fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value> {
match self {
ConnectionFlavour::RedisRs(conn, _uri) => conn.req_packed_command(cmd),
}
}
fn req_packed_commands<'a>(
&'a mut self,
pipeline: &'a Pipeline,
offset: usize,
count: usize,
) -> RedisFuture<'a, Vec<Value>> {
match self {
ConnectionFlavour::RedisRs(conn, _) => {
conn.req_packed_commands(pipeline, offset, count)
}
}
}
fn get_db(&self) -> i64 {
match self {
ConnectionFlavour::RedisRs(conn, _) => conn.get_db(),
}
}
}
impl<T: Poolable> ConnectionLike for Managed<T>
where
T: ConnectionLike,
{
fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value> {
async move {
let conn = match self.connection_mut() {
Some(conn) => conn,
None => {
return Err(
(ErrorKind::IoError, "no connection - this is a bug of reool").into(),
)
}
};
let value = conn.req_packed_command(cmd).await?;
Ok(value)
}
.boxed()
}
fn req_packed_commands<'a>(
&'a mut self,
pipeline: &'a Pipeline,
offset: usize,
count: usize,
) -> RedisFuture<'a, Vec<Value>> {
async move {
let conn = match self.connection_mut() {
Some(conn) => conn,
None => {
return Err(
(ErrorKind::IoError, "no connection - this is a bug of reool").into(),
)
}
};
let values = conn.req_packed_commands(pipeline, offset, count).await?;
Ok(values)
}
.boxed()
}
fn get_db(&self) -> i64 {
if let Some(conn) = self.connection() {
conn.get_db()
} else {
-1
}
}
}