#![warn(missing_docs, unreachable_pub)]
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use async_trait::async_trait;
use futures::FutureExt;
use log::{info, warn};
use tokio::spawn;
use tokio::sync::RwLock;
use tokio_postgres::{
tls::MakeTlsConnect, tls::TlsConnect, types::Type, Client as PgClient, Config as PgConfig,
Error, Socket, Statement, Transaction as PgTransaction,
};
pub mod config;
pub use crate::config::{Config, ManagerConfig, RecyclingMethod};
pub type Pool = deadpool::managed::Pool<ClientWrapper, tokio_postgres::Error>;
pub type PoolError = deadpool::managed::PoolError<tokio_postgres::Error>;
pub type Client = deadpool::managed::Object<ClientWrapper, tokio_postgres::Error>;
type RecycleResult = deadpool::managed::RecycleResult<Error>;
type RecycleError = deadpool::managed::RecycleError<Error>;
pub struct Manager<T: MakeTlsConnect<Socket>> {
config: ManagerConfig,
pg_config: PgConfig,
tls: T,
}
impl<T: MakeTlsConnect<Socket>> Manager<T> {
pub fn new(pg_config: tokio_postgres::Config, tls: T) -> Manager<T> {
Manager {
config: ManagerConfig::default(),
pg_config,
tls,
}
}
pub fn from_config(
pg_config: tokio_postgres::Config,
tls: T,
config: ManagerConfig,
) -> Manager<T> {
Manager {
config,
pg_config,
tls,
}
}
}
#[async_trait]
impl<T> deadpool::managed::Manager<ClientWrapper, Error> for Manager<T>
where
T: MakeTlsConnect<Socket> + Clone + Sync + Send + 'static,
T::Stream: Sync + Send,
T::TlsConnect: Sync + Send,
<T::TlsConnect as TlsConnect<Socket>>::Future: Send,
{
async fn create(&self) -> Result<ClientWrapper, Error> {
let (client, connection) = self.pg_config.connect(self.tls.clone()).await?;
let connection = connection.map(|r| {
if let Err(e) = r {
warn!(target: "deadpool.postgres", "Connection error: {}", e);
}
});
spawn(connection);
Ok(ClientWrapper::new(client))
}
async fn recycle(&self, client: &mut ClientWrapper) -> RecycleResult {
if client.is_closed() {
info!(target: "deadpool.postgres", "Connection could not be recycled: Connection closed");
return Err(RecycleError::Message("Connection closed".to_string()));
}
match self.config.recycling_method {
RecyclingMethod::Fast => Ok(()),
RecyclingMethod::Verified => match client.simple_query("").await {
Ok(_) => Ok(()),
Err(e) => {
info!(target: "deadpool.postgres", "Connection could not be recycled: {}", e);
Err(e.into())
}
},
}
}
}
pub struct StatementCache {
map: RwLock<HashMap<StatementCacheKey<'static>, Statement>>,
size: AtomicUsize,
}
#[derive(Hash, Eq, PartialEq)]
struct StatementCacheKey<'a> {
query: Cow<'a, str>,
types: Cow<'a, [Type]>,
}
impl StatementCache {
fn new() -> StatementCache {
StatementCache {
map: RwLock::new(HashMap::new()),
size: AtomicUsize::new(0),
}
}
pub fn size(&self) -> usize {
self.size.load(Ordering::Relaxed)
}
pub async fn clear(&self) {
let mut map = self.map.write().await;
map.clear();
self.size.store(0, Ordering::Relaxed);
}
async fn get<'a>(&self, query: &str, types: &[Type]) -> Option<Statement> {
let key = StatementCacheKey {
query: Cow::Borrowed(query),
types: Cow::Borrowed(types),
};
self.map.read().await.get(&key).map(|stmt| stmt.to_owned())
}
async fn insert(&self, query: &str, types: &[Type], stmt: Statement) {
let key = StatementCacheKey {
query: Cow::Owned(query.to_owned()),
types: Cow::Owned(types.to_owned()),
};
let mut map = self.map.write().await;
map.insert(key, stmt);
self.size.fetch_add(1, Ordering::Relaxed);
}
}
pub struct ClientWrapper {
client: PgClient,
pub statement_cache: StatementCache,
}
impl ClientWrapper {
pub fn new(client: PgClient) -> Self {
Self {
client: client,
statement_cache: StatementCache::new(),
}
}
pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
self.prepare_typed(query, &[]).await
}
pub async fn prepare_typed(&self, query: &str, types: &[Type]) -> Result<Statement, Error> {
match self.statement_cache.get(query, types).await {
Some(statement) => Ok(statement),
None => {
let stmt = self.client.prepare_typed(query, types).await?;
self.statement_cache
.insert(query, types, stmt.clone())
.await;
Ok(stmt)
}
}
}
pub async fn transaction<'a>(&'a mut self) -> Result<Transaction<'a>, Error> {
Ok(Transaction {
txn: PgClient::transaction(&mut self.client).await?,
statement_cache: &mut self.statement_cache,
})
}
}
impl Deref for ClientWrapper {
type Target = PgClient;
fn deref(&self) -> &PgClient {
&self.client
}
}
impl DerefMut for ClientWrapper {
fn deref_mut(&mut self) -> &mut PgClient {
&mut self.client
}
}
pub struct Transaction<'a> {
txn: PgTransaction<'a>,
pub statement_cache: &'a mut StatementCache,
}
impl<'a> Transaction<'a> {
pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
self.prepare_typed(query, &[]).await
}
pub async fn prepare_typed(&self, query: &str, types: &[Type]) -> Result<Statement, Error> {
match self.statement_cache.get(query, types).await {
Some(statement) => Ok(statement),
None => {
let stmt = self.txn.prepare_typed(query, types).await?;
self.statement_cache
.insert(query, types, stmt.clone())
.await;
Ok(stmt)
}
}
}
pub async fn commit(self) -> Result<(), Error> {
self.txn.commit().await
}
pub async fn rollback(self) -> Result<(), Error> {
self.txn.rollback().await
}
pub async fn transaction<'b>(&'b mut self) -> Result<Transaction<'b>, Error> {
Ok(Transaction {
txn: PgTransaction::transaction(&mut self.txn).await?,
statement_cache: &mut self.statement_cache,
})
}
}
impl<'a> Deref for Transaction<'a> {
type Target = PgTransaction<'a>;
fn deref(&self) -> &PgTransaction<'a> {
&self.txn
}
}
impl<'a> DerefMut for Transaction<'a> {
fn deref_mut(&mut self) -> &mut PgTransaction<'a> {
&mut self.txn
}
}