use std::cell::RefCell;
use std::future::poll_fn;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::task::{Poll, Waker};
use std::time::Duration;
use giong::time::Instant;
use crate::client::{Client, Transaction};
use crate::config::Config;
use crate::error::{Error, ErrorKind};
use crate::row::Row;
use crate::types::ToSql;
const STALLED: Duration = Duration::from_millis(5);
#[derive(Clone)]
pub struct Pool {
inner: Rc<Inner>,
}
struct Inner {
config: Config,
max_size: usize,
wait_timeout: Duration,
state: RefCell<State>,
}
#[derive(Default)]
struct State {
shared: Vec<Rc<Client>>,
taken: usize,
connecting: usize,
waiting: usize,
waiters: Vec<Waker>,
opened: u64,
connect_errors: u64,
timeouts: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PoolStats {
pub connections: usize,
pub taken: usize,
pub connecting: usize,
pub in_flight: usize,
pub waiting: usize,
pub opened: u64,
pub connect_errors: u64,
pub timeouts: u64,
}
enum Decision<T> {
Ready(T),
Connect,
Wait,
}
struct Connecting<'a>(&'a Pool);
impl Drop for Connecting<'_> {
fn drop(&mut self) {
self.0.inner.state.borrow_mut().connecting -= 1;
self.0.notify();
}
}
struct Waiting<'a>(&'a Pool);
impl Drop for Waiting<'_> {
fn drop(&mut self) {
self.0.inner.state.borrow_mut().waiting -= 1;
}
}
impl Pool {
pub fn new(config: Config, max_size: usize) -> Self {
assert!(
max_size > 0,
"a pool needs room for at least one connection"
);
Self {
inner: Rc::new(Inner {
config,
max_size,
wait_timeout: Duration::from_secs(5),
state: RefCell::default(),
}),
}
}
pub fn wait_timeout(mut self, timeout: Duration) -> Self {
Rc::get_mut(&mut self.inner)
.expect("set the wait timeout before cloning the pool")
.wait_timeout = timeout;
self
}
pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
let client = self.shared().await?;
let result = client.query(sql, params).await;
self.release(client);
result
}
pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
let client = self.shared().await?;
let result = client.query_one(sql, params).await;
self.release(client);
result
}
pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
let client = self.shared().await?;
let result = client.query_opt(sql, params).await;
self.release(client);
result
}
pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
let client = self.shared().await?;
let result = client.execute(sql, params).await;
self.release(client);
result
}
pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
let client = self.shared().await?;
let result = client.batch_execute(sql).await;
self.release(client);
result
}
pub async fn get(&self) -> Result<PooledClient, Error> {
let client = self
.acquire(|st, max| {
let idle = st
.shared
.iter()
.position(|c| Rc::strong_count(c) == 1 && c.in_flight() == 0);
if let Some(i) = idle {
let c = st.shared.swap_remove(i);
st.taken += 1;
return match Rc::try_unwrap(c) {
Ok(client) => Decision::Ready(client),
Err(_) => unreachable!("checked: nobody else holds it"),
};
}
if st.shared.len() + st.taken + st.connecting < max {
st.connecting += 1;
Decision::Connect
} else {
Decision::Wait
}
})
.await?;
let client = match client {
Ok(c) => c,
Err(new) => {
self.inner.state.borrow_mut().taken += 1;
new
}
};
Ok(PooledClient {
client: Some(client),
pool: self.clone(),
})
}
pub fn stats(&self) -> PoolStats {
let st = self.inner.state.borrow();
PoolStats {
connections: st.shared.len() + st.taken,
taken: st.taken,
connecting: st.connecting,
in_flight: st.shared.iter().map(|c| c.in_flight()).sum(),
waiting: st.waiting,
opened: st.opened,
connect_errors: st.connect_errors,
timeouts: st.timeouts,
}
}
async fn shared(&self) -> Result<Rc<Client>, Error> {
let client = self
.acquire(|st, max| {
let now = Instant::now();
let room = st.shared.len() + st.taken + st.connecting < max;
let best = st
.shared
.iter()
.filter(|c| c.waiting_for(now) <= STALLED)
.min_by_key(|c| Rc::strong_count(c))
.cloned();
match best {
Some(c) if Rc::strong_count(&c) == 2 || !room => Decision::Ready(c),
_ if room => {
st.connecting += 1;
Decision::Connect
}
_ => match st.shared.iter().min_by_key(|c| c.waiting_for(now)) {
Some(c) => Decision::Ready(c.clone()),
None => Decision::Wait,
},
}
})
.await?;
Ok(match client {
Ok(c) => c,
Err(new) => {
let c = Rc::new(new);
self.inner.state.borrow_mut().shared.push(c.clone());
c
}
})
}
fn release(&self, client: Rc<Client>) {
drop(client);
self.notify();
}
fn notify(&self) {
let waiters = std::mem::take(&mut self.inner.state.borrow_mut().waiters);
for w in waiters {
w.wake();
}
}
async fn acquire<T>(
&self,
mut decide: impl FnMut(&mut State, usize) -> Decision<T>,
) -> Result<Result<T, Client>, Error> {
let deadline = Instant::now() + self.inner.wait_timeout;
loop {
let decision = {
let mut st = self.inner.state.borrow_mut();
st.shared.retain(|c| !c.is_closed());
decide(&mut st, self.inner.max_size)
};
match decision {
Decision::Ready(c) => return Ok(Ok(c)),
Decision::Connect => {
let _connecting = Connecting(self);
let result = Client::connect(&self.inner.config).await;
let mut st = self.inner.state.borrow_mut();
return match result {
Ok(client) => {
st.opened += 1;
Ok(Err(client))
}
Err(e) => {
st.connect_errors += 1;
Err(e)
}
};
}
Decision::Wait => {
self.inner.state.borrow_mut().waiting += 1;
let _waiting = Waiting(self);
let mut registered = false;
let woken = poll_fn(|cx| {
if registered {
return Poll::Ready(());
}
registered = true;
self.inner
.state
.borrow_mut()
.waiters
.push(cx.waker().clone());
Poll::Pending
});
let left = deadline.saturating_duration_since(Instant::now());
if giong::time::timeout(left, woken).await.is_err() {
let mut st = self.inner.state.borrow_mut();
st.timeouts += 1;
return Err(Error::new(
ErrorKind::PoolTimeout,
format!(
"no connection to {} became free within {:?}: all {} are taken or \
busy. Raise the pool's max_size (the server's max_connections \
allowing), look for transactions held open too long, or raise \
Pool::wait_timeout",
self.inner.config.target(),
self.inner.wait_timeout,
self.inner.max_size
),
));
}
}
}
}
}
}
impl std::fmt::Debug for Pool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pool")
.field("server", &self.inner.config.target())
.field("max_size", &self.inner.max_size)
.field("stats", &self.stats())
.finish()
}
}
pub struct PooledClient {
client: Option<Client>,
pool: Pool,
}
impl PooledClient {
pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
self.deref_mut().transaction().await
}
}
impl Deref for PooledClient {
type Target = Client;
fn deref(&self) -> &Client {
self.client.as_ref().expect("present until dropped")
}
}
impl DerefMut for PooledClient {
fn deref_mut(&mut self) -> &mut Client {
self.client.as_mut().expect("present until dropped")
}
}
impl Drop for PooledClient {
fn drop(&mut self) {
let client = self.client.take().expect("present until dropped");
{
let mut st = self.pool.inner.state.borrow_mut();
st.taken -= 1;
if !client.is_closed() {
if client.in_transaction() {
client.send_and_forget("ROLLBACK");
}
st.shared.push(Rc::new(client));
}
}
self.pool.notify();
}
}
impl std::fmt::Debug for PooledClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("PooledClient").field(&**self).finish()
}
}