Skip to content

Commit bcbe750

Browse files
committed
Add performance counters gated by metrics feature
1 parent 3763e92 commit bcbe750

15 files changed

+225
-14
lines changed

Cargo.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pem = "1.0.1"
3030
percent-encoding = "2.1.0"
3131
pin-project = "1.0.2"
3232
priority-queue = "1"
33-
serde = "1"
33+
serde = { version = "1", features = ["derive", "rc"] }
3434
serde_json = "1"
3535
socket2 = "0.4.2"
3636
thiserror = "1.0.4"
@@ -96,6 +96,7 @@ default-rustls = [
9696
"derive",
9797
"rustls-tls",
9898
]
99+
metrics = []
99100
minimal = ["flate2/zlib"]
100101
native-tls-tls = ["native-tls", "tokio-native-tls"]
101102
rustls-tls = [

src/buffer_pool.rs

+22-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// option. All files in the project carrying such notice may not be copied,
77
// modified, or distributed except according to those terms.
88

9+
use crate::metrics::BufferPoolMetrics;
910
use crossbeam::queue::ArrayQueue;
1011
use std::{mem::replace, ops::Deref, sync::Arc};
1112

@@ -14,6 +15,7 @@ pub struct BufferPool {
1415
buffer_size_cap: usize,
1516
buffer_init_cap: usize,
1617
pool: ArrayQueue<Vec<u8>>,
18+
metrics: BufferPoolMetrics,
1719
}
1820

1921
impl BufferPool {
@@ -37,14 +39,21 @@ impl BufferPool {
3739
pool: ArrayQueue::new(pool_cap),
3840
buffer_size_cap,
3941
buffer_init_cap,
42+
metrics: Default::default(),
4043
}
4144
}
4245

4346
pub fn get(self: &Arc<Self>) -> PooledBuf {
44-
let buf = self
45-
.pool
46-
.pop()
47-
.unwrap_or_else(|| Vec::with_capacity(self.buffer_init_cap));
47+
let buf = match self.pool.pop() {
48+
Some(buf) => {
49+
self.metrics.reuses.incr();
50+
buf
51+
}
52+
None => {
53+
self.metrics.creations.incr();
54+
Vec::with_capacity(self.buffer_init_cap)
55+
}
56+
};
4857
debug_assert_eq!(buf.len(), 0);
4958
PooledBuf(buf, self.clone())
5059
}
@@ -64,7 +73,15 @@ impl BufferPool {
6473
buf.shrink_to(self.buffer_size_cap);
6574

6675
// ArrayQueue will make sure to drop the buffer if capacity is exceeded
67-
let _ = self.pool.push(buf);
76+
match self.pool.push(buf) {
77+
Ok(()) => self.metrics.returns.incr(),
78+
Err(_buf) => self.metrics.discards.incr(),
79+
};
80+
}
81+
82+
#[cfg(feature = "metrics")]
83+
pub(crate) fn snapshot_metrics(&self) -> BufferPoolMetrics {
84+
self.metrics.clone()
6885
}
6986
}
7087

