Skip to content

Make the Waitlist responsible for calling wake #367

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/conn/pool/futures/disconnect_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use futures_core::ready;
use tokio::sync::mpsc::UnboundedSender;

use crate::{
conn::pool::{Inner, Pool, QUEUE_END_ID},
conn::pool::{waitlist::QUEUE_END_ID, Inner, Pool},
error::Error,
Conn,
};
Expand Down
2 changes: 1 addition & 1 deletion src/conn/pool/futures/get_conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use {

use crate::{
conn::{
pool::{Pool, QueueId},
pool::{waitlist::QueueId, Pool},
Conn,
},
error::*,
Expand Down
140 changes: 9 additions & 131 deletions src/conn/pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,13 @@
// modified, or distributed except according to those terms.

use futures_util::FutureExt;
use keyed_priority_queue::KeyedPriorityQueue;
use tokio::sync::mpsc;

use std::{
borrow::Borrow,
cmp::Reverse,
collections::VecDeque,
hash::{Hash, Hasher},
str::FromStr,
sync::{atomic, Arc, Mutex},
task::{Context, Poll, Waker},
task::{Context, Poll},
time::{Duration, Instant},
};

Expand All @@ -29,12 +25,14 @@ use crate::{
};

pub use metrics::Metrics;
use waitlist::{QueueId, Waitlist};

mod recycler;
// this is a really unfortunate name for a module
pub mod futures;
mod metrics;
mod ttl_check_inerval;
mod waitlist;

/// Connection that is idling in the pool.
#[derive(Debug)]
Expand Down Expand Up @@ -104,86 +102,6 @@ impl Exchange {
}
}

#[derive(Default, Debug)]
struct Waitlist {
queue: KeyedPriorityQueue<QueuedWaker, QueueId>,
}

impl Waitlist {
/// Returns `true` if pushed.
fn push(&mut self, waker: Waker, queue_id: QueueId) -> bool {
// The documentation of Future::poll says:
// Note that on multiple calls to poll, only the Waker from
// the Context passed to the most recent call should be
// scheduled to receive a wakeup.
//
// But the the documentation of KeyedPriorityQueue::push says:
// Adds new element to queue if missing key or replace its
// priority if key exists. In second case doesn’t replace key.
//
// This means we have to remove first to have the most recent
// waker in the queue.
let occupied = self.remove(queue_id);
self.queue.push(QueuedWaker { queue_id, waker }, queue_id);
!occupied
}

fn pop(&mut self) -> Option<Waker> {
match self.queue.pop() {
Some((qw, _)) => Some(qw.waker),
None => None,
}
}

/// Returns `true` if removed.
fn remove(&mut self, id: QueueId) -> bool {
self.queue.remove(&id).is_some()
}

fn peek_id(&mut self) -> Option<QueueId> {
self.queue.peek().map(|(qw, _)| qw.queue_id)
}
}

const QUEUE_END_ID: QueueId = QueueId(Reverse(u64::MAX));

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub(crate) struct QueueId(Reverse<u64>);

impl QueueId {
fn next() -> Self {
static NEXT_QUEUE_ID: atomic::AtomicU64 = atomic::AtomicU64::new(0);
let id = NEXT_QUEUE_ID.fetch_add(1, atomic::Ordering::SeqCst);
QueueId(Reverse(id))
}
}

#[derive(Debug)]
struct QueuedWaker {
queue_id: QueueId,
waker: Waker,
}

impl Eq for QueuedWaker {}

impl Borrow<QueueId> for QueuedWaker {
fn borrow(&self) -> &QueueId {
&self.queue_id
}
}

impl PartialEq for QueuedWaker {
fn eq(&self, other: &Self) -> bool {
self.queue_id == other.queue_id
}
}

impl Hash for QueuedWaker {
fn hash<H: Hasher>(&self, state: &mut H) {
self.queue_id.hash(state)
}
}

/// Connection pool data.
#[derive(Debug)]
pub struct Inner {
Expand Down Expand Up @@ -310,9 +228,7 @@ impl Pool {
.connection_count
.store(exchange.exist, atomic::Ordering::Relaxed);
// we just enabled the creation of a new connection!
if let Some(w) = exchange.waiting.pop() {
w.wake();
}
exchange.waiting.wake();
}

/// Poll the pool for an available connection.
Expand Down Expand Up @@ -474,20 +390,16 @@ mod test {
use waker_fn::waker_fn;

use std::{
cmp::Reverse,
future::Future,
pin::pin,
sync::{Arc, OnceLock},
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
task::{Context, Poll},
time::Duration,
};

use crate::{
conn::pool::{Pool, QueueId, Waitlist, QUEUE_END_ID},
opts::PoolOpts,
prelude::*,
test_misc::get_opts,
PoolConstraints, Row, TxOpts, Value,
conn::pool::Pool, opts::PoolOpts, prelude::*, test_misc::get_opts, PoolConstraints, Row,
TxOpts, Value,
};

macro_rules! conn_ex_field {
Expand Down Expand Up @@ -1016,7 +928,7 @@ mod test {
}
drop(only_conn);

assert_eq!(0, pool.inner.exchange.lock().unwrap().waiting.queue.len());
assert_eq!(0, pool.inner.exchange.lock().unwrap().waiting.len());
// metrics should catch up with waiting queue (see #335)
assert_eq!(
0,
Expand Down Expand Up @@ -1070,40 +982,6 @@ mod test {
Ok(())
}

#[test]
fn waitlist_integrity() {
const DATA: *const () = &();
const NOOP_CLONE_FN: unsafe fn(*const ()) -> RawWaker = |_| RawWaker::new(DATA, &RW_VTABLE);
const NOOP_FN: unsafe fn(*const ()) = |_| {};
static RW_VTABLE: RawWakerVTable =
RawWakerVTable::new(NOOP_CLONE_FN, NOOP_FN, NOOP_FN, NOOP_FN);
let w = unsafe { Waker::from_raw(RawWaker::new(DATA, &RW_VTABLE)) };

let mut waitlist = Waitlist::default();
assert_eq!(0, waitlist.queue.len());

waitlist.push(w.clone(), QueueId(Reverse(4)));
waitlist.push(w.clone(), QueueId(Reverse(2)));
waitlist.push(w.clone(), QueueId(Reverse(8)));
waitlist.push(w.clone(), QUEUE_END_ID);
waitlist.push(w.clone(), QueueId(Reverse(10)));

waitlist.remove(QueueId(Reverse(8)));

assert_eq!(4, waitlist.queue.len());

let (_, id) = waitlist.queue.pop().unwrap();
assert_eq!(2, id.0 .0);
let (_, id) = waitlist.queue.pop().unwrap();
assert_eq!(4, id.0 .0);
let (_, id) = waitlist.queue.pop().unwrap();
assert_eq!(10, id.0 .0);
let (_, id) = waitlist.queue.pop().unwrap();
assert_eq!(QUEUE_END_ID, id);

assert_eq!(0, waitlist.queue.len());
}

#[tokio::test]
async fn check_absolute_connection_ttl() -> super::Result<()> {
let constraints = PoolConstraints::new(1, 3).unwrap();
Expand Down Expand Up @@ -1185,7 +1063,7 @@ mod test {

let queue_len = || {
let exchange = pool.inner.exchange.lock().unwrap();
exchange.waiting.queue.len()
exchange.waiting.len()
};

// Get a connection, so we know the next futures will be
Expand Down
89 changes: 40 additions & 49 deletions src/conn/pool/recycler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,36 @@ impl Recycler {
eof: false,
}
}

fn conn_return(&mut self, conn: Conn, pool_is_closed: bool) {
let mut exchange = self.inner.exchange.lock().unwrap();
if pool_is_closed || exchange.available.len() >= self.pool_opts.active_bound() {
drop(exchange);
self.inner
.metrics
.discarded_superfluous_connection
.fetch_add(1, Ordering::Relaxed);
self.discard.push(conn.close_conn().boxed());
} else {
self.inner
.metrics
.connection_returned_to_pool
.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "hdrhistogram")]
self.inner
.metrics
.connection_active_duration
.lock()
.unwrap()
.saturating_record(conn.inner.active_since.elapsed().as_micros() as u64);
exchange.available.push_back(conn.into());
self.inner
.metrics
.connections_in_pool
.store(exchange.available.len(), Ordering::Relaxed);
exchange.waiting.wake();
}
}
}

impl Future for Recycler {
Expand All @@ -62,44 +92,6 @@ impl Future for Recycler {
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut close = self.inner.close.load(Ordering::Acquire);

macro_rules! conn_return {
($self:ident, $conn:ident, $pool_is_closed: expr) => {{
let mut exchange = $self.inner.exchange.lock().unwrap();
if $pool_is_closed || exchange.available.len() >= $self.pool_opts.active_bound() {
drop(exchange);
$self
.inner
.metrics
.discarded_superfluous_connection
.fetch_add(1, Ordering::Relaxed);
$self.discard.push($conn.close_conn().boxed());
} else {
$self
.inner
.metrics
.connection_returned_to_pool
.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "hdrhistogram")]
$self
.inner
.metrics
.connection_active_duration
.lock()
.unwrap()
.saturating_record($conn.inner.active_since.elapsed().as_micros() as u64);
exchange.available.push_back($conn.into());
$self
.inner
.metrics
.connections_in_pool
.store(exchange.available.len(), Ordering::Relaxed);
if let Some(w) = exchange.waiting.pop() {
w.wake();
}
}
}};
}

macro_rules! conn_decision {
($self:ident, $conn:ident) => {
if $conn.inner.stream.is_none() || $conn.inner.disconnected {
Expand Down Expand Up @@ -132,7 +124,7 @@ impl Future for Recycler {
.fetch_add(1, Ordering::Relaxed);
$self.reset.push($conn.reset_for_pool().boxed());
} else {
conn_return!($self, $conn, false);
$self.conn_return($conn, false);
}
};
}
Expand Down Expand Up @@ -165,9 +157,12 @@ impl Future for Recycler {

// if we've been asked to close, reclaim any idle connections
if close || self.eof {
while let Some(IdlingConn { conn, .. }) =
self.inner.exchange.lock().unwrap().available.pop_front()
{
loop {
let Some(IdlingConn { conn, .. }) =
self.inner.exchange.lock().unwrap().available.pop_front()
else {
break;
};
assert!(conn.inner.pool.is_none());
conn_decision!(self, conn);
}
Expand Down Expand Up @@ -199,7 +194,7 @@ impl Future for Recycler {
loop {
match Pin::new(&mut self.reset).poll_next(cx) {
Poll::Pending | Poll::Ready(None) => break,
Poll::Ready(Some(Ok(conn))) => conn_return!(self, conn, close),
Poll::Ready(Some(Ok(conn))) => self.conn_return(conn, close),
Poll::Ready(Some(Err(e))) => {
// an error during reset.
// replace with a new connection
Expand Down Expand Up @@ -247,9 +242,7 @@ impl Future for Recycler {
.connection_count
.store(exchange.exist, Ordering::Relaxed);
for _ in 0..self.discarded {
if let Some(w) = exchange.waiting.pop() {
w.wake();
}
exchange.waiting.wake();
}
drop(exchange);
self.discarded = 0;
Expand Down Expand Up @@ -285,9 +278,7 @@ impl Future for Recycler {
if self.inner.closed.load(Ordering::Acquire) {
// `DisconnectPool` might still wait to be woken up.
let mut exchange = self.inner.exchange.lock().unwrap();
while let Some(w) = exchange.waiting.pop() {
w.wake();
}
while exchange.waiting.wake() {}
// we're about to exit, so there better be no outstanding connections
assert_eq!(exchange.exist, 0);
assert_eq!(exchange.available.len(), 0);
Expand Down
Loading
Loading