Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
use std::{future::Future, pin::Pin, sync::Arc};
use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
use common_utils::{
external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},
id_type,
request_context::RequestContext,
types::{keymanager, TenantConfig},
DbConnectionParams,
};
pub use diesel_models::DatabaseConnectionWithContext;
use diesel_models::{DejaPgConnection, RawPgConnection};
use error_stack::ResultExt;
use crate::{
config::Database,
errors::{StorageError, StorageResult},
metrics,
};
pub type RawPgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
#[derive(Debug, Clone)]
pub struct PgPool {
pub pg_pool: RawPgPool,
pub event_emitter: Arc<dyn ExternalServiceEventEmitter>,
pub tenant_id: id_type::TenantId,
pub pool_metrics: super::pool_metrics::PgPoolMetrics,
}
impl PgPool {
pub fn new(
pg_pool: RawPgPool,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
tenant_id: id_type::TenantId,
pool_metrics: super::pool_metrics::PgPoolMetrics,
) -> Self {
Self {
pg_pool,
event_emitter,
tenant_id,
pool_metrics,
}
}
pub fn new_without_event_emitter(
pool: RawPgPool,
tenant_id: id_type::TenantId,
pool_metrics: super::pool_metrics::PgPoolMetrics,
) -> Self {
Self::new(pool, Arc::new(NoOpEventEmitter), tenant_id, pool_metrics)
}
}
/// Shared database-pool ownership.
///
/// Request-scoped wrappers such as `RouterStore` and `KVRouterStore` implement
/// `RequestContext` separately. Connection helpers require that context when leasing
/// a connection, while pool-only stores can implement this trait without it.
#[async_trait::async_trait]
pub trait DatabaseStore: Clone + Send + Sync {
type Config: Send;
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
key_manager_state: Option<keymanager::KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self>;
fn get_master_pool(&self) -> &PgPool;
fn get_replica_pool(&self) -> &PgPool;
fn get_accounts_master_pool(&self) -> &PgPool;
fn get_accounts_replica_pool(&self) -> &PgPool;
/// Lease an accounts read connection with request and read-ledger context.
async fn pg_accounts_connection_read(&self) -> StorageResult<DatabaseConnectionWithContext<'_>>
where
Self: RequestContext,
{
// If only OLAP is enabled, get the replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let (pool, db_pool_label) = (
self.get_accounts_replica_pool(),
super::pool_metrics::DbPool::AccountsReplica,
);
// If either one of these is true, get the master pool:
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP are enabled.
// 3. Both OLAP and OLTP are disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let (pool, db_pool_label) = (
self.get_accounts_master_pool(),
super::pool_metrics::DbPool::AccountsMaster,
);
let tenant_id = pool.tenant_id.get_string_repr();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
let mut connection = metrics::record_db_connection_acquire_duration(
pool.pg_pool.get(),
db_pool_label,
tenant_id,
)
.await
.change_context(StorageError::DatabaseConnectionError)?;
#[cfg(feature = "deja")]
crate::utils::deja_route_replay_schema(&mut connection, self).await;
Ok(DatabaseConnectionWithContext::new(
connection,
self.request_id().map(str::to_owned),
pool.event_emitter.clone(),
self.read_ledger().cloned(),
))
}
/// Lease an accounts-master write connection with request and read-ledger context.
async fn pg_accounts_connection_write(&self) -> StorageResult<DatabaseConnectionWithContext<'_>>
where
Self: RequestContext,
{
let pool = self.get_accounts_master_pool();
let tenant_id = pool.tenant_id.get_string_repr();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
let mut connection = metrics::record_db_connection_acquire_duration(
pool.pg_pool.get(),
super::pool_metrics::DbPool::AccountsMaster,
tenant_id,
)
.await
.change_context(StorageError::DatabaseConnectionError)?;
#[cfg(feature = "deja")]
crate::utils::deja_route_replay_schema(&mut connection, self).await;
Ok(DatabaseConnectionWithContext::new(
connection,
self.request_id().map(str::to_owned),
pool.event_emitter.clone(),
self.read_ledger().cloned(),
))
}
/// Request correlation used by deja replay to route database connections to
/// the active replay schema. Stores without request identity return `None`.
#[cfg(feature = "deja")]
fn get_request_id(&self) -> Option<String> {
None
}
}
#[derive(Debug, Clone)]
pub struct Store {
pub master_pool: PgPool,
pub accounts_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for Store {
/// (master config, accounts config)
type Config = (Database, Database);
async fn new(
config: (Database, Database),
tenant_config: &dyn TenantConfig,
test_transaction: bool,
_key_manager_state: Option<keymanager::KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self> {
let (master_config, accounts_config) = config;
Ok(Self {
master_pool: diesel_make_pg_pool(
&master_config,
tenant_config.get_schema(),
test_transaction,
Arc::clone(&event_emitter),
super::pool_metrics::DbPool::Master,
tenant_config.get_tenant_id(),
)
.await?,
accounts_pool: diesel_make_pg_pool(
&accounts_config,
tenant_config.get_accounts_schema(),
test_transaction,
event_emitter,
super::pool_metrics::DbPool::AccountsMaster,
tenant_config.get_tenant_id(),
)
.await?,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_pool
}
}
#[derive(Debug, Clone)]
pub struct ReplicaStore {
pub master_pool: PgPool,
pub replica_pool: PgPool,
pub accounts_master_pool: PgPool,
pub accounts_replica_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for ReplicaStore {
/// (master config, replica config, accounts master config, accounts replica config)
type Config = (Database, Database, Database, Database);
async fn new(
config: (Database, Database, Database, Database),
tenant_config: &dyn TenantConfig,
test_transaction: bool,
_key_manager_state: Option<keymanager::KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self> {
let (master_config, replica_config, accounts_master_config, accounts_replica_config) =
config;
let master_pool = diesel_make_pg_pool(
&master_config,
tenant_config.get_schema(),
test_transaction,
Arc::clone(&event_emitter),
super::pool_metrics::DbPool::Master,
tenant_config.get_tenant_id(),
)
.await
.attach_printable("failed to create master pool")?;
let accounts_master_pool = diesel_make_pg_pool(
&accounts_master_config,
tenant_config.get_accounts_schema(),
test_transaction,
Arc::clone(&event_emitter),
super::pool_metrics::DbPool::AccountsMaster,
tenant_config.get_tenant_id(),
)
.await
.attach_printable("failed to create accounts master pool")?;
let replica_pool = diesel_make_pg_pool(
&replica_config,
tenant_config.get_schema(),
test_transaction,
Arc::clone(&event_emitter),
super::pool_metrics::DbPool::Replica,
tenant_config.get_tenant_id(),
)
.await
.attach_printable("failed to create replica pool")?;
let accounts_replica_pool = diesel_make_pg_pool(
&accounts_replica_config,
tenant_config.get_accounts_schema(),
test_transaction,
event_emitter,
super::pool_metrics::DbPool::AccountsReplica,
tenant_config.get_tenant_id(),
)
.await
.attach_printable("failed to create accounts pool")?;
Ok(Self {
master_pool,
replica_pool,
accounts_master_pool,
accounts_replica_pool,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.replica_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_master_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_replica_pool
}
}
pub async fn diesel_make_pg_pool(
database: &Database,
schema: &str,
test_transaction: bool,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
db_pool: super::pool_metrics::DbPool,
tenant_id: &id_type::TenantId,
) -> StorageResult<PgPool> {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<DejaPgConnection>::new(database_url);
let mut pool = bb8::Pool::builder()
.max_size(database.max_pool_size)
.min_idle(Some(database.min_idle_pool_size))
.queue_strategy(database.queue_strategy.into())
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout))
.max_lifetime(std::time::Duration::from_secs(database.max_lifetime))
.idle_timeout(std::time::Duration::from_secs(database.idle_timeout));
if test_transaction {
pool = pool.connection_customizer(Box::new(TestTransaction));
}
let raw_pool = pool
.build(manager)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create PostgreSQL connection pool")?;
// Register row identity (primary-key columns) with deja from this
// database's own catalog. Idempotent; on failure identity stays
// unregistered, making recorded row keys absent rather than wrong.
#[cfg(feature = "deja")]
if !deja::runtime_mode_is_disabled() {
use async_bb8_diesel::AsyncConnection;
use diesel::RunQueryDsl;
if let Ok(connection) = raw_pool.get().await {
let rows = connection
.run(|conn| {
diesel::sql_query(deja::TABLE_IDENTITY_SQL)
.load::<deja::db::TableIdentityRow>(conn)
.map(|rows| {
rows.into_iter()
.map(|row| (row.table_name, row.column_name))
.collect::<Vec<(String, String)>>()
})
})
.await;
match rows {
Ok(rows) => deja::db::register_table_identity_rows(rows),
Err(error) => {
router_env::logger::warn!(
?error,
"deja: could not read row identity from the schema; recorded row keys will fall back to query fingerprints"
);
}
}
}
}
let pool_metrics =
super::pool_metrics::PgPoolMetrics::new(raw_pool.clone(), db_pool, tenant_id);
Ok(PgPool::new(
raw_pool,
event_emitter,
tenant_id.clone(),
pool_metrics,
))
}
#[derive(Debug)]
struct TestTransaction;
impl CustomizeConnection<RawPgConnection, ConnectionError> for TestTransaction {
#[allow(clippy::unwrap_used)]
fn on_acquire<'a>(
&'a self,
conn: &'a mut RawPgConnection,
) -> Pin<Box<dyn Future<Output = Result<(), ConnectionError>> + Send + 'a>> {
Box::pin(async move {
use diesel::Connection;
conn.run(|conn| {
conn.begin_test_transaction().unwrap();
Ok(())
})
.await
})
}
}