src/conn/mod.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ use crate::{
3838
consts::{CapabilityFlags, Command, StatusFlags},
3939
error::*,
4040
io::Stream,
41+
metrics::ConnMetrics,
4142
opts::Opts,
4243
queryable::{
4344
query_result::{QueryResult, ResultSetMeta},
@@ -56,6 +57,8 @@ pub mod stmt_cache;
5657

5758
/// Helper that asynchronously disconnects the givent connection on the default tokio executor.
5859
fn disconnect(mut conn: Conn) {
60+
conn.metrics().disconnects.incr();
61+
5962
let disconnected = conn.inner.disconnected;
6063

6164
// Mark conn as disconnected.
@@ -116,6 +119,7 @@ struct ConnInner {
116119
/// One-time connection-level infile handler.
117120
infile_handler:
118121
Option<Pin<Box<dyn Future<Output = crate::Result<InfileData>> + Send + Sync + 'static>>>,
122+
conn_metrics: Arc<ConnMetrics>,
119123
}
120124

121125
impl fmt::Debug for ConnInner {
@@ -137,6 +141,7 @@ impl fmt::Debug for ConnInner {
137141
impl ConnInner {
138142
/// Constructs an empty connection.
139143
fn empty(opts: Opts) -> ConnInner {
144+
let conn_metrics: Arc<ConnMetrics> = Default::default();
140145
ConnInner {
141146
capabilities: opts.get_capabilities(),
142147
status: StatusFlags::empty(),
@@ -151,7 +156,7 @@ impl ConnInner {
151156
tx_status: TxStatus::None,
152157
last_io: Instant::now(),
153158
wait_timeout: Duration::from_secs(0),
154-
stmt_cache: StmtCache::new(opts.stmt_cache_size()),
159+
stmt_cache: StmtCache::new(opts.stmt_cache_size(), conn_metrics.clone()),
155160
socket: opts.socket().map(Into::into),
156161
opts,
157162
nonce: Vec::default(),
@@ -161,6 +166,7 @@ impl ConnInner {
161166
server_key: None,
162167
infile_handler: None,
163168
reset_upon_returning_to_a_pool: false,
169+
conn_metrics,
164170
}
165171
}
166172

@@ -172,6 +178,18 @@ impl ConnInner {
172178
.as_mut()
173179
.ok_or_else(|| DriverError::ConnectionClosed.into())
174180
}
181+
182+
fn set_pool(&mut self, pool: Option<Pool>) {
183+
let conn_metrics = if let Some(ref pool) = pool {
184+
Arc::clone(&pool.inner.metrics.conn)
185+
} else {
186+
Default::default()
187+
};
188+
self.conn_metrics = Arc::clone(&conn_metrics);
189+
self.stmt_cache.conn_metrics = conn_metrics;
190+
191+
self.pool = pool;
192+
}
175193
}
176194

177195
/// MySql server connection.
@@ -907,6 +925,8 @@ impl Conn {
907925
conn.read_wait_timeout().await?;
908926
conn.run_init_commands().await?;
909927

928+
conn.metrics().connects.incr();
929+
910930
Ok(conn)
911931
}
912932
.boxed()
@@ -1045,6 +1065,10 @@ impl Conn {
10451065
self.routine(routines::ChangeUser).await?;
10461066
self.inner.stmt_cache.clear();
10471067
self.inner.infile_handler = None;
1068+
// self.inner.set_pool(pool);
1069+
1070+
// TODO: clear some metrics?
1071+
10481072
Ok(())
10491073
}
10501074

@@ -1159,6 +1183,10 @@ impl Conn {
11591183

11601184
Ok(BinlogStream::new(self))
11611185
}
1186+
1187+
pub(crate) fn metrics(&self) -> &ConnMetrics {
1188+
&self.inner.conn_metrics
1189+
}
11621190
}
11631191

11641192
#[cfg(test)]

src/conn/pool/futures/get_conn.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,10 @@ impl Future for GetConn {
142142

143143
return match result {
144144
Ok(mut c) => {
145-
c.inner.pool = Some(pool);
145+
c.inner.set_pool(Some(pool));
146146
c.inner.reset_upon_returning_to_a_pool =
147147
self.reset_upon_returning_to_a_pool;
148+
c.metrics().connects.incr();
148149
Poll::Ready(Ok(c))
149150
}
150151
Err(e) => {
@@ -160,7 +161,8 @@ impl Future for GetConn {
160161
self.inner = GetConnInner::Done;
161162

162163
let pool = self.pool_take();
163-
c.inner.pool = Some(pool);
164+
pool.inner.metrics.reuses.incr();
165+
c.inner.set_pool(Some(pool));
164166
c.inner.reset_upon_returning_to_a_pool =
165167
self.reset_upon_returning_to_a_pool;
166168
return Poll::Ready(Ok(c));

src/conn/pool/mod.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use std::{
2525
use crate::{
2626
conn::{pool::futures::*, Conn},
2727
error::*,
28+
metrics::PoolMetrics,
2829
opts::{Opts, PoolOpts},
2930
queryable::transaction::{Transaction, TxOpts, TxStatus},
3031
};
@@ -177,6 +178,7 @@ pub struct Inner {
177178
close: atomic::AtomicBool,
178179
closed: atomic::AtomicBool,
179180
exchange: Mutex<Exchange>,
181+
pub(crate) metrics: PoolMetrics,
180182
}
181183

182184
/// Asynchronous pool of MySql connections.
@@ -190,7 +192,7 @@ pub struct Inner {
190192
#[derive(Debug, Clone)]
191193
pub struct Pool {
192194
opts: Opts,
193-
inner: Arc<Inner>,
195+
pub(super) inner: Arc<Inner>,
194196
drop: mpsc::UnboundedSender<Option<Conn>>,
195197
}
196198

@@ -219,6 +221,7 @@ impl Pool {
219221
exist: 0,
220222
recycler: Some((rx, pool_opts)),
221223
}),
224+
metrics: Default::default(),
222225
}),
223226
drop: tx,
224227
}
@@ -232,6 +235,7 @@ impl Pool {
232235

233236
/// Async function that resolves to `Conn`.
234237
pub fn get_conn(&self) -> GetConn {
238+
self.inner.metrics.gets.incr();
235239
GetConn::new(self, true)
236240
}
237241

@@ -249,6 +253,11 @@ impl Pool {
249253
DisconnectPool::new(self)
250254
}
251255

256+
#[cfg(feature = "metrics")]
257+
pub fn snapshot_metrics(&self) -> PoolMetrics {
258+
self.inner.metrics.clone()
259+
}
260+
252261
/// A way to return connection taken from a pool.
253262
fn return_conn(&mut self, conn: Conn) {
254263
// NOTE: we're not in async context here, so we can't block or return NotReady
@@ -264,18 +273,23 @@ impl Pool {
264273
{
265274
let mut exchange = self.inner.exchange.lock().unwrap();
266275
if exchange.available.len() < self.opts.pool_opts().active_bound() {
276+
self.inner.metrics.direct_returnals.incr();
267277
exchange.available.push_back(conn.into());
268278
if let Some(w) = exchange.waiting.pop() {
269279
w.wake();
270280
}
271281
return;
282+
} else {
283+
self.inner.metrics.discards.incr();
272284
}
273285
}
274286

275287
self.send_to_recycler(conn);
276288
}
277289

278290
fn send_to_recycler(&self, conn: Conn) {
291+
self.inner.metrics.recycler.recycles.incr();
292+
279293
if let Err(conn) = self.drop.send(Some(conn)) {
280294
let conn = conn.0.unwrap();
281295

src/conn/pool/recycler.rs

+5
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,10 @@ impl Future for Recycler {
6767
let mut exchange = $self.inner.exchange.lock().unwrap();
6868
if exchange.available.len() >= $self.pool_opts.active_bound() {
6969
drop(exchange);
70+
$self.inner.metrics.recycler.discards.incr();
7071
$self.discard.push($conn.close_conn().boxed());
7172
} else {
73+
$self.inner.metrics.recycler.recycled_returnals.incr();
7274
exchange.available.push_back($conn.into());
7375
if let Some(w) = exchange.waiting.pop() {
7476
w.wake();
@@ -80,11 +82,14 @@ impl Future for Recycler {
8082
macro_rules! conn_decision {
8183
($self:ident, $conn:ident) => {
8284
if $conn.inner.stream.is_none() || $conn.inner.disconnected {
85+
$self.inner.metrics.recycler.discards.incr();
8386
// drop unestablished connection
8487
$self.discard.push(futures_util::future::ok(()).boxed());
8588
} else if $conn.inner.tx_status != TxStatus::None || $conn.has_pending_result() {
89+
$self.inner.metrics.recycler.cleans.incr();
8690
$self.cleaning.push($conn.cleanup_for_pool().boxed());
8791
} else if $conn.expired() || close {
92+
$self.inner.metrics.recycler.discards.incr();
8893
$self.discard.push($conn.close_conn().boxed());
8994
} else if $conn.inner.reset_upon_returning_to_a_pool {
9095
$self.reset.push($conn.reset_for_pool().boxed());

src/conn/routines/exec.rs

+2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ impl<'a> ExecRoutine<'a> {
2525

2626
impl Routine<()> for ExecRoutine<'_> {
2727
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
28+
conn.metrics().routines.execs.incr();
29+
2830
#[cfg(feature = "tracing")]
2931
let span = info_span!(
3032
"mysql_async::exec",

src/conn/routines/next_set.rs

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ where
2424
P: Protocol,
2525
{
2626
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
27+
conn.metrics().routines.next_sets.incr();
28+
2729
#[cfg(feature = "tracing")]
2830
let span = debug_span!(
2931
"mysql_async::next_set",

src/conn/routines/ping.rs

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ pub struct PingRoutine;
1414

1515
impl Routine<()> for PingRoutine {
1616
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
17+
conn.metrics().routines.pings.incr();
18+
1719
#[cfg(feature = "tracing")]
1820
let span = debug_span!("mysql_async::ping", mysql_async.connection.id = conn.id());
1921

src/conn/routines/prepare.rs

+2
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ impl PrepareRoutine {
2626

2727
impl Routine<Arc<StmtInner>> for PrepareRoutine {
2828
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<Arc<StmtInner>>> {
29+
conn.metrics().routines.prepares.incr();
30+
2931
#[cfg(feature = "tracing")]
3032
let span = info_span!(
3133
"mysql_async::prepare",

src/conn/routines/query.rs

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ impl<'a, L: TracingLevel> QueryRoutine<'a, L> {
2929

3030
impl<L: TracingLevel> Routine<()> for QueryRoutine<'_, L> {
3131
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
32+
conn.metrics().routines.queries.incr();
33+
3234
#[cfg(feature = "tracing")]
3335
let span = create_span!(
3436
L::LEVEL,

src/conn/routines/reset.rs

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ pub struct ResetRoutine;
1414

1515
impl Routine<()> for ResetRoutine {
1616
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
17+
conn.metrics().routines.resets.incr();
18+
1719
#[cfg(feature = "tracing")]
1820
let span = debug_span!("mysql_async::reset", mysql_async.connection.id = conn.id());
1921

0 commit comments

Comments
 (0)