use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::time::Instant;
use tokio_postgres::error::SqlState;
use tokio_postgres::types::ToSql;
use tokio_postgres::{Error, Row, SimpleQueryMessage};
use tracing::Instrument;
use crate::record::{Analysis, Call, Failure, analyze};
const POSTGRESQL: &str = "postgresql";
const CLIENT_ERROR: &str = "tokio_postgres::Error";
#[derive(Clone, Debug, Default)]
pub struct Database(Arc<Target>);
#[derive(Debug, Default)]
struct Target {
namespace: Option<String>,
server: Option<(String, u16)>,
}
impl Database {
pub fn new(config: &tokio_postgres::Config) -> Self {
crate::record::describe_metrics();
let server = match config.get_hosts() {
[host] => {
let address = match host {
tokio_postgres::config::Host::Tcp(name) => name.clone(),
#[cfg(unix)]
tokio_postgres::config::Host::Unix(path) => path.display().to_string(),
};
let port = config.get_ports().first().copied().unwrap_or(5432);
Some((address, port))
}
_ => None,
};
Database(Arc::new(Target {
namespace: config.get_dbname().map(str::to_owned),
server,
}))
}
fn call<'a>(&'a self, analysis: &'a Analysis) -> Call<'a> {
Call {
system: POSTGRESQL,
namespace: self.0.namespace.as_deref(),
server: self.0.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
analysis,
}
}
}
async fn record<R>(
database: &Database,
analysis: &Analysis,
operation: impl Future<Output = Result<R, Error>>,
) -> Result<R, Error> {
let call = database.call(analysis);
let span = call.span();
let started = Instant::now();
let result = operation.instrument(span.clone()).await;
let seconds = started.elapsed().as_secs_f64();
let _entered = span.enter();
match &result {
Ok(_) => call.record_duration(seconds, None),
Err(error) => {
let code = error.code().map(SqlState::code);
let failure = Failure {
error_type: code.unwrap_or(CLIENT_ERROR),
status_code: code,
};
failure.record(&span);
call.record_duration(seconds, Some(&failure));
}
}
result
}
#[derive(Clone)]
pub struct Statement {
inner: tokio_postgres::Statement,
analysis: Arc<Analysis>,
}
impl Statement {
pub fn into_inner(self) -> tokio_postgres::Statement {
self.inner
}
}
impl Deref for Statement {
type Target = tokio_postgres::Statement;
fn deref(&self) -> &tokio_postgres::Statement {
&self.inner
}
}
impl std::fmt::Debug for Statement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Statement")
.field("summary", &self.analysis.summary)
.finish_non_exhaustive()
}
}
pub trait Query: sealed::Query + Sync {}
impl Query for str {}
impl Query for String {}
impl Query for Statement {}
impl Query for tokio_postgres::Statement {}
mod sealed {
use crate::record::Analysis;
pub enum Target<'a> {
Text(&'a str),
Prepared(Prepared<'a>),
}
pub struct Prepared<'a> {
pub(crate) statement: &'a tokio_postgres::Statement,
pub(crate) analysis: &'a Analysis,
}
pub trait Query {
fn target(&self) -> Target<'_>;
}
impl Query for str {
fn target(&self) -> Target<'_> {
Target::Text(self)
}
}
impl Query for String {
fn target(&self) -> Target<'_> {
Target::Text(self)
}
}
impl Query for super::Statement {
fn target(&self) -> Target<'_> {
Target::Prepared(Prepared {
statement: &self.inner,
analysis: &self.analysis,
})
}
}
impl Query for tokio_postgres::Statement {
fn target(&self) -> Target<'_> {
Target::Prepared(Prepared {
statement: self,
analysis: &crate::record::UNKNOWN,
})
}
}
}
use sealed::Target as Run;
macro_rules! calls {
() => {
pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
let inner = self.pg().prepare(query).await?;
Ok(Statement {
inner,
analysis: analyze(query),
})
}
pub async fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Vec<Row>, Error>
where
T: ?Sized + Query,
{
match statement.target() {
Run::Text(sql) => {
record(&self.database, &analyze(sql), self.pg().query(sql, params)).await
}
Run::Prepared(p) => {
record(
&self.database,
p.analysis,
self.pg().query(p.statement, params),
)
.await
}
}
}
pub async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Row, Error>
where
T: ?Sized + Query,
{
match statement.target() {
Run::Text(sql) => {
record(
&self.database,
&analyze(sql),
self.pg().query_one(sql, params),
)
.await
}
Run::Prepared(p) => {
record(
&self.database,
p.analysis,
self.pg().query_one(p.statement, params),
)
.await
}
}
}
pub async fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Option<Row>, Error>
where
T: ?Sized + Query,
{
match statement.target() {
Run::Text(sql) => {
record(
&self.database,
&analyze(sql),
self.pg().query_opt(sql, params),
)
.await
}
Run::Prepared(p) => {
record(
&self.database,
p.analysis,
self.pg().query_opt(p.statement, params),
)
.await
}
}
}
pub async fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<u64, Error>
where
T: ?Sized + Query,
{
match statement.target() {
Run::Text(sql) => {
record(
&self.database,
&analyze(sql),
self.pg().execute(sql, params),
)
.await
}
Run::Prepared(p) => {
record(
&self.database,
p.analysis,
self.pg().execute(p.statement, params),
)
.await
}
}
}
pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
record(
&self.database,
&analyze(query),
self.pg().batch_execute(query),
)
.await
}
pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
record(
&self.database,
&analyze(query),
self.pg().simple_query(query),
)
.await
}
};
}
pub struct Client<C = tokio_postgres::Client> {
inner: C,
database: Database,
_lease: Option<Lease>,
}
#[cfg(feature = "deadpool-postgres")]
use crate::pool::Lease;
#[cfg(not(feature = "deadpool-postgres"))]
type Lease = std::convert::Infallible;
pub trait AsClient {
fn as_client(&self) -> &tokio_postgres::Client;
fn as_client_mut(&mut self) -> &mut tokio_postgres::Client;
}
impl AsClient for tokio_postgres::Client {
fn as_client(&self) -> &tokio_postgres::Client {
self
}
fn as_client_mut(&mut self) -> &mut tokio_postgres::Client {
self
}
}
impl<C: AsClient> Client<C> {
pub fn new(client: C, config: &tokio_postgres::Config) -> Self {
Self::with_database(client, &Database::new(config))
}
pub fn with_database(client: C, database: &Database) -> Self {
Client {
inner: client,
database: database.clone(),
_lease: None,
}
}
pub fn get_ref(&self) -> &C {
&self.inner
}
pub fn into_inner(self) -> C {
self.inner
}
fn pg(&self) -> &tokio_postgres::Client {
self.inner.as_client()
}
calls!();
pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
let database = self.database.clone();
let inner = record(
&database,
&analyze("BEGIN"),
self.inner.as_client_mut().transaction(),
)
.await?;
Ok(Transaction { inner, database })
}
}
impl<C: AsClient> Deref for Client<C> {
type Target = tokio_postgres::Client;
fn deref(&self) -> &tokio_postgres::Client {
self.inner.as_client()
}
}
impl<C: AsClient> DerefMut for Client<C> {
fn deref_mut(&mut self) -> &mut tokio_postgres::Client {
self.inner.as_client_mut()
}
}
impl<C> std::fmt::Debug for Client<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("database", &self.database)
.finish_non_exhaustive()
}
}
pub struct Transaction<'a> {
inner: tokio_postgres::Transaction<'a>,
database: Database,
}
impl<'a> Transaction<'a> {
fn pg(&self) -> &tokio_postgres::Transaction<'a> {
&self.inner
}
calls!();
pub async fn commit(self) -> Result<(), Error> {
record(&self.database, &analyze("COMMIT"), self.inner.commit()).await
}
pub async fn rollback(self) -> Result<(), Error> {
record(&self.database, &analyze("ROLLBACK"), self.inner.rollback()).await
}
pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
let database = self.database.clone();
let inner = record(&database, &analyze("SAVEPOINT"), self.inner.transaction()).await?;
Ok(Transaction { inner, database })
}
}
impl<'a> Deref for Transaction<'a> {
type Target = tokio_postgres::Transaction<'a>;
fn deref(&self) -> &tokio_postgres::Transaction<'a> {
&self.inner
}
}
impl std::fmt::Debug for Transaction<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Transaction")
.field("database", &self.database)
.finish_non_exhaustive()
}
}
pub trait GenericClient: Sync {
fn prepare(&self, query: &str) -> impl Future<Output = Result<Statement, Error>> + Send;
fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
where
T: ?Sized + Query;
fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Row, Error>> + Send
where
T: ?Sized + Query;
fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Option<Row>, Error>> + Send
where
T: ?Sized + Query;
fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + Query;
fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
}
macro_rules! generic_client {
() => {
fn prepare(&self, query: &str) -> impl Future<Output = Result<Statement, Error>> + Send {
Self::prepare(self, query)
}
fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
where
T: ?Sized + Query,
{
Self::query(self, statement, params)
}
fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Row, Error>> + Send
where
T: ?Sized + Query,
{
Self::query_one(self, statement, params)
}
fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Option<Row>, Error>> + Send
where
T: ?Sized + Query,
{
Self::query_opt(self, statement, params)
}
fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + Query,
{
Self::execute(self, statement, params)
}
fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
Self::batch_execute(self, query)
}
};
}
impl<C: AsClient + Sync> GenericClient for Client<C> {
generic_client!();
}
impl GenericClient for Transaction<'_> {
generic_client!();
}
#[cfg(feature = "deadpool-postgres")]
mod pool {
use super::*;
impl AsClient for deadpool_postgres::Object {
fn as_client(&self) -> &tokio_postgres::Client {
self
}
fn as_client_mut(&mut self) -> &mut tokio_postgres::Client {
self
}
}
impl Client<deadpool_postgres::Object> {
pub async fn prepare_cached(&self, query: &str) -> Result<Statement, Error> {
let inner = self.inner.prepare_cached(query).await?;
Ok(Statement {
inner,
analysis: analyze(query),
})
}
}
#[derive(Clone)]
pub struct Pool {
inner: deadpool_postgres::Pool,
database: Database,
name: Arc<str>,
}
impl Pool {
pub fn new(pool: deadpool_postgres::Pool, config: &tokio_postgres::Config) -> Self {
crate::pool::describe_metrics();
let database = Database::new(config);
let name = crate::pool::default_name(
POSTGRESQL,
database.0.namespace.as_deref(),
database.0.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
);
Pool {
inner: pool,
database,
name: name.into(),
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into().into();
self
}
pub async fn get(
&self,
) -> Result<Client<deadpool_postgres::Object>, deadpool_postgres::PoolError> {
let waiting = crate::pool::Waiting::start(&self.name);
let started = Instant::now();
let result = self.inner.get().await;
drop(waiting);
let timed_out = matches!(&result, Err(deadpool_postgres::PoolError::Timeout(_)));
crate::pool::record_wait(&self.name, started, timed_out);
sample(&self.inner, &self.name);
let client = result?;
let (pool, name) = (self.inner.clone(), Arc::clone(&self.name));
Ok(Client {
inner: client,
database: self.database.clone(),
_lease: Some(Lease::start(&self.name, move || sample(&pool, &name))),
})
}
}
fn sample(pool: &deadpool_postgres::Pool, name: &str) {
let status = pool.status();
crate::pool::record_counts(
name,
status.available,
status.size.saturating_sub(status.available),
status.max_size,
);
}
impl Deref for Pool {
type Target = deadpool_postgres::Pool;
fn deref(&self) -> &deadpool_postgres::Pool {
&self.inner
}
}
impl std::fmt::Debug for Pool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pool")
.field("database", &self.database)
.finish_non_exhaustive()
}
}
}
#[cfg(feature = "deadpool-postgres")]
pub use pool::Pool;