Dataset Viewer
Auto-converted to Parquet
text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/storage_impl/src/tokenization.rs // Module: storage_impl::src::tokenization #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use diesel_models::tokenization as tokenization_diesel; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use error_stack::{report, ResultExt}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use super::MockDb; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use crate::{connection, errors}; use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] pub trait TokenizationInterface {} #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub trait TokenizationInterface { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn update_tokenization_record( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; tokenization .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let tokenization = tokenization_diesel::Tokenization::find_by_id(&conn, token) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let domain = tokenization .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(domain) } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let tokenization_record = Conversion::convert(tokenization_record) .await .change_context(errors::StorageError::DecryptionError)?; self.call_database( key_manager_state, merchant_key_store, tokenization_record.update_with_id( &conn, tokenization_diesel::TokenizationUpdateInternal::from(tokenization_update), ), ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .insert_tokenization(tokenization, merchant_key_store, key_manager_state) .await } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) .await } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .update_tokenization_record( tokenization_record, tokenization_update, merchant_key_store, key_manager_state, ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl TokenizationInterface for MockDb { async fn insert_tokenization( &self, _tokenization: hyperswitch_domain_models::tokenization::Tokenization, _merchant_key_store: &MerchantKeyStore, _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn get_entity_id_vault_id_by_token_id( &self, _token: &common_utils::id_type::GlobalTokenId, _merchant_key_store: &MerchantKeyStore, _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl TokenizationInterface for MockDb {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {}
crates/storage_impl/src/tokenization.rs
storage_impl::src::tokenization
1,887
true
// File: crates/storage_impl/src/mock_db.rs // Module: storage_impl::src::mock_db use std::sync::Arc; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models as store; use error_stack::ResultExt; use futures::lock::{Mutex, MutexGuard}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use redis_interface::RedisSettings; use crate::{errors::StorageError, redis::RedisStore}; pub mod payment_attempt; pub mod payment_intent; #[cfg(feature = "payouts")] pub mod payout_attempt; #[cfg(feature = "payouts")] pub mod payouts; pub mod redis_conn; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; #[derive(Clone)] pub struct MockDb { pub addresses: Arc<Mutex<Vec<store::Address>>>, pub configs: Arc<Mutex<Vec<store::Config>>>, pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>, pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>, pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>, pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>, pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>, pub customers: Arc<Mutex<Vec<store::Customer>>>, pub refunds: Arc<Mutex<Vec<store::Refund>>>, pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>, pub redis: Arc<RedisStore>, pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>, pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>, pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>, pub events: Arc<Mutex<Vec<store::Event>>>, pub disputes: Arc<Mutex<Vec<store::Dispute>>>, pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>, pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>, pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, #[cfg(feature = "payouts")] pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>, #[cfg(feature = "payouts")] pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>, pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>, pub roles: Arc<Mutex<Vec<store::role::Role>>>, pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>, pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, pub hyperswitch_ai_interactions: Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>, } impl MockDb { pub async fn new(redis: &RedisSettings) -> error_stack::Result<Self, StorageError> { Ok(Self { addresses: Default::default(), configs: Default::default(), merchant_accounts: Default::default(), merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), payment_intents: Default::default(), payment_methods: Default::default(), customers: Default::default(), refunds: Default::default(), processes: Default::default(), redis: Arc::new( RedisStore::new(redis) .await .change_context(StorageError::InitializationError)?, ), api_keys: Default::default(), ephemeral_keys: Default::default(), cards_info: Default::default(), events: Default::default(), disputes: Default::default(), lockers: Default::default(), mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), #[cfg(all(feature = "v2", feature = "tokenization_v2"))] tokenizations: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), payment_link: Default::default(), organizations: Default::default(), users: Default::default(), user_roles: Default::default(), authorizations: Default::default(), dashboard_metadata: Default::default(), #[cfg(feature = "payouts")] payout_attempt: Default::default(), #[cfg(feature = "payouts")] payouts: Default::default(), authentications: Default::default(), roles: Default::default(), user_key_store: Default::default(), user_authentication_methods: Default::default(), themes: Default::default(), hyperswitch_ai_interactions: Default::default(), }) } /// Returns an option of the resource if it exists pub async fn find_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, ) -> CustomResult<Option<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resource = resources.iter().find(filter_fn).cloned(); match resource { Some(res) => Ok(Some( res.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } /// Throws errors when the requested resource is not found pub async fn get_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { match self .find_resource(state, key_store, resources, filter_fn) .await? { Some(res) => Ok(res), None => Err(StorageError::ValueNotFound(error_message).into()), } } pub async fn get_resources<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<Vec<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect(); if resources.is_empty() { Err(StorageError::ValueNotFound(error_message).into()) } else { let pm_futures = resources .into_iter() .map(|pm| async { pm.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let domain_resources = futures::future::try_join_all(pm_futures).await?; Ok(domain_resources) } } pub async fn update_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, mut resources: MutexGuard<'_, Vec<D>>, resource_updated: D, filter_fn: impl Fn(&&mut D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { if let Some(pm) = resources.iter_mut().find(filter_fn) { *pm = resource_updated.clone(); let result = resource_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(result) } else { Err(StorageError::ValueNotFound(error_message).into()) } } pub fn master_key(&self) -> &[u8] { &[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ] } } #[cfg(not(feature = "payouts"))] impl PayoutsInterface for MockDb {} #[cfg(not(feature = "payouts"))] impl PayoutAttemptInterface for MockDb {}
crates/storage_impl/src/mock_db.rs
storage_impl::src::mock_db
2,223
true
// File: crates/storage_impl/src/callback_mapper.rs // Module: storage_impl::src::callback_mapper use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper; use hyperswitch_domain_models::callback_mapper::CallbackMapper; use crate::DataModelExt; impl DataModelExt for CallbackMapper { type StorageModel = DieselCallbackMapper; fn to_storage_model(self) -> Self::StorageModel { DieselCallbackMapper { id: self.id, type_: self.callback_mapper_id_type, data: self.data, created_at: self.created_at, last_modified_at: self.last_modified_at, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { id: storage_model.id, callback_mapper_id_type: storage_model.type_, data: storage_model.data, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, } } }
crates/storage_impl/src/callback_mapper.rs
storage_impl::src::callback_mapper
201
true
// File: crates/storage_impl/src/lookup.rs // Module: storage_impl::src::lookup use common_utils::errors::CustomResult; use diesel_models::{ enums as storage_enums, kv, reverse_lookup::{ ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew, }, }; use error_stack::ResultExt; use redis_interface::SetnxReply; use crate::{ diesel_error_to_data_error, errors::{self, RedisErrorExt}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, try_redis_get_else_try_database_get}, DatabaseStore, RouterStore, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = self .get_master_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; new.insert(&conn).await.map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = utils::pg_connection_read(self).await?; DieselReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => { self.router_store .insert_reverse_lookup(new, storage_scheme) .await } storage_enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = DieselReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let database_call = || async { self.router_store .get_lookup_by_lookup_id(id, storage_scheme) .await }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await, storage_enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<DieselReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } }
crates/storage_impl/src/lookup.rs
storage_impl::src::lookup
1,204
true
// File: crates/storage_impl/src/merchant_account.rs // Module: storage_impl::src::merchant_account #[cfg(feature = "olap")] use std::collections::HashMap; use common_utils::ext_traits::AsyncExt; use diesel_models::merchant_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, master_key::MasterKeyInterface, merchant_account::{self as domain, MerchantAccountInterface}, merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface}, }; use masking::PeekInterface; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::{ cache, cache::{CacheKind, ACCOUNTS_CACHE}, }; #[cfg(feature = "accounts_cache")] use crate::RedisConnInterface; use crate::{ kv_router_store, store::MerchantAccountUpdateInternal, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .insert_merchant(state, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .find_merchant_account_by_merchant_id(state, merchant_id, merchant_key_store) .await } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_merchant(state, this, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_specific_fields_in_merchant( state, merchant_id, merchant_account, merchant_key_store, ) .await } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { self.router_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { self.router_store .list_merchant_and_org_ids(_state, limit, offset) .await } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { self.router_store .update_all_merchant_account(merchant_account) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; merchant_account .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert( state, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, merchant_id.get_string_repr(), fetch_func, &ACCOUNTS_CACHE, ) .await? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = Conversion::convert(this) .await .change_context(StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields( &conn, merchant_id, merchant_account.into(), ) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let fetch_by_pub_key_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key) .await .map_err(|error| report!(StorageError::from(error))) }; let merchant_account; #[cfg(not(feature = "accounts_cache"))] { merchant_account = fetch_by_pub_key_func().await?; } #[cfg(feature = "accounts_cache")] { merchant_account = cache::get_or_populate_in_memory( self, publishable_key, fetch_by_pub_key_func, &ACCOUNTS_CACHE, ) .await?; } let key_store = self .get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &self.master_key().peek().to_vec().into(), ) .await?; let domain_merchant_account = merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((domain_merchant_account, key_store)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { use futures::future::try_join_all; let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_by_organization_id(&conn, organization_id) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &db_master_key, ) })) .await?; let merchant_accounts = try_join_all( encrypted_merchant_accounts .into_iter() .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; Ok(merchant_accounts) } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_accounts_connection_write(self).await?; let is_deleted_func = || async { storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; let is_deleted; #[cfg(not(feature = "accounts_cache"))] { is_deleted = is_deleted_func().await?; } #[cfg(feature = "accounts_cache")] { let merchant_account = storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error)))?; is_deleted = is_deleted_func().await?; publish_and_redact_merchant_account_cache(self, &merchant_account).await?; } Ok(is_deleted) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = self .list_multiple_key_stores( state, encrypted_merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id()) .cloned() .collect(), &db_master_key, ) .await?; let key_stores_by_id: HashMap<_, _> = merchant_key_stores .iter() .map(|key_store| (key_store.merchant_id.to_owned(), key_store)) .collect(); let merchant_accounts = futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map( |merchant_account| async { let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or( StorageError::ValueNotFound(format!( "merchant_key_store with merchant_id = {:?}", merchant_account.get_id() )), )?; merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }, )) .await?; Ok(merchant_accounts) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) .await .map_err(|error| report!(StorageError::from(error)))?; let merchant_and_org_ids = encrypted_merchant_accounts .into_iter() .map(|merchant_account| { let merchant_id = merchant_account.get_id().clone(); let org_id = merchant_account.organization_id; (merchant_id, org_id) }) .collect(); Ok(merchant_and_org_ids) } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let conn = pg_accounts_connection_read(self).await?; let db_func = || async { storage::MerchantAccount::update_all_merchant_accounts( &conn, MerchantAccountUpdateInternal::from(merchant_account), ) .await .map_err(|error| report!(StorageError::from(error))) }; let total; #[cfg(not(feature = "accounts_cache"))] { let ma = db_func().await?; total = ma.len(); } #[cfg(feature = "accounts_cache")] { let ma = db_func().await?; publish_and_redact_all_merchant_account_cache(self, &ma).await?; total = ma.len(); } Ok(total) } } #[async_trait::async_trait] impl MerchantAccountInterface for MockDb { type Error = StorageError; #[allow(clippy::panic)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?; accounts.push(account.clone()); account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let accounts = self.merchant_accounts.lock().await; accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() .ok_or(StorageError::ValueNotFound(format!( "Merchant ID: {merchant_id:?} not found", )))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn update_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let merchant_id = merchant_account.get_id().to_owned(); let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_account.get_id()) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset( Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?, ); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_id) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset(account.clone()); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let accounts = self.merchant_accounts.lock().await; let account = accounts .iter() .find(|account| { account .publishable_key .as_ref() .is_some_and(|key| key == publishable_key) }) .ok_or(StorageError::ValueNotFound(format!( "Publishable Key: {publishable_key} not found", )))?; let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let merchant_account = account .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((merchant_account, key_store)) } async fn update_all_merchant_account( &self, merchant_account_update: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let mut accounts = self.merchant_accounts.lock().await; Ok(accounts.iter_mut().fold(0, |acc, account| { let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) .apply_changeset(account.clone()); *account = update; acc + 1 })) } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts.retain(|x| x.get_id() != merchant_id); Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| account.organization_id == *organization_id) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| merchant_ids.contains(account.get_id())) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let accounts = self.merchant_accounts.lock().await; let limit = limit.try_into().unwrap_or(accounts.len()); let offset = offset.unwrap_or(0).try_into().unwrap_or(0); let merchant_and_org_ids = accounts .iter() .skip(offset) .take(limit) .map(|account| (account.get_id().clone(), account.organization_id.clone())) .collect::<Vec<_>>(); Ok(merchant_and_org_ids) } } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_merchant_account_cache( store: &(dyn RedisConnInterface + Send + Sync), merchant_account: &storage::MerchantAccount, ) -> CustomResult<(), StorageError> { let publishable_key = merchant_account .publishable_key .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "v1")] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( "cgraph_{}_{}", merchant_account.get_id().get_string_repr(), profile_id.get_string_repr(), ) .into(), ) }); // TODO: we will not have default profile in v2 #[cfg(feature = "v2")] let cgraph_key = None; let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; cache_keys.extend(publishable_key.into_iter()); cache_keys.extend(cgraph_key.into_iter()); cache::redact_from_redis_and_publish(store, cache_keys).await?; Ok(()) } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_all_merchant_account_cache( cache: &(dyn RedisConnInterface + Send + Sync), merchant_accounts: &[storage::MerchantAccount], ) -> CustomResult<(), StorageError> { let merchant_ids = merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); let cache_keys: Vec<CacheKind<'_>> = merchant_ids .chain(publishable_keys) .map(|s| CacheKind::Accounts(s.into())) .collect(); cache::redact_from_redis_and_publish(cache, cache_keys).await?; Ok(()) }
crates/storage_impl/src/merchant_account.rs
storage_impl::src::merchant_account
6,137
true
// File: crates/storage_impl/src/payouts.rs // Module: storage_impl::src::payouts pub mod payout_attempt; #[allow(clippy::module_inception)] pub mod payouts; use diesel_models::{payout_attempt::PayoutAttempt, payouts::Payouts}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Payouts {} impl KvStorePartition for PayoutAttempt {}
crates/storage_impl/src/payouts.rs
storage_impl::src::payouts
91
true
// File: crates/storage_impl/src/database.rs // Module: storage_impl::src::database pub mod store;
crates/storage_impl/src/database.rs
storage_impl::src::database
24
true
// File: crates/storage_impl/src/cards_info.rs // Module: storage_impl::src::cards_info pub use diesel_models::{CardInfo, UpdateCardInfo}; use error_stack::report; use hyperswitch_domain_models::cards_info::CardsInfoInterface; use router_env::{instrument, tracing}; use crate::{ errors::StorageError, kv_router_store::KVRouterStore, redis::kv_store::KvStorePartition, utils::{pg_connection_read, pg_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, }; impl KvStorePartition for CardInfo {} #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl CardsInfoInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { Ok(self .cards_info .lock() .await .iter() .find(|ci| ci.card_iin == card_iin) .cloned()) } async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } async fn update_card_info( &self, _card_iin: String, _data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/cards_info.rs
storage_impl::src::cards_info
845
true
// File: crates/storage_impl/src/payment_method.rs // Module: storage_impl::src::payment_method pub use diesel_models::payment_method::PaymentMethod; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentMethod {} use common_enums::enums::MerchantStorageScheme; use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState}; #[cfg(feature = "v1")] use diesel_models::kv; use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::behaviour::ReverseConversion; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface}, }; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ diesel_error_to_data_error, errors, kv_router_store::{FindResourceBy, KVRouterStore}, utils::{pg_connection_read, pg_connection_write}, DatabaseStore, RouterStore, }; #[cfg(feature = "v1")] use crate::{ kv_router_store::{FilterResourceParams, InsertResourceParams, UpdateResourceParams}, redis::kv_store::{Op, PartitionKey}, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), FindResourceBy::LookupId(format!("payment_method_{payment_method_id}")), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_id(&conn, payment_method_id), FindResourceBy::LookupId(format!( "payment_method_{}", payment_method_id.get_string_repr() )), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_locker_id(&conn, locker_id), FindResourceBy::LookupId(format!("payment_method_locker_{locker_id}")), ) .await } // not supported in kv #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .insert_payment_method(state, key_store, payment_method, storage_scheme) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; let mut payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; payment_method_new.update_storage_scheme(storage_scheme); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &payment_method_new.merchant_id.clone(), customer_id: &payment_method_new.customer_id.clone(), }; let identifier = format!("payment_method_id_{}", payment_method_new.get_id()); let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id()); let mut reverse_lookups = vec![lookup_id1]; if let Some(locker_id) = &payment_method_new.locker_id { reverse_lookups.push(format!("payment_method_locker_{locker_id}")) } let payment_method = (&payment_method_new.clone()).into(); self.insert_resource( state, key_store, storage_scheme, payment_method_new.clone().insert(&conn), payment_method, InsertResourceParams { insertable: kv::Insertable::PaymentMethod(payment_method_new.clone()), reverse_lookups, key, identifier, resource_type: "payment_method", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let merchant_id = payment_method.merchant_id.clone(); let customer_id = payment_method.customer_id.clone(); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let conn = pg_connection_write(self).await?; let field = format!("payment_method_id_{}", payment_method.get_id().clone()); let p_update: PaymentMethodUpdateInternal = payment_method_update.convert_to_payment_method_update(storage_scheme); let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone()); self.update_resource( state, key_store, storage_scheme, payment_method .clone() .update_with_payment_method_id(&conn, p_update.clone()), updated_payment_method, UpdateResourceParams { updateable: kv::Updateable::PaymentMethodUpdate(Box::new( kv::PaymentMethodUpdateMems { orig: payment_method.clone(), update_data: p_update.clone(), }, )), operation: Op::Update( key.clone(), &field, payment_method.clone().updated_by.as_deref(), ), }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .update_payment_method( state, key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_list_by_global_customer_id(state, key_store, customer_id, limit) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.filter_resources( state, key_store, storage_scheme, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), |pm| pm.status == status, FilterResourceParams { key: PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, pattern: "payment_method_id_*", limit, }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_global_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method_by_merchant_id_payment_method_id( state, key_store, merchant_id, payment_method_id, ) .await } // Soft delete, Check if KV stuff is needed here #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method(state, key_store, payment_method) .await } // Check if KV stuff is needed here #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_locker_id(&conn, locker_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database(state, key_store, payment_method_new.insert(&conn)) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_payment_method_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit), ) .await } // Need to fix this once we move to payment method for customer #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id(&conn, id, limit), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; self.call_database( state, key_store, PaymentMethod::delete_by_merchant_id_payment_method_id( &conn, merchant_id, payment_method_id, ), ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id), ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for MockDb { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_id == Some(locker_id.to_string()), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| pm.merchant_id == *merchant_id && pm.status == status) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn insert_payment_method( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; let pm = Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::DecryptionError)?; payment_methods.push(pm); Ok(payment_method) } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( state, key_store, payment_methods, |pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id, "cannot find payment method".to_string(), ) .await } // Need to fix this once we complete v2 payment method #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _id: &id_type::GlobalCustomerId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { todo!() } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( state, key_store, payment_methods, |pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let find_pm_by = |pm: &&PaymentMethod| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }; let error_message = "cannot find payment method".to_string(); self.get_resources(state, key_store, payment_methods, find_pm_by, error_message) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; match payment_methods .iter() .position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id) { Some(index) => { let deleted_payment_method = payment_methods.remove(index); Ok(deleted_payment_method .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?) } None => Err(errors::StorageError::ValueNotFound( "cannot find payment method to delete".to_string(), ) .into()), } } async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot update payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()), "cannot find payment method".to_string(), ) .await } }
crates/storage_impl/src/payment_method.rs
storage_impl::src::payment_method
7,319
true
// File: crates/storage_impl/src/merchant_connector_account.rs // Module: storage_impl::src::merchant_connector_account use async_bb8_diesel::AsyncConnection; use common_utils::{encryption::Encryption, ext_traits::AsyncExt}; use diesel_models::merchant_connector_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_connector_account::{self as domain, MerchantConnectorAccountInterface}, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::cache; use crate::{ kv_router_store, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_label( state, merchant_id, connector_label, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_profile_id_connector_name( state, profile_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_name( state, merchant_id, connector_name, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( state, merchant_id, merchant_connector_id, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_id(state, id, key_store) .await } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .insert_merchant_connector_account(state, t, key_store) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_enabled_connector_accounts_by_profile_id( state, profile_id, key_store, connector_type, ) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( state, merchant_id, get_disabled, key_store, ) .await } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_connector_account_by_profile_id(state, profile_id, key_store) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { self.router_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, connector_label, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", merchant_id.get_string_repr(), connector_label), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_profile_id_connector_name( &conn, profile_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", profile_id.get_string_repr(), connector_name), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector_name( &conn, merchant_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!( "{}_{}", merchant_id.get_string_repr(), merchant_connector_id.get_string_repr() ), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, id.get_string_repr(), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let conn = pg_accounts_connection_write(self).await?; t.construct_new() .await .change_context(Self::Error::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_enabled_by_profile_id( &conn, profile_id, connector_type, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { let conn = pg_accounts_connection_read(self).await?; let merchant_connector_account_vec = storage::MerchantConnectorAccount::find_by_merchant_id( &conn, merchant_id, get_disabled, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await?; Ok(domain::MerchantConnectorAccounts::new( merchant_connector_account_vec, )) } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { let conn = pg_accounts_connection_write(self).await?; async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(StorageError::from(error)))?; Ok(()) } conn.transaction_async(|connection_pool| async move { for (merchant_connector_account, update_merchant_connector_account) in merchant_connector_accounts { #[cfg(feature = "v1")] let _connector_name = merchant_connector_account.connector_name.clone(); #[cfg(feature = "v2")] let _connector_name = merchant_connector_account.connector_name.to_string(); let _profile_id = merchant_connector_account.profile_id.clone(); let _merchant_id = merchant_connector_account.merchant_id.clone(); let _merchant_connector_id = merchant_connector_account.get_id().clone(); let update = update_call( &connection_pool, ( merchant_connector_account, update_merchant_connector_account, ), ); #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], || update, )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; #[cfg(not(feature = "accounts_cache"))] { update.await.map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; } } Ok::<_, Self::Error>(()) }) .await?; Ok(()) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name.clone(); let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr(), ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name; let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.get_id().clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( _merchant_connector_id.get_string_repr().to_string().into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error)))?; let _profile_id = mca .profile_id .ok_or(Self::Error::ValueNotFound("profile_id".to_string()))?; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error)))?; let _profile_id = mca.profile_id; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { type Error = StorageError; async fn update_multiple_merchant_connector_accounts( &self, _merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), StorageError> { // No need to implement this function for `MockDb` as this function will be removed after the // apple pay certificate migration Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.connector_label == Some(connector.to_string()) }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } async fn list_enabled_connector_accounts_by_profile_id( &self, _state: &KeyManagerState, _profile_id: &common_utils::id_type::ProfileId, _key_store: &MerchantKeyStore, _connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account| { account.merchant_id == *merchant_id && account.connector_name == connector_name }) .cloned() .collect::<Vec<_>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let maybe_mca = self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.profile_id.eq(&Some(profile_id.to_owned())) && account.connector_name == connector_name }) .cloned(); match maybe_mca { Some(mca) => mca .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError), None => Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()), } } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| account.get_id() == *id) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), test_mode: t.test_mode, disabled: t.disabled, merchant_connector_id: t.merchant_connector_id.clone(), id: Some(t.merchant_connector_id), payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_configs: None, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, business_country: t.business_country, business_label: t.business_label, business_sub_label: t.business_sub_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: Some(t.profile_id), applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { id: t.id, merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), disabled: t.disabled, payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: t.profile_id, applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, feature_metadata: t.feature_metadata.map(From::from), }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { if get_disabled { account.merchant_id == *merchant_id } else { account.merchant_id == *merchant_id && account.disabled == Some(false) } }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(domain::MerchantConnectorAccounts::new(output)) } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { account.profile_id == *profile_id }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.merchant_connector_id == this.merchant_connector_id) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.get_id() == this.get_id()) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| account.get_id() == *id) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } }
crates/storage_impl/src/merchant_connector_account.rs
storage_impl::src::merchant_connector_account
10,501
true
// File: crates/storage_impl/src/config.rs // Module: storage_impl::src::config use common_utils::DbConnectionParams; use hyperswitch_domain_models::master_key::MasterKeyInterface; use masking::{PeekInterface, Secret}; use crate::{kv_router_store, DatabaseStore, MockDb, RouterStore}; #[derive(Debug, Clone, serde::Deserialize)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl DbConnectionParams for Database { fn get_username(&self) -> &str { &self.username } fn get_password(&self) -> Secret<String> { self.password.clone() } fn get_host(&self) -> &str { &self.host } fn get_port(&self) -> u16 { self.port } fn get_dbname(&self) -> &str { &self.dbname } } #[derive(Debug, serde::Deserialize, Clone, Copy, Default)] #[serde(rename_all = "PascalCase")] pub enum QueueStrategy { #[default] Fifo, Lifo, } impl From<QueueStrategy> for bb8::QueueStrategy { fn from(value: QueueStrategy) -> Self { match value { QueueStrategy::Fifo => Self::Fifo, QueueStrategy::Lifo => Self::Lifo, } } } impl Default for Database { fn default() -> Self { Self { username: String::new(), password: Secret::<String>::default(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, queue_strategy: QueueStrategy::default(), min_idle: None, max_lifetime: None, } } } impl<T: DatabaseStore> MasterKeyInterface for kv_router_store::KVRouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } impl<T: DatabaseStore> MasterKeyInterface for RouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } /// Default dummy key for MockDb impl MasterKeyInterface for MockDb { fn get_master_key(&self) -> &[u8] { self.master_key() } }
crates/storage_impl/src/config.rs
storage_impl::src::config
577
true
// File: crates/storage_impl/src/configs.rs // Module: storage_impl::src::configs use diesel_models::configs as storage; use error_stack::report; use hyperswitch_domain_models::configs::ConfigInterface; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store, redis::{ cache, cache::{CacheKind, CONFIG_CACHE}, }, store::ConfigUpdateInternal, CustomResult, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { self.router_store.insert_config(config).await } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_in_database(key, config_update) .await } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_by_key(key, config_update) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key_from_db(key).await } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key(key).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { self.router_store .find_config_by_key_unwrap_or(key, default_config) .await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.delete_config_by_key(key).await } } #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let inserted = config .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&inserted.key).into())]) .await?; Ok(inserted) } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::update_by_key(&conn, key, config_update) .await .map_err(|error| report!(StorageError::from(error))) } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { cache::publish_and_redact(self, CacheKind::Config(key.into()), || { self.update_config_in_database(key, config_update) }) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let find_config_by_key_from_db = || async { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) }; cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { let find_else_unwrap_or = || async { let conn = connection::pg_connection_write(self).await?; match storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) { Ok(a) => Ok(a), Err(err) => { if err.current_context().is_db_not_found() { default_config .map(|c| { storage::ConfigNew { key: key.to_string(), config: c, } .into() }) .ok_or(err) } else { Err(err) } } } }; cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&deleted.key).into())]) .await?; Ok(deleted) } } #[async_trait::async_trait] impl ConfigInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let config_new = storage::Config { key: config.key, config: config.config, }; configs.push(config_new.clone()); Ok(config_new) } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { self.update_config_by_key(key, config_update).await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { let result = self .configs .lock() .await .iter_mut() .find(|c| c.key == key) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to update".to_string()).into() }) .map(|c| { let config_updated = ConfigUpdateInternal::from(config_update).create_config(c.clone()); *c = config_updated.clone(); config_updated }); result } async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) .map(|index| configs.remove(index)) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to delete".to_string()).into() }); result } async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let configs = self.configs.lock().await; let config = configs.iter().find(|c| c.key == key).cloned(); config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into()) } async fn find_config_by_key_unwrap_or( &self, key: &str, _default_config: Option<String>, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } }
crates/storage_impl/src/configs.rs
storage_impl::src::configs
2,129
true
// File: crates/storage_impl/src/payments.rs // Module: storage_impl::src::payments pub mod payment_attempt; pub mod payment_intent; use diesel_models::{payment_attempt::PaymentAttempt, PaymentIntent}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentIntent {} impl KvStorePartition for PaymentAttempt {}
crates/storage_impl/src/payments.rs
storage_impl::src::payments
73
true
// File: crates/storage_impl/src/lib.rs // Module: storage_impl::src::lib use std::{fmt::Debug, sync::Arc}; use common_utils::types::TenantConfig; use diesel_models as store; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use masking::StrongSecret; use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore}; mod address; pub mod business_profile; pub mod callback_mapper; pub mod cards_info; pub mod config; pub mod configs; pub mod connection; pub mod customers; pub mod database; pub mod errors; pub mod invoice; pub mod kv_router_store; pub mod lookup; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod metrics; pub mod mock_db; pub mod payment_method; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod redis; pub mod refund; mod reverse_lookup; pub mod subscription; pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; pub use mock_db::MockDb; use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply}; #[cfg(not(feature = "payouts"))] pub use crate::database::store::Store; pub use crate::{database::store::DatabaseStore, errors::StorageError}; #[derive(Debug, Clone)] pub struct RouterStore<T: DatabaseStore> { db_store: T, cache_store: Arc<RedisStore>, master_encryption_key: StrongSecret<Vec<u8>>, pub request_id: Option<String>, } #[async_trait::async_trait] impl<T: DatabaseStore> DatabaseStore for RouterStore<T> where T::Config: Send, { type Config = ( T::Config, redis_interface::RedisSettings, StrongSecret<Vec<u8>>, tokio::sync::oneshot::Sender<()>, &'static str, ); async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> error_stack::Result<Self, StorageError> { let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) = config; if test_transaction { Self::test_store(db_conf, tenant_config, &cache_conf, encryption_key) .await .attach_printable("failed to create test router store") } else { Self::from_config( db_conf, tenant_config, encryption_key, Self::cache_store(&cache_conf, cache_error_signal).await?, inmemory_cache_stream, ) .await .attach_printable("failed to create store") } } fn get_master_pool(&self) -> &PgPool { self.db_store.get_master_pool() } fn get_replica_pool(&self) -> &PgPool { self.db_store.get_replica_pool() } fn get_accounts_master_pool(&self) -> &PgPool { self.db_store.get_accounts_master_pool() } fn get_accounts_replica_pool(&self) -> &PgPool { self.db_store.get_accounts_replica_pool() } } impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> { fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> { self.cache_store.get_redis_conn() } } impl<T: DatabaseStore> RouterStore<T> { pub async fn from_config( db_conf: T::Config, tenant_config: &dyn TenantConfig, encryption_key: StrongSecret<Vec<u8>>, cache_store: Arc<RedisStore>, inmemory_cache_stream: &str, ) -> error_stack::Result<Self, StorageError> { let db_store = T::new(db_conf, tenant_config, false).await?; let redis_conn = cache_store.redis_conn.clone(); let cache_store = Arc::new(RedisStore { redis_conn: Arc::new(RedisConnectionPool::clone( &redis_conn, tenant_config.get_redis_key_prefix(), )), }); cache_store .redis_conn .subscribe(inmemory_cache_stream) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to subscribe to inmemory cache stream")?; Ok(Self { db_store, cache_store, master_encryption_key: encryption_key, request_id: None, }) } pub async fn cache_store( cache_conf: &redis_interface::RedisSettings, cache_error_signal: tokio::sync::oneshot::Sender<()>, ) -> error_stack::Result<Arc<RedisStore>, StorageError> { let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to create cache store")?; cache_store.set_error_callback(cache_error_signal); Ok(Arc::new(cache_store)) } pub fn master_key(&self) -> &StrongSecret<Vec<u8>> { &self.master_encryption_key } pub async fn call_database<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<D, StorageError> where D: Debug + Sync + Conversion, R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>> + Send, M: ReverseConversion<D>, { execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } pub async fn find_optional_resource<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query_fut: R, ) -> error_stack::Result<Option<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { match execute_query_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? { Some(resource) => Ok(Some( resource .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } pub async fn find_resources<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<Vec<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { let resource_futures = execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .into_iter() .map(|resource| async { resource .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let resources = futures::future::try_join_all(resource_futures).await?; Ok(resources) } /// # Panics /// /// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set pub async fn test_store( db_conf: T::Config, tenant_config: &dyn TenantConfig, cache_conf: &redis_interface::RedisSettings, encryption_key: StrongSecret<Vec<u8>>, ) -> error_stack::Result<Self, StorageError> { // TODO: create an error enum and return proper error here let db_store = T::new(db_conf, tenant_config, true).await?; let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("failed to create redis cache")?; Ok(Self { db_store, cache_store: Arc::new(cache_store), master_encryption_key: encryption_key, request_id: None, }) } } // TODO: This should not be used beyond this crate // Remove the pub modified once StorageScheme usage is completed pub trait DataModelExt { type StorageModel; fn to_storage_model(self) -> Self::StorageModel; fn from_storage_model(storage_model: Self::StorageModel) -> Self; } pub(crate) fn diesel_error_to_data_error( diesel_error: diesel_models::errors::DatabaseError, ) -> StorageError { match diesel_error { diesel_models::errors::DatabaseError::DatabaseConnectionError => { StorageError::DatabaseConnectionError } diesel_models::errors::DatabaseError::NotFound => { StorageError::ValueNotFound("Value not found".to_string()) } diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, _ => StorageError::DatabaseError(error_stack::report!(diesel_error)), } } #[async_trait::async_trait] pub trait UniqueConstraints { fn unique_constraints(&self) -> Vec<String>; fn table_name(&self) -> &str; async fn check_for_constraints( &self, redis_conn: &Arc<RedisConnectionPool>, ) -> CustomResult<(), RedisError> { let constraints = self.unique_constraints(); let sadd_result = redis_conn .sadd( &format!("unique_constraint:{}", self.table_name()).into(), constraints, ) .await?; match sadd_result { SaddReply::KeyNotSet => Err(error_stack::report!(RedisError::SetAddMembersFailed)), SaddReply::KeySet => Ok(()), } } } impl UniqueConstraints for diesel_models::Address { fn unique_constraints(&self) -> Vec<String> { vec![format!("address_{}", self.address_id)] } fn table_name(&self) -> &str { "Address" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentIntent { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentIntent { #[cfg(feature = "v1")] fn unique_constraints(&self) -> Vec<String> { vec![format!( "pi_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr() )] } #[cfg(feature = "v2")] fn unique_constraints(&self) -> Vec<String> { vec![format!("pi_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "pa_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id )] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!("pa_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![format!( "refund_{}_{}", self.merchant_id.get_string_repr(), self.refund_id )] } fn table_name(&self) -> &str { "Refund" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "Refund" } } impl UniqueConstraints for diesel_models::ReverseLookup { fn unique_constraints(&self) -> Vec<String> { vec![format!("reverselookup_{}", self.lookup_id)] } fn table_name(&self) -> &str { "ReverseLookup" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::Payouts { fn unique_constraints(&self) -> Vec<String> { vec![format!( "po_{}_{}", self.merchant_id.get_string_repr(), self.payout_id.get_string_repr() )] } fn table_name(&self) -> &str { "Payouts" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::PayoutAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "poa_{}_{}", self.merchant_id.get_string_repr(), self.payout_attempt_id )] } fn table_name(&self) -> &str { "PayoutAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![format!("paymentmethod_{}", self.payment_method_id)] } fn table_name(&self) -> &str { "PaymentMethod" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentMethod" } } impl UniqueConstraints for diesel_models::Mandate { fn unique_constraints(&self) -> Vec<String> { vec![format!( "mand_{}_{}", self.merchant_id.get_string_repr(), self.mandate_id )] } fn table_name(&self) -> &str { "Mandate" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!( "customer_{}_{}", self.customer_id.get_string_repr(), self.merchant_id.get_string_repr(), )] } fn table_name(&self) -> &str { "Customer" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!("customer_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "Customer" } } #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {} #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl UniqueConstraints for diesel_models::tokenization::Tokenization { fn unique_constraints(&self) -> Vec<String> { vec![format!("id_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "tokenization" } }
crates/storage_impl/src/lib.rs
storage_impl::src::lib
3,594
true
// File: crates/storage_impl/src/subscription.rs // Module: storage_impl::src::subscription use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; pub use diesel_models::subscription::Subscription; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, subscription::{ Subscription as DomainSubscription, SubscriptionInterface, SubscriptionUpdate as DomainSubscriptionUpdate, }, }; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = subscription_new .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database(state, key_store, sub_new.insert(&conn)) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { let conn = connection::pg_connection_write(self).await?; self.call_database( state, key_store, Subscription::find_by_merchant_id_subscription_id(&conn, merchant_id, subscription_id), ) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = data .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database( state, key_store, Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, sub_new), ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .insert_subscription_entry(state, key_store, subscription_new) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .update_subscription_entry(state, key_store, merchant_id, subscription_id, data) .await } } #[async_trait::async_trait] impl SubscriptionInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn find_by_merchant_id_subscription_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn update_subscription_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, _data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/subscription.rs
storage_impl::src::subscription
1,129
true
// File: crates/storage_impl/src/address.rs // Module: storage_impl::src::address use diesel_models::address::Address; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Address {}
crates/storage_impl/src/address.rs
storage_impl::src::address
48
true
// File: crates/storage_impl/src/metrics.rs // Module: storage_impl::src::metrics use router_env::{counter_metric, gauge_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // Metrics for KV counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER); counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER); counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER); // Metrics for In-memory cache gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
crates/storage_impl/src/metrics.rs
storage_impl::src::metrics
196
true
// File: crates/storage_impl/src/refund.rs // Module: storage_impl::src::refund use diesel_models::refund::Refund; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Refund {}
crates/storage_impl/src/refund.rs
storage_impl::src::refund
51
true
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
27