Dataset Viewer
Auto-converted to Parquet
id
stringlengths
24
57
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
8.08k
87.1k
metadata
dict
large_file_-3612199710970036087
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/mock_db.rs </path> <file> 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 {} </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/mock_db.rs", "files": null, "module": null, "num_files": null, "token_count": 2201 }
large_file_-2158814459434422572
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/merchant_account.rs </path> <file> #[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(()) } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/merchant_account.rs", "files": null, "module": null, "num_files": null, "token_count": 6114 }
large_file_-4619901670390511572
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/payment_method.rs </path> <file> 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 } } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/payment_method.rs", "files": null, "module": null, "num_files": null, "token_count": 7297 }
large_file_6999153258997339718
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/merchant_connector_account.rs </path> <file> 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()) } } } } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/merchant_connector_account.rs", "files": null, "module": null, "num_files": null, "token_count": 10476 }
large_file_4023498033037075140
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/configs.rs </path> <file> 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 } } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/configs.rs", "files": null, "module": null, "num_files": null, "token_count": 2108 }
large_file_-8658755190753490785
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/lib.rs </path> <file> 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" } } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/lib.rs", "files": null, "module": null, "num_files": null, "token_count": 3574 }
large_file_-8974719706452346473
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/business_profile.rs </path> <file> use common_utils::ext_traits::AsyncExt; use diesel_models::business_profile::{self, ProfileUpdateInternal}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, business_profile as domain, business_profile::ProfileInterface, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; 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> ProfileInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .insert_business_profile(key_manager_state, merchant_key_store, business_profile) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_key_store, merchant_id, profile_id, ) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_key_store, profile_name, merchant_id, ) .await } #[instrument(skip_all)] async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { self.router_store .update_profile_by_profile_id( key_manager_state, merchant_key_store, current_state, profile_update, ) .await } #[instrument(skip_all)] async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_profile_by_profile_id_merchant_id(profile_id, merchant_id) .await } #[instrument(skip_all)] async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { self.router_store .list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> ProfileInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_write(self).await?; business_profile .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))? .convert( key_manager_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_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( key_manager_state, merchant_key_store, business_profile::Profile::find_by_profile_id(&conn, profile_id), ) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( key_manager_state, merchant_key_store, business_profile::Profile::find_by_merchant_id_profile_id( &conn, merchant_id, profile_id, ), ) .await } #[instrument(skip_all)] async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.call_database( key_manager_state, merchant_key_store, business_profile::Profile::find_by_profile_name_merchant_id( &conn, profile_name, merchant_id, ), ) .await } #[instrument(skip_all)] async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(StorageError::EncryptionError)? .update_by_profile_id(&conn, ProfileUpdateInternal::from(profile_update)) .await .map_err(|error| report!(StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_accounts_connection_write(self).await?; business_profile::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { let conn = pg_accounts_connection_read(self).await?; self.find_resources( key_manager_state, merchant_key_store, business_profile::Profile::list_profile_by_merchant_id(&conn, merchant_id), ) .await } } #[async_trait::async_trait] impl ProfileInterface for MockDb { type Error = StorageError; async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, StorageError> { let stored_business_profile = Conversion::convert(business_profile) .await .change_context(StorageError::EncryptionError)?; self.business_profiles .lock() .await .push(stored_business_profile.clone()); stored_business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| business_profile.get_id() == profile_id) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_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!( "No business profile found for profile_id = {profile_id:?}" )) .into(), ) } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.merchant_id == *merchant_id && business_profile.get_id() == profile_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_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!( "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}" )) .into(), ) } async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, StorageError> { let profile_id = current_state.get_id().to_owned(); self.business_profiles .lock() .await .iter_mut() .find(|business_profile| business_profile.get_id() == current_state.get_id()) .async_map(|business_profile| async { let profile_updated = ProfileUpdateInternal::from(profile_update).apply_changeset( Conversion::convert(current_state) .await .change_context(StorageError::EncryptionError)?, ); *business_profile = profile_updated.clone(); profile_updated .convert( key_manager_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!( "No business profile found for profile_id = {profile_id:?}", )) .into(), ) } async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut business_profiles = self.business_profiles.lock().await; let index = business_profiles .iter() .position(|business_profile| { business_profile.get_id() == profile_id && business_profile.merchant_id == *merchant_id }) .ok_or::<StorageError>(StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}" )))?; business_profiles.remove(index); Ok(true) } async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, StorageError> { let business_profiles = self .business_profiles .lock() .await .iter() .filter(|business_profile| business_profile.merchant_id == *merchant_id) .cloned() .collect::<Vec<_>>(); let mut domain_business_profiles = Vec::with_capacity(business_profiles.len()); for business_profile in business_profiles { let domain_profile = business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; domain_business_profiles.push(domain_profile); } Ok(domain_business_profiles) } async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.profile_name == profile_name && business_profile.merchant_id == *merchant_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_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!( "No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}" )) .into(), ) } } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/business_profile.rs", "files": null, "module": null, "num_files": null, "token_count": 3433 }
large_file_4469905062043723593
clm
file
<path> Repository: hyperswitch Crate: storage_impl File: crates/storage_impl/src/errors.rs </path> <file> pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult}; pub use redis_interface::errors::RedisError; use crate::store::errors::DatabaseError; pub type StorageResult<T> = error_stack::Result<T, StorageError>; #[derive(Debug, thiserror::Error)] pub enum StorageError { #[error("Initialization Error")] InitializationError, #[error("DatabaseError: {0:?}")] DatabaseError(error_stack::Report<DatabaseError>), #[error("ValueNotFound: {0}")] ValueNotFound(String), #[error("DuplicateValue: {entity} already exists {key:?}")] DuplicateValue { entity: &'static str, key: Option<String>, }, #[error("Timed out while trying to connect to the database")] DatabaseConnectionError, #[error("KV error")] KVError, #[error("Serialization failure")] SerializationFailed, #[error("MockDb error")] MockDbError, #[error("Kafka error")] KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] DeserializationFailed, #[error("Error while encrypting data")] EncryptionError, #[error("Error while decrypting data from database")] DecryptionError, #[error("RedisError: {0:?}")] RedisError(error_stack::Report<RedisError>), } impl From<error_stack::Report<RedisError>> for StorageError { fn from(err: error_stack::Report<RedisError>) -> Self { match err.current_context() { RedisError::NotFound => Self::ValueNotFound("redis value not found".to_string()), RedisError::JsonSerializationFailed => Self::SerializationFailed, RedisError::JsonDeserializationFailed => Self::DeserializationFailed, _ => Self::RedisError(err), } } } impl From<diesel::result::Error> for StorageError { fn from(err: diesel::result::Error) -> Self { Self::from(error_stack::report!(DatabaseError::from(err))) } } impl From<error_stack::Report<DatabaseError>> for StorageError { fn from(err: error_stack::Report<DatabaseError>) -> Self { match err.current_context() { DatabaseError::DatabaseConnectionError => Self::DatabaseConnectionError, DatabaseError::NotFound => Self::ValueNotFound(String::from("db value not found")), DatabaseError::UniqueViolation => Self::DuplicateValue { entity: "db entity", key: None, }, _ => Self::DatabaseError(err), } } } impl StorageError { pub fn is_db_not_found(&self) -> bool { match self { Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound), Self::ValueNotFound(_) => true, Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound), _ => false, } } pub fn is_db_unique_violation(&self) -> bool { match self { Self::DatabaseError(err) => { matches!(err.current_context(), DatabaseError::UniqueViolation,) } Self::DuplicateValue { .. } => true, _ => false, } } } pub trait RedisErrorExt { #[track_caller] fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError>; } impl RedisErrorExt for error_stack::Report<RedisError> { fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> { match self.current_context() { RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!( "Data does not exist for key {key}", ))), RedisError::SetNxFailed | RedisError::SetAddMembersFailed => { self.change_context(StorageError::DuplicateValue { entity: "redis", key: Some(key.to_string()), }) } _ => self.change_context(StorageError::KVError), } } } #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Error while obtaining URL for the integration")] FailedToObtainIntegrationUrl, #[error("Failed to encode connector request")] RequestEncodingFailed, #[error("Request encoding failed : {0}")] RequestEncodingFailedWithReason(String), #[error("Parsing failed")] ParsingFailed, #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, #[error("Failed to execute a processing step: {0:?}")] ProcessingStepFailed(Option<bytes::Bytes>), #[error("The connector returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to parse custom routing rules from merchant account")] RoutingRulesParsingError, #[error("Failed to obtain preferred connector from merchant account")] FailedToObtainPreferredConnector, #[error("An invalid connector name was provided")] InvalidConnectorName, #[error("An invalid Wallet was used")] InvalidWallet, #[error("Failed to handle connector response")] ResponseHandlingFailed, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("Missing required fields: {field_names:?}")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Failed to obtain certificate")] FailedToObtainCertificate, #[error("Connector meta data not found")] NoConnectorMetaData, #[error("Failed to obtain certificate key")] FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] NotImplemented(String), #[error("{message} is not supported by {connector}")] NotSupported { message: String, connector: &'static str, payment_experience: String, }, #[error("{flow} flow not supported by {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}'")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, #[error("Capture method not supported")] CaptureMethodNotSupported, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] MissingConnectorRefundID, #[error("Webhooks not implemented for this connector")] WebhooksNotImplemented, #[error("Failed to decode webhook event body")] WebhookBodyDecodingFailed, #[error("Signature not found for incoming webhook")] WebhookSignatureNotFound, #[error("Failed to verify webhook source")] WebhookSourceVerificationFailed, #[error("Could not find merchant secret in DB for incoming webhook source verification")] WebhookVerificationSecretNotFound, #[error("Incoming webhook object reference ID not found")] WebhookReferenceIdNotFound, #[error("Incoming webhook event type not found")] WebhookEventTypeNotFound, #[error("Incoming webhook event resource object not found")] WebhookResourceObjectNotFound, #[error("Could not respond to the incoming webhook event")] WebhookResponseEncodingFailed, #[error("Invalid Date/time format")] InvalidDateFormat, #[error("Date Formatting Failed")] DateFormattingFailed, #[error("Invalid Data format")] InvalidDataFormat { field_name: &'static str }, #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] MismatchedPaymentData, #[error("Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error("Failed to parse Wallet token")] InvalidWalletToken { wallet_name: String }, #[error("Missing Connector Related Transaction ID")] MissingConnectorRelatedTransactionID { id: String }, #[error("File Validation failed")] FileValidationFailed { reason: String }, #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, } #[derive(Debug, thiserror::Error)] pub enum HealthCheckDBError { #[error("Error while connecting to database")] DBError, #[error("Error while writing to database")] DBWriteError, #[error("Error while reading element in the database")] DBReadError, #[error("Error while deleting element in the database")] DBDeleteError, #[error("Unpredictable error occurred")] UnknownError, #[error("Error in database transaction")] TransactionError, #[error("Error while executing query in Sqlx Analytics")] SqlxAnalyticsError, #[error("Error while executing query in Clickhouse Analytics")] ClickhouseAnalyticsError, #[error("Error while executing query in Opensearch")] OpensearchError, } impl From<diesel::result::Error> for HealthCheckDBError { fn from(error: diesel::result::Error) -> Self { match error { diesel::result::Error::DatabaseError(_, _) => Self::DBError, diesel::result::Error::RollbackErrorOnCommit { .. } | diesel::result::Error::RollbackTransaction | diesel::result::Error::AlreadyInTransaction | diesel::result::Error::NotInTransaction | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, _ => Self::UnknownError, } } } #[derive(Debug, thiserror::Error)] pub enum HealthCheckRedisError { #[error("Failed to establish Redis connection")] RedisConnectionError, #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to get key value in Redis")] GetFailed, #[error("Failed to delete key value in Redis")] DeleteFailed, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckLockerError { #[error("Failed to establish Locker connection")] FailedToCallLocker, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckGRPCServiceError { #[error("Failed to establish connection with gRPC service")] FailedToCallService, } #[derive(thiserror::Error, Debug, Clone)] pub enum RecoveryError { #[error("Failed to make a recovery payment")] PaymentCallFailed, #[error("Encountered a Process Tracker Task Failure")] ProcessTrackerFailure, #[error("The encountered task is invalid")] InvalidTask, #[error("The Process Tracker data was not found")] ValueNotFound, #[error("Failed to update billing connector")] RecordBackToBillingConnectorFailed, #[error("Failed to fetch billing connector account id")] BillingMerchantConnectorAccountIdNotFound, #[error("Failed to generate payment sync data")] PaymentsResponseGenerationFailed, #[error("Outgoing Webhook Failed")] RevenueRecoveryOutgoingWebhookFailed, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckDecisionEngineError { #[error("Failed to establish Decision Engine connection")] FailedToCallDecisionEngineService, } #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckUnifiedConnectorServiceError { #[error("Failed to establish Unified Connector Service connection")] FailedToCallUnifiedConnectorService, } </file>
{ "crate": "storage_impl", "file": "crates/storage_impl/src/errors.rs", "files": null, "module": null, "num_files": null, "token_count": 2457 }
large_file_1484038564034034151
clm
file
"<path>\nRepository: hyperswitch\nCrate: storage_impl\nFile: crates/storage_impl/src/customers.rs\n<(...TRUNCATED)
{"crate":"storage_impl","file":"crates/storage_impl/src/customers.rs","files":null,"module":null,"nu(...TRUNCATED)
large_file_-1614440293481408760
clm
file
"<path>\nRepository: hyperswitch\nCrate: storage_impl\nFile: crates/storage_impl/src/kv_router_store(...TRUNCATED)
{"crate":"storage_impl","file":"crates/storage_impl/src/kv_router_store.rs","files":null,"module":nu(...TRUNCATED)
End of preview. Expand in Data Studio
YAML Metadata Warning: empty or missing yaml metadata in repo card (https://huggingface.co/docs/hub/datasets-cards)

Hyperswitch Token-Aware CPT Dataset

This dataset contains 1,076 samples of Rust code from the Hyperswitch payment router project, optimized for Continued Pre-Training (CPT) with the Kwaipilot/KAT-Dev tokenizer.

Dataset Statistics

  • Total Samples: 1,076
  • Total Tokens: 5,687,255
  • Mean Tokens per Sample: 5,285
  • Token Range: 2,001 - 15,609

Token Distribution

  • < 4k tokens: 38.1% of samples
  • 4k-10k tokens: 52.0% of samples
  • 10k+ tokens: 9.9% of samples

Granularity Types

  • file: 721 samples (single large files)
  • module: 180 samples (multiple files from same module)
  • combined_files: 160 samples (small files combined by crate)
  • crate: 15 samples (entire small crates)

Top Crates

  1. router - 371 samples
  2. hyperswitch_connectors - 336 samples
  3. analytics - 54 samples
  4. diesel_models - 39 samples
  5. api_models - 28 samples

Sample Structure

Each sample contains:

  • id: Unique identifier
  • type: Sample type (always "clm" for causal language modeling)
  • granularity: Level of code organization (file/module/combined_files/crate)
  • content: Full code with path metadata in format:
    <path>
    Repository: hyperswitch
    Crate: [crate_name]
    File: [file_path]
    Tokens: [token_count]
    </path>
    
    <file>
    [actual code content]
    </file>
    
  • metadata: Contains crate, file info, and token count

Usage

from datasets import load_dataset

# Load the dataset
dataset = load_dataset("archit11/hyperswitch-token-aware-cpt")

# Access samples
sample = dataset['train'][0]
print(f"Tokens: {sample['metadata']['token_count']:,}")
print(f"Crate: {sample['metadata']['crate']}")
print(f"Granularity: {sample['granularity']}")

# Filter by token count
medium_samples = dataset['train'].filter(
    lambda x: 4000 <= x['metadata']['token_count'] < 10000
)

# Filter by crate
router_samples = dataset['train'].filter(
    lambda x: x['metadata']['crate'] == 'router'
)

Training Recommendations

  • Context Length: 16k tokens (max sample is 15,609 tokens)
  • Tokenizer: Kwaipilot/KAT-Dev
  • Suggested Batch Size: 1-2 samples per batch (due to large context)
  • Format: Samples are pre-formatted with <path> and <file> tags

Source

Generation Method

Samples were generated using token-aware strategies:

  1. Large files (2k-16k tokens) included as-is
  2. Small files combined within same crate until reaching 2k+ tokens
  3. Module clusters grouped by directory structure
  4. Complete crates for small crates that fit within context

All token counts measured using the Kwaipilot/KAT-Dev tokenizer.

Downloads last month
22