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: Rc<RefCell<State>>,
_observed: Rc<Observed>,
}
struct Observed {
name: String,
max_size: usize,
state: Rc<RefCell<State>>,
}
impl giong::observe::Source for Observed {
fn kind(&self) -> &'static str {
"postgres pool"
}
fn name(&self) -> String {
self.name.clone()
}
fn stats(&self) -> Vec<(&'static str, u64)> {
let s = stats_of(&self.state.borrow());
let n = |v: usize| v as u64;
vec![
("max_size", n(self.max_size)),
("connections", n(s.connections)),
("taken", n(s.taken)),
("connecting", n(s.connecting)),
("in_flight", n(s.in_flight)),
("waiting", n(s.waiting)),
("opened", s.opened),
("connect_errors", s.connect_errors),
("timeouts", s.timeouts),
]
}
}
fn stats_of(st: &State) -> PoolStats {
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,
}
}
#[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"
);
let state = Rc::new(RefCell::default());
let observed = Rc::new(Observed {
name: config.describe(),
max_size,
state: Rc::clone(&state),
});
giong::observe::register_rc(&observed);
Self {
inner: Rc::new(Inner {
config,
max_size,
wait_timeout: Duration::from_secs(5),
state,
_observed: observed,
}),
}
}
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> {
refuse_transaction(sql)?;
let client = self.shared().await?;
client.query(sql, params).await
}
pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
refuse_transaction(sql)?;
let client = self.shared().await?;
client.query_one(sql, params).await
}
pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
refuse_transaction(sql)?;
let client = self.shared().await?;
client.query_opt(sql, params).await
}
pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
refuse_transaction(sql)?;
let client = self.shared().await?;
client.execute(sql, params).await
}
pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
let client = self.shared().await?;
client.batch_execute(sql).await
}
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) => {
client.set_shared(false);
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 {
stats_of(&self.inner.state.borrow())
}
async fn shared(&self) -> Result<Lent<'_>, 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?;
let client = match client {
Ok(c) => c,
Err(new) => {
new.set_shared(true);
let c = Rc::new(new);
self.inner.state.borrow_mut().shared.push(c.clone());
c
}
};
Ok(Lent {
pool: self,
client: Some(client),
})
}
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;
let mut st = self.inner.state.borrow_mut();
st.waiters.push(cx.waker().clone());
for c in &st.shared {
if Rc::strong_count(c) == 1 && c.in_flight() > 0 {
c.wake_when_idle(cx.waker());
}
}
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
),
));
}
}
}
}
}
}
struct Lent<'a> {
pool: &'a Pool,
client: Option<Rc<Client>>,
}
impl Deref for Lent<'_> {
type Target = Client;
fn deref(&self) -> &Client {
self.client.as_ref().expect("present until dropped")
}
}
impl Drop for Lent<'_> {
fn drop(&mut self) {
self.client = None;
self.pool.notify();
}
}
fn refuse_transaction(sql: &str) -> Result<(), Error> {
let words = leading_words(sql);
let word = |i: usize| words.get(i).map_or("", String::as_str);
let refused = match word(0) {
"BEGIN" | "START" | "END" | "ABORT" | "SAVEPOINT" | "RELEASE" => true,
"COMMIT" | "ROLLBACK" => word(1) != "PREPARED",
"PREPARE" => word(1) == "TRANSACTION",
_ => false,
};
if !refused {
return Ok(());
}
Err(Error::new(
ErrorKind::Statement,
format!(
"{} controls a transaction, and the pool's own methods run statements on \
connections that other tasks share, whose statements would run inside it; \
nothing was sent. Run the transaction on a connection of this task's own: \
let mut conn = pool.get().await?; let tx = conn.transaction().await?; ...; \
tx.commit().await?",
word(0)
),
))
}
fn leading_words(sql: &str) -> Vec<String> {
let b = sql.as_bytes();
let mut i = 0;
let mut words = Vec::new();
while words.len() < 2 && i < b.len() {
match b[i] {
c if c.is_ascii_whitespace() => i += 1,
b'-' if b.get(i + 1) == Some(&b'-') => {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
}
b'/' if b.get(i + 1) == Some(&b'*') => {
let mut depth = 0;
while i < b.len() {
if b[i..].starts_with(b"/*") {
depth += 1;
i += 2;
} else if b[i..].starts_with(b"*/") {
depth -= 1;
i += 2;
if depth == 0 {
break;
}
} else {
i += 1;
}
}
}
c if c.is_ascii_alphabetic() || c == b'_' => {
let start = i;
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
i += 1;
}
words.push(sql[start..i].to_ascii_uppercase());
}
_ => break,
}
}
words
}
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_flight() > 0 || client.in_transaction() {
client.send_and_forget("ROLLBACK");
}
client.set_shared(true);
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()
}
}